Commit e51a3288 authored by yangjianbo's avatar yangjianbo
Browse files

merge: 合并 test 分支到 test-dev,解决冲突

解决的冲突文件:
- wire_gen.go: 合并 ConcurrencyService/CRSSyncService 参数和 userAttributeHandler
- gateway_handler.go: 合并 pkg/errors 和 antigravity 导入
- gateway_service.go: 合并 validateUpstreamBaseURL 和 GetAvailableModels
- config.example.yaml: 合并 billing/turnstile 配置和额外 gateway 选项

🤖 Generated with [Claude Code](https://claude.com/claude-code

)
Co-Authored-By: default avatarClaude Opus 4.5 <noreply@anthropic.com>
parents 25e16326 8a50ca59
...@@ -77,6 +77,7 @@ temp/ ...@@ -77,6 +77,7 @@ temp/
*.temp *.temp
*.log *.log
*.bak *.bak
.cache/
# =================== # ===================
# 构建产物 # 构建产物
......
...@@ -306,6 +306,16 @@ go generate ./cmd/server ...@@ -306,6 +306,16 @@ go generate ./cmd/server
--- ---
## Simple Mode
Simple Mode is designed for individual developers or internal teams who want quick access without full SaaS features.
- Enable: Set environment variable `RUN_MODE=simple`
- Difference: Hides SaaS-related features and skips billing process
- Security note: In production, you must also set `SIMPLE_MODE_CONFIRM=true` to allow startup
---
## Antigravity Support ## Antigravity Support
Sub2API supports [Antigravity](https://antigravity.so/) accounts. After authorization, dedicated endpoints are available for Claude and Gemini models. Sub2API supports [Antigravity](https://antigravity.so/) accounts. After authorization, dedicated endpoints are available for Claude and Gemini models.
...@@ -330,6 +340,12 @@ Antigravity accounts support optional **hybrid scheduling**. When enabled, the g ...@@ -330,6 +340,12 @@ Antigravity accounts support optional **hybrid scheduling**. When enabled, the g
> **⚠️ Warning**: Anthropic Claude and Antigravity Claude **cannot be mixed within the same conversation context**. Use groups to isolate them properly. > **⚠️ Warning**: Anthropic Claude and Antigravity Claude **cannot be mixed within the same conversation context**. Use groups to isolate them properly.
### Known Issues
In Claude Code, Plan Mode cannot exit automatically. (Normally when using the native Claude API, after planning is complete, Claude Code will pop up options for users to approve or reject the plan.)
**Workaround**: Press `Shift + Tab` to manually exit Plan Mode, then type your response to approve or reject the plan.
--- ---
## Project Structure ## Project Structure
......
...@@ -340,6 +340,10 @@ Antigravity 账户支持可选的**混合调度**功能。开启后,通用端 ...@@ -340,6 +340,10 @@ Antigravity 账户支持可选的**混合调度**功能。开启后,通用端
> **⚠️ 注意**:Anthropic Claude 和 Antigravity Claude **不能在同一上下文中混合使用**,请通过分组功能做好隔离。 > **⚠️ 注意**:Anthropic Claude 和 Antigravity Claude **不能在同一上下文中混合使用**,请通过分组功能做好隔离。
### 已知问题
在 Claude Code 中,无法自动退出Plan Mode。(正常使用原生Claude Api时,Plan 完成后,Claude Code会弹出弹出选项让用户同意或拒绝Plan。)
解决办法:shift + Tab,手动退出Plan mode,然后输入内容 告诉 Claude Code 同意或拒绝 Plan
--- ---
## 项目结构 ## 项目结构
......
...@@ -12,7 +12,6 @@ import ( ...@@ -12,7 +12,6 @@ import (
"github.com/Wei-Shaw/sub2api/ent" "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/repository" "github.com/Wei-Shaw/sub2api/internal/repository"
"github.com/Wei-Shaw/sub2api/internal/server" "github.com/Wei-Shaw/sub2api/internal/server"
"github.com/Wei-Shaw/sub2api/internal/server/middleware" "github.com/Wei-Shaw/sub2api/internal/server/middleware"
...@@ -31,7 +30,6 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { ...@@ -31,7 +30,6 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
wire.Build( wire.Build(
// Infrastructure layer ProviderSets // Infrastructure layer ProviderSets
config.ProviderSet, config.ProviderSet,
infrastructure.ProviderSet,
// Business layer ProviderSets // Business layer ProviderSets
repository.ProviderSet, repository.ProviderSet,
......
...@@ -12,7 +12,6 @@ import ( ...@@ -12,7 +12,6 @@ import (
"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"
"github.com/Wei-Shaw/sub2api/internal/infrastructure"
"github.com/Wei-Shaw/sub2api/internal/repository" "github.com/Wei-Shaw/sub2api/internal/repository"
"github.com/Wei-Shaw/sub2api/internal/server" "github.com/Wei-Shaw/sub2api/internal/server"
"github.com/Wei-Shaw/sub2api/internal/server/middleware" "github.com/Wei-Shaw/sub2api/internal/server/middleware"
...@@ -35,18 +34,18 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { ...@@ -35,18 +34,18 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
client, err := infrastructure.ProvideEnt(configConfig) client, err := repository.ProvideEnt(configConfig)
if err != nil { if err != nil {
return nil, err return nil, err
} }
db, err := infrastructure.ProvideSQLDB(client) db, err := repository.ProvideSQLDB(client)
if err != nil { if err != nil {
return nil, err return nil, err
} }
userRepository := repository.NewUserRepository(client, db) userRepository := repository.NewUserRepository(client, db)
settingRepository := repository.NewSettingRepository(client) settingRepository := repository.NewSettingRepository(client)
settingService := service.NewSettingService(settingRepository, configConfig) settingService := service.NewSettingService(settingRepository, configConfig)
redisClient := infrastructure.ProvideRedis(configConfig) redisClient := repository.ProvideRedis(configConfig)
emailCache := repository.NewEmailCache(redisClient) emailCache := repository.NewEmailCache(redisClient)
emailService := service.NewEmailService(settingRepository, emailCache) emailService := service.NewEmailService(settingRepository, emailCache)
turnstileVerifier := repository.NewTurnstileVerifier() turnstileVerifier := repository.NewTurnstileVerifier()
...@@ -88,9 +87,10 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { ...@@ -88,9 +87,10 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
geminiOAuthClient := repository.NewGeminiOAuthClient(configConfig) geminiOAuthClient := repository.NewGeminiOAuthClient(configConfig)
geminiCliCodeAssistClient := repository.NewGeminiCliCodeAssistClient() geminiCliCodeAssistClient := repository.NewGeminiCliCodeAssistClient()
geminiOAuthService := service.NewGeminiOAuthService(proxyRepository, geminiOAuthClient, geminiCliCodeAssistClient, configConfig) geminiOAuthService := service.NewGeminiOAuthService(proxyRepository, geminiOAuthClient, geminiCliCodeAssistClient, configConfig)
rateLimitService := service.NewRateLimitService(accountRepository, configConfig) geminiQuotaService := service.NewGeminiQuotaService(configConfig, settingRepository)
rateLimitService := service.NewRateLimitService(accountRepository, usageLogRepository, configConfig, geminiQuotaService)
claudeUsageFetcher := repository.NewClaudeUsageFetcher() claudeUsageFetcher := repository.NewClaudeUsageFetcher()
accountUsageService := service.NewAccountUsageService(accountRepository, usageLogRepository, claudeUsageFetcher) accountUsageService := service.NewAccountUsageService(accountRepository, usageLogRepository, claudeUsageFetcher, geminiQuotaService)
geminiTokenCache := repository.NewGeminiTokenCache(redisClient) geminiTokenCache := repository.NewGeminiTokenCache(redisClient)
geminiTokenProvider := service.NewGeminiTokenProvider(accountRepository, geminiTokenCache, geminiOAuthService) geminiTokenProvider := service.NewGeminiTokenProvider(accountRepository, geminiTokenCache, geminiOAuthService)
gatewayCache := repository.NewGatewayCache(redisClient) gatewayCache := repository.NewGatewayCache(redisClient)
...@@ -109,7 +109,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { ...@@ -109,7 +109,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
antigravityOAuthHandler := admin.NewAntigravityOAuthHandler(antigravityOAuthService) antigravityOAuthHandler := admin.NewAntigravityOAuthHandler(antigravityOAuthService)
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, turnstileService)
updateCache := repository.NewUpdateCache(redisClient) updateCache := repository.NewUpdateCache(redisClient)
gitHubReleaseClient := repository.NewGitHubReleaseClient() gitHubReleaseClient := repository.NewGitHubReleaseClient()
serviceBuildInfo := provideServiceBuildInfo(buildInfo) serviceBuildInfo := provideServiceBuildInfo(buildInfo)
...@@ -117,7 +117,11 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { ...@@ -117,7 +117,11 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
systemHandler := handler.ProvideSystemHandler(updateService) systemHandler := handler.ProvideSystemHandler(updateService)
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, antigravityOAuthHandler, proxyHandler, adminRedeemHandler, settingHandler, systemHandler, adminSubscriptionHandler, adminUsageHandler) userAttributeDefinitionRepository := repository.NewUserAttributeDefinitionRepository(client)
userAttributeValueRepository := repository.NewUserAttributeValueRepository(client)
userAttributeService := service.NewUserAttributeService(userAttributeDefinitionRepository, userAttributeValueRepository)
userAttributeHandler := admin.NewUserAttributeHandler(userAttributeService)
adminHandlers := handler.ProvideAdminHandlers(dashboardHandler, adminUserHandler, groupHandler, accountHandler, oAuthHandler, openAIOAuthHandler, geminiOAuthHandler, antigravityOAuthHandler, proxyHandler, adminRedeemHandler, settingHandler, systemHandler, adminSubscriptionHandler, adminUsageHandler, userAttributeHandler)
pricingRemoteClient := repository.NewPricingRemoteClient(configConfig) pricingRemoteClient := repository.NewPricingRemoteClient(configConfig)
pricingService, err := service.ProvidePricingService(configConfig, pricingRemoteClient) pricingService, err := service.ProvidePricingService(configConfig, pricingRemoteClient)
if err != nil { if err != nil {
...@@ -128,10 +132,10 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { ...@@ -128,10 +132,10 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
identityService := service.NewIdentityService(identityCache) identityService := service.NewIdentityService(identityCache)
timingWheelService := service.ProvideTimingWheelService() timingWheelService := service.ProvideTimingWheelService()
deferredService := service.ProvideDeferredService(accountRepository, timingWheelService) deferredService := service.ProvideDeferredService(accountRepository, timingWheelService)
gatewayService := service.NewGatewayService(accountRepository, groupRepository, usageLogRepository, userRepository, userSubscriptionRepository, gatewayCache, configConfig, billingService, rateLimitService, billingCacheService, identityService, httpUpstream, deferredService) gatewayService := service.NewGatewayService(accountRepository, groupRepository, usageLogRepository, userRepository, userSubscriptionRepository, gatewayCache, configConfig, concurrencyService, billingService, rateLimitService, billingCacheService, identityService, httpUpstream, deferredService)
geminiMessagesCompatService := service.NewGeminiMessagesCompatService(accountRepository, groupRepository, gatewayCache, geminiTokenProvider, rateLimitService, httpUpstream, antigravityGatewayService, configConfig) geminiMessagesCompatService := service.NewGeminiMessagesCompatService(accountRepository, groupRepository, gatewayCache, geminiTokenProvider, rateLimitService, httpUpstream, antigravityGatewayService, configConfig)
gatewayHandler := handler.NewGatewayHandler(gatewayService, geminiMessagesCompatService, antigravityGatewayService, userService, concurrencyService, billingCacheService) gatewayHandler := handler.NewGatewayHandler(gatewayService, geminiMessagesCompatService, antigravityGatewayService, userService, concurrencyService, billingCacheService)
openAIGatewayService := service.NewOpenAIGatewayService(accountRepository, usageLogRepository, userRepository, userSubscriptionRepository, gatewayCache, configConfig, billingService, rateLimitService, billingCacheService, httpUpstream, deferredService) openAIGatewayService := service.NewOpenAIGatewayService(accountRepository, usageLogRepository, userRepository, userSubscriptionRepository, gatewayCache, configConfig, concurrencyService, billingService, rateLimitService, billingCacheService, httpUpstream, deferredService)
openAIGatewayHandler := handler.NewOpenAIGatewayHandler(openAIGatewayService, concurrencyService, billingCacheService) openAIGatewayHandler := handler.NewOpenAIGatewayHandler(openAIGatewayService, concurrencyService, billingCacheService)
handlerSettingHandler := handler.ProvideSettingHandler(settingService, buildInfo) handlerSettingHandler := handler.ProvideSettingHandler(settingService, buildInfo)
handlers := handler.ProvideHandlers(authHandler, userHandler, apiKeyHandler, usageHandler, redeemHandler, subscriptionHandler, adminHandlers, gatewayHandler, openAIGatewayHandler, handlerSettingHandler) handlers := handler.ProvideHandlers(authHandler, userHandler, apiKeyHandler, usageHandler, redeemHandler, subscriptionHandler, adminHandlers, gatewayHandler, openAIGatewayHandler, handlerSettingHandler)
......
...@@ -25,6 +25,8 @@ import ( ...@@ -25,6 +25,8 @@ import (
"github.com/Wei-Shaw/sub2api/ent/usagelog" "github.com/Wei-Shaw/sub2api/ent/usagelog"
"github.com/Wei-Shaw/sub2api/ent/user" "github.com/Wei-Shaw/sub2api/ent/user"
"github.com/Wei-Shaw/sub2api/ent/userallowedgroup" "github.com/Wei-Shaw/sub2api/ent/userallowedgroup"
"github.com/Wei-Shaw/sub2api/ent/userattributedefinition"
"github.com/Wei-Shaw/sub2api/ent/userattributevalue"
"github.com/Wei-Shaw/sub2api/ent/usersubscription" "github.com/Wei-Shaw/sub2api/ent/usersubscription"
stdsql "database/sql" stdsql "database/sql"
...@@ -55,6 +57,10 @@ type Client struct { ...@@ -55,6 +57,10 @@ type Client struct {
User *UserClient User *UserClient
// UserAllowedGroup is the client for interacting with the UserAllowedGroup builders. // UserAllowedGroup is the client for interacting with the UserAllowedGroup builders.
UserAllowedGroup *UserAllowedGroupClient UserAllowedGroup *UserAllowedGroupClient
// UserAttributeDefinition is the client for interacting with the UserAttributeDefinition builders.
UserAttributeDefinition *UserAttributeDefinitionClient
// UserAttributeValue is the client for interacting with the UserAttributeValue builders.
UserAttributeValue *UserAttributeValueClient
// UserSubscription is the client for interacting with the UserSubscription builders. // UserSubscription is the client for interacting with the UserSubscription builders.
UserSubscription *UserSubscriptionClient UserSubscription *UserSubscriptionClient
} }
...@@ -78,6 +84,8 @@ func (c *Client) init() { ...@@ -78,6 +84,8 @@ func (c *Client) init() {
c.UsageLog = NewUsageLogClient(c.config) c.UsageLog = NewUsageLogClient(c.config)
c.User = NewUserClient(c.config) c.User = NewUserClient(c.config)
c.UserAllowedGroup = NewUserAllowedGroupClient(c.config) c.UserAllowedGroup = NewUserAllowedGroupClient(c.config)
c.UserAttributeDefinition = NewUserAttributeDefinitionClient(c.config)
c.UserAttributeValue = NewUserAttributeValueClient(c.config)
c.UserSubscription = NewUserSubscriptionClient(c.config) c.UserSubscription = NewUserSubscriptionClient(c.config)
} }
...@@ -181,6 +189,8 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { ...@@ -181,6 +189,8 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) {
UsageLog: NewUsageLogClient(cfg), UsageLog: NewUsageLogClient(cfg),
User: NewUserClient(cfg), User: NewUserClient(cfg),
UserAllowedGroup: NewUserAllowedGroupClient(cfg), UserAllowedGroup: NewUserAllowedGroupClient(cfg),
UserAttributeDefinition: NewUserAttributeDefinitionClient(cfg),
UserAttributeValue: NewUserAttributeValueClient(cfg),
UserSubscription: NewUserSubscriptionClient(cfg), UserSubscription: NewUserSubscriptionClient(cfg),
}, nil }, nil
} }
...@@ -211,6 +221,8 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) ...@@ -211,6 +221,8 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error)
UsageLog: NewUsageLogClient(cfg), UsageLog: NewUsageLogClient(cfg),
User: NewUserClient(cfg), User: NewUserClient(cfg),
UserAllowedGroup: NewUserAllowedGroupClient(cfg), UserAllowedGroup: NewUserAllowedGroupClient(cfg),
UserAttributeDefinition: NewUserAttributeDefinitionClient(cfg),
UserAttributeValue: NewUserAttributeValueClient(cfg),
UserSubscription: NewUserSubscriptionClient(cfg), UserSubscription: NewUserSubscriptionClient(cfg),
}, nil }, nil
} }
...@@ -242,7 +254,8 @@ func (c *Client) Close() error { ...@@ -242,7 +254,8 @@ func (c *Client) Close() error {
func (c *Client) Use(hooks ...Hook) { func (c *Client) Use(hooks ...Hook) {
for _, n := range []interface{ Use(...Hook) }{ for _, n := range []interface{ Use(...Hook) }{
c.Account, c.AccountGroup, c.ApiKey, c.Group, c.Proxy, c.RedeemCode, c.Setting, c.Account, c.AccountGroup, c.ApiKey, c.Group, c.Proxy, c.RedeemCode, c.Setting,
c.UsageLog, c.User, c.UserAllowedGroup, c.UserSubscription, c.UsageLog, c.User, c.UserAllowedGroup, c.UserAttributeDefinition,
c.UserAttributeValue, c.UserSubscription,
} { } {
n.Use(hooks...) n.Use(hooks...)
} }
...@@ -253,7 +266,8 @@ func (c *Client) Use(hooks ...Hook) { ...@@ -253,7 +266,8 @@ func (c *Client) Use(hooks ...Hook) {
func (c *Client) Intercept(interceptors ...Interceptor) { func (c *Client) Intercept(interceptors ...Interceptor) {
for _, n := range []interface{ Intercept(...Interceptor) }{ for _, n := range []interface{ Intercept(...Interceptor) }{
c.Account, c.AccountGroup, c.ApiKey, c.Group, c.Proxy, c.RedeemCode, c.Setting, c.Account, c.AccountGroup, c.ApiKey, c.Group, c.Proxy, c.RedeemCode, c.Setting,
c.UsageLog, c.User, c.UserAllowedGroup, c.UserSubscription, c.UsageLog, c.User, c.UserAllowedGroup, c.UserAttributeDefinition,
c.UserAttributeValue, c.UserSubscription,
} { } {
n.Intercept(interceptors...) n.Intercept(interceptors...)
} }
...@@ -282,6 +296,10 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { ...@@ -282,6 +296,10 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) {
return c.User.mutate(ctx, m) return c.User.mutate(ctx, m)
case *UserAllowedGroupMutation: case *UserAllowedGroupMutation:
return c.UserAllowedGroup.mutate(ctx, m) return c.UserAllowedGroup.mutate(ctx, m)
case *UserAttributeDefinitionMutation:
return c.UserAttributeDefinition.mutate(ctx, m)
case *UserAttributeValueMutation:
return c.UserAttributeValue.mutate(ctx, m)
case *UserSubscriptionMutation: case *UserSubscriptionMutation:
return c.UserSubscription.mutate(ctx, m) return c.UserSubscription.mutate(ctx, m)
default: default:
...@@ -1916,6 +1934,22 @@ func (c *UserClient) QueryUsageLogs(_m *User) *UsageLogQuery { ...@@ -1916,6 +1934,22 @@ func (c *UserClient) QueryUsageLogs(_m *User) *UsageLogQuery {
return query return query
} }
// QueryAttributeValues queries the attribute_values edge of a User.
func (c *UserClient) QueryAttributeValues(_m *User) *UserAttributeValueQuery {
query := (&UserAttributeValueClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(user.Table, user.FieldID, id),
sqlgraph.To(userattributevalue.Table, userattributevalue.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, user.AttributeValuesTable, user.AttributeValuesColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryUserAllowedGroups queries the user_allowed_groups edge of a User. // QueryUserAllowedGroups queries the user_allowed_groups edge of a User.
func (c *UserClient) QueryUserAllowedGroups(_m *User) *UserAllowedGroupQuery { func (c *UserClient) QueryUserAllowedGroups(_m *User) *UserAllowedGroupQuery {
query := (&UserAllowedGroupClient{config: c.config}).Query() query := (&UserAllowedGroupClient{config: c.config}).Query()
...@@ -2075,6 +2109,322 @@ func (c *UserAllowedGroupClient) mutate(ctx context.Context, m *UserAllowedGroup ...@@ -2075,6 +2109,322 @@ func (c *UserAllowedGroupClient) mutate(ctx context.Context, m *UserAllowedGroup
} }
} }
// UserAttributeDefinitionClient is a client for the UserAttributeDefinition schema.
type UserAttributeDefinitionClient struct {
config
}
// NewUserAttributeDefinitionClient returns a client for the UserAttributeDefinition from the given config.
func NewUserAttributeDefinitionClient(c config) *UserAttributeDefinitionClient {
return &UserAttributeDefinitionClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `userattributedefinition.Hooks(f(g(h())))`.
func (c *UserAttributeDefinitionClient) Use(hooks ...Hook) {
c.hooks.UserAttributeDefinition = append(c.hooks.UserAttributeDefinition, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `userattributedefinition.Intercept(f(g(h())))`.
func (c *UserAttributeDefinitionClient) Intercept(interceptors ...Interceptor) {
c.inters.UserAttributeDefinition = append(c.inters.UserAttributeDefinition, interceptors...)
}
// Create returns a builder for creating a UserAttributeDefinition entity.
func (c *UserAttributeDefinitionClient) Create() *UserAttributeDefinitionCreate {
mutation := newUserAttributeDefinitionMutation(c.config, OpCreate)
return &UserAttributeDefinitionCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of UserAttributeDefinition entities.
func (c *UserAttributeDefinitionClient) CreateBulk(builders ...*UserAttributeDefinitionCreate) *UserAttributeDefinitionCreateBulk {
return &UserAttributeDefinitionCreateBulk{config: c.config, builders: builders}
}
// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates
// a builder and applies setFunc on it.
func (c *UserAttributeDefinitionClient) MapCreateBulk(slice any, setFunc func(*UserAttributeDefinitionCreate, int)) *UserAttributeDefinitionCreateBulk {
rv := reflect.ValueOf(slice)
if rv.Kind() != reflect.Slice {
return &UserAttributeDefinitionCreateBulk{err: fmt.Errorf("calling to UserAttributeDefinitionClient.MapCreateBulk with wrong type %T, need slice", slice)}
}
builders := make([]*UserAttributeDefinitionCreate, rv.Len())
for i := 0; i < rv.Len(); i++ {
builders[i] = c.Create()
setFunc(builders[i], i)
}
return &UserAttributeDefinitionCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for UserAttributeDefinition.
func (c *UserAttributeDefinitionClient) Update() *UserAttributeDefinitionUpdate {
mutation := newUserAttributeDefinitionMutation(c.config, OpUpdate)
return &UserAttributeDefinitionUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *UserAttributeDefinitionClient) UpdateOne(_m *UserAttributeDefinition) *UserAttributeDefinitionUpdateOne {
mutation := newUserAttributeDefinitionMutation(c.config, OpUpdateOne, withUserAttributeDefinition(_m))
return &UserAttributeDefinitionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *UserAttributeDefinitionClient) UpdateOneID(id int64) *UserAttributeDefinitionUpdateOne {
mutation := newUserAttributeDefinitionMutation(c.config, OpUpdateOne, withUserAttributeDefinitionID(id))
return &UserAttributeDefinitionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for UserAttributeDefinition.
func (c *UserAttributeDefinitionClient) Delete() *UserAttributeDefinitionDelete {
mutation := newUserAttributeDefinitionMutation(c.config, OpDelete)
return &UserAttributeDefinitionDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *UserAttributeDefinitionClient) DeleteOne(_m *UserAttributeDefinition) *UserAttributeDefinitionDeleteOne {
return c.DeleteOneID(_m.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *UserAttributeDefinitionClient) DeleteOneID(id int64) *UserAttributeDefinitionDeleteOne {
builder := c.Delete().Where(userattributedefinition.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &UserAttributeDefinitionDeleteOne{builder}
}
// Query returns a query builder for UserAttributeDefinition.
func (c *UserAttributeDefinitionClient) Query() *UserAttributeDefinitionQuery {
return &UserAttributeDefinitionQuery{
config: c.config,
ctx: &QueryContext{Type: TypeUserAttributeDefinition},
inters: c.Interceptors(),
}
}
// Get returns a UserAttributeDefinition entity by its id.
func (c *UserAttributeDefinitionClient) Get(ctx context.Context, id int64) (*UserAttributeDefinition, error) {
return c.Query().Where(userattributedefinition.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *UserAttributeDefinitionClient) GetX(ctx context.Context, id int64) *UserAttributeDefinition {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// QueryValues queries the values edge of a UserAttributeDefinition.
func (c *UserAttributeDefinitionClient) QueryValues(_m *UserAttributeDefinition) *UserAttributeValueQuery {
query := (&UserAttributeValueClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(userattributedefinition.Table, userattributedefinition.FieldID, id),
sqlgraph.To(userattributevalue.Table, userattributevalue.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, userattributedefinition.ValuesTable, userattributedefinition.ValuesColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *UserAttributeDefinitionClient) Hooks() []Hook {
hooks := c.hooks.UserAttributeDefinition
return append(hooks[:len(hooks):len(hooks)], userattributedefinition.Hooks[:]...)
}
// Interceptors returns the client interceptors.
func (c *UserAttributeDefinitionClient) Interceptors() []Interceptor {
inters := c.inters.UserAttributeDefinition
return append(inters[:len(inters):len(inters)], userattributedefinition.Interceptors[:]...)
}
func (c *UserAttributeDefinitionClient) mutate(ctx context.Context, m *UserAttributeDefinitionMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&UserAttributeDefinitionCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&UserAttributeDefinitionUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&UserAttributeDefinitionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&UserAttributeDefinitionDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("ent: unknown UserAttributeDefinition mutation op: %q", m.Op())
}
}
// UserAttributeValueClient is a client for the UserAttributeValue schema.
type UserAttributeValueClient struct {
config
}
// NewUserAttributeValueClient returns a client for the UserAttributeValue from the given config.
func NewUserAttributeValueClient(c config) *UserAttributeValueClient {
return &UserAttributeValueClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `userattributevalue.Hooks(f(g(h())))`.
func (c *UserAttributeValueClient) Use(hooks ...Hook) {
c.hooks.UserAttributeValue = append(c.hooks.UserAttributeValue, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `userattributevalue.Intercept(f(g(h())))`.
func (c *UserAttributeValueClient) Intercept(interceptors ...Interceptor) {
c.inters.UserAttributeValue = append(c.inters.UserAttributeValue, interceptors...)
}
// Create returns a builder for creating a UserAttributeValue entity.
func (c *UserAttributeValueClient) Create() *UserAttributeValueCreate {
mutation := newUserAttributeValueMutation(c.config, OpCreate)
return &UserAttributeValueCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of UserAttributeValue entities.
func (c *UserAttributeValueClient) CreateBulk(builders ...*UserAttributeValueCreate) *UserAttributeValueCreateBulk {
return &UserAttributeValueCreateBulk{config: c.config, builders: builders}
}
// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates
// a builder and applies setFunc on it.
func (c *UserAttributeValueClient) MapCreateBulk(slice any, setFunc func(*UserAttributeValueCreate, int)) *UserAttributeValueCreateBulk {
rv := reflect.ValueOf(slice)
if rv.Kind() != reflect.Slice {
return &UserAttributeValueCreateBulk{err: fmt.Errorf("calling to UserAttributeValueClient.MapCreateBulk with wrong type %T, need slice", slice)}
}
builders := make([]*UserAttributeValueCreate, rv.Len())
for i := 0; i < rv.Len(); i++ {
builders[i] = c.Create()
setFunc(builders[i], i)
}
return &UserAttributeValueCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for UserAttributeValue.
func (c *UserAttributeValueClient) Update() *UserAttributeValueUpdate {
mutation := newUserAttributeValueMutation(c.config, OpUpdate)
return &UserAttributeValueUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *UserAttributeValueClient) UpdateOne(_m *UserAttributeValue) *UserAttributeValueUpdateOne {
mutation := newUserAttributeValueMutation(c.config, OpUpdateOne, withUserAttributeValue(_m))
return &UserAttributeValueUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *UserAttributeValueClient) UpdateOneID(id int64) *UserAttributeValueUpdateOne {
mutation := newUserAttributeValueMutation(c.config, OpUpdateOne, withUserAttributeValueID(id))
return &UserAttributeValueUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for UserAttributeValue.
func (c *UserAttributeValueClient) Delete() *UserAttributeValueDelete {
mutation := newUserAttributeValueMutation(c.config, OpDelete)
return &UserAttributeValueDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *UserAttributeValueClient) DeleteOne(_m *UserAttributeValue) *UserAttributeValueDeleteOne {
return c.DeleteOneID(_m.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *UserAttributeValueClient) DeleteOneID(id int64) *UserAttributeValueDeleteOne {
builder := c.Delete().Where(userattributevalue.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &UserAttributeValueDeleteOne{builder}
}
// Query returns a query builder for UserAttributeValue.
func (c *UserAttributeValueClient) Query() *UserAttributeValueQuery {
return &UserAttributeValueQuery{
config: c.config,
ctx: &QueryContext{Type: TypeUserAttributeValue},
inters: c.Interceptors(),
}
}
// Get returns a UserAttributeValue entity by its id.
func (c *UserAttributeValueClient) Get(ctx context.Context, id int64) (*UserAttributeValue, error) {
return c.Query().Where(userattributevalue.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *UserAttributeValueClient) GetX(ctx context.Context, id int64) *UserAttributeValue {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// QueryUser queries the user edge of a UserAttributeValue.
func (c *UserAttributeValueClient) QueryUser(_m *UserAttributeValue) *UserQuery {
query := (&UserClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(userattributevalue.Table, userattributevalue.FieldID, id),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, userattributevalue.UserTable, userattributevalue.UserColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryDefinition queries the definition edge of a UserAttributeValue.
func (c *UserAttributeValueClient) QueryDefinition(_m *UserAttributeValue) *UserAttributeDefinitionQuery {
query := (&UserAttributeDefinitionClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(userattributevalue.Table, userattributevalue.FieldID, id),
sqlgraph.To(userattributedefinition.Table, userattributedefinition.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, userattributevalue.DefinitionTable, userattributevalue.DefinitionColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *UserAttributeValueClient) Hooks() []Hook {
return c.hooks.UserAttributeValue
}
// Interceptors returns the client interceptors.
func (c *UserAttributeValueClient) Interceptors() []Interceptor {
return c.inters.UserAttributeValue
}
func (c *UserAttributeValueClient) mutate(ctx context.Context, m *UserAttributeValueMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&UserAttributeValueCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&UserAttributeValueUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&UserAttributeValueUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&UserAttributeValueDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("ent: unknown UserAttributeValue mutation op: %q", m.Op())
}
}
// UserSubscriptionClient is a client for the UserSubscription schema. // UserSubscriptionClient is a client for the UserSubscription schema.
type UserSubscriptionClient struct { type UserSubscriptionClient struct {
config config
...@@ -2278,11 +2628,13 @@ func (c *UserSubscriptionClient) mutate(ctx context.Context, m *UserSubscription ...@@ -2278,11 +2628,13 @@ func (c *UserSubscriptionClient) mutate(ctx context.Context, m *UserSubscription
type ( type (
hooks struct { hooks struct {
Account, AccountGroup, ApiKey, Group, Proxy, RedeemCode, Setting, UsageLog, Account, AccountGroup, ApiKey, Group, Proxy, RedeemCode, Setting, UsageLog,
User, UserAllowedGroup, UserSubscription []ent.Hook User, UserAllowedGroup, UserAttributeDefinition, UserAttributeValue,
UserSubscription []ent.Hook
} }
inters struct { inters struct {
Account, AccountGroup, ApiKey, Group, Proxy, RedeemCode, Setting, UsageLog, Account, AccountGroup, ApiKey, Group, Proxy, RedeemCode, Setting, UsageLog,
User, UserAllowedGroup, UserSubscription []ent.Interceptor User, UserAllowedGroup, UserAttributeDefinition, UserAttributeValue,
UserSubscription []ent.Interceptor
} }
) )
......
...@@ -22,6 +22,8 @@ import ( ...@@ -22,6 +22,8 @@ import (
"github.com/Wei-Shaw/sub2api/ent/usagelog" "github.com/Wei-Shaw/sub2api/ent/usagelog"
"github.com/Wei-Shaw/sub2api/ent/user" "github.com/Wei-Shaw/sub2api/ent/user"
"github.com/Wei-Shaw/sub2api/ent/userallowedgroup" "github.com/Wei-Shaw/sub2api/ent/userallowedgroup"
"github.com/Wei-Shaw/sub2api/ent/userattributedefinition"
"github.com/Wei-Shaw/sub2api/ent/userattributevalue"
"github.com/Wei-Shaw/sub2api/ent/usersubscription" "github.com/Wei-Shaw/sub2api/ent/usersubscription"
) )
...@@ -93,6 +95,8 @@ func checkColumn(t, c string) error { ...@@ -93,6 +95,8 @@ func checkColumn(t, c string) error {
usagelog.Table: usagelog.ValidColumn, usagelog.Table: usagelog.ValidColumn,
user.Table: user.ValidColumn, user.Table: user.ValidColumn,
userallowedgroup.Table: userallowedgroup.ValidColumn, userallowedgroup.Table: userallowedgroup.ValidColumn,
userattributedefinition.Table: userattributedefinition.ValidColumn,
userattributevalue.Table: userattributevalue.ValidColumn,
usersubscription.Table: usersubscription.ValidColumn, usersubscription.Table: usersubscription.ValidColumn,
}) })
}) })
......
...@@ -129,6 +129,30 @@ func (f UserAllowedGroupFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.V ...@@ -129,6 +129,30 @@ func (f UserAllowedGroupFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.V
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.UserAllowedGroupMutation", m) return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.UserAllowedGroupMutation", m)
} }
// The UserAttributeDefinitionFunc type is an adapter to allow the use of ordinary
// function as UserAttributeDefinition mutator.
type UserAttributeDefinitionFunc func(context.Context, *ent.UserAttributeDefinitionMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f UserAttributeDefinitionFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.UserAttributeDefinitionMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.UserAttributeDefinitionMutation", m)
}
// The UserAttributeValueFunc type is an adapter to allow the use of ordinary
// function as UserAttributeValue mutator.
type UserAttributeValueFunc func(context.Context, *ent.UserAttributeValueMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f UserAttributeValueFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.UserAttributeValueMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.UserAttributeValueMutation", m)
}
// The UserSubscriptionFunc type is an adapter to allow the use of ordinary // The UserSubscriptionFunc type is an adapter to allow the use of ordinary
// function as UserSubscription mutator. // function as UserSubscription mutator.
type UserSubscriptionFunc func(context.Context, *ent.UserSubscriptionMutation) (ent.Value, error) type UserSubscriptionFunc func(context.Context, *ent.UserSubscriptionMutation) (ent.Value, error)
......
...@@ -19,6 +19,8 @@ import ( ...@@ -19,6 +19,8 @@ import (
"github.com/Wei-Shaw/sub2api/ent/usagelog" "github.com/Wei-Shaw/sub2api/ent/usagelog"
"github.com/Wei-Shaw/sub2api/ent/user" "github.com/Wei-Shaw/sub2api/ent/user"
"github.com/Wei-Shaw/sub2api/ent/userallowedgroup" "github.com/Wei-Shaw/sub2api/ent/userallowedgroup"
"github.com/Wei-Shaw/sub2api/ent/userattributedefinition"
"github.com/Wei-Shaw/sub2api/ent/userattributevalue"
"github.com/Wei-Shaw/sub2api/ent/usersubscription" "github.com/Wei-Shaw/sub2api/ent/usersubscription"
) )
...@@ -348,6 +350,60 @@ func (f TraverseUserAllowedGroup) Traverse(ctx context.Context, q ent.Query) err ...@@ -348,6 +350,60 @@ func (f TraverseUserAllowedGroup) Traverse(ctx context.Context, q ent.Query) err
return fmt.Errorf("unexpected query type %T. expect *ent.UserAllowedGroupQuery", q) return fmt.Errorf("unexpected query type %T. expect *ent.UserAllowedGroupQuery", q)
} }
// The UserAttributeDefinitionFunc type is an adapter to allow the use of ordinary function as a Querier.
type UserAttributeDefinitionFunc func(context.Context, *ent.UserAttributeDefinitionQuery) (ent.Value, error)
// Query calls f(ctx, q).
func (f UserAttributeDefinitionFunc) Query(ctx context.Context, q ent.Query) (ent.Value, error) {
if q, ok := q.(*ent.UserAttributeDefinitionQuery); ok {
return f(ctx, q)
}
return nil, fmt.Errorf("unexpected query type %T. expect *ent.UserAttributeDefinitionQuery", q)
}
// The TraverseUserAttributeDefinition type is an adapter to allow the use of ordinary function as Traverser.
type TraverseUserAttributeDefinition func(context.Context, *ent.UserAttributeDefinitionQuery) error
// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
func (f TraverseUserAttributeDefinition) Intercept(next ent.Querier) ent.Querier {
return next
}
// Traverse calls f(ctx, q).
func (f TraverseUserAttributeDefinition) Traverse(ctx context.Context, q ent.Query) error {
if q, ok := q.(*ent.UserAttributeDefinitionQuery); ok {
return f(ctx, q)
}
return fmt.Errorf("unexpected query type %T. expect *ent.UserAttributeDefinitionQuery", q)
}
// The UserAttributeValueFunc type is an adapter to allow the use of ordinary function as a Querier.
type UserAttributeValueFunc func(context.Context, *ent.UserAttributeValueQuery) (ent.Value, error)
// Query calls f(ctx, q).
func (f UserAttributeValueFunc) Query(ctx context.Context, q ent.Query) (ent.Value, error) {
if q, ok := q.(*ent.UserAttributeValueQuery); ok {
return f(ctx, q)
}
return nil, fmt.Errorf("unexpected query type %T. expect *ent.UserAttributeValueQuery", q)
}
// The TraverseUserAttributeValue type is an adapter to allow the use of ordinary function as Traverser.
type TraverseUserAttributeValue func(context.Context, *ent.UserAttributeValueQuery) error
// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
func (f TraverseUserAttributeValue) Intercept(next ent.Querier) ent.Querier {
return next
}
// Traverse calls f(ctx, q).
func (f TraverseUserAttributeValue) Traverse(ctx context.Context, q ent.Query) error {
if q, ok := q.(*ent.UserAttributeValueQuery); ok {
return f(ctx, q)
}
return fmt.Errorf("unexpected query type %T. expect *ent.UserAttributeValueQuery", q)
}
// The UserSubscriptionFunc type is an adapter to allow the use of ordinary function as a Querier. // 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) type UserSubscriptionFunc func(context.Context, *ent.UserSubscriptionQuery) (ent.Value, error)
...@@ -398,6 +454,10 @@ func NewQuery(q ent.Query) (Query, error) { ...@@ -398,6 +454,10 @@ func NewQuery(q ent.Query) (Query, error) {
return &query[*ent.UserQuery, predicate.User, user.OrderOption]{typ: ent.TypeUser, tq: q}, nil return &query[*ent.UserQuery, predicate.User, user.OrderOption]{typ: ent.TypeUser, tq: q}, nil
case *ent.UserAllowedGroupQuery: case *ent.UserAllowedGroupQuery:
return &query[*ent.UserAllowedGroupQuery, predicate.UserAllowedGroup, userallowedgroup.OrderOption]{typ: ent.TypeUserAllowedGroup, tq: q}, nil return &query[*ent.UserAllowedGroupQuery, predicate.UserAllowedGroup, userallowedgroup.OrderOption]{typ: ent.TypeUserAllowedGroup, tq: q}, nil
case *ent.UserAttributeDefinitionQuery:
return &query[*ent.UserAttributeDefinitionQuery, predicate.UserAttributeDefinition, userattributedefinition.OrderOption]{typ: ent.TypeUserAttributeDefinition, tq: q}, nil
case *ent.UserAttributeValueQuery:
return &query[*ent.UserAttributeValueQuery, predicate.UserAttributeValue, userattributevalue.OrderOption]{typ: ent.TypeUserAttributeValue, tq: q}, nil
case *ent.UserSubscriptionQuery: case *ent.UserSubscriptionQuery:
return &query[*ent.UserSubscriptionQuery, predicate.UserSubscription, usersubscription.OrderOption]{typ: ent.TypeUserSubscription, tq: q}, nil return &query[*ent.UserSubscriptionQuery, predicate.UserSubscription, usersubscription.OrderOption]{typ: ent.TypeUserSubscription, tq: q}, nil
default: default:
......
...@@ -477,7 +477,6 @@ var ( ...@@ -477,7 +477,6 @@ var (
{Name: "concurrency", Type: field.TypeInt, Default: 5}, {Name: "concurrency", Type: field.TypeInt, Default: 5},
{Name: "status", Type: field.TypeString, Size: 20, Default: "active"}, {Name: "status", Type: field.TypeString, Size: 20, Default: "active"},
{Name: "username", Type: field.TypeString, Size: 100, Default: ""}, {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"}}, {Name: "notes", Type: field.TypeString, Default: "", SchemaType: map[string]string{"postgres": "text"}},
} }
// UsersTable holds the schema information for the "users" table. // UsersTable holds the schema information for the "users" table.
...@@ -531,6 +530,92 @@ var ( ...@@ -531,6 +530,92 @@ var (
}, },
}, },
} }
// UserAttributeDefinitionsColumns holds the columns for the "user_attribute_definitions" table.
UserAttributeDefinitionsColumns = []*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, Size: 100},
{Name: "name", Type: field.TypeString, Size: 255},
{Name: "description", Type: field.TypeString, Default: "", SchemaType: map[string]string{"postgres": "text"}},
{Name: "type", Type: field.TypeString, Size: 20},
{Name: "options", Type: field.TypeJSON, SchemaType: map[string]string{"postgres": "jsonb"}},
{Name: "required", Type: field.TypeBool, Default: false},
{Name: "validation", Type: field.TypeJSON, SchemaType: map[string]string{"postgres": "jsonb"}},
{Name: "placeholder", Type: field.TypeString, Size: 255, Default: ""},
{Name: "display_order", Type: field.TypeInt, Default: 0},
{Name: "enabled", Type: field.TypeBool, Default: true},
}
// UserAttributeDefinitionsTable holds the schema information for the "user_attribute_definitions" table.
UserAttributeDefinitionsTable = &schema.Table{
Name: "user_attribute_definitions",
Columns: UserAttributeDefinitionsColumns,
PrimaryKey: []*schema.Column{UserAttributeDefinitionsColumns[0]},
Indexes: []*schema.Index{
{
Name: "userattributedefinition_key",
Unique: false,
Columns: []*schema.Column{UserAttributeDefinitionsColumns[4]},
},
{
Name: "userattributedefinition_enabled",
Unique: false,
Columns: []*schema.Column{UserAttributeDefinitionsColumns[13]},
},
{
Name: "userattributedefinition_display_order",
Unique: false,
Columns: []*schema.Column{UserAttributeDefinitionsColumns[12]},
},
{
Name: "userattributedefinition_deleted_at",
Unique: false,
Columns: []*schema.Column{UserAttributeDefinitionsColumns[3]},
},
},
}
// UserAttributeValuesColumns holds the columns for the "user_attribute_values" table.
UserAttributeValuesColumns = []*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: "value", Type: field.TypeString, Size: 2147483647, Default: ""},
{Name: "user_id", Type: field.TypeInt64},
{Name: "attribute_id", Type: field.TypeInt64},
}
// UserAttributeValuesTable holds the schema information for the "user_attribute_values" table.
UserAttributeValuesTable = &schema.Table{
Name: "user_attribute_values",
Columns: UserAttributeValuesColumns,
PrimaryKey: []*schema.Column{UserAttributeValuesColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "user_attribute_values_users_attribute_values",
Columns: []*schema.Column{UserAttributeValuesColumns[4]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.NoAction,
},
{
Symbol: "user_attribute_values_user_attribute_definitions_values",
Columns: []*schema.Column{UserAttributeValuesColumns[5]},
RefColumns: []*schema.Column{UserAttributeDefinitionsColumns[0]},
OnDelete: schema.NoAction,
},
},
Indexes: []*schema.Index{
{
Name: "userattributevalue_user_id_attribute_id",
Unique: true,
Columns: []*schema.Column{UserAttributeValuesColumns[4], UserAttributeValuesColumns[5]},
},
{
Name: "userattributevalue_attribute_id",
Unique: false,
Columns: []*schema.Column{UserAttributeValuesColumns[5]},
},
},
}
// UserSubscriptionsColumns holds the columns for the "user_subscriptions" table. // UserSubscriptionsColumns holds the columns for the "user_subscriptions" table.
UserSubscriptionsColumns = []*schema.Column{ UserSubscriptionsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt64, Increment: true}, {Name: "id", Type: field.TypeInt64, Increment: true},
...@@ -627,6 +712,8 @@ var ( ...@@ -627,6 +712,8 @@ var (
UsageLogsTable, UsageLogsTable,
UsersTable, UsersTable,
UserAllowedGroupsTable, UserAllowedGroupsTable,
UserAttributeDefinitionsTable,
UserAttributeValuesTable,
UserSubscriptionsTable, UserSubscriptionsTable,
} }
) )
...@@ -676,6 +763,14 @@ func init() { ...@@ -676,6 +763,14 @@ func init() {
UserAllowedGroupsTable.Annotation = &entsql.Annotation{ UserAllowedGroupsTable.Annotation = &entsql.Annotation{
Table: "user_allowed_groups", Table: "user_allowed_groups",
} }
UserAttributeDefinitionsTable.Annotation = &entsql.Annotation{
Table: "user_attribute_definitions",
}
UserAttributeValuesTable.ForeignKeys[0].RefTable = UsersTable
UserAttributeValuesTable.ForeignKeys[1].RefTable = UserAttributeDefinitionsTable
UserAttributeValuesTable.Annotation = &entsql.Annotation{
Table: "user_attribute_values",
}
UserSubscriptionsTable.ForeignKeys[0].RefTable = GroupsTable UserSubscriptionsTable.ForeignKeys[0].RefTable = GroupsTable
UserSubscriptionsTable.ForeignKeys[1].RefTable = UsersTable UserSubscriptionsTable.ForeignKeys[1].RefTable = UsersTable
UserSubscriptionsTable.ForeignKeys[2].RefTable = UsersTable UserSubscriptionsTable.ForeignKeys[2].RefTable = UsersTable
......
...@@ -22,6 +22,8 @@ import ( ...@@ -22,6 +22,8 @@ import (
"github.com/Wei-Shaw/sub2api/ent/usagelog" "github.com/Wei-Shaw/sub2api/ent/usagelog"
"github.com/Wei-Shaw/sub2api/ent/user" "github.com/Wei-Shaw/sub2api/ent/user"
"github.com/Wei-Shaw/sub2api/ent/userallowedgroup" "github.com/Wei-Shaw/sub2api/ent/userallowedgroup"
"github.com/Wei-Shaw/sub2api/ent/userattributedefinition"
"github.com/Wei-Shaw/sub2api/ent/userattributevalue"
"github.com/Wei-Shaw/sub2api/ent/usersubscription" "github.com/Wei-Shaw/sub2api/ent/usersubscription"
) )
...@@ -44,6 +46,8 @@ const ( ...@@ -44,6 +46,8 @@ const (
TypeUsageLog = "UsageLog" TypeUsageLog = "UsageLog"
TypeUser = "User" TypeUser = "User"
TypeUserAllowedGroup = "UserAllowedGroup" TypeUserAllowedGroup = "UserAllowedGroup"
TypeUserAttributeDefinition = "UserAttributeDefinition"
TypeUserAttributeValue = "UserAttributeValue"
TypeUserSubscription = "UserSubscription" TypeUserSubscription = "UserSubscription"
) )
...@@ -10158,7 +10162,6 @@ type UserMutation struct { ...@@ -10158,7 +10162,6 @@ type UserMutation struct {
addconcurrency *int addconcurrency *int
status *string status *string
username *string username *string
wechat *string
notes *string notes *string
clearedFields map[string]struct{} clearedFields map[string]struct{}
api_keys map[int64]struct{} api_keys map[int64]struct{}
...@@ -10179,6 +10182,9 @@ type UserMutation struct { ...@@ -10179,6 +10182,9 @@ type UserMutation struct {
usage_logs map[int64]struct{} usage_logs map[int64]struct{}
removedusage_logs map[int64]struct{} removedusage_logs map[int64]struct{}
clearedusage_logs bool clearedusage_logs bool
attribute_values map[int64]struct{}
removedattribute_values map[int64]struct{}
clearedattribute_values bool
done bool done bool
oldValue func(context.Context) (*User, error) oldValue func(context.Context) (*User, error)
predicates []predicate.User predicates []predicate.User
...@@ -10695,42 +10701,6 @@ func (m *UserMutation) ResetUsername() { ...@@ -10695,42 +10701,6 @@ func (m *UserMutation) ResetUsername() {
m.username = nil m.username = nil
} }
// SetWechat sets the "wechat" field.
func (m *UserMutation) SetWechat(s string) {
m.wechat = &s
}
// Wechat returns the value of the "wechat" field in the mutation.
func (m *UserMutation) Wechat() (r string, exists bool) {
v := m.wechat
if v == nil {
return
}
return *v, true
}
// OldWechat returns the old "wechat" field's value of the User entity.
// If the User object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *UserMutation) OldWechat(ctx context.Context) (v string, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldWechat is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldWechat requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldWechat: %w", err)
}
return oldValue.Wechat, nil
}
// ResetWechat resets all changes to the "wechat" field.
func (m *UserMutation) ResetWechat() {
m.wechat = nil
}
// SetNotes sets the "notes" field. // SetNotes sets the "notes" field.
func (m *UserMutation) SetNotes(s string) { func (m *UserMutation) SetNotes(s string) {
m.notes = &s m.notes = &s
...@@ -11091,6 +11061,60 @@ func (m *UserMutation) ResetUsageLogs() { ...@@ -11091,6 +11061,60 @@ func (m *UserMutation) ResetUsageLogs() {
m.removedusage_logs = nil m.removedusage_logs = nil
} }
// AddAttributeValueIDs adds the "attribute_values" edge to the UserAttributeValue entity by ids.
func (m *UserMutation) AddAttributeValueIDs(ids ...int64) {
if m.attribute_values == nil {
m.attribute_values = make(map[int64]struct{})
}
for i := range ids {
m.attribute_values[ids[i]] = struct{}{}
}
}
// ClearAttributeValues clears the "attribute_values" edge to the UserAttributeValue entity.
func (m *UserMutation) ClearAttributeValues() {
m.clearedattribute_values = true
}
// AttributeValuesCleared reports if the "attribute_values" edge to the UserAttributeValue entity was cleared.
func (m *UserMutation) AttributeValuesCleared() bool {
return m.clearedattribute_values
}
// RemoveAttributeValueIDs removes the "attribute_values" edge to the UserAttributeValue entity by IDs.
func (m *UserMutation) RemoveAttributeValueIDs(ids ...int64) {
if m.removedattribute_values == nil {
m.removedattribute_values = make(map[int64]struct{})
}
for i := range ids {
delete(m.attribute_values, ids[i])
m.removedattribute_values[ids[i]] = struct{}{}
}
}
// RemovedAttributeValues returns the removed IDs of the "attribute_values" edge to the UserAttributeValue entity.
func (m *UserMutation) RemovedAttributeValuesIDs() (ids []int64) {
for id := range m.removedattribute_values {
ids = append(ids, id)
}
return
}
// AttributeValuesIDs returns the "attribute_values" edge IDs in the mutation.
func (m *UserMutation) AttributeValuesIDs() (ids []int64) {
for id := range m.attribute_values {
ids = append(ids, id)
}
return
}
// ResetAttributeValues resets all changes to the "attribute_values" edge.
func (m *UserMutation) ResetAttributeValues() {
m.attribute_values = nil
m.clearedattribute_values = false
m.removedattribute_values = nil
}
// Where appends a list predicates to the UserMutation builder. // Where appends a list predicates to the UserMutation builder.
func (m *UserMutation) Where(ps ...predicate.User) { func (m *UserMutation) Where(ps ...predicate.User) {
m.predicates = append(m.predicates, ps...) m.predicates = append(m.predicates, ps...)
...@@ -11125,7 +11149,7 @@ func (m *UserMutation) Type() string { ...@@ -11125,7 +11149,7 @@ func (m *UserMutation) Type() string {
// order to get all numeric fields that were incremented/decremented, call // order to get all numeric fields that were incremented/decremented, call
// AddedFields(). // AddedFields().
func (m *UserMutation) Fields() []string { func (m *UserMutation) Fields() []string {
fields := make([]string, 0, 12) fields := make([]string, 0, 11)
if m.created_at != nil { if m.created_at != nil {
fields = append(fields, user.FieldCreatedAt) fields = append(fields, user.FieldCreatedAt)
} }
...@@ -11156,9 +11180,6 @@ func (m *UserMutation) Fields() []string { ...@@ -11156,9 +11180,6 @@ func (m *UserMutation) Fields() []string {
if m.username != nil { if m.username != nil {
fields = append(fields, user.FieldUsername) fields = append(fields, user.FieldUsername)
} }
if m.wechat != nil {
fields = append(fields, user.FieldWechat)
}
if m.notes != nil { if m.notes != nil {
fields = append(fields, user.FieldNotes) fields = append(fields, user.FieldNotes)
} }
...@@ -11190,8 +11211,6 @@ func (m *UserMutation) Field(name string) (ent.Value, bool) { ...@@ -11190,8 +11211,6 @@ func (m *UserMutation) Field(name string) (ent.Value, bool) {
return m.Status() return m.Status()
case user.FieldUsername: case user.FieldUsername:
return m.Username() return m.Username()
case user.FieldWechat:
return m.Wechat()
case user.FieldNotes: case user.FieldNotes:
return m.Notes() return m.Notes()
} }
...@@ -11223,8 +11242,6 @@ func (m *UserMutation) OldField(ctx context.Context, name string) (ent.Value, er ...@@ -11223,8 +11242,6 @@ func (m *UserMutation) OldField(ctx context.Context, name string) (ent.Value, er
return m.OldStatus(ctx) return m.OldStatus(ctx)
case user.FieldUsername: case user.FieldUsername:
return m.OldUsername(ctx) return m.OldUsername(ctx)
case user.FieldWechat:
return m.OldWechat(ctx)
case user.FieldNotes: case user.FieldNotes:
return m.OldNotes(ctx) return m.OldNotes(ctx)
} }
...@@ -11306,13 +11323,6 @@ func (m *UserMutation) SetField(name string, value ent.Value) error { ...@@ -11306,13 +11323,6 @@ func (m *UserMutation) SetField(name string, value ent.Value) error {
} }
m.SetUsername(v) m.SetUsername(v)
return nil return nil
case user.FieldWechat:
v, ok := value.(string)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetWechat(v)
return nil
case user.FieldNotes: case user.FieldNotes:
v, ok := value.(string) v, ok := value.(string)
if !ok { if !ok {
...@@ -11435,9 +11445,6 @@ func (m *UserMutation) ResetField(name string) error { ...@@ -11435,9 +11445,6 @@ func (m *UserMutation) ResetField(name string) error {
case user.FieldUsername: case user.FieldUsername:
m.ResetUsername() m.ResetUsername()
return nil return nil
case user.FieldWechat:
m.ResetWechat()
return nil
case user.FieldNotes: case user.FieldNotes:
m.ResetNotes() m.ResetNotes()
return nil return nil
...@@ -11447,7 +11454,7 @@ func (m *UserMutation) ResetField(name string) error { ...@@ -11447,7 +11454,7 @@ func (m *UserMutation) ResetField(name string) error {
// AddedEdges returns all edge names that were set/added in this mutation. // AddedEdges returns all edge names that were set/added in this mutation.
func (m *UserMutation) AddedEdges() []string { func (m *UserMutation) AddedEdges() []string {
edges := make([]string, 0, 6) edges := make([]string, 0, 7)
if m.api_keys != nil { if m.api_keys != nil {
edges = append(edges, user.EdgeAPIKeys) edges = append(edges, user.EdgeAPIKeys)
} }
...@@ -11466,6 +11473,9 @@ func (m *UserMutation) AddedEdges() []string { ...@@ -11466,6 +11473,9 @@ func (m *UserMutation) AddedEdges() []string {
if m.usage_logs != nil { if m.usage_logs != nil {
edges = append(edges, user.EdgeUsageLogs) edges = append(edges, user.EdgeUsageLogs)
} }
if m.attribute_values != nil {
edges = append(edges, user.EdgeAttributeValues)
}
return edges return edges
} }
...@@ -11509,13 +11519,19 @@ func (m *UserMutation) AddedIDs(name string) []ent.Value { ...@@ -11509,13 +11519,19 @@ func (m *UserMutation) AddedIDs(name string) []ent.Value {
ids = append(ids, id) ids = append(ids, id)
} }
return ids return ids
case user.EdgeAttributeValues:
ids := make([]ent.Value, 0, len(m.attribute_values))
for id := range m.attribute_values {
ids = append(ids, id)
}
return ids
} }
return nil return nil
} }
// RemovedEdges returns all edge names that were removed in this mutation. // RemovedEdges returns all edge names that were removed in this mutation.
func (m *UserMutation) RemovedEdges() []string { func (m *UserMutation) RemovedEdges() []string {
edges := make([]string, 0, 6) edges := make([]string, 0, 7)
if m.removedapi_keys != nil { if m.removedapi_keys != nil {
edges = append(edges, user.EdgeAPIKeys) edges = append(edges, user.EdgeAPIKeys)
} }
...@@ -11534,6 +11550,9 @@ func (m *UserMutation) RemovedEdges() []string { ...@@ -11534,6 +11550,9 @@ func (m *UserMutation) RemovedEdges() []string {
if m.removedusage_logs != nil { if m.removedusage_logs != nil {
edges = append(edges, user.EdgeUsageLogs) edges = append(edges, user.EdgeUsageLogs)
} }
if m.removedattribute_values != nil {
edges = append(edges, user.EdgeAttributeValues)
}
return edges return edges
} }
...@@ -11577,13 +11596,19 @@ func (m *UserMutation) RemovedIDs(name string) []ent.Value { ...@@ -11577,13 +11596,19 @@ func (m *UserMutation) RemovedIDs(name string) []ent.Value {
ids = append(ids, id) ids = append(ids, id)
} }
return ids return ids
case user.EdgeAttributeValues:
ids := make([]ent.Value, 0, len(m.removedattribute_values))
for id := range m.removedattribute_values {
ids = append(ids, id)
}
return ids
} }
return nil return nil
} }
// ClearedEdges returns all edge names that were cleared in this mutation. // ClearedEdges returns all edge names that were cleared in this mutation.
func (m *UserMutation) ClearedEdges() []string { func (m *UserMutation) ClearedEdges() []string {
edges := make([]string, 0, 6) edges := make([]string, 0, 7)
if m.clearedapi_keys { if m.clearedapi_keys {
edges = append(edges, user.EdgeAPIKeys) edges = append(edges, user.EdgeAPIKeys)
} }
...@@ -11602,6 +11627,9 @@ func (m *UserMutation) ClearedEdges() []string { ...@@ -11602,6 +11627,9 @@ func (m *UserMutation) ClearedEdges() []string {
if m.clearedusage_logs { if m.clearedusage_logs {
edges = append(edges, user.EdgeUsageLogs) edges = append(edges, user.EdgeUsageLogs)
} }
if m.clearedattribute_values {
edges = append(edges, user.EdgeAttributeValues)
}
return edges return edges
} }
...@@ -11621,6 +11649,8 @@ func (m *UserMutation) EdgeCleared(name string) bool { ...@@ -11621,6 +11649,8 @@ func (m *UserMutation) EdgeCleared(name string) bool {
return m.clearedallowed_groups return m.clearedallowed_groups
case user.EdgeUsageLogs: case user.EdgeUsageLogs:
return m.clearedusage_logs return m.clearedusage_logs
case user.EdgeAttributeValues:
return m.clearedattribute_values
} }
return false return false
} }
...@@ -11655,6 +11685,9 @@ func (m *UserMutation) ResetEdge(name string) error { ...@@ -11655,6 +11685,9 @@ func (m *UserMutation) ResetEdge(name string) error {
case user.EdgeUsageLogs: case user.EdgeUsageLogs:
m.ResetUsageLogs() m.ResetUsageLogs()
return nil return nil
case user.EdgeAttributeValues:
m.ResetAttributeValues()
return nil
} }
return fmt.Errorf("unknown User edge %s", name) return fmt.Errorf("unknown User edge %s", name)
} }
...@@ -12076,6 +12109,1805 @@ func (m *UserAllowedGroupMutation) ResetEdge(name string) error { ...@@ -12076,6 +12109,1805 @@ func (m *UserAllowedGroupMutation) ResetEdge(name string) error {
return fmt.Errorf("unknown UserAllowedGroup edge %s", name) return fmt.Errorf("unknown UserAllowedGroup edge %s", name)
} }
// UserAttributeDefinitionMutation represents an operation that mutates the UserAttributeDefinition nodes in the graph.
type UserAttributeDefinitionMutation struct {
config
op Op
typ string
id *int64
created_at *time.Time
updated_at *time.Time
deleted_at *time.Time
key *string
name *string
description *string
_type *string
options *[]map[string]interface{}
appendoptions []map[string]interface{}
required *bool
validation *map[string]interface{}
placeholder *string
display_order *int
adddisplay_order *int
enabled *bool
clearedFields map[string]struct{}
values map[int64]struct{}
removedvalues map[int64]struct{}
clearedvalues bool
done bool
oldValue func(context.Context) (*UserAttributeDefinition, error)
predicates []predicate.UserAttributeDefinition
}
var _ ent.Mutation = (*UserAttributeDefinitionMutation)(nil)
// userattributedefinitionOption allows management of the mutation configuration using functional options.
type userattributedefinitionOption func(*UserAttributeDefinitionMutation)
// newUserAttributeDefinitionMutation creates new mutation for the UserAttributeDefinition entity.
func newUserAttributeDefinitionMutation(c config, op Op, opts ...userattributedefinitionOption) *UserAttributeDefinitionMutation {
m := &UserAttributeDefinitionMutation{
config: c,
op: op,
typ: TypeUserAttributeDefinition,
clearedFields: make(map[string]struct{}),
}
for _, opt := range opts {
opt(m)
}
return m
}
// withUserAttributeDefinitionID sets the ID field of the mutation.
func withUserAttributeDefinitionID(id int64) userattributedefinitionOption {
return func(m *UserAttributeDefinitionMutation) {
var (
err error
once sync.Once
value *UserAttributeDefinition
)
m.oldValue = func(ctx context.Context) (*UserAttributeDefinition, error) {
once.Do(func() {
if m.done {
err = errors.New("querying old values post mutation is not allowed")
} else {
value, err = m.Client().UserAttributeDefinition.Get(ctx, id)
}
})
return value, err
}
m.id = &id
}
}
// withUserAttributeDefinition sets the old UserAttributeDefinition of the mutation.
func withUserAttributeDefinition(node *UserAttributeDefinition) userattributedefinitionOption {
return func(m *UserAttributeDefinitionMutation) {
m.oldValue = func(context.Context) (*UserAttributeDefinition, error) {
return node, nil
}
m.id = &node.ID
}
}
// Client returns a new `ent.Client` from the mutation. If the mutation was
// executed in a transaction (ent.Tx), a transactional client is returned.
func (m UserAttributeDefinitionMutation) Client() *Client {
client := &Client{config: m.config}
client.init()
return client
}
// Tx returns an `ent.Tx` for mutations that were executed in transactions;
// it returns an error otherwise.
func (m UserAttributeDefinitionMutation) Tx() (*Tx, error) {
if _, ok := m.driver.(*txDriver); !ok {
return nil, errors.New("ent: mutation is not running in a transaction")
}
tx := &Tx{config: m.config}
tx.init()
return tx, nil
}
// ID returns the ID value in the mutation. Note that the ID is only available
// if it was provided to the builder or after it was returned from the database.
func (m *UserAttributeDefinitionMutation) ID() (id int64, exists bool) {
if m.id == nil {
return
}
return *m.id, true
}
// IDs queries the database and returns the entity ids that match the mutation's predicate.
// That means, if the mutation is applied within a transaction with an isolation level such
// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated
// or updated by the mutation.
func (m *UserAttributeDefinitionMutation) IDs(ctx context.Context) ([]int64, error) {
switch {
case m.op.Is(OpUpdateOne | OpDeleteOne):
id, exists := m.ID()
if exists {
return []int64{id}, nil
}
fallthrough
case m.op.Is(OpUpdate | OpDelete):
return m.Client().UserAttributeDefinition.Query().Where(m.predicates...).IDs(ctx)
default:
return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op)
}
}
// SetCreatedAt sets the "created_at" field.
func (m *UserAttributeDefinitionMutation) SetCreatedAt(t time.Time) {
m.created_at = &t
}
// CreatedAt returns the value of the "created_at" field in the mutation.
func (m *UserAttributeDefinitionMutation) CreatedAt() (r time.Time, exists bool) {
v := m.created_at
if v == nil {
return
}
return *v, true
}
// OldCreatedAt returns the old "created_at" field's value of the UserAttributeDefinition entity.
// If the UserAttributeDefinition object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *UserAttributeDefinitionMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldCreatedAt requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err)
}
return oldValue.CreatedAt, nil
}
// ResetCreatedAt resets all changes to the "created_at" field.
func (m *UserAttributeDefinitionMutation) ResetCreatedAt() {
m.created_at = nil
}
// SetUpdatedAt sets the "updated_at" field.
func (m *UserAttributeDefinitionMutation) SetUpdatedAt(t time.Time) {
m.updated_at = &t
}
// UpdatedAt returns the value of the "updated_at" field in the mutation.
func (m *UserAttributeDefinitionMutation) UpdatedAt() (r time.Time, exists bool) {
v := m.updated_at
if v == nil {
return
}
return *v, true
}
// OldUpdatedAt returns the old "updated_at" field's value of the UserAttributeDefinition entity.
// If the UserAttributeDefinition object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *UserAttributeDefinitionMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldUpdatedAt requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err)
}
return oldValue.UpdatedAt, nil
}
// ResetUpdatedAt resets all changes to the "updated_at" field.
func (m *UserAttributeDefinitionMutation) ResetUpdatedAt() {
m.updated_at = nil
}
// SetDeletedAt sets the "deleted_at" field.
func (m *UserAttributeDefinitionMutation) SetDeletedAt(t time.Time) {
m.deleted_at = &t
}
// DeletedAt returns the value of the "deleted_at" field in the mutation.
func (m *UserAttributeDefinitionMutation) DeletedAt() (r time.Time, exists bool) {
v := m.deleted_at
if v == nil {
return
}
return *v, true
}
// OldDeletedAt returns the old "deleted_at" field's value of the UserAttributeDefinition entity.
// If the UserAttributeDefinition object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *UserAttributeDefinitionMutation) OldDeletedAt(ctx context.Context) (v *time.Time, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldDeletedAt is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldDeletedAt requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldDeletedAt: %w", err)
}
return oldValue.DeletedAt, nil
}
// ClearDeletedAt clears the value of the "deleted_at" field.
func (m *UserAttributeDefinitionMutation) ClearDeletedAt() {
m.deleted_at = nil
m.clearedFields[userattributedefinition.FieldDeletedAt] = struct{}{}
}
// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation.
func (m *UserAttributeDefinitionMutation) DeletedAtCleared() bool {
_, ok := m.clearedFields[userattributedefinition.FieldDeletedAt]
return ok
}
// ResetDeletedAt resets all changes to the "deleted_at" field.
func (m *UserAttributeDefinitionMutation) ResetDeletedAt() {
m.deleted_at = nil
delete(m.clearedFields, userattributedefinition.FieldDeletedAt)
}
// SetKey sets the "key" field.
func (m *UserAttributeDefinitionMutation) SetKey(s string) {
m.key = &s
}
// Key returns the value of the "key" field in the mutation.
func (m *UserAttributeDefinitionMutation) Key() (r string, exists bool) {
v := m.key
if v == nil {
return
}
return *v, true
}
// OldKey returns the old "key" field's value of the UserAttributeDefinition entity.
// If the UserAttributeDefinition object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *UserAttributeDefinitionMutation) OldKey(ctx context.Context) (v string, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldKey is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldKey requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldKey: %w", err)
}
return oldValue.Key, nil
}
// ResetKey resets all changes to the "key" field.
func (m *UserAttributeDefinitionMutation) ResetKey() {
m.key = nil
}
// SetName sets the "name" field.
func (m *UserAttributeDefinitionMutation) SetName(s string) {
m.name = &s
}
// Name returns the value of the "name" field in the mutation.
func (m *UserAttributeDefinitionMutation) Name() (r string, exists bool) {
v := m.name
if v == nil {
return
}
return *v, true
}
// OldName returns the old "name" field's value of the UserAttributeDefinition entity.
// If the UserAttributeDefinition object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *UserAttributeDefinitionMutation) OldName(ctx context.Context) (v string, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldName is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldName requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldName: %w", err)
}
return oldValue.Name, nil
}
// ResetName resets all changes to the "name" field.
func (m *UserAttributeDefinitionMutation) ResetName() {
m.name = nil
}
// SetDescription sets the "description" field.
func (m *UserAttributeDefinitionMutation) SetDescription(s string) {
m.description = &s
}
// Description returns the value of the "description" field in the mutation.
func (m *UserAttributeDefinitionMutation) Description() (r string, exists bool) {
v := m.description
if v == nil {
return
}
return *v, true
}
// OldDescription returns the old "description" field's value of the UserAttributeDefinition entity.
// If the UserAttributeDefinition object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *UserAttributeDefinitionMutation) OldDescription(ctx context.Context) (v string, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldDescription is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldDescription requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldDescription: %w", err)
}
return oldValue.Description, nil
}
// ResetDescription resets all changes to the "description" field.
func (m *UserAttributeDefinitionMutation) ResetDescription() {
m.description = nil
}
// SetType sets the "type" field.
func (m *UserAttributeDefinitionMutation) SetType(s string) {
m._type = &s
}
// GetType returns the value of the "type" field in the mutation.
func (m *UserAttributeDefinitionMutation) GetType() (r string, exists bool) {
v := m._type
if v == nil {
return
}
return *v, true
}
// OldType returns the old "type" field's value of the UserAttributeDefinition entity.
// If the UserAttributeDefinition object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *UserAttributeDefinitionMutation) OldType(ctx context.Context) (v string, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldType is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldType requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldType: %w", err)
}
return oldValue.Type, nil
}
// ResetType resets all changes to the "type" field.
func (m *UserAttributeDefinitionMutation) ResetType() {
m._type = nil
}
// SetOptions sets the "options" field.
func (m *UserAttributeDefinitionMutation) SetOptions(value []map[string]interface{}) {
m.options = &value
m.appendoptions = nil
}
// Options returns the value of the "options" field in the mutation.
func (m *UserAttributeDefinitionMutation) Options() (r []map[string]interface{}, exists bool) {
v := m.options
if v == nil {
return
}
return *v, true
}
// OldOptions returns the old "options" field's value of the UserAttributeDefinition entity.
// If the UserAttributeDefinition object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *UserAttributeDefinitionMutation) OldOptions(ctx context.Context) (v []map[string]interface{}, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldOptions is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldOptions requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldOptions: %w", err)
}
return oldValue.Options, nil
}
// AppendOptions adds value to the "options" field.
func (m *UserAttributeDefinitionMutation) AppendOptions(value []map[string]interface{}) {
m.appendoptions = append(m.appendoptions, value...)
}
// AppendedOptions returns the list of values that were appended to the "options" field in this mutation.
func (m *UserAttributeDefinitionMutation) AppendedOptions() ([]map[string]interface{}, bool) {
if len(m.appendoptions) == 0 {
return nil, false
}
return m.appendoptions, true
}
// ResetOptions resets all changes to the "options" field.
func (m *UserAttributeDefinitionMutation) ResetOptions() {
m.options = nil
m.appendoptions = nil
}
// SetRequired sets the "required" field.
func (m *UserAttributeDefinitionMutation) SetRequired(b bool) {
m.required = &b
}
// Required returns the value of the "required" field in the mutation.
func (m *UserAttributeDefinitionMutation) Required() (r bool, exists bool) {
v := m.required
if v == nil {
return
}
return *v, true
}
// OldRequired returns the old "required" field's value of the UserAttributeDefinition entity.
// If the UserAttributeDefinition object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *UserAttributeDefinitionMutation) OldRequired(ctx context.Context) (v bool, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldRequired is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldRequired requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldRequired: %w", err)
}
return oldValue.Required, nil
}
// ResetRequired resets all changes to the "required" field.
func (m *UserAttributeDefinitionMutation) ResetRequired() {
m.required = nil
}
// SetValidation sets the "validation" field.
func (m *UserAttributeDefinitionMutation) SetValidation(value map[string]interface{}) {
m.validation = &value
}
// Validation returns the value of the "validation" field in the mutation.
func (m *UserAttributeDefinitionMutation) Validation() (r map[string]interface{}, exists bool) {
v := m.validation
if v == nil {
return
}
return *v, true
}
// OldValidation returns the old "validation" field's value of the UserAttributeDefinition entity.
// If the UserAttributeDefinition object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *UserAttributeDefinitionMutation) OldValidation(ctx context.Context) (v map[string]interface{}, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldValidation is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldValidation requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldValidation: %w", err)
}
return oldValue.Validation, nil
}
// ResetValidation resets all changes to the "validation" field.
func (m *UserAttributeDefinitionMutation) ResetValidation() {
m.validation = nil
}
// SetPlaceholder sets the "placeholder" field.
func (m *UserAttributeDefinitionMutation) SetPlaceholder(s string) {
m.placeholder = &s
}
// Placeholder returns the value of the "placeholder" field in the mutation.
func (m *UserAttributeDefinitionMutation) Placeholder() (r string, exists bool) {
v := m.placeholder
if v == nil {
return
}
return *v, true
}
// OldPlaceholder returns the old "placeholder" field's value of the UserAttributeDefinition entity.
// If the UserAttributeDefinition object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *UserAttributeDefinitionMutation) OldPlaceholder(ctx context.Context) (v string, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldPlaceholder is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldPlaceholder requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldPlaceholder: %w", err)
}
return oldValue.Placeholder, nil
}
// ResetPlaceholder resets all changes to the "placeholder" field.
func (m *UserAttributeDefinitionMutation) ResetPlaceholder() {
m.placeholder = nil
}
// SetDisplayOrder sets the "display_order" field.
func (m *UserAttributeDefinitionMutation) SetDisplayOrder(i int) {
m.display_order = &i
m.adddisplay_order = nil
}
// DisplayOrder returns the value of the "display_order" field in the mutation.
func (m *UserAttributeDefinitionMutation) DisplayOrder() (r int, exists bool) {
v := m.display_order
if v == nil {
return
}
return *v, true
}
// OldDisplayOrder returns the old "display_order" field's value of the UserAttributeDefinition entity.
// If the UserAttributeDefinition object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *UserAttributeDefinitionMutation) OldDisplayOrder(ctx context.Context) (v int, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldDisplayOrder is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldDisplayOrder requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldDisplayOrder: %w", err)
}
return oldValue.DisplayOrder, nil
}
// AddDisplayOrder adds i to the "display_order" field.
func (m *UserAttributeDefinitionMutation) AddDisplayOrder(i int) {
if m.adddisplay_order != nil {
*m.adddisplay_order += i
} else {
m.adddisplay_order = &i
}
}
// AddedDisplayOrder returns the value that was added to the "display_order" field in this mutation.
func (m *UserAttributeDefinitionMutation) AddedDisplayOrder() (r int, exists bool) {
v := m.adddisplay_order
if v == nil {
return
}
return *v, true
}
// ResetDisplayOrder resets all changes to the "display_order" field.
func (m *UserAttributeDefinitionMutation) ResetDisplayOrder() {
m.display_order = nil
m.adddisplay_order = nil
}
// SetEnabled sets the "enabled" field.
func (m *UserAttributeDefinitionMutation) SetEnabled(b bool) {
m.enabled = &b
}
// Enabled returns the value of the "enabled" field in the mutation.
func (m *UserAttributeDefinitionMutation) Enabled() (r bool, exists bool) {
v := m.enabled
if v == nil {
return
}
return *v, true
}
// OldEnabled returns the old "enabled" field's value of the UserAttributeDefinition entity.
// If the UserAttributeDefinition object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *UserAttributeDefinitionMutation) OldEnabled(ctx context.Context) (v bool, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldEnabled is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldEnabled requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldEnabled: %w", err)
}
return oldValue.Enabled, nil
}
// ResetEnabled resets all changes to the "enabled" field.
func (m *UserAttributeDefinitionMutation) ResetEnabled() {
m.enabled = nil
}
// AddValueIDs adds the "values" edge to the UserAttributeValue entity by ids.
func (m *UserAttributeDefinitionMutation) AddValueIDs(ids ...int64) {
if m.values == nil {
m.values = make(map[int64]struct{})
}
for i := range ids {
m.values[ids[i]] = struct{}{}
}
}
// ClearValues clears the "values" edge to the UserAttributeValue entity.
func (m *UserAttributeDefinitionMutation) ClearValues() {
m.clearedvalues = true
}
// ValuesCleared reports if the "values" edge to the UserAttributeValue entity was cleared.
func (m *UserAttributeDefinitionMutation) ValuesCleared() bool {
return m.clearedvalues
}
// RemoveValueIDs removes the "values" edge to the UserAttributeValue entity by IDs.
func (m *UserAttributeDefinitionMutation) RemoveValueIDs(ids ...int64) {
if m.removedvalues == nil {
m.removedvalues = make(map[int64]struct{})
}
for i := range ids {
delete(m.values, ids[i])
m.removedvalues[ids[i]] = struct{}{}
}
}
// RemovedValues returns the removed IDs of the "values" edge to the UserAttributeValue entity.
func (m *UserAttributeDefinitionMutation) RemovedValuesIDs() (ids []int64) {
for id := range m.removedvalues {
ids = append(ids, id)
}
return
}
// ValuesIDs returns the "values" edge IDs in the mutation.
func (m *UserAttributeDefinitionMutation) ValuesIDs() (ids []int64) {
for id := range m.values {
ids = append(ids, id)
}
return
}
// ResetValues resets all changes to the "values" edge.
func (m *UserAttributeDefinitionMutation) ResetValues() {
m.values = nil
m.clearedvalues = false
m.removedvalues = nil
}
// Where appends a list predicates to the UserAttributeDefinitionMutation builder.
func (m *UserAttributeDefinitionMutation) Where(ps ...predicate.UserAttributeDefinition) {
m.predicates = append(m.predicates, ps...)
}
// WhereP appends storage-level predicates to the UserAttributeDefinitionMutation builder. Using this method,
// users can use type-assertion to append predicates that do not depend on any generated package.
func (m *UserAttributeDefinitionMutation) WhereP(ps ...func(*sql.Selector)) {
p := make([]predicate.UserAttributeDefinition, len(ps))
for i := range ps {
p[i] = ps[i]
}
m.Where(p...)
}
// Op returns the operation name.
func (m *UserAttributeDefinitionMutation) Op() Op {
return m.op
}
// SetOp allows setting the mutation operation.
func (m *UserAttributeDefinitionMutation) SetOp(op Op) {
m.op = op
}
// Type returns the node type of this mutation (UserAttributeDefinition).
func (m *UserAttributeDefinitionMutation) Type() string {
return m.typ
}
// Fields returns all fields that were changed during this mutation. Note that in
// order to get all numeric fields that were incremented/decremented, call
// AddedFields().
func (m *UserAttributeDefinitionMutation) Fields() []string {
fields := make([]string, 0, 13)
if m.created_at != nil {
fields = append(fields, userattributedefinition.FieldCreatedAt)
}
if m.updated_at != nil {
fields = append(fields, userattributedefinition.FieldUpdatedAt)
}
if m.deleted_at != nil {
fields = append(fields, userattributedefinition.FieldDeletedAt)
}
if m.key != nil {
fields = append(fields, userattributedefinition.FieldKey)
}
if m.name != nil {
fields = append(fields, userattributedefinition.FieldName)
}
if m.description != nil {
fields = append(fields, userattributedefinition.FieldDescription)
}
if m._type != nil {
fields = append(fields, userattributedefinition.FieldType)
}
if m.options != nil {
fields = append(fields, userattributedefinition.FieldOptions)
}
if m.required != nil {
fields = append(fields, userattributedefinition.FieldRequired)
}
if m.validation != nil {
fields = append(fields, userattributedefinition.FieldValidation)
}
if m.placeholder != nil {
fields = append(fields, userattributedefinition.FieldPlaceholder)
}
if m.display_order != nil {
fields = append(fields, userattributedefinition.FieldDisplayOrder)
}
if m.enabled != nil {
fields = append(fields, userattributedefinition.FieldEnabled)
}
return fields
}
// Field returns the value of a field with the given name. The second boolean
// return value indicates that this field was not set, or was not defined in the
// schema.
func (m *UserAttributeDefinitionMutation) Field(name string) (ent.Value, bool) {
switch name {
case userattributedefinition.FieldCreatedAt:
return m.CreatedAt()
case userattributedefinition.FieldUpdatedAt:
return m.UpdatedAt()
case userattributedefinition.FieldDeletedAt:
return m.DeletedAt()
case userattributedefinition.FieldKey:
return m.Key()
case userattributedefinition.FieldName:
return m.Name()
case userattributedefinition.FieldDescription:
return m.Description()
case userattributedefinition.FieldType:
return m.GetType()
case userattributedefinition.FieldOptions:
return m.Options()
case userattributedefinition.FieldRequired:
return m.Required()
case userattributedefinition.FieldValidation:
return m.Validation()
case userattributedefinition.FieldPlaceholder:
return m.Placeholder()
case userattributedefinition.FieldDisplayOrder:
return m.DisplayOrder()
case userattributedefinition.FieldEnabled:
return m.Enabled()
}
return nil, false
}
// OldField returns the old value of the field from the database. An error is
// returned if the mutation operation is not UpdateOne, or the query to the
// database failed.
func (m *UserAttributeDefinitionMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
switch name {
case userattributedefinition.FieldCreatedAt:
return m.OldCreatedAt(ctx)
case userattributedefinition.FieldUpdatedAt:
return m.OldUpdatedAt(ctx)
case userattributedefinition.FieldDeletedAt:
return m.OldDeletedAt(ctx)
case userattributedefinition.FieldKey:
return m.OldKey(ctx)
case userattributedefinition.FieldName:
return m.OldName(ctx)
case userattributedefinition.FieldDescription:
return m.OldDescription(ctx)
case userattributedefinition.FieldType:
return m.OldType(ctx)
case userattributedefinition.FieldOptions:
return m.OldOptions(ctx)
case userattributedefinition.FieldRequired:
return m.OldRequired(ctx)
case userattributedefinition.FieldValidation:
return m.OldValidation(ctx)
case userattributedefinition.FieldPlaceholder:
return m.OldPlaceholder(ctx)
case userattributedefinition.FieldDisplayOrder:
return m.OldDisplayOrder(ctx)
case userattributedefinition.FieldEnabled:
return m.OldEnabled(ctx)
}
return nil, fmt.Errorf("unknown UserAttributeDefinition field %s", name)
}
// SetField sets the value of a field with the given name. It returns an error if
// the field is not defined in the schema, or if the type mismatched the field
// type.
func (m *UserAttributeDefinitionMutation) SetField(name string, value ent.Value) error {
switch name {
case userattributedefinition.FieldCreatedAt:
v, ok := value.(time.Time)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetCreatedAt(v)
return nil
case userattributedefinition.FieldUpdatedAt:
v, ok := value.(time.Time)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetUpdatedAt(v)
return nil
case userattributedefinition.FieldDeletedAt:
v, ok := value.(time.Time)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetDeletedAt(v)
return nil
case userattributedefinition.FieldKey:
v, ok := value.(string)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetKey(v)
return nil
case userattributedefinition.FieldName:
v, ok := value.(string)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetName(v)
return nil
case userattributedefinition.FieldDescription:
v, ok := value.(string)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetDescription(v)
return nil
case userattributedefinition.FieldType:
v, ok := value.(string)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetType(v)
return nil
case userattributedefinition.FieldOptions:
v, ok := value.([]map[string]interface{})
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetOptions(v)
return nil
case userattributedefinition.FieldRequired:
v, ok := value.(bool)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetRequired(v)
return nil
case userattributedefinition.FieldValidation:
v, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetValidation(v)
return nil
case userattributedefinition.FieldPlaceholder:
v, ok := value.(string)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetPlaceholder(v)
return nil
case userattributedefinition.FieldDisplayOrder:
v, ok := value.(int)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetDisplayOrder(v)
return nil
case userattributedefinition.FieldEnabled:
v, ok := value.(bool)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetEnabled(v)
return nil
}
return fmt.Errorf("unknown UserAttributeDefinition field %s", name)
}
// AddedFields returns all numeric fields that were incremented/decremented during
// this mutation.
func (m *UserAttributeDefinitionMutation) AddedFields() []string {
var fields []string
if m.adddisplay_order != nil {
fields = append(fields, userattributedefinition.FieldDisplayOrder)
}
return fields
}
// AddedField returns the numeric value that was incremented/decremented on a field
// with the given name. The second boolean return value indicates that this field
// was not set, or was not defined in the schema.
func (m *UserAttributeDefinitionMutation) AddedField(name string) (ent.Value, bool) {
switch name {
case userattributedefinition.FieldDisplayOrder:
return m.AddedDisplayOrder()
}
return nil, false
}
// AddField adds the value to the field with the given name. It returns an error if
// the field is not defined in the schema, or if the type mismatched the field
// type.
func (m *UserAttributeDefinitionMutation) AddField(name string, value ent.Value) error {
switch name {
case userattributedefinition.FieldDisplayOrder:
v, ok := value.(int)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.AddDisplayOrder(v)
return nil
}
return fmt.Errorf("unknown UserAttributeDefinition numeric field %s", name)
}
// ClearedFields returns all nullable fields that were cleared during this
// mutation.
func (m *UserAttributeDefinitionMutation) ClearedFields() []string {
var fields []string
if m.FieldCleared(userattributedefinition.FieldDeletedAt) {
fields = append(fields, userattributedefinition.FieldDeletedAt)
}
return fields
}
// FieldCleared returns a boolean indicating if a field with the given name was
// cleared in this mutation.
func (m *UserAttributeDefinitionMutation) FieldCleared(name string) bool {
_, ok := m.clearedFields[name]
return ok
}
// ClearField clears the value of the field with the given name. It returns an
// error if the field is not defined in the schema.
func (m *UserAttributeDefinitionMutation) ClearField(name string) error {
switch name {
case userattributedefinition.FieldDeletedAt:
m.ClearDeletedAt()
return nil
}
return fmt.Errorf("unknown UserAttributeDefinition nullable field %s", name)
}
// ResetField resets all changes in the mutation for the field with the given name.
// It returns an error if the field is not defined in the schema.
func (m *UserAttributeDefinitionMutation) ResetField(name string) error {
switch name {
case userattributedefinition.FieldCreatedAt:
m.ResetCreatedAt()
return nil
case userattributedefinition.FieldUpdatedAt:
m.ResetUpdatedAt()
return nil
case userattributedefinition.FieldDeletedAt:
m.ResetDeletedAt()
return nil
case userattributedefinition.FieldKey:
m.ResetKey()
return nil
case userattributedefinition.FieldName:
m.ResetName()
return nil
case userattributedefinition.FieldDescription:
m.ResetDescription()
return nil
case userattributedefinition.FieldType:
m.ResetType()
return nil
case userattributedefinition.FieldOptions:
m.ResetOptions()
return nil
case userattributedefinition.FieldRequired:
m.ResetRequired()
return nil
case userattributedefinition.FieldValidation:
m.ResetValidation()
return nil
case userattributedefinition.FieldPlaceholder:
m.ResetPlaceholder()
return nil
case userattributedefinition.FieldDisplayOrder:
m.ResetDisplayOrder()
return nil
case userattributedefinition.FieldEnabled:
m.ResetEnabled()
return nil
}
return fmt.Errorf("unknown UserAttributeDefinition field %s", name)
}
// AddedEdges returns all edge names that were set/added in this mutation.
func (m *UserAttributeDefinitionMutation) AddedEdges() []string {
edges := make([]string, 0, 1)
if m.values != nil {
edges = append(edges, userattributedefinition.EdgeValues)
}
return edges
}
// AddedIDs returns all IDs (to other nodes) that were added for the given edge
// name in this mutation.
func (m *UserAttributeDefinitionMutation) AddedIDs(name string) []ent.Value {
switch name {
case userattributedefinition.EdgeValues:
ids := make([]ent.Value, 0, len(m.values))
for id := range m.values {
ids = append(ids, id)
}
return ids
}
return nil
}
// RemovedEdges returns all edge names that were removed in this mutation.
func (m *UserAttributeDefinitionMutation) RemovedEdges() []string {
edges := make([]string, 0, 1)
if m.removedvalues != nil {
edges = append(edges, userattributedefinition.EdgeValues)
}
return edges
}
// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with
// the given name in this mutation.
func (m *UserAttributeDefinitionMutation) RemovedIDs(name string) []ent.Value {
switch name {
case userattributedefinition.EdgeValues:
ids := make([]ent.Value, 0, len(m.removedvalues))
for id := range m.removedvalues {
ids = append(ids, id)
}
return ids
}
return nil
}
// ClearedEdges returns all edge names that were cleared in this mutation.
func (m *UserAttributeDefinitionMutation) ClearedEdges() []string {
edges := make([]string, 0, 1)
if m.clearedvalues {
edges = append(edges, userattributedefinition.EdgeValues)
}
return edges
}
// EdgeCleared returns a boolean which indicates if the edge with the given name
// was cleared in this mutation.
func (m *UserAttributeDefinitionMutation) EdgeCleared(name string) bool {
switch name {
case userattributedefinition.EdgeValues:
return m.clearedvalues
}
return false
}
// ClearEdge clears the value of the edge with the given name. It returns an error
// if that edge is not defined in the schema.
func (m *UserAttributeDefinitionMutation) ClearEdge(name string) error {
switch name {
}
return fmt.Errorf("unknown UserAttributeDefinition unique edge %s", name)
}
// ResetEdge resets all changes to the edge with the given name in this mutation.
// It returns an error if the edge is not defined in the schema.
func (m *UserAttributeDefinitionMutation) ResetEdge(name string) error {
switch name {
case userattributedefinition.EdgeValues:
m.ResetValues()
return nil
}
return fmt.Errorf("unknown UserAttributeDefinition edge %s", name)
}
// UserAttributeValueMutation represents an operation that mutates the UserAttributeValue nodes in the graph.
type UserAttributeValueMutation struct {
config
op Op
typ string
id *int64
created_at *time.Time
updated_at *time.Time
value *string
clearedFields map[string]struct{}
user *int64
cleareduser bool
definition *int64
cleareddefinition bool
done bool
oldValue func(context.Context) (*UserAttributeValue, error)
predicates []predicate.UserAttributeValue
}
var _ ent.Mutation = (*UserAttributeValueMutation)(nil)
// userattributevalueOption allows management of the mutation configuration using functional options.
type userattributevalueOption func(*UserAttributeValueMutation)
// newUserAttributeValueMutation creates new mutation for the UserAttributeValue entity.
func newUserAttributeValueMutation(c config, op Op, opts ...userattributevalueOption) *UserAttributeValueMutation {
m := &UserAttributeValueMutation{
config: c,
op: op,
typ: TypeUserAttributeValue,
clearedFields: make(map[string]struct{}),
}
for _, opt := range opts {
opt(m)
}
return m
}
// withUserAttributeValueID sets the ID field of the mutation.
func withUserAttributeValueID(id int64) userattributevalueOption {
return func(m *UserAttributeValueMutation) {
var (
err error
once sync.Once
value *UserAttributeValue
)
m.oldValue = func(ctx context.Context) (*UserAttributeValue, error) {
once.Do(func() {
if m.done {
err = errors.New("querying old values post mutation is not allowed")
} else {
value, err = m.Client().UserAttributeValue.Get(ctx, id)
}
})
return value, err
}
m.id = &id
}
}
// withUserAttributeValue sets the old UserAttributeValue of the mutation.
func withUserAttributeValue(node *UserAttributeValue) userattributevalueOption {
return func(m *UserAttributeValueMutation) {
m.oldValue = func(context.Context) (*UserAttributeValue, error) {
return node, nil
}
m.id = &node.ID
}
}
// Client returns a new `ent.Client` from the mutation. If the mutation was
// executed in a transaction (ent.Tx), a transactional client is returned.
func (m UserAttributeValueMutation) Client() *Client {
client := &Client{config: m.config}
client.init()
return client
}
// Tx returns an `ent.Tx` for mutations that were executed in transactions;
// it returns an error otherwise.
func (m UserAttributeValueMutation) Tx() (*Tx, error) {
if _, ok := m.driver.(*txDriver); !ok {
return nil, errors.New("ent: mutation is not running in a transaction")
}
tx := &Tx{config: m.config}
tx.init()
return tx, nil
}
// ID returns the ID value in the mutation. Note that the ID is only available
// if it was provided to the builder or after it was returned from the database.
func (m *UserAttributeValueMutation) ID() (id int64, exists bool) {
if m.id == nil {
return
}
return *m.id, true
}
// IDs queries the database and returns the entity ids that match the mutation's predicate.
// That means, if the mutation is applied within a transaction with an isolation level such
// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated
// or updated by the mutation.
func (m *UserAttributeValueMutation) IDs(ctx context.Context) ([]int64, error) {
switch {
case m.op.Is(OpUpdateOne | OpDeleteOne):
id, exists := m.ID()
if exists {
return []int64{id}, nil
}
fallthrough
case m.op.Is(OpUpdate | OpDelete):
return m.Client().UserAttributeValue.Query().Where(m.predicates...).IDs(ctx)
default:
return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op)
}
}
// SetCreatedAt sets the "created_at" field.
func (m *UserAttributeValueMutation) SetCreatedAt(t time.Time) {
m.created_at = &t
}
// CreatedAt returns the value of the "created_at" field in the mutation.
func (m *UserAttributeValueMutation) CreatedAt() (r time.Time, exists bool) {
v := m.created_at
if v == nil {
return
}
return *v, true
}
// OldCreatedAt returns the old "created_at" field's value of the UserAttributeValue entity.
// If the UserAttributeValue object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *UserAttributeValueMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldCreatedAt requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err)
}
return oldValue.CreatedAt, nil
}
// ResetCreatedAt resets all changes to the "created_at" field.
func (m *UserAttributeValueMutation) ResetCreatedAt() {
m.created_at = nil
}
// SetUpdatedAt sets the "updated_at" field.
func (m *UserAttributeValueMutation) SetUpdatedAt(t time.Time) {
m.updated_at = &t
}
// UpdatedAt returns the value of the "updated_at" field in the mutation.
func (m *UserAttributeValueMutation) UpdatedAt() (r time.Time, exists bool) {
v := m.updated_at
if v == nil {
return
}
return *v, true
}
// OldUpdatedAt returns the old "updated_at" field's value of the UserAttributeValue entity.
// If the UserAttributeValue object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *UserAttributeValueMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldUpdatedAt requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err)
}
return oldValue.UpdatedAt, nil
}
// ResetUpdatedAt resets all changes to the "updated_at" field.
func (m *UserAttributeValueMutation) ResetUpdatedAt() {
m.updated_at = nil
}
// SetUserID sets the "user_id" field.
func (m *UserAttributeValueMutation) SetUserID(i int64) {
m.user = &i
}
// UserID returns the value of the "user_id" field in the mutation.
func (m *UserAttributeValueMutation) UserID() (r int64, exists bool) {
v := m.user
if v == nil {
return
}
return *v, true
}
// OldUserID returns the old "user_id" field's value of the UserAttributeValue entity.
// If the UserAttributeValue object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *UserAttributeValueMutation) OldUserID(ctx context.Context) (v int64, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldUserID is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldUserID requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldUserID: %w", err)
}
return oldValue.UserID, nil
}
// ResetUserID resets all changes to the "user_id" field.
func (m *UserAttributeValueMutation) ResetUserID() {
m.user = nil
}
// SetAttributeID sets the "attribute_id" field.
func (m *UserAttributeValueMutation) SetAttributeID(i int64) {
m.definition = &i
}
// AttributeID returns the value of the "attribute_id" field in the mutation.
func (m *UserAttributeValueMutation) AttributeID() (r int64, exists bool) {
v := m.definition
if v == nil {
return
}
return *v, true
}
// OldAttributeID returns the old "attribute_id" field's value of the UserAttributeValue entity.
// If the UserAttributeValue object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *UserAttributeValueMutation) OldAttributeID(ctx context.Context) (v int64, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldAttributeID is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldAttributeID requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldAttributeID: %w", err)
}
return oldValue.AttributeID, nil
}
// ResetAttributeID resets all changes to the "attribute_id" field.
func (m *UserAttributeValueMutation) ResetAttributeID() {
m.definition = nil
}
// SetValue sets the "value" field.
func (m *UserAttributeValueMutation) SetValue(s string) {
m.value = &s
}
// Value returns the value of the "value" field in the mutation.
func (m *UserAttributeValueMutation) Value() (r string, exists bool) {
v := m.value
if v == nil {
return
}
return *v, true
}
// OldValue returns the old "value" field's value of the UserAttributeValue entity.
// If the UserAttributeValue object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *UserAttributeValueMutation) OldValue(ctx context.Context) (v string, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldValue is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldValue requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldValue: %w", err)
}
return oldValue.Value, nil
}
// ResetValue resets all changes to the "value" field.
func (m *UserAttributeValueMutation) ResetValue() {
m.value = nil
}
// ClearUser clears the "user" edge to the User entity.
func (m *UserAttributeValueMutation) ClearUser() {
m.cleareduser = true
m.clearedFields[userattributevalue.FieldUserID] = struct{}{}
}
// UserCleared reports if the "user" edge to the User entity was cleared.
func (m *UserAttributeValueMutation) UserCleared() bool {
return m.cleareduser
}
// UserIDs returns the "user" edge IDs in the mutation.
// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use
// UserID instead. It exists only for internal usage by the builders.
func (m *UserAttributeValueMutation) UserIDs() (ids []int64) {
if id := m.user; id != nil {
ids = append(ids, *id)
}
return
}
// ResetUser resets all changes to the "user" edge.
func (m *UserAttributeValueMutation) ResetUser() {
m.user = nil
m.cleareduser = false
}
// SetDefinitionID sets the "definition" edge to the UserAttributeDefinition entity by id.
func (m *UserAttributeValueMutation) SetDefinitionID(id int64) {
m.definition = &id
}
// ClearDefinition clears the "definition" edge to the UserAttributeDefinition entity.
func (m *UserAttributeValueMutation) ClearDefinition() {
m.cleareddefinition = true
m.clearedFields[userattributevalue.FieldAttributeID] = struct{}{}
}
// DefinitionCleared reports if the "definition" edge to the UserAttributeDefinition entity was cleared.
func (m *UserAttributeValueMutation) DefinitionCleared() bool {
return m.cleareddefinition
}
// DefinitionID returns the "definition" edge ID in the mutation.
func (m *UserAttributeValueMutation) DefinitionID() (id int64, exists bool) {
if m.definition != nil {
return *m.definition, true
}
return
}
// DefinitionIDs returns the "definition" edge IDs in the mutation.
// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use
// DefinitionID instead. It exists only for internal usage by the builders.
func (m *UserAttributeValueMutation) DefinitionIDs() (ids []int64) {
if id := m.definition; id != nil {
ids = append(ids, *id)
}
return
}
// ResetDefinition resets all changes to the "definition" edge.
func (m *UserAttributeValueMutation) ResetDefinition() {
m.definition = nil
m.cleareddefinition = false
}
// Where appends a list predicates to the UserAttributeValueMutation builder.
func (m *UserAttributeValueMutation) Where(ps ...predicate.UserAttributeValue) {
m.predicates = append(m.predicates, ps...)
}
// WhereP appends storage-level predicates to the UserAttributeValueMutation builder. Using this method,
// users can use type-assertion to append predicates that do not depend on any generated package.
func (m *UserAttributeValueMutation) WhereP(ps ...func(*sql.Selector)) {
p := make([]predicate.UserAttributeValue, len(ps))
for i := range ps {
p[i] = ps[i]
}
m.Where(p...)
}
// Op returns the operation name.
func (m *UserAttributeValueMutation) Op() Op {
return m.op
}
// SetOp allows setting the mutation operation.
func (m *UserAttributeValueMutation) SetOp(op Op) {
m.op = op
}
// Type returns the node type of this mutation (UserAttributeValue).
func (m *UserAttributeValueMutation) Type() string {
return m.typ
}
// Fields returns all fields that were changed during this mutation. Note that in
// order to get all numeric fields that were incremented/decremented, call
// AddedFields().
func (m *UserAttributeValueMutation) Fields() []string {
fields := make([]string, 0, 5)
if m.created_at != nil {
fields = append(fields, userattributevalue.FieldCreatedAt)
}
if m.updated_at != nil {
fields = append(fields, userattributevalue.FieldUpdatedAt)
}
if m.user != nil {
fields = append(fields, userattributevalue.FieldUserID)
}
if m.definition != nil {
fields = append(fields, userattributevalue.FieldAttributeID)
}
if m.value != nil {
fields = append(fields, userattributevalue.FieldValue)
}
return fields
}
// Field returns the value of a field with the given name. The second boolean
// return value indicates that this field was not set, or was not defined in the
// schema.
func (m *UserAttributeValueMutation) Field(name string) (ent.Value, bool) {
switch name {
case userattributevalue.FieldCreatedAt:
return m.CreatedAt()
case userattributevalue.FieldUpdatedAt:
return m.UpdatedAt()
case userattributevalue.FieldUserID:
return m.UserID()
case userattributevalue.FieldAttributeID:
return m.AttributeID()
case userattributevalue.FieldValue:
return m.Value()
}
return nil, false
}
// OldField returns the old value of the field from the database. An error is
// returned if the mutation operation is not UpdateOne, or the query to the
// database failed.
func (m *UserAttributeValueMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
switch name {
case userattributevalue.FieldCreatedAt:
return m.OldCreatedAt(ctx)
case userattributevalue.FieldUpdatedAt:
return m.OldUpdatedAt(ctx)
case userattributevalue.FieldUserID:
return m.OldUserID(ctx)
case userattributevalue.FieldAttributeID:
return m.OldAttributeID(ctx)
case userattributevalue.FieldValue:
return m.OldValue(ctx)
}
return nil, fmt.Errorf("unknown UserAttributeValue field %s", name)
}
// SetField sets the value of a field with the given name. It returns an error if
// the field is not defined in the schema, or if the type mismatched the field
// type.
func (m *UserAttributeValueMutation) SetField(name string, value ent.Value) error {
switch name {
case userattributevalue.FieldCreatedAt:
v, ok := value.(time.Time)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetCreatedAt(v)
return nil
case userattributevalue.FieldUpdatedAt:
v, ok := value.(time.Time)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetUpdatedAt(v)
return nil
case userattributevalue.FieldUserID:
v, ok := value.(int64)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetUserID(v)
return nil
case userattributevalue.FieldAttributeID:
v, ok := value.(int64)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetAttributeID(v)
return nil
case userattributevalue.FieldValue:
v, ok := value.(string)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetValue(v)
return nil
}
return fmt.Errorf("unknown UserAttributeValue field %s", name)
}
// AddedFields returns all numeric fields that were incremented/decremented during
// this mutation.
func (m *UserAttributeValueMutation) AddedFields() []string {
var fields []string
return fields
}
// AddedField returns the numeric value that was incremented/decremented on a field
// with the given name. The second boolean return value indicates that this field
// was not set, or was not defined in the schema.
func (m *UserAttributeValueMutation) AddedField(name string) (ent.Value, bool) {
switch name {
}
return nil, false
}
// AddField adds the value to the field with the given name. It returns an error if
// the field is not defined in the schema, or if the type mismatched the field
// type.
func (m *UserAttributeValueMutation) AddField(name string, value ent.Value) error {
switch name {
}
return fmt.Errorf("unknown UserAttributeValue numeric field %s", name)
}
// ClearedFields returns all nullable fields that were cleared during this
// mutation.
func (m *UserAttributeValueMutation) ClearedFields() []string {
return nil
}
// FieldCleared returns a boolean indicating if a field with the given name was
// cleared in this mutation.
func (m *UserAttributeValueMutation) FieldCleared(name string) bool {
_, ok := m.clearedFields[name]
return ok
}
// ClearField clears the value of the field with the given name. It returns an
// error if the field is not defined in the schema.
func (m *UserAttributeValueMutation) ClearField(name string) error {
return fmt.Errorf("unknown UserAttributeValue nullable field %s", name)
}
// ResetField resets all changes in the mutation for the field with the given name.
// It returns an error if the field is not defined in the schema.
func (m *UserAttributeValueMutation) ResetField(name string) error {
switch name {
case userattributevalue.FieldCreatedAt:
m.ResetCreatedAt()
return nil
case userattributevalue.FieldUpdatedAt:
m.ResetUpdatedAt()
return nil
case userattributevalue.FieldUserID:
m.ResetUserID()
return nil
case userattributevalue.FieldAttributeID:
m.ResetAttributeID()
return nil
case userattributevalue.FieldValue:
m.ResetValue()
return nil
}
return fmt.Errorf("unknown UserAttributeValue field %s", name)
}
// AddedEdges returns all edge names that were set/added in this mutation.
func (m *UserAttributeValueMutation) AddedEdges() []string {
edges := make([]string, 0, 2)
if m.user != nil {
edges = append(edges, userattributevalue.EdgeUser)
}
if m.definition != nil {
edges = append(edges, userattributevalue.EdgeDefinition)
}
return edges
}
// AddedIDs returns all IDs (to other nodes) that were added for the given edge
// name in this mutation.
func (m *UserAttributeValueMutation) AddedIDs(name string) []ent.Value {
switch name {
case userattributevalue.EdgeUser:
if id := m.user; id != nil {
return []ent.Value{*id}
}
case userattributevalue.EdgeDefinition:
if id := m.definition; id != nil {
return []ent.Value{*id}
}
}
return nil
}
// RemovedEdges returns all edge names that were removed in this mutation.
func (m *UserAttributeValueMutation) RemovedEdges() []string {
edges := make([]string, 0, 2)
return edges
}
// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with
// the given name in this mutation.
func (m *UserAttributeValueMutation) RemovedIDs(name string) []ent.Value {
return nil
}
// ClearedEdges returns all edge names that were cleared in this mutation.
func (m *UserAttributeValueMutation) ClearedEdges() []string {
edges := make([]string, 0, 2)
if m.cleareduser {
edges = append(edges, userattributevalue.EdgeUser)
}
if m.cleareddefinition {
edges = append(edges, userattributevalue.EdgeDefinition)
}
return edges
}
// EdgeCleared returns a boolean which indicates if the edge with the given name
// was cleared in this mutation.
func (m *UserAttributeValueMutation) EdgeCleared(name string) bool {
switch name {
case userattributevalue.EdgeUser:
return m.cleareduser
case userattributevalue.EdgeDefinition:
return m.cleareddefinition
}
return false
}
// ClearEdge clears the value of the edge with the given name. It returns an error
// if that edge is not defined in the schema.
func (m *UserAttributeValueMutation) ClearEdge(name string) error {
switch name {
case userattributevalue.EdgeUser:
m.ClearUser()
return nil
case userattributevalue.EdgeDefinition:
m.ClearDefinition()
return nil
}
return fmt.Errorf("unknown UserAttributeValue unique edge %s", name)
}
// ResetEdge resets all changes to the edge with the given name in this mutation.
// It returns an error if the edge is not defined in the schema.
func (m *UserAttributeValueMutation) ResetEdge(name string) error {
switch name {
case userattributevalue.EdgeUser:
m.ResetUser()
return nil
case userattributevalue.EdgeDefinition:
m.ResetDefinition()
return nil
}
return fmt.Errorf("unknown UserAttributeValue edge %s", name)
}
// UserSubscriptionMutation represents an operation that mutates the UserSubscription nodes in the graph. // UserSubscriptionMutation represents an operation that mutates the UserSubscription nodes in the graph.
type UserSubscriptionMutation struct { type UserSubscriptionMutation struct {
config config
......
...@@ -36,5 +36,11 @@ type User func(*sql.Selector) ...@@ -36,5 +36,11 @@ type User func(*sql.Selector)
// UserAllowedGroup is the predicate function for userallowedgroup builders. // UserAllowedGroup is the predicate function for userallowedgroup builders.
type UserAllowedGroup func(*sql.Selector) type UserAllowedGroup func(*sql.Selector)
// UserAttributeDefinition is the predicate function for userattributedefinition builders.
type UserAttributeDefinition func(*sql.Selector)
// UserAttributeValue is the predicate function for userattributevalue builders.
type UserAttributeValue func(*sql.Selector)
// UserSubscription is the predicate function for usersubscription builders. // UserSubscription is the predicate function for usersubscription builders.
type UserSubscription func(*sql.Selector) type UserSubscription func(*sql.Selector)
...@@ -16,6 +16,8 @@ import ( ...@@ -16,6 +16,8 @@ import (
"github.com/Wei-Shaw/sub2api/ent/usagelog" "github.com/Wei-Shaw/sub2api/ent/usagelog"
"github.com/Wei-Shaw/sub2api/ent/user" "github.com/Wei-Shaw/sub2api/ent/user"
"github.com/Wei-Shaw/sub2api/ent/userallowedgroup" "github.com/Wei-Shaw/sub2api/ent/userallowedgroup"
"github.com/Wei-Shaw/sub2api/ent/userattributedefinition"
"github.com/Wei-Shaw/sub2api/ent/userattributevalue"
"github.com/Wei-Shaw/sub2api/ent/usersubscription" "github.com/Wei-Shaw/sub2api/ent/usersubscription"
) )
...@@ -604,14 +606,8 @@ func init() { ...@@ -604,14 +606,8 @@ func init() {
user.DefaultUsername = userDescUsername.Default.(string) user.DefaultUsername = userDescUsername.Default.(string)
// user.UsernameValidator is a validator for the "username" field. It is called by the builders before save. // 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) 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 is the schema descriptor for notes field.
userDescNotes := userFields[8].Descriptor() userDescNotes := userFields[7].Descriptor()
// user.DefaultNotes holds the default value on creation for the notes field. // user.DefaultNotes holds the default value on creation for the notes field.
user.DefaultNotes = userDescNotes.Default.(string) user.DefaultNotes = userDescNotes.Default.(string)
userallowedgroupFields := schema.UserAllowedGroup{}.Fields() userallowedgroupFields := schema.UserAllowedGroup{}.Fields()
...@@ -620,6 +616,128 @@ func init() { ...@@ -620,6 +616,128 @@ func init() {
userallowedgroupDescCreatedAt := userallowedgroupFields[2].Descriptor() userallowedgroupDescCreatedAt := userallowedgroupFields[2].Descriptor()
// userallowedgroup.DefaultCreatedAt holds the default value on creation for the created_at field. // userallowedgroup.DefaultCreatedAt holds the default value on creation for the created_at field.
userallowedgroup.DefaultCreatedAt = userallowedgroupDescCreatedAt.Default.(func() time.Time) userallowedgroup.DefaultCreatedAt = userallowedgroupDescCreatedAt.Default.(func() time.Time)
userattributedefinitionMixin := schema.UserAttributeDefinition{}.Mixin()
userattributedefinitionMixinHooks1 := userattributedefinitionMixin[1].Hooks()
userattributedefinition.Hooks[0] = userattributedefinitionMixinHooks1[0]
userattributedefinitionMixinInters1 := userattributedefinitionMixin[1].Interceptors()
userattributedefinition.Interceptors[0] = userattributedefinitionMixinInters1[0]
userattributedefinitionMixinFields0 := userattributedefinitionMixin[0].Fields()
_ = userattributedefinitionMixinFields0
userattributedefinitionFields := schema.UserAttributeDefinition{}.Fields()
_ = userattributedefinitionFields
// userattributedefinitionDescCreatedAt is the schema descriptor for created_at field.
userattributedefinitionDescCreatedAt := userattributedefinitionMixinFields0[0].Descriptor()
// userattributedefinition.DefaultCreatedAt holds the default value on creation for the created_at field.
userattributedefinition.DefaultCreatedAt = userattributedefinitionDescCreatedAt.Default.(func() time.Time)
// userattributedefinitionDescUpdatedAt is the schema descriptor for updated_at field.
userattributedefinitionDescUpdatedAt := userattributedefinitionMixinFields0[1].Descriptor()
// userattributedefinition.DefaultUpdatedAt holds the default value on creation for the updated_at field.
userattributedefinition.DefaultUpdatedAt = userattributedefinitionDescUpdatedAt.Default.(func() time.Time)
// userattributedefinition.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
userattributedefinition.UpdateDefaultUpdatedAt = userattributedefinitionDescUpdatedAt.UpdateDefault.(func() time.Time)
// userattributedefinitionDescKey is the schema descriptor for key field.
userattributedefinitionDescKey := userattributedefinitionFields[0].Descriptor()
// userattributedefinition.KeyValidator is a validator for the "key" field. It is called by the builders before save.
userattributedefinition.KeyValidator = func() func(string) error {
validators := userattributedefinitionDescKey.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
}
}()
// userattributedefinitionDescName is the schema descriptor for name field.
userattributedefinitionDescName := userattributedefinitionFields[1].Descriptor()
// userattributedefinition.NameValidator is a validator for the "name" field. It is called by the builders before save.
userattributedefinition.NameValidator = func() func(string) error {
validators := userattributedefinitionDescName.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
}
}()
// userattributedefinitionDescDescription is the schema descriptor for description field.
userattributedefinitionDescDescription := userattributedefinitionFields[2].Descriptor()
// userattributedefinition.DefaultDescription holds the default value on creation for the description field.
userattributedefinition.DefaultDescription = userattributedefinitionDescDescription.Default.(string)
// userattributedefinitionDescType is the schema descriptor for type field.
userattributedefinitionDescType := userattributedefinitionFields[3].Descriptor()
// userattributedefinition.TypeValidator is a validator for the "type" field. It is called by the builders before save.
userattributedefinition.TypeValidator = func() func(string) error {
validators := userattributedefinitionDescType.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
}
}()
// userattributedefinitionDescOptions is the schema descriptor for options field.
userattributedefinitionDescOptions := userattributedefinitionFields[4].Descriptor()
// userattributedefinition.DefaultOptions holds the default value on creation for the options field.
userattributedefinition.DefaultOptions = userattributedefinitionDescOptions.Default.([]map[string]interface{})
// userattributedefinitionDescRequired is the schema descriptor for required field.
userattributedefinitionDescRequired := userattributedefinitionFields[5].Descriptor()
// userattributedefinition.DefaultRequired holds the default value on creation for the required field.
userattributedefinition.DefaultRequired = userattributedefinitionDescRequired.Default.(bool)
// userattributedefinitionDescValidation is the schema descriptor for validation field.
userattributedefinitionDescValidation := userattributedefinitionFields[6].Descriptor()
// userattributedefinition.DefaultValidation holds the default value on creation for the validation field.
userattributedefinition.DefaultValidation = userattributedefinitionDescValidation.Default.(map[string]interface{})
// userattributedefinitionDescPlaceholder is the schema descriptor for placeholder field.
userattributedefinitionDescPlaceholder := userattributedefinitionFields[7].Descriptor()
// userattributedefinition.DefaultPlaceholder holds the default value on creation for the placeholder field.
userattributedefinition.DefaultPlaceholder = userattributedefinitionDescPlaceholder.Default.(string)
// userattributedefinition.PlaceholderValidator is a validator for the "placeholder" field. It is called by the builders before save.
userattributedefinition.PlaceholderValidator = userattributedefinitionDescPlaceholder.Validators[0].(func(string) error)
// userattributedefinitionDescDisplayOrder is the schema descriptor for display_order field.
userattributedefinitionDescDisplayOrder := userattributedefinitionFields[8].Descriptor()
// userattributedefinition.DefaultDisplayOrder holds the default value on creation for the display_order field.
userattributedefinition.DefaultDisplayOrder = userattributedefinitionDescDisplayOrder.Default.(int)
// userattributedefinitionDescEnabled is the schema descriptor for enabled field.
userattributedefinitionDescEnabled := userattributedefinitionFields[9].Descriptor()
// userattributedefinition.DefaultEnabled holds the default value on creation for the enabled field.
userattributedefinition.DefaultEnabled = userattributedefinitionDescEnabled.Default.(bool)
userattributevalueMixin := schema.UserAttributeValue{}.Mixin()
userattributevalueMixinFields0 := userattributevalueMixin[0].Fields()
_ = userattributevalueMixinFields0
userattributevalueFields := schema.UserAttributeValue{}.Fields()
_ = userattributevalueFields
// userattributevalueDescCreatedAt is the schema descriptor for created_at field.
userattributevalueDescCreatedAt := userattributevalueMixinFields0[0].Descriptor()
// userattributevalue.DefaultCreatedAt holds the default value on creation for the created_at field.
userattributevalue.DefaultCreatedAt = userattributevalueDescCreatedAt.Default.(func() time.Time)
// userattributevalueDescUpdatedAt is the schema descriptor for updated_at field.
userattributevalueDescUpdatedAt := userattributevalueMixinFields0[1].Descriptor()
// userattributevalue.DefaultUpdatedAt holds the default value on creation for the updated_at field.
userattributevalue.DefaultUpdatedAt = userattributevalueDescUpdatedAt.Default.(func() time.Time)
// userattributevalue.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
userattributevalue.UpdateDefaultUpdatedAt = userattributevalueDescUpdatedAt.UpdateDefault.(func() time.Time)
// userattributevalueDescValue is the schema descriptor for value field.
userattributevalueDescValue := userattributevalueFields[2].Descriptor()
// userattributevalue.DefaultValue holds the default value on creation for the value field.
userattributevalue.DefaultValue = userattributevalueDescValue.Default.(string)
usersubscriptionMixin := schema.UserSubscription{}.Mixin() usersubscriptionMixin := schema.UserSubscription{}.Mixin()
usersubscriptionMixinHooks1 := usersubscriptionMixin[1].Hooks() usersubscriptionMixinHooks1 := usersubscriptionMixin[1].Hooks()
usersubscription.Hooks[0] = usersubscriptionMixinHooks1[0] usersubscription.Hooks[0] = usersubscriptionMixinHooks1[0]
......
...@@ -57,9 +57,7 @@ func (User) Fields() []ent.Field { ...@@ -57,9 +57,7 @@ func (User) Fields() []ent.Field {
field.String("username"). field.String("username").
MaxLen(100). MaxLen(100).
Default(""), Default(""),
field.String("wechat"). // wechat field migrated to user_attribute_values (see migration 019)
MaxLen(100).
Default(""),
field.String("notes"). field.String("notes").
SchemaType(map[string]string{dialect.Postgres: "text"}). SchemaType(map[string]string{dialect.Postgres: "text"}).
Default(""), Default(""),
...@@ -75,6 +73,7 @@ func (User) Edges() []ent.Edge { ...@@ -75,6 +73,7 @@ func (User) Edges() []ent.Edge {
edge.To("allowed_groups", Group.Type). edge.To("allowed_groups", Group.Type).
Through("user_allowed_groups", UserAllowedGroup.Type), Through("user_allowed_groups", UserAllowedGroup.Type),
edge.To("usage_logs", UsageLog.Type), edge.To("usage_logs", UsageLog.Type),
edge.To("attribute_values", UserAttributeValue.Type),
} }
} }
......
package schema
import (
"github.com/Wei-Shaw/sub2api/ent/schema/mixins"
"entgo.io/ent"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/schema"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/index"
)
// UserAttributeDefinition holds the schema definition for custom user attributes.
//
// This entity defines the metadata for user attributes, such as:
// - Attribute key (unique identifier like "company_name")
// - Display name shown in forms
// - Field type (text, number, select, etc.)
// - Validation rules
// - Whether the field is required or enabled
type UserAttributeDefinition struct {
ent.Schema
}
func (UserAttributeDefinition) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Annotation{Table: "user_attribute_definitions"},
}
}
func (UserAttributeDefinition) Mixin() []ent.Mixin {
return []ent.Mixin{
mixins.TimeMixin{},
mixins.SoftDeleteMixin{},
}
}
func (UserAttributeDefinition) Fields() []ent.Field {
return []ent.Field{
// key: Unique identifier for the attribute (e.g., "company_name")
// Used for programmatic reference
field.String("key").
MaxLen(100).
NotEmpty(),
// name: Display name shown in forms (e.g., "Company Name")
field.String("name").
MaxLen(255).
NotEmpty(),
// description: Optional description/help text for the attribute
field.String("description").
SchemaType(map[string]string{dialect.Postgres: "text"}).
Default(""),
// type: Attribute type - text, textarea, number, email, url, date, select, multi_select
field.String("type").
MaxLen(20).
NotEmpty(),
// options: Select options for select/multi_select types (stored as JSONB)
// Format: [{"value": "xxx", "label": "XXX"}, ...]
field.JSON("options", []map[string]any{}).
Default([]map[string]any{}).
SchemaType(map[string]string{dialect.Postgres: "jsonb"}),
// required: Whether this attribute is required when editing a user
field.Bool("required").
Default(false),
// validation: Validation rules for the attribute value (stored as JSONB)
// Format: {"min_length": 1, "max_length": 100, "min": 0, "max": 100, "pattern": "^[a-z]+$", "message": "..."}
field.JSON("validation", map[string]any{}).
Default(map[string]any{}).
SchemaType(map[string]string{dialect.Postgres: "jsonb"}),
// placeholder: Placeholder text shown in input fields
field.String("placeholder").
MaxLen(255).
Default(""),
// display_order: Order in which attributes are displayed (lower = first)
field.Int("display_order").
Default(0),
// enabled: Whether this attribute is active and shown in forms
field.Bool("enabled").
Default(true),
}
}
func (UserAttributeDefinition) Edges() []ent.Edge {
return []ent.Edge{
// values: All user values for this attribute definition
edge.To("values", UserAttributeValue.Type),
}
}
func (UserAttributeDefinition) Indexes() []ent.Index {
return []ent.Index{
// Partial unique index on key (WHERE deleted_at IS NULL) via migration
index.Fields("key"),
index.Fields("enabled"),
index.Fields("display_order"),
index.Fields("deleted_at"),
}
}
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/edge"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/index"
)
// UserAttributeValue holds a user's value for a specific attribute.
//
// This entity stores the actual values that users have for each attribute definition.
// Values are stored as strings and converted to the appropriate type by the application.
type UserAttributeValue struct {
ent.Schema
}
func (UserAttributeValue) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Annotation{Table: "user_attribute_values"},
}
}
func (UserAttributeValue) Mixin() []ent.Mixin {
return []ent.Mixin{
// Only use TimeMixin, no soft delete - values are hard deleted
mixins.TimeMixin{},
}
}
func (UserAttributeValue) Fields() []ent.Field {
return []ent.Field{
// user_id: References the user this value belongs to
field.Int64("user_id"),
// attribute_id: References the attribute definition
field.Int64("attribute_id"),
// value: The actual value stored as a string
// For multi_select, this is a JSON array string
field.Text("value").
Default(""),
}
}
func (UserAttributeValue) Edges() []ent.Edge {
return []ent.Edge{
// user: The user who owns this attribute value
edge.From("user", User.Type).
Ref("attribute_values").
Field("user_id").
Required().
Unique(),
// definition: The attribute definition this value is for
edge.From("definition", UserAttributeDefinition.Type).
Ref("values").
Field("attribute_id").
Required().
Unique(),
}
}
func (UserAttributeValue) Indexes() []ent.Index {
return []ent.Index{
// Unique index on (user_id, attribute_id)
index.Fields("user_id", "attribute_id").Unique(),
index.Fields("attribute_id"),
}
}
...@@ -34,6 +34,10 @@ type Tx struct { ...@@ -34,6 +34,10 @@ type Tx struct {
User *UserClient User *UserClient
// UserAllowedGroup is the client for interacting with the UserAllowedGroup builders. // UserAllowedGroup is the client for interacting with the UserAllowedGroup builders.
UserAllowedGroup *UserAllowedGroupClient UserAllowedGroup *UserAllowedGroupClient
// UserAttributeDefinition is the client for interacting with the UserAttributeDefinition builders.
UserAttributeDefinition *UserAttributeDefinitionClient
// UserAttributeValue is the client for interacting with the UserAttributeValue builders.
UserAttributeValue *UserAttributeValueClient
// UserSubscription is the client for interacting with the UserSubscription builders. // UserSubscription is the client for interacting with the UserSubscription builders.
UserSubscription *UserSubscriptionClient UserSubscription *UserSubscriptionClient
...@@ -177,6 +181,8 @@ func (tx *Tx) init() { ...@@ -177,6 +181,8 @@ func (tx *Tx) init() {
tx.UsageLog = NewUsageLogClient(tx.config) tx.UsageLog = NewUsageLogClient(tx.config)
tx.User = NewUserClient(tx.config) tx.User = NewUserClient(tx.config)
tx.UserAllowedGroup = NewUserAllowedGroupClient(tx.config) tx.UserAllowedGroup = NewUserAllowedGroupClient(tx.config)
tx.UserAttributeDefinition = NewUserAttributeDefinitionClient(tx.config)
tx.UserAttributeValue = NewUserAttributeValueClient(tx.config)
tx.UserSubscription = NewUserSubscriptionClient(tx.config) tx.UserSubscription = NewUserSubscriptionClient(tx.config)
} }
......
...@@ -37,8 +37,6 @@ type User struct { ...@@ -37,8 +37,6 @@ type User struct {
Status string `json:"status,omitempty"` Status string `json:"status,omitempty"`
// Username holds the value of the "username" field. // Username holds the value of the "username" field.
Username string `json:"username,omitempty"` 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 holds the value of the "notes" field.
Notes string `json:"notes,omitempty"` Notes string `json:"notes,omitempty"`
// Edges holds the relations/edges for other nodes in the graph. // Edges holds the relations/edges for other nodes in the graph.
...@@ -61,11 +59,13 @@ type UserEdges struct { ...@@ -61,11 +59,13 @@ type UserEdges struct {
AllowedGroups []*Group `json:"allowed_groups,omitempty"` AllowedGroups []*Group `json:"allowed_groups,omitempty"`
// UsageLogs holds the value of the usage_logs edge. // UsageLogs holds the value of the usage_logs edge.
UsageLogs []*UsageLog `json:"usage_logs,omitempty"` UsageLogs []*UsageLog `json:"usage_logs,omitempty"`
// AttributeValues holds the value of the attribute_values edge.
AttributeValues []*UserAttributeValue `json:"attribute_values,omitempty"`
// UserAllowedGroups holds the value of the user_allowed_groups edge. // UserAllowedGroups holds the value of the user_allowed_groups edge.
UserAllowedGroups []*UserAllowedGroup `json:"user_allowed_groups,omitempty"` UserAllowedGroups []*UserAllowedGroup `json:"user_allowed_groups,omitempty"`
// loadedTypes holds the information for reporting if a // loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not. // type was loaded (or requested) in eager-loading or not.
loadedTypes [7]bool loadedTypes [8]bool
} }
// APIKeysOrErr returns the APIKeys value or an error if the edge // APIKeysOrErr returns the APIKeys value or an error if the edge
...@@ -122,10 +122,19 @@ func (e UserEdges) UsageLogsOrErr() ([]*UsageLog, error) { ...@@ -122,10 +122,19 @@ func (e UserEdges) UsageLogsOrErr() ([]*UsageLog, error) {
return nil, &NotLoadedError{edge: "usage_logs"} return nil, &NotLoadedError{edge: "usage_logs"}
} }
// AttributeValuesOrErr returns the AttributeValues value or an error if the edge
// was not loaded in eager-loading.
func (e UserEdges) AttributeValuesOrErr() ([]*UserAttributeValue, error) {
if e.loadedTypes[6] {
return e.AttributeValues, nil
}
return nil, &NotLoadedError{edge: "attribute_values"}
}
// UserAllowedGroupsOrErr returns the UserAllowedGroups value or an error if the edge // UserAllowedGroupsOrErr returns the UserAllowedGroups value or an error if the edge
// was not loaded in eager-loading. // was not loaded in eager-loading.
func (e UserEdges) UserAllowedGroupsOrErr() ([]*UserAllowedGroup, error) { func (e UserEdges) UserAllowedGroupsOrErr() ([]*UserAllowedGroup, error) {
if e.loadedTypes[6] { if e.loadedTypes[7] {
return e.UserAllowedGroups, nil return e.UserAllowedGroups, nil
} }
return nil, &NotLoadedError{edge: "user_allowed_groups"} return nil, &NotLoadedError{edge: "user_allowed_groups"}
...@@ -140,7 +149,7 @@ func (*User) scanValues(columns []string) ([]any, error) { ...@@ -140,7 +149,7 @@ func (*User) scanValues(columns []string) ([]any, error) {
values[i] = new(sql.NullFloat64) values[i] = new(sql.NullFloat64)
case user.FieldID, user.FieldConcurrency: case user.FieldID, user.FieldConcurrency:
values[i] = new(sql.NullInt64) values[i] = new(sql.NullInt64)
case user.FieldEmail, user.FieldPasswordHash, user.FieldRole, user.FieldStatus, user.FieldUsername, user.FieldWechat, user.FieldNotes: case user.FieldEmail, user.FieldPasswordHash, user.FieldRole, user.FieldStatus, user.FieldUsername, user.FieldNotes:
values[i] = new(sql.NullString) values[i] = new(sql.NullString)
case user.FieldCreatedAt, user.FieldUpdatedAt, user.FieldDeletedAt: case user.FieldCreatedAt, user.FieldUpdatedAt, user.FieldDeletedAt:
values[i] = new(sql.NullTime) values[i] = new(sql.NullTime)
...@@ -226,12 +235,6 @@ func (_m *User) assignValues(columns []string, values []any) error { ...@@ -226,12 +235,6 @@ func (_m *User) assignValues(columns []string, values []any) error {
} else if value.Valid { } else if value.Valid {
_m.Username = value.String _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: case user.FieldNotes:
if value, ok := values[i].(*sql.NullString); !ok { if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field notes", values[i]) return fmt.Errorf("unexpected type %T for field notes", values[i])
...@@ -281,6 +284,11 @@ func (_m *User) QueryUsageLogs() *UsageLogQuery { ...@@ -281,6 +284,11 @@ func (_m *User) QueryUsageLogs() *UsageLogQuery {
return NewUserClient(_m.config).QueryUsageLogs(_m) return NewUserClient(_m.config).QueryUsageLogs(_m)
} }
// QueryAttributeValues queries the "attribute_values" edge of the User entity.
func (_m *User) QueryAttributeValues() *UserAttributeValueQuery {
return NewUserClient(_m.config).QueryAttributeValues(_m)
}
// QueryUserAllowedGroups queries the "user_allowed_groups" edge of the User entity. // QueryUserAllowedGroups queries the "user_allowed_groups" edge of the User entity.
func (_m *User) QueryUserAllowedGroups() *UserAllowedGroupQuery { func (_m *User) QueryUserAllowedGroups() *UserAllowedGroupQuery {
return NewUserClient(_m.config).QueryUserAllowedGroups(_m) return NewUserClient(_m.config).QueryUserAllowedGroups(_m)
...@@ -341,9 +349,6 @@ func (_m *User) String() string { ...@@ -341,9 +349,6 @@ func (_m *User) String() string {
builder.WriteString("username=") builder.WriteString("username=")
builder.WriteString(_m.Username) builder.WriteString(_m.Username)
builder.WriteString(", ") builder.WriteString(", ")
builder.WriteString("wechat=")
builder.WriteString(_m.Wechat)
builder.WriteString(", ")
builder.WriteString("notes=") builder.WriteString("notes=")
builder.WriteString(_m.Notes) builder.WriteString(_m.Notes)
builder.WriteByte(')') builder.WriteByte(')')
......
...@@ -35,8 +35,6 @@ const ( ...@@ -35,8 +35,6 @@ const (
FieldStatus = "status" FieldStatus = "status"
// FieldUsername holds the string denoting the username field in the database. // FieldUsername holds the string denoting the username field in the database.
FieldUsername = "username" 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 holds the string denoting the notes field in the database.
FieldNotes = "notes" FieldNotes = "notes"
// EdgeAPIKeys holds the string denoting the api_keys edge name in mutations. // EdgeAPIKeys holds the string denoting the api_keys edge name in mutations.
...@@ -51,6 +49,8 @@ const ( ...@@ -51,6 +49,8 @@ const (
EdgeAllowedGroups = "allowed_groups" EdgeAllowedGroups = "allowed_groups"
// EdgeUsageLogs holds the string denoting the usage_logs edge name in mutations. // EdgeUsageLogs holds the string denoting the usage_logs edge name in mutations.
EdgeUsageLogs = "usage_logs" EdgeUsageLogs = "usage_logs"
// EdgeAttributeValues holds the string denoting the attribute_values edge name in mutations.
EdgeAttributeValues = "attribute_values"
// EdgeUserAllowedGroups holds the string denoting the user_allowed_groups edge name in mutations. // EdgeUserAllowedGroups holds the string denoting the user_allowed_groups edge name in mutations.
EdgeUserAllowedGroups = "user_allowed_groups" EdgeUserAllowedGroups = "user_allowed_groups"
// Table holds the table name of the user in the database. // Table holds the table name of the user in the database.
...@@ -95,6 +95,13 @@ const ( ...@@ -95,6 +95,13 @@ const (
UsageLogsInverseTable = "usage_logs" UsageLogsInverseTable = "usage_logs"
// UsageLogsColumn is the table column denoting the usage_logs relation/edge. // UsageLogsColumn is the table column denoting the usage_logs relation/edge.
UsageLogsColumn = "user_id" UsageLogsColumn = "user_id"
// AttributeValuesTable is the table that holds the attribute_values relation/edge.
AttributeValuesTable = "user_attribute_values"
// AttributeValuesInverseTable is the table name for the UserAttributeValue entity.
// It exists in this package in order to avoid circular dependency with the "userattributevalue" package.
AttributeValuesInverseTable = "user_attribute_values"
// AttributeValuesColumn is the table column denoting the attribute_values relation/edge.
AttributeValuesColumn = "user_id"
// UserAllowedGroupsTable is the table that holds the user_allowed_groups relation/edge. // UserAllowedGroupsTable is the table that holds the user_allowed_groups relation/edge.
UserAllowedGroupsTable = "user_allowed_groups" UserAllowedGroupsTable = "user_allowed_groups"
// UserAllowedGroupsInverseTable is the table name for the UserAllowedGroup entity. // UserAllowedGroupsInverseTable is the table name for the UserAllowedGroup entity.
...@@ -117,7 +124,6 @@ var Columns = []string{ ...@@ -117,7 +124,6 @@ var Columns = []string{
FieldConcurrency, FieldConcurrency,
FieldStatus, FieldStatus,
FieldUsername, FieldUsername,
FieldWechat,
FieldNotes, FieldNotes,
} }
...@@ -171,10 +177,6 @@ var ( ...@@ -171,10 +177,6 @@ var (
DefaultUsername string DefaultUsername string
// UsernameValidator is a validator for the "username" field. It is called by the builders before save. // UsernameValidator is a validator for the "username" field. It is called by the builders before save.
UsernameValidator func(string) error 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 holds the default value on creation for the "notes" field.
DefaultNotes string DefaultNotes string
) )
...@@ -237,11 +239,6 @@ func ByUsername(opts ...sql.OrderTermOption) OrderOption { ...@@ -237,11 +239,6 @@ func ByUsername(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldUsername, opts...).ToFunc() 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. // ByNotes orders the results by the notes field.
func ByNotes(opts ...sql.OrderTermOption) OrderOption { func ByNotes(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldNotes, opts...).ToFunc() return sql.OrderByField(FieldNotes, opts...).ToFunc()
...@@ -331,6 +328,20 @@ func ByUsageLogs(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { ...@@ -331,6 +328,20 @@ func ByUsageLogs(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
} }
} }
// ByAttributeValuesCount orders the results by attribute_values count.
func ByAttributeValuesCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newAttributeValuesStep(), opts...)
}
}
// ByAttributeValues orders the results by attribute_values terms.
func ByAttributeValues(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newAttributeValuesStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
// ByUserAllowedGroupsCount orders the results by user_allowed_groups count. // ByUserAllowedGroupsCount orders the results by user_allowed_groups count.
func ByUserAllowedGroupsCount(opts ...sql.OrderTermOption) OrderOption { func ByUserAllowedGroupsCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) { return func(s *sql.Selector) {
...@@ -386,6 +397,13 @@ func newUsageLogsStep() *sqlgraph.Step { ...@@ -386,6 +397,13 @@ func newUsageLogsStep() *sqlgraph.Step {
sqlgraph.Edge(sqlgraph.O2M, false, UsageLogsTable, UsageLogsColumn), sqlgraph.Edge(sqlgraph.O2M, false, UsageLogsTable, UsageLogsColumn),
) )
} }
func newAttributeValuesStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(AttributeValuesInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, AttributeValuesTable, AttributeValuesColumn),
)
}
func newUserAllowedGroupsStep() *sqlgraph.Step { func newUserAllowedGroupsStep() *sqlgraph.Step {
return sqlgraph.NewStep( return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID), sqlgraph.From(Table, FieldID),
......
...@@ -105,11 +105,6 @@ func Username(v string) predicate.User { ...@@ -105,11 +105,6 @@ func Username(v string) predicate.User {
return predicate.User(sql.FieldEQ(FieldUsername, v)) 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. // Notes applies equality check predicate on the "notes" field. It's identical to NotesEQ.
func Notes(v string) predicate.User { func Notes(v string) predicate.User {
return predicate.User(sql.FieldEQ(FieldNotes, v)) return predicate.User(sql.FieldEQ(FieldNotes, v))
...@@ -650,71 +645,6 @@ func UsernameContainsFold(v string) predicate.User { ...@@ -650,71 +645,6 @@ func UsernameContainsFold(v string) predicate.User {
return predicate.User(sql.FieldContainsFold(FieldUsername, v)) 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. // NotesEQ applies the EQ predicate on the "notes" field.
func NotesEQ(v string) predicate.User { func NotesEQ(v string) predicate.User {
return predicate.User(sql.FieldEQ(FieldNotes, v)) return predicate.User(sql.FieldEQ(FieldNotes, v))
...@@ -918,6 +848,29 @@ func HasUsageLogsWith(preds ...predicate.UsageLog) predicate.User { ...@@ -918,6 +848,29 @@ func HasUsageLogsWith(preds ...predicate.UsageLog) predicate.User {
}) })
} }
// HasAttributeValues applies the HasEdge predicate on the "attribute_values" edge.
func HasAttributeValues() predicate.User {
return predicate.User(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, AttributeValuesTable, AttributeValuesColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasAttributeValuesWith applies the HasEdge predicate on the "attribute_values" edge with a given conditions (other predicates).
func HasAttributeValuesWith(preds ...predicate.UserAttributeValue) predicate.User {
return predicate.User(func(s *sql.Selector) {
step := newAttributeValuesStep()
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. // HasUserAllowedGroups applies the HasEdge predicate on the "user_allowed_groups" edge.
func HasUserAllowedGroups() predicate.User { func HasUserAllowedGroups() predicate.User {
return predicate.User(func(s *sql.Selector) { return predicate.User(func(s *sql.Selector) {
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment