diff --git a/backend/Makefile b/backend/Makefile
new file mode 100644
index 0000000..1d381f8
--- /dev/null
+++ b/backend/Makefile
@@ -0,0 +1,35 @@
+PLATFORM=linux/amd64
+TAG=main
+OUTPUT=type=docker,dest=/tmp/monkeycode_server.tar
+GOCACHE=$HOME/.cache/go-build
+GOMODCACHE=$HOME/go/pkg/mod
+REGISTRY=monkeycode.chaitin.cn/monkeycode
+
+# make build PLATFORM= TAG= OUTPUT= GOCACHE=
+image:
+ docker buildx build \
+ -f build/Dockerfile \
+ --build-arg GOCACHE=${GOCACHE} \
+ --build-arg GOMODCACHE=${GOMODCACHE} \
+ --build-arg REPO_COMMIT=$(shell git rev-parse HEAD) \
+ --platform ${PLATFORM} \
+ --tag ${REGISTRY}/backend:${TAG} \
+ --output ${OUTPUT} \
+ .
+
+image-nginx:
+ docker buildx build \
+ -f build/Dockerfile.nginx \
+ --platform ${PLATFORM} \
+ --tag ${REGISTRY}/nginx:${TAG} \
+ --output ${OUTPUT} \
+ .
+
+wire:
+ wire cmd/server/wire.go cmd/server/main.go
+
+swag:
+ swag fmt -d internal && swag init --pd -g cmd/server/main.go -ot "json"
+
+migrate_sql:
+ migrate create -ext sql -dir migration -seq ${SEQ}
\ No newline at end of file
diff --git a/backend/README.md b/backend/README.md
new file mode 100644
index 0000000..bfcc0ae
--- /dev/null
+++ b/backend/README.md
@@ -0,0 +1 @@
+## Monkeycode Server
diff --git a/backend/build/Dockerfile b/backend/build/Dockerfile
new file mode 100644
index 0000000..ac9f8a8
--- /dev/null
+++ b/backend/build/Dockerfile
@@ -0,0 +1,25 @@
+FROM --platform=$BUILDPLATFORM golang:1.23-alpine AS builder
+
+WORKDIR /src
+ENV CGO_ENABLED=0
+
+COPY go.* .
+ARG GOMODCACHE
+RUN --mount=type=cache,target=${GOMODCACHE} \
+ go mod download
+
+ARG TARGETOS TARGETARCH GOCACHE
+RUN --mount=type=bind,target=. \
+--mount=type=cache,target=${GOMODCACHE} \
+--mount=type=cache,target=${GOCACHE} \
+GOOS=$TARGETOS GOARCH=$TARGETARCH go build -o /out/main cmd/server/main.go cmd/server/wire_gen.go
+
+FROM alpine:3.21 as binary
+
+WORKDIR /app
+
+ADD migration ./migration
+
+COPY --from=builder /out/main /app/main
+
+CMD [ "./main" ]
\ No newline at end of file
diff --git a/backend/build/Dockerfile.nginx b/backend/build/Dockerfile.nginx
new file mode 100644
index 0000000..23ea460
--- /dev/null
+++ b/backend/build/Dockerfile.nginx
@@ -0,0 +1,7 @@
+FROM nginx:1.27.5-alpine3.21
+
+COPY ./build/nginx.conf /etc/nginx/conf.d/default.conf
+
+EXPOSE 80
+
+CMD ["nginx", "-g", "daemon off;"]
\ No newline at end of file
diff --git a/backend/build/nginx.conf b/backend/build/nginx.conf
new file mode 100644
index 0000000..a883e03
--- /dev/null
+++ b/backend/build/nginx.conf
@@ -0,0 +1,29 @@
+upstream backend {
+ server monkeycode-server:8888;
+}
+
+upstream frontend {
+ server monkeycode-frontend:80;
+}
+
+server {
+ listen 80;
+ server_name _;
+
+ proxy_set_header Host $host;
+ proxy_set_header X-Real-IP $remote_addr;
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+ proxy_set_header X-Forwarded-Proto $scheme;
+
+ location / {
+ proxy_pass http://frontend;
+ }
+
+ location /api {
+ proxy_pass http://backend;
+ }
+
+ location /v1 {
+ proxy_pass http://backend;
+ }
+}
\ No newline at end of file
diff --git a/backend/cmd/server/main.go b/backend/cmd/server/main.go
new file mode 100644
index 0000000..630e8b6
--- /dev/null
+++ b/backend/cmd/server/main.go
@@ -0,0 +1,71 @@
+package main
+
+import (
+ "context"
+
+ "github.com/google/wire"
+
+ "github.com/GoYoko/web"
+
+ "github.com/chaitin/MonkeyCode/backend/config"
+ "github.com/chaitin/MonkeyCode/backend/docs"
+ "github.com/chaitin/MonkeyCode/backend/internal"
+ "github.com/chaitin/MonkeyCode/backend/pkg"
+ "github.com/chaitin/MonkeyCode/backend/pkg/service"
+ "github.com/chaitin/MonkeyCode/backend/pkg/store"
+)
+
+// @title MonkeyCode API
+// @version 1.0
+// @description MonkeyCode API
+func main() {
+ s, err := newServer("/app/config")
+ if err != nil {
+ panic(err)
+ }
+
+ s.logger.With("config", s.config).Debug("config")
+
+ if s.config.Debug {
+ s.web.Swagger("MonkeyCode API", "/reference", string(docs.SwaggerJSON), web.WithBasicAuth("mc", "mc88"))
+ }
+
+ s.web.PrintRoutes()
+
+ if err := store.MigrateSQL(s.config, s.logger); err != nil {
+ panic(err)
+ }
+
+ if err := s.userV1.InitAdmin(); err != nil {
+ panic(err)
+ }
+
+ svc := service.NewService(service.WithPprof())
+ svc.Add(s)
+ if err := svc.Run(); err != nil {
+ panic(err)
+ }
+}
+
+// Name implements service.Servicer.
+func (s *Server) Name() string {
+ return "Server"
+}
+
+// Start implements service.Servicer.
+func (s *Server) Start() error {
+ return s.web.Run(s.config.Server.Http.Host)
+}
+
+// Stop implements service.Servicer.
+func (s *Server) Stop() error {
+ return s.web.Echo().Shutdown(context.Background())
+}
+
+//lint:ignore U1000 unused for wire
+var appSet = wire.NewSet(
+ wire.FieldsOf(new(*config.Config), "Logger"),
+ config.Init,
+ pkg.Provider,
+ internal.Provider,
+)
diff --git a/backend/cmd/server/wire.go b/backend/cmd/server/wire.go
new file mode 100644
index 0000000..11381f7
--- /dev/null
+++ b/backend/cmd/server/wire.go
@@ -0,0 +1,42 @@
+//go:build wireinject
+// +build wireinject
+
+package main
+
+import (
+ "log/slog"
+
+ "github.com/google/wire"
+
+ "github.com/GoYoko/web"
+
+ "github.com/chaitin/MonkeyCode/backend/config"
+ "github.com/chaitin/MonkeyCode/backend/db"
+ "github.com/chaitin/MonkeyCode/backend/domain"
+ billingv1 "github.com/chaitin/MonkeyCode/backend/internal/billing/handler/http/v1"
+ dashv1 "github.com/chaitin/MonkeyCode/backend/internal/dashboard/handler/v1"
+ v1 "github.com/chaitin/MonkeyCode/backend/internal/model/handler/http/v1"
+ openaiV1 "github.com/chaitin/MonkeyCode/backend/internal/openai/handler/v1"
+ userV1 "github.com/chaitin/MonkeyCode/backend/internal/user/handler/v1"
+)
+
+type Server struct {
+ config *config.Config
+ web *web.Web
+ ent *db.Client
+ logger *slog.Logger
+ proxy domain.Proxy
+ openaiV1 *openaiV1.V1Handler
+ modelV1 *v1.ModelHandler
+ userV1 *userV1.UserHandler
+ dashboardV1 *dashv1.DashboardHandler
+ billingV1 *billingv1.BillingHandler
+}
+
+func newServer(dir string) (*Server, error) {
+ wire.Build(
+ wire.Struct(new(Server), "*"),
+ appSet,
+ )
+ return &Server{}, nil
+}
diff --git a/backend/cmd/server/wire_gen.go b/backend/cmd/server/wire_gen.go
new file mode 100644
index 0000000..63960bc
--- /dev/null
+++ b/backend/cmd/server/wire_gen.go
@@ -0,0 +1,105 @@
+// Code generated by Wire. DO NOT EDIT.
+
+//go:generate go run -mod=mod github.com/google/wire/cmd/wire
+//go:build !wireinject
+// +build !wireinject
+
+package main
+
+import (
+ "log/slog"
+
+ "github.com/GoYoko/web"
+ "github.com/chaitin/MonkeyCode/backend/config"
+ "github.com/chaitin/MonkeyCode/backend/db"
+ "github.com/chaitin/MonkeyCode/backend/domain"
+ v1_5 "github.com/chaitin/MonkeyCode/backend/internal/billing/handler/http/v1"
+ repo6 "github.com/chaitin/MonkeyCode/backend/internal/billing/repo"
+ usecase5 "github.com/chaitin/MonkeyCode/backend/internal/billing/usecase"
+ v1_4 "github.com/chaitin/MonkeyCode/backend/internal/dashboard/handler/v1"
+ repo5 "github.com/chaitin/MonkeyCode/backend/internal/dashboard/repo"
+ usecase4 "github.com/chaitin/MonkeyCode/backend/internal/dashboard/usecase"
+ "github.com/chaitin/MonkeyCode/backend/internal/middleware"
+ v1_2 "github.com/chaitin/MonkeyCode/backend/internal/model/handler/http/v1"
+ repo3 "github.com/chaitin/MonkeyCode/backend/internal/model/repo"
+ usecase2 "github.com/chaitin/MonkeyCode/backend/internal/model/usecase"
+ v1 "github.com/chaitin/MonkeyCode/backend/internal/openai/handler/v1"
+ repo2 "github.com/chaitin/MonkeyCode/backend/internal/openai/repo"
+ openai "github.com/chaitin/MonkeyCode/backend/internal/openai/usecase"
+ "github.com/chaitin/MonkeyCode/backend/internal/proxy"
+ "github.com/chaitin/MonkeyCode/backend/internal/proxy/repo"
+ "github.com/chaitin/MonkeyCode/backend/internal/proxy/usecase"
+ v1_3 "github.com/chaitin/MonkeyCode/backend/internal/user/handler/v1"
+ repo4 "github.com/chaitin/MonkeyCode/backend/internal/user/repo"
+ usecase3 "github.com/chaitin/MonkeyCode/backend/internal/user/usecase"
+ "github.com/chaitin/MonkeyCode/backend/pkg"
+ "github.com/chaitin/MonkeyCode/backend/pkg/logger"
+ "github.com/chaitin/MonkeyCode/backend/pkg/session"
+ "github.com/chaitin/MonkeyCode/backend/pkg/store"
+)
+
+// Injectors from wire.go:
+
+func newServer(dir string) (*Server, error) {
+ configConfig, err := config.Init(dir)
+ if err != nil {
+ return nil, err
+ }
+ web := pkg.NewWeb(configConfig)
+ loggerConfig := configConfig.Logger
+ slogLogger := logger.NewLogger(loggerConfig)
+ client, err := store.NewEntDB(configConfig, slogLogger)
+ if err != nil {
+ return nil, err
+ }
+ proxyRepo := repo.NewProxyRepo(client)
+ proxyUsecase := usecase.NewProxyUsecase(proxyRepo)
+ domainProxy := proxy.NewLLMProxy(proxyUsecase, configConfig, slogLogger)
+ openAIRepo := repo2.NewOpenAIRepo(client)
+ openAIUsecase := openai.NewOpenAIUsecase(configConfig, openAIRepo, slogLogger)
+ proxyMiddleware := middleware.NewProxyMiddleware(proxyUsecase)
+ v1Handler := v1.NewV1Handler(slogLogger, web, domainProxy, openAIUsecase, proxyMiddleware)
+ modelRepo := repo3.NewModelRepo(client)
+ modelUsecase := usecase2.NewModelUsecase(modelRepo)
+ sessionSession := session.NewSession(configConfig)
+ authMiddleware := middleware.NewAuthMiddleware(sessionSession, slogLogger)
+ modelHandler := v1_2.NewModelHandler(web, modelUsecase, authMiddleware, slogLogger)
+ redisClient := store.NewRedisCli(configConfig)
+ userRepo := repo4.NewUserRepo(client)
+ userUsecase := usecase3.NewUserUsecase(configConfig, redisClient, userRepo, slogLogger)
+ userHandler := v1_3.NewUserHandler(web, userUsecase, authMiddleware, sessionSession, slogLogger, configConfig)
+ dashboardRepo := repo5.NewDashboardRepo(client)
+ dashboardUsecase := usecase4.NewDashboardUsecase(dashboardRepo)
+ dashboardHandler := v1_4.NewDashboardHandler(web, dashboardUsecase, authMiddleware)
+ billingRepo := repo6.NewBillingRepo(client)
+ billingUsecase := usecase5.NewBillingUsecase(billingRepo)
+ billingHandler := v1_5.NewBillingHandler(web, billingUsecase, authMiddleware)
+ server := &Server{
+ config: configConfig,
+ web: web,
+ ent: client,
+ logger: slogLogger,
+ proxy: domainProxy,
+ openaiV1: v1Handler,
+ modelV1: modelHandler,
+ userV1: userHandler,
+ dashboardV1: dashboardHandler,
+ billingV1: billingHandler,
+ }
+ return server, nil
+}
+
+// wire.go:
+
+type Server struct {
+ config *config.Config
+ web *web.Web
+ ent *db.Client
+ logger *slog.Logger
+ proxy domain.Proxy
+ openaiV1 *v1.V1Handler
+ modelV1 *v1_2.ModelHandler
+ userV1 *v1_3.UserHandler
+ dashboardV1 *v1_4.DashboardHandler
+ billingV1 *v1_5.BillingHandler
+}
diff --git a/backend/config/config.go b/backend/config/config.go
new file mode 100644
index 0000000..c3a86bf
--- /dev/null
+++ b/backend/config/config.go
@@ -0,0 +1,96 @@
+package config
+
+import (
+ _ "embed"
+
+ "github.com/spf13/viper"
+
+ "github.com/chaitin/MonkeyCode/backend/pkg/cvt"
+ "github.com/chaitin/MonkeyCode/backend/pkg/logger"
+)
+
+//go:embed config.json.tmpl
+var ConfigTmpl []byte
+
+type Config struct {
+ Debug bool `mapstructure:"debug"`
+
+ Logger *logger.Config `mapstructure:"logger"`
+
+ BaseUrl string `mapstructure:"base_url"`
+
+ Server struct {
+ Http struct {
+ Host string `mapstructure:"host"`
+ } `mapstructure:"http"`
+ } `mapstructure:"server"`
+
+ Admin struct {
+ User string `mapstructure:"user"`
+ Password string `mapstructure:"password"`
+ } `mapstructure:"admin"`
+
+ Session struct {
+ ExpireDay int `mapstructure:"expire_day"`
+ } `mapstructure:"session"`
+
+ Database struct {
+ Master string `mapstructure:"master"`
+ Slave string `mapstructure:"slave"`
+ MaxOpenConns int `mapstructure:"max_open_conns"`
+ MaxIdleConns int `mapstructure:"max_idle_conns"`
+ ConnMaxLifetime int `mapstructure:"conn_max_lifetime"`
+ } `mapstructure:"database"`
+
+ Redis struct {
+ Host string `mapstructure:"host"`
+ Port string `mapstructure:"port"`
+ Pass string `mapstructure:"pass"`
+ DB int `mapstructure:"db"`
+ IdleConn int `mapstructure:"idle_conn"`
+ } `mapstructure:"redis"`
+
+ LLMProxy struct {
+ Timeout string `mapstructure:"timeout"`
+ KeepAlive string `mapstructure:"keep_alive"`
+ ClientPoolSize int `mapstructure:"client_pool_size"`
+ RequestLogPath string `mapstructure:"request_log_path"`
+ } `mapstructure:"llm_proxy"`
+
+ VSCode struct {
+ VSIXFile string `mapstructure:"vsix_file"`
+ } `mapstructure:"vscode"`
+}
+
+func Init(dir string) (*Config, error) {
+ viper.SetConfigName("config")
+ viper.SetConfigType("yaml")
+ viper.AddConfigPath(dir)
+ if err := viper.ReadInConfig(); err != nil {
+ return nil, err
+ }
+
+ c := Config{}
+ if err := viper.Unmarshal(&c); err != nil {
+ return nil, err
+ }
+
+ c = defaultValue(c)
+ return &c, nil
+}
+
+func defaultValue(c Config) Config {
+ c.Server.Http.Host = cvt.ZeroWithDefault(c.Server.Http.Host, ":8888")
+ c.Redis.IdleConn = cvt.ZeroWithDefault(c.Redis.IdleConn, 20)
+ c.Database.MaxOpenConns = cvt.ZeroWithDefault(c.Database.MaxOpenConns, 50)
+ c.Database.MaxIdleConns = cvt.ZeroWithDefault(c.Database.MaxIdleConns, 10)
+ c.Database.ConnMaxLifetime = cvt.ZeroWithDefault(c.Database.ConnMaxLifetime, 30)
+ c.Session.ExpireDay = cvt.ZeroWithDefault(c.Session.ExpireDay, 15)
+
+ c.LLMProxy.Timeout = cvt.ZeroWithDefault(c.LLMProxy.Timeout, "30s")
+ c.LLMProxy.KeepAlive = cvt.ZeroWithDefault(c.LLMProxy.KeepAlive, "60s")
+ c.LLMProxy.ClientPoolSize = cvt.ZeroWithDefault(c.LLMProxy.ClientPoolSize, 100)
+ c.LLMProxy.RequestLogPath = cvt.ZeroWithDefault(c.LLMProxy.RequestLogPath, "/app/request/logs")
+
+ return c
+}
diff --git a/backend/config/config.json.tmpl b/backend/config/config.json.tmpl
new file mode 100644
index 0000000..74e6af0
--- /dev/null
+++ b/backend/config/config.json.tmpl
@@ -0,0 +1,52 @@
+{
+ "providerProfiles": {
+ "currentApiConfigName": "default",
+ "apiConfigs": {
+ "default": {
+ "apiProvider": "openai",
+ "apiModelId": "{{ .chatModel }}",
+ "openAiBaseUrl": "{{ .apiBase}}/v1",
+ "openAiApiKey": "{{ .apikey }}",
+ "openAiModelId": "{{ .chatModel }}",
+ "openAiCustomModelInfo": {
+ "maxTokens": 8192,
+ "contextWindow": 32768,
+ "supportsImages": false,
+ "supportsComputerUse": false,
+ "supportsPromptCache": false
+ },
+ "id": "59admorkig4"
+ }
+ },
+ "modeApiConfigs": {
+ "code": "59admorkig4",
+ "architect": "59admorkig4",
+ "ask": "59admorkig4",
+ "debug": "59admorkig4",
+ "deepresearch": "59admorkig4"
+ },
+ "migrations": {
+ "rateLimitSecondsMigrated": true,
+ "diffSettingsMigrated": true
+ }
+ },
+ "ctcodeTabCompletions": {
+ "enabled": true,
+ "apiProvider": "openai",
+ "openAiBaseUrl": "{{ .apiBase}}/v1",
+ "openAiApiKey": "{{ .apikey }}",
+ "openAiModelId": "{{ .codeModel }}"
+ },
+ "globalSettings": {
+ "allowedCommands": [
+ "npm test",
+ "npm install",
+ "tsc",
+ "git log",
+ "git diff",
+ "git show"
+ ],
+ "mode": "code",
+ "customModes": []
+ }
+ }
\ No newline at end of file
diff --git a/backend/config/config.yaml b/backend/config/config.yaml
new file mode 100644
index 0000000..44fa666
--- /dev/null
+++ b/backend/config/config.yaml
@@ -0,0 +1,26 @@
+debug: true
+base_url: http://{{.LOCAL_IP}}:{{.NGINX_PORT}}
+logger:
+ level: info
+server:
+ http:
+ host: 0.0.0.0:8888
+admin:
+ user: {{.ADMIN_USER}}
+ password: {{.ADMIN_PASSWORD}}
+database:
+ master: postgres://{{.POSTGRES_USER}}:{{.POSTGRES_PASSWORD}}@monkeycode-db:5432/{{.POSTGRES_DB}}?sslmode=disable&timezone=Asia/Shanghai
+ slave: postgres://{{.POSTGRES_USER}}:{{.POSTGRES_PASSWORD}}@monkeycode-db:5432/{{.POSTGRES_DB}}?sslmode=disable&timezone=Asia/Shanghai
+redis:
+ host: monkeycode-redis
+ port: "6379"
+ pass: {{.REDIS_PASSWORD}}
+ db: 0
+ idle_conn: 10
+llm_proxy:
+ timeout: 30s
+ keep_alive: 1m
+ client_pool_size: 10
+ request_log_path: /app/request/logs
+vscode:
+ vsix_file: /app/static/monkeycode.vsix
\ No newline at end of file
diff --git a/backend/config/provider.go b/backend/config/provider.go
new file mode 100644
index 0000000..c53ee8a
--- /dev/null
+++ b/backend/config/provider.go
@@ -0,0 +1,9 @@
+package config
+
+import (
+ "github.com/google/wire"
+)
+
+var ProviderSet = wire.NewSet(
+ Init,
+)
diff --git a/backend/consts/admin.go b/backend/consts/admin.go
new file mode 100644
index 0000000..1ee2a02
--- /dev/null
+++ b/backend/consts/admin.go
@@ -0,0 +1,8 @@
+package consts
+
+type AdminStatus string
+
+const (
+ AdminStatusActive AdminStatus = "active"
+ AdminStatusInactive AdminStatus = "inactive"
+)
diff --git a/backend/consts/apikey.go b/backend/consts/apikey.go
new file mode 100644
index 0000000..31ccc05
--- /dev/null
+++ b/backend/consts/apikey.go
@@ -0,0 +1,8 @@
+package consts
+
+type ApiKeyStatus string
+
+const (
+ ApiKeyStatusActive ApiKeyStatus = "active"
+ ApiKeyStatusInactive ApiKeyStatus = "inactive"
+)
diff --git a/backend/consts/model.go b/backend/consts/model.go
new file mode 100644
index 0000000..a2bb46f
--- /dev/null
+++ b/backend/consts/model.go
@@ -0,0 +1,18 @@
+package consts
+
+type ModelStatus string
+
+const (
+ ModelStatusActive ModelStatus = "active"
+ ModelStatusInactive ModelStatus = "inactive"
+)
+
+type ModelType string
+
+const (
+ ModelTypeLLM ModelType = "llm"
+ ModelTypeCoder ModelType = "coder"
+ ModelTypeEmbedding ModelType = "embedding"
+ ModelTypeAudio ModelType = "audio"
+ ModelTypeReranker ModelType = "reranker"
+)
diff --git a/backend/consts/openai.go b/backend/consts/openai.go
new file mode 100644
index 0000000..5320032
--- /dev/null
+++ b/backend/consts/openai.go
@@ -0,0 +1,8 @@
+package consts
+
+type ConfigType string
+
+const (
+ ConfigTypeContinue ConfigType = "continue"
+ ConfigTypeRooCode ConfigType = "roo-code"
+)
diff --git a/backend/consts/tenant.go b/backend/consts/tenant.go
new file mode 100644
index 0000000..02c70d5
--- /dev/null
+++ b/backend/consts/tenant.go
@@ -0,0 +1,8 @@
+package consts
+
+type TenantStatus string
+
+const (
+ TenantStatusActive TenantStatus = "active"
+ TenantStatusInactive TenantStatus = "inactive"
+)
diff --git a/backend/consts/user.go b/backend/consts/user.go
new file mode 100644
index 0000000..33b9618
--- /dev/null
+++ b/backend/consts/user.go
@@ -0,0 +1,13 @@
+package consts
+
+type UserStatus string
+
+const (
+ UserStatusActive UserStatus = "active"
+ UserStatusInactive UserStatus = "inactive"
+ UserStatusLocked UserStatus = "locked"
+)
+
+const (
+ SessionName = "monkeycode_session"
+)
diff --git a/backend/db/admin.go b/backend/db/admin.go
new file mode 100644
index 0000000..8d7eca2
--- /dev/null
+++ b/backend/db/admin.go
@@ -0,0 +1,189 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "fmt"
+ "strings"
+ "time"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect/sql"
+ "github.com/chaitin/MonkeyCode/backend/consts"
+ "github.com/chaitin/MonkeyCode/backend/db/admin"
+ "github.com/google/uuid"
+)
+
+// Admin is the model entity for the Admin schema.
+type Admin struct {
+ config `json:"-"`
+ // ID of the ent.
+ ID uuid.UUID `json:"id,omitempty"`
+ // Username holds the value of the "username" field.
+ Username string `json:"username,omitempty"`
+ // Password holds the value of the "password" field.
+ Password string `json:"password,omitempty"`
+ // Status holds the value of the "status" field.
+ Status consts.AdminStatus `json:"status,omitempty"`
+ // LastActiveAt holds the value of the "last_active_at" field.
+ LastActiveAt time.Time `json:"last_active_at,omitempty"`
+ // CreatedAt holds the value of the "created_at" field.
+ CreatedAt time.Time `json:"created_at,omitempty"`
+ // UpdatedAt holds the value of the "updated_at" field.
+ UpdatedAt time.Time `json:"updated_at,omitempty"`
+ // Edges holds the relations/edges for other nodes in the graph.
+ // The values are being populated by the AdminQuery when eager-loading is set.
+ Edges AdminEdges `json:"edges"`
+ selectValues sql.SelectValues
+}
+
+// AdminEdges holds the relations/edges for other nodes in the graph.
+type AdminEdges struct {
+ // LoginHistories holds the value of the login_histories edge.
+ LoginHistories []*AdminLoginHistory `json:"login_histories,omitempty"`
+ // loadedTypes holds the information for reporting if a
+ // type was loaded (or requested) in eager-loading or not.
+ loadedTypes [1]bool
+}
+
+// LoginHistoriesOrErr returns the LoginHistories value or an error if the edge
+// was not loaded in eager-loading.
+func (e AdminEdges) LoginHistoriesOrErr() ([]*AdminLoginHistory, error) {
+ if e.loadedTypes[0] {
+ return e.LoginHistories, nil
+ }
+ return nil, &NotLoadedError{edge: "login_histories"}
+}
+
+// scanValues returns the types for scanning values from sql.Rows.
+func (*Admin) scanValues(columns []string) ([]any, error) {
+ values := make([]any, len(columns))
+ for i := range columns {
+ switch columns[i] {
+ case admin.FieldUsername, admin.FieldPassword, admin.FieldStatus:
+ values[i] = new(sql.NullString)
+ case admin.FieldLastActiveAt, admin.FieldCreatedAt, admin.FieldUpdatedAt:
+ values[i] = new(sql.NullTime)
+ case admin.FieldID:
+ values[i] = new(uuid.UUID)
+ default:
+ values[i] = new(sql.UnknownType)
+ }
+ }
+ return values, nil
+}
+
+// assignValues assigns the values that were returned from sql.Rows (after scanning)
+// to the Admin fields.
+func (a *Admin) assignValues(columns []string, values []any) error {
+ if m, n := len(values), len(columns); m < n {
+ return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
+ }
+ for i := range columns {
+ switch columns[i] {
+ case admin.FieldID:
+ if value, ok := values[i].(*uuid.UUID); !ok {
+ return fmt.Errorf("unexpected type %T for field id", values[i])
+ } else if value != nil {
+ a.ID = *value
+ }
+ case admin.FieldUsername:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field username", values[i])
+ } else if value.Valid {
+ a.Username = value.String
+ }
+ case admin.FieldPassword:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field password", values[i])
+ } else if value.Valid {
+ a.Password = value.String
+ }
+ case admin.FieldStatus:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field status", values[i])
+ } else if value.Valid {
+ a.Status = consts.AdminStatus(value.String)
+ }
+ case admin.FieldLastActiveAt:
+ if value, ok := values[i].(*sql.NullTime); !ok {
+ return fmt.Errorf("unexpected type %T for field last_active_at", values[i])
+ } else if value.Valid {
+ a.LastActiveAt = value.Time
+ }
+ case admin.FieldCreatedAt:
+ if value, ok := values[i].(*sql.NullTime); !ok {
+ return fmt.Errorf("unexpected type %T for field created_at", values[i])
+ } else if value.Valid {
+ a.CreatedAt = value.Time
+ }
+ case admin.FieldUpdatedAt:
+ if value, ok := values[i].(*sql.NullTime); !ok {
+ return fmt.Errorf("unexpected type %T for field updated_at", values[i])
+ } else if value.Valid {
+ a.UpdatedAt = value.Time
+ }
+ default:
+ a.selectValues.Set(columns[i], values[i])
+ }
+ }
+ return nil
+}
+
+// Value returns the ent.Value that was dynamically selected and assigned to the Admin.
+// This includes values selected through modifiers, order, etc.
+func (a *Admin) Value(name string) (ent.Value, error) {
+ return a.selectValues.Get(name)
+}
+
+// QueryLoginHistories queries the "login_histories" edge of the Admin entity.
+func (a *Admin) QueryLoginHistories() *AdminLoginHistoryQuery {
+ return NewAdminClient(a.config).QueryLoginHistories(a)
+}
+
+// Update returns a builder for updating this Admin.
+// Note that you need to call Admin.Unwrap() before calling this method if this Admin
+// was returned from a transaction, and the transaction was committed or rolled back.
+func (a *Admin) Update() *AdminUpdateOne {
+ return NewAdminClient(a.config).UpdateOne(a)
+}
+
+// Unwrap unwraps the Admin entity that was returned from a transaction after it was closed,
+// so that all future queries will be executed through the driver which created the transaction.
+func (a *Admin) Unwrap() *Admin {
+ _tx, ok := a.config.driver.(*txDriver)
+ if !ok {
+ panic("db: Admin is not a transactional entity")
+ }
+ a.config.driver = _tx.drv
+ return a
+}
+
+// String implements the fmt.Stringer.
+func (a *Admin) String() string {
+ var builder strings.Builder
+ builder.WriteString("Admin(")
+ builder.WriteString(fmt.Sprintf("id=%v, ", a.ID))
+ builder.WriteString("username=")
+ builder.WriteString(a.Username)
+ builder.WriteString(", ")
+ builder.WriteString("password=")
+ builder.WriteString(a.Password)
+ builder.WriteString(", ")
+ builder.WriteString("status=")
+ builder.WriteString(fmt.Sprintf("%v", a.Status))
+ builder.WriteString(", ")
+ builder.WriteString("last_active_at=")
+ builder.WriteString(a.LastActiveAt.Format(time.ANSIC))
+ builder.WriteString(", ")
+ builder.WriteString("created_at=")
+ builder.WriteString(a.CreatedAt.Format(time.ANSIC))
+ builder.WriteString(", ")
+ builder.WriteString("updated_at=")
+ builder.WriteString(a.UpdatedAt.Format(time.ANSIC))
+ builder.WriteByte(')')
+ return builder.String()
+}
+
+// Admins is a parsable slice of Admin.
+type Admins []*Admin
diff --git a/backend/db/admin/admin.go b/backend/db/admin/admin.go
new file mode 100644
index 0000000..823d8d9
--- /dev/null
+++ b/backend/db/admin/admin.go
@@ -0,0 +1,131 @@
+// Code generated by ent, DO NOT EDIT.
+
+package admin
+
+import (
+ "time"
+
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+)
+
+const (
+ // Label holds the string label denoting the admin type in the database.
+ Label = "admin"
+ // FieldID holds the string denoting the id field in the database.
+ FieldID = "id"
+ // FieldUsername holds the string denoting the username field in the database.
+ FieldUsername = "username"
+ // FieldPassword holds the string denoting the password field in the database.
+ FieldPassword = "password"
+ // FieldStatus holds the string denoting the status field in the database.
+ FieldStatus = "status"
+ // FieldLastActiveAt holds the string denoting the last_active_at field in the database.
+ FieldLastActiveAt = "last_active_at"
+ // FieldCreatedAt holds the string denoting the created_at field in the database.
+ FieldCreatedAt = "created_at"
+ // FieldUpdatedAt holds the string denoting the updated_at field in the database.
+ FieldUpdatedAt = "updated_at"
+ // EdgeLoginHistories holds the string denoting the login_histories edge name in mutations.
+ EdgeLoginHistories = "login_histories"
+ // Table holds the table name of the admin in the database.
+ Table = "admins"
+ // LoginHistoriesTable is the table that holds the login_histories relation/edge.
+ LoginHistoriesTable = "admin_login_histories"
+ // LoginHistoriesInverseTable is the table name for the AdminLoginHistory entity.
+ // It exists in this package in order to avoid circular dependency with the "adminloginhistory" package.
+ LoginHistoriesInverseTable = "admin_login_histories"
+ // LoginHistoriesColumn is the table column denoting the login_histories relation/edge.
+ LoginHistoriesColumn = "admin_login_histories"
+)
+
+// Columns holds all SQL columns for admin fields.
+var Columns = []string{
+ FieldID,
+ FieldUsername,
+ FieldPassword,
+ FieldStatus,
+ FieldLastActiveAt,
+ FieldCreatedAt,
+ FieldUpdatedAt,
+}
+
+// ValidColumn reports if the column name is valid (part of the table columns).
+func ValidColumn(column string) bool {
+ for i := range Columns {
+ if column == Columns[i] {
+ return true
+ }
+ }
+ return false
+}
+
+var (
+ // DefaultLastActiveAt holds the default value on creation for the "last_active_at" field.
+ DefaultLastActiveAt func() time.Time
+ // DefaultCreatedAt holds the default value on creation for the "created_at" field.
+ DefaultCreatedAt func() time.Time
+ // DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
+ DefaultUpdatedAt func() time.Time
+ // UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field.
+ UpdateDefaultUpdatedAt func() time.Time
+)
+
+// OrderOption defines the ordering options for the Admin queries.
+type OrderOption func(*sql.Selector)
+
+// ByID orders the results by the id field.
+func ByID(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldID, opts...).ToFunc()
+}
+
+// ByUsername orders the results by the username field.
+func ByUsername(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldUsername, opts...).ToFunc()
+}
+
+// ByPassword orders the results by the password field.
+func ByPassword(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldPassword, opts...).ToFunc()
+}
+
+// ByStatus orders the results by the status field.
+func ByStatus(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldStatus, opts...).ToFunc()
+}
+
+// ByLastActiveAt orders the results by the last_active_at field.
+func ByLastActiveAt(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldLastActiveAt, opts...).ToFunc()
+}
+
+// ByCreatedAt orders the results by the created_at field.
+func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
+}
+
+// ByUpdatedAt orders the results by the updated_at field.
+func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc()
+}
+
+// ByLoginHistoriesCount orders the results by login_histories count.
+func ByLoginHistoriesCount(opts ...sql.OrderTermOption) OrderOption {
+ return func(s *sql.Selector) {
+ sqlgraph.OrderByNeighborsCount(s, newLoginHistoriesStep(), opts...)
+ }
+}
+
+// ByLoginHistories orders the results by login_histories terms.
+func ByLoginHistories(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
+ return func(s *sql.Selector) {
+ sqlgraph.OrderByNeighborTerms(s, newLoginHistoriesStep(), append([]sql.OrderTerm{term}, terms...)...)
+ }
+}
+func newLoginHistoriesStep() *sqlgraph.Step {
+ return sqlgraph.NewStep(
+ sqlgraph.From(Table, FieldID),
+ sqlgraph.To(LoginHistoriesInverseTable, FieldID),
+ sqlgraph.Edge(sqlgraph.O2M, false, LoginHistoriesTable, LoginHistoriesColumn),
+ )
+}
diff --git a/backend/db/admin/where.go b/backend/db/admin/where.go
new file mode 100644
index 0000000..cfc3caf
--- /dev/null
+++ b/backend/db/admin/where.go
@@ -0,0 +1,461 @@
+// Code generated by ent, DO NOT EDIT.
+
+package admin
+
+import (
+ "time"
+
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "github.com/chaitin/MonkeyCode/backend/consts"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+ "github.com/google/uuid"
+)
+
+// ID filters vertices based on their ID field.
+func ID(id uuid.UUID) predicate.Admin {
+ return predicate.Admin(sql.FieldEQ(FieldID, id))
+}
+
+// IDEQ applies the EQ predicate on the ID field.
+func IDEQ(id uuid.UUID) predicate.Admin {
+ return predicate.Admin(sql.FieldEQ(FieldID, id))
+}
+
+// IDNEQ applies the NEQ predicate on the ID field.
+func IDNEQ(id uuid.UUID) predicate.Admin {
+ return predicate.Admin(sql.FieldNEQ(FieldID, id))
+}
+
+// IDIn applies the In predicate on the ID field.
+func IDIn(ids ...uuid.UUID) predicate.Admin {
+ return predicate.Admin(sql.FieldIn(FieldID, ids...))
+}
+
+// IDNotIn applies the NotIn predicate on the ID field.
+func IDNotIn(ids ...uuid.UUID) predicate.Admin {
+ return predicate.Admin(sql.FieldNotIn(FieldID, ids...))
+}
+
+// IDGT applies the GT predicate on the ID field.
+func IDGT(id uuid.UUID) predicate.Admin {
+ return predicate.Admin(sql.FieldGT(FieldID, id))
+}
+
+// IDGTE applies the GTE predicate on the ID field.
+func IDGTE(id uuid.UUID) predicate.Admin {
+ return predicate.Admin(sql.FieldGTE(FieldID, id))
+}
+
+// IDLT applies the LT predicate on the ID field.
+func IDLT(id uuid.UUID) predicate.Admin {
+ return predicate.Admin(sql.FieldLT(FieldID, id))
+}
+
+// IDLTE applies the LTE predicate on the ID field.
+func IDLTE(id uuid.UUID) predicate.Admin {
+ return predicate.Admin(sql.FieldLTE(FieldID, id))
+}
+
+// Username applies equality check predicate on the "username" field. It's identical to UsernameEQ.
+func Username(v string) predicate.Admin {
+ return predicate.Admin(sql.FieldEQ(FieldUsername, v))
+}
+
+// Password applies equality check predicate on the "password" field. It's identical to PasswordEQ.
+func Password(v string) predicate.Admin {
+ return predicate.Admin(sql.FieldEQ(FieldPassword, v))
+}
+
+// Status applies equality check predicate on the "status" field. It's identical to StatusEQ.
+func Status(v consts.AdminStatus) predicate.Admin {
+ vc := string(v)
+ return predicate.Admin(sql.FieldEQ(FieldStatus, vc))
+}
+
+// LastActiveAt applies equality check predicate on the "last_active_at" field. It's identical to LastActiveAtEQ.
+func LastActiveAt(v time.Time) predicate.Admin {
+ return predicate.Admin(sql.FieldEQ(FieldLastActiveAt, v))
+}
+
+// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
+func CreatedAt(v time.Time) predicate.Admin {
+ return predicate.Admin(sql.FieldEQ(FieldCreatedAt, v))
+}
+
+// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
+func UpdatedAt(v time.Time) predicate.Admin {
+ return predicate.Admin(sql.FieldEQ(FieldUpdatedAt, v))
+}
+
+// UsernameEQ applies the EQ predicate on the "username" field.
+func UsernameEQ(v string) predicate.Admin {
+ return predicate.Admin(sql.FieldEQ(FieldUsername, v))
+}
+
+// UsernameNEQ applies the NEQ predicate on the "username" field.
+func UsernameNEQ(v string) predicate.Admin {
+ return predicate.Admin(sql.FieldNEQ(FieldUsername, v))
+}
+
+// UsernameIn applies the In predicate on the "username" field.
+func UsernameIn(vs ...string) predicate.Admin {
+ return predicate.Admin(sql.FieldIn(FieldUsername, vs...))
+}
+
+// UsernameNotIn applies the NotIn predicate on the "username" field.
+func UsernameNotIn(vs ...string) predicate.Admin {
+ return predicate.Admin(sql.FieldNotIn(FieldUsername, vs...))
+}
+
+// UsernameGT applies the GT predicate on the "username" field.
+func UsernameGT(v string) predicate.Admin {
+ return predicate.Admin(sql.FieldGT(FieldUsername, v))
+}
+
+// UsernameGTE applies the GTE predicate on the "username" field.
+func UsernameGTE(v string) predicate.Admin {
+ return predicate.Admin(sql.FieldGTE(FieldUsername, v))
+}
+
+// UsernameLT applies the LT predicate on the "username" field.
+func UsernameLT(v string) predicate.Admin {
+ return predicate.Admin(sql.FieldLT(FieldUsername, v))
+}
+
+// UsernameLTE applies the LTE predicate on the "username" field.
+func UsernameLTE(v string) predicate.Admin {
+ return predicate.Admin(sql.FieldLTE(FieldUsername, v))
+}
+
+// UsernameContains applies the Contains predicate on the "username" field.
+func UsernameContains(v string) predicate.Admin {
+ return predicate.Admin(sql.FieldContains(FieldUsername, v))
+}
+
+// UsernameHasPrefix applies the HasPrefix predicate on the "username" field.
+func UsernameHasPrefix(v string) predicate.Admin {
+ return predicate.Admin(sql.FieldHasPrefix(FieldUsername, v))
+}
+
+// UsernameHasSuffix applies the HasSuffix predicate on the "username" field.
+func UsernameHasSuffix(v string) predicate.Admin {
+ return predicate.Admin(sql.FieldHasSuffix(FieldUsername, v))
+}
+
+// UsernameEqualFold applies the EqualFold predicate on the "username" field.
+func UsernameEqualFold(v string) predicate.Admin {
+ return predicate.Admin(sql.FieldEqualFold(FieldUsername, v))
+}
+
+// UsernameContainsFold applies the ContainsFold predicate on the "username" field.
+func UsernameContainsFold(v string) predicate.Admin {
+ return predicate.Admin(sql.FieldContainsFold(FieldUsername, v))
+}
+
+// PasswordEQ applies the EQ predicate on the "password" field.
+func PasswordEQ(v string) predicate.Admin {
+ return predicate.Admin(sql.FieldEQ(FieldPassword, v))
+}
+
+// PasswordNEQ applies the NEQ predicate on the "password" field.
+func PasswordNEQ(v string) predicate.Admin {
+ return predicate.Admin(sql.FieldNEQ(FieldPassword, v))
+}
+
+// PasswordIn applies the In predicate on the "password" field.
+func PasswordIn(vs ...string) predicate.Admin {
+ return predicate.Admin(sql.FieldIn(FieldPassword, vs...))
+}
+
+// PasswordNotIn applies the NotIn predicate on the "password" field.
+func PasswordNotIn(vs ...string) predicate.Admin {
+ return predicate.Admin(sql.FieldNotIn(FieldPassword, vs...))
+}
+
+// PasswordGT applies the GT predicate on the "password" field.
+func PasswordGT(v string) predicate.Admin {
+ return predicate.Admin(sql.FieldGT(FieldPassword, v))
+}
+
+// PasswordGTE applies the GTE predicate on the "password" field.
+func PasswordGTE(v string) predicate.Admin {
+ return predicate.Admin(sql.FieldGTE(FieldPassword, v))
+}
+
+// PasswordLT applies the LT predicate on the "password" field.
+func PasswordLT(v string) predicate.Admin {
+ return predicate.Admin(sql.FieldLT(FieldPassword, v))
+}
+
+// PasswordLTE applies the LTE predicate on the "password" field.
+func PasswordLTE(v string) predicate.Admin {
+ return predicate.Admin(sql.FieldLTE(FieldPassword, v))
+}
+
+// PasswordContains applies the Contains predicate on the "password" field.
+func PasswordContains(v string) predicate.Admin {
+ return predicate.Admin(sql.FieldContains(FieldPassword, v))
+}
+
+// PasswordHasPrefix applies the HasPrefix predicate on the "password" field.
+func PasswordHasPrefix(v string) predicate.Admin {
+ return predicate.Admin(sql.FieldHasPrefix(FieldPassword, v))
+}
+
+// PasswordHasSuffix applies the HasSuffix predicate on the "password" field.
+func PasswordHasSuffix(v string) predicate.Admin {
+ return predicate.Admin(sql.FieldHasSuffix(FieldPassword, v))
+}
+
+// PasswordEqualFold applies the EqualFold predicate on the "password" field.
+func PasswordEqualFold(v string) predicate.Admin {
+ return predicate.Admin(sql.FieldEqualFold(FieldPassword, v))
+}
+
+// PasswordContainsFold applies the ContainsFold predicate on the "password" field.
+func PasswordContainsFold(v string) predicate.Admin {
+ return predicate.Admin(sql.FieldContainsFold(FieldPassword, v))
+}
+
+// StatusEQ applies the EQ predicate on the "status" field.
+func StatusEQ(v consts.AdminStatus) predicate.Admin {
+ vc := string(v)
+ return predicate.Admin(sql.FieldEQ(FieldStatus, vc))
+}
+
+// StatusNEQ applies the NEQ predicate on the "status" field.
+func StatusNEQ(v consts.AdminStatus) predicate.Admin {
+ vc := string(v)
+ return predicate.Admin(sql.FieldNEQ(FieldStatus, vc))
+}
+
+// StatusIn applies the In predicate on the "status" field.
+func StatusIn(vs ...consts.AdminStatus) predicate.Admin {
+ v := make([]any, len(vs))
+ for i := range v {
+ v[i] = string(vs[i])
+ }
+ return predicate.Admin(sql.FieldIn(FieldStatus, v...))
+}
+
+// StatusNotIn applies the NotIn predicate on the "status" field.
+func StatusNotIn(vs ...consts.AdminStatus) predicate.Admin {
+ v := make([]any, len(vs))
+ for i := range v {
+ v[i] = string(vs[i])
+ }
+ return predicate.Admin(sql.FieldNotIn(FieldStatus, v...))
+}
+
+// StatusGT applies the GT predicate on the "status" field.
+func StatusGT(v consts.AdminStatus) predicate.Admin {
+ vc := string(v)
+ return predicate.Admin(sql.FieldGT(FieldStatus, vc))
+}
+
+// StatusGTE applies the GTE predicate on the "status" field.
+func StatusGTE(v consts.AdminStatus) predicate.Admin {
+ vc := string(v)
+ return predicate.Admin(sql.FieldGTE(FieldStatus, vc))
+}
+
+// StatusLT applies the LT predicate on the "status" field.
+func StatusLT(v consts.AdminStatus) predicate.Admin {
+ vc := string(v)
+ return predicate.Admin(sql.FieldLT(FieldStatus, vc))
+}
+
+// StatusLTE applies the LTE predicate on the "status" field.
+func StatusLTE(v consts.AdminStatus) predicate.Admin {
+ vc := string(v)
+ return predicate.Admin(sql.FieldLTE(FieldStatus, vc))
+}
+
+// StatusContains applies the Contains predicate on the "status" field.
+func StatusContains(v consts.AdminStatus) predicate.Admin {
+ vc := string(v)
+ return predicate.Admin(sql.FieldContains(FieldStatus, vc))
+}
+
+// StatusHasPrefix applies the HasPrefix predicate on the "status" field.
+func StatusHasPrefix(v consts.AdminStatus) predicate.Admin {
+ vc := string(v)
+ return predicate.Admin(sql.FieldHasPrefix(FieldStatus, vc))
+}
+
+// StatusHasSuffix applies the HasSuffix predicate on the "status" field.
+func StatusHasSuffix(v consts.AdminStatus) predicate.Admin {
+ vc := string(v)
+ return predicate.Admin(sql.FieldHasSuffix(FieldStatus, vc))
+}
+
+// StatusEqualFold applies the EqualFold predicate on the "status" field.
+func StatusEqualFold(v consts.AdminStatus) predicate.Admin {
+ vc := string(v)
+ return predicate.Admin(sql.FieldEqualFold(FieldStatus, vc))
+}
+
+// StatusContainsFold applies the ContainsFold predicate on the "status" field.
+func StatusContainsFold(v consts.AdminStatus) predicate.Admin {
+ vc := string(v)
+ return predicate.Admin(sql.FieldContainsFold(FieldStatus, vc))
+}
+
+// LastActiveAtEQ applies the EQ predicate on the "last_active_at" field.
+func LastActiveAtEQ(v time.Time) predicate.Admin {
+ return predicate.Admin(sql.FieldEQ(FieldLastActiveAt, v))
+}
+
+// LastActiveAtNEQ applies the NEQ predicate on the "last_active_at" field.
+func LastActiveAtNEQ(v time.Time) predicate.Admin {
+ return predicate.Admin(sql.FieldNEQ(FieldLastActiveAt, v))
+}
+
+// LastActiveAtIn applies the In predicate on the "last_active_at" field.
+func LastActiveAtIn(vs ...time.Time) predicate.Admin {
+ return predicate.Admin(sql.FieldIn(FieldLastActiveAt, vs...))
+}
+
+// LastActiveAtNotIn applies the NotIn predicate on the "last_active_at" field.
+func LastActiveAtNotIn(vs ...time.Time) predicate.Admin {
+ return predicate.Admin(sql.FieldNotIn(FieldLastActiveAt, vs...))
+}
+
+// LastActiveAtGT applies the GT predicate on the "last_active_at" field.
+func LastActiveAtGT(v time.Time) predicate.Admin {
+ return predicate.Admin(sql.FieldGT(FieldLastActiveAt, v))
+}
+
+// LastActiveAtGTE applies the GTE predicate on the "last_active_at" field.
+func LastActiveAtGTE(v time.Time) predicate.Admin {
+ return predicate.Admin(sql.FieldGTE(FieldLastActiveAt, v))
+}
+
+// LastActiveAtLT applies the LT predicate on the "last_active_at" field.
+func LastActiveAtLT(v time.Time) predicate.Admin {
+ return predicate.Admin(sql.FieldLT(FieldLastActiveAt, v))
+}
+
+// LastActiveAtLTE applies the LTE predicate on the "last_active_at" field.
+func LastActiveAtLTE(v time.Time) predicate.Admin {
+ return predicate.Admin(sql.FieldLTE(FieldLastActiveAt, v))
+}
+
+// CreatedAtEQ applies the EQ predicate on the "created_at" field.
+func CreatedAtEQ(v time.Time) predicate.Admin {
+ return predicate.Admin(sql.FieldEQ(FieldCreatedAt, v))
+}
+
+// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
+func CreatedAtNEQ(v time.Time) predicate.Admin {
+ return predicate.Admin(sql.FieldNEQ(FieldCreatedAt, v))
+}
+
+// CreatedAtIn applies the In predicate on the "created_at" field.
+func CreatedAtIn(vs ...time.Time) predicate.Admin {
+ return predicate.Admin(sql.FieldIn(FieldCreatedAt, vs...))
+}
+
+// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
+func CreatedAtNotIn(vs ...time.Time) predicate.Admin {
+ return predicate.Admin(sql.FieldNotIn(FieldCreatedAt, vs...))
+}
+
+// CreatedAtGT applies the GT predicate on the "created_at" field.
+func CreatedAtGT(v time.Time) predicate.Admin {
+ return predicate.Admin(sql.FieldGT(FieldCreatedAt, v))
+}
+
+// CreatedAtGTE applies the GTE predicate on the "created_at" field.
+func CreatedAtGTE(v time.Time) predicate.Admin {
+ return predicate.Admin(sql.FieldGTE(FieldCreatedAt, v))
+}
+
+// CreatedAtLT applies the LT predicate on the "created_at" field.
+func CreatedAtLT(v time.Time) predicate.Admin {
+ return predicate.Admin(sql.FieldLT(FieldCreatedAt, v))
+}
+
+// CreatedAtLTE applies the LTE predicate on the "created_at" field.
+func CreatedAtLTE(v time.Time) predicate.Admin {
+ return predicate.Admin(sql.FieldLTE(FieldCreatedAt, v))
+}
+
+// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
+func UpdatedAtEQ(v time.Time) predicate.Admin {
+ return predicate.Admin(sql.FieldEQ(FieldUpdatedAt, v))
+}
+
+// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
+func UpdatedAtNEQ(v time.Time) predicate.Admin {
+ return predicate.Admin(sql.FieldNEQ(FieldUpdatedAt, v))
+}
+
+// UpdatedAtIn applies the In predicate on the "updated_at" field.
+func UpdatedAtIn(vs ...time.Time) predicate.Admin {
+ return predicate.Admin(sql.FieldIn(FieldUpdatedAt, vs...))
+}
+
+// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
+func UpdatedAtNotIn(vs ...time.Time) predicate.Admin {
+ return predicate.Admin(sql.FieldNotIn(FieldUpdatedAt, vs...))
+}
+
+// UpdatedAtGT applies the GT predicate on the "updated_at" field.
+func UpdatedAtGT(v time.Time) predicate.Admin {
+ return predicate.Admin(sql.FieldGT(FieldUpdatedAt, v))
+}
+
+// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
+func UpdatedAtGTE(v time.Time) predicate.Admin {
+ return predicate.Admin(sql.FieldGTE(FieldUpdatedAt, v))
+}
+
+// UpdatedAtLT applies the LT predicate on the "updated_at" field.
+func UpdatedAtLT(v time.Time) predicate.Admin {
+ return predicate.Admin(sql.FieldLT(FieldUpdatedAt, v))
+}
+
+// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
+func UpdatedAtLTE(v time.Time) predicate.Admin {
+ return predicate.Admin(sql.FieldLTE(FieldUpdatedAt, v))
+}
+
+// HasLoginHistories applies the HasEdge predicate on the "login_histories" edge.
+func HasLoginHistories() predicate.Admin {
+ return predicate.Admin(func(s *sql.Selector) {
+ step := sqlgraph.NewStep(
+ sqlgraph.From(Table, FieldID),
+ sqlgraph.Edge(sqlgraph.O2M, false, LoginHistoriesTable, LoginHistoriesColumn),
+ )
+ sqlgraph.HasNeighbors(s, step)
+ })
+}
+
+// HasLoginHistoriesWith applies the HasEdge predicate on the "login_histories" edge with a given conditions (other predicates).
+func HasLoginHistoriesWith(preds ...predicate.AdminLoginHistory) predicate.Admin {
+ return predicate.Admin(func(s *sql.Selector) {
+ step := newLoginHistoriesStep()
+ sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
+ for _, p := range preds {
+ p(s)
+ }
+ })
+ })
+}
+
+// And groups predicates with the AND operator between them.
+func And(predicates ...predicate.Admin) predicate.Admin {
+ return predicate.Admin(sql.AndPredicates(predicates...))
+}
+
+// Or groups predicates with the OR operator between them.
+func Or(predicates ...predicate.Admin) predicate.Admin {
+ return predicate.Admin(sql.OrPredicates(predicates...))
+}
+
+// Not applies the not operator on the given predicate.
+func Not(p predicate.Admin) predicate.Admin {
+ return predicate.Admin(sql.NotPredicates(p))
+}
diff --git a/backend/db/admin_create.go b/backend/db/admin_create.go
new file mode 100644
index 0000000..f84718f
--- /dev/null
+++ b/backend/db/admin_create.go
@@ -0,0 +1,831 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "time"
+
+ "entgo.io/ent/dialect"
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/consts"
+ "github.com/chaitin/MonkeyCode/backend/db/admin"
+ "github.com/chaitin/MonkeyCode/backend/db/adminloginhistory"
+ "github.com/google/uuid"
+)
+
+// AdminCreate is the builder for creating a Admin entity.
+type AdminCreate struct {
+ config
+ mutation *AdminMutation
+ hooks []Hook
+ conflict []sql.ConflictOption
+}
+
+// SetUsername sets the "username" field.
+func (ac *AdminCreate) SetUsername(s string) *AdminCreate {
+ ac.mutation.SetUsername(s)
+ return ac
+}
+
+// SetPassword sets the "password" field.
+func (ac *AdminCreate) SetPassword(s string) *AdminCreate {
+ ac.mutation.SetPassword(s)
+ return ac
+}
+
+// SetStatus sets the "status" field.
+func (ac *AdminCreate) SetStatus(cs consts.AdminStatus) *AdminCreate {
+ ac.mutation.SetStatus(cs)
+ return ac
+}
+
+// SetLastActiveAt sets the "last_active_at" field.
+func (ac *AdminCreate) SetLastActiveAt(t time.Time) *AdminCreate {
+ ac.mutation.SetLastActiveAt(t)
+ return ac
+}
+
+// SetNillableLastActiveAt sets the "last_active_at" field if the given value is not nil.
+func (ac *AdminCreate) SetNillableLastActiveAt(t *time.Time) *AdminCreate {
+ if t != nil {
+ ac.SetLastActiveAt(*t)
+ }
+ return ac
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (ac *AdminCreate) SetCreatedAt(t time.Time) *AdminCreate {
+ ac.mutation.SetCreatedAt(t)
+ return ac
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (ac *AdminCreate) SetNillableCreatedAt(t *time.Time) *AdminCreate {
+ if t != nil {
+ ac.SetCreatedAt(*t)
+ }
+ return ac
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (ac *AdminCreate) SetUpdatedAt(t time.Time) *AdminCreate {
+ ac.mutation.SetUpdatedAt(t)
+ return ac
+}
+
+// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
+func (ac *AdminCreate) SetNillableUpdatedAt(t *time.Time) *AdminCreate {
+ if t != nil {
+ ac.SetUpdatedAt(*t)
+ }
+ return ac
+}
+
+// SetID sets the "id" field.
+func (ac *AdminCreate) SetID(u uuid.UUID) *AdminCreate {
+ ac.mutation.SetID(u)
+ return ac
+}
+
+// AddLoginHistoryIDs adds the "login_histories" edge to the AdminLoginHistory entity by IDs.
+func (ac *AdminCreate) AddLoginHistoryIDs(ids ...uuid.UUID) *AdminCreate {
+ ac.mutation.AddLoginHistoryIDs(ids...)
+ return ac
+}
+
+// AddLoginHistories adds the "login_histories" edges to the AdminLoginHistory entity.
+func (ac *AdminCreate) AddLoginHistories(a ...*AdminLoginHistory) *AdminCreate {
+ ids := make([]uuid.UUID, len(a))
+ for i := range a {
+ ids[i] = a[i].ID
+ }
+ return ac.AddLoginHistoryIDs(ids...)
+}
+
+// Mutation returns the AdminMutation object of the builder.
+func (ac *AdminCreate) Mutation() *AdminMutation {
+ return ac.mutation
+}
+
+// Save creates the Admin in the database.
+func (ac *AdminCreate) Save(ctx context.Context) (*Admin, error) {
+ ac.defaults()
+ return withHooks(ctx, ac.sqlSave, ac.mutation, ac.hooks)
+}
+
+// SaveX calls Save and panics if Save returns an error.
+func (ac *AdminCreate) SaveX(ctx context.Context) *Admin {
+ v, err := ac.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return v
+}
+
+// Exec executes the query.
+func (ac *AdminCreate) Exec(ctx context.Context) error {
+ _, err := ac.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (ac *AdminCreate) ExecX(ctx context.Context) {
+ if err := ac.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// defaults sets the default values of the builder before save.
+func (ac *AdminCreate) defaults() {
+ if _, ok := ac.mutation.LastActiveAt(); !ok {
+ v := admin.DefaultLastActiveAt()
+ ac.mutation.SetLastActiveAt(v)
+ }
+ if _, ok := ac.mutation.CreatedAt(); !ok {
+ v := admin.DefaultCreatedAt()
+ ac.mutation.SetCreatedAt(v)
+ }
+ if _, ok := ac.mutation.UpdatedAt(); !ok {
+ v := admin.DefaultUpdatedAt()
+ ac.mutation.SetUpdatedAt(v)
+ }
+}
+
+// check runs all checks and user-defined validators on the builder.
+func (ac *AdminCreate) check() error {
+ if _, ok := ac.mutation.Username(); !ok {
+ return &ValidationError{Name: "username", err: errors.New(`db: missing required field "Admin.username"`)}
+ }
+ if _, ok := ac.mutation.Password(); !ok {
+ return &ValidationError{Name: "password", err: errors.New(`db: missing required field "Admin.password"`)}
+ }
+ if _, ok := ac.mutation.Status(); !ok {
+ return &ValidationError{Name: "status", err: errors.New(`db: missing required field "Admin.status"`)}
+ }
+ if _, ok := ac.mutation.LastActiveAt(); !ok {
+ return &ValidationError{Name: "last_active_at", err: errors.New(`db: missing required field "Admin.last_active_at"`)}
+ }
+ if _, ok := ac.mutation.CreatedAt(); !ok {
+ return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "Admin.created_at"`)}
+ }
+ if _, ok := ac.mutation.UpdatedAt(); !ok {
+ return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "Admin.updated_at"`)}
+ }
+ return nil
+}
+
+func (ac *AdminCreate) sqlSave(ctx context.Context) (*Admin, error) {
+ if err := ac.check(); err != nil {
+ return nil, err
+ }
+ _node, _spec := ac.createSpec()
+ if err := sqlgraph.CreateNode(ctx, ac.driver, _spec); err != nil {
+ if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return nil, err
+ }
+ if _spec.ID.Value != nil {
+ if id, ok := _spec.ID.Value.(*uuid.UUID); ok {
+ _node.ID = *id
+ } else if err := _node.ID.Scan(_spec.ID.Value); err != nil {
+ return nil, err
+ }
+ }
+ ac.mutation.id = &_node.ID
+ ac.mutation.done = true
+ return _node, nil
+}
+
+func (ac *AdminCreate) createSpec() (*Admin, *sqlgraph.CreateSpec) {
+ var (
+ _node = &Admin{config: ac.config}
+ _spec = sqlgraph.NewCreateSpec(admin.Table, sqlgraph.NewFieldSpec(admin.FieldID, field.TypeUUID))
+ )
+ _spec.OnConflict = ac.conflict
+ if id, ok := ac.mutation.ID(); ok {
+ _node.ID = id
+ _spec.ID.Value = &id
+ }
+ if value, ok := ac.mutation.Username(); ok {
+ _spec.SetField(admin.FieldUsername, field.TypeString, value)
+ _node.Username = value
+ }
+ if value, ok := ac.mutation.Password(); ok {
+ _spec.SetField(admin.FieldPassword, field.TypeString, value)
+ _node.Password = value
+ }
+ if value, ok := ac.mutation.Status(); ok {
+ _spec.SetField(admin.FieldStatus, field.TypeString, value)
+ _node.Status = value
+ }
+ if value, ok := ac.mutation.LastActiveAt(); ok {
+ _spec.SetField(admin.FieldLastActiveAt, field.TypeTime, value)
+ _node.LastActiveAt = value
+ }
+ if value, ok := ac.mutation.CreatedAt(); ok {
+ _spec.SetField(admin.FieldCreatedAt, field.TypeTime, value)
+ _node.CreatedAt = value
+ }
+ if value, ok := ac.mutation.UpdatedAt(); ok {
+ _spec.SetField(admin.FieldUpdatedAt, field.TypeTime, value)
+ _node.UpdatedAt = value
+ }
+ if nodes := ac.mutation.LoginHistoriesIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: admin.LoginHistoriesTable,
+ Columns: []string{admin.LoginHistoriesColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(adminloginhistory.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges = append(_spec.Edges, edge)
+ }
+ return _node, _spec
+}
+
+// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
+// of the `INSERT` statement. For example:
+//
+// client.Admin.Create().
+// SetUsername(v).
+// OnConflict(
+// // Update the row with the new values
+// // the was proposed for insertion.
+// sql.ResolveWithNewValues(),
+// ).
+// // Override some of the fields with custom
+// // update values.
+// Update(func(u *ent.AdminUpsert) {
+// SetUsername(v+v).
+// }).
+// Exec(ctx)
+func (ac *AdminCreate) OnConflict(opts ...sql.ConflictOption) *AdminUpsertOne {
+ ac.conflict = opts
+ return &AdminUpsertOne{
+ create: ac,
+ }
+}
+
+// OnConflictColumns calls `OnConflict` and configures the columns
+// as conflict target. Using this option is equivalent to using:
+//
+// client.Admin.Create().
+// OnConflict(sql.ConflictColumns(columns...)).
+// Exec(ctx)
+func (ac *AdminCreate) OnConflictColumns(columns ...string) *AdminUpsertOne {
+ ac.conflict = append(ac.conflict, sql.ConflictColumns(columns...))
+ return &AdminUpsertOne{
+ create: ac,
+ }
+}
+
+type (
+ // AdminUpsertOne is the builder for "upsert"-ing
+ // one Admin node.
+ AdminUpsertOne struct {
+ create *AdminCreate
+ }
+
+ // AdminUpsert is the "OnConflict" setter.
+ AdminUpsert struct {
+ *sql.UpdateSet
+ }
+)
+
+// SetUsername sets the "username" field.
+func (u *AdminUpsert) SetUsername(v string) *AdminUpsert {
+ u.Set(admin.FieldUsername, v)
+ return u
+}
+
+// UpdateUsername sets the "username" field to the value that was provided on create.
+func (u *AdminUpsert) UpdateUsername() *AdminUpsert {
+ u.SetExcluded(admin.FieldUsername)
+ return u
+}
+
+// SetPassword sets the "password" field.
+func (u *AdminUpsert) SetPassword(v string) *AdminUpsert {
+ u.Set(admin.FieldPassword, v)
+ return u
+}
+
+// UpdatePassword sets the "password" field to the value that was provided on create.
+func (u *AdminUpsert) UpdatePassword() *AdminUpsert {
+ u.SetExcluded(admin.FieldPassword)
+ return u
+}
+
+// SetStatus sets the "status" field.
+func (u *AdminUpsert) SetStatus(v consts.AdminStatus) *AdminUpsert {
+ u.Set(admin.FieldStatus, v)
+ return u
+}
+
+// UpdateStatus sets the "status" field to the value that was provided on create.
+func (u *AdminUpsert) UpdateStatus() *AdminUpsert {
+ u.SetExcluded(admin.FieldStatus)
+ return u
+}
+
+// SetLastActiveAt sets the "last_active_at" field.
+func (u *AdminUpsert) SetLastActiveAt(v time.Time) *AdminUpsert {
+ u.Set(admin.FieldLastActiveAt, v)
+ return u
+}
+
+// UpdateLastActiveAt sets the "last_active_at" field to the value that was provided on create.
+func (u *AdminUpsert) UpdateLastActiveAt() *AdminUpsert {
+ u.SetExcluded(admin.FieldLastActiveAt)
+ return u
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (u *AdminUpsert) SetCreatedAt(v time.Time) *AdminUpsert {
+ u.Set(admin.FieldCreatedAt, v)
+ return u
+}
+
+// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
+func (u *AdminUpsert) UpdateCreatedAt() *AdminUpsert {
+ u.SetExcluded(admin.FieldCreatedAt)
+ return u
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (u *AdminUpsert) SetUpdatedAt(v time.Time) *AdminUpsert {
+ u.Set(admin.FieldUpdatedAt, v)
+ return u
+}
+
+// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
+func (u *AdminUpsert) UpdateUpdatedAt() *AdminUpsert {
+ u.SetExcluded(admin.FieldUpdatedAt)
+ return u
+}
+
+// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field.
+// Using this option is equivalent to using:
+//
+// client.Admin.Create().
+// OnConflict(
+// sql.ResolveWithNewValues(),
+// sql.ResolveWith(func(u *sql.UpdateSet) {
+// u.SetIgnore(admin.FieldID)
+// }),
+// ).
+// Exec(ctx)
+func (u *AdminUpsertOne) UpdateNewValues() *AdminUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
+ if _, exists := u.create.mutation.ID(); exists {
+ s.SetIgnore(admin.FieldID)
+ }
+ }))
+ return u
+}
+
+// Ignore sets each column to itself in case of conflict.
+// Using this option is equivalent to using:
+//
+// client.Admin.Create().
+// OnConflict(sql.ResolveWithIgnore()).
+// Exec(ctx)
+func (u *AdminUpsertOne) Ignore() *AdminUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
+ return u
+}
+
+// DoNothing configures the conflict_action to `DO NOTHING`.
+// Supported only by SQLite and PostgreSQL.
+func (u *AdminUpsertOne) DoNothing() *AdminUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.DoNothing())
+ return u
+}
+
+// Update allows overriding fields `UPDATE` values. See the AdminCreate.OnConflict
+// documentation for more info.
+func (u *AdminUpsertOne) Update(set func(*AdminUpsert)) *AdminUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
+ set(&AdminUpsert{UpdateSet: update})
+ }))
+ return u
+}
+
+// SetUsername sets the "username" field.
+func (u *AdminUpsertOne) SetUsername(v string) *AdminUpsertOne {
+ return u.Update(func(s *AdminUpsert) {
+ s.SetUsername(v)
+ })
+}
+
+// UpdateUsername sets the "username" field to the value that was provided on create.
+func (u *AdminUpsertOne) UpdateUsername() *AdminUpsertOne {
+ return u.Update(func(s *AdminUpsert) {
+ s.UpdateUsername()
+ })
+}
+
+// SetPassword sets the "password" field.
+func (u *AdminUpsertOne) SetPassword(v string) *AdminUpsertOne {
+ return u.Update(func(s *AdminUpsert) {
+ s.SetPassword(v)
+ })
+}
+
+// UpdatePassword sets the "password" field to the value that was provided on create.
+func (u *AdminUpsertOne) UpdatePassword() *AdminUpsertOne {
+ return u.Update(func(s *AdminUpsert) {
+ s.UpdatePassword()
+ })
+}
+
+// SetStatus sets the "status" field.
+func (u *AdminUpsertOne) SetStatus(v consts.AdminStatus) *AdminUpsertOne {
+ return u.Update(func(s *AdminUpsert) {
+ s.SetStatus(v)
+ })
+}
+
+// UpdateStatus sets the "status" field to the value that was provided on create.
+func (u *AdminUpsertOne) UpdateStatus() *AdminUpsertOne {
+ return u.Update(func(s *AdminUpsert) {
+ s.UpdateStatus()
+ })
+}
+
+// SetLastActiveAt sets the "last_active_at" field.
+func (u *AdminUpsertOne) SetLastActiveAt(v time.Time) *AdminUpsertOne {
+ return u.Update(func(s *AdminUpsert) {
+ s.SetLastActiveAt(v)
+ })
+}
+
+// UpdateLastActiveAt sets the "last_active_at" field to the value that was provided on create.
+func (u *AdminUpsertOne) UpdateLastActiveAt() *AdminUpsertOne {
+ return u.Update(func(s *AdminUpsert) {
+ s.UpdateLastActiveAt()
+ })
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (u *AdminUpsertOne) SetCreatedAt(v time.Time) *AdminUpsertOne {
+ return u.Update(func(s *AdminUpsert) {
+ s.SetCreatedAt(v)
+ })
+}
+
+// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
+func (u *AdminUpsertOne) UpdateCreatedAt() *AdminUpsertOne {
+ return u.Update(func(s *AdminUpsert) {
+ s.UpdateCreatedAt()
+ })
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (u *AdminUpsertOne) SetUpdatedAt(v time.Time) *AdminUpsertOne {
+ return u.Update(func(s *AdminUpsert) {
+ s.SetUpdatedAt(v)
+ })
+}
+
+// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
+func (u *AdminUpsertOne) UpdateUpdatedAt() *AdminUpsertOne {
+ return u.Update(func(s *AdminUpsert) {
+ s.UpdateUpdatedAt()
+ })
+}
+
+// Exec executes the query.
+func (u *AdminUpsertOne) Exec(ctx context.Context) error {
+ if len(u.create.conflict) == 0 {
+ return errors.New("db: missing options for AdminCreate.OnConflict")
+ }
+ return u.create.Exec(ctx)
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (u *AdminUpsertOne) ExecX(ctx context.Context) {
+ if err := u.create.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// Exec executes the UPSERT query and returns the inserted/updated ID.
+func (u *AdminUpsertOne) ID(ctx context.Context) (id uuid.UUID, err error) {
+ if u.create.driver.Dialect() == dialect.MySQL {
+ // In case of "ON CONFLICT", there is no way to get back non-numeric ID
+ // fields from the database since MySQL does not support the RETURNING clause.
+ return id, errors.New("db: AdminUpsertOne.ID is not supported by MySQL driver. Use AdminUpsertOne.Exec instead")
+ }
+ node, err := u.create.Save(ctx)
+ if err != nil {
+ return id, err
+ }
+ return node.ID, nil
+}
+
+// IDX is like ID, but panics if an error occurs.
+func (u *AdminUpsertOne) IDX(ctx context.Context) uuid.UUID {
+ id, err := u.ID(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return id
+}
+
+// AdminCreateBulk is the builder for creating many Admin entities in bulk.
+type AdminCreateBulk struct {
+ config
+ err error
+ builders []*AdminCreate
+ conflict []sql.ConflictOption
+}
+
+// Save creates the Admin entities in the database.
+func (acb *AdminCreateBulk) Save(ctx context.Context) ([]*Admin, error) {
+ if acb.err != nil {
+ return nil, acb.err
+ }
+ specs := make([]*sqlgraph.CreateSpec, len(acb.builders))
+ nodes := make([]*Admin, len(acb.builders))
+ mutators := make([]Mutator, len(acb.builders))
+ for i := range acb.builders {
+ func(i int, root context.Context) {
+ builder := acb.builders[i]
+ builder.defaults()
+ var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
+ mutation, ok := m.(*AdminMutation)
+ if !ok {
+ return nil, fmt.Errorf("unexpected mutation type %T", m)
+ }
+ if err := builder.check(); err != nil {
+ return nil, err
+ }
+ builder.mutation = mutation
+ var err error
+ nodes[i], specs[i] = builder.createSpec()
+ if i < len(mutators)-1 {
+ _, err = mutators[i+1].Mutate(root, acb.builders[i+1].mutation)
+ } else {
+ spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
+ spec.OnConflict = acb.conflict
+ // Invoke the actual operation on the latest mutation in the chain.
+ if err = sqlgraph.BatchCreate(ctx, acb.driver, spec); err != nil {
+ if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ }
+ }
+ if err != nil {
+ return nil, err
+ }
+ mutation.id = &nodes[i].ID
+ mutation.done = true
+ return nodes[i], nil
+ })
+ for i := len(builder.hooks) - 1; i >= 0; i-- {
+ mut = builder.hooks[i](mut)
+ }
+ mutators[i] = mut
+ }(i, ctx)
+ }
+ if len(mutators) > 0 {
+ if _, err := mutators[0].Mutate(ctx, acb.builders[0].mutation); err != nil {
+ return nil, err
+ }
+ }
+ return nodes, nil
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (acb *AdminCreateBulk) SaveX(ctx context.Context) []*Admin {
+ v, err := acb.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return v
+}
+
+// Exec executes the query.
+func (acb *AdminCreateBulk) Exec(ctx context.Context) error {
+ _, err := acb.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (acb *AdminCreateBulk) ExecX(ctx context.Context) {
+ if err := acb.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
+// of the `INSERT` statement. For example:
+//
+// client.Admin.CreateBulk(builders...).
+// OnConflict(
+// // Update the row with the new values
+// // the was proposed for insertion.
+// sql.ResolveWithNewValues(),
+// ).
+// // Override some of the fields with custom
+// // update values.
+// Update(func(u *ent.AdminUpsert) {
+// SetUsername(v+v).
+// }).
+// Exec(ctx)
+func (acb *AdminCreateBulk) OnConflict(opts ...sql.ConflictOption) *AdminUpsertBulk {
+ acb.conflict = opts
+ return &AdminUpsertBulk{
+ create: acb,
+ }
+}
+
+// OnConflictColumns calls `OnConflict` and configures the columns
+// as conflict target. Using this option is equivalent to using:
+//
+// client.Admin.Create().
+// OnConflict(sql.ConflictColumns(columns...)).
+// Exec(ctx)
+func (acb *AdminCreateBulk) OnConflictColumns(columns ...string) *AdminUpsertBulk {
+ acb.conflict = append(acb.conflict, sql.ConflictColumns(columns...))
+ return &AdminUpsertBulk{
+ create: acb,
+ }
+}
+
+// AdminUpsertBulk is the builder for "upsert"-ing
+// a bulk of Admin nodes.
+type AdminUpsertBulk struct {
+ create *AdminCreateBulk
+}
+
+// UpdateNewValues updates the mutable fields using the new values that
+// were set on create. Using this option is equivalent to using:
+//
+// client.Admin.Create().
+// OnConflict(
+// sql.ResolveWithNewValues(),
+// sql.ResolveWith(func(u *sql.UpdateSet) {
+// u.SetIgnore(admin.FieldID)
+// }),
+// ).
+// Exec(ctx)
+func (u *AdminUpsertBulk) UpdateNewValues() *AdminUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
+ for _, b := range u.create.builders {
+ if _, exists := b.mutation.ID(); exists {
+ s.SetIgnore(admin.FieldID)
+ }
+ }
+ }))
+ return u
+}
+
+// Ignore sets each column to itself in case of conflict.
+// Using this option is equivalent to using:
+//
+// client.Admin.Create().
+// OnConflict(sql.ResolveWithIgnore()).
+// Exec(ctx)
+func (u *AdminUpsertBulk) Ignore() *AdminUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
+ return u
+}
+
+// DoNothing configures the conflict_action to `DO NOTHING`.
+// Supported only by SQLite and PostgreSQL.
+func (u *AdminUpsertBulk) DoNothing() *AdminUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.DoNothing())
+ return u
+}
+
+// Update allows overriding fields `UPDATE` values. See the AdminCreateBulk.OnConflict
+// documentation for more info.
+func (u *AdminUpsertBulk) Update(set func(*AdminUpsert)) *AdminUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
+ set(&AdminUpsert{UpdateSet: update})
+ }))
+ return u
+}
+
+// SetUsername sets the "username" field.
+func (u *AdminUpsertBulk) SetUsername(v string) *AdminUpsertBulk {
+ return u.Update(func(s *AdminUpsert) {
+ s.SetUsername(v)
+ })
+}
+
+// UpdateUsername sets the "username" field to the value that was provided on create.
+func (u *AdminUpsertBulk) UpdateUsername() *AdminUpsertBulk {
+ return u.Update(func(s *AdminUpsert) {
+ s.UpdateUsername()
+ })
+}
+
+// SetPassword sets the "password" field.
+func (u *AdminUpsertBulk) SetPassword(v string) *AdminUpsertBulk {
+ return u.Update(func(s *AdminUpsert) {
+ s.SetPassword(v)
+ })
+}
+
+// UpdatePassword sets the "password" field to the value that was provided on create.
+func (u *AdminUpsertBulk) UpdatePassword() *AdminUpsertBulk {
+ return u.Update(func(s *AdminUpsert) {
+ s.UpdatePassword()
+ })
+}
+
+// SetStatus sets the "status" field.
+func (u *AdminUpsertBulk) SetStatus(v consts.AdminStatus) *AdminUpsertBulk {
+ return u.Update(func(s *AdminUpsert) {
+ s.SetStatus(v)
+ })
+}
+
+// UpdateStatus sets the "status" field to the value that was provided on create.
+func (u *AdminUpsertBulk) UpdateStatus() *AdminUpsertBulk {
+ return u.Update(func(s *AdminUpsert) {
+ s.UpdateStatus()
+ })
+}
+
+// SetLastActiveAt sets the "last_active_at" field.
+func (u *AdminUpsertBulk) SetLastActiveAt(v time.Time) *AdminUpsertBulk {
+ return u.Update(func(s *AdminUpsert) {
+ s.SetLastActiveAt(v)
+ })
+}
+
+// UpdateLastActiveAt sets the "last_active_at" field to the value that was provided on create.
+func (u *AdminUpsertBulk) UpdateLastActiveAt() *AdminUpsertBulk {
+ return u.Update(func(s *AdminUpsert) {
+ s.UpdateLastActiveAt()
+ })
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (u *AdminUpsertBulk) SetCreatedAt(v time.Time) *AdminUpsertBulk {
+ return u.Update(func(s *AdminUpsert) {
+ s.SetCreatedAt(v)
+ })
+}
+
+// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
+func (u *AdminUpsertBulk) UpdateCreatedAt() *AdminUpsertBulk {
+ return u.Update(func(s *AdminUpsert) {
+ s.UpdateCreatedAt()
+ })
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (u *AdminUpsertBulk) SetUpdatedAt(v time.Time) *AdminUpsertBulk {
+ return u.Update(func(s *AdminUpsert) {
+ s.SetUpdatedAt(v)
+ })
+}
+
+// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
+func (u *AdminUpsertBulk) UpdateUpdatedAt() *AdminUpsertBulk {
+ return u.Update(func(s *AdminUpsert) {
+ s.UpdateUpdatedAt()
+ })
+}
+
+// Exec executes the query.
+func (u *AdminUpsertBulk) Exec(ctx context.Context) error {
+ if u.create.err != nil {
+ return u.create.err
+ }
+ for i, b := range u.create.builders {
+ if len(b.conflict) != 0 {
+ return fmt.Errorf("db: OnConflict was set for builder %d. Set it on the AdminCreateBulk instead", i)
+ }
+ }
+ if len(u.create.conflict) == 0 {
+ return errors.New("db: missing options for AdminCreateBulk.OnConflict")
+ }
+ return u.create.Exec(ctx)
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (u *AdminUpsertBulk) ExecX(ctx context.Context) {
+ if err := u.create.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
diff --git a/backend/db/admin_delete.go b/backend/db/admin_delete.go
new file mode 100644
index 0000000..d10f786
--- /dev/null
+++ b/backend/db/admin_delete.go
@@ -0,0 +1,88 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/admin"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+)
+
+// AdminDelete is the builder for deleting a Admin entity.
+type AdminDelete struct {
+ config
+ hooks []Hook
+ mutation *AdminMutation
+}
+
+// Where appends a list predicates to the AdminDelete builder.
+func (ad *AdminDelete) Where(ps ...predicate.Admin) *AdminDelete {
+ ad.mutation.Where(ps...)
+ return ad
+}
+
+// Exec executes the deletion query and returns how many vertices were deleted.
+func (ad *AdminDelete) Exec(ctx context.Context) (int, error) {
+ return withHooks(ctx, ad.sqlExec, ad.mutation, ad.hooks)
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (ad *AdminDelete) ExecX(ctx context.Context) int {
+ n, err := ad.Exec(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return n
+}
+
+func (ad *AdminDelete) sqlExec(ctx context.Context) (int, error) {
+ _spec := sqlgraph.NewDeleteSpec(admin.Table, sqlgraph.NewFieldSpec(admin.FieldID, field.TypeUUID))
+ if ps := ad.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ affected, err := sqlgraph.DeleteNodes(ctx, ad.driver, _spec)
+ if err != nil && sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ ad.mutation.done = true
+ return affected, err
+}
+
+// AdminDeleteOne is the builder for deleting a single Admin entity.
+type AdminDeleteOne struct {
+ ad *AdminDelete
+}
+
+// Where appends a list predicates to the AdminDelete builder.
+func (ado *AdminDeleteOne) Where(ps ...predicate.Admin) *AdminDeleteOne {
+ ado.ad.mutation.Where(ps...)
+ return ado
+}
+
+// Exec executes the deletion query.
+func (ado *AdminDeleteOne) Exec(ctx context.Context) error {
+ n, err := ado.ad.Exec(ctx)
+ switch {
+ case err != nil:
+ return err
+ case n == 0:
+ return &NotFoundError{admin.Label}
+ default:
+ return nil
+ }
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (ado *AdminDeleteOne) ExecX(ctx context.Context) {
+ if err := ado.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
diff --git a/backend/db/admin_query.go b/backend/db/admin_query.go
new file mode 100644
index 0000000..b41db58
--- /dev/null
+++ b/backend/db/admin_query.go
@@ -0,0 +1,658 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "database/sql/driver"
+ "fmt"
+ "math"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect"
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/admin"
+ "github.com/chaitin/MonkeyCode/backend/db/adminloginhistory"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+ "github.com/google/uuid"
+)
+
+// AdminQuery is the builder for querying Admin entities.
+type AdminQuery struct {
+ config
+ ctx *QueryContext
+ order []admin.OrderOption
+ inters []Interceptor
+ predicates []predicate.Admin
+ withLoginHistories *AdminLoginHistoryQuery
+ modifiers []func(*sql.Selector)
+ // intermediate query (i.e. traversal path).
+ sql *sql.Selector
+ path func(context.Context) (*sql.Selector, error)
+}
+
+// Where adds a new predicate for the AdminQuery builder.
+func (aq *AdminQuery) Where(ps ...predicate.Admin) *AdminQuery {
+ aq.predicates = append(aq.predicates, ps...)
+ return aq
+}
+
+// Limit the number of records to be returned by this query.
+func (aq *AdminQuery) Limit(limit int) *AdminQuery {
+ aq.ctx.Limit = &limit
+ return aq
+}
+
+// Offset to start from.
+func (aq *AdminQuery) Offset(offset int) *AdminQuery {
+ aq.ctx.Offset = &offset
+ return aq
+}
+
+// Unique configures the query builder to filter duplicate records on query.
+// By default, unique is set to true, and can be disabled using this method.
+func (aq *AdminQuery) Unique(unique bool) *AdminQuery {
+ aq.ctx.Unique = &unique
+ return aq
+}
+
+// Order specifies how the records should be ordered.
+func (aq *AdminQuery) Order(o ...admin.OrderOption) *AdminQuery {
+ aq.order = append(aq.order, o...)
+ return aq
+}
+
+// QueryLoginHistories chains the current query on the "login_histories" edge.
+func (aq *AdminQuery) QueryLoginHistories() *AdminLoginHistoryQuery {
+ query := (&AdminLoginHistoryClient{config: aq.config}).Query()
+ query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
+ if err := aq.prepareQuery(ctx); err != nil {
+ return nil, err
+ }
+ selector := aq.sqlQuery(ctx)
+ if err := selector.Err(); err != nil {
+ return nil, err
+ }
+ step := sqlgraph.NewStep(
+ sqlgraph.From(admin.Table, admin.FieldID, selector),
+ sqlgraph.To(adminloginhistory.Table, adminloginhistory.FieldID),
+ sqlgraph.Edge(sqlgraph.O2M, false, admin.LoginHistoriesTable, admin.LoginHistoriesColumn),
+ )
+ fromU = sqlgraph.SetNeighbors(aq.driver.Dialect(), step)
+ return fromU, nil
+ }
+ return query
+}
+
+// First returns the first Admin entity from the query.
+// Returns a *NotFoundError when no Admin was found.
+func (aq *AdminQuery) First(ctx context.Context) (*Admin, error) {
+ nodes, err := aq.Limit(1).All(setContextOp(ctx, aq.ctx, ent.OpQueryFirst))
+ if err != nil {
+ return nil, err
+ }
+ if len(nodes) == 0 {
+ return nil, &NotFoundError{admin.Label}
+ }
+ return nodes[0], nil
+}
+
+// FirstX is like First, but panics if an error occurs.
+func (aq *AdminQuery) FirstX(ctx context.Context) *Admin {
+ node, err := aq.First(ctx)
+ if err != nil && !IsNotFound(err) {
+ panic(err)
+ }
+ return node
+}
+
+// FirstID returns the first Admin ID from the query.
+// Returns a *NotFoundError when no Admin ID was found.
+func (aq *AdminQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
+ var ids []uuid.UUID
+ if ids, err = aq.Limit(1).IDs(setContextOp(ctx, aq.ctx, ent.OpQueryFirstID)); err != nil {
+ return
+ }
+ if len(ids) == 0 {
+ err = &NotFoundError{admin.Label}
+ return
+ }
+ return ids[0], nil
+}
+
+// FirstIDX is like FirstID, but panics if an error occurs.
+func (aq *AdminQuery) FirstIDX(ctx context.Context) uuid.UUID {
+ id, err := aq.FirstID(ctx)
+ if err != nil && !IsNotFound(err) {
+ panic(err)
+ }
+ return id
+}
+
+// Only returns a single Admin entity found by the query, ensuring it only returns one.
+// Returns a *NotSingularError when more than one Admin entity is found.
+// Returns a *NotFoundError when no Admin entities are found.
+func (aq *AdminQuery) Only(ctx context.Context) (*Admin, error) {
+ nodes, err := aq.Limit(2).All(setContextOp(ctx, aq.ctx, ent.OpQueryOnly))
+ if err != nil {
+ return nil, err
+ }
+ switch len(nodes) {
+ case 1:
+ return nodes[0], nil
+ case 0:
+ return nil, &NotFoundError{admin.Label}
+ default:
+ return nil, &NotSingularError{admin.Label}
+ }
+}
+
+// OnlyX is like Only, but panics if an error occurs.
+func (aq *AdminQuery) OnlyX(ctx context.Context) *Admin {
+ node, err := aq.Only(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return node
+}
+
+// OnlyID is like Only, but returns the only Admin ID in the query.
+// Returns a *NotSingularError when more than one Admin ID is found.
+// Returns a *NotFoundError when no entities are found.
+func (aq *AdminQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
+ var ids []uuid.UUID
+ if ids, err = aq.Limit(2).IDs(setContextOp(ctx, aq.ctx, ent.OpQueryOnlyID)); err != nil {
+ return
+ }
+ switch len(ids) {
+ case 1:
+ id = ids[0]
+ case 0:
+ err = &NotFoundError{admin.Label}
+ default:
+ err = &NotSingularError{admin.Label}
+ }
+ return
+}
+
+// OnlyIDX is like OnlyID, but panics if an error occurs.
+func (aq *AdminQuery) OnlyIDX(ctx context.Context) uuid.UUID {
+ id, err := aq.OnlyID(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return id
+}
+
+// All executes the query and returns a list of Admins.
+func (aq *AdminQuery) All(ctx context.Context) ([]*Admin, error) {
+ ctx = setContextOp(ctx, aq.ctx, ent.OpQueryAll)
+ if err := aq.prepareQuery(ctx); err != nil {
+ return nil, err
+ }
+ qr := querierAll[[]*Admin, *AdminQuery]()
+ return withInterceptors[[]*Admin](ctx, aq, qr, aq.inters)
+}
+
+// AllX is like All, but panics if an error occurs.
+func (aq *AdminQuery) AllX(ctx context.Context) []*Admin {
+ nodes, err := aq.All(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return nodes
+}
+
+// IDs executes the query and returns a list of Admin IDs.
+func (aq *AdminQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) {
+ if aq.ctx.Unique == nil && aq.path != nil {
+ aq.Unique(true)
+ }
+ ctx = setContextOp(ctx, aq.ctx, ent.OpQueryIDs)
+ if err = aq.Select(admin.FieldID).Scan(ctx, &ids); err != nil {
+ return nil, err
+ }
+ return ids, nil
+}
+
+// IDsX is like IDs, but panics if an error occurs.
+func (aq *AdminQuery) IDsX(ctx context.Context) []uuid.UUID {
+ ids, err := aq.IDs(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return ids
+}
+
+// Count returns the count of the given query.
+func (aq *AdminQuery) Count(ctx context.Context) (int, error) {
+ ctx = setContextOp(ctx, aq.ctx, ent.OpQueryCount)
+ if err := aq.prepareQuery(ctx); err != nil {
+ return 0, err
+ }
+ return withInterceptors[int](ctx, aq, querierCount[*AdminQuery](), aq.inters)
+}
+
+// CountX is like Count, but panics if an error occurs.
+func (aq *AdminQuery) CountX(ctx context.Context) int {
+ count, err := aq.Count(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return count
+}
+
+// Exist returns true if the query has elements in the graph.
+func (aq *AdminQuery) Exist(ctx context.Context) (bool, error) {
+ ctx = setContextOp(ctx, aq.ctx, ent.OpQueryExist)
+ switch _, err := aq.FirstID(ctx); {
+ case IsNotFound(err):
+ return false, nil
+ case err != nil:
+ return false, fmt.Errorf("db: check existence: %w", err)
+ default:
+ return true, nil
+ }
+}
+
+// ExistX is like Exist, but panics if an error occurs.
+func (aq *AdminQuery) ExistX(ctx context.Context) bool {
+ exist, err := aq.Exist(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return exist
+}
+
+// Clone returns a duplicate of the AdminQuery builder, including all associated steps. It can be
+// used to prepare common query builders and use them differently after the clone is made.
+func (aq *AdminQuery) Clone() *AdminQuery {
+ if aq == nil {
+ return nil
+ }
+ return &AdminQuery{
+ config: aq.config,
+ ctx: aq.ctx.Clone(),
+ order: append([]admin.OrderOption{}, aq.order...),
+ inters: append([]Interceptor{}, aq.inters...),
+ predicates: append([]predicate.Admin{}, aq.predicates...),
+ withLoginHistories: aq.withLoginHistories.Clone(),
+ // clone intermediate query.
+ sql: aq.sql.Clone(),
+ path: aq.path,
+ modifiers: append([]func(*sql.Selector){}, aq.modifiers...),
+ }
+}
+
+// WithLoginHistories tells the query-builder to eager-load the nodes that are connected to
+// the "login_histories" edge. The optional arguments are used to configure the query builder of the edge.
+func (aq *AdminQuery) WithLoginHistories(opts ...func(*AdminLoginHistoryQuery)) *AdminQuery {
+ query := (&AdminLoginHistoryClient{config: aq.config}).Query()
+ for _, opt := range opts {
+ opt(query)
+ }
+ aq.withLoginHistories = query
+ return aq
+}
+
+// GroupBy is used to group vertices by one or more fields/columns.
+// It is often used with aggregate functions, like: count, max, mean, min, sum.
+//
+// Example:
+//
+// var v []struct {
+// Username string `json:"username,omitempty"`
+// Count int `json:"count,omitempty"`
+// }
+//
+// client.Admin.Query().
+// GroupBy(admin.FieldUsername).
+// Aggregate(db.Count()).
+// Scan(ctx, &v)
+func (aq *AdminQuery) GroupBy(field string, fields ...string) *AdminGroupBy {
+ aq.ctx.Fields = append([]string{field}, fields...)
+ grbuild := &AdminGroupBy{build: aq}
+ grbuild.flds = &aq.ctx.Fields
+ grbuild.label = admin.Label
+ grbuild.scan = grbuild.Scan
+ return grbuild
+}
+
+// Select allows the selection one or more fields/columns for the given query,
+// instead of selecting all fields in the entity.
+//
+// Example:
+//
+// var v []struct {
+// Username string `json:"username,omitempty"`
+// }
+//
+// client.Admin.Query().
+// Select(admin.FieldUsername).
+// Scan(ctx, &v)
+func (aq *AdminQuery) Select(fields ...string) *AdminSelect {
+ aq.ctx.Fields = append(aq.ctx.Fields, fields...)
+ sbuild := &AdminSelect{AdminQuery: aq}
+ sbuild.label = admin.Label
+ sbuild.flds, sbuild.scan = &aq.ctx.Fields, sbuild.Scan
+ return sbuild
+}
+
+// Aggregate returns a AdminSelect configured with the given aggregations.
+func (aq *AdminQuery) Aggregate(fns ...AggregateFunc) *AdminSelect {
+ return aq.Select().Aggregate(fns...)
+}
+
+func (aq *AdminQuery) prepareQuery(ctx context.Context) error {
+ for _, inter := range aq.inters {
+ if inter == nil {
+ return fmt.Errorf("db: uninitialized interceptor (forgotten import db/runtime?)")
+ }
+ if trv, ok := inter.(Traverser); ok {
+ if err := trv.Traverse(ctx, aq); err != nil {
+ return err
+ }
+ }
+ }
+ for _, f := range aq.ctx.Fields {
+ if !admin.ValidColumn(f) {
+ return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
+ }
+ }
+ if aq.path != nil {
+ prev, err := aq.path(ctx)
+ if err != nil {
+ return err
+ }
+ aq.sql = prev
+ }
+ return nil
+}
+
+func (aq *AdminQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Admin, error) {
+ var (
+ nodes = []*Admin{}
+ _spec = aq.querySpec()
+ loadedTypes = [1]bool{
+ aq.withLoginHistories != nil,
+ }
+ )
+ _spec.ScanValues = func(columns []string) ([]any, error) {
+ return (*Admin).scanValues(nil, columns)
+ }
+ _spec.Assign = func(columns []string, values []any) error {
+ node := &Admin{config: aq.config}
+ nodes = append(nodes, node)
+ node.Edges.loadedTypes = loadedTypes
+ return node.assignValues(columns, values)
+ }
+ if len(aq.modifiers) > 0 {
+ _spec.Modifiers = aq.modifiers
+ }
+ for i := range hooks {
+ hooks[i](ctx, _spec)
+ }
+ if err := sqlgraph.QueryNodes(ctx, aq.driver, _spec); err != nil {
+ return nil, err
+ }
+ if len(nodes) == 0 {
+ return nodes, nil
+ }
+ if query := aq.withLoginHistories; query != nil {
+ if err := aq.loadLoginHistories(ctx, query, nodes,
+ func(n *Admin) { n.Edges.LoginHistories = []*AdminLoginHistory{} },
+ func(n *Admin, e *AdminLoginHistory) { n.Edges.LoginHistories = append(n.Edges.LoginHistories, e) }); err != nil {
+ return nil, err
+ }
+ }
+ return nodes, nil
+}
+
+func (aq *AdminQuery) loadLoginHistories(ctx context.Context, query *AdminLoginHistoryQuery, nodes []*Admin, init func(*Admin), assign func(*Admin, *AdminLoginHistory)) error {
+ fks := make([]driver.Value, 0, len(nodes))
+ nodeids := make(map[uuid.UUID]*Admin)
+ for i := range nodes {
+ fks = append(fks, nodes[i].ID)
+ nodeids[nodes[i].ID] = nodes[i]
+ if init != nil {
+ init(nodes[i])
+ }
+ }
+ query.withFKs = true
+ query.Where(predicate.AdminLoginHistory(func(s *sql.Selector) {
+ s.Where(sql.InValues(s.C(admin.LoginHistoriesColumn), fks...))
+ }))
+ neighbors, err := query.All(ctx)
+ if err != nil {
+ return err
+ }
+ for _, n := range neighbors {
+ fk := n.admin_login_histories
+ if fk == nil {
+ return fmt.Errorf(`foreign-key "admin_login_histories" is nil for node %v`, n.ID)
+ }
+ node, ok := nodeids[*fk]
+ if !ok {
+ return fmt.Errorf(`unexpected referenced foreign-key "admin_login_histories" returned %v for node %v`, *fk, n.ID)
+ }
+ assign(node, n)
+ }
+ return nil
+}
+
+func (aq *AdminQuery) sqlCount(ctx context.Context) (int, error) {
+ _spec := aq.querySpec()
+ if len(aq.modifiers) > 0 {
+ _spec.Modifiers = aq.modifiers
+ }
+ _spec.Node.Columns = aq.ctx.Fields
+ if len(aq.ctx.Fields) > 0 {
+ _spec.Unique = aq.ctx.Unique != nil && *aq.ctx.Unique
+ }
+ return sqlgraph.CountNodes(ctx, aq.driver, _spec)
+}
+
+func (aq *AdminQuery) querySpec() *sqlgraph.QuerySpec {
+ _spec := sqlgraph.NewQuerySpec(admin.Table, admin.Columns, sqlgraph.NewFieldSpec(admin.FieldID, field.TypeUUID))
+ _spec.From = aq.sql
+ if unique := aq.ctx.Unique; unique != nil {
+ _spec.Unique = *unique
+ } else if aq.path != nil {
+ _spec.Unique = true
+ }
+ if fields := aq.ctx.Fields; len(fields) > 0 {
+ _spec.Node.Columns = make([]string, 0, len(fields))
+ _spec.Node.Columns = append(_spec.Node.Columns, admin.FieldID)
+ for i := range fields {
+ if fields[i] != admin.FieldID {
+ _spec.Node.Columns = append(_spec.Node.Columns, fields[i])
+ }
+ }
+ }
+ if ps := aq.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if limit := aq.ctx.Limit; limit != nil {
+ _spec.Limit = *limit
+ }
+ if offset := aq.ctx.Offset; offset != nil {
+ _spec.Offset = *offset
+ }
+ if ps := aq.order; len(ps) > 0 {
+ _spec.Order = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ return _spec
+}
+
+func (aq *AdminQuery) sqlQuery(ctx context.Context) *sql.Selector {
+ builder := sql.Dialect(aq.driver.Dialect())
+ t1 := builder.Table(admin.Table)
+ columns := aq.ctx.Fields
+ if len(columns) == 0 {
+ columns = admin.Columns
+ }
+ selector := builder.Select(t1.Columns(columns...)...).From(t1)
+ if aq.sql != nil {
+ selector = aq.sql
+ selector.Select(selector.Columns(columns...)...)
+ }
+ if aq.ctx.Unique != nil && *aq.ctx.Unique {
+ selector.Distinct()
+ }
+ for _, m := range aq.modifiers {
+ m(selector)
+ }
+ for _, p := range aq.predicates {
+ p(selector)
+ }
+ for _, p := range aq.order {
+ p(selector)
+ }
+ if offset := aq.ctx.Offset; offset != nil {
+ // limit is mandatory for offset clause. We start
+ // with default value, and override it below if needed.
+ selector.Offset(*offset).Limit(math.MaxInt32)
+ }
+ if limit := aq.ctx.Limit; limit != nil {
+ selector.Limit(*limit)
+ }
+ return selector
+}
+
+// ForUpdate locks the selected rows against concurrent updates, and prevent them from being
+// updated, deleted or "selected ... for update" by other sessions, until the transaction is
+// either committed or rolled-back.
+func (aq *AdminQuery) ForUpdate(opts ...sql.LockOption) *AdminQuery {
+ if aq.driver.Dialect() == dialect.Postgres {
+ aq.Unique(false)
+ }
+ aq.modifiers = append(aq.modifiers, func(s *sql.Selector) {
+ s.ForUpdate(opts...)
+ })
+ return aq
+}
+
+// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock
+// on any rows that are read. Other sessions can read the rows, but cannot modify them
+// until your transaction commits.
+func (aq *AdminQuery) ForShare(opts ...sql.LockOption) *AdminQuery {
+ if aq.driver.Dialect() == dialect.Postgres {
+ aq.Unique(false)
+ }
+ aq.modifiers = append(aq.modifiers, func(s *sql.Selector) {
+ s.ForShare(opts...)
+ })
+ return aq
+}
+
+// Modify adds a query modifier for attaching custom logic to queries.
+func (aq *AdminQuery) Modify(modifiers ...func(s *sql.Selector)) *AdminSelect {
+ aq.modifiers = append(aq.modifiers, modifiers...)
+ return aq.Select()
+}
+
+// AdminGroupBy is the group-by builder for Admin entities.
+type AdminGroupBy struct {
+ selector
+ build *AdminQuery
+}
+
+// Aggregate adds the given aggregation functions to the group-by query.
+func (agb *AdminGroupBy) Aggregate(fns ...AggregateFunc) *AdminGroupBy {
+ agb.fns = append(agb.fns, fns...)
+ return agb
+}
+
+// Scan applies the selector query and scans the result into the given value.
+func (agb *AdminGroupBy) Scan(ctx context.Context, v any) error {
+ ctx = setContextOp(ctx, agb.build.ctx, ent.OpQueryGroupBy)
+ if err := agb.build.prepareQuery(ctx); err != nil {
+ return err
+ }
+ return scanWithInterceptors[*AdminQuery, *AdminGroupBy](ctx, agb.build, agb, agb.build.inters, v)
+}
+
+func (agb *AdminGroupBy) sqlScan(ctx context.Context, root *AdminQuery, v any) error {
+ selector := root.sqlQuery(ctx).Select()
+ aggregation := make([]string, 0, len(agb.fns))
+ for _, fn := range agb.fns {
+ aggregation = append(aggregation, fn(selector))
+ }
+ if len(selector.SelectedColumns()) == 0 {
+ columns := make([]string, 0, len(*agb.flds)+len(agb.fns))
+ for _, f := range *agb.flds {
+ columns = append(columns, selector.C(f))
+ }
+ columns = append(columns, aggregation...)
+ selector.Select(columns...)
+ }
+ selector.GroupBy(selector.Columns(*agb.flds...)...)
+ if err := selector.Err(); err != nil {
+ return err
+ }
+ rows := &sql.Rows{}
+ query, args := selector.Query()
+ if err := agb.build.driver.Query(ctx, query, args, rows); err != nil {
+ return err
+ }
+ defer rows.Close()
+ return sql.ScanSlice(rows, v)
+}
+
+// AdminSelect is the builder for selecting fields of Admin entities.
+type AdminSelect struct {
+ *AdminQuery
+ selector
+}
+
+// Aggregate adds the given aggregation functions to the selector query.
+func (as *AdminSelect) Aggregate(fns ...AggregateFunc) *AdminSelect {
+ as.fns = append(as.fns, fns...)
+ return as
+}
+
+// Scan applies the selector query and scans the result into the given value.
+func (as *AdminSelect) Scan(ctx context.Context, v any) error {
+ ctx = setContextOp(ctx, as.ctx, ent.OpQuerySelect)
+ if err := as.prepareQuery(ctx); err != nil {
+ return err
+ }
+ return scanWithInterceptors[*AdminQuery, *AdminSelect](ctx, as.AdminQuery, as, as.inters, v)
+}
+
+func (as *AdminSelect) sqlScan(ctx context.Context, root *AdminQuery, v any) error {
+ selector := root.sqlQuery(ctx)
+ aggregation := make([]string, 0, len(as.fns))
+ for _, fn := range as.fns {
+ aggregation = append(aggregation, fn(selector))
+ }
+ switch n := len(*as.selector.flds); {
+ case n == 0 && len(aggregation) > 0:
+ selector.Select(aggregation...)
+ case n != 0 && len(aggregation) > 0:
+ selector.AppendSelect(aggregation...)
+ }
+ rows := &sql.Rows{}
+ query, args := selector.Query()
+ if err := as.driver.Query(ctx, query, args, rows); err != nil {
+ return err
+ }
+ defer rows.Close()
+ return sql.ScanSlice(rows, v)
+}
+
+// Modify adds a query modifier for attaching custom logic to queries.
+func (as *AdminSelect) Modify(modifiers ...func(s *sql.Selector)) *AdminSelect {
+ as.modifiers = append(as.modifiers, modifiers...)
+ return as
+}
diff --git a/backend/db/admin_update.go b/backend/db/admin_update.go
new file mode 100644
index 0000000..91280e2
--- /dev/null
+++ b/backend/db/admin_update.go
@@ -0,0 +1,563 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "time"
+
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/consts"
+ "github.com/chaitin/MonkeyCode/backend/db/admin"
+ "github.com/chaitin/MonkeyCode/backend/db/adminloginhistory"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+ "github.com/google/uuid"
+)
+
+// AdminUpdate is the builder for updating Admin entities.
+type AdminUpdate struct {
+ config
+ hooks []Hook
+ mutation *AdminMutation
+ modifiers []func(*sql.UpdateBuilder)
+}
+
+// Where appends a list predicates to the AdminUpdate builder.
+func (au *AdminUpdate) Where(ps ...predicate.Admin) *AdminUpdate {
+ au.mutation.Where(ps...)
+ return au
+}
+
+// SetUsername sets the "username" field.
+func (au *AdminUpdate) SetUsername(s string) *AdminUpdate {
+ au.mutation.SetUsername(s)
+ return au
+}
+
+// SetNillableUsername sets the "username" field if the given value is not nil.
+func (au *AdminUpdate) SetNillableUsername(s *string) *AdminUpdate {
+ if s != nil {
+ au.SetUsername(*s)
+ }
+ return au
+}
+
+// SetPassword sets the "password" field.
+func (au *AdminUpdate) SetPassword(s string) *AdminUpdate {
+ au.mutation.SetPassword(s)
+ return au
+}
+
+// SetNillablePassword sets the "password" field if the given value is not nil.
+func (au *AdminUpdate) SetNillablePassword(s *string) *AdminUpdate {
+ if s != nil {
+ au.SetPassword(*s)
+ }
+ return au
+}
+
+// SetStatus sets the "status" field.
+func (au *AdminUpdate) SetStatus(cs consts.AdminStatus) *AdminUpdate {
+ au.mutation.SetStatus(cs)
+ return au
+}
+
+// SetNillableStatus sets the "status" field if the given value is not nil.
+func (au *AdminUpdate) SetNillableStatus(cs *consts.AdminStatus) *AdminUpdate {
+ if cs != nil {
+ au.SetStatus(*cs)
+ }
+ return au
+}
+
+// SetLastActiveAt sets the "last_active_at" field.
+func (au *AdminUpdate) SetLastActiveAt(t time.Time) *AdminUpdate {
+ au.mutation.SetLastActiveAt(t)
+ return au
+}
+
+// SetNillableLastActiveAt sets the "last_active_at" field if the given value is not nil.
+func (au *AdminUpdate) SetNillableLastActiveAt(t *time.Time) *AdminUpdate {
+ if t != nil {
+ au.SetLastActiveAt(*t)
+ }
+ return au
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (au *AdminUpdate) SetCreatedAt(t time.Time) *AdminUpdate {
+ au.mutation.SetCreatedAt(t)
+ return au
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (au *AdminUpdate) SetNillableCreatedAt(t *time.Time) *AdminUpdate {
+ if t != nil {
+ au.SetCreatedAt(*t)
+ }
+ return au
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (au *AdminUpdate) SetUpdatedAt(t time.Time) *AdminUpdate {
+ au.mutation.SetUpdatedAt(t)
+ return au
+}
+
+// AddLoginHistoryIDs adds the "login_histories" edge to the AdminLoginHistory entity by IDs.
+func (au *AdminUpdate) AddLoginHistoryIDs(ids ...uuid.UUID) *AdminUpdate {
+ au.mutation.AddLoginHistoryIDs(ids...)
+ return au
+}
+
+// AddLoginHistories adds the "login_histories" edges to the AdminLoginHistory entity.
+func (au *AdminUpdate) AddLoginHistories(a ...*AdminLoginHistory) *AdminUpdate {
+ ids := make([]uuid.UUID, len(a))
+ for i := range a {
+ ids[i] = a[i].ID
+ }
+ return au.AddLoginHistoryIDs(ids...)
+}
+
+// Mutation returns the AdminMutation object of the builder.
+func (au *AdminUpdate) Mutation() *AdminMutation {
+ return au.mutation
+}
+
+// ClearLoginHistories clears all "login_histories" edges to the AdminLoginHistory entity.
+func (au *AdminUpdate) ClearLoginHistories() *AdminUpdate {
+ au.mutation.ClearLoginHistories()
+ return au
+}
+
+// RemoveLoginHistoryIDs removes the "login_histories" edge to AdminLoginHistory entities by IDs.
+func (au *AdminUpdate) RemoveLoginHistoryIDs(ids ...uuid.UUID) *AdminUpdate {
+ au.mutation.RemoveLoginHistoryIDs(ids...)
+ return au
+}
+
+// RemoveLoginHistories removes "login_histories" edges to AdminLoginHistory entities.
+func (au *AdminUpdate) RemoveLoginHistories(a ...*AdminLoginHistory) *AdminUpdate {
+ ids := make([]uuid.UUID, len(a))
+ for i := range a {
+ ids[i] = a[i].ID
+ }
+ return au.RemoveLoginHistoryIDs(ids...)
+}
+
+// Save executes the query and returns the number of nodes affected by the update operation.
+func (au *AdminUpdate) Save(ctx context.Context) (int, error) {
+ au.defaults()
+ return withHooks(ctx, au.sqlSave, au.mutation, au.hooks)
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (au *AdminUpdate) SaveX(ctx context.Context) int {
+ affected, err := au.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return affected
+}
+
+// Exec executes the query.
+func (au *AdminUpdate) Exec(ctx context.Context) error {
+ _, err := au.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (au *AdminUpdate) ExecX(ctx context.Context) {
+ if err := au.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// defaults sets the default values of the builder before save.
+func (au *AdminUpdate) defaults() {
+ if _, ok := au.mutation.UpdatedAt(); !ok {
+ v := admin.UpdateDefaultUpdatedAt()
+ au.mutation.SetUpdatedAt(v)
+ }
+}
+
+// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
+func (au *AdminUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *AdminUpdate {
+ au.modifiers = append(au.modifiers, modifiers...)
+ return au
+}
+
+func (au *AdminUpdate) sqlSave(ctx context.Context) (n int, err error) {
+ _spec := sqlgraph.NewUpdateSpec(admin.Table, admin.Columns, sqlgraph.NewFieldSpec(admin.FieldID, field.TypeUUID))
+ if ps := au.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if value, ok := au.mutation.Username(); ok {
+ _spec.SetField(admin.FieldUsername, field.TypeString, value)
+ }
+ if value, ok := au.mutation.Password(); ok {
+ _spec.SetField(admin.FieldPassword, field.TypeString, value)
+ }
+ if value, ok := au.mutation.Status(); ok {
+ _spec.SetField(admin.FieldStatus, field.TypeString, value)
+ }
+ if value, ok := au.mutation.LastActiveAt(); ok {
+ _spec.SetField(admin.FieldLastActiveAt, field.TypeTime, value)
+ }
+ if value, ok := au.mutation.CreatedAt(); ok {
+ _spec.SetField(admin.FieldCreatedAt, field.TypeTime, value)
+ }
+ if value, ok := au.mutation.UpdatedAt(); ok {
+ _spec.SetField(admin.FieldUpdatedAt, field.TypeTime, value)
+ }
+ if au.mutation.LoginHistoriesCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: admin.LoginHistoriesTable,
+ Columns: []string{admin.LoginHistoriesColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(adminloginhistory.FieldID, field.TypeUUID),
+ },
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := au.mutation.RemovedLoginHistoriesIDs(); len(nodes) > 0 && !au.mutation.LoginHistoriesCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: admin.LoginHistoriesTable,
+ Columns: []string{admin.LoginHistoriesColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(adminloginhistory.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := au.mutation.LoginHistoriesIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: admin.LoginHistoriesTable,
+ Columns: []string{admin.LoginHistoriesColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(adminloginhistory.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Add = append(_spec.Edges.Add, edge)
+ }
+ _spec.AddModifiers(au.modifiers...)
+ if n, err = sqlgraph.UpdateNodes(ctx, au.driver, _spec); err != nil {
+ if _, ok := err.(*sqlgraph.NotFoundError); ok {
+ err = &NotFoundError{admin.Label}
+ } else if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return 0, err
+ }
+ au.mutation.done = true
+ return n, nil
+}
+
+// AdminUpdateOne is the builder for updating a single Admin entity.
+type AdminUpdateOne struct {
+ config
+ fields []string
+ hooks []Hook
+ mutation *AdminMutation
+ modifiers []func(*sql.UpdateBuilder)
+}
+
+// SetUsername sets the "username" field.
+func (auo *AdminUpdateOne) SetUsername(s string) *AdminUpdateOne {
+ auo.mutation.SetUsername(s)
+ return auo
+}
+
+// SetNillableUsername sets the "username" field if the given value is not nil.
+func (auo *AdminUpdateOne) SetNillableUsername(s *string) *AdminUpdateOne {
+ if s != nil {
+ auo.SetUsername(*s)
+ }
+ return auo
+}
+
+// SetPassword sets the "password" field.
+func (auo *AdminUpdateOne) SetPassword(s string) *AdminUpdateOne {
+ auo.mutation.SetPassword(s)
+ return auo
+}
+
+// SetNillablePassword sets the "password" field if the given value is not nil.
+func (auo *AdminUpdateOne) SetNillablePassword(s *string) *AdminUpdateOne {
+ if s != nil {
+ auo.SetPassword(*s)
+ }
+ return auo
+}
+
+// SetStatus sets the "status" field.
+func (auo *AdminUpdateOne) SetStatus(cs consts.AdminStatus) *AdminUpdateOne {
+ auo.mutation.SetStatus(cs)
+ return auo
+}
+
+// SetNillableStatus sets the "status" field if the given value is not nil.
+func (auo *AdminUpdateOne) SetNillableStatus(cs *consts.AdminStatus) *AdminUpdateOne {
+ if cs != nil {
+ auo.SetStatus(*cs)
+ }
+ return auo
+}
+
+// SetLastActiveAt sets the "last_active_at" field.
+func (auo *AdminUpdateOne) SetLastActiveAt(t time.Time) *AdminUpdateOne {
+ auo.mutation.SetLastActiveAt(t)
+ return auo
+}
+
+// SetNillableLastActiveAt sets the "last_active_at" field if the given value is not nil.
+func (auo *AdminUpdateOne) SetNillableLastActiveAt(t *time.Time) *AdminUpdateOne {
+ if t != nil {
+ auo.SetLastActiveAt(*t)
+ }
+ return auo
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (auo *AdminUpdateOne) SetCreatedAt(t time.Time) *AdminUpdateOne {
+ auo.mutation.SetCreatedAt(t)
+ return auo
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (auo *AdminUpdateOne) SetNillableCreatedAt(t *time.Time) *AdminUpdateOne {
+ if t != nil {
+ auo.SetCreatedAt(*t)
+ }
+ return auo
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (auo *AdminUpdateOne) SetUpdatedAt(t time.Time) *AdminUpdateOne {
+ auo.mutation.SetUpdatedAt(t)
+ return auo
+}
+
+// AddLoginHistoryIDs adds the "login_histories" edge to the AdminLoginHistory entity by IDs.
+func (auo *AdminUpdateOne) AddLoginHistoryIDs(ids ...uuid.UUID) *AdminUpdateOne {
+ auo.mutation.AddLoginHistoryIDs(ids...)
+ return auo
+}
+
+// AddLoginHistories adds the "login_histories" edges to the AdminLoginHistory entity.
+func (auo *AdminUpdateOne) AddLoginHistories(a ...*AdminLoginHistory) *AdminUpdateOne {
+ ids := make([]uuid.UUID, len(a))
+ for i := range a {
+ ids[i] = a[i].ID
+ }
+ return auo.AddLoginHistoryIDs(ids...)
+}
+
+// Mutation returns the AdminMutation object of the builder.
+func (auo *AdminUpdateOne) Mutation() *AdminMutation {
+ return auo.mutation
+}
+
+// ClearLoginHistories clears all "login_histories" edges to the AdminLoginHistory entity.
+func (auo *AdminUpdateOne) ClearLoginHistories() *AdminUpdateOne {
+ auo.mutation.ClearLoginHistories()
+ return auo
+}
+
+// RemoveLoginHistoryIDs removes the "login_histories" edge to AdminLoginHistory entities by IDs.
+func (auo *AdminUpdateOne) RemoveLoginHistoryIDs(ids ...uuid.UUID) *AdminUpdateOne {
+ auo.mutation.RemoveLoginHistoryIDs(ids...)
+ return auo
+}
+
+// RemoveLoginHistories removes "login_histories" edges to AdminLoginHistory entities.
+func (auo *AdminUpdateOne) RemoveLoginHistories(a ...*AdminLoginHistory) *AdminUpdateOne {
+ ids := make([]uuid.UUID, len(a))
+ for i := range a {
+ ids[i] = a[i].ID
+ }
+ return auo.RemoveLoginHistoryIDs(ids...)
+}
+
+// Where appends a list predicates to the AdminUpdate builder.
+func (auo *AdminUpdateOne) Where(ps ...predicate.Admin) *AdminUpdateOne {
+ auo.mutation.Where(ps...)
+ return auo
+}
+
+// Select allows selecting one or more fields (columns) of the returned entity.
+// The default is selecting all fields defined in the entity schema.
+func (auo *AdminUpdateOne) Select(field string, fields ...string) *AdminUpdateOne {
+ auo.fields = append([]string{field}, fields...)
+ return auo
+}
+
+// Save executes the query and returns the updated Admin entity.
+func (auo *AdminUpdateOne) Save(ctx context.Context) (*Admin, error) {
+ auo.defaults()
+ return withHooks(ctx, auo.sqlSave, auo.mutation, auo.hooks)
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (auo *AdminUpdateOne) SaveX(ctx context.Context) *Admin {
+ node, err := auo.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return node
+}
+
+// Exec executes the query on the entity.
+func (auo *AdminUpdateOne) Exec(ctx context.Context) error {
+ _, err := auo.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (auo *AdminUpdateOne) ExecX(ctx context.Context) {
+ if err := auo.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// defaults sets the default values of the builder before save.
+func (auo *AdminUpdateOne) defaults() {
+ if _, ok := auo.mutation.UpdatedAt(); !ok {
+ v := admin.UpdateDefaultUpdatedAt()
+ auo.mutation.SetUpdatedAt(v)
+ }
+}
+
+// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
+func (auo *AdminUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *AdminUpdateOne {
+ auo.modifiers = append(auo.modifiers, modifiers...)
+ return auo
+}
+
+func (auo *AdminUpdateOne) sqlSave(ctx context.Context) (_node *Admin, err error) {
+ _spec := sqlgraph.NewUpdateSpec(admin.Table, admin.Columns, sqlgraph.NewFieldSpec(admin.FieldID, field.TypeUUID))
+ id, ok := auo.mutation.ID()
+ if !ok {
+ return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "Admin.id" for update`)}
+ }
+ _spec.Node.ID.Value = id
+ if fields := auo.fields; len(fields) > 0 {
+ _spec.Node.Columns = make([]string, 0, len(fields))
+ _spec.Node.Columns = append(_spec.Node.Columns, admin.FieldID)
+ for _, f := range fields {
+ if !admin.ValidColumn(f) {
+ return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
+ }
+ if f != admin.FieldID {
+ _spec.Node.Columns = append(_spec.Node.Columns, f)
+ }
+ }
+ }
+ if ps := auo.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if value, ok := auo.mutation.Username(); ok {
+ _spec.SetField(admin.FieldUsername, field.TypeString, value)
+ }
+ if value, ok := auo.mutation.Password(); ok {
+ _spec.SetField(admin.FieldPassword, field.TypeString, value)
+ }
+ if value, ok := auo.mutation.Status(); ok {
+ _spec.SetField(admin.FieldStatus, field.TypeString, value)
+ }
+ if value, ok := auo.mutation.LastActiveAt(); ok {
+ _spec.SetField(admin.FieldLastActiveAt, field.TypeTime, value)
+ }
+ if value, ok := auo.mutation.CreatedAt(); ok {
+ _spec.SetField(admin.FieldCreatedAt, field.TypeTime, value)
+ }
+ if value, ok := auo.mutation.UpdatedAt(); ok {
+ _spec.SetField(admin.FieldUpdatedAt, field.TypeTime, value)
+ }
+ if auo.mutation.LoginHistoriesCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: admin.LoginHistoriesTable,
+ Columns: []string{admin.LoginHistoriesColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(adminloginhistory.FieldID, field.TypeUUID),
+ },
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := auo.mutation.RemovedLoginHistoriesIDs(); len(nodes) > 0 && !auo.mutation.LoginHistoriesCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: admin.LoginHistoriesTable,
+ Columns: []string{admin.LoginHistoriesColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(adminloginhistory.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := auo.mutation.LoginHistoriesIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: admin.LoginHistoriesTable,
+ Columns: []string{admin.LoginHistoriesColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(adminloginhistory.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Add = append(_spec.Edges.Add, edge)
+ }
+ _spec.AddModifiers(auo.modifiers...)
+ _node = &Admin{config: auo.config}
+ _spec.Assign = _node.assignValues
+ _spec.ScanValues = _node.scanValues
+ if err = sqlgraph.UpdateNode(ctx, auo.driver, _spec); err != nil {
+ if _, ok := err.(*sqlgraph.NotFoundError); ok {
+ err = &NotFoundError{admin.Label}
+ } else if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return nil, err
+ }
+ auo.mutation.done = true
+ return _node, nil
+}
diff --git a/backend/db/adminloginhistory.go b/backend/db/adminloginhistory.go
new file mode 100644
index 0000000..283b4b0
--- /dev/null
+++ b/backend/db/adminloginhistory.go
@@ -0,0 +1,245 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "fmt"
+ "strings"
+ "time"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect/sql"
+ "github.com/chaitin/MonkeyCode/backend/db/admin"
+ "github.com/chaitin/MonkeyCode/backend/db/adminloginhistory"
+ "github.com/google/uuid"
+)
+
+// AdminLoginHistory is the model entity for the AdminLoginHistory schema.
+type AdminLoginHistory struct {
+ config `json:"-"`
+ // ID of the ent.
+ ID uuid.UUID `json:"id,omitempty"`
+ // AdminID holds the value of the "admin_id" field.
+ AdminID uuid.UUID `json:"admin_id,omitempty"`
+ // IP holds the value of the "ip" field.
+ IP string `json:"ip,omitempty"`
+ // Country holds the value of the "country" field.
+ Country string `json:"country,omitempty"`
+ // Province holds the value of the "province" field.
+ Province string `json:"province,omitempty"`
+ // City holds the value of the "city" field.
+ City string `json:"city,omitempty"`
+ // Isp holds the value of the "isp" field.
+ Isp string `json:"isp,omitempty"`
+ // Asn holds the value of the "asn" field.
+ Asn string `json:"asn,omitempty"`
+ // ClientVersion holds the value of the "client_version" field.
+ ClientVersion string `json:"client_version,omitempty"`
+ // Device holds the value of the "device" field.
+ Device string `json:"device,omitempty"`
+ // CreatedAt holds the value of the "created_at" field.
+ CreatedAt time.Time `json:"created_at,omitempty"`
+ // Edges holds the relations/edges for other nodes in the graph.
+ // The values are being populated by the AdminLoginHistoryQuery when eager-loading is set.
+ Edges AdminLoginHistoryEdges `json:"edges"`
+ admin_login_histories *uuid.UUID
+ selectValues sql.SelectValues
+}
+
+// AdminLoginHistoryEdges holds the relations/edges for other nodes in the graph.
+type AdminLoginHistoryEdges struct {
+ // Owner holds the value of the owner edge.
+ Owner *Admin `json:"owner,omitempty"`
+ // loadedTypes holds the information for reporting if a
+ // type was loaded (or requested) in eager-loading or not.
+ loadedTypes [1]bool
+}
+
+// OwnerOrErr returns the Owner value or an error if the edge
+// was not loaded in eager-loading, or loaded but was not found.
+func (e AdminLoginHistoryEdges) OwnerOrErr() (*Admin, error) {
+ if e.Owner != nil {
+ return e.Owner, nil
+ } else if e.loadedTypes[0] {
+ return nil, &NotFoundError{label: admin.Label}
+ }
+ return nil, &NotLoadedError{edge: "owner"}
+}
+
+// scanValues returns the types for scanning values from sql.Rows.
+func (*AdminLoginHistory) scanValues(columns []string) ([]any, error) {
+ values := make([]any, len(columns))
+ for i := range columns {
+ switch columns[i] {
+ case adminloginhistory.FieldIP, adminloginhistory.FieldCountry, adminloginhistory.FieldProvince, adminloginhistory.FieldCity, adminloginhistory.FieldIsp, adminloginhistory.FieldAsn, adminloginhistory.FieldClientVersion, adminloginhistory.FieldDevice:
+ values[i] = new(sql.NullString)
+ case adminloginhistory.FieldCreatedAt:
+ values[i] = new(sql.NullTime)
+ case adminloginhistory.FieldID, adminloginhistory.FieldAdminID:
+ values[i] = new(uuid.UUID)
+ case adminloginhistory.ForeignKeys[0]: // admin_login_histories
+ values[i] = &sql.NullScanner{S: new(uuid.UUID)}
+ default:
+ values[i] = new(sql.UnknownType)
+ }
+ }
+ return values, nil
+}
+
+// assignValues assigns the values that were returned from sql.Rows (after scanning)
+// to the AdminLoginHistory fields.
+func (alh *AdminLoginHistory) assignValues(columns []string, values []any) error {
+ if m, n := len(values), len(columns); m < n {
+ return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
+ }
+ for i := range columns {
+ switch columns[i] {
+ case adminloginhistory.FieldID:
+ if value, ok := values[i].(*uuid.UUID); !ok {
+ return fmt.Errorf("unexpected type %T for field id", values[i])
+ } else if value != nil {
+ alh.ID = *value
+ }
+ case adminloginhistory.FieldAdminID:
+ if value, ok := values[i].(*uuid.UUID); !ok {
+ return fmt.Errorf("unexpected type %T for field admin_id", values[i])
+ } else if value != nil {
+ alh.AdminID = *value
+ }
+ case adminloginhistory.FieldIP:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field ip", values[i])
+ } else if value.Valid {
+ alh.IP = value.String
+ }
+ case adminloginhistory.FieldCountry:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field country", values[i])
+ } else if value.Valid {
+ alh.Country = value.String
+ }
+ case adminloginhistory.FieldProvince:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field province", values[i])
+ } else if value.Valid {
+ alh.Province = value.String
+ }
+ case adminloginhistory.FieldCity:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field city", values[i])
+ } else if value.Valid {
+ alh.City = value.String
+ }
+ case adminloginhistory.FieldIsp:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field isp", values[i])
+ } else if value.Valid {
+ alh.Isp = value.String
+ }
+ case adminloginhistory.FieldAsn:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field asn", values[i])
+ } else if value.Valid {
+ alh.Asn = value.String
+ }
+ case adminloginhistory.FieldClientVersion:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field client_version", values[i])
+ } else if value.Valid {
+ alh.ClientVersion = value.String
+ }
+ case adminloginhistory.FieldDevice:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field device", values[i])
+ } else if value.Valid {
+ alh.Device = value.String
+ }
+ case adminloginhistory.FieldCreatedAt:
+ if value, ok := values[i].(*sql.NullTime); !ok {
+ return fmt.Errorf("unexpected type %T for field created_at", values[i])
+ } else if value.Valid {
+ alh.CreatedAt = value.Time
+ }
+ case adminloginhistory.ForeignKeys[0]:
+ if value, ok := values[i].(*sql.NullScanner); !ok {
+ return fmt.Errorf("unexpected type %T for field admin_login_histories", values[i])
+ } else if value.Valid {
+ alh.admin_login_histories = new(uuid.UUID)
+ *alh.admin_login_histories = *value.S.(*uuid.UUID)
+ }
+ default:
+ alh.selectValues.Set(columns[i], values[i])
+ }
+ }
+ return nil
+}
+
+// Value returns the ent.Value that was dynamically selected and assigned to the AdminLoginHistory.
+// This includes values selected through modifiers, order, etc.
+func (alh *AdminLoginHistory) Value(name string) (ent.Value, error) {
+ return alh.selectValues.Get(name)
+}
+
+// QueryOwner queries the "owner" edge of the AdminLoginHistory entity.
+func (alh *AdminLoginHistory) QueryOwner() *AdminQuery {
+ return NewAdminLoginHistoryClient(alh.config).QueryOwner(alh)
+}
+
+// Update returns a builder for updating this AdminLoginHistory.
+// Note that you need to call AdminLoginHistory.Unwrap() before calling this method if this AdminLoginHistory
+// was returned from a transaction, and the transaction was committed or rolled back.
+func (alh *AdminLoginHistory) Update() *AdminLoginHistoryUpdateOne {
+ return NewAdminLoginHistoryClient(alh.config).UpdateOne(alh)
+}
+
+// Unwrap unwraps the AdminLoginHistory entity that was returned from a transaction after it was closed,
+// so that all future queries will be executed through the driver which created the transaction.
+func (alh *AdminLoginHistory) Unwrap() *AdminLoginHistory {
+ _tx, ok := alh.config.driver.(*txDriver)
+ if !ok {
+ panic("db: AdminLoginHistory is not a transactional entity")
+ }
+ alh.config.driver = _tx.drv
+ return alh
+}
+
+// String implements the fmt.Stringer.
+func (alh *AdminLoginHistory) String() string {
+ var builder strings.Builder
+ builder.WriteString("AdminLoginHistory(")
+ builder.WriteString(fmt.Sprintf("id=%v, ", alh.ID))
+ builder.WriteString("admin_id=")
+ builder.WriteString(fmt.Sprintf("%v", alh.AdminID))
+ builder.WriteString(", ")
+ builder.WriteString("ip=")
+ builder.WriteString(alh.IP)
+ builder.WriteString(", ")
+ builder.WriteString("country=")
+ builder.WriteString(alh.Country)
+ builder.WriteString(", ")
+ builder.WriteString("province=")
+ builder.WriteString(alh.Province)
+ builder.WriteString(", ")
+ builder.WriteString("city=")
+ builder.WriteString(alh.City)
+ builder.WriteString(", ")
+ builder.WriteString("isp=")
+ builder.WriteString(alh.Isp)
+ builder.WriteString(", ")
+ builder.WriteString("asn=")
+ builder.WriteString(alh.Asn)
+ builder.WriteString(", ")
+ builder.WriteString("client_version=")
+ builder.WriteString(alh.ClientVersion)
+ builder.WriteString(", ")
+ builder.WriteString("device=")
+ builder.WriteString(alh.Device)
+ builder.WriteString(", ")
+ builder.WriteString("created_at=")
+ builder.WriteString(alh.CreatedAt.Format(time.ANSIC))
+ builder.WriteByte(')')
+ return builder.String()
+}
+
+// AdminLoginHistories is a parsable slice of AdminLoginHistory.
+type AdminLoginHistories []*AdminLoginHistory
diff --git a/backend/db/adminloginhistory/adminloginhistory.go b/backend/db/adminloginhistory/adminloginhistory.go
new file mode 100644
index 0000000..720b07a
--- /dev/null
+++ b/backend/db/adminloginhistory/adminloginhistory.go
@@ -0,0 +1,161 @@
+// Code generated by ent, DO NOT EDIT.
+
+package adminloginhistory
+
+import (
+ "time"
+
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+)
+
+const (
+ // Label holds the string label denoting the adminloginhistory type in the database.
+ Label = "admin_login_history"
+ // FieldID holds the string denoting the id field in the database.
+ FieldID = "id"
+ // FieldAdminID holds the string denoting the admin_id field in the database.
+ FieldAdminID = "admin_id"
+ // FieldIP holds the string denoting the ip field in the database.
+ FieldIP = "ip"
+ // FieldCountry holds the string denoting the country field in the database.
+ FieldCountry = "country"
+ // FieldProvince holds the string denoting the province field in the database.
+ FieldProvince = "province"
+ // FieldCity holds the string denoting the city field in the database.
+ FieldCity = "city"
+ // FieldIsp holds the string denoting the isp field in the database.
+ FieldIsp = "isp"
+ // FieldAsn holds the string denoting the asn field in the database.
+ FieldAsn = "asn"
+ // FieldClientVersion holds the string denoting the client_version field in the database.
+ FieldClientVersion = "client_version"
+ // FieldDevice holds the string denoting the device field in the database.
+ FieldDevice = "device"
+ // FieldCreatedAt holds the string denoting the created_at field in the database.
+ FieldCreatedAt = "created_at"
+ // EdgeOwner holds the string denoting the owner edge name in mutations.
+ EdgeOwner = "owner"
+ // Table holds the table name of the adminloginhistory in the database.
+ Table = "admin_login_histories"
+ // OwnerTable is the table that holds the owner relation/edge.
+ OwnerTable = "admin_login_histories"
+ // OwnerInverseTable is the table name for the Admin entity.
+ // It exists in this package in order to avoid circular dependency with the "admin" package.
+ OwnerInverseTable = "admins"
+ // OwnerColumn is the table column denoting the owner relation/edge.
+ OwnerColumn = "admin_login_histories"
+)
+
+// Columns holds all SQL columns for adminloginhistory fields.
+var Columns = []string{
+ FieldID,
+ FieldAdminID,
+ FieldIP,
+ FieldCountry,
+ FieldProvince,
+ FieldCity,
+ FieldIsp,
+ FieldAsn,
+ FieldClientVersion,
+ FieldDevice,
+ FieldCreatedAt,
+}
+
+// ForeignKeys holds the SQL foreign-keys that are owned by the "admin_login_histories"
+// table and are not defined as standalone fields in the schema.
+var ForeignKeys = []string{
+ "admin_login_histories",
+}
+
+// ValidColumn reports if the column name is valid (part of the table columns).
+func ValidColumn(column string) bool {
+ for i := range Columns {
+ if column == Columns[i] {
+ return true
+ }
+ }
+ for i := range ForeignKeys {
+ if column == ForeignKeys[i] {
+ return true
+ }
+ }
+ return false
+}
+
+var (
+ // DefaultCreatedAt holds the default value on creation for the "created_at" field.
+ DefaultCreatedAt func() time.Time
+)
+
+// OrderOption defines the ordering options for the AdminLoginHistory queries.
+type OrderOption func(*sql.Selector)
+
+// ByID orders the results by the id field.
+func ByID(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldID, opts...).ToFunc()
+}
+
+// ByAdminID orders the results by the admin_id field.
+func ByAdminID(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldAdminID, opts...).ToFunc()
+}
+
+// ByIP orders the results by the ip field.
+func ByIP(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldIP, opts...).ToFunc()
+}
+
+// ByCountry orders the results by the country field.
+func ByCountry(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldCountry, opts...).ToFunc()
+}
+
+// ByProvince orders the results by the province field.
+func ByProvince(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldProvince, opts...).ToFunc()
+}
+
+// ByCity orders the results by the city field.
+func ByCity(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldCity, opts...).ToFunc()
+}
+
+// ByIsp orders the results by the isp field.
+func ByIsp(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldIsp, opts...).ToFunc()
+}
+
+// ByAsn orders the results by the asn field.
+func ByAsn(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldAsn, opts...).ToFunc()
+}
+
+// ByClientVersion orders the results by the client_version field.
+func ByClientVersion(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldClientVersion, opts...).ToFunc()
+}
+
+// ByDevice orders the results by the device field.
+func ByDevice(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldDevice, opts...).ToFunc()
+}
+
+// ByCreatedAt orders the results by the created_at field.
+func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
+}
+
+// ByOwnerField orders the results by owner field.
+func ByOwnerField(field string, opts ...sql.OrderTermOption) OrderOption {
+ return func(s *sql.Selector) {
+ sqlgraph.OrderByNeighborTerms(s, newOwnerStep(), sql.OrderByField(field, opts...))
+ }
+}
+func newOwnerStep() *sqlgraph.Step {
+ return sqlgraph.NewStep(
+ sqlgraph.From(Table, FieldID),
+ sqlgraph.To(OwnerInverseTable, FieldID),
+ sqlgraph.Edge(sqlgraph.M2O, true, OwnerTable, OwnerColumn),
+ )
+}
diff --git a/backend/db/adminloginhistory/where.go b/backend/db/adminloginhistory/where.go
new file mode 100644
index 0000000..910ad33
--- /dev/null
+++ b/backend/db/adminloginhistory/where.go
@@ -0,0 +1,745 @@
+// Code generated by ent, DO NOT EDIT.
+
+package adminloginhistory
+
+import (
+ "time"
+
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+ "github.com/google/uuid"
+)
+
+// ID filters vertices based on their ID field.
+func ID(id uuid.UUID) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldEQ(FieldID, id))
+}
+
+// IDEQ applies the EQ predicate on the ID field.
+func IDEQ(id uuid.UUID) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldEQ(FieldID, id))
+}
+
+// IDNEQ applies the NEQ predicate on the ID field.
+func IDNEQ(id uuid.UUID) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldNEQ(FieldID, id))
+}
+
+// IDIn applies the In predicate on the ID field.
+func IDIn(ids ...uuid.UUID) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldIn(FieldID, ids...))
+}
+
+// IDNotIn applies the NotIn predicate on the ID field.
+func IDNotIn(ids ...uuid.UUID) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldNotIn(FieldID, ids...))
+}
+
+// IDGT applies the GT predicate on the ID field.
+func IDGT(id uuid.UUID) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldGT(FieldID, id))
+}
+
+// IDGTE applies the GTE predicate on the ID field.
+func IDGTE(id uuid.UUID) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldGTE(FieldID, id))
+}
+
+// IDLT applies the LT predicate on the ID field.
+func IDLT(id uuid.UUID) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldLT(FieldID, id))
+}
+
+// IDLTE applies the LTE predicate on the ID field.
+func IDLTE(id uuid.UUID) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldLTE(FieldID, id))
+}
+
+// AdminID applies equality check predicate on the "admin_id" field. It's identical to AdminIDEQ.
+func AdminID(v uuid.UUID) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldEQ(FieldAdminID, v))
+}
+
+// IP applies equality check predicate on the "ip" field. It's identical to IPEQ.
+func IP(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldEQ(FieldIP, v))
+}
+
+// Country applies equality check predicate on the "country" field. It's identical to CountryEQ.
+func Country(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldEQ(FieldCountry, v))
+}
+
+// Province applies equality check predicate on the "province" field. It's identical to ProvinceEQ.
+func Province(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldEQ(FieldProvince, v))
+}
+
+// City applies equality check predicate on the "city" field. It's identical to CityEQ.
+func City(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldEQ(FieldCity, v))
+}
+
+// Isp applies equality check predicate on the "isp" field. It's identical to IspEQ.
+func Isp(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldEQ(FieldIsp, v))
+}
+
+// Asn applies equality check predicate on the "asn" field. It's identical to AsnEQ.
+func Asn(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldEQ(FieldAsn, v))
+}
+
+// ClientVersion applies equality check predicate on the "client_version" field. It's identical to ClientVersionEQ.
+func ClientVersion(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldEQ(FieldClientVersion, v))
+}
+
+// Device applies equality check predicate on the "device" field. It's identical to DeviceEQ.
+func Device(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldEQ(FieldDevice, v))
+}
+
+// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
+func CreatedAt(v time.Time) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldEQ(FieldCreatedAt, v))
+}
+
+// AdminIDEQ applies the EQ predicate on the "admin_id" field.
+func AdminIDEQ(v uuid.UUID) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldEQ(FieldAdminID, v))
+}
+
+// AdminIDNEQ applies the NEQ predicate on the "admin_id" field.
+func AdminIDNEQ(v uuid.UUID) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldNEQ(FieldAdminID, v))
+}
+
+// AdminIDIn applies the In predicate on the "admin_id" field.
+func AdminIDIn(vs ...uuid.UUID) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldIn(FieldAdminID, vs...))
+}
+
+// AdminIDNotIn applies the NotIn predicate on the "admin_id" field.
+func AdminIDNotIn(vs ...uuid.UUID) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldNotIn(FieldAdminID, vs...))
+}
+
+// AdminIDGT applies the GT predicate on the "admin_id" field.
+func AdminIDGT(v uuid.UUID) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldGT(FieldAdminID, v))
+}
+
+// AdminIDGTE applies the GTE predicate on the "admin_id" field.
+func AdminIDGTE(v uuid.UUID) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldGTE(FieldAdminID, v))
+}
+
+// AdminIDLT applies the LT predicate on the "admin_id" field.
+func AdminIDLT(v uuid.UUID) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldLT(FieldAdminID, v))
+}
+
+// AdminIDLTE applies the LTE predicate on the "admin_id" field.
+func AdminIDLTE(v uuid.UUID) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldLTE(FieldAdminID, v))
+}
+
+// IPEQ applies the EQ predicate on the "ip" field.
+func IPEQ(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldEQ(FieldIP, v))
+}
+
+// IPNEQ applies the NEQ predicate on the "ip" field.
+func IPNEQ(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldNEQ(FieldIP, v))
+}
+
+// IPIn applies the In predicate on the "ip" field.
+func IPIn(vs ...string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldIn(FieldIP, vs...))
+}
+
+// IPNotIn applies the NotIn predicate on the "ip" field.
+func IPNotIn(vs ...string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldNotIn(FieldIP, vs...))
+}
+
+// IPGT applies the GT predicate on the "ip" field.
+func IPGT(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldGT(FieldIP, v))
+}
+
+// IPGTE applies the GTE predicate on the "ip" field.
+func IPGTE(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldGTE(FieldIP, v))
+}
+
+// IPLT applies the LT predicate on the "ip" field.
+func IPLT(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldLT(FieldIP, v))
+}
+
+// IPLTE applies the LTE predicate on the "ip" field.
+func IPLTE(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldLTE(FieldIP, v))
+}
+
+// IPContains applies the Contains predicate on the "ip" field.
+func IPContains(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldContains(FieldIP, v))
+}
+
+// IPHasPrefix applies the HasPrefix predicate on the "ip" field.
+func IPHasPrefix(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldHasPrefix(FieldIP, v))
+}
+
+// IPHasSuffix applies the HasSuffix predicate on the "ip" field.
+func IPHasSuffix(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldHasSuffix(FieldIP, v))
+}
+
+// IPEqualFold applies the EqualFold predicate on the "ip" field.
+func IPEqualFold(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldEqualFold(FieldIP, v))
+}
+
+// IPContainsFold applies the ContainsFold predicate on the "ip" field.
+func IPContainsFold(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldContainsFold(FieldIP, v))
+}
+
+// CountryEQ applies the EQ predicate on the "country" field.
+func CountryEQ(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldEQ(FieldCountry, v))
+}
+
+// CountryNEQ applies the NEQ predicate on the "country" field.
+func CountryNEQ(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldNEQ(FieldCountry, v))
+}
+
+// CountryIn applies the In predicate on the "country" field.
+func CountryIn(vs ...string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldIn(FieldCountry, vs...))
+}
+
+// CountryNotIn applies the NotIn predicate on the "country" field.
+func CountryNotIn(vs ...string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldNotIn(FieldCountry, vs...))
+}
+
+// CountryGT applies the GT predicate on the "country" field.
+func CountryGT(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldGT(FieldCountry, v))
+}
+
+// CountryGTE applies the GTE predicate on the "country" field.
+func CountryGTE(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldGTE(FieldCountry, v))
+}
+
+// CountryLT applies the LT predicate on the "country" field.
+func CountryLT(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldLT(FieldCountry, v))
+}
+
+// CountryLTE applies the LTE predicate on the "country" field.
+func CountryLTE(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldLTE(FieldCountry, v))
+}
+
+// CountryContains applies the Contains predicate on the "country" field.
+func CountryContains(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldContains(FieldCountry, v))
+}
+
+// CountryHasPrefix applies the HasPrefix predicate on the "country" field.
+func CountryHasPrefix(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldHasPrefix(FieldCountry, v))
+}
+
+// CountryHasSuffix applies the HasSuffix predicate on the "country" field.
+func CountryHasSuffix(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldHasSuffix(FieldCountry, v))
+}
+
+// CountryEqualFold applies the EqualFold predicate on the "country" field.
+func CountryEqualFold(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldEqualFold(FieldCountry, v))
+}
+
+// CountryContainsFold applies the ContainsFold predicate on the "country" field.
+func CountryContainsFold(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldContainsFold(FieldCountry, v))
+}
+
+// ProvinceEQ applies the EQ predicate on the "province" field.
+func ProvinceEQ(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldEQ(FieldProvince, v))
+}
+
+// ProvinceNEQ applies the NEQ predicate on the "province" field.
+func ProvinceNEQ(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldNEQ(FieldProvince, v))
+}
+
+// ProvinceIn applies the In predicate on the "province" field.
+func ProvinceIn(vs ...string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldIn(FieldProvince, vs...))
+}
+
+// ProvinceNotIn applies the NotIn predicate on the "province" field.
+func ProvinceNotIn(vs ...string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldNotIn(FieldProvince, vs...))
+}
+
+// ProvinceGT applies the GT predicate on the "province" field.
+func ProvinceGT(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldGT(FieldProvince, v))
+}
+
+// ProvinceGTE applies the GTE predicate on the "province" field.
+func ProvinceGTE(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldGTE(FieldProvince, v))
+}
+
+// ProvinceLT applies the LT predicate on the "province" field.
+func ProvinceLT(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldLT(FieldProvince, v))
+}
+
+// ProvinceLTE applies the LTE predicate on the "province" field.
+func ProvinceLTE(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldLTE(FieldProvince, v))
+}
+
+// ProvinceContains applies the Contains predicate on the "province" field.
+func ProvinceContains(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldContains(FieldProvince, v))
+}
+
+// ProvinceHasPrefix applies the HasPrefix predicate on the "province" field.
+func ProvinceHasPrefix(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldHasPrefix(FieldProvince, v))
+}
+
+// ProvinceHasSuffix applies the HasSuffix predicate on the "province" field.
+func ProvinceHasSuffix(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldHasSuffix(FieldProvince, v))
+}
+
+// ProvinceEqualFold applies the EqualFold predicate on the "province" field.
+func ProvinceEqualFold(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldEqualFold(FieldProvince, v))
+}
+
+// ProvinceContainsFold applies the ContainsFold predicate on the "province" field.
+func ProvinceContainsFold(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldContainsFold(FieldProvince, v))
+}
+
+// CityEQ applies the EQ predicate on the "city" field.
+func CityEQ(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldEQ(FieldCity, v))
+}
+
+// CityNEQ applies the NEQ predicate on the "city" field.
+func CityNEQ(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldNEQ(FieldCity, v))
+}
+
+// CityIn applies the In predicate on the "city" field.
+func CityIn(vs ...string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldIn(FieldCity, vs...))
+}
+
+// CityNotIn applies the NotIn predicate on the "city" field.
+func CityNotIn(vs ...string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldNotIn(FieldCity, vs...))
+}
+
+// CityGT applies the GT predicate on the "city" field.
+func CityGT(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldGT(FieldCity, v))
+}
+
+// CityGTE applies the GTE predicate on the "city" field.
+func CityGTE(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldGTE(FieldCity, v))
+}
+
+// CityLT applies the LT predicate on the "city" field.
+func CityLT(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldLT(FieldCity, v))
+}
+
+// CityLTE applies the LTE predicate on the "city" field.
+func CityLTE(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldLTE(FieldCity, v))
+}
+
+// CityContains applies the Contains predicate on the "city" field.
+func CityContains(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldContains(FieldCity, v))
+}
+
+// CityHasPrefix applies the HasPrefix predicate on the "city" field.
+func CityHasPrefix(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldHasPrefix(FieldCity, v))
+}
+
+// CityHasSuffix applies the HasSuffix predicate on the "city" field.
+func CityHasSuffix(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldHasSuffix(FieldCity, v))
+}
+
+// CityEqualFold applies the EqualFold predicate on the "city" field.
+func CityEqualFold(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldEqualFold(FieldCity, v))
+}
+
+// CityContainsFold applies the ContainsFold predicate on the "city" field.
+func CityContainsFold(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldContainsFold(FieldCity, v))
+}
+
+// IspEQ applies the EQ predicate on the "isp" field.
+func IspEQ(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldEQ(FieldIsp, v))
+}
+
+// IspNEQ applies the NEQ predicate on the "isp" field.
+func IspNEQ(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldNEQ(FieldIsp, v))
+}
+
+// IspIn applies the In predicate on the "isp" field.
+func IspIn(vs ...string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldIn(FieldIsp, vs...))
+}
+
+// IspNotIn applies the NotIn predicate on the "isp" field.
+func IspNotIn(vs ...string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldNotIn(FieldIsp, vs...))
+}
+
+// IspGT applies the GT predicate on the "isp" field.
+func IspGT(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldGT(FieldIsp, v))
+}
+
+// IspGTE applies the GTE predicate on the "isp" field.
+func IspGTE(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldGTE(FieldIsp, v))
+}
+
+// IspLT applies the LT predicate on the "isp" field.
+func IspLT(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldLT(FieldIsp, v))
+}
+
+// IspLTE applies the LTE predicate on the "isp" field.
+func IspLTE(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldLTE(FieldIsp, v))
+}
+
+// IspContains applies the Contains predicate on the "isp" field.
+func IspContains(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldContains(FieldIsp, v))
+}
+
+// IspHasPrefix applies the HasPrefix predicate on the "isp" field.
+func IspHasPrefix(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldHasPrefix(FieldIsp, v))
+}
+
+// IspHasSuffix applies the HasSuffix predicate on the "isp" field.
+func IspHasSuffix(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldHasSuffix(FieldIsp, v))
+}
+
+// IspEqualFold applies the EqualFold predicate on the "isp" field.
+func IspEqualFold(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldEqualFold(FieldIsp, v))
+}
+
+// IspContainsFold applies the ContainsFold predicate on the "isp" field.
+func IspContainsFold(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldContainsFold(FieldIsp, v))
+}
+
+// AsnEQ applies the EQ predicate on the "asn" field.
+func AsnEQ(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldEQ(FieldAsn, v))
+}
+
+// AsnNEQ applies the NEQ predicate on the "asn" field.
+func AsnNEQ(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldNEQ(FieldAsn, v))
+}
+
+// AsnIn applies the In predicate on the "asn" field.
+func AsnIn(vs ...string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldIn(FieldAsn, vs...))
+}
+
+// AsnNotIn applies the NotIn predicate on the "asn" field.
+func AsnNotIn(vs ...string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldNotIn(FieldAsn, vs...))
+}
+
+// AsnGT applies the GT predicate on the "asn" field.
+func AsnGT(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldGT(FieldAsn, v))
+}
+
+// AsnGTE applies the GTE predicate on the "asn" field.
+func AsnGTE(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldGTE(FieldAsn, v))
+}
+
+// AsnLT applies the LT predicate on the "asn" field.
+func AsnLT(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldLT(FieldAsn, v))
+}
+
+// AsnLTE applies the LTE predicate on the "asn" field.
+func AsnLTE(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldLTE(FieldAsn, v))
+}
+
+// AsnContains applies the Contains predicate on the "asn" field.
+func AsnContains(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldContains(FieldAsn, v))
+}
+
+// AsnHasPrefix applies the HasPrefix predicate on the "asn" field.
+func AsnHasPrefix(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldHasPrefix(FieldAsn, v))
+}
+
+// AsnHasSuffix applies the HasSuffix predicate on the "asn" field.
+func AsnHasSuffix(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldHasSuffix(FieldAsn, v))
+}
+
+// AsnEqualFold applies the EqualFold predicate on the "asn" field.
+func AsnEqualFold(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldEqualFold(FieldAsn, v))
+}
+
+// AsnContainsFold applies the ContainsFold predicate on the "asn" field.
+func AsnContainsFold(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldContainsFold(FieldAsn, v))
+}
+
+// ClientVersionEQ applies the EQ predicate on the "client_version" field.
+func ClientVersionEQ(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldEQ(FieldClientVersion, v))
+}
+
+// ClientVersionNEQ applies the NEQ predicate on the "client_version" field.
+func ClientVersionNEQ(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldNEQ(FieldClientVersion, v))
+}
+
+// ClientVersionIn applies the In predicate on the "client_version" field.
+func ClientVersionIn(vs ...string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldIn(FieldClientVersion, vs...))
+}
+
+// ClientVersionNotIn applies the NotIn predicate on the "client_version" field.
+func ClientVersionNotIn(vs ...string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldNotIn(FieldClientVersion, vs...))
+}
+
+// ClientVersionGT applies the GT predicate on the "client_version" field.
+func ClientVersionGT(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldGT(FieldClientVersion, v))
+}
+
+// ClientVersionGTE applies the GTE predicate on the "client_version" field.
+func ClientVersionGTE(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldGTE(FieldClientVersion, v))
+}
+
+// ClientVersionLT applies the LT predicate on the "client_version" field.
+func ClientVersionLT(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldLT(FieldClientVersion, v))
+}
+
+// ClientVersionLTE applies the LTE predicate on the "client_version" field.
+func ClientVersionLTE(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldLTE(FieldClientVersion, v))
+}
+
+// ClientVersionContains applies the Contains predicate on the "client_version" field.
+func ClientVersionContains(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldContains(FieldClientVersion, v))
+}
+
+// ClientVersionHasPrefix applies the HasPrefix predicate on the "client_version" field.
+func ClientVersionHasPrefix(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldHasPrefix(FieldClientVersion, v))
+}
+
+// ClientVersionHasSuffix applies the HasSuffix predicate on the "client_version" field.
+func ClientVersionHasSuffix(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldHasSuffix(FieldClientVersion, v))
+}
+
+// ClientVersionEqualFold applies the EqualFold predicate on the "client_version" field.
+func ClientVersionEqualFold(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldEqualFold(FieldClientVersion, v))
+}
+
+// ClientVersionContainsFold applies the ContainsFold predicate on the "client_version" field.
+func ClientVersionContainsFold(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldContainsFold(FieldClientVersion, v))
+}
+
+// DeviceEQ applies the EQ predicate on the "device" field.
+func DeviceEQ(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldEQ(FieldDevice, v))
+}
+
+// DeviceNEQ applies the NEQ predicate on the "device" field.
+func DeviceNEQ(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldNEQ(FieldDevice, v))
+}
+
+// DeviceIn applies the In predicate on the "device" field.
+func DeviceIn(vs ...string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldIn(FieldDevice, vs...))
+}
+
+// DeviceNotIn applies the NotIn predicate on the "device" field.
+func DeviceNotIn(vs ...string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldNotIn(FieldDevice, vs...))
+}
+
+// DeviceGT applies the GT predicate on the "device" field.
+func DeviceGT(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldGT(FieldDevice, v))
+}
+
+// DeviceGTE applies the GTE predicate on the "device" field.
+func DeviceGTE(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldGTE(FieldDevice, v))
+}
+
+// DeviceLT applies the LT predicate on the "device" field.
+func DeviceLT(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldLT(FieldDevice, v))
+}
+
+// DeviceLTE applies the LTE predicate on the "device" field.
+func DeviceLTE(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldLTE(FieldDevice, v))
+}
+
+// DeviceContains applies the Contains predicate on the "device" field.
+func DeviceContains(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldContains(FieldDevice, v))
+}
+
+// DeviceHasPrefix applies the HasPrefix predicate on the "device" field.
+func DeviceHasPrefix(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldHasPrefix(FieldDevice, v))
+}
+
+// DeviceHasSuffix applies the HasSuffix predicate on the "device" field.
+func DeviceHasSuffix(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldHasSuffix(FieldDevice, v))
+}
+
+// DeviceEqualFold applies the EqualFold predicate on the "device" field.
+func DeviceEqualFold(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldEqualFold(FieldDevice, v))
+}
+
+// DeviceContainsFold applies the ContainsFold predicate on the "device" field.
+func DeviceContainsFold(v string) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldContainsFold(FieldDevice, v))
+}
+
+// CreatedAtEQ applies the EQ predicate on the "created_at" field.
+func CreatedAtEQ(v time.Time) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldEQ(FieldCreatedAt, v))
+}
+
+// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
+func CreatedAtNEQ(v time.Time) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldNEQ(FieldCreatedAt, v))
+}
+
+// CreatedAtIn applies the In predicate on the "created_at" field.
+func CreatedAtIn(vs ...time.Time) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldIn(FieldCreatedAt, vs...))
+}
+
+// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
+func CreatedAtNotIn(vs ...time.Time) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldNotIn(FieldCreatedAt, vs...))
+}
+
+// CreatedAtGT applies the GT predicate on the "created_at" field.
+func CreatedAtGT(v time.Time) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldGT(FieldCreatedAt, v))
+}
+
+// CreatedAtGTE applies the GTE predicate on the "created_at" field.
+func CreatedAtGTE(v time.Time) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldGTE(FieldCreatedAt, v))
+}
+
+// CreatedAtLT applies the LT predicate on the "created_at" field.
+func CreatedAtLT(v time.Time) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldLT(FieldCreatedAt, v))
+}
+
+// CreatedAtLTE applies the LTE predicate on the "created_at" field.
+func CreatedAtLTE(v time.Time) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.FieldLTE(FieldCreatedAt, v))
+}
+
+// HasOwner applies the HasEdge predicate on the "owner" edge.
+func HasOwner() predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(func(s *sql.Selector) {
+ step := sqlgraph.NewStep(
+ sqlgraph.From(Table, FieldID),
+ sqlgraph.Edge(sqlgraph.M2O, true, OwnerTable, OwnerColumn),
+ )
+ sqlgraph.HasNeighbors(s, step)
+ })
+}
+
+// HasOwnerWith applies the HasEdge predicate on the "owner" edge with a given conditions (other predicates).
+func HasOwnerWith(preds ...predicate.Admin) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(func(s *sql.Selector) {
+ step := newOwnerStep()
+ sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
+ for _, p := range preds {
+ p(s)
+ }
+ })
+ })
+}
+
+// And groups predicates with the AND operator between them.
+func And(predicates ...predicate.AdminLoginHistory) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.AndPredicates(predicates...))
+}
+
+// Or groups predicates with the OR operator between them.
+func Or(predicates ...predicate.AdminLoginHistory) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.OrPredicates(predicates...))
+}
+
+// Not applies the not operator on the given predicate.
+func Not(p predicate.AdminLoginHistory) predicate.AdminLoginHistory {
+ return predicate.AdminLoginHistory(sql.NotPredicates(p))
+}
diff --git a/backend/db/adminloginhistory_create.go b/backend/db/adminloginhistory_create.go
new file mode 100644
index 0000000..dfef7fa
--- /dev/null
+++ b/backend/db/adminloginhistory_create.go
@@ -0,0 +1,1023 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "time"
+
+ "entgo.io/ent/dialect"
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/admin"
+ "github.com/chaitin/MonkeyCode/backend/db/adminloginhistory"
+ "github.com/google/uuid"
+)
+
+// AdminLoginHistoryCreate is the builder for creating a AdminLoginHistory entity.
+type AdminLoginHistoryCreate struct {
+ config
+ mutation *AdminLoginHistoryMutation
+ hooks []Hook
+ conflict []sql.ConflictOption
+}
+
+// SetAdminID sets the "admin_id" field.
+func (alhc *AdminLoginHistoryCreate) SetAdminID(u uuid.UUID) *AdminLoginHistoryCreate {
+ alhc.mutation.SetAdminID(u)
+ return alhc
+}
+
+// SetIP sets the "ip" field.
+func (alhc *AdminLoginHistoryCreate) SetIP(s string) *AdminLoginHistoryCreate {
+ alhc.mutation.SetIP(s)
+ return alhc
+}
+
+// SetCountry sets the "country" field.
+func (alhc *AdminLoginHistoryCreate) SetCountry(s string) *AdminLoginHistoryCreate {
+ alhc.mutation.SetCountry(s)
+ return alhc
+}
+
+// SetProvince sets the "province" field.
+func (alhc *AdminLoginHistoryCreate) SetProvince(s string) *AdminLoginHistoryCreate {
+ alhc.mutation.SetProvince(s)
+ return alhc
+}
+
+// SetCity sets the "city" field.
+func (alhc *AdminLoginHistoryCreate) SetCity(s string) *AdminLoginHistoryCreate {
+ alhc.mutation.SetCity(s)
+ return alhc
+}
+
+// SetIsp sets the "isp" field.
+func (alhc *AdminLoginHistoryCreate) SetIsp(s string) *AdminLoginHistoryCreate {
+ alhc.mutation.SetIsp(s)
+ return alhc
+}
+
+// SetAsn sets the "asn" field.
+func (alhc *AdminLoginHistoryCreate) SetAsn(s string) *AdminLoginHistoryCreate {
+ alhc.mutation.SetAsn(s)
+ return alhc
+}
+
+// SetClientVersion sets the "client_version" field.
+func (alhc *AdminLoginHistoryCreate) SetClientVersion(s string) *AdminLoginHistoryCreate {
+ alhc.mutation.SetClientVersion(s)
+ return alhc
+}
+
+// SetDevice sets the "device" field.
+func (alhc *AdminLoginHistoryCreate) SetDevice(s string) *AdminLoginHistoryCreate {
+ alhc.mutation.SetDevice(s)
+ return alhc
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (alhc *AdminLoginHistoryCreate) SetCreatedAt(t time.Time) *AdminLoginHistoryCreate {
+ alhc.mutation.SetCreatedAt(t)
+ return alhc
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (alhc *AdminLoginHistoryCreate) SetNillableCreatedAt(t *time.Time) *AdminLoginHistoryCreate {
+ if t != nil {
+ alhc.SetCreatedAt(*t)
+ }
+ return alhc
+}
+
+// SetID sets the "id" field.
+func (alhc *AdminLoginHistoryCreate) SetID(u uuid.UUID) *AdminLoginHistoryCreate {
+ alhc.mutation.SetID(u)
+ return alhc
+}
+
+// SetOwnerID sets the "owner" edge to the Admin entity by ID.
+func (alhc *AdminLoginHistoryCreate) SetOwnerID(id uuid.UUID) *AdminLoginHistoryCreate {
+ alhc.mutation.SetOwnerID(id)
+ return alhc
+}
+
+// SetNillableOwnerID sets the "owner" edge to the Admin entity by ID if the given value is not nil.
+func (alhc *AdminLoginHistoryCreate) SetNillableOwnerID(id *uuid.UUID) *AdminLoginHistoryCreate {
+ if id != nil {
+ alhc = alhc.SetOwnerID(*id)
+ }
+ return alhc
+}
+
+// SetOwner sets the "owner" edge to the Admin entity.
+func (alhc *AdminLoginHistoryCreate) SetOwner(a *Admin) *AdminLoginHistoryCreate {
+ return alhc.SetOwnerID(a.ID)
+}
+
+// Mutation returns the AdminLoginHistoryMutation object of the builder.
+func (alhc *AdminLoginHistoryCreate) Mutation() *AdminLoginHistoryMutation {
+ return alhc.mutation
+}
+
+// Save creates the AdminLoginHistory in the database.
+func (alhc *AdminLoginHistoryCreate) Save(ctx context.Context) (*AdminLoginHistory, error) {
+ alhc.defaults()
+ return withHooks(ctx, alhc.sqlSave, alhc.mutation, alhc.hooks)
+}
+
+// SaveX calls Save and panics if Save returns an error.
+func (alhc *AdminLoginHistoryCreate) SaveX(ctx context.Context) *AdminLoginHistory {
+ v, err := alhc.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return v
+}
+
+// Exec executes the query.
+func (alhc *AdminLoginHistoryCreate) Exec(ctx context.Context) error {
+ _, err := alhc.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (alhc *AdminLoginHistoryCreate) ExecX(ctx context.Context) {
+ if err := alhc.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// defaults sets the default values of the builder before save.
+func (alhc *AdminLoginHistoryCreate) defaults() {
+ if _, ok := alhc.mutation.CreatedAt(); !ok {
+ v := adminloginhistory.DefaultCreatedAt()
+ alhc.mutation.SetCreatedAt(v)
+ }
+}
+
+// check runs all checks and user-defined validators on the builder.
+func (alhc *AdminLoginHistoryCreate) check() error {
+ if _, ok := alhc.mutation.AdminID(); !ok {
+ return &ValidationError{Name: "admin_id", err: errors.New(`db: missing required field "AdminLoginHistory.admin_id"`)}
+ }
+ if _, ok := alhc.mutation.IP(); !ok {
+ return &ValidationError{Name: "ip", err: errors.New(`db: missing required field "AdminLoginHistory.ip"`)}
+ }
+ if _, ok := alhc.mutation.Country(); !ok {
+ return &ValidationError{Name: "country", err: errors.New(`db: missing required field "AdminLoginHistory.country"`)}
+ }
+ if _, ok := alhc.mutation.Province(); !ok {
+ return &ValidationError{Name: "province", err: errors.New(`db: missing required field "AdminLoginHistory.province"`)}
+ }
+ if _, ok := alhc.mutation.City(); !ok {
+ return &ValidationError{Name: "city", err: errors.New(`db: missing required field "AdminLoginHistory.city"`)}
+ }
+ if _, ok := alhc.mutation.Isp(); !ok {
+ return &ValidationError{Name: "isp", err: errors.New(`db: missing required field "AdminLoginHistory.isp"`)}
+ }
+ if _, ok := alhc.mutation.Asn(); !ok {
+ return &ValidationError{Name: "asn", err: errors.New(`db: missing required field "AdminLoginHistory.asn"`)}
+ }
+ if _, ok := alhc.mutation.ClientVersion(); !ok {
+ return &ValidationError{Name: "client_version", err: errors.New(`db: missing required field "AdminLoginHistory.client_version"`)}
+ }
+ if _, ok := alhc.mutation.Device(); !ok {
+ return &ValidationError{Name: "device", err: errors.New(`db: missing required field "AdminLoginHistory.device"`)}
+ }
+ if _, ok := alhc.mutation.CreatedAt(); !ok {
+ return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "AdminLoginHistory.created_at"`)}
+ }
+ return nil
+}
+
+func (alhc *AdminLoginHistoryCreate) sqlSave(ctx context.Context) (*AdminLoginHistory, error) {
+ if err := alhc.check(); err != nil {
+ return nil, err
+ }
+ _node, _spec := alhc.createSpec()
+ if err := sqlgraph.CreateNode(ctx, alhc.driver, _spec); err != nil {
+ if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return nil, err
+ }
+ if _spec.ID.Value != nil {
+ if id, ok := _spec.ID.Value.(*uuid.UUID); ok {
+ _node.ID = *id
+ } else if err := _node.ID.Scan(_spec.ID.Value); err != nil {
+ return nil, err
+ }
+ }
+ alhc.mutation.id = &_node.ID
+ alhc.mutation.done = true
+ return _node, nil
+}
+
+func (alhc *AdminLoginHistoryCreate) createSpec() (*AdminLoginHistory, *sqlgraph.CreateSpec) {
+ var (
+ _node = &AdminLoginHistory{config: alhc.config}
+ _spec = sqlgraph.NewCreateSpec(adminloginhistory.Table, sqlgraph.NewFieldSpec(adminloginhistory.FieldID, field.TypeUUID))
+ )
+ _spec.OnConflict = alhc.conflict
+ if id, ok := alhc.mutation.ID(); ok {
+ _node.ID = id
+ _spec.ID.Value = &id
+ }
+ if value, ok := alhc.mutation.AdminID(); ok {
+ _spec.SetField(adminloginhistory.FieldAdminID, field.TypeUUID, value)
+ _node.AdminID = value
+ }
+ if value, ok := alhc.mutation.IP(); ok {
+ _spec.SetField(adminloginhistory.FieldIP, field.TypeString, value)
+ _node.IP = value
+ }
+ if value, ok := alhc.mutation.Country(); ok {
+ _spec.SetField(adminloginhistory.FieldCountry, field.TypeString, value)
+ _node.Country = value
+ }
+ if value, ok := alhc.mutation.Province(); ok {
+ _spec.SetField(adminloginhistory.FieldProvince, field.TypeString, value)
+ _node.Province = value
+ }
+ if value, ok := alhc.mutation.City(); ok {
+ _spec.SetField(adminloginhistory.FieldCity, field.TypeString, value)
+ _node.City = value
+ }
+ if value, ok := alhc.mutation.Isp(); ok {
+ _spec.SetField(adminloginhistory.FieldIsp, field.TypeString, value)
+ _node.Isp = value
+ }
+ if value, ok := alhc.mutation.Asn(); ok {
+ _spec.SetField(adminloginhistory.FieldAsn, field.TypeString, value)
+ _node.Asn = value
+ }
+ if value, ok := alhc.mutation.ClientVersion(); ok {
+ _spec.SetField(adminloginhistory.FieldClientVersion, field.TypeString, value)
+ _node.ClientVersion = value
+ }
+ if value, ok := alhc.mutation.Device(); ok {
+ _spec.SetField(adminloginhistory.FieldDevice, field.TypeString, value)
+ _node.Device = value
+ }
+ if value, ok := alhc.mutation.CreatedAt(); ok {
+ _spec.SetField(adminloginhistory.FieldCreatedAt, field.TypeTime, value)
+ _node.CreatedAt = value
+ }
+ if nodes := alhc.mutation.OwnerIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: true,
+ Table: adminloginhistory.OwnerTable,
+ Columns: []string{adminloginhistory.OwnerColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(admin.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _node.admin_login_histories = &nodes[0]
+ _spec.Edges = append(_spec.Edges, edge)
+ }
+ return _node, _spec
+}
+
+// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
+// of the `INSERT` statement. For example:
+//
+// client.AdminLoginHistory.Create().
+// SetAdminID(v).
+// OnConflict(
+// // Update the row with the new values
+// // the was proposed for insertion.
+// sql.ResolveWithNewValues(),
+// ).
+// // Override some of the fields with custom
+// // update values.
+// Update(func(u *ent.AdminLoginHistoryUpsert) {
+// SetAdminID(v+v).
+// }).
+// Exec(ctx)
+func (alhc *AdminLoginHistoryCreate) OnConflict(opts ...sql.ConflictOption) *AdminLoginHistoryUpsertOne {
+ alhc.conflict = opts
+ return &AdminLoginHistoryUpsertOne{
+ create: alhc,
+ }
+}
+
+// OnConflictColumns calls `OnConflict` and configures the columns
+// as conflict target. Using this option is equivalent to using:
+//
+// client.AdminLoginHistory.Create().
+// OnConflict(sql.ConflictColumns(columns...)).
+// Exec(ctx)
+func (alhc *AdminLoginHistoryCreate) OnConflictColumns(columns ...string) *AdminLoginHistoryUpsertOne {
+ alhc.conflict = append(alhc.conflict, sql.ConflictColumns(columns...))
+ return &AdminLoginHistoryUpsertOne{
+ create: alhc,
+ }
+}
+
+type (
+ // AdminLoginHistoryUpsertOne is the builder for "upsert"-ing
+ // one AdminLoginHistory node.
+ AdminLoginHistoryUpsertOne struct {
+ create *AdminLoginHistoryCreate
+ }
+
+ // AdminLoginHistoryUpsert is the "OnConflict" setter.
+ AdminLoginHistoryUpsert struct {
+ *sql.UpdateSet
+ }
+)
+
+// SetAdminID sets the "admin_id" field.
+func (u *AdminLoginHistoryUpsert) SetAdminID(v uuid.UUID) *AdminLoginHistoryUpsert {
+ u.Set(adminloginhistory.FieldAdminID, v)
+ return u
+}
+
+// UpdateAdminID sets the "admin_id" field to the value that was provided on create.
+func (u *AdminLoginHistoryUpsert) UpdateAdminID() *AdminLoginHistoryUpsert {
+ u.SetExcluded(adminloginhistory.FieldAdminID)
+ return u
+}
+
+// SetIP sets the "ip" field.
+func (u *AdminLoginHistoryUpsert) SetIP(v string) *AdminLoginHistoryUpsert {
+ u.Set(adminloginhistory.FieldIP, v)
+ return u
+}
+
+// UpdateIP sets the "ip" field to the value that was provided on create.
+func (u *AdminLoginHistoryUpsert) UpdateIP() *AdminLoginHistoryUpsert {
+ u.SetExcluded(adminloginhistory.FieldIP)
+ return u
+}
+
+// SetCountry sets the "country" field.
+func (u *AdminLoginHistoryUpsert) SetCountry(v string) *AdminLoginHistoryUpsert {
+ u.Set(adminloginhistory.FieldCountry, v)
+ return u
+}
+
+// UpdateCountry sets the "country" field to the value that was provided on create.
+func (u *AdminLoginHistoryUpsert) UpdateCountry() *AdminLoginHistoryUpsert {
+ u.SetExcluded(adminloginhistory.FieldCountry)
+ return u
+}
+
+// SetProvince sets the "province" field.
+func (u *AdminLoginHistoryUpsert) SetProvince(v string) *AdminLoginHistoryUpsert {
+ u.Set(adminloginhistory.FieldProvince, v)
+ return u
+}
+
+// UpdateProvince sets the "province" field to the value that was provided on create.
+func (u *AdminLoginHistoryUpsert) UpdateProvince() *AdminLoginHistoryUpsert {
+ u.SetExcluded(adminloginhistory.FieldProvince)
+ return u
+}
+
+// SetCity sets the "city" field.
+func (u *AdminLoginHistoryUpsert) SetCity(v string) *AdminLoginHistoryUpsert {
+ u.Set(adminloginhistory.FieldCity, v)
+ return u
+}
+
+// UpdateCity sets the "city" field to the value that was provided on create.
+func (u *AdminLoginHistoryUpsert) UpdateCity() *AdminLoginHistoryUpsert {
+ u.SetExcluded(adminloginhistory.FieldCity)
+ return u
+}
+
+// SetIsp sets the "isp" field.
+func (u *AdminLoginHistoryUpsert) SetIsp(v string) *AdminLoginHistoryUpsert {
+ u.Set(adminloginhistory.FieldIsp, v)
+ return u
+}
+
+// UpdateIsp sets the "isp" field to the value that was provided on create.
+func (u *AdminLoginHistoryUpsert) UpdateIsp() *AdminLoginHistoryUpsert {
+ u.SetExcluded(adminloginhistory.FieldIsp)
+ return u
+}
+
+// SetAsn sets the "asn" field.
+func (u *AdminLoginHistoryUpsert) SetAsn(v string) *AdminLoginHistoryUpsert {
+ u.Set(adminloginhistory.FieldAsn, v)
+ return u
+}
+
+// UpdateAsn sets the "asn" field to the value that was provided on create.
+func (u *AdminLoginHistoryUpsert) UpdateAsn() *AdminLoginHistoryUpsert {
+ u.SetExcluded(adminloginhistory.FieldAsn)
+ return u
+}
+
+// SetClientVersion sets the "client_version" field.
+func (u *AdminLoginHistoryUpsert) SetClientVersion(v string) *AdminLoginHistoryUpsert {
+ u.Set(adminloginhistory.FieldClientVersion, v)
+ return u
+}
+
+// UpdateClientVersion sets the "client_version" field to the value that was provided on create.
+func (u *AdminLoginHistoryUpsert) UpdateClientVersion() *AdminLoginHistoryUpsert {
+ u.SetExcluded(adminloginhistory.FieldClientVersion)
+ return u
+}
+
+// SetDevice sets the "device" field.
+func (u *AdminLoginHistoryUpsert) SetDevice(v string) *AdminLoginHistoryUpsert {
+ u.Set(adminloginhistory.FieldDevice, v)
+ return u
+}
+
+// UpdateDevice sets the "device" field to the value that was provided on create.
+func (u *AdminLoginHistoryUpsert) UpdateDevice() *AdminLoginHistoryUpsert {
+ u.SetExcluded(adminloginhistory.FieldDevice)
+ return u
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (u *AdminLoginHistoryUpsert) SetCreatedAt(v time.Time) *AdminLoginHistoryUpsert {
+ u.Set(adminloginhistory.FieldCreatedAt, v)
+ return u
+}
+
+// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
+func (u *AdminLoginHistoryUpsert) UpdateCreatedAt() *AdminLoginHistoryUpsert {
+ u.SetExcluded(adminloginhistory.FieldCreatedAt)
+ return u
+}
+
+// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field.
+// Using this option is equivalent to using:
+//
+// client.AdminLoginHistory.Create().
+// OnConflict(
+// sql.ResolveWithNewValues(),
+// sql.ResolveWith(func(u *sql.UpdateSet) {
+// u.SetIgnore(adminloginhistory.FieldID)
+// }),
+// ).
+// Exec(ctx)
+func (u *AdminLoginHistoryUpsertOne) UpdateNewValues() *AdminLoginHistoryUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
+ if _, exists := u.create.mutation.ID(); exists {
+ s.SetIgnore(adminloginhistory.FieldID)
+ }
+ }))
+ return u
+}
+
+// Ignore sets each column to itself in case of conflict.
+// Using this option is equivalent to using:
+//
+// client.AdminLoginHistory.Create().
+// OnConflict(sql.ResolveWithIgnore()).
+// Exec(ctx)
+func (u *AdminLoginHistoryUpsertOne) Ignore() *AdminLoginHistoryUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
+ return u
+}
+
+// DoNothing configures the conflict_action to `DO NOTHING`.
+// Supported only by SQLite and PostgreSQL.
+func (u *AdminLoginHistoryUpsertOne) DoNothing() *AdminLoginHistoryUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.DoNothing())
+ return u
+}
+
+// Update allows overriding fields `UPDATE` values. See the AdminLoginHistoryCreate.OnConflict
+// documentation for more info.
+func (u *AdminLoginHistoryUpsertOne) Update(set func(*AdminLoginHistoryUpsert)) *AdminLoginHistoryUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
+ set(&AdminLoginHistoryUpsert{UpdateSet: update})
+ }))
+ return u
+}
+
+// SetAdminID sets the "admin_id" field.
+func (u *AdminLoginHistoryUpsertOne) SetAdminID(v uuid.UUID) *AdminLoginHistoryUpsertOne {
+ return u.Update(func(s *AdminLoginHistoryUpsert) {
+ s.SetAdminID(v)
+ })
+}
+
+// UpdateAdminID sets the "admin_id" field to the value that was provided on create.
+func (u *AdminLoginHistoryUpsertOne) UpdateAdminID() *AdminLoginHistoryUpsertOne {
+ return u.Update(func(s *AdminLoginHistoryUpsert) {
+ s.UpdateAdminID()
+ })
+}
+
+// SetIP sets the "ip" field.
+func (u *AdminLoginHistoryUpsertOne) SetIP(v string) *AdminLoginHistoryUpsertOne {
+ return u.Update(func(s *AdminLoginHistoryUpsert) {
+ s.SetIP(v)
+ })
+}
+
+// UpdateIP sets the "ip" field to the value that was provided on create.
+func (u *AdminLoginHistoryUpsertOne) UpdateIP() *AdminLoginHistoryUpsertOne {
+ return u.Update(func(s *AdminLoginHistoryUpsert) {
+ s.UpdateIP()
+ })
+}
+
+// SetCountry sets the "country" field.
+func (u *AdminLoginHistoryUpsertOne) SetCountry(v string) *AdminLoginHistoryUpsertOne {
+ return u.Update(func(s *AdminLoginHistoryUpsert) {
+ s.SetCountry(v)
+ })
+}
+
+// UpdateCountry sets the "country" field to the value that was provided on create.
+func (u *AdminLoginHistoryUpsertOne) UpdateCountry() *AdminLoginHistoryUpsertOne {
+ return u.Update(func(s *AdminLoginHistoryUpsert) {
+ s.UpdateCountry()
+ })
+}
+
+// SetProvince sets the "province" field.
+func (u *AdminLoginHistoryUpsertOne) SetProvince(v string) *AdminLoginHistoryUpsertOne {
+ return u.Update(func(s *AdminLoginHistoryUpsert) {
+ s.SetProvince(v)
+ })
+}
+
+// UpdateProvince sets the "province" field to the value that was provided on create.
+func (u *AdminLoginHistoryUpsertOne) UpdateProvince() *AdminLoginHistoryUpsertOne {
+ return u.Update(func(s *AdminLoginHistoryUpsert) {
+ s.UpdateProvince()
+ })
+}
+
+// SetCity sets the "city" field.
+func (u *AdminLoginHistoryUpsertOne) SetCity(v string) *AdminLoginHistoryUpsertOne {
+ return u.Update(func(s *AdminLoginHistoryUpsert) {
+ s.SetCity(v)
+ })
+}
+
+// UpdateCity sets the "city" field to the value that was provided on create.
+func (u *AdminLoginHistoryUpsertOne) UpdateCity() *AdminLoginHistoryUpsertOne {
+ return u.Update(func(s *AdminLoginHistoryUpsert) {
+ s.UpdateCity()
+ })
+}
+
+// SetIsp sets the "isp" field.
+func (u *AdminLoginHistoryUpsertOne) SetIsp(v string) *AdminLoginHistoryUpsertOne {
+ return u.Update(func(s *AdminLoginHistoryUpsert) {
+ s.SetIsp(v)
+ })
+}
+
+// UpdateIsp sets the "isp" field to the value that was provided on create.
+func (u *AdminLoginHistoryUpsertOne) UpdateIsp() *AdminLoginHistoryUpsertOne {
+ return u.Update(func(s *AdminLoginHistoryUpsert) {
+ s.UpdateIsp()
+ })
+}
+
+// SetAsn sets the "asn" field.
+func (u *AdminLoginHistoryUpsertOne) SetAsn(v string) *AdminLoginHistoryUpsertOne {
+ return u.Update(func(s *AdminLoginHistoryUpsert) {
+ s.SetAsn(v)
+ })
+}
+
+// UpdateAsn sets the "asn" field to the value that was provided on create.
+func (u *AdminLoginHistoryUpsertOne) UpdateAsn() *AdminLoginHistoryUpsertOne {
+ return u.Update(func(s *AdminLoginHistoryUpsert) {
+ s.UpdateAsn()
+ })
+}
+
+// SetClientVersion sets the "client_version" field.
+func (u *AdminLoginHistoryUpsertOne) SetClientVersion(v string) *AdminLoginHistoryUpsertOne {
+ return u.Update(func(s *AdminLoginHistoryUpsert) {
+ s.SetClientVersion(v)
+ })
+}
+
+// UpdateClientVersion sets the "client_version" field to the value that was provided on create.
+func (u *AdminLoginHistoryUpsertOne) UpdateClientVersion() *AdminLoginHistoryUpsertOne {
+ return u.Update(func(s *AdminLoginHistoryUpsert) {
+ s.UpdateClientVersion()
+ })
+}
+
+// SetDevice sets the "device" field.
+func (u *AdminLoginHistoryUpsertOne) SetDevice(v string) *AdminLoginHistoryUpsertOne {
+ return u.Update(func(s *AdminLoginHistoryUpsert) {
+ s.SetDevice(v)
+ })
+}
+
+// UpdateDevice sets the "device" field to the value that was provided on create.
+func (u *AdminLoginHistoryUpsertOne) UpdateDevice() *AdminLoginHistoryUpsertOne {
+ return u.Update(func(s *AdminLoginHistoryUpsert) {
+ s.UpdateDevice()
+ })
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (u *AdminLoginHistoryUpsertOne) SetCreatedAt(v time.Time) *AdminLoginHistoryUpsertOne {
+ return u.Update(func(s *AdminLoginHistoryUpsert) {
+ s.SetCreatedAt(v)
+ })
+}
+
+// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
+func (u *AdminLoginHistoryUpsertOne) UpdateCreatedAt() *AdminLoginHistoryUpsertOne {
+ return u.Update(func(s *AdminLoginHistoryUpsert) {
+ s.UpdateCreatedAt()
+ })
+}
+
+// Exec executes the query.
+func (u *AdminLoginHistoryUpsertOne) Exec(ctx context.Context) error {
+ if len(u.create.conflict) == 0 {
+ return errors.New("db: missing options for AdminLoginHistoryCreate.OnConflict")
+ }
+ return u.create.Exec(ctx)
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (u *AdminLoginHistoryUpsertOne) ExecX(ctx context.Context) {
+ if err := u.create.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// Exec executes the UPSERT query and returns the inserted/updated ID.
+func (u *AdminLoginHistoryUpsertOne) ID(ctx context.Context) (id uuid.UUID, err error) {
+ if u.create.driver.Dialect() == dialect.MySQL {
+ // In case of "ON CONFLICT", there is no way to get back non-numeric ID
+ // fields from the database since MySQL does not support the RETURNING clause.
+ return id, errors.New("db: AdminLoginHistoryUpsertOne.ID is not supported by MySQL driver. Use AdminLoginHistoryUpsertOne.Exec instead")
+ }
+ node, err := u.create.Save(ctx)
+ if err != nil {
+ return id, err
+ }
+ return node.ID, nil
+}
+
+// IDX is like ID, but panics if an error occurs.
+func (u *AdminLoginHistoryUpsertOne) IDX(ctx context.Context) uuid.UUID {
+ id, err := u.ID(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return id
+}
+
+// AdminLoginHistoryCreateBulk is the builder for creating many AdminLoginHistory entities in bulk.
+type AdminLoginHistoryCreateBulk struct {
+ config
+ err error
+ builders []*AdminLoginHistoryCreate
+ conflict []sql.ConflictOption
+}
+
+// Save creates the AdminLoginHistory entities in the database.
+func (alhcb *AdminLoginHistoryCreateBulk) Save(ctx context.Context) ([]*AdminLoginHistory, error) {
+ if alhcb.err != nil {
+ return nil, alhcb.err
+ }
+ specs := make([]*sqlgraph.CreateSpec, len(alhcb.builders))
+ nodes := make([]*AdminLoginHistory, len(alhcb.builders))
+ mutators := make([]Mutator, len(alhcb.builders))
+ for i := range alhcb.builders {
+ func(i int, root context.Context) {
+ builder := alhcb.builders[i]
+ builder.defaults()
+ var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
+ mutation, ok := m.(*AdminLoginHistoryMutation)
+ if !ok {
+ return nil, fmt.Errorf("unexpected mutation type %T", m)
+ }
+ if err := builder.check(); err != nil {
+ return nil, err
+ }
+ builder.mutation = mutation
+ var err error
+ nodes[i], specs[i] = builder.createSpec()
+ if i < len(mutators)-1 {
+ _, err = mutators[i+1].Mutate(root, alhcb.builders[i+1].mutation)
+ } else {
+ spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
+ spec.OnConflict = alhcb.conflict
+ // Invoke the actual operation on the latest mutation in the chain.
+ if err = sqlgraph.BatchCreate(ctx, alhcb.driver, spec); err != nil {
+ if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ }
+ }
+ if err != nil {
+ return nil, err
+ }
+ mutation.id = &nodes[i].ID
+ mutation.done = true
+ return nodes[i], nil
+ })
+ for i := len(builder.hooks) - 1; i >= 0; i-- {
+ mut = builder.hooks[i](mut)
+ }
+ mutators[i] = mut
+ }(i, ctx)
+ }
+ if len(mutators) > 0 {
+ if _, err := mutators[0].Mutate(ctx, alhcb.builders[0].mutation); err != nil {
+ return nil, err
+ }
+ }
+ return nodes, nil
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (alhcb *AdminLoginHistoryCreateBulk) SaveX(ctx context.Context) []*AdminLoginHistory {
+ v, err := alhcb.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return v
+}
+
+// Exec executes the query.
+func (alhcb *AdminLoginHistoryCreateBulk) Exec(ctx context.Context) error {
+ _, err := alhcb.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (alhcb *AdminLoginHistoryCreateBulk) ExecX(ctx context.Context) {
+ if err := alhcb.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
+// of the `INSERT` statement. For example:
+//
+// client.AdminLoginHistory.CreateBulk(builders...).
+// OnConflict(
+// // Update the row with the new values
+// // the was proposed for insertion.
+// sql.ResolveWithNewValues(),
+// ).
+// // Override some of the fields with custom
+// // update values.
+// Update(func(u *ent.AdminLoginHistoryUpsert) {
+// SetAdminID(v+v).
+// }).
+// Exec(ctx)
+func (alhcb *AdminLoginHistoryCreateBulk) OnConflict(opts ...sql.ConflictOption) *AdminLoginHistoryUpsertBulk {
+ alhcb.conflict = opts
+ return &AdminLoginHistoryUpsertBulk{
+ create: alhcb,
+ }
+}
+
+// OnConflictColumns calls `OnConflict` and configures the columns
+// as conflict target. Using this option is equivalent to using:
+//
+// client.AdminLoginHistory.Create().
+// OnConflict(sql.ConflictColumns(columns...)).
+// Exec(ctx)
+func (alhcb *AdminLoginHistoryCreateBulk) OnConflictColumns(columns ...string) *AdminLoginHistoryUpsertBulk {
+ alhcb.conflict = append(alhcb.conflict, sql.ConflictColumns(columns...))
+ return &AdminLoginHistoryUpsertBulk{
+ create: alhcb,
+ }
+}
+
+// AdminLoginHistoryUpsertBulk is the builder for "upsert"-ing
+// a bulk of AdminLoginHistory nodes.
+type AdminLoginHistoryUpsertBulk struct {
+ create *AdminLoginHistoryCreateBulk
+}
+
+// UpdateNewValues updates the mutable fields using the new values that
+// were set on create. Using this option is equivalent to using:
+//
+// client.AdminLoginHistory.Create().
+// OnConflict(
+// sql.ResolveWithNewValues(),
+// sql.ResolveWith(func(u *sql.UpdateSet) {
+// u.SetIgnore(adminloginhistory.FieldID)
+// }),
+// ).
+// Exec(ctx)
+func (u *AdminLoginHistoryUpsertBulk) UpdateNewValues() *AdminLoginHistoryUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
+ for _, b := range u.create.builders {
+ if _, exists := b.mutation.ID(); exists {
+ s.SetIgnore(adminloginhistory.FieldID)
+ }
+ }
+ }))
+ return u
+}
+
+// Ignore sets each column to itself in case of conflict.
+// Using this option is equivalent to using:
+//
+// client.AdminLoginHistory.Create().
+// OnConflict(sql.ResolveWithIgnore()).
+// Exec(ctx)
+func (u *AdminLoginHistoryUpsertBulk) Ignore() *AdminLoginHistoryUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
+ return u
+}
+
+// DoNothing configures the conflict_action to `DO NOTHING`.
+// Supported only by SQLite and PostgreSQL.
+func (u *AdminLoginHistoryUpsertBulk) DoNothing() *AdminLoginHistoryUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.DoNothing())
+ return u
+}
+
+// Update allows overriding fields `UPDATE` values. See the AdminLoginHistoryCreateBulk.OnConflict
+// documentation for more info.
+func (u *AdminLoginHistoryUpsertBulk) Update(set func(*AdminLoginHistoryUpsert)) *AdminLoginHistoryUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
+ set(&AdminLoginHistoryUpsert{UpdateSet: update})
+ }))
+ return u
+}
+
+// SetAdminID sets the "admin_id" field.
+func (u *AdminLoginHistoryUpsertBulk) SetAdminID(v uuid.UUID) *AdminLoginHistoryUpsertBulk {
+ return u.Update(func(s *AdminLoginHistoryUpsert) {
+ s.SetAdminID(v)
+ })
+}
+
+// UpdateAdminID sets the "admin_id" field to the value that was provided on create.
+func (u *AdminLoginHistoryUpsertBulk) UpdateAdminID() *AdminLoginHistoryUpsertBulk {
+ return u.Update(func(s *AdminLoginHistoryUpsert) {
+ s.UpdateAdminID()
+ })
+}
+
+// SetIP sets the "ip" field.
+func (u *AdminLoginHistoryUpsertBulk) SetIP(v string) *AdminLoginHistoryUpsertBulk {
+ return u.Update(func(s *AdminLoginHistoryUpsert) {
+ s.SetIP(v)
+ })
+}
+
+// UpdateIP sets the "ip" field to the value that was provided on create.
+func (u *AdminLoginHistoryUpsertBulk) UpdateIP() *AdminLoginHistoryUpsertBulk {
+ return u.Update(func(s *AdminLoginHistoryUpsert) {
+ s.UpdateIP()
+ })
+}
+
+// SetCountry sets the "country" field.
+func (u *AdminLoginHistoryUpsertBulk) SetCountry(v string) *AdminLoginHistoryUpsertBulk {
+ return u.Update(func(s *AdminLoginHistoryUpsert) {
+ s.SetCountry(v)
+ })
+}
+
+// UpdateCountry sets the "country" field to the value that was provided on create.
+func (u *AdminLoginHistoryUpsertBulk) UpdateCountry() *AdminLoginHistoryUpsertBulk {
+ return u.Update(func(s *AdminLoginHistoryUpsert) {
+ s.UpdateCountry()
+ })
+}
+
+// SetProvince sets the "province" field.
+func (u *AdminLoginHistoryUpsertBulk) SetProvince(v string) *AdminLoginHistoryUpsertBulk {
+ return u.Update(func(s *AdminLoginHistoryUpsert) {
+ s.SetProvince(v)
+ })
+}
+
+// UpdateProvince sets the "province" field to the value that was provided on create.
+func (u *AdminLoginHistoryUpsertBulk) UpdateProvince() *AdminLoginHistoryUpsertBulk {
+ return u.Update(func(s *AdminLoginHistoryUpsert) {
+ s.UpdateProvince()
+ })
+}
+
+// SetCity sets the "city" field.
+func (u *AdminLoginHistoryUpsertBulk) SetCity(v string) *AdminLoginHistoryUpsertBulk {
+ return u.Update(func(s *AdminLoginHistoryUpsert) {
+ s.SetCity(v)
+ })
+}
+
+// UpdateCity sets the "city" field to the value that was provided on create.
+func (u *AdminLoginHistoryUpsertBulk) UpdateCity() *AdminLoginHistoryUpsertBulk {
+ return u.Update(func(s *AdminLoginHistoryUpsert) {
+ s.UpdateCity()
+ })
+}
+
+// SetIsp sets the "isp" field.
+func (u *AdminLoginHistoryUpsertBulk) SetIsp(v string) *AdminLoginHistoryUpsertBulk {
+ return u.Update(func(s *AdminLoginHistoryUpsert) {
+ s.SetIsp(v)
+ })
+}
+
+// UpdateIsp sets the "isp" field to the value that was provided on create.
+func (u *AdminLoginHistoryUpsertBulk) UpdateIsp() *AdminLoginHistoryUpsertBulk {
+ return u.Update(func(s *AdminLoginHistoryUpsert) {
+ s.UpdateIsp()
+ })
+}
+
+// SetAsn sets the "asn" field.
+func (u *AdminLoginHistoryUpsertBulk) SetAsn(v string) *AdminLoginHistoryUpsertBulk {
+ return u.Update(func(s *AdminLoginHistoryUpsert) {
+ s.SetAsn(v)
+ })
+}
+
+// UpdateAsn sets the "asn" field to the value that was provided on create.
+func (u *AdminLoginHistoryUpsertBulk) UpdateAsn() *AdminLoginHistoryUpsertBulk {
+ return u.Update(func(s *AdminLoginHistoryUpsert) {
+ s.UpdateAsn()
+ })
+}
+
+// SetClientVersion sets the "client_version" field.
+func (u *AdminLoginHistoryUpsertBulk) SetClientVersion(v string) *AdminLoginHistoryUpsertBulk {
+ return u.Update(func(s *AdminLoginHistoryUpsert) {
+ s.SetClientVersion(v)
+ })
+}
+
+// UpdateClientVersion sets the "client_version" field to the value that was provided on create.
+func (u *AdminLoginHistoryUpsertBulk) UpdateClientVersion() *AdminLoginHistoryUpsertBulk {
+ return u.Update(func(s *AdminLoginHistoryUpsert) {
+ s.UpdateClientVersion()
+ })
+}
+
+// SetDevice sets the "device" field.
+func (u *AdminLoginHistoryUpsertBulk) SetDevice(v string) *AdminLoginHistoryUpsertBulk {
+ return u.Update(func(s *AdminLoginHistoryUpsert) {
+ s.SetDevice(v)
+ })
+}
+
+// UpdateDevice sets the "device" field to the value that was provided on create.
+func (u *AdminLoginHistoryUpsertBulk) UpdateDevice() *AdminLoginHistoryUpsertBulk {
+ return u.Update(func(s *AdminLoginHistoryUpsert) {
+ s.UpdateDevice()
+ })
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (u *AdminLoginHistoryUpsertBulk) SetCreatedAt(v time.Time) *AdminLoginHistoryUpsertBulk {
+ return u.Update(func(s *AdminLoginHistoryUpsert) {
+ s.SetCreatedAt(v)
+ })
+}
+
+// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
+func (u *AdminLoginHistoryUpsertBulk) UpdateCreatedAt() *AdminLoginHistoryUpsertBulk {
+ return u.Update(func(s *AdminLoginHistoryUpsert) {
+ s.UpdateCreatedAt()
+ })
+}
+
+// Exec executes the query.
+func (u *AdminLoginHistoryUpsertBulk) Exec(ctx context.Context) error {
+ if u.create.err != nil {
+ return u.create.err
+ }
+ for i, b := range u.create.builders {
+ if len(b.conflict) != 0 {
+ return fmt.Errorf("db: OnConflict was set for builder %d. Set it on the AdminLoginHistoryCreateBulk instead", i)
+ }
+ }
+ if len(u.create.conflict) == 0 {
+ return errors.New("db: missing options for AdminLoginHistoryCreateBulk.OnConflict")
+ }
+ return u.create.Exec(ctx)
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (u *AdminLoginHistoryUpsertBulk) ExecX(ctx context.Context) {
+ if err := u.create.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
diff --git a/backend/db/adminloginhistory_delete.go b/backend/db/adminloginhistory_delete.go
new file mode 100644
index 0000000..869a0f7
--- /dev/null
+++ b/backend/db/adminloginhistory_delete.go
@@ -0,0 +1,88 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/adminloginhistory"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+)
+
+// AdminLoginHistoryDelete is the builder for deleting a AdminLoginHistory entity.
+type AdminLoginHistoryDelete struct {
+ config
+ hooks []Hook
+ mutation *AdminLoginHistoryMutation
+}
+
+// Where appends a list predicates to the AdminLoginHistoryDelete builder.
+func (alhd *AdminLoginHistoryDelete) Where(ps ...predicate.AdminLoginHistory) *AdminLoginHistoryDelete {
+ alhd.mutation.Where(ps...)
+ return alhd
+}
+
+// Exec executes the deletion query and returns how many vertices were deleted.
+func (alhd *AdminLoginHistoryDelete) Exec(ctx context.Context) (int, error) {
+ return withHooks(ctx, alhd.sqlExec, alhd.mutation, alhd.hooks)
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (alhd *AdminLoginHistoryDelete) ExecX(ctx context.Context) int {
+ n, err := alhd.Exec(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return n
+}
+
+func (alhd *AdminLoginHistoryDelete) sqlExec(ctx context.Context) (int, error) {
+ _spec := sqlgraph.NewDeleteSpec(adminloginhistory.Table, sqlgraph.NewFieldSpec(adminloginhistory.FieldID, field.TypeUUID))
+ if ps := alhd.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ affected, err := sqlgraph.DeleteNodes(ctx, alhd.driver, _spec)
+ if err != nil && sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ alhd.mutation.done = true
+ return affected, err
+}
+
+// AdminLoginHistoryDeleteOne is the builder for deleting a single AdminLoginHistory entity.
+type AdminLoginHistoryDeleteOne struct {
+ alhd *AdminLoginHistoryDelete
+}
+
+// Where appends a list predicates to the AdminLoginHistoryDelete builder.
+func (alhdo *AdminLoginHistoryDeleteOne) Where(ps ...predicate.AdminLoginHistory) *AdminLoginHistoryDeleteOne {
+ alhdo.alhd.mutation.Where(ps...)
+ return alhdo
+}
+
+// Exec executes the deletion query.
+func (alhdo *AdminLoginHistoryDeleteOne) Exec(ctx context.Context) error {
+ n, err := alhdo.alhd.Exec(ctx)
+ switch {
+ case err != nil:
+ return err
+ case n == 0:
+ return &NotFoundError{adminloginhistory.Label}
+ default:
+ return nil
+ }
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (alhdo *AdminLoginHistoryDeleteOne) ExecX(ctx context.Context) {
+ if err := alhdo.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
diff --git a/backend/db/adminloginhistory_query.go b/backend/db/adminloginhistory_query.go
new file mode 100644
index 0000000..afac175
--- /dev/null
+++ b/backend/db/adminloginhistory_query.go
@@ -0,0 +1,665 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "fmt"
+ "math"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect"
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/admin"
+ "github.com/chaitin/MonkeyCode/backend/db/adminloginhistory"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+ "github.com/google/uuid"
+)
+
+// AdminLoginHistoryQuery is the builder for querying AdminLoginHistory entities.
+type AdminLoginHistoryQuery struct {
+ config
+ ctx *QueryContext
+ order []adminloginhistory.OrderOption
+ inters []Interceptor
+ predicates []predicate.AdminLoginHistory
+ withOwner *AdminQuery
+ withFKs bool
+ modifiers []func(*sql.Selector)
+ // intermediate query (i.e. traversal path).
+ sql *sql.Selector
+ path func(context.Context) (*sql.Selector, error)
+}
+
+// Where adds a new predicate for the AdminLoginHistoryQuery builder.
+func (alhq *AdminLoginHistoryQuery) Where(ps ...predicate.AdminLoginHistory) *AdminLoginHistoryQuery {
+ alhq.predicates = append(alhq.predicates, ps...)
+ return alhq
+}
+
+// Limit the number of records to be returned by this query.
+func (alhq *AdminLoginHistoryQuery) Limit(limit int) *AdminLoginHistoryQuery {
+ alhq.ctx.Limit = &limit
+ return alhq
+}
+
+// Offset to start from.
+func (alhq *AdminLoginHistoryQuery) Offset(offset int) *AdminLoginHistoryQuery {
+ alhq.ctx.Offset = &offset
+ return alhq
+}
+
+// Unique configures the query builder to filter duplicate records on query.
+// By default, unique is set to true, and can be disabled using this method.
+func (alhq *AdminLoginHistoryQuery) Unique(unique bool) *AdminLoginHistoryQuery {
+ alhq.ctx.Unique = &unique
+ return alhq
+}
+
+// Order specifies how the records should be ordered.
+func (alhq *AdminLoginHistoryQuery) Order(o ...adminloginhistory.OrderOption) *AdminLoginHistoryQuery {
+ alhq.order = append(alhq.order, o...)
+ return alhq
+}
+
+// QueryOwner chains the current query on the "owner" edge.
+func (alhq *AdminLoginHistoryQuery) QueryOwner() *AdminQuery {
+ query := (&AdminClient{config: alhq.config}).Query()
+ query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
+ if err := alhq.prepareQuery(ctx); err != nil {
+ return nil, err
+ }
+ selector := alhq.sqlQuery(ctx)
+ if err := selector.Err(); err != nil {
+ return nil, err
+ }
+ step := sqlgraph.NewStep(
+ sqlgraph.From(adminloginhistory.Table, adminloginhistory.FieldID, selector),
+ sqlgraph.To(admin.Table, admin.FieldID),
+ sqlgraph.Edge(sqlgraph.M2O, true, adminloginhistory.OwnerTable, adminloginhistory.OwnerColumn),
+ )
+ fromU = sqlgraph.SetNeighbors(alhq.driver.Dialect(), step)
+ return fromU, nil
+ }
+ return query
+}
+
+// First returns the first AdminLoginHistory entity from the query.
+// Returns a *NotFoundError when no AdminLoginHistory was found.
+func (alhq *AdminLoginHistoryQuery) First(ctx context.Context) (*AdminLoginHistory, error) {
+ nodes, err := alhq.Limit(1).All(setContextOp(ctx, alhq.ctx, ent.OpQueryFirst))
+ if err != nil {
+ return nil, err
+ }
+ if len(nodes) == 0 {
+ return nil, &NotFoundError{adminloginhistory.Label}
+ }
+ return nodes[0], nil
+}
+
+// FirstX is like First, but panics if an error occurs.
+func (alhq *AdminLoginHistoryQuery) FirstX(ctx context.Context) *AdminLoginHistory {
+ node, err := alhq.First(ctx)
+ if err != nil && !IsNotFound(err) {
+ panic(err)
+ }
+ return node
+}
+
+// FirstID returns the first AdminLoginHistory ID from the query.
+// Returns a *NotFoundError when no AdminLoginHistory ID was found.
+func (alhq *AdminLoginHistoryQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
+ var ids []uuid.UUID
+ if ids, err = alhq.Limit(1).IDs(setContextOp(ctx, alhq.ctx, ent.OpQueryFirstID)); err != nil {
+ return
+ }
+ if len(ids) == 0 {
+ err = &NotFoundError{adminloginhistory.Label}
+ return
+ }
+ return ids[0], nil
+}
+
+// FirstIDX is like FirstID, but panics if an error occurs.
+func (alhq *AdminLoginHistoryQuery) FirstIDX(ctx context.Context) uuid.UUID {
+ id, err := alhq.FirstID(ctx)
+ if err != nil && !IsNotFound(err) {
+ panic(err)
+ }
+ return id
+}
+
+// Only returns a single AdminLoginHistory entity found by the query, ensuring it only returns one.
+// Returns a *NotSingularError when more than one AdminLoginHistory entity is found.
+// Returns a *NotFoundError when no AdminLoginHistory entities are found.
+func (alhq *AdminLoginHistoryQuery) Only(ctx context.Context) (*AdminLoginHistory, error) {
+ nodes, err := alhq.Limit(2).All(setContextOp(ctx, alhq.ctx, ent.OpQueryOnly))
+ if err != nil {
+ return nil, err
+ }
+ switch len(nodes) {
+ case 1:
+ return nodes[0], nil
+ case 0:
+ return nil, &NotFoundError{adminloginhistory.Label}
+ default:
+ return nil, &NotSingularError{adminloginhistory.Label}
+ }
+}
+
+// OnlyX is like Only, but panics if an error occurs.
+func (alhq *AdminLoginHistoryQuery) OnlyX(ctx context.Context) *AdminLoginHistory {
+ node, err := alhq.Only(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return node
+}
+
+// OnlyID is like Only, but returns the only AdminLoginHistory ID in the query.
+// Returns a *NotSingularError when more than one AdminLoginHistory ID is found.
+// Returns a *NotFoundError when no entities are found.
+func (alhq *AdminLoginHistoryQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
+ var ids []uuid.UUID
+ if ids, err = alhq.Limit(2).IDs(setContextOp(ctx, alhq.ctx, ent.OpQueryOnlyID)); err != nil {
+ return
+ }
+ switch len(ids) {
+ case 1:
+ id = ids[0]
+ case 0:
+ err = &NotFoundError{adminloginhistory.Label}
+ default:
+ err = &NotSingularError{adminloginhistory.Label}
+ }
+ return
+}
+
+// OnlyIDX is like OnlyID, but panics if an error occurs.
+func (alhq *AdminLoginHistoryQuery) OnlyIDX(ctx context.Context) uuid.UUID {
+ id, err := alhq.OnlyID(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return id
+}
+
+// All executes the query and returns a list of AdminLoginHistories.
+func (alhq *AdminLoginHistoryQuery) All(ctx context.Context) ([]*AdminLoginHistory, error) {
+ ctx = setContextOp(ctx, alhq.ctx, ent.OpQueryAll)
+ if err := alhq.prepareQuery(ctx); err != nil {
+ return nil, err
+ }
+ qr := querierAll[[]*AdminLoginHistory, *AdminLoginHistoryQuery]()
+ return withInterceptors[[]*AdminLoginHistory](ctx, alhq, qr, alhq.inters)
+}
+
+// AllX is like All, but panics if an error occurs.
+func (alhq *AdminLoginHistoryQuery) AllX(ctx context.Context) []*AdminLoginHistory {
+ nodes, err := alhq.All(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return nodes
+}
+
+// IDs executes the query and returns a list of AdminLoginHistory IDs.
+func (alhq *AdminLoginHistoryQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) {
+ if alhq.ctx.Unique == nil && alhq.path != nil {
+ alhq.Unique(true)
+ }
+ ctx = setContextOp(ctx, alhq.ctx, ent.OpQueryIDs)
+ if err = alhq.Select(adminloginhistory.FieldID).Scan(ctx, &ids); err != nil {
+ return nil, err
+ }
+ return ids, nil
+}
+
+// IDsX is like IDs, but panics if an error occurs.
+func (alhq *AdminLoginHistoryQuery) IDsX(ctx context.Context) []uuid.UUID {
+ ids, err := alhq.IDs(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return ids
+}
+
+// Count returns the count of the given query.
+func (alhq *AdminLoginHistoryQuery) Count(ctx context.Context) (int, error) {
+ ctx = setContextOp(ctx, alhq.ctx, ent.OpQueryCount)
+ if err := alhq.prepareQuery(ctx); err != nil {
+ return 0, err
+ }
+ return withInterceptors[int](ctx, alhq, querierCount[*AdminLoginHistoryQuery](), alhq.inters)
+}
+
+// CountX is like Count, but panics if an error occurs.
+func (alhq *AdminLoginHistoryQuery) CountX(ctx context.Context) int {
+ count, err := alhq.Count(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return count
+}
+
+// Exist returns true if the query has elements in the graph.
+func (alhq *AdminLoginHistoryQuery) Exist(ctx context.Context) (bool, error) {
+ ctx = setContextOp(ctx, alhq.ctx, ent.OpQueryExist)
+ switch _, err := alhq.FirstID(ctx); {
+ case IsNotFound(err):
+ return false, nil
+ case err != nil:
+ return false, fmt.Errorf("db: check existence: %w", err)
+ default:
+ return true, nil
+ }
+}
+
+// ExistX is like Exist, but panics if an error occurs.
+func (alhq *AdminLoginHistoryQuery) ExistX(ctx context.Context) bool {
+ exist, err := alhq.Exist(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return exist
+}
+
+// Clone returns a duplicate of the AdminLoginHistoryQuery builder, including all associated steps. It can be
+// used to prepare common query builders and use them differently after the clone is made.
+func (alhq *AdminLoginHistoryQuery) Clone() *AdminLoginHistoryQuery {
+ if alhq == nil {
+ return nil
+ }
+ return &AdminLoginHistoryQuery{
+ config: alhq.config,
+ ctx: alhq.ctx.Clone(),
+ order: append([]adminloginhistory.OrderOption{}, alhq.order...),
+ inters: append([]Interceptor{}, alhq.inters...),
+ predicates: append([]predicate.AdminLoginHistory{}, alhq.predicates...),
+ withOwner: alhq.withOwner.Clone(),
+ // clone intermediate query.
+ sql: alhq.sql.Clone(),
+ path: alhq.path,
+ modifiers: append([]func(*sql.Selector){}, alhq.modifiers...),
+ }
+}
+
+// WithOwner tells the query-builder to eager-load the nodes that are connected to
+// the "owner" edge. The optional arguments are used to configure the query builder of the edge.
+func (alhq *AdminLoginHistoryQuery) WithOwner(opts ...func(*AdminQuery)) *AdminLoginHistoryQuery {
+ query := (&AdminClient{config: alhq.config}).Query()
+ for _, opt := range opts {
+ opt(query)
+ }
+ alhq.withOwner = query
+ return alhq
+}
+
+// GroupBy is used to group vertices by one or more fields/columns.
+// It is often used with aggregate functions, like: count, max, mean, min, sum.
+//
+// Example:
+//
+// var v []struct {
+// AdminID uuid.UUID `json:"admin_id,omitempty"`
+// Count int `json:"count,omitempty"`
+// }
+//
+// client.AdminLoginHistory.Query().
+// GroupBy(adminloginhistory.FieldAdminID).
+// Aggregate(db.Count()).
+// Scan(ctx, &v)
+func (alhq *AdminLoginHistoryQuery) GroupBy(field string, fields ...string) *AdminLoginHistoryGroupBy {
+ alhq.ctx.Fields = append([]string{field}, fields...)
+ grbuild := &AdminLoginHistoryGroupBy{build: alhq}
+ grbuild.flds = &alhq.ctx.Fields
+ grbuild.label = adminloginhistory.Label
+ grbuild.scan = grbuild.Scan
+ return grbuild
+}
+
+// Select allows the selection one or more fields/columns for the given query,
+// instead of selecting all fields in the entity.
+//
+// Example:
+//
+// var v []struct {
+// AdminID uuid.UUID `json:"admin_id,omitempty"`
+// }
+//
+// client.AdminLoginHistory.Query().
+// Select(adminloginhistory.FieldAdminID).
+// Scan(ctx, &v)
+func (alhq *AdminLoginHistoryQuery) Select(fields ...string) *AdminLoginHistorySelect {
+ alhq.ctx.Fields = append(alhq.ctx.Fields, fields...)
+ sbuild := &AdminLoginHistorySelect{AdminLoginHistoryQuery: alhq}
+ sbuild.label = adminloginhistory.Label
+ sbuild.flds, sbuild.scan = &alhq.ctx.Fields, sbuild.Scan
+ return sbuild
+}
+
+// Aggregate returns a AdminLoginHistorySelect configured with the given aggregations.
+func (alhq *AdminLoginHistoryQuery) Aggregate(fns ...AggregateFunc) *AdminLoginHistorySelect {
+ return alhq.Select().Aggregate(fns...)
+}
+
+func (alhq *AdminLoginHistoryQuery) prepareQuery(ctx context.Context) error {
+ for _, inter := range alhq.inters {
+ if inter == nil {
+ return fmt.Errorf("db: uninitialized interceptor (forgotten import db/runtime?)")
+ }
+ if trv, ok := inter.(Traverser); ok {
+ if err := trv.Traverse(ctx, alhq); err != nil {
+ return err
+ }
+ }
+ }
+ for _, f := range alhq.ctx.Fields {
+ if !adminloginhistory.ValidColumn(f) {
+ return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
+ }
+ }
+ if alhq.path != nil {
+ prev, err := alhq.path(ctx)
+ if err != nil {
+ return err
+ }
+ alhq.sql = prev
+ }
+ return nil
+}
+
+func (alhq *AdminLoginHistoryQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*AdminLoginHistory, error) {
+ var (
+ nodes = []*AdminLoginHistory{}
+ withFKs = alhq.withFKs
+ _spec = alhq.querySpec()
+ loadedTypes = [1]bool{
+ alhq.withOwner != nil,
+ }
+ )
+ if alhq.withOwner != nil {
+ withFKs = true
+ }
+ if withFKs {
+ _spec.Node.Columns = append(_spec.Node.Columns, adminloginhistory.ForeignKeys...)
+ }
+ _spec.ScanValues = func(columns []string) ([]any, error) {
+ return (*AdminLoginHistory).scanValues(nil, columns)
+ }
+ _spec.Assign = func(columns []string, values []any) error {
+ node := &AdminLoginHistory{config: alhq.config}
+ nodes = append(nodes, node)
+ node.Edges.loadedTypes = loadedTypes
+ return node.assignValues(columns, values)
+ }
+ if len(alhq.modifiers) > 0 {
+ _spec.Modifiers = alhq.modifiers
+ }
+ for i := range hooks {
+ hooks[i](ctx, _spec)
+ }
+ if err := sqlgraph.QueryNodes(ctx, alhq.driver, _spec); err != nil {
+ return nil, err
+ }
+ if len(nodes) == 0 {
+ return nodes, nil
+ }
+ if query := alhq.withOwner; query != nil {
+ if err := alhq.loadOwner(ctx, query, nodes, nil,
+ func(n *AdminLoginHistory, e *Admin) { n.Edges.Owner = e }); err != nil {
+ return nil, err
+ }
+ }
+ return nodes, nil
+}
+
+func (alhq *AdminLoginHistoryQuery) loadOwner(ctx context.Context, query *AdminQuery, nodes []*AdminLoginHistory, init func(*AdminLoginHistory), assign func(*AdminLoginHistory, *Admin)) error {
+ ids := make([]uuid.UUID, 0, len(nodes))
+ nodeids := make(map[uuid.UUID][]*AdminLoginHistory)
+ for i := range nodes {
+ if nodes[i].admin_login_histories == nil {
+ continue
+ }
+ fk := *nodes[i].admin_login_histories
+ if _, ok := nodeids[fk]; !ok {
+ ids = append(ids, fk)
+ }
+ nodeids[fk] = append(nodeids[fk], nodes[i])
+ }
+ if len(ids) == 0 {
+ return nil
+ }
+ query.Where(admin.IDIn(ids...))
+ neighbors, err := query.All(ctx)
+ if err != nil {
+ return err
+ }
+ for _, n := range neighbors {
+ nodes, ok := nodeids[n.ID]
+ if !ok {
+ return fmt.Errorf(`unexpected foreign-key "admin_login_histories" returned %v`, n.ID)
+ }
+ for i := range nodes {
+ assign(nodes[i], n)
+ }
+ }
+ return nil
+}
+
+func (alhq *AdminLoginHistoryQuery) sqlCount(ctx context.Context) (int, error) {
+ _spec := alhq.querySpec()
+ if len(alhq.modifiers) > 0 {
+ _spec.Modifiers = alhq.modifiers
+ }
+ _spec.Node.Columns = alhq.ctx.Fields
+ if len(alhq.ctx.Fields) > 0 {
+ _spec.Unique = alhq.ctx.Unique != nil && *alhq.ctx.Unique
+ }
+ return sqlgraph.CountNodes(ctx, alhq.driver, _spec)
+}
+
+func (alhq *AdminLoginHistoryQuery) querySpec() *sqlgraph.QuerySpec {
+ _spec := sqlgraph.NewQuerySpec(adminloginhistory.Table, adminloginhistory.Columns, sqlgraph.NewFieldSpec(adminloginhistory.FieldID, field.TypeUUID))
+ _spec.From = alhq.sql
+ if unique := alhq.ctx.Unique; unique != nil {
+ _spec.Unique = *unique
+ } else if alhq.path != nil {
+ _spec.Unique = true
+ }
+ if fields := alhq.ctx.Fields; len(fields) > 0 {
+ _spec.Node.Columns = make([]string, 0, len(fields))
+ _spec.Node.Columns = append(_spec.Node.Columns, adminloginhistory.FieldID)
+ for i := range fields {
+ if fields[i] != adminloginhistory.FieldID {
+ _spec.Node.Columns = append(_spec.Node.Columns, fields[i])
+ }
+ }
+ }
+ if ps := alhq.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if limit := alhq.ctx.Limit; limit != nil {
+ _spec.Limit = *limit
+ }
+ if offset := alhq.ctx.Offset; offset != nil {
+ _spec.Offset = *offset
+ }
+ if ps := alhq.order; len(ps) > 0 {
+ _spec.Order = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ return _spec
+}
+
+func (alhq *AdminLoginHistoryQuery) sqlQuery(ctx context.Context) *sql.Selector {
+ builder := sql.Dialect(alhq.driver.Dialect())
+ t1 := builder.Table(adminloginhistory.Table)
+ columns := alhq.ctx.Fields
+ if len(columns) == 0 {
+ columns = adminloginhistory.Columns
+ }
+ selector := builder.Select(t1.Columns(columns...)...).From(t1)
+ if alhq.sql != nil {
+ selector = alhq.sql
+ selector.Select(selector.Columns(columns...)...)
+ }
+ if alhq.ctx.Unique != nil && *alhq.ctx.Unique {
+ selector.Distinct()
+ }
+ for _, m := range alhq.modifiers {
+ m(selector)
+ }
+ for _, p := range alhq.predicates {
+ p(selector)
+ }
+ for _, p := range alhq.order {
+ p(selector)
+ }
+ if offset := alhq.ctx.Offset; offset != nil {
+ // limit is mandatory for offset clause. We start
+ // with default value, and override it below if needed.
+ selector.Offset(*offset).Limit(math.MaxInt32)
+ }
+ if limit := alhq.ctx.Limit; limit != nil {
+ selector.Limit(*limit)
+ }
+ return selector
+}
+
+// ForUpdate locks the selected rows against concurrent updates, and prevent them from being
+// updated, deleted or "selected ... for update" by other sessions, until the transaction is
+// either committed or rolled-back.
+func (alhq *AdminLoginHistoryQuery) ForUpdate(opts ...sql.LockOption) *AdminLoginHistoryQuery {
+ if alhq.driver.Dialect() == dialect.Postgres {
+ alhq.Unique(false)
+ }
+ alhq.modifiers = append(alhq.modifiers, func(s *sql.Selector) {
+ s.ForUpdate(opts...)
+ })
+ return alhq
+}
+
+// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock
+// on any rows that are read. Other sessions can read the rows, but cannot modify them
+// until your transaction commits.
+func (alhq *AdminLoginHistoryQuery) ForShare(opts ...sql.LockOption) *AdminLoginHistoryQuery {
+ if alhq.driver.Dialect() == dialect.Postgres {
+ alhq.Unique(false)
+ }
+ alhq.modifiers = append(alhq.modifiers, func(s *sql.Selector) {
+ s.ForShare(opts...)
+ })
+ return alhq
+}
+
+// Modify adds a query modifier for attaching custom logic to queries.
+func (alhq *AdminLoginHistoryQuery) Modify(modifiers ...func(s *sql.Selector)) *AdminLoginHistorySelect {
+ alhq.modifiers = append(alhq.modifiers, modifiers...)
+ return alhq.Select()
+}
+
+// AdminLoginHistoryGroupBy is the group-by builder for AdminLoginHistory entities.
+type AdminLoginHistoryGroupBy struct {
+ selector
+ build *AdminLoginHistoryQuery
+}
+
+// Aggregate adds the given aggregation functions to the group-by query.
+func (alhgb *AdminLoginHistoryGroupBy) Aggregate(fns ...AggregateFunc) *AdminLoginHistoryGroupBy {
+ alhgb.fns = append(alhgb.fns, fns...)
+ return alhgb
+}
+
+// Scan applies the selector query and scans the result into the given value.
+func (alhgb *AdminLoginHistoryGroupBy) Scan(ctx context.Context, v any) error {
+ ctx = setContextOp(ctx, alhgb.build.ctx, ent.OpQueryGroupBy)
+ if err := alhgb.build.prepareQuery(ctx); err != nil {
+ return err
+ }
+ return scanWithInterceptors[*AdminLoginHistoryQuery, *AdminLoginHistoryGroupBy](ctx, alhgb.build, alhgb, alhgb.build.inters, v)
+}
+
+func (alhgb *AdminLoginHistoryGroupBy) sqlScan(ctx context.Context, root *AdminLoginHistoryQuery, v any) error {
+ selector := root.sqlQuery(ctx).Select()
+ aggregation := make([]string, 0, len(alhgb.fns))
+ for _, fn := range alhgb.fns {
+ aggregation = append(aggregation, fn(selector))
+ }
+ if len(selector.SelectedColumns()) == 0 {
+ columns := make([]string, 0, len(*alhgb.flds)+len(alhgb.fns))
+ for _, f := range *alhgb.flds {
+ columns = append(columns, selector.C(f))
+ }
+ columns = append(columns, aggregation...)
+ selector.Select(columns...)
+ }
+ selector.GroupBy(selector.Columns(*alhgb.flds...)...)
+ if err := selector.Err(); err != nil {
+ return err
+ }
+ rows := &sql.Rows{}
+ query, args := selector.Query()
+ if err := alhgb.build.driver.Query(ctx, query, args, rows); err != nil {
+ return err
+ }
+ defer rows.Close()
+ return sql.ScanSlice(rows, v)
+}
+
+// AdminLoginHistorySelect is the builder for selecting fields of AdminLoginHistory entities.
+type AdminLoginHistorySelect struct {
+ *AdminLoginHistoryQuery
+ selector
+}
+
+// Aggregate adds the given aggregation functions to the selector query.
+func (alhs *AdminLoginHistorySelect) Aggregate(fns ...AggregateFunc) *AdminLoginHistorySelect {
+ alhs.fns = append(alhs.fns, fns...)
+ return alhs
+}
+
+// Scan applies the selector query and scans the result into the given value.
+func (alhs *AdminLoginHistorySelect) Scan(ctx context.Context, v any) error {
+ ctx = setContextOp(ctx, alhs.ctx, ent.OpQuerySelect)
+ if err := alhs.prepareQuery(ctx); err != nil {
+ return err
+ }
+ return scanWithInterceptors[*AdminLoginHistoryQuery, *AdminLoginHistorySelect](ctx, alhs.AdminLoginHistoryQuery, alhs, alhs.inters, v)
+}
+
+func (alhs *AdminLoginHistorySelect) sqlScan(ctx context.Context, root *AdminLoginHistoryQuery, v any) error {
+ selector := root.sqlQuery(ctx)
+ aggregation := make([]string, 0, len(alhs.fns))
+ for _, fn := range alhs.fns {
+ aggregation = append(aggregation, fn(selector))
+ }
+ switch n := len(*alhs.selector.flds); {
+ case n == 0 && len(aggregation) > 0:
+ selector.Select(aggregation...)
+ case n != 0 && len(aggregation) > 0:
+ selector.AppendSelect(aggregation...)
+ }
+ rows := &sql.Rows{}
+ query, args := selector.Query()
+ if err := alhs.driver.Query(ctx, query, args, rows); err != nil {
+ return err
+ }
+ defer rows.Close()
+ return sql.ScanSlice(rows, v)
+}
+
+// Modify adds a query modifier for attaching custom logic to queries.
+func (alhs *AdminLoginHistorySelect) Modify(modifiers ...func(s *sql.Selector)) *AdminLoginHistorySelect {
+ alhs.modifiers = append(alhs.modifiers, modifiers...)
+ return alhs
+}
diff --git a/backend/db/adminloginhistory_update.go b/backend/db/adminloginhistory_update.go
new file mode 100644
index 0000000..3f58dae
--- /dev/null
+++ b/backend/db/adminloginhistory_update.go
@@ -0,0 +1,642 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "time"
+
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/admin"
+ "github.com/chaitin/MonkeyCode/backend/db/adminloginhistory"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+ "github.com/google/uuid"
+)
+
+// AdminLoginHistoryUpdate is the builder for updating AdminLoginHistory entities.
+type AdminLoginHistoryUpdate struct {
+ config
+ hooks []Hook
+ mutation *AdminLoginHistoryMutation
+ modifiers []func(*sql.UpdateBuilder)
+}
+
+// Where appends a list predicates to the AdminLoginHistoryUpdate builder.
+func (alhu *AdminLoginHistoryUpdate) Where(ps ...predicate.AdminLoginHistory) *AdminLoginHistoryUpdate {
+ alhu.mutation.Where(ps...)
+ return alhu
+}
+
+// SetAdminID sets the "admin_id" field.
+func (alhu *AdminLoginHistoryUpdate) SetAdminID(u uuid.UUID) *AdminLoginHistoryUpdate {
+ alhu.mutation.SetAdminID(u)
+ return alhu
+}
+
+// SetNillableAdminID sets the "admin_id" field if the given value is not nil.
+func (alhu *AdminLoginHistoryUpdate) SetNillableAdminID(u *uuid.UUID) *AdminLoginHistoryUpdate {
+ if u != nil {
+ alhu.SetAdminID(*u)
+ }
+ return alhu
+}
+
+// SetIP sets the "ip" field.
+func (alhu *AdminLoginHistoryUpdate) SetIP(s string) *AdminLoginHistoryUpdate {
+ alhu.mutation.SetIP(s)
+ return alhu
+}
+
+// SetNillableIP sets the "ip" field if the given value is not nil.
+func (alhu *AdminLoginHistoryUpdate) SetNillableIP(s *string) *AdminLoginHistoryUpdate {
+ if s != nil {
+ alhu.SetIP(*s)
+ }
+ return alhu
+}
+
+// SetCountry sets the "country" field.
+func (alhu *AdminLoginHistoryUpdate) SetCountry(s string) *AdminLoginHistoryUpdate {
+ alhu.mutation.SetCountry(s)
+ return alhu
+}
+
+// SetNillableCountry sets the "country" field if the given value is not nil.
+func (alhu *AdminLoginHistoryUpdate) SetNillableCountry(s *string) *AdminLoginHistoryUpdate {
+ if s != nil {
+ alhu.SetCountry(*s)
+ }
+ return alhu
+}
+
+// SetProvince sets the "province" field.
+func (alhu *AdminLoginHistoryUpdate) SetProvince(s string) *AdminLoginHistoryUpdate {
+ alhu.mutation.SetProvince(s)
+ return alhu
+}
+
+// SetNillableProvince sets the "province" field if the given value is not nil.
+func (alhu *AdminLoginHistoryUpdate) SetNillableProvince(s *string) *AdminLoginHistoryUpdate {
+ if s != nil {
+ alhu.SetProvince(*s)
+ }
+ return alhu
+}
+
+// SetCity sets the "city" field.
+func (alhu *AdminLoginHistoryUpdate) SetCity(s string) *AdminLoginHistoryUpdate {
+ alhu.mutation.SetCity(s)
+ return alhu
+}
+
+// SetNillableCity sets the "city" field if the given value is not nil.
+func (alhu *AdminLoginHistoryUpdate) SetNillableCity(s *string) *AdminLoginHistoryUpdate {
+ if s != nil {
+ alhu.SetCity(*s)
+ }
+ return alhu
+}
+
+// SetIsp sets the "isp" field.
+func (alhu *AdminLoginHistoryUpdate) SetIsp(s string) *AdminLoginHistoryUpdate {
+ alhu.mutation.SetIsp(s)
+ return alhu
+}
+
+// SetNillableIsp sets the "isp" field if the given value is not nil.
+func (alhu *AdminLoginHistoryUpdate) SetNillableIsp(s *string) *AdminLoginHistoryUpdate {
+ if s != nil {
+ alhu.SetIsp(*s)
+ }
+ return alhu
+}
+
+// SetAsn sets the "asn" field.
+func (alhu *AdminLoginHistoryUpdate) SetAsn(s string) *AdminLoginHistoryUpdate {
+ alhu.mutation.SetAsn(s)
+ return alhu
+}
+
+// SetNillableAsn sets the "asn" field if the given value is not nil.
+func (alhu *AdminLoginHistoryUpdate) SetNillableAsn(s *string) *AdminLoginHistoryUpdate {
+ if s != nil {
+ alhu.SetAsn(*s)
+ }
+ return alhu
+}
+
+// SetClientVersion sets the "client_version" field.
+func (alhu *AdminLoginHistoryUpdate) SetClientVersion(s string) *AdminLoginHistoryUpdate {
+ alhu.mutation.SetClientVersion(s)
+ return alhu
+}
+
+// SetNillableClientVersion sets the "client_version" field if the given value is not nil.
+func (alhu *AdminLoginHistoryUpdate) SetNillableClientVersion(s *string) *AdminLoginHistoryUpdate {
+ if s != nil {
+ alhu.SetClientVersion(*s)
+ }
+ return alhu
+}
+
+// SetDevice sets the "device" field.
+func (alhu *AdminLoginHistoryUpdate) SetDevice(s string) *AdminLoginHistoryUpdate {
+ alhu.mutation.SetDevice(s)
+ return alhu
+}
+
+// SetNillableDevice sets the "device" field if the given value is not nil.
+func (alhu *AdminLoginHistoryUpdate) SetNillableDevice(s *string) *AdminLoginHistoryUpdate {
+ if s != nil {
+ alhu.SetDevice(*s)
+ }
+ return alhu
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (alhu *AdminLoginHistoryUpdate) SetCreatedAt(t time.Time) *AdminLoginHistoryUpdate {
+ alhu.mutation.SetCreatedAt(t)
+ return alhu
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (alhu *AdminLoginHistoryUpdate) SetNillableCreatedAt(t *time.Time) *AdminLoginHistoryUpdate {
+ if t != nil {
+ alhu.SetCreatedAt(*t)
+ }
+ return alhu
+}
+
+// SetOwnerID sets the "owner" edge to the Admin entity by ID.
+func (alhu *AdminLoginHistoryUpdate) SetOwnerID(id uuid.UUID) *AdminLoginHistoryUpdate {
+ alhu.mutation.SetOwnerID(id)
+ return alhu
+}
+
+// SetNillableOwnerID sets the "owner" edge to the Admin entity by ID if the given value is not nil.
+func (alhu *AdminLoginHistoryUpdate) SetNillableOwnerID(id *uuid.UUID) *AdminLoginHistoryUpdate {
+ if id != nil {
+ alhu = alhu.SetOwnerID(*id)
+ }
+ return alhu
+}
+
+// SetOwner sets the "owner" edge to the Admin entity.
+func (alhu *AdminLoginHistoryUpdate) SetOwner(a *Admin) *AdminLoginHistoryUpdate {
+ return alhu.SetOwnerID(a.ID)
+}
+
+// Mutation returns the AdminLoginHistoryMutation object of the builder.
+func (alhu *AdminLoginHistoryUpdate) Mutation() *AdminLoginHistoryMutation {
+ return alhu.mutation
+}
+
+// ClearOwner clears the "owner" edge to the Admin entity.
+func (alhu *AdminLoginHistoryUpdate) ClearOwner() *AdminLoginHistoryUpdate {
+ alhu.mutation.ClearOwner()
+ return alhu
+}
+
+// Save executes the query and returns the number of nodes affected by the update operation.
+func (alhu *AdminLoginHistoryUpdate) Save(ctx context.Context) (int, error) {
+ return withHooks(ctx, alhu.sqlSave, alhu.mutation, alhu.hooks)
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (alhu *AdminLoginHistoryUpdate) SaveX(ctx context.Context) int {
+ affected, err := alhu.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return affected
+}
+
+// Exec executes the query.
+func (alhu *AdminLoginHistoryUpdate) Exec(ctx context.Context) error {
+ _, err := alhu.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (alhu *AdminLoginHistoryUpdate) ExecX(ctx context.Context) {
+ if err := alhu.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
+func (alhu *AdminLoginHistoryUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *AdminLoginHistoryUpdate {
+ alhu.modifiers = append(alhu.modifiers, modifiers...)
+ return alhu
+}
+
+func (alhu *AdminLoginHistoryUpdate) sqlSave(ctx context.Context) (n int, err error) {
+ _spec := sqlgraph.NewUpdateSpec(adminloginhistory.Table, adminloginhistory.Columns, sqlgraph.NewFieldSpec(adminloginhistory.FieldID, field.TypeUUID))
+ if ps := alhu.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if value, ok := alhu.mutation.AdminID(); ok {
+ _spec.SetField(adminloginhistory.FieldAdminID, field.TypeUUID, value)
+ }
+ if value, ok := alhu.mutation.IP(); ok {
+ _spec.SetField(adminloginhistory.FieldIP, field.TypeString, value)
+ }
+ if value, ok := alhu.mutation.Country(); ok {
+ _spec.SetField(adminloginhistory.FieldCountry, field.TypeString, value)
+ }
+ if value, ok := alhu.mutation.Province(); ok {
+ _spec.SetField(adminloginhistory.FieldProvince, field.TypeString, value)
+ }
+ if value, ok := alhu.mutation.City(); ok {
+ _spec.SetField(adminloginhistory.FieldCity, field.TypeString, value)
+ }
+ if value, ok := alhu.mutation.Isp(); ok {
+ _spec.SetField(adminloginhistory.FieldIsp, field.TypeString, value)
+ }
+ if value, ok := alhu.mutation.Asn(); ok {
+ _spec.SetField(adminloginhistory.FieldAsn, field.TypeString, value)
+ }
+ if value, ok := alhu.mutation.ClientVersion(); ok {
+ _spec.SetField(adminloginhistory.FieldClientVersion, field.TypeString, value)
+ }
+ if value, ok := alhu.mutation.Device(); ok {
+ _spec.SetField(adminloginhistory.FieldDevice, field.TypeString, value)
+ }
+ if value, ok := alhu.mutation.CreatedAt(); ok {
+ _spec.SetField(adminloginhistory.FieldCreatedAt, field.TypeTime, value)
+ }
+ if alhu.mutation.OwnerCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: true,
+ Table: adminloginhistory.OwnerTable,
+ Columns: []string{adminloginhistory.OwnerColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(admin.FieldID, field.TypeUUID),
+ },
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := alhu.mutation.OwnerIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: true,
+ Table: adminloginhistory.OwnerTable,
+ Columns: []string{adminloginhistory.OwnerColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(admin.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Add = append(_spec.Edges.Add, edge)
+ }
+ _spec.AddModifiers(alhu.modifiers...)
+ if n, err = sqlgraph.UpdateNodes(ctx, alhu.driver, _spec); err != nil {
+ if _, ok := err.(*sqlgraph.NotFoundError); ok {
+ err = &NotFoundError{adminloginhistory.Label}
+ } else if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return 0, err
+ }
+ alhu.mutation.done = true
+ return n, nil
+}
+
+// AdminLoginHistoryUpdateOne is the builder for updating a single AdminLoginHistory entity.
+type AdminLoginHistoryUpdateOne struct {
+ config
+ fields []string
+ hooks []Hook
+ mutation *AdminLoginHistoryMutation
+ modifiers []func(*sql.UpdateBuilder)
+}
+
+// SetAdminID sets the "admin_id" field.
+func (alhuo *AdminLoginHistoryUpdateOne) SetAdminID(u uuid.UUID) *AdminLoginHistoryUpdateOne {
+ alhuo.mutation.SetAdminID(u)
+ return alhuo
+}
+
+// SetNillableAdminID sets the "admin_id" field if the given value is not nil.
+func (alhuo *AdminLoginHistoryUpdateOne) SetNillableAdminID(u *uuid.UUID) *AdminLoginHistoryUpdateOne {
+ if u != nil {
+ alhuo.SetAdminID(*u)
+ }
+ return alhuo
+}
+
+// SetIP sets the "ip" field.
+func (alhuo *AdminLoginHistoryUpdateOne) SetIP(s string) *AdminLoginHistoryUpdateOne {
+ alhuo.mutation.SetIP(s)
+ return alhuo
+}
+
+// SetNillableIP sets the "ip" field if the given value is not nil.
+func (alhuo *AdminLoginHistoryUpdateOne) SetNillableIP(s *string) *AdminLoginHistoryUpdateOne {
+ if s != nil {
+ alhuo.SetIP(*s)
+ }
+ return alhuo
+}
+
+// SetCountry sets the "country" field.
+func (alhuo *AdminLoginHistoryUpdateOne) SetCountry(s string) *AdminLoginHistoryUpdateOne {
+ alhuo.mutation.SetCountry(s)
+ return alhuo
+}
+
+// SetNillableCountry sets the "country" field if the given value is not nil.
+func (alhuo *AdminLoginHistoryUpdateOne) SetNillableCountry(s *string) *AdminLoginHistoryUpdateOne {
+ if s != nil {
+ alhuo.SetCountry(*s)
+ }
+ return alhuo
+}
+
+// SetProvince sets the "province" field.
+func (alhuo *AdminLoginHistoryUpdateOne) SetProvince(s string) *AdminLoginHistoryUpdateOne {
+ alhuo.mutation.SetProvince(s)
+ return alhuo
+}
+
+// SetNillableProvince sets the "province" field if the given value is not nil.
+func (alhuo *AdminLoginHistoryUpdateOne) SetNillableProvince(s *string) *AdminLoginHistoryUpdateOne {
+ if s != nil {
+ alhuo.SetProvince(*s)
+ }
+ return alhuo
+}
+
+// SetCity sets the "city" field.
+func (alhuo *AdminLoginHistoryUpdateOne) SetCity(s string) *AdminLoginHistoryUpdateOne {
+ alhuo.mutation.SetCity(s)
+ return alhuo
+}
+
+// SetNillableCity sets the "city" field if the given value is not nil.
+func (alhuo *AdminLoginHistoryUpdateOne) SetNillableCity(s *string) *AdminLoginHistoryUpdateOne {
+ if s != nil {
+ alhuo.SetCity(*s)
+ }
+ return alhuo
+}
+
+// SetIsp sets the "isp" field.
+func (alhuo *AdminLoginHistoryUpdateOne) SetIsp(s string) *AdminLoginHistoryUpdateOne {
+ alhuo.mutation.SetIsp(s)
+ return alhuo
+}
+
+// SetNillableIsp sets the "isp" field if the given value is not nil.
+func (alhuo *AdminLoginHistoryUpdateOne) SetNillableIsp(s *string) *AdminLoginHistoryUpdateOne {
+ if s != nil {
+ alhuo.SetIsp(*s)
+ }
+ return alhuo
+}
+
+// SetAsn sets the "asn" field.
+func (alhuo *AdminLoginHistoryUpdateOne) SetAsn(s string) *AdminLoginHistoryUpdateOne {
+ alhuo.mutation.SetAsn(s)
+ return alhuo
+}
+
+// SetNillableAsn sets the "asn" field if the given value is not nil.
+func (alhuo *AdminLoginHistoryUpdateOne) SetNillableAsn(s *string) *AdminLoginHistoryUpdateOne {
+ if s != nil {
+ alhuo.SetAsn(*s)
+ }
+ return alhuo
+}
+
+// SetClientVersion sets the "client_version" field.
+func (alhuo *AdminLoginHistoryUpdateOne) SetClientVersion(s string) *AdminLoginHistoryUpdateOne {
+ alhuo.mutation.SetClientVersion(s)
+ return alhuo
+}
+
+// SetNillableClientVersion sets the "client_version" field if the given value is not nil.
+func (alhuo *AdminLoginHistoryUpdateOne) SetNillableClientVersion(s *string) *AdminLoginHistoryUpdateOne {
+ if s != nil {
+ alhuo.SetClientVersion(*s)
+ }
+ return alhuo
+}
+
+// SetDevice sets the "device" field.
+func (alhuo *AdminLoginHistoryUpdateOne) SetDevice(s string) *AdminLoginHistoryUpdateOne {
+ alhuo.mutation.SetDevice(s)
+ return alhuo
+}
+
+// SetNillableDevice sets the "device" field if the given value is not nil.
+func (alhuo *AdminLoginHistoryUpdateOne) SetNillableDevice(s *string) *AdminLoginHistoryUpdateOne {
+ if s != nil {
+ alhuo.SetDevice(*s)
+ }
+ return alhuo
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (alhuo *AdminLoginHistoryUpdateOne) SetCreatedAt(t time.Time) *AdminLoginHistoryUpdateOne {
+ alhuo.mutation.SetCreatedAt(t)
+ return alhuo
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (alhuo *AdminLoginHistoryUpdateOne) SetNillableCreatedAt(t *time.Time) *AdminLoginHistoryUpdateOne {
+ if t != nil {
+ alhuo.SetCreatedAt(*t)
+ }
+ return alhuo
+}
+
+// SetOwnerID sets the "owner" edge to the Admin entity by ID.
+func (alhuo *AdminLoginHistoryUpdateOne) SetOwnerID(id uuid.UUID) *AdminLoginHistoryUpdateOne {
+ alhuo.mutation.SetOwnerID(id)
+ return alhuo
+}
+
+// SetNillableOwnerID sets the "owner" edge to the Admin entity by ID if the given value is not nil.
+func (alhuo *AdminLoginHistoryUpdateOne) SetNillableOwnerID(id *uuid.UUID) *AdminLoginHistoryUpdateOne {
+ if id != nil {
+ alhuo = alhuo.SetOwnerID(*id)
+ }
+ return alhuo
+}
+
+// SetOwner sets the "owner" edge to the Admin entity.
+func (alhuo *AdminLoginHistoryUpdateOne) SetOwner(a *Admin) *AdminLoginHistoryUpdateOne {
+ return alhuo.SetOwnerID(a.ID)
+}
+
+// Mutation returns the AdminLoginHistoryMutation object of the builder.
+func (alhuo *AdminLoginHistoryUpdateOne) Mutation() *AdminLoginHistoryMutation {
+ return alhuo.mutation
+}
+
+// ClearOwner clears the "owner" edge to the Admin entity.
+func (alhuo *AdminLoginHistoryUpdateOne) ClearOwner() *AdminLoginHistoryUpdateOne {
+ alhuo.mutation.ClearOwner()
+ return alhuo
+}
+
+// Where appends a list predicates to the AdminLoginHistoryUpdate builder.
+func (alhuo *AdminLoginHistoryUpdateOne) Where(ps ...predicate.AdminLoginHistory) *AdminLoginHistoryUpdateOne {
+ alhuo.mutation.Where(ps...)
+ return alhuo
+}
+
+// Select allows selecting one or more fields (columns) of the returned entity.
+// The default is selecting all fields defined in the entity schema.
+func (alhuo *AdminLoginHistoryUpdateOne) Select(field string, fields ...string) *AdminLoginHistoryUpdateOne {
+ alhuo.fields = append([]string{field}, fields...)
+ return alhuo
+}
+
+// Save executes the query and returns the updated AdminLoginHistory entity.
+func (alhuo *AdminLoginHistoryUpdateOne) Save(ctx context.Context) (*AdminLoginHistory, error) {
+ return withHooks(ctx, alhuo.sqlSave, alhuo.mutation, alhuo.hooks)
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (alhuo *AdminLoginHistoryUpdateOne) SaveX(ctx context.Context) *AdminLoginHistory {
+ node, err := alhuo.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return node
+}
+
+// Exec executes the query on the entity.
+func (alhuo *AdminLoginHistoryUpdateOne) Exec(ctx context.Context) error {
+ _, err := alhuo.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (alhuo *AdminLoginHistoryUpdateOne) ExecX(ctx context.Context) {
+ if err := alhuo.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
+func (alhuo *AdminLoginHistoryUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *AdminLoginHistoryUpdateOne {
+ alhuo.modifiers = append(alhuo.modifiers, modifiers...)
+ return alhuo
+}
+
+func (alhuo *AdminLoginHistoryUpdateOne) sqlSave(ctx context.Context) (_node *AdminLoginHistory, err error) {
+ _spec := sqlgraph.NewUpdateSpec(adminloginhistory.Table, adminloginhistory.Columns, sqlgraph.NewFieldSpec(adminloginhistory.FieldID, field.TypeUUID))
+ id, ok := alhuo.mutation.ID()
+ if !ok {
+ return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "AdminLoginHistory.id" for update`)}
+ }
+ _spec.Node.ID.Value = id
+ if fields := alhuo.fields; len(fields) > 0 {
+ _spec.Node.Columns = make([]string, 0, len(fields))
+ _spec.Node.Columns = append(_spec.Node.Columns, adminloginhistory.FieldID)
+ for _, f := range fields {
+ if !adminloginhistory.ValidColumn(f) {
+ return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
+ }
+ if f != adminloginhistory.FieldID {
+ _spec.Node.Columns = append(_spec.Node.Columns, f)
+ }
+ }
+ }
+ if ps := alhuo.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if value, ok := alhuo.mutation.AdminID(); ok {
+ _spec.SetField(adminloginhistory.FieldAdminID, field.TypeUUID, value)
+ }
+ if value, ok := alhuo.mutation.IP(); ok {
+ _spec.SetField(adminloginhistory.FieldIP, field.TypeString, value)
+ }
+ if value, ok := alhuo.mutation.Country(); ok {
+ _spec.SetField(adminloginhistory.FieldCountry, field.TypeString, value)
+ }
+ if value, ok := alhuo.mutation.Province(); ok {
+ _spec.SetField(adminloginhistory.FieldProvince, field.TypeString, value)
+ }
+ if value, ok := alhuo.mutation.City(); ok {
+ _spec.SetField(adminloginhistory.FieldCity, field.TypeString, value)
+ }
+ if value, ok := alhuo.mutation.Isp(); ok {
+ _spec.SetField(adminloginhistory.FieldIsp, field.TypeString, value)
+ }
+ if value, ok := alhuo.mutation.Asn(); ok {
+ _spec.SetField(adminloginhistory.FieldAsn, field.TypeString, value)
+ }
+ if value, ok := alhuo.mutation.ClientVersion(); ok {
+ _spec.SetField(adminloginhistory.FieldClientVersion, field.TypeString, value)
+ }
+ if value, ok := alhuo.mutation.Device(); ok {
+ _spec.SetField(adminloginhistory.FieldDevice, field.TypeString, value)
+ }
+ if value, ok := alhuo.mutation.CreatedAt(); ok {
+ _spec.SetField(adminloginhistory.FieldCreatedAt, field.TypeTime, value)
+ }
+ if alhuo.mutation.OwnerCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: true,
+ Table: adminloginhistory.OwnerTable,
+ Columns: []string{adminloginhistory.OwnerColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(admin.FieldID, field.TypeUUID),
+ },
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := alhuo.mutation.OwnerIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: true,
+ Table: adminloginhistory.OwnerTable,
+ Columns: []string{adminloginhistory.OwnerColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(admin.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Add = append(_spec.Edges.Add, edge)
+ }
+ _spec.AddModifiers(alhuo.modifiers...)
+ _node = &AdminLoginHistory{config: alhuo.config}
+ _spec.Assign = _node.assignValues
+ _spec.ScanValues = _node.scanValues
+ if err = sqlgraph.UpdateNode(ctx, alhuo.driver, _spec); err != nil {
+ if _, ok := err.(*sqlgraph.NotFoundError); ok {
+ err = &NotFoundError{adminloginhistory.Label}
+ } else if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return nil, err
+ }
+ alhuo.mutation.done = true
+ return _node, nil
+}
diff --git a/backend/db/apikey.go b/backend/db/apikey.go
new file mode 100644
index 0000000..c45c72b
--- /dev/null
+++ b/backend/db/apikey.go
@@ -0,0 +1,174 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "fmt"
+ "strings"
+ "time"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect/sql"
+ "github.com/chaitin/MonkeyCode/backend/consts"
+ "github.com/chaitin/MonkeyCode/backend/db/apikey"
+ "github.com/google/uuid"
+)
+
+// ApiKey is the model entity for the ApiKey schema.
+type ApiKey struct {
+ config `json:"-"`
+ // ID of the ent.
+ ID uuid.UUID `json:"id,omitempty"`
+ // UserID holds the value of the "user_id" field.
+ UserID uuid.UUID `json:"user_id,omitempty"`
+ // Key holds the value of the "key" field.
+ Key string `json:"key,omitempty"`
+ // Name holds the value of the "name" field.
+ Name string `json:"name,omitempty"`
+ // Status holds the value of the "status" field.
+ Status consts.ApiKeyStatus `json:"status,omitempty"`
+ // LastUsed holds the value of the "last_used" field.
+ LastUsed time.Time `json:"last_used,omitempty"`
+ // CreatedAt holds the value of the "created_at" field.
+ CreatedAt time.Time `json:"created_at,omitempty"`
+ // UpdatedAt holds the value of the "updated_at" field.
+ UpdatedAt time.Time `json:"updated_at,omitempty"`
+ selectValues sql.SelectValues
+}
+
+// scanValues returns the types for scanning values from sql.Rows.
+func (*ApiKey) scanValues(columns []string) ([]any, error) {
+ values := make([]any, len(columns))
+ for i := range columns {
+ switch columns[i] {
+ case apikey.FieldKey, apikey.FieldName, apikey.FieldStatus:
+ values[i] = new(sql.NullString)
+ case apikey.FieldLastUsed, apikey.FieldCreatedAt, apikey.FieldUpdatedAt:
+ values[i] = new(sql.NullTime)
+ case apikey.FieldID, apikey.FieldUserID:
+ values[i] = new(uuid.UUID)
+ default:
+ values[i] = new(sql.UnknownType)
+ }
+ }
+ return values, nil
+}
+
+// assignValues assigns the values that were returned from sql.Rows (after scanning)
+// to the ApiKey fields.
+func (ak *ApiKey) assignValues(columns []string, values []any) error {
+ if m, n := len(values), len(columns); m < n {
+ return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
+ }
+ for i := range columns {
+ switch columns[i] {
+ case apikey.FieldID:
+ if value, ok := values[i].(*uuid.UUID); !ok {
+ return fmt.Errorf("unexpected type %T for field id", values[i])
+ } else if value != nil {
+ ak.ID = *value
+ }
+ case apikey.FieldUserID:
+ if value, ok := values[i].(*uuid.UUID); !ok {
+ return fmt.Errorf("unexpected type %T for field user_id", values[i])
+ } else if value != nil {
+ ak.UserID = *value
+ }
+ case apikey.FieldKey:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field key", values[i])
+ } else if value.Valid {
+ ak.Key = value.String
+ }
+ case apikey.FieldName:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field name", values[i])
+ } else if value.Valid {
+ ak.Name = value.String
+ }
+ case apikey.FieldStatus:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field status", values[i])
+ } else if value.Valid {
+ ak.Status = consts.ApiKeyStatus(value.String)
+ }
+ case apikey.FieldLastUsed:
+ if value, ok := values[i].(*sql.NullTime); !ok {
+ return fmt.Errorf("unexpected type %T for field last_used", values[i])
+ } else if value.Valid {
+ ak.LastUsed = value.Time
+ }
+ case apikey.FieldCreatedAt:
+ if value, ok := values[i].(*sql.NullTime); !ok {
+ return fmt.Errorf("unexpected type %T for field created_at", values[i])
+ } else if value.Valid {
+ ak.CreatedAt = value.Time
+ }
+ case apikey.FieldUpdatedAt:
+ if value, ok := values[i].(*sql.NullTime); !ok {
+ return fmt.Errorf("unexpected type %T for field updated_at", values[i])
+ } else if value.Valid {
+ ak.UpdatedAt = value.Time
+ }
+ default:
+ ak.selectValues.Set(columns[i], values[i])
+ }
+ }
+ return nil
+}
+
+// Value returns the ent.Value that was dynamically selected and assigned to the ApiKey.
+// This includes values selected through modifiers, order, etc.
+func (ak *ApiKey) Value(name string) (ent.Value, error) {
+ return ak.selectValues.Get(name)
+}
+
+// Update returns a builder for updating this ApiKey.
+// Note that you need to call ApiKey.Unwrap() before calling this method if this ApiKey
+// was returned from a transaction, and the transaction was committed or rolled back.
+func (ak *ApiKey) Update() *ApiKeyUpdateOne {
+ return NewApiKeyClient(ak.config).UpdateOne(ak)
+}
+
+// Unwrap unwraps the ApiKey entity that was returned from a transaction after it was closed,
+// so that all future queries will be executed through the driver which created the transaction.
+func (ak *ApiKey) Unwrap() *ApiKey {
+ _tx, ok := ak.config.driver.(*txDriver)
+ if !ok {
+ panic("db: ApiKey is not a transactional entity")
+ }
+ ak.config.driver = _tx.drv
+ return ak
+}
+
+// String implements the fmt.Stringer.
+func (ak *ApiKey) String() string {
+ var builder strings.Builder
+ builder.WriteString("ApiKey(")
+ builder.WriteString(fmt.Sprintf("id=%v, ", ak.ID))
+ builder.WriteString("user_id=")
+ builder.WriteString(fmt.Sprintf("%v", ak.UserID))
+ builder.WriteString(", ")
+ builder.WriteString("key=")
+ builder.WriteString(ak.Key)
+ builder.WriteString(", ")
+ builder.WriteString("name=")
+ builder.WriteString(ak.Name)
+ builder.WriteString(", ")
+ builder.WriteString("status=")
+ builder.WriteString(fmt.Sprintf("%v", ak.Status))
+ builder.WriteString(", ")
+ builder.WriteString("last_used=")
+ builder.WriteString(ak.LastUsed.Format(time.ANSIC))
+ builder.WriteString(", ")
+ builder.WriteString("created_at=")
+ builder.WriteString(ak.CreatedAt.Format(time.ANSIC))
+ builder.WriteString(", ")
+ builder.WriteString("updated_at=")
+ builder.WriteString(ak.UpdatedAt.Format(time.ANSIC))
+ builder.WriteByte(')')
+ return builder.String()
+}
+
+// ApiKeys is a parsable slice of ApiKey.
+type ApiKeys []*ApiKey
diff --git a/backend/db/apikey/apikey.go b/backend/db/apikey/apikey.go
new file mode 100644
index 0000000..5ba11a1
--- /dev/null
+++ b/backend/db/apikey/apikey.go
@@ -0,0 +1,109 @@
+// Code generated by ent, DO NOT EDIT.
+
+package apikey
+
+import (
+ "time"
+
+ "entgo.io/ent/dialect/sql"
+ "github.com/chaitin/MonkeyCode/backend/consts"
+)
+
+const (
+ // Label holds the string label denoting the apikey type in the database.
+ Label = "api_key"
+ // FieldID holds the string denoting the id field in the database.
+ FieldID = "id"
+ // FieldUserID holds the string denoting the user_id field in the database.
+ FieldUserID = "user_id"
+ // FieldKey holds the string denoting the key field in the database.
+ FieldKey = "key"
+ // FieldName holds the string denoting the name field in the database.
+ FieldName = "name"
+ // FieldStatus holds the string denoting the status field in the database.
+ FieldStatus = "status"
+ // FieldLastUsed holds the string denoting the last_used field in the database.
+ FieldLastUsed = "last_used"
+ // FieldCreatedAt holds the string denoting the created_at field in the database.
+ FieldCreatedAt = "created_at"
+ // FieldUpdatedAt holds the string denoting the updated_at field in the database.
+ FieldUpdatedAt = "updated_at"
+ // Table holds the table name of the apikey in the database.
+ Table = "api_keys"
+)
+
+// Columns holds all SQL columns for apikey fields.
+var Columns = []string{
+ FieldID,
+ FieldUserID,
+ FieldKey,
+ FieldName,
+ FieldStatus,
+ FieldLastUsed,
+ FieldCreatedAt,
+ FieldUpdatedAt,
+}
+
+// ValidColumn reports if the column name is valid (part of the table columns).
+func ValidColumn(column string) bool {
+ for i := range Columns {
+ if column == Columns[i] {
+ return true
+ }
+ }
+ return false
+}
+
+var (
+ // DefaultStatus holds the default value on creation for the "status" field.
+ DefaultStatus consts.ApiKeyStatus
+ // DefaultCreatedAt holds the default value on creation for the "created_at" field.
+ DefaultCreatedAt func() time.Time
+ // DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
+ DefaultUpdatedAt func() time.Time
+ // UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field.
+ UpdateDefaultUpdatedAt func() time.Time
+)
+
+// OrderOption defines the ordering options for the ApiKey queries.
+type OrderOption func(*sql.Selector)
+
+// ByID orders the results by the id field.
+func ByID(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldID, opts...).ToFunc()
+}
+
+// ByUserID orders the results by the user_id field.
+func ByUserID(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldUserID, opts...).ToFunc()
+}
+
+// ByKey orders the results by the key field.
+func ByKey(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldKey, opts...).ToFunc()
+}
+
+// ByName orders the results by the name field.
+func ByName(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldName, opts...).ToFunc()
+}
+
+// ByStatus orders the results by the status field.
+func ByStatus(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldStatus, opts...).ToFunc()
+}
+
+// ByLastUsed orders the results by the last_used field.
+func ByLastUsed(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldLastUsed, opts...).ToFunc()
+}
+
+// ByCreatedAt orders the results by the created_at field.
+func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
+}
+
+// ByUpdatedAt orders the results by the updated_at field.
+func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc()
+}
diff --git a/backend/db/apikey/where.go b/backend/db/apikey/where.go
new file mode 100644
index 0000000..3d9f8dc
--- /dev/null
+++ b/backend/db/apikey/where.go
@@ -0,0 +1,492 @@
+// Code generated by ent, DO NOT EDIT.
+
+package apikey
+
+import (
+ "time"
+
+ "entgo.io/ent/dialect/sql"
+ "github.com/chaitin/MonkeyCode/backend/consts"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+ "github.com/google/uuid"
+)
+
+// ID filters vertices based on their ID field.
+func ID(id uuid.UUID) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldEQ(FieldID, id))
+}
+
+// IDEQ applies the EQ predicate on the ID field.
+func IDEQ(id uuid.UUID) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldEQ(FieldID, id))
+}
+
+// IDNEQ applies the NEQ predicate on the ID field.
+func IDNEQ(id uuid.UUID) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldNEQ(FieldID, id))
+}
+
+// IDIn applies the In predicate on the ID field.
+func IDIn(ids ...uuid.UUID) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldIn(FieldID, ids...))
+}
+
+// IDNotIn applies the NotIn predicate on the ID field.
+func IDNotIn(ids ...uuid.UUID) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldNotIn(FieldID, ids...))
+}
+
+// IDGT applies the GT predicate on the ID field.
+func IDGT(id uuid.UUID) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldGT(FieldID, id))
+}
+
+// IDGTE applies the GTE predicate on the ID field.
+func IDGTE(id uuid.UUID) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldGTE(FieldID, id))
+}
+
+// IDLT applies the LT predicate on the ID field.
+func IDLT(id uuid.UUID) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldLT(FieldID, id))
+}
+
+// IDLTE applies the LTE predicate on the ID field.
+func IDLTE(id uuid.UUID) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldLTE(FieldID, id))
+}
+
+// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ.
+func UserID(v uuid.UUID) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldEQ(FieldUserID, v))
+}
+
+// Key applies equality check predicate on the "key" field. It's identical to KeyEQ.
+func Key(v string) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldEQ(FieldKey, v))
+}
+
+// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
+func Name(v string) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldEQ(FieldName, v))
+}
+
+// Status applies equality check predicate on the "status" field. It's identical to StatusEQ.
+func Status(v consts.ApiKeyStatus) predicate.ApiKey {
+ vc := string(v)
+ return predicate.ApiKey(sql.FieldEQ(FieldStatus, vc))
+}
+
+// LastUsed applies equality check predicate on the "last_used" field. It's identical to LastUsedEQ.
+func LastUsed(v time.Time) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldEQ(FieldLastUsed, v))
+}
+
+// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
+func CreatedAt(v time.Time) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldEQ(FieldCreatedAt, v))
+}
+
+// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
+func UpdatedAt(v time.Time) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldEQ(FieldUpdatedAt, v))
+}
+
+// UserIDEQ applies the EQ predicate on the "user_id" field.
+func UserIDEQ(v uuid.UUID) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldEQ(FieldUserID, v))
+}
+
+// UserIDNEQ applies the NEQ predicate on the "user_id" field.
+func UserIDNEQ(v uuid.UUID) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldNEQ(FieldUserID, v))
+}
+
+// UserIDIn applies the In predicate on the "user_id" field.
+func UserIDIn(vs ...uuid.UUID) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldIn(FieldUserID, vs...))
+}
+
+// UserIDNotIn applies the NotIn predicate on the "user_id" field.
+func UserIDNotIn(vs ...uuid.UUID) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldNotIn(FieldUserID, vs...))
+}
+
+// UserIDGT applies the GT predicate on the "user_id" field.
+func UserIDGT(v uuid.UUID) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldGT(FieldUserID, v))
+}
+
+// UserIDGTE applies the GTE predicate on the "user_id" field.
+func UserIDGTE(v uuid.UUID) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldGTE(FieldUserID, v))
+}
+
+// UserIDLT applies the LT predicate on the "user_id" field.
+func UserIDLT(v uuid.UUID) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldLT(FieldUserID, v))
+}
+
+// UserIDLTE applies the LTE predicate on the "user_id" field.
+func UserIDLTE(v uuid.UUID) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldLTE(FieldUserID, v))
+}
+
+// KeyEQ applies the EQ predicate on the "key" field.
+func KeyEQ(v string) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldEQ(FieldKey, v))
+}
+
+// KeyNEQ applies the NEQ predicate on the "key" field.
+func KeyNEQ(v string) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldNEQ(FieldKey, v))
+}
+
+// KeyIn applies the In predicate on the "key" field.
+func KeyIn(vs ...string) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldIn(FieldKey, vs...))
+}
+
+// KeyNotIn applies the NotIn predicate on the "key" field.
+func KeyNotIn(vs ...string) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldNotIn(FieldKey, vs...))
+}
+
+// KeyGT applies the GT predicate on the "key" field.
+func KeyGT(v string) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldGT(FieldKey, v))
+}
+
+// KeyGTE applies the GTE predicate on the "key" field.
+func KeyGTE(v string) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldGTE(FieldKey, v))
+}
+
+// KeyLT applies the LT predicate on the "key" field.
+func KeyLT(v string) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldLT(FieldKey, v))
+}
+
+// KeyLTE applies the LTE predicate on the "key" field.
+func KeyLTE(v string) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldLTE(FieldKey, v))
+}
+
+// KeyContains applies the Contains predicate on the "key" field.
+func KeyContains(v string) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldContains(FieldKey, v))
+}
+
+// KeyHasPrefix applies the HasPrefix predicate on the "key" field.
+func KeyHasPrefix(v string) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldHasPrefix(FieldKey, v))
+}
+
+// KeyHasSuffix applies the HasSuffix predicate on the "key" field.
+func KeyHasSuffix(v string) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldHasSuffix(FieldKey, v))
+}
+
+// KeyEqualFold applies the EqualFold predicate on the "key" field.
+func KeyEqualFold(v string) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldEqualFold(FieldKey, v))
+}
+
+// KeyContainsFold applies the ContainsFold predicate on the "key" field.
+func KeyContainsFold(v string) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldContainsFold(FieldKey, v))
+}
+
+// NameEQ applies the EQ predicate on the "name" field.
+func NameEQ(v string) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldEQ(FieldName, v))
+}
+
+// NameNEQ applies the NEQ predicate on the "name" field.
+func NameNEQ(v string) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldNEQ(FieldName, v))
+}
+
+// NameIn applies the In predicate on the "name" field.
+func NameIn(vs ...string) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldIn(FieldName, vs...))
+}
+
+// NameNotIn applies the NotIn predicate on the "name" field.
+func NameNotIn(vs ...string) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldNotIn(FieldName, vs...))
+}
+
+// NameGT applies the GT predicate on the "name" field.
+func NameGT(v string) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldGT(FieldName, v))
+}
+
+// NameGTE applies the GTE predicate on the "name" field.
+func NameGTE(v string) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldGTE(FieldName, v))
+}
+
+// NameLT applies the LT predicate on the "name" field.
+func NameLT(v string) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldLT(FieldName, v))
+}
+
+// NameLTE applies the LTE predicate on the "name" field.
+func NameLTE(v string) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldLTE(FieldName, v))
+}
+
+// NameContains applies the Contains predicate on the "name" field.
+func NameContains(v string) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldContains(FieldName, v))
+}
+
+// NameHasPrefix applies the HasPrefix predicate on the "name" field.
+func NameHasPrefix(v string) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldHasPrefix(FieldName, v))
+}
+
+// NameHasSuffix applies the HasSuffix predicate on the "name" field.
+func NameHasSuffix(v string) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldHasSuffix(FieldName, v))
+}
+
+// NameEqualFold applies the EqualFold predicate on the "name" field.
+func NameEqualFold(v string) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldEqualFold(FieldName, v))
+}
+
+// NameContainsFold applies the ContainsFold predicate on the "name" field.
+func NameContainsFold(v string) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldContainsFold(FieldName, v))
+}
+
+// StatusEQ applies the EQ predicate on the "status" field.
+func StatusEQ(v consts.ApiKeyStatus) predicate.ApiKey {
+ vc := string(v)
+ return predicate.ApiKey(sql.FieldEQ(FieldStatus, vc))
+}
+
+// StatusNEQ applies the NEQ predicate on the "status" field.
+func StatusNEQ(v consts.ApiKeyStatus) predicate.ApiKey {
+ vc := string(v)
+ return predicate.ApiKey(sql.FieldNEQ(FieldStatus, vc))
+}
+
+// StatusIn applies the In predicate on the "status" field.
+func StatusIn(vs ...consts.ApiKeyStatus) predicate.ApiKey {
+ v := make([]any, len(vs))
+ for i := range v {
+ v[i] = string(vs[i])
+ }
+ return predicate.ApiKey(sql.FieldIn(FieldStatus, v...))
+}
+
+// StatusNotIn applies the NotIn predicate on the "status" field.
+func StatusNotIn(vs ...consts.ApiKeyStatus) predicate.ApiKey {
+ v := make([]any, len(vs))
+ for i := range v {
+ v[i] = string(vs[i])
+ }
+ return predicate.ApiKey(sql.FieldNotIn(FieldStatus, v...))
+}
+
+// StatusGT applies the GT predicate on the "status" field.
+func StatusGT(v consts.ApiKeyStatus) predicate.ApiKey {
+ vc := string(v)
+ return predicate.ApiKey(sql.FieldGT(FieldStatus, vc))
+}
+
+// StatusGTE applies the GTE predicate on the "status" field.
+func StatusGTE(v consts.ApiKeyStatus) predicate.ApiKey {
+ vc := string(v)
+ return predicate.ApiKey(sql.FieldGTE(FieldStatus, vc))
+}
+
+// StatusLT applies the LT predicate on the "status" field.
+func StatusLT(v consts.ApiKeyStatus) predicate.ApiKey {
+ vc := string(v)
+ return predicate.ApiKey(sql.FieldLT(FieldStatus, vc))
+}
+
+// StatusLTE applies the LTE predicate on the "status" field.
+func StatusLTE(v consts.ApiKeyStatus) predicate.ApiKey {
+ vc := string(v)
+ return predicate.ApiKey(sql.FieldLTE(FieldStatus, vc))
+}
+
+// StatusContains applies the Contains predicate on the "status" field.
+func StatusContains(v consts.ApiKeyStatus) predicate.ApiKey {
+ vc := string(v)
+ return predicate.ApiKey(sql.FieldContains(FieldStatus, vc))
+}
+
+// StatusHasPrefix applies the HasPrefix predicate on the "status" field.
+func StatusHasPrefix(v consts.ApiKeyStatus) predicate.ApiKey {
+ vc := string(v)
+ return predicate.ApiKey(sql.FieldHasPrefix(FieldStatus, vc))
+}
+
+// StatusHasSuffix applies the HasSuffix predicate on the "status" field.
+func StatusHasSuffix(v consts.ApiKeyStatus) predicate.ApiKey {
+ vc := string(v)
+ return predicate.ApiKey(sql.FieldHasSuffix(FieldStatus, vc))
+}
+
+// StatusEqualFold applies the EqualFold predicate on the "status" field.
+func StatusEqualFold(v consts.ApiKeyStatus) predicate.ApiKey {
+ vc := string(v)
+ return predicate.ApiKey(sql.FieldEqualFold(FieldStatus, vc))
+}
+
+// StatusContainsFold applies the ContainsFold predicate on the "status" field.
+func StatusContainsFold(v consts.ApiKeyStatus) predicate.ApiKey {
+ vc := string(v)
+ return predicate.ApiKey(sql.FieldContainsFold(FieldStatus, vc))
+}
+
+// LastUsedEQ applies the EQ predicate on the "last_used" field.
+func LastUsedEQ(v time.Time) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldEQ(FieldLastUsed, v))
+}
+
+// LastUsedNEQ applies the NEQ predicate on the "last_used" field.
+func LastUsedNEQ(v time.Time) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldNEQ(FieldLastUsed, v))
+}
+
+// LastUsedIn applies the In predicate on the "last_used" field.
+func LastUsedIn(vs ...time.Time) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldIn(FieldLastUsed, vs...))
+}
+
+// LastUsedNotIn applies the NotIn predicate on the "last_used" field.
+func LastUsedNotIn(vs ...time.Time) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldNotIn(FieldLastUsed, vs...))
+}
+
+// LastUsedGT applies the GT predicate on the "last_used" field.
+func LastUsedGT(v time.Time) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldGT(FieldLastUsed, v))
+}
+
+// LastUsedGTE applies the GTE predicate on the "last_used" field.
+func LastUsedGTE(v time.Time) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldGTE(FieldLastUsed, v))
+}
+
+// LastUsedLT applies the LT predicate on the "last_used" field.
+func LastUsedLT(v time.Time) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldLT(FieldLastUsed, v))
+}
+
+// LastUsedLTE applies the LTE predicate on the "last_used" field.
+func LastUsedLTE(v time.Time) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldLTE(FieldLastUsed, v))
+}
+
+// LastUsedIsNil applies the IsNil predicate on the "last_used" field.
+func LastUsedIsNil() predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldIsNull(FieldLastUsed))
+}
+
+// LastUsedNotNil applies the NotNil predicate on the "last_used" field.
+func LastUsedNotNil() predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldNotNull(FieldLastUsed))
+}
+
+// CreatedAtEQ applies the EQ predicate on the "created_at" field.
+func CreatedAtEQ(v time.Time) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldEQ(FieldCreatedAt, v))
+}
+
+// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
+func CreatedAtNEQ(v time.Time) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldNEQ(FieldCreatedAt, v))
+}
+
+// CreatedAtIn applies the In predicate on the "created_at" field.
+func CreatedAtIn(vs ...time.Time) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldIn(FieldCreatedAt, vs...))
+}
+
+// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
+func CreatedAtNotIn(vs ...time.Time) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldNotIn(FieldCreatedAt, vs...))
+}
+
+// CreatedAtGT applies the GT predicate on the "created_at" field.
+func CreatedAtGT(v time.Time) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldGT(FieldCreatedAt, v))
+}
+
+// CreatedAtGTE applies the GTE predicate on the "created_at" field.
+func CreatedAtGTE(v time.Time) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldGTE(FieldCreatedAt, v))
+}
+
+// CreatedAtLT applies the LT predicate on the "created_at" field.
+func CreatedAtLT(v time.Time) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldLT(FieldCreatedAt, v))
+}
+
+// CreatedAtLTE applies the LTE predicate on the "created_at" field.
+func CreatedAtLTE(v time.Time) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldLTE(FieldCreatedAt, v))
+}
+
+// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
+func UpdatedAtEQ(v time.Time) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldEQ(FieldUpdatedAt, v))
+}
+
+// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
+func UpdatedAtNEQ(v time.Time) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldNEQ(FieldUpdatedAt, v))
+}
+
+// UpdatedAtIn applies the In predicate on the "updated_at" field.
+func UpdatedAtIn(vs ...time.Time) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldIn(FieldUpdatedAt, vs...))
+}
+
+// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
+func UpdatedAtNotIn(vs ...time.Time) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldNotIn(FieldUpdatedAt, vs...))
+}
+
+// UpdatedAtGT applies the GT predicate on the "updated_at" field.
+func UpdatedAtGT(v time.Time) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldGT(FieldUpdatedAt, v))
+}
+
+// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
+func UpdatedAtGTE(v time.Time) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldGTE(FieldUpdatedAt, v))
+}
+
+// UpdatedAtLT applies the LT predicate on the "updated_at" field.
+func UpdatedAtLT(v time.Time) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldLT(FieldUpdatedAt, v))
+}
+
+// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
+func UpdatedAtLTE(v time.Time) predicate.ApiKey {
+ return predicate.ApiKey(sql.FieldLTE(FieldUpdatedAt, v))
+}
+
+// And groups predicates with the AND operator between them.
+func And(predicates ...predicate.ApiKey) predicate.ApiKey {
+ return predicate.ApiKey(sql.AndPredicates(predicates...))
+}
+
+// Or groups predicates with the OR operator between them.
+func Or(predicates ...predicate.ApiKey) predicate.ApiKey {
+ return predicate.ApiKey(sql.OrPredicates(predicates...))
+}
+
+// Not applies the not operator on the given predicate.
+func Not(p predicate.ApiKey) predicate.ApiKey {
+ return predicate.ApiKey(sql.NotPredicates(p))
+}
diff --git a/backend/db/apikey_create.go b/backend/db/apikey_create.go
new file mode 100644
index 0000000..1e06d02
--- /dev/null
+++ b/backend/db/apikey_create.go
@@ -0,0 +1,877 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "time"
+
+ "entgo.io/ent/dialect"
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/consts"
+ "github.com/chaitin/MonkeyCode/backend/db/apikey"
+ "github.com/google/uuid"
+)
+
+// ApiKeyCreate is the builder for creating a ApiKey entity.
+type ApiKeyCreate struct {
+ config
+ mutation *ApiKeyMutation
+ hooks []Hook
+ conflict []sql.ConflictOption
+}
+
+// SetUserID sets the "user_id" field.
+func (akc *ApiKeyCreate) SetUserID(u uuid.UUID) *ApiKeyCreate {
+ akc.mutation.SetUserID(u)
+ return akc
+}
+
+// SetKey sets the "key" field.
+func (akc *ApiKeyCreate) SetKey(s string) *ApiKeyCreate {
+ akc.mutation.SetKey(s)
+ return akc
+}
+
+// SetName sets the "name" field.
+func (akc *ApiKeyCreate) SetName(s string) *ApiKeyCreate {
+ akc.mutation.SetName(s)
+ return akc
+}
+
+// SetStatus sets the "status" field.
+func (akc *ApiKeyCreate) SetStatus(cks consts.ApiKeyStatus) *ApiKeyCreate {
+ akc.mutation.SetStatus(cks)
+ return akc
+}
+
+// SetNillableStatus sets the "status" field if the given value is not nil.
+func (akc *ApiKeyCreate) SetNillableStatus(cks *consts.ApiKeyStatus) *ApiKeyCreate {
+ if cks != nil {
+ akc.SetStatus(*cks)
+ }
+ return akc
+}
+
+// SetLastUsed sets the "last_used" field.
+func (akc *ApiKeyCreate) SetLastUsed(t time.Time) *ApiKeyCreate {
+ akc.mutation.SetLastUsed(t)
+ return akc
+}
+
+// SetNillableLastUsed sets the "last_used" field if the given value is not nil.
+func (akc *ApiKeyCreate) SetNillableLastUsed(t *time.Time) *ApiKeyCreate {
+ if t != nil {
+ akc.SetLastUsed(*t)
+ }
+ return akc
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (akc *ApiKeyCreate) SetCreatedAt(t time.Time) *ApiKeyCreate {
+ akc.mutation.SetCreatedAt(t)
+ return akc
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (akc *ApiKeyCreate) SetNillableCreatedAt(t *time.Time) *ApiKeyCreate {
+ if t != nil {
+ akc.SetCreatedAt(*t)
+ }
+ return akc
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (akc *ApiKeyCreate) SetUpdatedAt(t time.Time) *ApiKeyCreate {
+ akc.mutation.SetUpdatedAt(t)
+ return akc
+}
+
+// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
+func (akc *ApiKeyCreate) SetNillableUpdatedAt(t *time.Time) *ApiKeyCreate {
+ if t != nil {
+ akc.SetUpdatedAt(*t)
+ }
+ return akc
+}
+
+// SetID sets the "id" field.
+func (akc *ApiKeyCreate) SetID(u uuid.UUID) *ApiKeyCreate {
+ akc.mutation.SetID(u)
+ return akc
+}
+
+// Mutation returns the ApiKeyMutation object of the builder.
+func (akc *ApiKeyCreate) Mutation() *ApiKeyMutation {
+ return akc.mutation
+}
+
+// Save creates the ApiKey in the database.
+func (akc *ApiKeyCreate) Save(ctx context.Context) (*ApiKey, error) {
+ akc.defaults()
+ return withHooks(ctx, akc.sqlSave, akc.mutation, akc.hooks)
+}
+
+// SaveX calls Save and panics if Save returns an error.
+func (akc *ApiKeyCreate) SaveX(ctx context.Context) *ApiKey {
+ v, err := akc.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return v
+}
+
+// Exec executes the query.
+func (akc *ApiKeyCreate) Exec(ctx context.Context) error {
+ _, err := akc.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (akc *ApiKeyCreate) ExecX(ctx context.Context) {
+ if err := akc.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// defaults sets the default values of the builder before save.
+func (akc *ApiKeyCreate) defaults() {
+ if _, ok := akc.mutation.Status(); !ok {
+ v := apikey.DefaultStatus
+ akc.mutation.SetStatus(v)
+ }
+ if _, ok := akc.mutation.CreatedAt(); !ok {
+ v := apikey.DefaultCreatedAt()
+ akc.mutation.SetCreatedAt(v)
+ }
+ if _, ok := akc.mutation.UpdatedAt(); !ok {
+ v := apikey.DefaultUpdatedAt()
+ akc.mutation.SetUpdatedAt(v)
+ }
+}
+
+// check runs all checks and user-defined validators on the builder.
+func (akc *ApiKeyCreate) check() error {
+ if _, ok := akc.mutation.UserID(); !ok {
+ return &ValidationError{Name: "user_id", err: errors.New(`db: missing required field "ApiKey.user_id"`)}
+ }
+ if _, ok := akc.mutation.Key(); !ok {
+ return &ValidationError{Name: "key", err: errors.New(`db: missing required field "ApiKey.key"`)}
+ }
+ if _, ok := akc.mutation.Name(); !ok {
+ return &ValidationError{Name: "name", err: errors.New(`db: missing required field "ApiKey.name"`)}
+ }
+ if _, ok := akc.mutation.Status(); !ok {
+ return &ValidationError{Name: "status", err: errors.New(`db: missing required field "ApiKey.status"`)}
+ }
+ if _, ok := akc.mutation.CreatedAt(); !ok {
+ return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "ApiKey.created_at"`)}
+ }
+ if _, ok := akc.mutation.UpdatedAt(); !ok {
+ return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "ApiKey.updated_at"`)}
+ }
+ return nil
+}
+
+func (akc *ApiKeyCreate) sqlSave(ctx context.Context) (*ApiKey, error) {
+ if err := akc.check(); err != nil {
+ return nil, err
+ }
+ _node, _spec := akc.createSpec()
+ if err := sqlgraph.CreateNode(ctx, akc.driver, _spec); err != nil {
+ if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return nil, err
+ }
+ if _spec.ID.Value != nil {
+ if id, ok := _spec.ID.Value.(*uuid.UUID); ok {
+ _node.ID = *id
+ } else if err := _node.ID.Scan(_spec.ID.Value); err != nil {
+ return nil, err
+ }
+ }
+ akc.mutation.id = &_node.ID
+ akc.mutation.done = true
+ return _node, nil
+}
+
+func (akc *ApiKeyCreate) createSpec() (*ApiKey, *sqlgraph.CreateSpec) {
+ var (
+ _node = &ApiKey{config: akc.config}
+ _spec = sqlgraph.NewCreateSpec(apikey.Table, sqlgraph.NewFieldSpec(apikey.FieldID, field.TypeUUID))
+ )
+ _spec.OnConflict = akc.conflict
+ if id, ok := akc.mutation.ID(); ok {
+ _node.ID = id
+ _spec.ID.Value = &id
+ }
+ if value, ok := akc.mutation.UserID(); ok {
+ _spec.SetField(apikey.FieldUserID, field.TypeUUID, value)
+ _node.UserID = value
+ }
+ if value, ok := akc.mutation.Key(); ok {
+ _spec.SetField(apikey.FieldKey, field.TypeString, value)
+ _node.Key = value
+ }
+ if value, ok := akc.mutation.Name(); ok {
+ _spec.SetField(apikey.FieldName, field.TypeString, value)
+ _node.Name = value
+ }
+ if value, ok := akc.mutation.Status(); ok {
+ _spec.SetField(apikey.FieldStatus, field.TypeString, value)
+ _node.Status = value
+ }
+ if value, ok := akc.mutation.LastUsed(); ok {
+ _spec.SetField(apikey.FieldLastUsed, field.TypeTime, value)
+ _node.LastUsed = value
+ }
+ if value, ok := akc.mutation.CreatedAt(); ok {
+ _spec.SetField(apikey.FieldCreatedAt, field.TypeTime, value)
+ _node.CreatedAt = value
+ }
+ if value, ok := akc.mutation.UpdatedAt(); ok {
+ _spec.SetField(apikey.FieldUpdatedAt, field.TypeTime, value)
+ _node.UpdatedAt = value
+ }
+ return _node, _spec
+}
+
+// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
+// of the `INSERT` statement. For example:
+//
+// client.ApiKey.Create().
+// SetUserID(v).
+// OnConflict(
+// // Update the row with the new values
+// // the was proposed for insertion.
+// sql.ResolveWithNewValues(),
+// ).
+// // Override some of the fields with custom
+// // update values.
+// Update(func(u *ent.ApiKeyUpsert) {
+// SetUserID(v+v).
+// }).
+// Exec(ctx)
+func (akc *ApiKeyCreate) OnConflict(opts ...sql.ConflictOption) *ApiKeyUpsertOne {
+ akc.conflict = opts
+ return &ApiKeyUpsertOne{
+ create: akc,
+ }
+}
+
+// OnConflictColumns calls `OnConflict` and configures the columns
+// as conflict target. Using this option is equivalent to using:
+//
+// client.ApiKey.Create().
+// OnConflict(sql.ConflictColumns(columns...)).
+// Exec(ctx)
+func (akc *ApiKeyCreate) OnConflictColumns(columns ...string) *ApiKeyUpsertOne {
+ akc.conflict = append(akc.conflict, sql.ConflictColumns(columns...))
+ return &ApiKeyUpsertOne{
+ create: akc,
+ }
+}
+
+type (
+ // ApiKeyUpsertOne is the builder for "upsert"-ing
+ // one ApiKey node.
+ ApiKeyUpsertOne struct {
+ create *ApiKeyCreate
+ }
+
+ // ApiKeyUpsert is the "OnConflict" setter.
+ ApiKeyUpsert struct {
+ *sql.UpdateSet
+ }
+)
+
+// SetUserID sets the "user_id" field.
+func (u *ApiKeyUpsert) SetUserID(v uuid.UUID) *ApiKeyUpsert {
+ u.Set(apikey.FieldUserID, v)
+ return u
+}
+
+// UpdateUserID sets the "user_id" field to the value that was provided on create.
+func (u *ApiKeyUpsert) UpdateUserID() *ApiKeyUpsert {
+ u.SetExcluded(apikey.FieldUserID)
+ return u
+}
+
+// SetKey sets the "key" field.
+func (u *ApiKeyUpsert) SetKey(v string) *ApiKeyUpsert {
+ u.Set(apikey.FieldKey, v)
+ return u
+}
+
+// UpdateKey sets the "key" field to the value that was provided on create.
+func (u *ApiKeyUpsert) UpdateKey() *ApiKeyUpsert {
+ u.SetExcluded(apikey.FieldKey)
+ return u
+}
+
+// SetName sets the "name" field.
+func (u *ApiKeyUpsert) SetName(v string) *ApiKeyUpsert {
+ u.Set(apikey.FieldName, v)
+ return u
+}
+
+// UpdateName sets the "name" field to the value that was provided on create.
+func (u *ApiKeyUpsert) UpdateName() *ApiKeyUpsert {
+ u.SetExcluded(apikey.FieldName)
+ return u
+}
+
+// SetStatus sets the "status" field.
+func (u *ApiKeyUpsert) SetStatus(v consts.ApiKeyStatus) *ApiKeyUpsert {
+ u.Set(apikey.FieldStatus, v)
+ return u
+}
+
+// UpdateStatus sets the "status" field to the value that was provided on create.
+func (u *ApiKeyUpsert) UpdateStatus() *ApiKeyUpsert {
+ u.SetExcluded(apikey.FieldStatus)
+ return u
+}
+
+// SetLastUsed sets the "last_used" field.
+func (u *ApiKeyUpsert) SetLastUsed(v time.Time) *ApiKeyUpsert {
+ u.Set(apikey.FieldLastUsed, v)
+ return u
+}
+
+// UpdateLastUsed sets the "last_used" field to the value that was provided on create.
+func (u *ApiKeyUpsert) UpdateLastUsed() *ApiKeyUpsert {
+ u.SetExcluded(apikey.FieldLastUsed)
+ return u
+}
+
+// ClearLastUsed clears the value of the "last_used" field.
+func (u *ApiKeyUpsert) ClearLastUsed() *ApiKeyUpsert {
+ u.SetNull(apikey.FieldLastUsed)
+ return u
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (u *ApiKeyUpsert) SetCreatedAt(v time.Time) *ApiKeyUpsert {
+ u.Set(apikey.FieldCreatedAt, v)
+ return u
+}
+
+// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
+func (u *ApiKeyUpsert) UpdateCreatedAt() *ApiKeyUpsert {
+ u.SetExcluded(apikey.FieldCreatedAt)
+ return u
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (u *ApiKeyUpsert) SetUpdatedAt(v time.Time) *ApiKeyUpsert {
+ u.Set(apikey.FieldUpdatedAt, v)
+ return u
+}
+
+// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
+func (u *ApiKeyUpsert) UpdateUpdatedAt() *ApiKeyUpsert {
+ u.SetExcluded(apikey.FieldUpdatedAt)
+ return u
+}
+
+// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field.
+// Using this option is equivalent to using:
+//
+// client.ApiKey.Create().
+// OnConflict(
+// sql.ResolveWithNewValues(),
+// sql.ResolveWith(func(u *sql.UpdateSet) {
+// u.SetIgnore(apikey.FieldID)
+// }),
+// ).
+// Exec(ctx)
+func (u *ApiKeyUpsertOne) UpdateNewValues() *ApiKeyUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
+ if _, exists := u.create.mutation.ID(); exists {
+ s.SetIgnore(apikey.FieldID)
+ }
+ }))
+ return u
+}
+
+// Ignore sets each column to itself in case of conflict.
+// Using this option is equivalent to using:
+//
+// client.ApiKey.Create().
+// OnConflict(sql.ResolveWithIgnore()).
+// Exec(ctx)
+func (u *ApiKeyUpsertOne) Ignore() *ApiKeyUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
+ return u
+}
+
+// DoNothing configures the conflict_action to `DO NOTHING`.
+// Supported only by SQLite and PostgreSQL.
+func (u *ApiKeyUpsertOne) DoNothing() *ApiKeyUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.DoNothing())
+ return u
+}
+
+// Update allows overriding fields `UPDATE` values. See the ApiKeyCreate.OnConflict
+// documentation for more info.
+func (u *ApiKeyUpsertOne) Update(set func(*ApiKeyUpsert)) *ApiKeyUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
+ set(&ApiKeyUpsert{UpdateSet: update})
+ }))
+ return u
+}
+
+// SetUserID sets the "user_id" field.
+func (u *ApiKeyUpsertOne) SetUserID(v uuid.UUID) *ApiKeyUpsertOne {
+ return u.Update(func(s *ApiKeyUpsert) {
+ s.SetUserID(v)
+ })
+}
+
+// UpdateUserID sets the "user_id" field to the value that was provided on create.
+func (u *ApiKeyUpsertOne) UpdateUserID() *ApiKeyUpsertOne {
+ return u.Update(func(s *ApiKeyUpsert) {
+ s.UpdateUserID()
+ })
+}
+
+// SetKey sets the "key" field.
+func (u *ApiKeyUpsertOne) SetKey(v string) *ApiKeyUpsertOne {
+ return u.Update(func(s *ApiKeyUpsert) {
+ s.SetKey(v)
+ })
+}
+
+// UpdateKey sets the "key" field to the value that was provided on create.
+func (u *ApiKeyUpsertOne) UpdateKey() *ApiKeyUpsertOne {
+ return u.Update(func(s *ApiKeyUpsert) {
+ s.UpdateKey()
+ })
+}
+
+// SetName sets the "name" field.
+func (u *ApiKeyUpsertOne) SetName(v string) *ApiKeyUpsertOne {
+ return u.Update(func(s *ApiKeyUpsert) {
+ s.SetName(v)
+ })
+}
+
+// UpdateName sets the "name" field to the value that was provided on create.
+func (u *ApiKeyUpsertOne) UpdateName() *ApiKeyUpsertOne {
+ return u.Update(func(s *ApiKeyUpsert) {
+ s.UpdateName()
+ })
+}
+
+// SetStatus sets the "status" field.
+func (u *ApiKeyUpsertOne) SetStatus(v consts.ApiKeyStatus) *ApiKeyUpsertOne {
+ return u.Update(func(s *ApiKeyUpsert) {
+ s.SetStatus(v)
+ })
+}
+
+// UpdateStatus sets the "status" field to the value that was provided on create.
+func (u *ApiKeyUpsertOne) UpdateStatus() *ApiKeyUpsertOne {
+ return u.Update(func(s *ApiKeyUpsert) {
+ s.UpdateStatus()
+ })
+}
+
+// SetLastUsed sets the "last_used" field.
+func (u *ApiKeyUpsertOne) SetLastUsed(v time.Time) *ApiKeyUpsertOne {
+ return u.Update(func(s *ApiKeyUpsert) {
+ s.SetLastUsed(v)
+ })
+}
+
+// UpdateLastUsed sets the "last_used" field to the value that was provided on create.
+func (u *ApiKeyUpsertOne) UpdateLastUsed() *ApiKeyUpsertOne {
+ return u.Update(func(s *ApiKeyUpsert) {
+ s.UpdateLastUsed()
+ })
+}
+
+// ClearLastUsed clears the value of the "last_used" field.
+func (u *ApiKeyUpsertOne) ClearLastUsed() *ApiKeyUpsertOne {
+ return u.Update(func(s *ApiKeyUpsert) {
+ s.ClearLastUsed()
+ })
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (u *ApiKeyUpsertOne) SetCreatedAt(v time.Time) *ApiKeyUpsertOne {
+ return u.Update(func(s *ApiKeyUpsert) {
+ s.SetCreatedAt(v)
+ })
+}
+
+// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
+func (u *ApiKeyUpsertOne) UpdateCreatedAt() *ApiKeyUpsertOne {
+ return u.Update(func(s *ApiKeyUpsert) {
+ s.UpdateCreatedAt()
+ })
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (u *ApiKeyUpsertOne) SetUpdatedAt(v time.Time) *ApiKeyUpsertOne {
+ return u.Update(func(s *ApiKeyUpsert) {
+ s.SetUpdatedAt(v)
+ })
+}
+
+// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
+func (u *ApiKeyUpsertOne) UpdateUpdatedAt() *ApiKeyUpsertOne {
+ return u.Update(func(s *ApiKeyUpsert) {
+ s.UpdateUpdatedAt()
+ })
+}
+
+// Exec executes the query.
+func (u *ApiKeyUpsertOne) Exec(ctx context.Context) error {
+ if len(u.create.conflict) == 0 {
+ return errors.New("db: missing options for ApiKeyCreate.OnConflict")
+ }
+ return u.create.Exec(ctx)
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (u *ApiKeyUpsertOne) ExecX(ctx context.Context) {
+ if err := u.create.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// Exec executes the UPSERT query and returns the inserted/updated ID.
+func (u *ApiKeyUpsertOne) ID(ctx context.Context) (id uuid.UUID, err error) {
+ if u.create.driver.Dialect() == dialect.MySQL {
+ // In case of "ON CONFLICT", there is no way to get back non-numeric ID
+ // fields from the database since MySQL does not support the RETURNING clause.
+ return id, errors.New("db: ApiKeyUpsertOne.ID is not supported by MySQL driver. Use ApiKeyUpsertOne.Exec instead")
+ }
+ node, err := u.create.Save(ctx)
+ if err != nil {
+ return id, err
+ }
+ return node.ID, nil
+}
+
+// IDX is like ID, but panics if an error occurs.
+func (u *ApiKeyUpsertOne) IDX(ctx context.Context) uuid.UUID {
+ id, err := u.ID(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return id
+}
+
+// ApiKeyCreateBulk is the builder for creating many ApiKey entities in bulk.
+type ApiKeyCreateBulk struct {
+ config
+ err error
+ builders []*ApiKeyCreate
+ conflict []sql.ConflictOption
+}
+
+// Save creates the ApiKey entities in the database.
+func (akcb *ApiKeyCreateBulk) Save(ctx context.Context) ([]*ApiKey, error) {
+ if akcb.err != nil {
+ return nil, akcb.err
+ }
+ specs := make([]*sqlgraph.CreateSpec, len(akcb.builders))
+ nodes := make([]*ApiKey, len(akcb.builders))
+ mutators := make([]Mutator, len(akcb.builders))
+ for i := range akcb.builders {
+ func(i int, root context.Context) {
+ builder := akcb.builders[i]
+ builder.defaults()
+ var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
+ mutation, ok := m.(*ApiKeyMutation)
+ if !ok {
+ return nil, fmt.Errorf("unexpected mutation type %T", m)
+ }
+ if err := builder.check(); err != nil {
+ return nil, err
+ }
+ builder.mutation = mutation
+ var err error
+ nodes[i], specs[i] = builder.createSpec()
+ if i < len(mutators)-1 {
+ _, err = mutators[i+1].Mutate(root, akcb.builders[i+1].mutation)
+ } else {
+ spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
+ spec.OnConflict = akcb.conflict
+ // Invoke the actual operation on the latest mutation in the chain.
+ if err = sqlgraph.BatchCreate(ctx, akcb.driver, spec); err != nil {
+ if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ }
+ }
+ if err != nil {
+ return nil, err
+ }
+ mutation.id = &nodes[i].ID
+ mutation.done = true
+ return nodes[i], nil
+ })
+ for i := len(builder.hooks) - 1; i >= 0; i-- {
+ mut = builder.hooks[i](mut)
+ }
+ mutators[i] = mut
+ }(i, ctx)
+ }
+ if len(mutators) > 0 {
+ if _, err := mutators[0].Mutate(ctx, akcb.builders[0].mutation); err != nil {
+ return nil, err
+ }
+ }
+ return nodes, nil
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (akcb *ApiKeyCreateBulk) SaveX(ctx context.Context) []*ApiKey {
+ v, err := akcb.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return v
+}
+
+// Exec executes the query.
+func (akcb *ApiKeyCreateBulk) Exec(ctx context.Context) error {
+ _, err := akcb.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (akcb *ApiKeyCreateBulk) ExecX(ctx context.Context) {
+ if err := akcb.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
+// of the `INSERT` statement. For example:
+//
+// client.ApiKey.CreateBulk(builders...).
+// OnConflict(
+// // Update the row with the new values
+// // the was proposed for insertion.
+// sql.ResolveWithNewValues(),
+// ).
+// // Override some of the fields with custom
+// // update values.
+// Update(func(u *ent.ApiKeyUpsert) {
+// SetUserID(v+v).
+// }).
+// Exec(ctx)
+func (akcb *ApiKeyCreateBulk) OnConflict(opts ...sql.ConflictOption) *ApiKeyUpsertBulk {
+ akcb.conflict = opts
+ return &ApiKeyUpsertBulk{
+ create: akcb,
+ }
+}
+
+// OnConflictColumns calls `OnConflict` and configures the columns
+// as conflict target. Using this option is equivalent to using:
+//
+// client.ApiKey.Create().
+// OnConflict(sql.ConflictColumns(columns...)).
+// Exec(ctx)
+func (akcb *ApiKeyCreateBulk) OnConflictColumns(columns ...string) *ApiKeyUpsertBulk {
+ akcb.conflict = append(akcb.conflict, sql.ConflictColumns(columns...))
+ return &ApiKeyUpsertBulk{
+ create: akcb,
+ }
+}
+
+// ApiKeyUpsertBulk is the builder for "upsert"-ing
+// a bulk of ApiKey nodes.
+type ApiKeyUpsertBulk struct {
+ create *ApiKeyCreateBulk
+}
+
+// UpdateNewValues updates the mutable fields using the new values that
+// were set on create. Using this option is equivalent to using:
+//
+// client.ApiKey.Create().
+// OnConflict(
+// sql.ResolveWithNewValues(),
+// sql.ResolveWith(func(u *sql.UpdateSet) {
+// u.SetIgnore(apikey.FieldID)
+// }),
+// ).
+// Exec(ctx)
+func (u *ApiKeyUpsertBulk) UpdateNewValues() *ApiKeyUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
+ for _, b := range u.create.builders {
+ if _, exists := b.mutation.ID(); exists {
+ s.SetIgnore(apikey.FieldID)
+ }
+ }
+ }))
+ return u
+}
+
+// Ignore sets each column to itself in case of conflict.
+// Using this option is equivalent to using:
+//
+// client.ApiKey.Create().
+// OnConflict(sql.ResolveWithIgnore()).
+// Exec(ctx)
+func (u *ApiKeyUpsertBulk) Ignore() *ApiKeyUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
+ return u
+}
+
+// DoNothing configures the conflict_action to `DO NOTHING`.
+// Supported only by SQLite and PostgreSQL.
+func (u *ApiKeyUpsertBulk) DoNothing() *ApiKeyUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.DoNothing())
+ return u
+}
+
+// Update allows overriding fields `UPDATE` values. See the ApiKeyCreateBulk.OnConflict
+// documentation for more info.
+func (u *ApiKeyUpsertBulk) Update(set func(*ApiKeyUpsert)) *ApiKeyUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
+ set(&ApiKeyUpsert{UpdateSet: update})
+ }))
+ return u
+}
+
+// SetUserID sets the "user_id" field.
+func (u *ApiKeyUpsertBulk) SetUserID(v uuid.UUID) *ApiKeyUpsertBulk {
+ return u.Update(func(s *ApiKeyUpsert) {
+ s.SetUserID(v)
+ })
+}
+
+// UpdateUserID sets the "user_id" field to the value that was provided on create.
+func (u *ApiKeyUpsertBulk) UpdateUserID() *ApiKeyUpsertBulk {
+ return u.Update(func(s *ApiKeyUpsert) {
+ s.UpdateUserID()
+ })
+}
+
+// SetKey sets the "key" field.
+func (u *ApiKeyUpsertBulk) SetKey(v string) *ApiKeyUpsertBulk {
+ return u.Update(func(s *ApiKeyUpsert) {
+ s.SetKey(v)
+ })
+}
+
+// UpdateKey sets the "key" field to the value that was provided on create.
+func (u *ApiKeyUpsertBulk) UpdateKey() *ApiKeyUpsertBulk {
+ return u.Update(func(s *ApiKeyUpsert) {
+ s.UpdateKey()
+ })
+}
+
+// SetName sets the "name" field.
+func (u *ApiKeyUpsertBulk) SetName(v string) *ApiKeyUpsertBulk {
+ return u.Update(func(s *ApiKeyUpsert) {
+ s.SetName(v)
+ })
+}
+
+// UpdateName sets the "name" field to the value that was provided on create.
+func (u *ApiKeyUpsertBulk) UpdateName() *ApiKeyUpsertBulk {
+ return u.Update(func(s *ApiKeyUpsert) {
+ s.UpdateName()
+ })
+}
+
+// SetStatus sets the "status" field.
+func (u *ApiKeyUpsertBulk) SetStatus(v consts.ApiKeyStatus) *ApiKeyUpsertBulk {
+ return u.Update(func(s *ApiKeyUpsert) {
+ s.SetStatus(v)
+ })
+}
+
+// UpdateStatus sets the "status" field to the value that was provided on create.
+func (u *ApiKeyUpsertBulk) UpdateStatus() *ApiKeyUpsertBulk {
+ return u.Update(func(s *ApiKeyUpsert) {
+ s.UpdateStatus()
+ })
+}
+
+// SetLastUsed sets the "last_used" field.
+func (u *ApiKeyUpsertBulk) SetLastUsed(v time.Time) *ApiKeyUpsertBulk {
+ return u.Update(func(s *ApiKeyUpsert) {
+ s.SetLastUsed(v)
+ })
+}
+
+// UpdateLastUsed sets the "last_used" field to the value that was provided on create.
+func (u *ApiKeyUpsertBulk) UpdateLastUsed() *ApiKeyUpsertBulk {
+ return u.Update(func(s *ApiKeyUpsert) {
+ s.UpdateLastUsed()
+ })
+}
+
+// ClearLastUsed clears the value of the "last_used" field.
+func (u *ApiKeyUpsertBulk) ClearLastUsed() *ApiKeyUpsertBulk {
+ return u.Update(func(s *ApiKeyUpsert) {
+ s.ClearLastUsed()
+ })
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (u *ApiKeyUpsertBulk) SetCreatedAt(v time.Time) *ApiKeyUpsertBulk {
+ return u.Update(func(s *ApiKeyUpsert) {
+ s.SetCreatedAt(v)
+ })
+}
+
+// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
+func (u *ApiKeyUpsertBulk) UpdateCreatedAt() *ApiKeyUpsertBulk {
+ return u.Update(func(s *ApiKeyUpsert) {
+ s.UpdateCreatedAt()
+ })
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (u *ApiKeyUpsertBulk) SetUpdatedAt(v time.Time) *ApiKeyUpsertBulk {
+ return u.Update(func(s *ApiKeyUpsert) {
+ s.SetUpdatedAt(v)
+ })
+}
+
+// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
+func (u *ApiKeyUpsertBulk) UpdateUpdatedAt() *ApiKeyUpsertBulk {
+ return u.Update(func(s *ApiKeyUpsert) {
+ s.UpdateUpdatedAt()
+ })
+}
+
+// Exec executes the query.
+func (u *ApiKeyUpsertBulk) Exec(ctx context.Context) error {
+ if u.create.err != nil {
+ return u.create.err
+ }
+ for i, b := range u.create.builders {
+ if len(b.conflict) != 0 {
+ return fmt.Errorf("db: OnConflict was set for builder %d. Set it on the ApiKeyCreateBulk instead", i)
+ }
+ }
+ if len(u.create.conflict) == 0 {
+ return errors.New("db: missing options for ApiKeyCreateBulk.OnConflict")
+ }
+ return u.create.Exec(ctx)
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (u *ApiKeyUpsertBulk) ExecX(ctx context.Context) {
+ if err := u.create.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
diff --git a/backend/db/apikey_delete.go b/backend/db/apikey_delete.go
new file mode 100644
index 0000000..e6ad69a
--- /dev/null
+++ b/backend/db/apikey_delete.go
@@ -0,0 +1,88 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/apikey"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+)
+
+// ApiKeyDelete is the builder for deleting a ApiKey entity.
+type ApiKeyDelete struct {
+ config
+ hooks []Hook
+ mutation *ApiKeyMutation
+}
+
+// Where appends a list predicates to the ApiKeyDelete builder.
+func (akd *ApiKeyDelete) Where(ps ...predicate.ApiKey) *ApiKeyDelete {
+ akd.mutation.Where(ps...)
+ return akd
+}
+
+// Exec executes the deletion query and returns how many vertices were deleted.
+func (akd *ApiKeyDelete) Exec(ctx context.Context) (int, error) {
+ return withHooks(ctx, akd.sqlExec, akd.mutation, akd.hooks)
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (akd *ApiKeyDelete) ExecX(ctx context.Context) int {
+ n, err := akd.Exec(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return n
+}
+
+func (akd *ApiKeyDelete) sqlExec(ctx context.Context) (int, error) {
+ _spec := sqlgraph.NewDeleteSpec(apikey.Table, sqlgraph.NewFieldSpec(apikey.FieldID, field.TypeUUID))
+ if ps := akd.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ affected, err := sqlgraph.DeleteNodes(ctx, akd.driver, _spec)
+ if err != nil && sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ akd.mutation.done = true
+ return affected, err
+}
+
+// ApiKeyDeleteOne is the builder for deleting a single ApiKey entity.
+type ApiKeyDeleteOne struct {
+ akd *ApiKeyDelete
+}
+
+// Where appends a list predicates to the ApiKeyDelete builder.
+func (akdo *ApiKeyDeleteOne) Where(ps ...predicate.ApiKey) *ApiKeyDeleteOne {
+ akdo.akd.mutation.Where(ps...)
+ return akdo
+}
+
+// Exec executes the deletion query.
+func (akdo *ApiKeyDeleteOne) Exec(ctx context.Context) error {
+ n, err := akdo.akd.Exec(ctx)
+ switch {
+ case err != nil:
+ return err
+ case n == 0:
+ return &NotFoundError{apikey.Label}
+ default:
+ return nil
+ }
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (akdo *ApiKeyDeleteOne) ExecX(ctx context.Context) {
+ if err := akdo.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
diff --git a/backend/db/apikey_query.go b/backend/db/apikey_query.go
new file mode 100644
index 0000000..313c3d6
--- /dev/null
+++ b/backend/db/apikey_query.go
@@ -0,0 +1,578 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "fmt"
+ "math"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect"
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/apikey"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+ "github.com/google/uuid"
+)
+
+// ApiKeyQuery is the builder for querying ApiKey entities.
+type ApiKeyQuery struct {
+ config
+ ctx *QueryContext
+ order []apikey.OrderOption
+ inters []Interceptor
+ predicates []predicate.ApiKey
+ modifiers []func(*sql.Selector)
+ // intermediate query (i.e. traversal path).
+ sql *sql.Selector
+ path func(context.Context) (*sql.Selector, error)
+}
+
+// Where adds a new predicate for the ApiKeyQuery builder.
+func (akq *ApiKeyQuery) Where(ps ...predicate.ApiKey) *ApiKeyQuery {
+ akq.predicates = append(akq.predicates, ps...)
+ return akq
+}
+
+// Limit the number of records to be returned by this query.
+func (akq *ApiKeyQuery) Limit(limit int) *ApiKeyQuery {
+ akq.ctx.Limit = &limit
+ return akq
+}
+
+// Offset to start from.
+func (akq *ApiKeyQuery) Offset(offset int) *ApiKeyQuery {
+ akq.ctx.Offset = &offset
+ return akq
+}
+
+// Unique configures the query builder to filter duplicate records on query.
+// By default, unique is set to true, and can be disabled using this method.
+func (akq *ApiKeyQuery) Unique(unique bool) *ApiKeyQuery {
+ akq.ctx.Unique = &unique
+ return akq
+}
+
+// Order specifies how the records should be ordered.
+func (akq *ApiKeyQuery) Order(o ...apikey.OrderOption) *ApiKeyQuery {
+ akq.order = append(akq.order, o...)
+ return akq
+}
+
+// First returns the first ApiKey entity from the query.
+// Returns a *NotFoundError when no ApiKey was found.
+func (akq *ApiKeyQuery) First(ctx context.Context) (*ApiKey, error) {
+ nodes, err := akq.Limit(1).All(setContextOp(ctx, akq.ctx, ent.OpQueryFirst))
+ if err != nil {
+ return nil, err
+ }
+ if len(nodes) == 0 {
+ return nil, &NotFoundError{apikey.Label}
+ }
+ return nodes[0], nil
+}
+
+// FirstX is like First, but panics if an error occurs.
+func (akq *ApiKeyQuery) FirstX(ctx context.Context) *ApiKey {
+ node, err := akq.First(ctx)
+ if err != nil && !IsNotFound(err) {
+ panic(err)
+ }
+ return node
+}
+
+// FirstID returns the first ApiKey ID from the query.
+// Returns a *NotFoundError when no ApiKey ID was found.
+func (akq *ApiKeyQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
+ var ids []uuid.UUID
+ if ids, err = akq.Limit(1).IDs(setContextOp(ctx, akq.ctx, ent.OpQueryFirstID)); err != nil {
+ return
+ }
+ if len(ids) == 0 {
+ err = &NotFoundError{apikey.Label}
+ return
+ }
+ return ids[0], nil
+}
+
+// FirstIDX is like FirstID, but panics if an error occurs.
+func (akq *ApiKeyQuery) FirstIDX(ctx context.Context) uuid.UUID {
+ id, err := akq.FirstID(ctx)
+ if err != nil && !IsNotFound(err) {
+ panic(err)
+ }
+ return id
+}
+
+// Only returns a single ApiKey entity found by the query, ensuring it only returns one.
+// Returns a *NotSingularError when more than one ApiKey entity is found.
+// Returns a *NotFoundError when no ApiKey entities are found.
+func (akq *ApiKeyQuery) Only(ctx context.Context) (*ApiKey, error) {
+ nodes, err := akq.Limit(2).All(setContextOp(ctx, akq.ctx, ent.OpQueryOnly))
+ if err != nil {
+ return nil, err
+ }
+ switch len(nodes) {
+ case 1:
+ return nodes[0], nil
+ case 0:
+ return nil, &NotFoundError{apikey.Label}
+ default:
+ return nil, &NotSingularError{apikey.Label}
+ }
+}
+
+// OnlyX is like Only, but panics if an error occurs.
+func (akq *ApiKeyQuery) OnlyX(ctx context.Context) *ApiKey {
+ node, err := akq.Only(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return node
+}
+
+// OnlyID is like Only, but returns the only ApiKey ID in the query.
+// Returns a *NotSingularError when more than one ApiKey ID is found.
+// Returns a *NotFoundError when no entities are found.
+func (akq *ApiKeyQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
+ var ids []uuid.UUID
+ if ids, err = akq.Limit(2).IDs(setContextOp(ctx, akq.ctx, ent.OpQueryOnlyID)); err != nil {
+ return
+ }
+ switch len(ids) {
+ case 1:
+ id = ids[0]
+ case 0:
+ err = &NotFoundError{apikey.Label}
+ default:
+ err = &NotSingularError{apikey.Label}
+ }
+ return
+}
+
+// OnlyIDX is like OnlyID, but panics if an error occurs.
+func (akq *ApiKeyQuery) OnlyIDX(ctx context.Context) uuid.UUID {
+ id, err := akq.OnlyID(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return id
+}
+
+// All executes the query and returns a list of ApiKeys.
+func (akq *ApiKeyQuery) All(ctx context.Context) ([]*ApiKey, error) {
+ ctx = setContextOp(ctx, akq.ctx, ent.OpQueryAll)
+ if err := akq.prepareQuery(ctx); err != nil {
+ return nil, err
+ }
+ qr := querierAll[[]*ApiKey, *ApiKeyQuery]()
+ return withInterceptors[[]*ApiKey](ctx, akq, qr, akq.inters)
+}
+
+// AllX is like All, but panics if an error occurs.
+func (akq *ApiKeyQuery) AllX(ctx context.Context) []*ApiKey {
+ nodes, err := akq.All(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return nodes
+}
+
+// IDs executes the query and returns a list of ApiKey IDs.
+func (akq *ApiKeyQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) {
+ if akq.ctx.Unique == nil && akq.path != nil {
+ akq.Unique(true)
+ }
+ ctx = setContextOp(ctx, akq.ctx, ent.OpQueryIDs)
+ if err = akq.Select(apikey.FieldID).Scan(ctx, &ids); err != nil {
+ return nil, err
+ }
+ return ids, nil
+}
+
+// IDsX is like IDs, but panics if an error occurs.
+func (akq *ApiKeyQuery) IDsX(ctx context.Context) []uuid.UUID {
+ ids, err := akq.IDs(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return ids
+}
+
+// Count returns the count of the given query.
+func (akq *ApiKeyQuery) Count(ctx context.Context) (int, error) {
+ ctx = setContextOp(ctx, akq.ctx, ent.OpQueryCount)
+ if err := akq.prepareQuery(ctx); err != nil {
+ return 0, err
+ }
+ return withInterceptors[int](ctx, akq, querierCount[*ApiKeyQuery](), akq.inters)
+}
+
+// CountX is like Count, but panics if an error occurs.
+func (akq *ApiKeyQuery) CountX(ctx context.Context) int {
+ count, err := akq.Count(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return count
+}
+
+// Exist returns true if the query has elements in the graph.
+func (akq *ApiKeyQuery) Exist(ctx context.Context) (bool, error) {
+ ctx = setContextOp(ctx, akq.ctx, ent.OpQueryExist)
+ switch _, err := akq.FirstID(ctx); {
+ case IsNotFound(err):
+ return false, nil
+ case err != nil:
+ return false, fmt.Errorf("db: check existence: %w", err)
+ default:
+ return true, nil
+ }
+}
+
+// ExistX is like Exist, but panics if an error occurs.
+func (akq *ApiKeyQuery) ExistX(ctx context.Context) bool {
+ exist, err := akq.Exist(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return exist
+}
+
+// Clone returns a duplicate of the ApiKeyQuery builder, including all associated steps. It can be
+// used to prepare common query builders and use them differently after the clone is made.
+func (akq *ApiKeyQuery) Clone() *ApiKeyQuery {
+ if akq == nil {
+ return nil
+ }
+ return &ApiKeyQuery{
+ config: akq.config,
+ ctx: akq.ctx.Clone(),
+ order: append([]apikey.OrderOption{}, akq.order...),
+ inters: append([]Interceptor{}, akq.inters...),
+ predicates: append([]predicate.ApiKey{}, akq.predicates...),
+ // clone intermediate query.
+ sql: akq.sql.Clone(),
+ path: akq.path,
+ modifiers: append([]func(*sql.Selector){}, akq.modifiers...),
+ }
+}
+
+// GroupBy is used to group vertices by one or more fields/columns.
+// It is often used with aggregate functions, like: count, max, mean, min, sum.
+//
+// Example:
+//
+// var v []struct {
+// UserID uuid.UUID `json:"user_id,omitempty"`
+// Count int `json:"count,omitempty"`
+// }
+//
+// client.ApiKey.Query().
+// GroupBy(apikey.FieldUserID).
+// Aggregate(db.Count()).
+// Scan(ctx, &v)
+func (akq *ApiKeyQuery) GroupBy(field string, fields ...string) *ApiKeyGroupBy {
+ akq.ctx.Fields = append([]string{field}, fields...)
+ grbuild := &ApiKeyGroupBy{build: akq}
+ grbuild.flds = &akq.ctx.Fields
+ grbuild.label = apikey.Label
+ grbuild.scan = grbuild.Scan
+ return grbuild
+}
+
+// Select allows the selection one or more fields/columns for the given query,
+// instead of selecting all fields in the entity.
+//
+// Example:
+//
+// var v []struct {
+// UserID uuid.UUID `json:"user_id,omitempty"`
+// }
+//
+// client.ApiKey.Query().
+// Select(apikey.FieldUserID).
+// Scan(ctx, &v)
+func (akq *ApiKeyQuery) Select(fields ...string) *ApiKeySelect {
+ akq.ctx.Fields = append(akq.ctx.Fields, fields...)
+ sbuild := &ApiKeySelect{ApiKeyQuery: akq}
+ sbuild.label = apikey.Label
+ sbuild.flds, sbuild.scan = &akq.ctx.Fields, sbuild.Scan
+ return sbuild
+}
+
+// Aggregate returns a ApiKeySelect configured with the given aggregations.
+func (akq *ApiKeyQuery) Aggregate(fns ...AggregateFunc) *ApiKeySelect {
+ return akq.Select().Aggregate(fns...)
+}
+
+func (akq *ApiKeyQuery) prepareQuery(ctx context.Context) error {
+ for _, inter := range akq.inters {
+ if inter == nil {
+ return fmt.Errorf("db: uninitialized interceptor (forgotten import db/runtime?)")
+ }
+ if trv, ok := inter.(Traverser); ok {
+ if err := trv.Traverse(ctx, akq); err != nil {
+ return err
+ }
+ }
+ }
+ for _, f := range akq.ctx.Fields {
+ if !apikey.ValidColumn(f) {
+ return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
+ }
+ }
+ if akq.path != nil {
+ prev, err := akq.path(ctx)
+ if err != nil {
+ return err
+ }
+ akq.sql = prev
+ }
+ return nil
+}
+
+func (akq *ApiKeyQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*ApiKey, error) {
+ var (
+ nodes = []*ApiKey{}
+ _spec = akq.querySpec()
+ )
+ _spec.ScanValues = func(columns []string) ([]any, error) {
+ return (*ApiKey).scanValues(nil, columns)
+ }
+ _spec.Assign = func(columns []string, values []any) error {
+ node := &ApiKey{config: akq.config}
+ nodes = append(nodes, node)
+ return node.assignValues(columns, values)
+ }
+ if len(akq.modifiers) > 0 {
+ _spec.Modifiers = akq.modifiers
+ }
+ for i := range hooks {
+ hooks[i](ctx, _spec)
+ }
+ if err := sqlgraph.QueryNodes(ctx, akq.driver, _spec); err != nil {
+ return nil, err
+ }
+ if len(nodes) == 0 {
+ return nodes, nil
+ }
+ return nodes, nil
+}
+
+func (akq *ApiKeyQuery) sqlCount(ctx context.Context) (int, error) {
+ _spec := akq.querySpec()
+ if len(akq.modifiers) > 0 {
+ _spec.Modifiers = akq.modifiers
+ }
+ _spec.Node.Columns = akq.ctx.Fields
+ if len(akq.ctx.Fields) > 0 {
+ _spec.Unique = akq.ctx.Unique != nil && *akq.ctx.Unique
+ }
+ return sqlgraph.CountNodes(ctx, akq.driver, _spec)
+}
+
+func (akq *ApiKeyQuery) querySpec() *sqlgraph.QuerySpec {
+ _spec := sqlgraph.NewQuerySpec(apikey.Table, apikey.Columns, sqlgraph.NewFieldSpec(apikey.FieldID, field.TypeUUID))
+ _spec.From = akq.sql
+ if unique := akq.ctx.Unique; unique != nil {
+ _spec.Unique = *unique
+ } else if akq.path != nil {
+ _spec.Unique = true
+ }
+ if fields := akq.ctx.Fields; len(fields) > 0 {
+ _spec.Node.Columns = make([]string, 0, len(fields))
+ _spec.Node.Columns = append(_spec.Node.Columns, apikey.FieldID)
+ for i := range fields {
+ if fields[i] != apikey.FieldID {
+ _spec.Node.Columns = append(_spec.Node.Columns, fields[i])
+ }
+ }
+ }
+ if ps := akq.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if limit := akq.ctx.Limit; limit != nil {
+ _spec.Limit = *limit
+ }
+ if offset := akq.ctx.Offset; offset != nil {
+ _spec.Offset = *offset
+ }
+ if ps := akq.order; len(ps) > 0 {
+ _spec.Order = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ return _spec
+}
+
+func (akq *ApiKeyQuery) sqlQuery(ctx context.Context) *sql.Selector {
+ builder := sql.Dialect(akq.driver.Dialect())
+ t1 := builder.Table(apikey.Table)
+ columns := akq.ctx.Fields
+ if len(columns) == 0 {
+ columns = apikey.Columns
+ }
+ selector := builder.Select(t1.Columns(columns...)...).From(t1)
+ if akq.sql != nil {
+ selector = akq.sql
+ selector.Select(selector.Columns(columns...)...)
+ }
+ if akq.ctx.Unique != nil && *akq.ctx.Unique {
+ selector.Distinct()
+ }
+ for _, m := range akq.modifiers {
+ m(selector)
+ }
+ for _, p := range akq.predicates {
+ p(selector)
+ }
+ for _, p := range akq.order {
+ p(selector)
+ }
+ if offset := akq.ctx.Offset; offset != nil {
+ // limit is mandatory for offset clause. We start
+ // with default value, and override it below if needed.
+ selector.Offset(*offset).Limit(math.MaxInt32)
+ }
+ if limit := akq.ctx.Limit; limit != nil {
+ selector.Limit(*limit)
+ }
+ return selector
+}
+
+// ForUpdate locks the selected rows against concurrent updates, and prevent them from being
+// updated, deleted or "selected ... for update" by other sessions, until the transaction is
+// either committed or rolled-back.
+func (akq *ApiKeyQuery) ForUpdate(opts ...sql.LockOption) *ApiKeyQuery {
+ if akq.driver.Dialect() == dialect.Postgres {
+ akq.Unique(false)
+ }
+ akq.modifiers = append(akq.modifiers, func(s *sql.Selector) {
+ s.ForUpdate(opts...)
+ })
+ return akq
+}
+
+// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock
+// on any rows that are read. Other sessions can read the rows, but cannot modify them
+// until your transaction commits.
+func (akq *ApiKeyQuery) ForShare(opts ...sql.LockOption) *ApiKeyQuery {
+ if akq.driver.Dialect() == dialect.Postgres {
+ akq.Unique(false)
+ }
+ akq.modifiers = append(akq.modifiers, func(s *sql.Selector) {
+ s.ForShare(opts...)
+ })
+ return akq
+}
+
+// Modify adds a query modifier for attaching custom logic to queries.
+func (akq *ApiKeyQuery) Modify(modifiers ...func(s *sql.Selector)) *ApiKeySelect {
+ akq.modifiers = append(akq.modifiers, modifiers...)
+ return akq.Select()
+}
+
+// ApiKeyGroupBy is the group-by builder for ApiKey entities.
+type ApiKeyGroupBy struct {
+ selector
+ build *ApiKeyQuery
+}
+
+// Aggregate adds the given aggregation functions to the group-by query.
+func (akgb *ApiKeyGroupBy) Aggregate(fns ...AggregateFunc) *ApiKeyGroupBy {
+ akgb.fns = append(akgb.fns, fns...)
+ return akgb
+}
+
+// Scan applies the selector query and scans the result into the given value.
+func (akgb *ApiKeyGroupBy) Scan(ctx context.Context, v any) error {
+ ctx = setContextOp(ctx, akgb.build.ctx, ent.OpQueryGroupBy)
+ if err := akgb.build.prepareQuery(ctx); err != nil {
+ return err
+ }
+ return scanWithInterceptors[*ApiKeyQuery, *ApiKeyGroupBy](ctx, akgb.build, akgb, akgb.build.inters, v)
+}
+
+func (akgb *ApiKeyGroupBy) sqlScan(ctx context.Context, root *ApiKeyQuery, v any) error {
+ selector := root.sqlQuery(ctx).Select()
+ aggregation := make([]string, 0, len(akgb.fns))
+ for _, fn := range akgb.fns {
+ aggregation = append(aggregation, fn(selector))
+ }
+ if len(selector.SelectedColumns()) == 0 {
+ columns := make([]string, 0, len(*akgb.flds)+len(akgb.fns))
+ for _, f := range *akgb.flds {
+ columns = append(columns, selector.C(f))
+ }
+ columns = append(columns, aggregation...)
+ selector.Select(columns...)
+ }
+ selector.GroupBy(selector.Columns(*akgb.flds...)...)
+ if err := selector.Err(); err != nil {
+ return err
+ }
+ rows := &sql.Rows{}
+ query, args := selector.Query()
+ if err := akgb.build.driver.Query(ctx, query, args, rows); err != nil {
+ return err
+ }
+ defer rows.Close()
+ return sql.ScanSlice(rows, v)
+}
+
+// ApiKeySelect is the builder for selecting fields of ApiKey entities.
+type ApiKeySelect struct {
+ *ApiKeyQuery
+ selector
+}
+
+// Aggregate adds the given aggregation functions to the selector query.
+func (aks *ApiKeySelect) Aggregate(fns ...AggregateFunc) *ApiKeySelect {
+ aks.fns = append(aks.fns, fns...)
+ return aks
+}
+
+// Scan applies the selector query and scans the result into the given value.
+func (aks *ApiKeySelect) Scan(ctx context.Context, v any) error {
+ ctx = setContextOp(ctx, aks.ctx, ent.OpQuerySelect)
+ if err := aks.prepareQuery(ctx); err != nil {
+ return err
+ }
+ return scanWithInterceptors[*ApiKeyQuery, *ApiKeySelect](ctx, aks.ApiKeyQuery, aks, aks.inters, v)
+}
+
+func (aks *ApiKeySelect) sqlScan(ctx context.Context, root *ApiKeyQuery, v any) error {
+ selector := root.sqlQuery(ctx)
+ aggregation := make([]string, 0, len(aks.fns))
+ for _, fn := range aks.fns {
+ aggregation = append(aggregation, fn(selector))
+ }
+ switch n := len(*aks.selector.flds); {
+ case n == 0 && len(aggregation) > 0:
+ selector.Select(aggregation...)
+ case n != 0 && len(aggregation) > 0:
+ selector.AppendSelect(aggregation...)
+ }
+ rows := &sql.Rows{}
+ query, args := selector.Query()
+ if err := aks.driver.Query(ctx, query, args, rows); err != nil {
+ return err
+ }
+ defer rows.Close()
+ return sql.ScanSlice(rows, v)
+}
+
+// Modify adds a query modifier for attaching custom logic to queries.
+func (aks *ApiKeySelect) Modify(modifiers ...func(s *sql.Selector)) *ApiKeySelect {
+ aks.modifiers = append(aks.modifiers, modifiers...)
+ return aks
+}
diff --git a/backend/db/apikey_update.go b/backend/db/apikey_update.go
new file mode 100644
index 0000000..dbbe139
--- /dev/null
+++ b/backend/db/apikey_update.go
@@ -0,0 +1,452 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "time"
+
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/consts"
+ "github.com/chaitin/MonkeyCode/backend/db/apikey"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+ "github.com/google/uuid"
+)
+
+// ApiKeyUpdate is the builder for updating ApiKey entities.
+type ApiKeyUpdate struct {
+ config
+ hooks []Hook
+ mutation *ApiKeyMutation
+ modifiers []func(*sql.UpdateBuilder)
+}
+
+// Where appends a list predicates to the ApiKeyUpdate builder.
+func (aku *ApiKeyUpdate) Where(ps ...predicate.ApiKey) *ApiKeyUpdate {
+ aku.mutation.Where(ps...)
+ return aku
+}
+
+// SetUserID sets the "user_id" field.
+func (aku *ApiKeyUpdate) SetUserID(u uuid.UUID) *ApiKeyUpdate {
+ aku.mutation.SetUserID(u)
+ return aku
+}
+
+// SetNillableUserID sets the "user_id" field if the given value is not nil.
+func (aku *ApiKeyUpdate) SetNillableUserID(u *uuid.UUID) *ApiKeyUpdate {
+ if u != nil {
+ aku.SetUserID(*u)
+ }
+ return aku
+}
+
+// SetKey sets the "key" field.
+func (aku *ApiKeyUpdate) SetKey(s string) *ApiKeyUpdate {
+ aku.mutation.SetKey(s)
+ return aku
+}
+
+// SetNillableKey sets the "key" field if the given value is not nil.
+func (aku *ApiKeyUpdate) SetNillableKey(s *string) *ApiKeyUpdate {
+ if s != nil {
+ aku.SetKey(*s)
+ }
+ return aku
+}
+
+// SetName sets the "name" field.
+func (aku *ApiKeyUpdate) SetName(s string) *ApiKeyUpdate {
+ aku.mutation.SetName(s)
+ return aku
+}
+
+// SetNillableName sets the "name" field if the given value is not nil.
+func (aku *ApiKeyUpdate) SetNillableName(s *string) *ApiKeyUpdate {
+ if s != nil {
+ aku.SetName(*s)
+ }
+ return aku
+}
+
+// SetStatus sets the "status" field.
+func (aku *ApiKeyUpdate) SetStatus(cks consts.ApiKeyStatus) *ApiKeyUpdate {
+ aku.mutation.SetStatus(cks)
+ return aku
+}
+
+// SetNillableStatus sets the "status" field if the given value is not nil.
+func (aku *ApiKeyUpdate) SetNillableStatus(cks *consts.ApiKeyStatus) *ApiKeyUpdate {
+ if cks != nil {
+ aku.SetStatus(*cks)
+ }
+ return aku
+}
+
+// SetLastUsed sets the "last_used" field.
+func (aku *ApiKeyUpdate) SetLastUsed(t time.Time) *ApiKeyUpdate {
+ aku.mutation.SetLastUsed(t)
+ return aku
+}
+
+// SetNillableLastUsed sets the "last_used" field if the given value is not nil.
+func (aku *ApiKeyUpdate) SetNillableLastUsed(t *time.Time) *ApiKeyUpdate {
+ if t != nil {
+ aku.SetLastUsed(*t)
+ }
+ return aku
+}
+
+// ClearLastUsed clears the value of the "last_used" field.
+func (aku *ApiKeyUpdate) ClearLastUsed() *ApiKeyUpdate {
+ aku.mutation.ClearLastUsed()
+ return aku
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (aku *ApiKeyUpdate) SetCreatedAt(t time.Time) *ApiKeyUpdate {
+ aku.mutation.SetCreatedAt(t)
+ return aku
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (aku *ApiKeyUpdate) SetNillableCreatedAt(t *time.Time) *ApiKeyUpdate {
+ if t != nil {
+ aku.SetCreatedAt(*t)
+ }
+ return aku
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (aku *ApiKeyUpdate) SetUpdatedAt(t time.Time) *ApiKeyUpdate {
+ aku.mutation.SetUpdatedAt(t)
+ return aku
+}
+
+// Mutation returns the ApiKeyMutation object of the builder.
+func (aku *ApiKeyUpdate) Mutation() *ApiKeyMutation {
+ return aku.mutation
+}
+
+// Save executes the query and returns the number of nodes affected by the update operation.
+func (aku *ApiKeyUpdate) Save(ctx context.Context) (int, error) {
+ aku.defaults()
+ return withHooks(ctx, aku.sqlSave, aku.mutation, aku.hooks)
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (aku *ApiKeyUpdate) SaveX(ctx context.Context) int {
+ affected, err := aku.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return affected
+}
+
+// Exec executes the query.
+func (aku *ApiKeyUpdate) Exec(ctx context.Context) error {
+ _, err := aku.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (aku *ApiKeyUpdate) ExecX(ctx context.Context) {
+ if err := aku.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// defaults sets the default values of the builder before save.
+func (aku *ApiKeyUpdate) defaults() {
+ if _, ok := aku.mutation.UpdatedAt(); !ok {
+ v := apikey.UpdateDefaultUpdatedAt()
+ aku.mutation.SetUpdatedAt(v)
+ }
+}
+
+// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
+func (aku *ApiKeyUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *ApiKeyUpdate {
+ aku.modifiers = append(aku.modifiers, modifiers...)
+ return aku
+}
+
+func (aku *ApiKeyUpdate) sqlSave(ctx context.Context) (n int, err error) {
+ _spec := sqlgraph.NewUpdateSpec(apikey.Table, apikey.Columns, sqlgraph.NewFieldSpec(apikey.FieldID, field.TypeUUID))
+ if ps := aku.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if value, ok := aku.mutation.UserID(); ok {
+ _spec.SetField(apikey.FieldUserID, field.TypeUUID, value)
+ }
+ if value, ok := aku.mutation.Key(); ok {
+ _spec.SetField(apikey.FieldKey, field.TypeString, value)
+ }
+ if value, ok := aku.mutation.Name(); ok {
+ _spec.SetField(apikey.FieldName, field.TypeString, value)
+ }
+ if value, ok := aku.mutation.Status(); ok {
+ _spec.SetField(apikey.FieldStatus, field.TypeString, value)
+ }
+ if value, ok := aku.mutation.LastUsed(); ok {
+ _spec.SetField(apikey.FieldLastUsed, field.TypeTime, value)
+ }
+ if aku.mutation.LastUsedCleared() {
+ _spec.ClearField(apikey.FieldLastUsed, field.TypeTime)
+ }
+ if value, ok := aku.mutation.CreatedAt(); ok {
+ _spec.SetField(apikey.FieldCreatedAt, field.TypeTime, value)
+ }
+ if value, ok := aku.mutation.UpdatedAt(); ok {
+ _spec.SetField(apikey.FieldUpdatedAt, field.TypeTime, value)
+ }
+ _spec.AddModifiers(aku.modifiers...)
+ if n, err = sqlgraph.UpdateNodes(ctx, aku.driver, _spec); err != nil {
+ if _, ok := err.(*sqlgraph.NotFoundError); ok {
+ err = &NotFoundError{apikey.Label}
+ } else if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return 0, err
+ }
+ aku.mutation.done = true
+ return n, nil
+}
+
+// ApiKeyUpdateOne is the builder for updating a single ApiKey entity.
+type ApiKeyUpdateOne struct {
+ config
+ fields []string
+ hooks []Hook
+ mutation *ApiKeyMutation
+ modifiers []func(*sql.UpdateBuilder)
+}
+
+// SetUserID sets the "user_id" field.
+func (akuo *ApiKeyUpdateOne) SetUserID(u uuid.UUID) *ApiKeyUpdateOne {
+ akuo.mutation.SetUserID(u)
+ return akuo
+}
+
+// SetNillableUserID sets the "user_id" field if the given value is not nil.
+func (akuo *ApiKeyUpdateOne) SetNillableUserID(u *uuid.UUID) *ApiKeyUpdateOne {
+ if u != nil {
+ akuo.SetUserID(*u)
+ }
+ return akuo
+}
+
+// SetKey sets the "key" field.
+func (akuo *ApiKeyUpdateOne) SetKey(s string) *ApiKeyUpdateOne {
+ akuo.mutation.SetKey(s)
+ return akuo
+}
+
+// SetNillableKey sets the "key" field if the given value is not nil.
+func (akuo *ApiKeyUpdateOne) SetNillableKey(s *string) *ApiKeyUpdateOne {
+ if s != nil {
+ akuo.SetKey(*s)
+ }
+ return akuo
+}
+
+// SetName sets the "name" field.
+func (akuo *ApiKeyUpdateOne) SetName(s string) *ApiKeyUpdateOne {
+ akuo.mutation.SetName(s)
+ return akuo
+}
+
+// SetNillableName sets the "name" field if the given value is not nil.
+func (akuo *ApiKeyUpdateOne) SetNillableName(s *string) *ApiKeyUpdateOne {
+ if s != nil {
+ akuo.SetName(*s)
+ }
+ return akuo
+}
+
+// SetStatus sets the "status" field.
+func (akuo *ApiKeyUpdateOne) SetStatus(cks consts.ApiKeyStatus) *ApiKeyUpdateOne {
+ akuo.mutation.SetStatus(cks)
+ return akuo
+}
+
+// SetNillableStatus sets the "status" field if the given value is not nil.
+func (akuo *ApiKeyUpdateOne) SetNillableStatus(cks *consts.ApiKeyStatus) *ApiKeyUpdateOne {
+ if cks != nil {
+ akuo.SetStatus(*cks)
+ }
+ return akuo
+}
+
+// SetLastUsed sets the "last_used" field.
+func (akuo *ApiKeyUpdateOne) SetLastUsed(t time.Time) *ApiKeyUpdateOne {
+ akuo.mutation.SetLastUsed(t)
+ return akuo
+}
+
+// SetNillableLastUsed sets the "last_used" field if the given value is not nil.
+func (akuo *ApiKeyUpdateOne) SetNillableLastUsed(t *time.Time) *ApiKeyUpdateOne {
+ if t != nil {
+ akuo.SetLastUsed(*t)
+ }
+ return akuo
+}
+
+// ClearLastUsed clears the value of the "last_used" field.
+func (akuo *ApiKeyUpdateOne) ClearLastUsed() *ApiKeyUpdateOne {
+ akuo.mutation.ClearLastUsed()
+ return akuo
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (akuo *ApiKeyUpdateOne) SetCreatedAt(t time.Time) *ApiKeyUpdateOne {
+ akuo.mutation.SetCreatedAt(t)
+ return akuo
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (akuo *ApiKeyUpdateOne) SetNillableCreatedAt(t *time.Time) *ApiKeyUpdateOne {
+ if t != nil {
+ akuo.SetCreatedAt(*t)
+ }
+ return akuo
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (akuo *ApiKeyUpdateOne) SetUpdatedAt(t time.Time) *ApiKeyUpdateOne {
+ akuo.mutation.SetUpdatedAt(t)
+ return akuo
+}
+
+// Mutation returns the ApiKeyMutation object of the builder.
+func (akuo *ApiKeyUpdateOne) Mutation() *ApiKeyMutation {
+ return akuo.mutation
+}
+
+// Where appends a list predicates to the ApiKeyUpdate builder.
+func (akuo *ApiKeyUpdateOne) Where(ps ...predicate.ApiKey) *ApiKeyUpdateOne {
+ akuo.mutation.Where(ps...)
+ return akuo
+}
+
+// Select allows selecting one or more fields (columns) of the returned entity.
+// The default is selecting all fields defined in the entity schema.
+func (akuo *ApiKeyUpdateOne) Select(field string, fields ...string) *ApiKeyUpdateOne {
+ akuo.fields = append([]string{field}, fields...)
+ return akuo
+}
+
+// Save executes the query and returns the updated ApiKey entity.
+func (akuo *ApiKeyUpdateOne) Save(ctx context.Context) (*ApiKey, error) {
+ akuo.defaults()
+ return withHooks(ctx, akuo.sqlSave, akuo.mutation, akuo.hooks)
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (akuo *ApiKeyUpdateOne) SaveX(ctx context.Context) *ApiKey {
+ node, err := akuo.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return node
+}
+
+// Exec executes the query on the entity.
+func (akuo *ApiKeyUpdateOne) Exec(ctx context.Context) error {
+ _, err := akuo.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (akuo *ApiKeyUpdateOne) ExecX(ctx context.Context) {
+ if err := akuo.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// defaults sets the default values of the builder before save.
+func (akuo *ApiKeyUpdateOne) defaults() {
+ if _, ok := akuo.mutation.UpdatedAt(); !ok {
+ v := apikey.UpdateDefaultUpdatedAt()
+ akuo.mutation.SetUpdatedAt(v)
+ }
+}
+
+// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
+func (akuo *ApiKeyUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *ApiKeyUpdateOne {
+ akuo.modifiers = append(akuo.modifiers, modifiers...)
+ return akuo
+}
+
+func (akuo *ApiKeyUpdateOne) sqlSave(ctx context.Context) (_node *ApiKey, err error) {
+ _spec := sqlgraph.NewUpdateSpec(apikey.Table, apikey.Columns, sqlgraph.NewFieldSpec(apikey.FieldID, field.TypeUUID))
+ id, ok := akuo.mutation.ID()
+ if !ok {
+ return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "ApiKey.id" for update`)}
+ }
+ _spec.Node.ID.Value = id
+ if fields := akuo.fields; len(fields) > 0 {
+ _spec.Node.Columns = make([]string, 0, len(fields))
+ _spec.Node.Columns = append(_spec.Node.Columns, apikey.FieldID)
+ for _, f := range fields {
+ if !apikey.ValidColumn(f) {
+ return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
+ }
+ if f != apikey.FieldID {
+ _spec.Node.Columns = append(_spec.Node.Columns, f)
+ }
+ }
+ }
+ if ps := akuo.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if value, ok := akuo.mutation.UserID(); ok {
+ _spec.SetField(apikey.FieldUserID, field.TypeUUID, value)
+ }
+ if value, ok := akuo.mutation.Key(); ok {
+ _spec.SetField(apikey.FieldKey, field.TypeString, value)
+ }
+ if value, ok := akuo.mutation.Name(); ok {
+ _spec.SetField(apikey.FieldName, field.TypeString, value)
+ }
+ if value, ok := akuo.mutation.Status(); ok {
+ _spec.SetField(apikey.FieldStatus, field.TypeString, value)
+ }
+ if value, ok := akuo.mutation.LastUsed(); ok {
+ _spec.SetField(apikey.FieldLastUsed, field.TypeTime, value)
+ }
+ if akuo.mutation.LastUsedCleared() {
+ _spec.ClearField(apikey.FieldLastUsed, field.TypeTime)
+ }
+ if value, ok := akuo.mutation.CreatedAt(); ok {
+ _spec.SetField(apikey.FieldCreatedAt, field.TypeTime, value)
+ }
+ if value, ok := akuo.mutation.UpdatedAt(); ok {
+ _spec.SetField(apikey.FieldUpdatedAt, field.TypeTime, value)
+ }
+ _spec.AddModifiers(akuo.modifiers...)
+ _node = &ApiKey{config: akuo.config}
+ _spec.Assign = _node.assignValues
+ _spec.ScanValues = _node.scanValues
+ if err = sqlgraph.UpdateNode(ctx, akuo.driver, _spec); err != nil {
+ if _, ok := err.(*sqlgraph.NotFoundError); ok {
+ err = &NotFoundError{apikey.Label}
+ } else if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return nil, err
+ }
+ akuo.mutation.done = true
+ return _node, nil
+}
diff --git a/backend/db/billingplan.go b/backend/db/billingplan.go
new file mode 100644
index 0000000..365960f
--- /dev/null
+++ b/backend/db/billingplan.go
@@ -0,0 +1,153 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "encoding/json"
+ "fmt"
+ "strings"
+ "time"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect/sql"
+ "github.com/chaitin/MonkeyCode/backend/db/billingplan"
+)
+
+// BillingPlan is the model entity for the BillingPlan schema.
+type BillingPlan struct {
+ config `json:"-"`
+ // ID of the ent.
+ ID string `json:"id,omitempty"`
+ // Name holds the value of the "name" field.
+ Name string `json:"name,omitempty"`
+ // Description holds the value of the "description" field.
+ Description string `json:"description,omitempty"`
+ // Rules holds the value of the "rules" field.
+ Rules map[string]interface{} `json:"rules,omitempty"`
+ // CreatedAt holds the value of the "created_at" field.
+ CreatedAt time.Time `json:"created_at,omitempty"`
+ // UpdatedAt holds the value of the "updated_at" field.
+ UpdatedAt time.Time `json:"updated_at,omitempty"`
+ selectValues sql.SelectValues
+}
+
+// scanValues returns the types for scanning values from sql.Rows.
+func (*BillingPlan) scanValues(columns []string) ([]any, error) {
+ values := make([]any, len(columns))
+ for i := range columns {
+ switch columns[i] {
+ case billingplan.FieldRules:
+ values[i] = new([]byte)
+ case billingplan.FieldID, billingplan.FieldName, billingplan.FieldDescription:
+ values[i] = new(sql.NullString)
+ case billingplan.FieldCreatedAt, billingplan.FieldUpdatedAt:
+ values[i] = new(sql.NullTime)
+ default:
+ values[i] = new(sql.UnknownType)
+ }
+ }
+ return values, nil
+}
+
+// assignValues assigns the values that were returned from sql.Rows (after scanning)
+// to the BillingPlan fields.
+func (bp *BillingPlan) assignValues(columns []string, values []any) error {
+ if m, n := len(values), len(columns); m < n {
+ return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
+ }
+ for i := range columns {
+ switch columns[i] {
+ case billingplan.FieldID:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field id", values[i])
+ } else if value.Valid {
+ bp.ID = value.String
+ }
+ case billingplan.FieldName:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field name", values[i])
+ } else if value.Valid {
+ bp.Name = value.String
+ }
+ case billingplan.FieldDescription:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field description", values[i])
+ } else if value.Valid {
+ bp.Description = value.String
+ }
+ case billingplan.FieldRules:
+ if value, ok := values[i].(*[]byte); !ok {
+ return fmt.Errorf("unexpected type %T for field rules", values[i])
+ } else if value != nil && len(*value) > 0 {
+ if err := json.Unmarshal(*value, &bp.Rules); err != nil {
+ return fmt.Errorf("unmarshal field rules: %w", err)
+ }
+ }
+ case billingplan.FieldCreatedAt:
+ if value, ok := values[i].(*sql.NullTime); !ok {
+ return fmt.Errorf("unexpected type %T for field created_at", values[i])
+ } else if value.Valid {
+ bp.CreatedAt = value.Time
+ }
+ case billingplan.FieldUpdatedAt:
+ if value, ok := values[i].(*sql.NullTime); !ok {
+ return fmt.Errorf("unexpected type %T for field updated_at", values[i])
+ } else if value.Valid {
+ bp.UpdatedAt = value.Time
+ }
+ default:
+ bp.selectValues.Set(columns[i], values[i])
+ }
+ }
+ return nil
+}
+
+// Value returns the ent.Value that was dynamically selected and assigned to the BillingPlan.
+// This includes values selected through modifiers, order, etc.
+func (bp *BillingPlan) Value(name string) (ent.Value, error) {
+ return bp.selectValues.Get(name)
+}
+
+// Update returns a builder for updating this BillingPlan.
+// Note that you need to call BillingPlan.Unwrap() before calling this method if this BillingPlan
+// was returned from a transaction, and the transaction was committed or rolled back.
+func (bp *BillingPlan) Update() *BillingPlanUpdateOne {
+ return NewBillingPlanClient(bp.config).UpdateOne(bp)
+}
+
+// Unwrap unwraps the BillingPlan entity that was returned from a transaction after it was closed,
+// so that all future queries will be executed through the driver which created the transaction.
+func (bp *BillingPlan) Unwrap() *BillingPlan {
+ _tx, ok := bp.config.driver.(*txDriver)
+ if !ok {
+ panic("db: BillingPlan is not a transactional entity")
+ }
+ bp.config.driver = _tx.drv
+ return bp
+}
+
+// String implements the fmt.Stringer.
+func (bp *BillingPlan) String() string {
+ var builder strings.Builder
+ builder.WriteString("BillingPlan(")
+ builder.WriteString(fmt.Sprintf("id=%v, ", bp.ID))
+ builder.WriteString("name=")
+ builder.WriteString(bp.Name)
+ builder.WriteString(", ")
+ builder.WriteString("description=")
+ builder.WriteString(bp.Description)
+ builder.WriteString(", ")
+ builder.WriteString("rules=")
+ builder.WriteString(fmt.Sprintf("%v", bp.Rules))
+ builder.WriteString(", ")
+ builder.WriteString("created_at=")
+ builder.WriteString(bp.CreatedAt.Format(time.ANSIC))
+ builder.WriteString(", ")
+ builder.WriteString("updated_at=")
+ builder.WriteString(bp.UpdatedAt.Format(time.ANSIC))
+ builder.WriteByte(')')
+ return builder.String()
+}
+
+// BillingPlans is a parsable slice of BillingPlan.
+type BillingPlans []*BillingPlan
diff --git a/backend/db/billingplan/billingplan.go b/backend/db/billingplan/billingplan.go
new file mode 100644
index 0000000..1c261b5
--- /dev/null
+++ b/backend/db/billingplan/billingplan.go
@@ -0,0 +1,85 @@
+// Code generated by ent, DO NOT EDIT.
+
+package billingplan
+
+import (
+ "time"
+
+ "entgo.io/ent/dialect/sql"
+)
+
+const (
+ // Label holds the string label denoting the billingplan type in the database.
+ Label = "billing_plan"
+ // FieldID holds the string denoting the id field in the database.
+ FieldID = "id"
+ // FieldName holds the string denoting the name field in the database.
+ FieldName = "name"
+ // FieldDescription holds the string denoting the description field in the database.
+ FieldDescription = "description"
+ // FieldRules holds the string denoting the rules field in the database.
+ FieldRules = "rules"
+ // FieldCreatedAt holds the string denoting the created_at field in the database.
+ FieldCreatedAt = "created_at"
+ // FieldUpdatedAt holds the string denoting the updated_at field in the database.
+ FieldUpdatedAt = "updated_at"
+ // Table holds the table name of the billingplan in the database.
+ Table = "billing_plans"
+)
+
+// Columns holds all SQL columns for billingplan fields.
+var Columns = []string{
+ FieldID,
+ FieldName,
+ FieldDescription,
+ FieldRules,
+ FieldCreatedAt,
+ FieldUpdatedAt,
+}
+
+// ValidColumn reports if the column name is valid (part of the table columns).
+func ValidColumn(column string) bool {
+ for i := range Columns {
+ if column == Columns[i] {
+ return true
+ }
+ }
+ return false
+}
+
+var (
+ // DefaultCreatedAt holds the default value on creation for the "created_at" field.
+ DefaultCreatedAt func() time.Time
+ // DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
+ DefaultUpdatedAt func() time.Time
+ // UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field.
+ UpdateDefaultUpdatedAt func() time.Time
+)
+
+// OrderOption defines the ordering options for the BillingPlan queries.
+type OrderOption func(*sql.Selector)
+
+// ByID orders the results by the id field.
+func ByID(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldID, opts...).ToFunc()
+}
+
+// ByName orders the results by the name field.
+func ByName(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldName, opts...).ToFunc()
+}
+
+// ByDescription orders the results by the description field.
+func ByDescription(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldDescription, opts...).ToFunc()
+}
+
+// ByCreatedAt orders the results by the created_at field.
+func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
+}
+
+// ByUpdatedAt orders the results by the updated_at field.
+func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc()
+}
diff --git a/backend/db/billingplan/where.go b/backend/db/billingplan/where.go
new file mode 100644
index 0000000..c402272
--- /dev/null
+++ b/backend/db/billingplan/where.go
@@ -0,0 +1,310 @@
+// Code generated by ent, DO NOT EDIT.
+
+package billingplan
+
+import (
+ "time"
+
+ "entgo.io/ent/dialect/sql"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+)
+
+// ID filters vertices based on their ID field.
+func ID(id string) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldEQ(FieldID, id))
+}
+
+// IDEQ applies the EQ predicate on the ID field.
+func IDEQ(id string) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldEQ(FieldID, id))
+}
+
+// IDNEQ applies the NEQ predicate on the ID field.
+func IDNEQ(id string) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldNEQ(FieldID, id))
+}
+
+// IDIn applies the In predicate on the ID field.
+func IDIn(ids ...string) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldIn(FieldID, ids...))
+}
+
+// IDNotIn applies the NotIn predicate on the ID field.
+func IDNotIn(ids ...string) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldNotIn(FieldID, ids...))
+}
+
+// IDGT applies the GT predicate on the ID field.
+func IDGT(id string) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldGT(FieldID, id))
+}
+
+// IDGTE applies the GTE predicate on the ID field.
+func IDGTE(id string) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldGTE(FieldID, id))
+}
+
+// IDLT applies the LT predicate on the ID field.
+func IDLT(id string) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldLT(FieldID, id))
+}
+
+// IDLTE applies the LTE predicate on the ID field.
+func IDLTE(id string) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldLTE(FieldID, id))
+}
+
+// IDEqualFold applies the EqualFold predicate on the ID field.
+func IDEqualFold(id string) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldEqualFold(FieldID, id))
+}
+
+// IDContainsFold applies the ContainsFold predicate on the ID field.
+func IDContainsFold(id string) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldContainsFold(FieldID, id))
+}
+
+// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
+func Name(v string) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldEQ(FieldName, v))
+}
+
+// Description applies equality check predicate on the "description" field. It's identical to DescriptionEQ.
+func Description(v string) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldEQ(FieldDescription, v))
+}
+
+// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
+func CreatedAt(v time.Time) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldEQ(FieldCreatedAt, v))
+}
+
+// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
+func UpdatedAt(v time.Time) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldEQ(FieldUpdatedAt, v))
+}
+
+// NameEQ applies the EQ predicate on the "name" field.
+func NameEQ(v string) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldEQ(FieldName, v))
+}
+
+// NameNEQ applies the NEQ predicate on the "name" field.
+func NameNEQ(v string) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldNEQ(FieldName, v))
+}
+
+// NameIn applies the In predicate on the "name" field.
+func NameIn(vs ...string) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldIn(FieldName, vs...))
+}
+
+// NameNotIn applies the NotIn predicate on the "name" field.
+func NameNotIn(vs ...string) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldNotIn(FieldName, vs...))
+}
+
+// NameGT applies the GT predicate on the "name" field.
+func NameGT(v string) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldGT(FieldName, v))
+}
+
+// NameGTE applies the GTE predicate on the "name" field.
+func NameGTE(v string) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldGTE(FieldName, v))
+}
+
+// NameLT applies the LT predicate on the "name" field.
+func NameLT(v string) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldLT(FieldName, v))
+}
+
+// NameLTE applies the LTE predicate on the "name" field.
+func NameLTE(v string) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldLTE(FieldName, v))
+}
+
+// NameContains applies the Contains predicate on the "name" field.
+func NameContains(v string) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldContains(FieldName, v))
+}
+
+// NameHasPrefix applies the HasPrefix predicate on the "name" field.
+func NameHasPrefix(v string) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldHasPrefix(FieldName, v))
+}
+
+// NameHasSuffix applies the HasSuffix predicate on the "name" field.
+func NameHasSuffix(v string) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldHasSuffix(FieldName, v))
+}
+
+// NameEqualFold applies the EqualFold predicate on the "name" field.
+func NameEqualFold(v string) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldEqualFold(FieldName, v))
+}
+
+// NameContainsFold applies the ContainsFold predicate on the "name" field.
+func NameContainsFold(v string) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldContainsFold(FieldName, v))
+}
+
+// DescriptionEQ applies the EQ predicate on the "description" field.
+func DescriptionEQ(v string) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldEQ(FieldDescription, v))
+}
+
+// DescriptionNEQ applies the NEQ predicate on the "description" field.
+func DescriptionNEQ(v string) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldNEQ(FieldDescription, v))
+}
+
+// DescriptionIn applies the In predicate on the "description" field.
+func DescriptionIn(vs ...string) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldIn(FieldDescription, vs...))
+}
+
+// DescriptionNotIn applies the NotIn predicate on the "description" field.
+func DescriptionNotIn(vs ...string) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldNotIn(FieldDescription, vs...))
+}
+
+// DescriptionGT applies the GT predicate on the "description" field.
+func DescriptionGT(v string) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldGT(FieldDescription, v))
+}
+
+// DescriptionGTE applies the GTE predicate on the "description" field.
+func DescriptionGTE(v string) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldGTE(FieldDescription, v))
+}
+
+// DescriptionLT applies the LT predicate on the "description" field.
+func DescriptionLT(v string) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldLT(FieldDescription, v))
+}
+
+// DescriptionLTE applies the LTE predicate on the "description" field.
+func DescriptionLTE(v string) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldLTE(FieldDescription, v))
+}
+
+// DescriptionContains applies the Contains predicate on the "description" field.
+func DescriptionContains(v string) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldContains(FieldDescription, v))
+}
+
+// DescriptionHasPrefix applies the HasPrefix predicate on the "description" field.
+func DescriptionHasPrefix(v string) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldHasPrefix(FieldDescription, v))
+}
+
+// DescriptionHasSuffix applies the HasSuffix predicate on the "description" field.
+func DescriptionHasSuffix(v string) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldHasSuffix(FieldDescription, v))
+}
+
+// DescriptionEqualFold applies the EqualFold predicate on the "description" field.
+func DescriptionEqualFold(v string) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldEqualFold(FieldDescription, v))
+}
+
+// DescriptionContainsFold applies the ContainsFold predicate on the "description" field.
+func DescriptionContainsFold(v string) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldContainsFold(FieldDescription, v))
+}
+
+// CreatedAtEQ applies the EQ predicate on the "created_at" field.
+func CreatedAtEQ(v time.Time) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldEQ(FieldCreatedAt, v))
+}
+
+// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
+func CreatedAtNEQ(v time.Time) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldNEQ(FieldCreatedAt, v))
+}
+
+// CreatedAtIn applies the In predicate on the "created_at" field.
+func CreatedAtIn(vs ...time.Time) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldIn(FieldCreatedAt, vs...))
+}
+
+// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
+func CreatedAtNotIn(vs ...time.Time) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldNotIn(FieldCreatedAt, vs...))
+}
+
+// CreatedAtGT applies the GT predicate on the "created_at" field.
+func CreatedAtGT(v time.Time) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldGT(FieldCreatedAt, v))
+}
+
+// CreatedAtGTE applies the GTE predicate on the "created_at" field.
+func CreatedAtGTE(v time.Time) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldGTE(FieldCreatedAt, v))
+}
+
+// CreatedAtLT applies the LT predicate on the "created_at" field.
+func CreatedAtLT(v time.Time) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldLT(FieldCreatedAt, v))
+}
+
+// CreatedAtLTE applies the LTE predicate on the "created_at" field.
+func CreatedAtLTE(v time.Time) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldLTE(FieldCreatedAt, v))
+}
+
+// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
+func UpdatedAtEQ(v time.Time) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldEQ(FieldUpdatedAt, v))
+}
+
+// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
+func UpdatedAtNEQ(v time.Time) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldNEQ(FieldUpdatedAt, v))
+}
+
+// UpdatedAtIn applies the In predicate on the "updated_at" field.
+func UpdatedAtIn(vs ...time.Time) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldIn(FieldUpdatedAt, vs...))
+}
+
+// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
+func UpdatedAtNotIn(vs ...time.Time) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldNotIn(FieldUpdatedAt, vs...))
+}
+
+// UpdatedAtGT applies the GT predicate on the "updated_at" field.
+func UpdatedAtGT(v time.Time) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldGT(FieldUpdatedAt, v))
+}
+
+// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
+func UpdatedAtGTE(v time.Time) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldGTE(FieldUpdatedAt, v))
+}
+
+// UpdatedAtLT applies the LT predicate on the "updated_at" field.
+func UpdatedAtLT(v time.Time) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldLT(FieldUpdatedAt, v))
+}
+
+// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
+func UpdatedAtLTE(v time.Time) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.FieldLTE(FieldUpdatedAt, v))
+}
+
+// And groups predicates with the AND operator between them.
+func And(predicates ...predicate.BillingPlan) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.AndPredicates(predicates...))
+}
+
+// Or groups predicates with the OR operator between them.
+func Or(predicates ...predicate.BillingPlan) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.OrPredicates(predicates...))
+}
+
+// Not applies the not operator on the given predicate.
+func Not(p predicate.BillingPlan) predicate.BillingPlan {
+ return predicate.BillingPlan(sql.NotPredicates(p))
+}
diff --git a/backend/db/billingplan_create.go b/backend/db/billingplan_create.go
new file mode 100644
index 0000000..7ad7941
--- /dev/null
+++ b/backend/db/billingplan_create.go
@@ -0,0 +1,732 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "time"
+
+ "entgo.io/ent/dialect"
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/billingplan"
+)
+
+// BillingPlanCreate is the builder for creating a BillingPlan entity.
+type BillingPlanCreate struct {
+ config
+ mutation *BillingPlanMutation
+ hooks []Hook
+ conflict []sql.ConflictOption
+}
+
+// SetName sets the "name" field.
+func (bpc *BillingPlanCreate) SetName(s string) *BillingPlanCreate {
+ bpc.mutation.SetName(s)
+ return bpc
+}
+
+// SetDescription sets the "description" field.
+func (bpc *BillingPlanCreate) SetDescription(s string) *BillingPlanCreate {
+ bpc.mutation.SetDescription(s)
+ return bpc
+}
+
+// SetRules sets the "rules" field.
+func (bpc *BillingPlanCreate) SetRules(m map[string]interface{}) *BillingPlanCreate {
+ bpc.mutation.SetRules(m)
+ return bpc
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (bpc *BillingPlanCreate) SetCreatedAt(t time.Time) *BillingPlanCreate {
+ bpc.mutation.SetCreatedAt(t)
+ return bpc
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (bpc *BillingPlanCreate) SetNillableCreatedAt(t *time.Time) *BillingPlanCreate {
+ if t != nil {
+ bpc.SetCreatedAt(*t)
+ }
+ return bpc
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (bpc *BillingPlanCreate) SetUpdatedAt(t time.Time) *BillingPlanCreate {
+ bpc.mutation.SetUpdatedAt(t)
+ return bpc
+}
+
+// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
+func (bpc *BillingPlanCreate) SetNillableUpdatedAt(t *time.Time) *BillingPlanCreate {
+ if t != nil {
+ bpc.SetUpdatedAt(*t)
+ }
+ return bpc
+}
+
+// SetID sets the "id" field.
+func (bpc *BillingPlanCreate) SetID(s string) *BillingPlanCreate {
+ bpc.mutation.SetID(s)
+ return bpc
+}
+
+// Mutation returns the BillingPlanMutation object of the builder.
+func (bpc *BillingPlanCreate) Mutation() *BillingPlanMutation {
+ return bpc.mutation
+}
+
+// Save creates the BillingPlan in the database.
+func (bpc *BillingPlanCreate) Save(ctx context.Context) (*BillingPlan, error) {
+ bpc.defaults()
+ return withHooks(ctx, bpc.sqlSave, bpc.mutation, bpc.hooks)
+}
+
+// SaveX calls Save and panics if Save returns an error.
+func (bpc *BillingPlanCreate) SaveX(ctx context.Context) *BillingPlan {
+ v, err := bpc.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return v
+}
+
+// Exec executes the query.
+func (bpc *BillingPlanCreate) Exec(ctx context.Context) error {
+ _, err := bpc.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (bpc *BillingPlanCreate) ExecX(ctx context.Context) {
+ if err := bpc.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// defaults sets the default values of the builder before save.
+func (bpc *BillingPlanCreate) defaults() {
+ if _, ok := bpc.mutation.CreatedAt(); !ok {
+ v := billingplan.DefaultCreatedAt()
+ bpc.mutation.SetCreatedAt(v)
+ }
+ if _, ok := bpc.mutation.UpdatedAt(); !ok {
+ v := billingplan.DefaultUpdatedAt()
+ bpc.mutation.SetUpdatedAt(v)
+ }
+}
+
+// check runs all checks and user-defined validators on the builder.
+func (bpc *BillingPlanCreate) check() error {
+ if _, ok := bpc.mutation.Name(); !ok {
+ return &ValidationError{Name: "name", err: errors.New(`db: missing required field "BillingPlan.name"`)}
+ }
+ if _, ok := bpc.mutation.Description(); !ok {
+ return &ValidationError{Name: "description", err: errors.New(`db: missing required field "BillingPlan.description"`)}
+ }
+ if _, ok := bpc.mutation.Rules(); !ok {
+ return &ValidationError{Name: "rules", err: errors.New(`db: missing required field "BillingPlan.rules"`)}
+ }
+ if _, ok := bpc.mutation.CreatedAt(); !ok {
+ return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "BillingPlan.created_at"`)}
+ }
+ if _, ok := bpc.mutation.UpdatedAt(); !ok {
+ return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "BillingPlan.updated_at"`)}
+ }
+ return nil
+}
+
+func (bpc *BillingPlanCreate) sqlSave(ctx context.Context) (*BillingPlan, error) {
+ if err := bpc.check(); err != nil {
+ return nil, err
+ }
+ _node, _spec := bpc.createSpec()
+ if err := sqlgraph.CreateNode(ctx, bpc.driver, _spec); err != nil {
+ if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return nil, err
+ }
+ if _spec.ID.Value != nil {
+ if id, ok := _spec.ID.Value.(string); ok {
+ _node.ID = id
+ } else {
+ return nil, fmt.Errorf("unexpected BillingPlan.ID type: %T", _spec.ID.Value)
+ }
+ }
+ bpc.mutation.id = &_node.ID
+ bpc.mutation.done = true
+ return _node, nil
+}
+
+func (bpc *BillingPlanCreate) createSpec() (*BillingPlan, *sqlgraph.CreateSpec) {
+ var (
+ _node = &BillingPlan{config: bpc.config}
+ _spec = sqlgraph.NewCreateSpec(billingplan.Table, sqlgraph.NewFieldSpec(billingplan.FieldID, field.TypeString))
+ )
+ _spec.OnConflict = bpc.conflict
+ if id, ok := bpc.mutation.ID(); ok {
+ _node.ID = id
+ _spec.ID.Value = id
+ }
+ if value, ok := bpc.mutation.Name(); ok {
+ _spec.SetField(billingplan.FieldName, field.TypeString, value)
+ _node.Name = value
+ }
+ if value, ok := bpc.mutation.Description(); ok {
+ _spec.SetField(billingplan.FieldDescription, field.TypeString, value)
+ _node.Description = value
+ }
+ if value, ok := bpc.mutation.Rules(); ok {
+ _spec.SetField(billingplan.FieldRules, field.TypeJSON, value)
+ _node.Rules = value
+ }
+ if value, ok := bpc.mutation.CreatedAt(); ok {
+ _spec.SetField(billingplan.FieldCreatedAt, field.TypeTime, value)
+ _node.CreatedAt = value
+ }
+ if value, ok := bpc.mutation.UpdatedAt(); ok {
+ _spec.SetField(billingplan.FieldUpdatedAt, field.TypeTime, value)
+ _node.UpdatedAt = value
+ }
+ return _node, _spec
+}
+
+// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
+// of the `INSERT` statement. For example:
+//
+// client.BillingPlan.Create().
+// SetName(v).
+// OnConflict(
+// // Update the row with the new values
+// // the was proposed for insertion.
+// sql.ResolveWithNewValues(),
+// ).
+// // Override some of the fields with custom
+// // update values.
+// Update(func(u *ent.BillingPlanUpsert) {
+// SetName(v+v).
+// }).
+// Exec(ctx)
+func (bpc *BillingPlanCreate) OnConflict(opts ...sql.ConflictOption) *BillingPlanUpsertOne {
+ bpc.conflict = opts
+ return &BillingPlanUpsertOne{
+ create: bpc,
+ }
+}
+
+// OnConflictColumns calls `OnConflict` and configures the columns
+// as conflict target. Using this option is equivalent to using:
+//
+// client.BillingPlan.Create().
+// OnConflict(sql.ConflictColumns(columns...)).
+// Exec(ctx)
+func (bpc *BillingPlanCreate) OnConflictColumns(columns ...string) *BillingPlanUpsertOne {
+ bpc.conflict = append(bpc.conflict, sql.ConflictColumns(columns...))
+ return &BillingPlanUpsertOne{
+ create: bpc,
+ }
+}
+
+type (
+ // BillingPlanUpsertOne is the builder for "upsert"-ing
+ // one BillingPlan node.
+ BillingPlanUpsertOne struct {
+ create *BillingPlanCreate
+ }
+
+ // BillingPlanUpsert is the "OnConflict" setter.
+ BillingPlanUpsert struct {
+ *sql.UpdateSet
+ }
+)
+
+// SetName sets the "name" field.
+func (u *BillingPlanUpsert) SetName(v string) *BillingPlanUpsert {
+ u.Set(billingplan.FieldName, v)
+ return u
+}
+
+// UpdateName sets the "name" field to the value that was provided on create.
+func (u *BillingPlanUpsert) UpdateName() *BillingPlanUpsert {
+ u.SetExcluded(billingplan.FieldName)
+ return u
+}
+
+// SetDescription sets the "description" field.
+func (u *BillingPlanUpsert) SetDescription(v string) *BillingPlanUpsert {
+ u.Set(billingplan.FieldDescription, v)
+ return u
+}
+
+// UpdateDescription sets the "description" field to the value that was provided on create.
+func (u *BillingPlanUpsert) UpdateDescription() *BillingPlanUpsert {
+ u.SetExcluded(billingplan.FieldDescription)
+ return u
+}
+
+// SetRules sets the "rules" field.
+func (u *BillingPlanUpsert) SetRules(v map[string]interface{}) *BillingPlanUpsert {
+ u.Set(billingplan.FieldRules, v)
+ return u
+}
+
+// UpdateRules sets the "rules" field to the value that was provided on create.
+func (u *BillingPlanUpsert) UpdateRules() *BillingPlanUpsert {
+ u.SetExcluded(billingplan.FieldRules)
+ return u
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (u *BillingPlanUpsert) SetCreatedAt(v time.Time) *BillingPlanUpsert {
+ u.Set(billingplan.FieldCreatedAt, v)
+ return u
+}
+
+// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
+func (u *BillingPlanUpsert) UpdateCreatedAt() *BillingPlanUpsert {
+ u.SetExcluded(billingplan.FieldCreatedAt)
+ return u
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (u *BillingPlanUpsert) SetUpdatedAt(v time.Time) *BillingPlanUpsert {
+ u.Set(billingplan.FieldUpdatedAt, v)
+ return u
+}
+
+// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
+func (u *BillingPlanUpsert) UpdateUpdatedAt() *BillingPlanUpsert {
+ u.SetExcluded(billingplan.FieldUpdatedAt)
+ return u
+}
+
+// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field.
+// Using this option is equivalent to using:
+//
+// client.BillingPlan.Create().
+// OnConflict(
+// sql.ResolveWithNewValues(),
+// sql.ResolveWith(func(u *sql.UpdateSet) {
+// u.SetIgnore(billingplan.FieldID)
+// }),
+// ).
+// Exec(ctx)
+func (u *BillingPlanUpsertOne) UpdateNewValues() *BillingPlanUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
+ if _, exists := u.create.mutation.ID(); exists {
+ s.SetIgnore(billingplan.FieldID)
+ }
+ }))
+ return u
+}
+
+// Ignore sets each column to itself in case of conflict.
+// Using this option is equivalent to using:
+//
+// client.BillingPlan.Create().
+// OnConflict(sql.ResolveWithIgnore()).
+// Exec(ctx)
+func (u *BillingPlanUpsertOne) Ignore() *BillingPlanUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
+ return u
+}
+
+// DoNothing configures the conflict_action to `DO NOTHING`.
+// Supported only by SQLite and PostgreSQL.
+func (u *BillingPlanUpsertOne) DoNothing() *BillingPlanUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.DoNothing())
+ return u
+}
+
+// Update allows overriding fields `UPDATE` values. See the BillingPlanCreate.OnConflict
+// documentation for more info.
+func (u *BillingPlanUpsertOne) Update(set func(*BillingPlanUpsert)) *BillingPlanUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
+ set(&BillingPlanUpsert{UpdateSet: update})
+ }))
+ return u
+}
+
+// SetName sets the "name" field.
+func (u *BillingPlanUpsertOne) SetName(v string) *BillingPlanUpsertOne {
+ return u.Update(func(s *BillingPlanUpsert) {
+ s.SetName(v)
+ })
+}
+
+// UpdateName sets the "name" field to the value that was provided on create.
+func (u *BillingPlanUpsertOne) UpdateName() *BillingPlanUpsertOne {
+ return u.Update(func(s *BillingPlanUpsert) {
+ s.UpdateName()
+ })
+}
+
+// SetDescription sets the "description" field.
+func (u *BillingPlanUpsertOne) SetDescription(v string) *BillingPlanUpsertOne {
+ return u.Update(func(s *BillingPlanUpsert) {
+ s.SetDescription(v)
+ })
+}
+
+// UpdateDescription sets the "description" field to the value that was provided on create.
+func (u *BillingPlanUpsertOne) UpdateDescription() *BillingPlanUpsertOne {
+ return u.Update(func(s *BillingPlanUpsert) {
+ s.UpdateDescription()
+ })
+}
+
+// SetRules sets the "rules" field.
+func (u *BillingPlanUpsertOne) SetRules(v map[string]interface{}) *BillingPlanUpsertOne {
+ return u.Update(func(s *BillingPlanUpsert) {
+ s.SetRules(v)
+ })
+}
+
+// UpdateRules sets the "rules" field to the value that was provided on create.
+func (u *BillingPlanUpsertOne) UpdateRules() *BillingPlanUpsertOne {
+ return u.Update(func(s *BillingPlanUpsert) {
+ s.UpdateRules()
+ })
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (u *BillingPlanUpsertOne) SetCreatedAt(v time.Time) *BillingPlanUpsertOne {
+ return u.Update(func(s *BillingPlanUpsert) {
+ s.SetCreatedAt(v)
+ })
+}
+
+// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
+func (u *BillingPlanUpsertOne) UpdateCreatedAt() *BillingPlanUpsertOne {
+ return u.Update(func(s *BillingPlanUpsert) {
+ s.UpdateCreatedAt()
+ })
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (u *BillingPlanUpsertOne) SetUpdatedAt(v time.Time) *BillingPlanUpsertOne {
+ return u.Update(func(s *BillingPlanUpsert) {
+ s.SetUpdatedAt(v)
+ })
+}
+
+// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
+func (u *BillingPlanUpsertOne) UpdateUpdatedAt() *BillingPlanUpsertOne {
+ return u.Update(func(s *BillingPlanUpsert) {
+ s.UpdateUpdatedAt()
+ })
+}
+
+// Exec executes the query.
+func (u *BillingPlanUpsertOne) Exec(ctx context.Context) error {
+ if len(u.create.conflict) == 0 {
+ return errors.New("db: missing options for BillingPlanCreate.OnConflict")
+ }
+ return u.create.Exec(ctx)
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (u *BillingPlanUpsertOne) ExecX(ctx context.Context) {
+ if err := u.create.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// Exec executes the UPSERT query and returns the inserted/updated ID.
+func (u *BillingPlanUpsertOne) ID(ctx context.Context) (id string, err error) {
+ if u.create.driver.Dialect() == dialect.MySQL {
+ // In case of "ON CONFLICT", there is no way to get back non-numeric ID
+ // fields from the database since MySQL does not support the RETURNING clause.
+ return id, errors.New("db: BillingPlanUpsertOne.ID is not supported by MySQL driver. Use BillingPlanUpsertOne.Exec instead")
+ }
+ node, err := u.create.Save(ctx)
+ if err != nil {
+ return id, err
+ }
+ return node.ID, nil
+}
+
+// IDX is like ID, but panics if an error occurs.
+func (u *BillingPlanUpsertOne) IDX(ctx context.Context) string {
+ id, err := u.ID(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return id
+}
+
+// BillingPlanCreateBulk is the builder for creating many BillingPlan entities in bulk.
+type BillingPlanCreateBulk struct {
+ config
+ err error
+ builders []*BillingPlanCreate
+ conflict []sql.ConflictOption
+}
+
+// Save creates the BillingPlan entities in the database.
+func (bpcb *BillingPlanCreateBulk) Save(ctx context.Context) ([]*BillingPlan, error) {
+ if bpcb.err != nil {
+ return nil, bpcb.err
+ }
+ specs := make([]*sqlgraph.CreateSpec, len(bpcb.builders))
+ nodes := make([]*BillingPlan, len(bpcb.builders))
+ mutators := make([]Mutator, len(bpcb.builders))
+ for i := range bpcb.builders {
+ func(i int, root context.Context) {
+ builder := bpcb.builders[i]
+ builder.defaults()
+ var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
+ mutation, ok := m.(*BillingPlanMutation)
+ if !ok {
+ return nil, fmt.Errorf("unexpected mutation type %T", m)
+ }
+ if err := builder.check(); err != nil {
+ return nil, err
+ }
+ builder.mutation = mutation
+ var err error
+ nodes[i], specs[i] = builder.createSpec()
+ if i < len(mutators)-1 {
+ _, err = mutators[i+1].Mutate(root, bpcb.builders[i+1].mutation)
+ } else {
+ spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
+ spec.OnConflict = bpcb.conflict
+ // Invoke the actual operation on the latest mutation in the chain.
+ if err = sqlgraph.BatchCreate(ctx, bpcb.driver, spec); err != nil {
+ if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ }
+ }
+ if err != nil {
+ return nil, err
+ }
+ mutation.id = &nodes[i].ID
+ mutation.done = true
+ return nodes[i], nil
+ })
+ for i := len(builder.hooks) - 1; i >= 0; i-- {
+ mut = builder.hooks[i](mut)
+ }
+ mutators[i] = mut
+ }(i, ctx)
+ }
+ if len(mutators) > 0 {
+ if _, err := mutators[0].Mutate(ctx, bpcb.builders[0].mutation); err != nil {
+ return nil, err
+ }
+ }
+ return nodes, nil
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (bpcb *BillingPlanCreateBulk) SaveX(ctx context.Context) []*BillingPlan {
+ v, err := bpcb.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return v
+}
+
+// Exec executes the query.
+func (bpcb *BillingPlanCreateBulk) Exec(ctx context.Context) error {
+ _, err := bpcb.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (bpcb *BillingPlanCreateBulk) ExecX(ctx context.Context) {
+ if err := bpcb.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
+// of the `INSERT` statement. For example:
+//
+// client.BillingPlan.CreateBulk(builders...).
+// OnConflict(
+// // Update the row with the new values
+// // the was proposed for insertion.
+// sql.ResolveWithNewValues(),
+// ).
+// // Override some of the fields with custom
+// // update values.
+// Update(func(u *ent.BillingPlanUpsert) {
+// SetName(v+v).
+// }).
+// Exec(ctx)
+func (bpcb *BillingPlanCreateBulk) OnConflict(opts ...sql.ConflictOption) *BillingPlanUpsertBulk {
+ bpcb.conflict = opts
+ return &BillingPlanUpsertBulk{
+ create: bpcb,
+ }
+}
+
+// OnConflictColumns calls `OnConflict` and configures the columns
+// as conflict target. Using this option is equivalent to using:
+//
+// client.BillingPlan.Create().
+// OnConflict(sql.ConflictColumns(columns...)).
+// Exec(ctx)
+func (bpcb *BillingPlanCreateBulk) OnConflictColumns(columns ...string) *BillingPlanUpsertBulk {
+ bpcb.conflict = append(bpcb.conflict, sql.ConflictColumns(columns...))
+ return &BillingPlanUpsertBulk{
+ create: bpcb,
+ }
+}
+
+// BillingPlanUpsertBulk is the builder for "upsert"-ing
+// a bulk of BillingPlan nodes.
+type BillingPlanUpsertBulk struct {
+ create *BillingPlanCreateBulk
+}
+
+// UpdateNewValues updates the mutable fields using the new values that
+// were set on create. Using this option is equivalent to using:
+//
+// client.BillingPlan.Create().
+// OnConflict(
+// sql.ResolveWithNewValues(),
+// sql.ResolveWith(func(u *sql.UpdateSet) {
+// u.SetIgnore(billingplan.FieldID)
+// }),
+// ).
+// Exec(ctx)
+func (u *BillingPlanUpsertBulk) UpdateNewValues() *BillingPlanUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
+ for _, b := range u.create.builders {
+ if _, exists := b.mutation.ID(); exists {
+ s.SetIgnore(billingplan.FieldID)
+ }
+ }
+ }))
+ return u
+}
+
+// Ignore sets each column to itself in case of conflict.
+// Using this option is equivalent to using:
+//
+// client.BillingPlan.Create().
+// OnConflict(sql.ResolveWithIgnore()).
+// Exec(ctx)
+func (u *BillingPlanUpsertBulk) Ignore() *BillingPlanUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
+ return u
+}
+
+// DoNothing configures the conflict_action to `DO NOTHING`.
+// Supported only by SQLite and PostgreSQL.
+func (u *BillingPlanUpsertBulk) DoNothing() *BillingPlanUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.DoNothing())
+ return u
+}
+
+// Update allows overriding fields `UPDATE` values. See the BillingPlanCreateBulk.OnConflict
+// documentation for more info.
+func (u *BillingPlanUpsertBulk) Update(set func(*BillingPlanUpsert)) *BillingPlanUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
+ set(&BillingPlanUpsert{UpdateSet: update})
+ }))
+ return u
+}
+
+// SetName sets the "name" field.
+func (u *BillingPlanUpsertBulk) SetName(v string) *BillingPlanUpsertBulk {
+ return u.Update(func(s *BillingPlanUpsert) {
+ s.SetName(v)
+ })
+}
+
+// UpdateName sets the "name" field to the value that was provided on create.
+func (u *BillingPlanUpsertBulk) UpdateName() *BillingPlanUpsertBulk {
+ return u.Update(func(s *BillingPlanUpsert) {
+ s.UpdateName()
+ })
+}
+
+// SetDescription sets the "description" field.
+func (u *BillingPlanUpsertBulk) SetDescription(v string) *BillingPlanUpsertBulk {
+ return u.Update(func(s *BillingPlanUpsert) {
+ s.SetDescription(v)
+ })
+}
+
+// UpdateDescription sets the "description" field to the value that was provided on create.
+func (u *BillingPlanUpsertBulk) UpdateDescription() *BillingPlanUpsertBulk {
+ return u.Update(func(s *BillingPlanUpsert) {
+ s.UpdateDescription()
+ })
+}
+
+// SetRules sets the "rules" field.
+func (u *BillingPlanUpsertBulk) SetRules(v map[string]interface{}) *BillingPlanUpsertBulk {
+ return u.Update(func(s *BillingPlanUpsert) {
+ s.SetRules(v)
+ })
+}
+
+// UpdateRules sets the "rules" field to the value that was provided on create.
+func (u *BillingPlanUpsertBulk) UpdateRules() *BillingPlanUpsertBulk {
+ return u.Update(func(s *BillingPlanUpsert) {
+ s.UpdateRules()
+ })
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (u *BillingPlanUpsertBulk) SetCreatedAt(v time.Time) *BillingPlanUpsertBulk {
+ return u.Update(func(s *BillingPlanUpsert) {
+ s.SetCreatedAt(v)
+ })
+}
+
+// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
+func (u *BillingPlanUpsertBulk) UpdateCreatedAt() *BillingPlanUpsertBulk {
+ return u.Update(func(s *BillingPlanUpsert) {
+ s.UpdateCreatedAt()
+ })
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (u *BillingPlanUpsertBulk) SetUpdatedAt(v time.Time) *BillingPlanUpsertBulk {
+ return u.Update(func(s *BillingPlanUpsert) {
+ s.SetUpdatedAt(v)
+ })
+}
+
+// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
+func (u *BillingPlanUpsertBulk) UpdateUpdatedAt() *BillingPlanUpsertBulk {
+ return u.Update(func(s *BillingPlanUpsert) {
+ s.UpdateUpdatedAt()
+ })
+}
+
+// Exec executes the query.
+func (u *BillingPlanUpsertBulk) Exec(ctx context.Context) error {
+ if u.create.err != nil {
+ return u.create.err
+ }
+ for i, b := range u.create.builders {
+ if len(b.conflict) != 0 {
+ return fmt.Errorf("db: OnConflict was set for builder %d. Set it on the BillingPlanCreateBulk instead", i)
+ }
+ }
+ if len(u.create.conflict) == 0 {
+ return errors.New("db: missing options for BillingPlanCreateBulk.OnConflict")
+ }
+ return u.create.Exec(ctx)
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (u *BillingPlanUpsertBulk) ExecX(ctx context.Context) {
+ if err := u.create.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
diff --git a/backend/db/billingplan_delete.go b/backend/db/billingplan_delete.go
new file mode 100644
index 0000000..31fca60
--- /dev/null
+++ b/backend/db/billingplan_delete.go
@@ -0,0 +1,88 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/billingplan"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+)
+
+// BillingPlanDelete is the builder for deleting a BillingPlan entity.
+type BillingPlanDelete struct {
+ config
+ hooks []Hook
+ mutation *BillingPlanMutation
+}
+
+// Where appends a list predicates to the BillingPlanDelete builder.
+func (bpd *BillingPlanDelete) Where(ps ...predicate.BillingPlan) *BillingPlanDelete {
+ bpd.mutation.Where(ps...)
+ return bpd
+}
+
+// Exec executes the deletion query and returns how many vertices were deleted.
+func (bpd *BillingPlanDelete) Exec(ctx context.Context) (int, error) {
+ return withHooks(ctx, bpd.sqlExec, bpd.mutation, bpd.hooks)
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (bpd *BillingPlanDelete) ExecX(ctx context.Context) int {
+ n, err := bpd.Exec(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return n
+}
+
+func (bpd *BillingPlanDelete) sqlExec(ctx context.Context) (int, error) {
+ _spec := sqlgraph.NewDeleteSpec(billingplan.Table, sqlgraph.NewFieldSpec(billingplan.FieldID, field.TypeString))
+ if ps := bpd.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ affected, err := sqlgraph.DeleteNodes(ctx, bpd.driver, _spec)
+ if err != nil && sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ bpd.mutation.done = true
+ return affected, err
+}
+
+// BillingPlanDeleteOne is the builder for deleting a single BillingPlan entity.
+type BillingPlanDeleteOne struct {
+ bpd *BillingPlanDelete
+}
+
+// Where appends a list predicates to the BillingPlanDelete builder.
+func (bpdo *BillingPlanDeleteOne) Where(ps ...predicate.BillingPlan) *BillingPlanDeleteOne {
+ bpdo.bpd.mutation.Where(ps...)
+ return bpdo
+}
+
+// Exec executes the deletion query.
+func (bpdo *BillingPlanDeleteOne) Exec(ctx context.Context) error {
+ n, err := bpdo.bpd.Exec(ctx)
+ switch {
+ case err != nil:
+ return err
+ case n == 0:
+ return &NotFoundError{billingplan.Label}
+ default:
+ return nil
+ }
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (bpdo *BillingPlanDeleteOne) ExecX(ctx context.Context) {
+ if err := bpdo.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
diff --git a/backend/db/billingplan_query.go b/backend/db/billingplan_query.go
new file mode 100644
index 0000000..78c6b98
--- /dev/null
+++ b/backend/db/billingplan_query.go
@@ -0,0 +1,577 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "fmt"
+ "math"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect"
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/billingplan"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+)
+
+// BillingPlanQuery is the builder for querying BillingPlan entities.
+type BillingPlanQuery struct {
+ config
+ ctx *QueryContext
+ order []billingplan.OrderOption
+ inters []Interceptor
+ predicates []predicate.BillingPlan
+ modifiers []func(*sql.Selector)
+ // intermediate query (i.e. traversal path).
+ sql *sql.Selector
+ path func(context.Context) (*sql.Selector, error)
+}
+
+// Where adds a new predicate for the BillingPlanQuery builder.
+func (bpq *BillingPlanQuery) Where(ps ...predicate.BillingPlan) *BillingPlanQuery {
+ bpq.predicates = append(bpq.predicates, ps...)
+ return bpq
+}
+
+// Limit the number of records to be returned by this query.
+func (bpq *BillingPlanQuery) Limit(limit int) *BillingPlanQuery {
+ bpq.ctx.Limit = &limit
+ return bpq
+}
+
+// Offset to start from.
+func (bpq *BillingPlanQuery) Offset(offset int) *BillingPlanQuery {
+ bpq.ctx.Offset = &offset
+ return bpq
+}
+
+// Unique configures the query builder to filter duplicate records on query.
+// By default, unique is set to true, and can be disabled using this method.
+func (bpq *BillingPlanQuery) Unique(unique bool) *BillingPlanQuery {
+ bpq.ctx.Unique = &unique
+ return bpq
+}
+
+// Order specifies how the records should be ordered.
+func (bpq *BillingPlanQuery) Order(o ...billingplan.OrderOption) *BillingPlanQuery {
+ bpq.order = append(bpq.order, o...)
+ return bpq
+}
+
+// First returns the first BillingPlan entity from the query.
+// Returns a *NotFoundError when no BillingPlan was found.
+func (bpq *BillingPlanQuery) First(ctx context.Context) (*BillingPlan, error) {
+ nodes, err := bpq.Limit(1).All(setContextOp(ctx, bpq.ctx, ent.OpQueryFirst))
+ if err != nil {
+ return nil, err
+ }
+ if len(nodes) == 0 {
+ return nil, &NotFoundError{billingplan.Label}
+ }
+ return nodes[0], nil
+}
+
+// FirstX is like First, but panics if an error occurs.
+func (bpq *BillingPlanQuery) FirstX(ctx context.Context) *BillingPlan {
+ node, err := bpq.First(ctx)
+ if err != nil && !IsNotFound(err) {
+ panic(err)
+ }
+ return node
+}
+
+// FirstID returns the first BillingPlan ID from the query.
+// Returns a *NotFoundError when no BillingPlan ID was found.
+func (bpq *BillingPlanQuery) FirstID(ctx context.Context) (id string, err error) {
+ var ids []string
+ if ids, err = bpq.Limit(1).IDs(setContextOp(ctx, bpq.ctx, ent.OpQueryFirstID)); err != nil {
+ return
+ }
+ if len(ids) == 0 {
+ err = &NotFoundError{billingplan.Label}
+ return
+ }
+ return ids[0], nil
+}
+
+// FirstIDX is like FirstID, but panics if an error occurs.
+func (bpq *BillingPlanQuery) FirstIDX(ctx context.Context) string {
+ id, err := bpq.FirstID(ctx)
+ if err != nil && !IsNotFound(err) {
+ panic(err)
+ }
+ return id
+}
+
+// Only returns a single BillingPlan entity found by the query, ensuring it only returns one.
+// Returns a *NotSingularError when more than one BillingPlan entity is found.
+// Returns a *NotFoundError when no BillingPlan entities are found.
+func (bpq *BillingPlanQuery) Only(ctx context.Context) (*BillingPlan, error) {
+ nodes, err := bpq.Limit(2).All(setContextOp(ctx, bpq.ctx, ent.OpQueryOnly))
+ if err != nil {
+ return nil, err
+ }
+ switch len(nodes) {
+ case 1:
+ return nodes[0], nil
+ case 0:
+ return nil, &NotFoundError{billingplan.Label}
+ default:
+ return nil, &NotSingularError{billingplan.Label}
+ }
+}
+
+// OnlyX is like Only, but panics if an error occurs.
+func (bpq *BillingPlanQuery) OnlyX(ctx context.Context) *BillingPlan {
+ node, err := bpq.Only(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return node
+}
+
+// OnlyID is like Only, but returns the only BillingPlan ID in the query.
+// Returns a *NotSingularError when more than one BillingPlan ID is found.
+// Returns a *NotFoundError when no entities are found.
+func (bpq *BillingPlanQuery) OnlyID(ctx context.Context) (id string, err error) {
+ var ids []string
+ if ids, err = bpq.Limit(2).IDs(setContextOp(ctx, bpq.ctx, ent.OpQueryOnlyID)); err != nil {
+ return
+ }
+ switch len(ids) {
+ case 1:
+ id = ids[0]
+ case 0:
+ err = &NotFoundError{billingplan.Label}
+ default:
+ err = &NotSingularError{billingplan.Label}
+ }
+ return
+}
+
+// OnlyIDX is like OnlyID, but panics if an error occurs.
+func (bpq *BillingPlanQuery) OnlyIDX(ctx context.Context) string {
+ id, err := bpq.OnlyID(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return id
+}
+
+// All executes the query and returns a list of BillingPlans.
+func (bpq *BillingPlanQuery) All(ctx context.Context) ([]*BillingPlan, error) {
+ ctx = setContextOp(ctx, bpq.ctx, ent.OpQueryAll)
+ if err := bpq.prepareQuery(ctx); err != nil {
+ return nil, err
+ }
+ qr := querierAll[[]*BillingPlan, *BillingPlanQuery]()
+ return withInterceptors[[]*BillingPlan](ctx, bpq, qr, bpq.inters)
+}
+
+// AllX is like All, but panics if an error occurs.
+func (bpq *BillingPlanQuery) AllX(ctx context.Context) []*BillingPlan {
+ nodes, err := bpq.All(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return nodes
+}
+
+// IDs executes the query and returns a list of BillingPlan IDs.
+func (bpq *BillingPlanQuery) IDs(ctx context.Context) (ids []string, err error) {
+ if bpq.ctx.Unique == nil && bpq.path != nil {
+ bpq.Unique(true)
+ }
+ ctx = setContextOp(ctx, bpq.ctx, ent.OpQueryIDs)
+ if err = bpq.Select(billingplan.FieldID).Scan(ctx, &ids); err != nil {
+ return nil, err
+ }
+ return ids, nil
+}
+
+// IDsX is like IDs, but panics if an error occurs.
+func (bpq *BillingPlanQuery) IDsX(ctx context.Context) []string {
+ ids, err := bpq.IDs(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return ids
+}
+
+// Count returns the count of the given query.
+func (bpq *BillingPlanQuery) Count(ctx context.Context) (int, error) {
+ ctx = setContextOp(ctx, bpq.ctx, ent.OpQueryCount)
+ if err := bpq.prepareQuery(ctx); err != nil {
+ return 0, err
+ }
+ return withInterceptors[int](ctx, bpq, querierCount[*BillingPlanQuery](), bpq.inters)
+}
+
+// CountX is like Count, but panics if an error occurs.
+func (bpq *BillingPlanQuery) CountX(ctx context.Context) int {
+ count, err := bpq.Count(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return count
+}
+
+// Exist returns true if the query has elements in the graph.
+func (bpq *BillingPlanQuery) Exist(ctx context.Context) (bool, error) {
+ ctx = setContextOp(ctx, bpq.ctx, ent.OpQueryExist)
+ switch _, err := bpq.FirstID(ctx); {
+ case IsNotFound(err):
+ return false, nil
+ case err != nil:
+ return false, fmt.Errorf("db: check existence: %w", err)
+ default:
+ return true, nil
+ }
+}
+
+// ExistX is like Exist, but panics if an error occurs.
+func (bpq *BillingPlanQuery) ExistX(ctx context.Context) bool {
+ exist, err := bpq.Exist(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return exist
+}
+
+// Clone returns a duplicate of the BillingPlanQuery builder, including all associated steps. It can be
+// used to prepare common query builders and use them differently after the clone is made.
+func (bpq *BillingPlanQuery) Clone() *BillingPlanQuery {
+ if bpq == nil {
+ return nil
+ }
+ return &BillingPlanQuery{
+ config: bpq.config,
+ ctx: bpq.ctx.Clone(),
+ order: append([]billingplan.OrderOption{}, bpq.order...),
+ inters: append([]Interceptor{}, bpq.inters...),
+ predicates: append([]predicate.BillingPlan{}, bpq.predicates...),
+ // clone intermediate query.
+ sql: bpq.sql.Clone(),
+ path: bpq.path,
+ modifiers: append([]func(*sql.Selector){}, bpq.modifiers...),
+ }
+}
+
+// GroupBy is used to group vertices by one or more fields/columns.
+// It is often used with aggregate functions, like: count, max, mean, min, sum.
+//
+// Example:
+//
+// var v []struct {
+// Name string `json:"name,omitempty"`
+// Count int `json:"count,omitempty"`
+// }
+//
+// client.BillingPlan.Query().
+// GroupBy(billingplan.FieldName).
+// Aggregate(db.Count()).
+// Scan(ctx, &v)
+func (bpq *BillingPlanQuery) GroupBy(field string, fields ...string) *BillingPlanGroupBy {
+ bpq.ctx.Fields = append([]string{field}, fields...)
+ grbuild := &BillingPlanGroupBy{build: bpq}
+ grbuild.flds = &bpq.ctx.Fields
+ grbuild.label = billingplan.Label
+ grbuild.scan = grbuild.Scan
+ return grbuild
+}
+
+// Select allows the selection one or more fields/columns for the given query,
+// instead of selecting all fields in the entity.
+//
+// Example:
+//
+// var v []struct {
+// Name string `json:"name,omitempty"`
+// }
+//
+// client.BillingPlan.Query().
+// Select(billingplan.FieldName).
+// Scan(ctx, &v)
+func (bpq *BillingPlanQuery) Select(fields ...string) *BillingPlanSelect {
+ bpq.ctx.Fields = append(bpq.ctx.Fields, fields...)
+ sbuild := &BillingPlanSelect{BillingPlanQuery: bpq}
+ sbuild.label = billingplan.Label
+ sbuild.flds, sbuild.scan = &bpq.ctx.Fields, sbuild.Scan
+ return sbuild
+}
+
+// Aggregate returns a BillingPlanSelect configured with the given aggregations.
+func (bpq *BillingPlanQuery) Aggregate(fns ...AggregateFunc) *BillingPlanSelect {
+ return bpq.Select().Aggregate(fns...)
+}
+
+func (bpq *BillingPlanQuery) prepareQuery(ctx context.Context) error {
+ for _, inter := range bpq.inters {
+ if inter == nil {
+ return fmt.Errorf("db: uninitialized interceptor (forgotten import db/runtime?)")
+ }
+ if trv, ok := inter.(Traverser); ok {
+ if err := trv.Traverse(ctx, bpq); err != nil {
+ return err
+ }
+ }
+ }
+ for _, f := range bpq.ctx.Fields {
+ if !billingplan.ValidColumn(f) {
+ return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
+ }
+ }
+ if bpq.path != nil {
+ prev, err := bpq.path(ctx)
+ if err != nil {
+ return err
+ }
+ bpq.sql = prev
+ }
+ return nil
+}
+
+func (bpq *BillingPlanQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*BillingPlan, error) {
+ var (
+ nodes = []*BillingPlan{}
+ _spec = bpq.querySpec()
+ )
+ _spec.ScanValues = func(columns []string) ([]any, error) {
+ return (*BillingPlan).scanValues(nil, columns)
+ }
+ _spec.Assign = func(columns []string, values []any) error {
+ node := &BillingPlan{config: bpq.config}
+ nodes = append(nodes, node)
+ return node.assignValues(columns, values)
+ }
+ if len(bpq.modifiers) > 0 {
+ _spec.Modifiers = bpq.modifiers
+ }
+ for i := range hooks {
+ hooks[i](ctx, _spec)
+ }
+ if err := sqlgraph.QueryNodes(ctx, bpq.driver, _spec); err != nil {
+ return nil, err
+ }
+ if len(nodes) == 0 {
+ return nodes, nil
+ }
+ return nodes, nil
+}
+
+func (bpq *BillingPlanQuery) sqlCount(ctx context.Context) (int, error) {
+ _spec := bpq.querySpec()
+ if len(bpq.modifiers) > 0 {
+ _spec.Modifiers = bpq.modifiers
+ }
+ _spec.Node.Columns = bpq.ctx.Fields
+ if len(bpq.ctx.Fields) > 0 {
+ _spec.Unique = bpq.ctx.Unique != nil && *bpq.ctx.Unique
+ }
+ return sqlgraph.CountNodes(ctx, bpq.driver, _spec)
+}
+
+func (bpq *BillingPlanQuery) querySpec() *sqlgraph.QuerySpec {
+ _spec := sqlgraph.NewQuerySpec(billingplan.Table, billingplan.Columns, sqlgraph.NewFieldSpec(billingplan.FieldID, field.TypeString))
+ _spec.From = bpq.sql
+ if unique := bpq.ctx.Unique; unique != nil {
+ _spec.Unique = *unique
+ } else if bpq.path != nil {
+ _spec.Unique = true
+ }
+ if fields := bpq.ctx.Fields; len(fields) > 0 {
+ _spec.Node.Columns = make([]string, 0, len(fields))
+ _spec.Node.Columns = append(_spec.Node.Columns, billingplan.FieldID)
+ for i := range fields {
+ if fields[i] != billingplan.FieldID {
+ _spec.Node.Columns = append(_spec.Node.Columns, fields[i])
+ }
+ }
+ }
+ if ps := bpq.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if limit := bpq.ctx.Limit; limit != nil {
+ _spec.Limit = *limit
+ }
+ if offset := bpq.ctx.Offset; offset != nil {
+ _spec.Offset = *offset
+ }
+ if ps := bpq.order; len(ps) > 0 {
+ _spec.Order = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ return _spec
+}
+
+func (bpq *BillingPlanQuery) sqlQuery(ctx context.Context) *sql.Selector {
+ builder := sql.Dialect(bpq.driver.Dialect())
+ t1 := builder.Table(billingplan.Table)
+ columns := bpq.ctx.Fields
+ if len(columns) == 0 {
+ columns = billingplan.Columns
+ }
+ selector := builder.Select(t1.Columns(columns...)...).From(t1)
+ if bpq.sql != nil {
+ selector = bpq.sql
+ selector.Select(selector.Columns(columns...)...)
+ }
+ if bpq.ctx.Unique != nil && *bpq.ctx.Unique {
+ selector.Distinct()
+ }
+ for _, m := range bpq.modifiers {
+ m(selector)
+ }
+ for _, p := range bpq.predicates {
+ p(selector)
+ }
+ for _, p := range bpq.order {
+ p(selector)
+ }
+ if offset := bpq.ctx.Offset; offset != nil {
+ // limit is mandatory for offset clause. We start
+ // with default value, and override it below if needed.
+ selector.Offset(*offset).Limit(math.MaxInt32)
+ }
+ if limit := bpq.ctx.Limit; limit != nil {
+ selector.Limit(*limit)
+ }
+ return selector
+}
+
+// ForUpdate locks the selected rows against concurrent updates, and prevent them from being
+// updated, deleted or "selected ... for update" by other sessions, until the transaction is
+// either committed or rolled-back.
+func (bpq *BillingPlanQuery) ForUpdate(opts ...sql.LockOption) *BillingPlanQuery {
+ if bpq.driver.Dialect() == dialect.Postgres {
+ bpq.Unique(false)
+ }
+ bpq.modifiers = append(bpq.modifiers, func(s *sql.Selector) {
+ s.ForUpdate(opts...)
+ })
+ return bpq
+}
+
+// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock
+// on any rows that are read. Other sessions can read the rows, but cannot modify them
+// until your transaction commits.
+func (bpq *BillingPlanQuery) ForShare(opts ...sql.LockOption) *BillingPlanQuery {
+ if bpq.driver.Dialect() == dialect.Postgres {
+ bpq.Unique(false)
+ }
+ bpq.modifiers = append(bpq.modifiers, func(s *sql.Selector) {
+ s.ForShare(opts...)
+ })
+ return bpq
+}
+
+// Modify adds a query modifier for attaching custom logic to queries.
+func (bpq *BillingPlanQuery) Modify(modifiers ...func(s *sql.Selector)) *BillingPlanSelect {
+ bpq.modifiers = append(bpq.modifiers, modifiers...)
+ return bpq.Select()
+}
+
+// BillingPlanGroupBy is the group-by builder for BillingPlan entities.
+type BillingPlanGroupBy struct {
+ selector
+ build *BillingPlanQuery
+}
+
+// Aggregate adds the given aggregation functions to the group-by query.
+func (bpgb *BillingPlanGroupBy) Aggregate(fns ...AggregateFunc) *BillingPlanGroupBy {
+ bpgb.fns = append(bpgb.fns, fns...)
+ return bpgb
+}
+
+// Scan applies the selector query and scans the result into the given value.
+func (bpgb *BillingPlanGroupBy) Scan(ctx context.Context, v any) error {
+ ctx = setContextOp(ctx, bpgb.build.ctx, ent.OpQueryGroupBy)
+ if err := bpgb.build.prepareQuery(ctx); err != nil {
+ return err
+ }
+ return scanWithInterceptors[*BillingPlanQuery, *BillingPlanGroupBy](ctx, bpgb.build, bpgb, bpgb.build.inters, v)
+}
+
+func (bpgb *BillingPlanGroupBy) sqlScan(ctx context.Context, root *BillingPlanQuery, v any) error {
+ selector := root.sqlQuery(ctx).Select()
+ aggregation := make([]string, 0, len(bpgb.fns))
+ for _, fn := range bpgb.fns {
+ aggregation = append(aggregation, fn(selector))
+ }
+ if len(selector.SelectedColumns()) == 0 {
+ columns := make([]string, 0, len(*bpgb.flds)+len(bpgb.fns))
+ for _, f := range *bpgb.flds {
+ columns = append(columns, selector.C(f))
+ }
+ columns = append(columns, aggregation...)
+ selector.Select(columns...)
+ }
+ selector.GroupBy(selector.Columns(*bpgb.flds...)...)
+ if err := selector.Err(); err != nil {
+ return err
+ }
+ rows := &sql.Rows{}
+ query, args := selector.Query()
+ if err := bpgb.build.driver.Query(ctx, query, args, rows); err != nil {
+ return err
+ }
+ defer rows.Close()
+ return sql.ScanSlice(rows, v)
+}
+
+// BillingPlanSelect is the builder for selecting fields of BillingPlan entities.
+type BillingPlanSelect struct {
+ *BillingPlanQuery
+ selector
+}
+
+// Aggregate adds the given aggregation functions to the selector query.
+func (bps *BillingPlanSelect) Aggregate(fns ...AggregateFunc) *BillingPlanSelect {
+ bps.fns = append(bps.fns, fns...)
+ return bps
+}
+
+// Scan applies the selector query and scans the result into the given value.
+func (bps *BillingPlanSelect) Scan(ctx context.Context, v any) error {
+ ctx = setContextOp(ctx, bps.ctx, ent.OpQuerySelect)
+ if err := bps.prepareQuery(ctx); err != nil {
+ return err
+ }
+ return scanWithInterceptors[*BillingPlanQuery, *BillingPlanSelect](ctx, bps.BillingPlanQuery, bps, bps.inters, v)
+}
+
+func (bps *BillingPlanSelect) sqlScan(ctx context.Context, root *BillingPlanQuery, v any) error {
+ selector := root.sqlQuery(ctx)
+ aggregation := make([]string, 0, len(bps.fns))
+ for _, fn := range bps.fns {
+ aggregation = append(aggregation, fn(selector))
+ }
+ switch n := len(*bps.selector.flds); {
+ case n == 0 && len(aggregation) > 0:
+ selector.Select(aggregation...)
+ case n != 0 && len(aggregation) > 0:
+ selector.AppendSelect(aggregation...)
+ }
+ rows := &sql.Rows{}
+ query, args := selector.Query()
+ if err := bps.driver.Query(ctx, query, args, rows); err != nil {
+ return err
+ }
+ defer rows.Close()
+ return sql.ScanSlice(rows, v)
+}
+
+// Modify adds a query modifier for attaching custom logic to queries.
+func (bps *BillingPlanSelect) Modify(modifiers ...func(s *sql.Selector)) *BillingPlanSelect {
+ bps.modifiers = append(bps.modifiers, modifiers...)
+ return bps
+}
diff --git a/backend/db/billingplan_update.go b/backend/db/billingplan_update.go
new file mode 100644
index 0000000..c06bfbc
--- /dev/null
+++ b/backend/db/billingplan_update.go
@@ -0,0 +1,348 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "time"
+
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/billingplan"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+)
+
+// BillingPlanUpdate is the builder for updating BillingPlan entities.
+type BillingPlanUpdate struct {
+ config
+ hooks []Hook
+ mutation *BillingPlanMutation
+ modifiers []func(*sql.UpdateBuilder)
+}
+
+// Where appends a list predicates to the BillingPlanUpdate builder.
+func (bpu *BillingPlanUpdate) Where(ps ...predicate.BillingPlan) *BillingPlanUpdate {
+ bpu.mutation.Where(ps...)
+ return bpu
+}
+
+// SetName sets the "name" field.
+func (bpu *BillingPlanUpdate) SetName(s string) *BillingPlanUpdate {
+ bpu.mutation.SetName(s)
+ return bpu
+}
+
+// SetNillableName sets the "name" field if the given value is not nil.
+func (bpu *BillingPlanUpdate) SetNillableName(s *string) *BillingPlanUpdate {
+ if s != nil {
+ bpu.SetName(*s)
+ }
+ return bpu
+}
+
+// SetDescription sets the "description" field.
+func (bpu *BillingPlanUpdate) SetDescription(s string) *BillingPlanUpdate {
+ bpu.mutation.SetDescription(s)
+ return bpu
+}
+
+// SetNillableDescription sets the "description" field if the given value is not nil.
+func (bpu *BillingPlanUpdate) SetNillableDescription(s *string) *BillingPlanUpdate {
+ if s != nil {
+ bpu.SetDescription(*s)
+ }
+ return bpu
+}
+
+// SetRules sets the "rules" field.
+func (bpu *BillingPlanUpdate) SetRules(m map[string]interface{}) *BillingPlanUpdate {
+ bpu.mutation.SetRules(m)
+ return bpu
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (bpu *BillingPlanUpdate) SetCreatedAt(t time.Time) *BillingPlanUpdate {
+ bpu.mutation.SetCreatedAt(t)
+ return bpu
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (bpu *BillingPlanUpdate) SetNillableCreatedAt(t *time.Time) *BillingPlanUpdate {
+ if t != nil {
+ bpu.SetCreatedAt(*t)
+ }
+ return bpu
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (bpu *BillingPlanUpdate) SetUpdatedAt(t time.Time) *BillingPlanUpdate {
+ bpu.mutation.SetUpdatedAt(t)
+ return bpu
+}
+
+// Mutation returns the BillingPlanMutation object of the builder.
+func (bpu *BillingPlanUpdate) Mutation() *BillingPlanMutation {
+ return bpu.mutation
+}
+
+// Save executes the query and returns the number of nodes affected by the update operation.
+func (bpu *BillingPlanUpdate) Save(ctx context.Context) (int, error) {
+ bpu.defaults()
+ return withHooks(ctx, bpu.sqlSave, bpu.mutation, bpu.hooks)
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (bpu *BillingPlanUpdate) SaveX(ctx context.Context) int {
+ affected, err := bpu.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return affected
+}
+
+// Exec executes the query.
+func (bpu *BillingPlanUpdate) Exec(ctx context.Context) error {
+ _, err := bpu.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (bpu *BillingPlanUpdate) ExecX(ctx context.Context) {
+ if err := bpu.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// defaults sets the default values of the builder before save.
+func (bpu *BillingPlanUpdate) defaults() {
+ if _, ok := bpu.mutation.UpdatedAt(); !ok {
+ v := billingplan.UpdateDefaultUpdatedAt()
+ bpu.mutation.SetUpdatedAt(v)
+ }
+}
+
+// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
+func (bpu *BillingPlanUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *BillingPlanUpdate {
+ bpu.modifiers = append(bpu.modifiers, modifiers...)
+ return bpu
+}
+
+func (bpu *BillingPlanUpdate) sqlSave(ctx context.Context) (n int, err error) {
+ _spec := sqlgraph.NewUpdateSpec(billingplan.Table, billingplan.Columns, sqlgraph.NewFieldSpec(billingplan.FieldID, field.TypeString))
+ if ps := bpu.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if value, ok := bpu.mutation.Name(); ok {
+ _spec.SetField(billingplan.FieldName, field.TypeString, value)
+ }
+ if value, ok := bpu.mutation.Description(); ok {
+ _spec.SetField(billingplan.FieldDescription, field.TypeString, value)
+ }
+ if value, ok := bpu.mutation.Rules(); ok {
+ _spec.SetField(billingplan.FieldRules, field.TypeJSON, value)
+ }
+ if value, ok := bpu.mutation.CreatedAt(); ok {
+ _spec.SetField(billingplan.FieldCreatedAt, field.TypeTime, value)
+ }
+ if value, ok := bpu.mutation.UpdatedAt(); ok {
+ _spec.SetField(billingplan.FieldUpdatedAt, field.TypeTime, value)
+ }
+ _spec.AddModifiers(bpu.modifiers...)
+ if n, err = sqlgraph.UpdateNodes(ctx, bpu.driver, _spec); err != nil {
+ if _, ok := err.(*sqlgraph.NotFoundError); ok {
+ err = &NotFoundError{billingplan.Label}
+ } else if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return 0, err
+ }
+ bpu.mutation.done = true
+ return n, nil
+}
+
+// BillingPlanUpdateOne is the builder for updating a single BillingPlan entity.
+type BillingPlanUpdateOne struct {
+ config
+ fields []string
+ hooks []Hook
+ mutation *BillingPlanMutation
+ modifiers []func(*sql.UpdateBuilder)
+}
+
+// SetName sets the "name" field.
+func (bpuo *BillingPlanUpdateOne) SetName(s string) *BillingPlanUpdateOne {
+ bpuo.mutation.SetName(s)
+ return bpuo
+}
+
+// SetNillableName sets the "name" field if the given value is not nil.
+func (bpuo *BillingPlanUpdateOne) SetNillableName(s *string) *BillingPlanUpdateOne {
+ if s != nil {
+ bpuo.SetName(*s)
+ }
+ return bpuo
+}
+
+// SetDescription sets the "description" field.
+func (bpuo *BillingPlanUpdateOne) SetDescription(s string) *BillingPlanUpdateOne {
+ bpuo.mutation.SetDescription(s)
+ return bpuo
+}
+
+// SetNillableDescription sets the "description" field if the given value is not nil.
+func (bpuo *BillingPlanUpdateOne) SetNillableDescription(s *string) *BillingPlanUpdateOne {
+ if s != nil {
+ bpuo.SetDescription(*s)
+ }
+ return bpuo
+}
+
+// SetRules sets the "rules" field.
+func (bpuo *BillingPlanUpdateOne) SetRules(m map[string]interface{}) *BillingPlanUpdateOne {
+ bpuo.mutation.SetRules(m)
+ return bpuo
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (bpuo *BillingPlanUpdateOne) SetCreatedAt(t time.Time) *BillingPlanUpdateOne {
+ bpuo.mutation.SetCreatedAt(t)
+ return bpuo
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (bpuo *BillingPlanUpdateOne) SetNillableCreatedAt(t *time.Time) *BillingPlanUpdateOne {
+ if t != nil {
+ bpuo.SetCreatedAt(*t)
+ }
+ return bpuo
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (bpuo *BillingPlanUpdateOne) SetUpdatedAt(t time.Time) *BillingPlanUpdateOne {
+ bpuo.mutation.SetUpdatedAt(t)
+ return bpuo
+}
+
+// Mutation returns the BillingPlanMutation object of the builder.
+func (bpuo *BillingPlanUpdateOne) Mutation() *BillingPlanMutation {
+ return bpuo.mutation
+}
+
+// Where appends a list predicates to the BillingPlanUpdate builder.
+func (bpuo *BillingPlanUpdateOne) Where(ps ...predicate.BillingPlan) *BillingPlanUpdateOne {
+ bpuo.mutation.Where(ps...)
+ return bpuo
+}
+
+// Select allows selecting one or more fields (columns) of the returned entity.
+// The default is selecting all fields defined in the entity schema.
+func (bpuo *BillingPlanUpdateOne) Select(field string, fields ...string) *BillingPlanUpdateOne {
+ bpuo.fields = append([]string{field}, fields...)
+ return bpuo
+}
+
+// Save executes the query and returns the updated BillingPlan entity.
+func (bpuo *BillingPlanUpdateOne) Save(ctx context.Context) (*BillingPlan, error) {
+ bpuo.defaults()
+ return withHooks(ctx, bpuo.sqlSave, bpuo.mutation, bpuo.hooks)
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (bpuo *BillingPlanUpdateOne) SaveX(ctx context.Context) *BillingPlan {
+ node, err := bpuo.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return node
+}
+
+// Exec executes the query on the entity.
+func (bpuo *BillingPlanUpdateOne) Exec(ctx context.Context) error {
+ _, err := bpuo.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (bpuo *BillingPlanUpdateOne) ExecX(ctx context.Context) {
+ if err := bpuo.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// defaults sets the default values of the builder before save.
+func (bpuo *BillingPlanUpdateOne) defaults() {
+ if _, ok := bpuo.mutation.UpdatedAt(); !ok {
+ v := billingplan.UpdateDefaultUpdatedAt()
+ bpuo.mutation.SetUpdatedAt(v)
+ }
+}
+
+// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
+func (bpuo *BillingPlanUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *BillingPlanUpdateOne {
+ bpuo.modifiers = append(bpuo.modifiers, modifiers...)
+ return bpuo
+}
+
+func (bpuo *BillingPlanUpdateOne) sqlSave(ctx context.Context) (_node *BillingPlan, err error) {
+ _spec := sqlgraph.NewUpdateSpec(billingplan.Table, billingplan.Columns, sqlgraph.NewFieldSpec(billingplan.FieldID, field.TypeString))
+ id, ok := bpuo.mutation.ID()
+ if !ok {
+ return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "BillingPlan.id" for update`)}
+ }
+ _spec.Node.ID.Value = id
+ if fields := bpuo.fields; len(fields) > 0 {
+ _spec.Node.Columns = make([]string, 0, len(fields))
+ _spec.Node.Columns = append(_spec.Node.Columns, billingplan.FieldID)
+ for _, f := range fields {
+ if !billingplan.ValidColumn(f) {
+ return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
+ }
+ if f != billingplan.FieldID {
+ _spec.Node.Columns = append(_spec.Node.Columns, f)
+ }
+ }
+ }
+ if ps := bpuo.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if value, ok := bpuo.mutation.Name(); ok {
+ _spec.SetField(billingplan.FieldName, field.TypeString, value)
+ }
+ if value, ok := bpuo.mutation.Description(); ok {
+ _spec.SetField(billingplan.FieldDescription, field.TypeString, value)
+ }
+ if value, ok := bpuo.mutation.Rules(); ok {
+ _spec.SetField(billingplan.FieldRules, field.TypeJSON, value)
+ }
+ if value, ok := bpuo.mutation.CreatedAt(); ok {
+ _spec.SetField(billingplan.FieldCreatedAt, field.TypeTime, value)
+ }
+ if value, ok := bpuo.mutation.UpdatedAt(); ok {
+ _spec.SetField(billingplan.FieldUpdatedAt, field.TypeTime, value)
+ }
+ _spec.AddModifiers(bpuo.modifiers...)
+ _node = &BillingPlan{config: bpuo.config}
+ _spec.Assign = _node.assignValues
+ _spec.ScanValues = _node.scanValues
+ if err = sqlgraph.UpdateNode(ctx, bpuo.driver, _spec); err != nil {
+ if _, ok := err.(*sqlgraph.NotFoundError); ok {
+ err = &NotFoundError{billingplan.Label}
+ } else if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return nil, err
+ }
+ bpuo.mutation.done = true
+ return _node, nil
+}
diff --git a/backend/db/billingquota.go b/backend/db/billingquota.go
new file mode 100644
index 0000000..00e1fb6
--- /dev/null
+++ b/backend/db/billingquota.go
@@ -0,0 +1,172 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "fmt"
+ "strings"
+ "time"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect/sql"
+ "github.com/chaitin/MonkeyCode/backend/db/billingquota"
+)
+
+// BillingQuota is the model entity for the BillingQuota schema.
+type BillingQuota struct {
+ config `json:"-"`
+ // ID of the ent.
+ ID string `json:"id,omitempty"`
+ // DeletedAt holds the value of the "deleted_at" field.
+ DeletedAt time.Time `json:"deleted_at,omitempty"`
+ // UserID holds the value of the "user_id" field.
+ UserID string `json:"user_id,omitempty"`
+ // Total holds the value of the "total" field.
+ Total int64 `json:"total,omitempty"`
+ // Used holds the value of the "used" field.
+ Used int64 `json:"used,omitempty"`
+ // Remain holds the value of the "remain" field.
+ Remain int64 `json:"remain,omitempty"`
+ // CreatedAt holds the value of the "created_at" field.
+ CreatedAt time.Time `json:"created_at,omitempty"`
+ // UpdatedAt holds the value of the "updated_at" field.
+ UpdatedAt time.Time `json:"updated_at,omitempty"`
+ selectValues sql.SelectValues
+}
+
+// scanValues returns the types for scanning values from sql.Rows.
+func (*BillingQuota) scanValues(columns []string) ([]any, error) {
+ values := make([]any, len(columns))
+ for i := range columns {
+ switch columns[i] {
+ case billingquota.FieldTotal, billingquota.FieldUsed, billingquota.FieldRemain:
+ values[i] = new(sql.NullInt64)
+ case billingquota.FieldID, billingquota.FieldUserID:
+ values[i] = new(sql.NullString)
+ case billingquota.FieldDeletedAt, billingquota.FieldCreatedAt, billingquota.FieldUpdatedAt:
+ values[i] = new(sql.NullTime)
+ default:
+ values[i] = new(sql.UnknownType)
+ }
+ }
+ return values, nil
+}
+
+// assignValues assigns the values that were returned from sql.Rows (after scanning)
+// to the BillingQuota fields.
+func (bq *BillingQuota) assignValues(columns []string, values []any) error {
+ if m, n := len(values), len(columns); m < n {
+ return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
+ }
+ for i := range columns {
+ switch columns[i] {
+ case billingquota.FieldID:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field id", values[i])
+ } else if value.Valid {
+ bq.ID = value.String
+ }
+ case billingquota.FieldDeletedAt:
+ if value, ok := values[i].(*sql.NullTime); !ok {
+ return fmt.Errorf("unexpected type %T for field deleted_at", values[i])
+ } else if value.Valid {
+ bq.DeletedAt = value.Time
+ }
+ case billingquota.FieldUserID:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field user_id", values[i])
+ } else if value.Valid {
+ bq.UserID = value.String
+ }
+ case billingquota.FieldTotal:
+ if value, ok := values[i].(*sql.NullInt64); !ok {
+ return fmt.Errorf("unexpected type %T for field total", values[i])
+ } else if value.Valid {
+ bq.Total = value.Int64
+ }
+ case billingquota.FieldUsed:
+ if value, ok := values[i].(*sql.NullInt64); !ok {
+ return fmt.Errorf("unexpected type %T for field used", values[i])
+ } else if value.Valid {
+ bq.Used = value.Int64
+ }
+ case billingquota.FieldRemain:
+ if value, ok := values[i].(*sql.NullInt64); !ok {
+ return fmt.Errorf("unexpected type %T for field remain", values[i])
+ } else if value.Valid {
+ bq.Remain = value.Int64
+ }
+ case billingquota.FieldCreatedAt:
+ if value, ok := values[i].(*sql.NullTime); !ok {
+ return fmt.Errorf("unexpected type %T for field created_at", values[i])
+ } else if value.Valid {
+ bq.CreatedAt = value.Time
+ }
+ case billingquota.FieldUpdatedAt:
+ if value, ok := values[i].(*sql.NullTime); !ok {
+ return fmt.Errorf("unexpected type %T for field updated_at", values[i])
+ } else if value.Valid {
+ bq.UpdatedAt = value.Time
+ }
+ default:
+ bq.selectValues.Set(columns[i], values[i])
+ }
+ }
+ return nil
+}
+
+// Value returns the ent.Value that was dynamically selected and assigned to the BillingQuota.
+// This includes values selected through modifiers, order, etc.
+func (bq *BillingQuota) Value(name string) (ent.Value, error) {
+ return bq.selectValues.Get(name)
+}
+
+// Update returns a builder for updating this BillingQuota.
+// Note that you need to call BillingQuota.Unwrap() before calling this method if this BillingQuota
+// was returned from a transaction, and the transaction was committed or rolled back.
+func (bq *BillingQuota) Update() *BillingQuotaUpdateOne {
+ return NewBillingQuotaClient(bq.config).UpdateOne(bq)
+}
+
+// Unwrap unwraps the BillingQuota entity that was returned from a transaction after it was closed,
+// so that all future queries will be executed through the driver which created the transaction.
+func (bq *BillingQuota) Unwrap() *BillingQuota {
+ _tx, ok := bq.config.driver.(*txDriver)
+ if !ok {
+ panic("db: BillingQuota is not a transactional entity")
+ }
+ bq.config.driver = _tx.drv
+ return bq
+}
+
+// String implements the fmt.Stringer.
+func (bq *BillingQuota) String() string {
+ var builder strings.Builder
+ builder.WriteString("BillingQuota(")
+ builder.WriteString(fmt.Sprintf("id=%v, ", bq.ID))
+ builder.WriteString("deleted_at=")
+ builder.WriteString(bq.DeletedAt.Format(time.ANSIC))
+ builder.WriteString(", ")
+ builder.WriteString("user_id=")
+ builder.WriteString(bq.UserID)
+ builder.WriteString(", ")
+ builder.WriteString("total=")
+ builder.WriteString(fmt.Sprintf("%v", bq.Total))
+ builder.WriteString(", ")
+ builder.WriteString("used=")
+ builder.WriteString(fmt.Sprintf("%v", bq.Used))
+ builder.WriteString(", ")
+ builder.WriteString("remain=")
+ builder.WriteString(fmt.Sprintf("%v", bq.Remain))
+ builder.WriteString(", ")
+ builder.WriteString("created_at=")
+ builder.WriteString(bq.CreatedAt.Format(time.ANSIC))
+ builder.WriteString(", ")
+ builder.WriteString("updated_at=")
+ builder.WriteString(bq.UpdatedAt.Format(time.ANSIC))
+ builder.WriteByte(')')
+ return builder.String()
+}
+
+// BillingQuotaSlice is a parsable slice of BillingQuota.
+type BillingQuotaSlice []*BillingQuota
diff --git a/backend/db/billingquota/billingquota.go b/backend/db/billingquota/billingquota.go
new file mode 100644
index 0000000..8b065eb
--- /dev/null
+++ b/backend/db/billingquota/billingquota.go
@@ -0,0 +1,114 @@
+// Code generated by ent, DO NOT EDIT.
+
+package billingquota
+
+import (
+ "time"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect/sql"
+)
+
+const (
+ // Label holds the string label denoting the billingquota type in the database.
+ Label = "billing_quota"
+ // FieldID holds the string denoting the id field in the database.
+ FieldID = "id"
+ // FieldDeletedAt holds the string denoting the deleted_at field in the database.
+ FieldDeletedAt = "deleted_at"
+ // FieldUserID holds the string denoting the user_id field in the database.
+ FieldUserID = "user_id"
+ // FieldTotal holds the string denoting the total field in the database.
+ FieldTotal = "total"
+ // FieldUsed holds the string denoting the used field in the database.
+ FieldUsed = "used"
+ // FieldRemain holds the string denoting the remain field in the database.
+ FieldRemain = "remain"
+ // FieldCreatedAt holds the string denoting the created_at field in the database.
+ FieldCreatedAt = "created_at"
+ // FieldUpdatedAt holds the string denoting the updated_at field in the database.
+ FieldUpdatedAt = "updated_at"
+ // Table holds the table name of the billingquota in the database.
+ Table = "billing_quotas"
+)
+
+// Columns holds all SQL columns for billingquota fields.
+var Columns = []string{
+ FieldID,
+ FieldDeletedAt,
+ FieldUserID,
+ FieldTotal,
+ FieldUsed,
+ FieldRemain,
+ FieldCreatedAt,
+ FieldUpdatedAt,
+}
+
+// ValidColumn reports if the column name is valid (part of the table columns).
+func ValidColumn(column string) bool {
+ for i := range Columns {
+ if column == Columns[i] {
+ return true
+ }
+ }
+ return false
+}
+
+// Note that the variables below are initialized by the runtime
+// package on the initialization of the application. Therefore,
+// it should be imported in the main as follows:
+//
+// import _ "github.com/chaitin/MonkeyCode/backend/db/runtime"
+var (
+ Hooks [1]ent.Hook
+ Interceptors [1]ent.Interceptor
+ // DefaultCreatedAt holds the default value on creation for the "created_at" field.
+ DefaultCreatedAt func() time.Time
+ // DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
+ DefaultUpdatedAt func() time.Time
+ // UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field.
+ UpdateDefaultUpdatedAt func() time.Time
+)
+
+// OrderOption defines the ordering options for the BillingQuota queries.
+type OrderOption func(*sql.Selector)
+
+// ByID orders the results by the id field.
+func ByID(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldID, opts...).ToFunc()
+}
+
+// ByDeletedAt orders the results by the deleted_at field.
+func ByDeletedAt(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldDeletedAt, opts...).ToFunc()
+}
+
+// ByUserID orders the results by the user_id field.
+func ByUserID(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldUserID, opts...).ToFunc()
+}
+
+// ByTotal orders the results by the total field.
+func ByTotal(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldTotal, opts...).ToFunc()
+}
+
+// ByUsed orders the results by the used field.
+func ByUsed(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldUsed, opts...).ToFunc()
+}
+
+// ByRemain orders the results by the remain field.
+func ByRemain(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldRemain, opts...).ToFunc()
+}
+
+// ByCreatedAt orders the results by the created_at field.
+func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
+}
+
+// ByUpdatedAt orders the results by the updated_at field.
+func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc()
+}
diff --git a/backend/db/billingquota/where.go b/backend/db/billingquota/where.go
new file mode 100644
index 0000000..5f67a1d
--- /dev/null
+++ b/backend/db/billingquota/where.go
@@ -0,0 +1,430 @@
+// Code generated by ent, DO NOT EDIT.
+
+package billingquota
+
+import (
+ "time"
+
+ "entgo.io/ent/dialect/sql"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+)
+
+// ID filters vertices based on their ID field.
+func ID(id string) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldEQ(FieldID, id))
+}
+
+// IDEQ applies the EQ predicate on the ID field.
+func IDEQ(id string) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldEQ(FieldID, id))
+}
+
+// IDNEQ applies the NEQ predicate on the ID field.
+func IDNEQ(id string) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldNEQ(FieldID, id))
+}
+
+// IDIn applies the In predicate on the ID field.
+func IDIn(ids ...string) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldIn(FieldID, ids...))
+}
+
+// IDNotIn applies the NotIn predicate on the ID field.
+func IDNotIn(ids ...string) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldNotIn(FieldID, ids...))
+}
+
+// IDGT applies the GT predicate on the ID field.
+func IDGT(id string) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldGT(FieldID, id))
+}
+
+// IDGTE applies the GTE predicate on the ID field.
+func IDGTE(id string) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldGTE(FieldID, id))
+}
+
+// IDLT applies the LT predicate on the ID field.
+func IDLT(id string) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldLT(FieldID, id))
+}
+
+// IDLTE applies the LTE predicate on the ID field.
+func IDLTE(id string) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldLTE(FieldID, id))
+}
+
+// IDEqualFold applies the EqualFold predicate on the ID field.
+func IDEqualFold(id string) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldEqualFold(FieldID, id))
+}
+
+// IDContainsFold applies the ContainsFold predicate on the ID field.
+func IDContainsFold(id string) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldContainsFold(FieldID, id))
+}
+
+// DeletedAt applies equality check predicate on the "deleted_at" field. It's identical to DeletedAtEQ.
+func DeletedAt(v time.Time) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldEQ(FieldDeletedAt, v))
+}
+
+// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ.
+func UserID(v string) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldEQ(FieldUserID, v))
+}
+
+// Total applies equality check predicate on the "total" field. It's identical to TotalEQ.
+func Total(v int64) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldEQ(FieldTotal, v))
+}
+
+// Used applies equality check predicate on the "used" field. It's identical to UsedEQ.
+func Used(v int64) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldEQ(FieldUsed, v))
+}
+
+// Remain applies equality check predicate on the "remain" field. It's identical to RemainEQ.
+func Remain(v int64) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldEQ(FieldRemain, v))
+}
+
+// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
+func CreatedAt(v time.Time) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldEQ(FieldCreatedAt, v))
+}
+
+// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
+func UpdatedAt(v time.Time) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldEQ(FieldUpdatedAt, v))
+}
+
+// DeletedAtEQ applies the EQ predicate on the "deleted_at" field.
+func DeletedAtEQ(v time.Time) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldEQ(FieldDeletedAt, v))
+}
+
+// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field.
+func DeletedAtNEQ(v time.Time) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldNEQ(FieldDeletedAt, v))
+}
+
+// DeletedAtIn applies the In predicate on the "deleted_at" field.
+func DeletedAtIn(vs ...time.Time) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldIn(FieldDeletedAt, vs...))
+}
+
+// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field.
+func DeletedAtNotIn(vs ...time.Time) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldNotIn(FieldDeletedAt, vs...))
+}
+
+// DeletedAtGT applies the GT predicate on the "deleted_at" field.
+func DeletedAtGT(v time.Time) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldGT(FieldDeletedAt, v))
+}
+
+// DeletedAtGTE applies the GTE predicate on the "deleted_at" field.
+func DeletedAtGTE(v time.Time) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldGTE(FieldDeletedAt, v))
+}
+
+// DeletedAtLT applies the LT predicate on the "deleted_at" field.
+func DeletedAtLT(v time.Time) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldLT(FieldDeletedAt, v))
+}
+
+// DeletedAtLTE applies the LTE predicate on the "deleted_at" field.
+func DeletedAtLTE(v time.Time) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldLTE(FieldDeletedAt, v))
+}
+
+// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field.
+func DeletedAtIsNil() predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldIsNull(FieldDeletedAt))
+}
+
+// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field.
+func DeletedAtNotNil() predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldNotNull(FieldDeletedAt))
+}
+
+// UserIDEQ applies the EQ predicate on the "user_id" field.
+func UserIDEQ(v string) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldEQ(FieldUserID, v))
+}
+
+// UserIDNEQ applies the NEQ predicate on the "user_id" field.
+func UserIDNEQ(v string) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldNEQ(FieldUserID, v))
+}
+
+// UserIDIn applies the In predicate on the "user_id" field.
+func UserIDIn(vs ...string) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldIn(FieldUserID, vs...))
+}
+
+// UserIDNotIn applies the NotIn predicate on the "user_id" field.
+func UserIDNotIn(vs ...string) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldNotIn(FieldUserID, vs...))
+}
+
+// UserIDGT applies the GT predicate on the "user_id" field.
+func UserIDGT(v string) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldGT(FieldUserID, v))
+}
+
+// UserIDGTE applies the GTE predicate on the "user_id" field.
+func UserIDGTE(v string) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldGTE(FieldUserID, v))
+}
+
+// UserIDLT applies the LT predicate on the "user_id" field.
+func UserIDLT(v string) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldLT(FieldUserID, v))
+}
+
+// UserIDLTE applies the LTE predicate on the "user_id" field.
+func UserIDLTE(v string) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldLTE(FieldUserID, v))
+}
+
+// UserIDContains applies the Contains predicate on the "user_id" field.
+func UserIDContains(v string) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldContains(FieldUserID, v))
+}
+
+// UserIDHasPrefix applies the HasPrefix predicate on the "user_id" field.
+func UserIDHasPrefix(v string) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldHasPrefix(FieldUserID, v))
+}
+
+// UserIDHasSuffix applies the HasSuffix predicate on the "user_id" field.
+func UserIDHasSuffix(v string) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldHasSuffix(FieldUserID, v))
+}
+
+// UserIDEqualFold applies the EqualFold predicate on the "user_id" field.
+func UserIDEqualFold(v string) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldEqualFold(FieldUserID, v))
+}
+
+// UserIDContainsFold applies the ContainsFold predicate on the "user_id" field.
+func UserIDContainsFold(v string) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldContainsFold(FieldUserID, v))
+}
+
+// TotalEQ applies the EQ predicate on the "total" field.
+func TotalEQ(v int64) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldEQ(FieldTotal, v))
+}
+
+// TotalNEQ applies the NEQ predicate on the "total" field.
+func TotalNEQ(v int64) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldNEQ(FieldTotal, v))
+}
+
+// TotalIn applies the In predicate on the "total" field.
+func TotalIn(vs ...int64) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldIn(FieldTotal, vs...))
+}
+
+// TotalNotIn applies the NotIn predicate on the "total" field.
+func TotalNotIn(vs ...int64) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldNotIn(FieldTotal, vs...))
+}
+
+// TotalGT applies the GT predicate on the "total" field.
+func TotalGT(v int64) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldGT(FieldTotal, v))
+}
+
+// TotalGTE applies the GTE predicate on the "total" field.
+func TotalGTE(v int64) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldGTE(FieldTotal, v))
+}
+
+// TotalLT applies the LT predicate on the "total" field.
+func TotalLT(v int64) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldLT(FieldTotal, v))
+}
+
+// TotalLTE applies the LTE predicate on the "total" field.
+func TotalLTE(v int64) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldLTE(FieldTotal, v))
+}
+
+// UsedEQ applies the EQ predicate on the "used" field.
+func UsedEQ(v int64) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldEQ(FieldUsed, v))
+}
+
+// UsedNEQ applies the NEQ predicate on the "used" field.
+func UsedNEQ(v int64) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldNEQ(FieldUsed, v))
+}
+
+// UsedIn applies the In predicate on the "used" field.
+func UsedIn(vs ...int64) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldIn(FieldUsed, vs...))
+}
+
+// UsedNotIn applies the NotIn predicate on the "used" field.
+func UsedNotIn(vs ...int64) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldNotIn(FieldUsed, vs...))
+}
+
+// UsedGT applies the GT predicate on the "used" field.
+func UsedGT(v int64) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldGT(FieldUsed, v))
+}
+
+// UsedGTE applies the GTE predicate on the "used" field.
+func UsedGTE(v int64) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldGTE(FieldUsed, v))
+}
+
+// UsedLT applies the LT predicate on the "used" field.
+func UsedLT(v int64) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldLT(FieldUsed, v))
+}
+
+// UsedLTE applies the LTE predicate on the "used" field.
+func UsedLTE(v int64) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldLTE(FieldUsed, v))
+}
+
+// RemainEQ applies the EQ predicate on the "remain" field.
+func RemainEQ(v int64) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldEQ(FieldRemain, v))
+}
+
+// RemainNEQ applies the NEQ predicate on the "remain" field.
+func RemainNEQ(v int64) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldNEQ(FieldRemain, v))
+}
+
+// RemainIn applies the In predicate on the "remain" field.
+func RemainIn(vs ...int64) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldIn(FieldRemain, vs...))
+}
+
+// RemainNotIn applies the NotIn predicate on the "remain" field.
+func RemainNotIn(vs ...int64) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldNotIn(FieldRemain, vs...))
+}
+
+// RemainGT applies the GT predicate on the "remain" field.
+func RemainGT(v int64) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldGT(FieldRemain, v))
+}
+
+// RemainGTE applies the GTE predicate on the "remain" field.
+func RemainGTE(v int64) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldGTE(FieldRemain, v))
+}
+
+// RemainLT applies the LT predicate on the "remain" field.
+func RemainLT(v int64) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldLT(FieldRemain, v))
+}
+
+// RemainLTE applies the LTE predicate on the "remain" field.
+func RemainLTE(v int64) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldLTE(FieldRemain, v))
+}
+
+// CreatedAtEQ applies the EQ predicate on the "created_at" field.
+func CreatedAtEQ(v time.Time) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldEQ(FieldCreatedAt, v))
+}
+
+// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
+func CreatedAtNEQ(v time.Time) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldNEQ(FieldCreatedAt, v))
+}
+
+// CreatedAtIn applies the In predicate on the "created_at" field.
+func CreatedAtIn(vs ...time.Time) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldIn(FieldCreatedAt, vs...))
+}
+
+// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
+func CreatedAtNotIn(vs ...time.Time) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldNotIn(FieldCreatedAt, vs...))
+}
+
+// CreatedAtGT applies the GT predicate on the "created_at" field.
+func CreatedAtGT(v time.Time) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldGT(FieldCreatedAt, v))
+}
+
+// CreatedAtGTE applies the GTE predicate on the "created_at" field.
+func CreatedAtGTE(v time.Time) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldGTE(FieldCreatedAt, v))
+}
+
+// CreatedAtLT applies the LT predicate on the "created_at" field.
+func CreatedAtLT(v time.Time) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldLT(FieldCreatedAt, v))
+}
+
+// CreatedAtLTE applies the LTE predicate on the "created_at" field.
+func CreatedAtLTE(v time.Time) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldLTE(FieldCreatedAt, v))
+}
+
+// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
+func UpdatedAtEQ(v time.Time) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldEQ(FieldUpdatedAt, v))
+}
+
+// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
+func UpdatedAtNEQ(v time.Time) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldNEQ(FieldUpdatedAt, v))
+}
+
+// UpdatedAtIn applies the In predicate on the "updated_at" field.
+func UpdatedAtIn(vs ...time.Time) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldIn(FieldUpdatedAt, vs...))
+}
+
+// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
+func UpdatedAtNotIn(vs ...time.Time) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldNotIn(FieldUpdatedAt, vs...))
+}
+
+// UpdatedAtGT applies the GT predicate on the "updated_at" field.
+func UpdatedAtGT(v time.Time) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldGT(FieldUpdatedAt, v))
+}
+
+// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
+func UpdatedAtGTE(v time.Time) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldGTE(FieldUpdatedAt, v))
+}
+
+// UpdatedAtLT applies the LT predicate on the "updated_at" field.
+func UpdatedAtLT(v time.Time) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldLT(FieldUpdatedAt, v))
+}
+
+// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
+func UpdatedAtLTE(v time.Time) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.FieldLTE(FieldUpdatedAt, v))
+}
+
+// And groups predicates with the AND operator between them.
+func And(predicates ...predicate.BillingQuota) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.AndPredicates(predicates...))
+}
+
+// Or groups predicates with the OR operator between them.
+func Or(predicates ...predicate.BillingQuota) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.OrPredicates(predicates...))
+}
+
+// Not applies the not operator on the given predicate.
+func Not(p predicate.BillingQuota) predicate.BillingQuota {
+ return predicate.BillingQuota(sql.NotPredicates(p))
+}
diff --git a/backend/db/billingquota_create.go b/backend/db/billingquota_create.go
new file mode 100644
index 0000000..bf90604
--- /dev/null
+++ b/backend/db/billingquota_create.go
@@ -0,0 +1,932 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "time"
+
+ "entgo.io/ent/dialect"
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/billingquota"
+)
+
+// BillingQuotaCreate is the builder for creating a BillingQuota entity.
+type BillingQuotaCreate struct {
+ config
+ mutation *BillingQuotaMutation
+ hooks []Hook
+ conflict []sql.ConflictOption
+}
+
+// SetDeletedAt sets the "deleted_at" field.
+func (bqc *BillingQuotaCreate) SetDeletedAt(t time.Time) *BillingQuotaCreate {
+ bqc.mutation.SetDeletedAt(t)
+ return bqc
+}
+
+// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil.
+func (bqc *BillingQuotaCreate) SetNillableDeletedAt(t *time.Time) *BillingQuotaCreate {
+ if t != nil {
+ bqc.SetDeletedAt(*t)
+ }
+ return bqc
+}
+
+// SetUserID sets the "user_id" field.
+func (bqc *BillingQuotaCreate) SetUserID(s string) *BillingQuotaCreate {
+ bqc.mutation.SetUserID(s)
+ return bqc
+}
+
+// SetTotal sets the "total" field.
+func (bqc *BillingQuotaCreate) SetTotal(i int64) *BillingQuotaCreate {
+ bqc.mutation.SetTotal(i)
+ return bqc
+}
+
+// SetUsed sets the "used" field.
+func (bqc *BillingQuotaCreate) SetUsed(i int64) *BillingQuotaCreate {
+ bqc.mutation.SetUsed(i)
+ return bqc
+}
+
+// SetRemain sets the "remain" field.
+func (bqc *BillingQuotaCreate) SetRemain(i int64) *BillingQuotaCreate {
+ bqc.mutation.SetRemain(i)
+ return bqc
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (bqc *BillingQuotaCreate) SetCreatedAt(t time.Time) *BillingQuotaCreate {
+ bqc.mutation.SetCreatedAt(t)
+ return bqc
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (bqc *BillingQuotaCreate) SetNillableCreatedAt(t *time.Time) *BillingQuotaCreate {
+ if t != nil {
+ bqc.SetCreatedAt(*t)
+ }
+ return bqc
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (bqc *BillingQuotaCreate) SetUpdatedAt(t time.Time) *BillingQuotaCreate {
+ bqc.mutation.SetUpdatedAt(t)
+ return bqc
+}
+
+// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
+func (bqc *BillingQuotaCreate) SetNillableUpdatedAt(t *time.Time) *BillingQuotaCreate {
+ if t != nil {
+ bqc.SetUpdatedAt(*t)
+ }
+ return bqc
+}
+
+// SetID sets the "id" field.
+func (bqc *BillingQuotaCreate) SetID(s string) *BillingQuotaCreate {
+ bqc.mutation.SetID(s)
+ return bqc
+}
+
+// Mutation returns the BillingQuotaMutation object of the builder.
+func (bqc *BillingQuotaCreate) Mutation() *BillingQuotaMutation {
+ return bqc.mutation
+}
+
+// Save creates the BillingQuota in the database.
+func (bqc *BillingQuotaCreate) Save(ctx context.Context) (*BillingQuota, error) {
+ if err := bqc.defaults(); err != nil {
+ return nil, err
+ }
+ return withHooks(ctx, bqc.sqlSave, bqc.mutation, bqc.hooks)
+}
+
+// SaveX calls Save and panics if Save returns an error.
+func (bqc *BillingQuotaCreate) SaveX(ctx context.Context) *BillingQuota {
+ v, err := bqc.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return v
+}
+
+// Exec executes the query.
+func (bqc *BillingQuotaCreate) Exec(ctx context.Context) error {
+ _, err := bqc.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (bqc *BillingQuotaCreate) ExecX(ctx context.Context) {
+ if err := bqc.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// defaults sets the default values of the builder before save.
+func (bqc *BillingQuotaCreate) defaults() error {
+ if _, ok := bqc.mutation.CreatedAt(); !ok {
+ if billingquota.DefaultCreatedAt == nil {
+ return fmt.Errorf("db: uninitialized billingquota.DefaultCreatedAt (forgotten import db/runtime?)")
+ }
+ v := billingquota.DefaultCreatedAt()
+ bqc.mutation.SetCreatedAt(v)
+ }
+ if _, ok := bqc.mutation.UpdatedAt(); !ok {
+ if billingquota.DefaultUpdatedAt == nil {
+ return fmt.Errorf("db: uninitialized billingquota.DefaultUpdatedAt (forgotten import db/runtime?)")
+ }
+ v := billingquota.DefaultUpdatedAt()
+ bqc.mutation.SetUpdatedAt(v)
+ }
+ return nil
+}
+
+// check runs all checks and user-defined validators on the builder.
+func (bqc *BillingQuotaCreate) check() error {
+ if _, ok := bqc.mutation.UserID(); !ok {
+ return &ValidationError{Name: "user_id", err: errors.New(`db: missing required field "BillingQuota.user_id"`)}
+ }
+ if _, ok := bqc.mutation.Total(); !ok {
+ return &ValidationError{Name: "total", err: errors.New(`db: missing required field "BillingQuota.total"`)}
+ }
+ if _, ok := bqc.mutation.Used(); !ok {
+ return &ValidationError{Name: "used", err: errors.New(`db: missing required field "BillingQuota.used"`)}
+ }
+ if _, ok := bqc.mutation.Remain(); !ok {
+ return &ValidationError{Name: "remain", err: errors.New(`db: missing required field "BillingQuota.remain"`)}
+ }
+ if _, ok := bqc.mutation.CreatedAt(); !ok {
+ return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "BillingQuota.created_at"`)}
+ }
+ if _, ok := bqc.mutation.UpdatedAt(); !ok {
+ return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "BillingQuota.updated_at"`)}
+ }
+ return nil
+}
+
+func (bqc *BillingQuotaCreate) sqlSave(ctx context.Context) (*BillingQuota, error) {
+ if err := bqc.check(); err != nil {
+ return nil, err
+ }
+ _node, _spec := bqc.createSpec()
+ if err := sqlgraph.CreateNode(ctx, bqc.driver, _spec); err != nil {
+ if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return nil, err
+ }
+ if _spec.ID.Value != nil {
+ if id, ok := _spec.ID.Value.(string); ok {
+ _node.ID = id
+ } else {
+ return nil, fmt.Errorf("unexpected BillingQuota.ID type: %T", _spec.ID.Value)
+ }
+ }
+ bqc.mutation.id = &_node.ID
+ bqc.mutation.done = true
+ return _node, nil
+}
+
+func (bqc *BillingQuotaCreate) createSpec() (*BillingQuota, *sqlgraph.CreateSpec) {
+ var (
+ _node = &BillingQuota{config: bqc.config}
+ _spec = sqlgraph.NewCreateSpec(billingquota.Table, sqlgraph.NewFieldSpec(billingquota.FieldID, field.TypeString))
+ )
+ _spec.OnConflict = bqc.conflict
+ if id, ok := bqc.mutation.ID(); ok {
+ _node.ID = id
+ _spec.ID.Value = id
+ }
+ if value, ok := bqc.mutation.DeletedAt(); ok {
+ _spec.SetField(billingquota.FieldDeletedAt, field.TypeTime, value)
+ _node.DeletedAt = value
+ }
+ if value, ok := bqc.mutation.UserID(); ok {
+ _spec.SetField(billingquota.FieldUserID, field.TypeString, value)
+ _node.UserID = value
+ }
+ if value, ok := bqc.mutation.Total(); ok {
+ _spec.SetField(billingquota.FieldTotal, field.TypeInt64, value)
+ _node.Total = value
+ }
+ if value, ok := bqc.mutation.Used(); ok {
+ _spec.SetField(billingquota.FieldUsed, field.TypeInt64, value)
+ _node.Used = value
+ }
+ if value, ok := bqc.mutation.Remain(); ok {
+ _spec.SetField(billingquota.FieldRemain, field.TypeInt64, value)
+ _node.Remain = value
+ }
+ if value, ok := bqc.mutation.CreatedAt(); ok {
+ _spec.SetField(billingquota.FieldCreatedAt, field.TypeTime, value)
+ _node.CreatedAt = value
+ }
+ if value, ok := bqc.mutation.UpdatedAt(); ok {
+ _spec.SetField(billingquota.FieldUpdatedAt, field.TypeTime, value)
+ _node.UpdatedAt = value
+ }
+ return _node, _spec
+}
+
+// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
+// of the `INSERT` statement. For example:
+//
+// client.BillingQuota.Create().
+// SetDeletedAt(v).
+// OnConflict(
+// // Update the row with the new values
+// // the was proposed for insertion.
+// sql.ResolveWithNewValues(),
+// ).
+// // Override some of the fields with custom
+// // update values.
+// Update(func(u *ent.BillingQuotaUpsert) {
+// SetDeletedAt(v+v).
+// }).
+// Exec(ctx)
+func (bqc *BillingQuotaCreate) OnConflict(opts ...sql.ConflictOption) *BillingQuotaUpsertOne {
+ bqc.conflict = opts
+ return &BillingQuotaUpsertOne{
+ create: bqc,
+ }
+}
+
+// OnConflictColumns calls `OnConflict` and configures the columns
+// as conflict target. Using this option is equivalent to using:
+//
+// client.BillingQuota.Create().
+// OnConflict(sql.ConflictColumns(columns...)).
+// Exec(ctx)
+func (bqc *BillingQuotaCreate) OnConflictColumns(columns ...string) *BillingQuotaUpsertOne {
+ bqc.conflict = append(bqc.conflict, sql.ConflictColumns(columns...))
+ return &BillingQuotaUpsertOne{
+ create: bqc,
+ }
+}
+
+type (
+ // BillingQuotaUpsertOne is the builder for "upsert"-ing
+ // one BillingQuota node.
+ BillingQuotaUpsertOne struct {
+ create *BillingQuotaCreate
+ }
+
+ // BillingQuotaUpsert is the "OnConflict" setter.
+ BillingQuotaUpsert struct {
+ *sql.UpdateSet
+ }
+)
+
+// SetDeletedAt sets the "deleted_at" field.
+func (u *BillingQuotaUpsert) SetDeletedAt(v time.Time) *BillingQuotaUpsert {
+ u.Set(billingquota.FieldDeletedAt, v)
+ return u
+}
+
+// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create.
+func (u *BillingQuotaUpsert) UpdateDeletedAt() *BillingQuotaUpsert {
+ u.SetExcluded(billingquota.FieldDeletedAt)
+ return u
+}
+
+// ClearDeletedAt clears the value of the "deleted_at" field.
+func (u *BillingQuotaUpsert) ClearDeletedAt() *BillingQuotaUpsert {
+ u.SetNull(billingquota.FieldDeletedAt)
+ return u
+}
+
+// SetUserID sets the "user_id" field.
+func (u *BillingQuotaUpsert) SetUserID(v string) *BillingQuotaUpsert {
+ u.Set(billingquota.FieldUserID, v)
+ return u
+}
+
+// UpdateUserID sets the "user_id" field to the value that was provided on create.
+func (u *BillingQuotaUpsert) UpdateUserID() *BillingQuotaUpsert {
+ u.SetExcluded(billingquota.FieldUserID)
+ return u
+}
+
+// SetTotal sets the "total" field.
+func (u *BillingQuotaUpsert) SetTotal(v int64) *BillingQuotaUpsert {
+ u.Set(billingquota.FieldTotal, v)
+ return u
+}
+
+// UpdateTotal sets the "total" field to the value that was provided on create.
+func (u *BillingQuotaUpsert) UpdateTotal() *BillingQuotaUpsert {
+ u.SetExcluded(billingquota.FieldTotal)
+ return u
+}
+
+// AddTotal adds v to the "total" field.
+func (u *BillingQuotaUpsert) AddTotal(v int64) *BillingQuotaUpsert {
+ u.Add(billingquota.FieldTotal, v)
+ return u
+}
+
+// SetUsed sets the "used" field.
+func (u *BillingQuotaUpsert) SetUsed(v int64) *BillingQuotaUpsert {
+ u.Set(billingquota.FieldUsed, v)
+ return u
+}
+
+// UpdateUsed sets the "used" field to the value that was provided on create.
+func (u *BillingQuotaUpsert) UpdateUsed() *BillingQuotaUpsert {
+ u.SetExcluded(billingquota.FieldUsed)
+ return u
+}
+
+// AddUsed adds v to the "used" field.
+func (u *BillingQuotaUpsert) AddUsed(v int64) *BillingQuotaUpsert {
+ u.Add(billingquota.FieldUsed, v)
+ return u
+}
+
+// SetRemain sets the "remain" field.
+func (u *BillingQuotaUpsert) SetRemain(v int64) *BillingQuotaUpsert {
+ u.Set(billingquota.FieldRemain, v)
+ return u
+}
+
+// UpdateRemain sets the "remain" field to the value that was provided on create.
+func (u *BillingQuotaUpsert) UpdateRemain() *BillingQuotaUpsert {
+ u.SetExcluded(billingquota.FieldRemain)
+ return u
+}
+
+// AddRemain adds v to the "remain" field.
+func (u *BillingQuotaUpsert) AddRemain(v int64) *BillingQuotaUpsert {
+ u.Add(billingquota.FieldRemain, v)
+ return u
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (u *BillingQuotaUpsert) SetCreatedAt(v time.Time) *BillingQuotaUpsert {
+ u.Set(billingquota.FieldCreatedAt, v)
+ return u
+}
+
+// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
+func (u *BillingQuotaUpsert) UpdateCreatedAt() *BillingQuotaUpsert {
+ u.SetExcluded(billingquota.FieldCreatedAt)
+ return u
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (u *BillingQuotaUpsert) SetUpdatedAt(v time.Time) *BillingQuotaUpsert {
+ u.Set(billingquota.FieldUpdatedAt, v)
+ return u
+}
+
+// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
+func (u *BillingQuotaUpsert) UpdateUpdatedAt() *BillingQuotaUpsert {
+ u.SetExcluded(billingquota.FieldUpdatedAt)
+ return u
+}
+
+// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field.
+// Using this option is equivalent to using:
+//
+// client.BillingQuota.Create().
+// OnConflict(
+// sql.ResolveWithNewValues(),
+// sql.ResolveWith(func(u *sql.UpdateSet) {
+// u.SetIgnore(billingquota.FieldID)
+// }),
+// ).
+// Exec(ctx)
+func (u *BillingQuotaUpsertOne) UpdateNewValues() *BillingQuotaUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
+ if _, exists := u.create.mutation.ID(); exists {
+ s.SetIgnore(billingquota.FieldID)
+ }
+ }))
+ return u
+}
+
+// Ignore sets each column to itself in case of conflict.
+// Using this option is equivalent to using:
+//
+// client.BillingQuota.Create().
+// OnConflict(sql.ResolveWithIgnore()).
+// Exec(ctx)
+func (u *BillingQuotaUpsertOne) Ignore() *BillingQuotaUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
+ return u
+}
+
+// DoNothing configures the conflict_action to `DO NOTHING`.
+// Supported only by SQLite and PostgreSQL.
+func (u *BillingQuotaUpsertOne) DoNothing() *BillingQuotaUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.DoNothing())
+ return u
+}
+
+// Update allows overriding fields `UPDATE` values. See the BillingQuotaCreate.OnConflict
+// documentation for more info.
+func (u *BillingQuotaUpsertOne) Update(set func(*BillingQuotaUpsert)) *BillingQuotaUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
+ set(&BillingQuotaUpsert{UpdateSet: update})
+ }))
+ return u
+}
+
+// SetDeletedAt sets the "deleted_at" field.
+func (u *BillingQuotaUpsertOne) SetDeletedAt(v time.Time) *BillingQuotaUpsertOne {
+ return u.Update(func(s *BillingQuotaUpsert) {
+ s.SetDeletedAt(v)
+ })
+}
+
+// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create.
+func (u *BillingQuotaUpsertOne) UpdateDeletedAt() *BillingQuotaUpsertOne {
+ return u.Update(func(s *BillingQuotaUpsert) {
+ s.UpdateDeletedAt()
+ })
+}
+
+// ClearDeletedAt clears the value of the "deleted_at" field.
+func (u *BillingQuotaUpsertOne) ClearDeletedAt() *BillingQuotaUpsertOne {
+ return u.Update(func(s *BillingQuotaUpsert) {
+ s.ClearDeletedAt()
+ })
+}
+
+// SetUserID sets the "user_id" field.
+func (u *BillingQuotaUpsertOne) SetUserID(v string) *BillingQuotaUpsertOne {
+ return u.Update(func(s *BillingQuotaUpsert) {
+ s.SetUserID(v)
+ })
+}
+
+// UpdateUserID sets the "user_id" field to the value that was provided on create.
+func (u *BillingQuotaUpsertOne) UpdateUserID() *BillingQuotaUpsertOne {
+ return u.Update(func(s *BillingQuotaUpsert) {
+ s.UpdateUserID()
+ })
+}
+
+// SetTotal sets the "total" field.
+func (u *BillingQuotaUpsertOne) SetTotal(v int64) *BillingQuotaUpsertOne {
+ return u.Update(func(s *BillingQuotaUpsert) {
+ s.SetTotal(v)
+ })
+}
+
+// AddTotal adds v to the "total" field.
+func (u *BillingQuotaUpsertOne) AddTotal(v int64) *BillingQuotaUpsertOne {
+ return u.Update(func(s *BillingQuotaUpsert) {
+ s.AddTotal(v)
+ })
+}
+
+// UpdateTotal sets the "total" field to the value that was provided on create.
+func (u *BillingQuotaUpsertOne) UpdateTotal() *BillingQuotaUpsertOne {
+ return u.Update(func(s *BillingQuotaUpsert) {
+ s.UpdateTotal()
+ })
+}
+
+// SetUsed sets the "used" field.
+func (u *BillingQuotaUpsertOne) SetUsed(v int64) *BillingQuotaUpsertOne {
+ return u.Update(func(s *BillingQuotaUpsert) {
+ s.SetUsed(v)
+ })
+}
+
+// AddUsed adds v to the "used" field.
+func (u *BillingQuotaUpsertOne) AddUsed(v int64) *BillingQuotaUpsertOne {
+ return u.Update(func(s *BillingQuotaUpsert) {
+ s.AddUsed(v)
+ })
+}
+
+// UpdateUsed sets the "used" field to the value that was provided on create.
+func (u *BillingQuotaUpsertOne) UpdateUsed() *BillingQuotaUpsertOne {
+ return u.Update(func(s *BillingQuotaUpsert) {
+ s.UpdateUsed()
+ })
+}
+
+// SetRemain sets the "remain" field.
+func (u *BillingQuotaUpsertOne) SetRemain(v int64) *BillingQuotaUpsertOne {
+ return u.Update(func(s *BillingQuotaUpsert) {
+ s.SetRemain(v)
+ })
+}
+
+// AddRemain adds v to the "remain" field.
+func (u *BillingQuotaUpsertOne) AddRemain(v int64) *BillingQuotaUpsertOne {
+ return u.Update(func(s *BillingQuotaUpsert) {
+ s.AddRemain(v)
+ })
+}
+
+// UpdateRemain sets the "remain" field to the value that was provided on create.
+func (u *BillingQuotaUpsertOne) UpdateRemain() *BillingQuotaUpsertOne {
+ return u.Update(func(s *BillingQuotaUpsert) {
+ s.UpdateRemain()
+ })
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (u *BillingQuotaUpsertOne) SetCreatedAt(v time.Time) *BillingQuotaUpsertOne {
+ return u.Update(func(s *BillingQuotaUpsert) {
+ s.SetCreatedAt(v)
+ })
+}
+
+// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
+func (u *BillingQuotaUpsertOne) UpdateCreatedAt() *BillingQuotaUpsertOne {
+ return u.Update(func(s *BillingQuotaUpsert) {
+ s.UpdateCreatedAt()
+ })
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (u *BillingQuotaUpsertOne) SetUpdatedAt(v time.Time) *BillingQuotaUpsertOne {
+ return u.Update(func(s *BillingQuotaUpsert) {
+ s.SetUpdatedAt(v)
+ })
+}
+
+// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
+func (u *BillingQuotaUpsertOne) UpdateUpdatedAt() *BillingQuotaUpsertOne {
+ return u.Update(func(s *BillingQuotaUpsert) {
+ s.UpdateUpdatedAt()
+ })
+}
+
+// Exec executes the query.
+func (u *BillingQuotaUpsertOne) Exec(ctx context.Context) error {
+ if len(u.create.conflict) == 0 {
+ return errors.New("db: missing options for BillingQuotaCreate.OnConflict")
+ }
+ return u.create.Exec(ctx)
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (u *BillingQuotaUpsertOne) ExecX(ctx context.Context) {
+ if err := u.create.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// Exec executes the UPSERT query and returns the inserted/updated ID.
+func (u *BillingQuotaUpsertOne) ID(ctx context.Context) (id string, err error) {
+ if u.create.driver.Dialect() == dialect.MySQL {
+ // In case of "ON CONFLICT", there is no way to get back non-numeric ID
+ // fields from the database since MySQL does not support the RETURNING clause.
+ return id, errors.New("db: BillingQuotaUpsertOne.ID is not supported by MySQL driver. Use BillingQuotaUpsertOne.Exec instead")
+ }
+ node, err := u.create.Save(ctx)
+ if err != nil {
+ return id, err
+ }
+ return node.ID, nil
+}
+
+// IDX is like ID, but panics if an error occurs.
+func (u *BillingQuotaUpsertOne) IDX(ctx context.Context) string {
+ id, err := u.ID(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return id
+}
+
+// BillingQuotaCreateBulk is the builder for creating many BillingQuota entities in bulk.
+type BillingQuotaCreateBulk struct {
+ config
+ err error
+ builders []*BillingQuotaCreate
+ conflict []sql.ConflictOption
+}
+
+// Save creates the BillingQuota entities in the database.
+func (bqcb *BillingQuotaCreateBulk) Save(ctx context.Context) ([]*BillingQuota, error) {
+ if bqcb.err != nil {
+ return nil, bqcb.err
+ }
+ specs := make([]*sqlgraph.CreateSpec, len(bqcb.builders))
+ nodes := make([]*BillingQuota, len(bqcb.builders))
+ mutators := make([]Mutator, len(bqcb.builders))
+ for i := range bqcb.builders {
+ func(i int, root context.Context) {
+ builder := bqcb.builders[i]
+ builder.defaults()
+ var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
+ mutation, ok := m.(*BillingQuotaMutation)
+ if !ok {
+ return nil, fmt.Errorf("unexpected mutation type %T", m)
+ }
+ if err := builder.check(); err != nil {
+ return nil, err
+ }
+ builder.mutation = mutation
+ var err error
+ nodes[i], specs[i] = builder.createSpec()
+ if i < len(mutators)-1 {
+ _, err = mutators[i+1].Mutate(root, bqcb.builders[i+1].mutation)
+ } else {
+ spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
+ spec.OnConflict = bqcb.conflict
+ // Invoke the actual operation on the latest mutation in the chain.
+ if err = sqlgraph.BatchCreate(ctx, bqcb.driver, spec); err != nil {
+ if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ }
+ }
+ if err != nil {
+ return nil, err
+ }
+ mutation.id = &nodes[i].ID
+ mutation.done = true
+ return nodes[i], nil
+ })
+ for i := len(builder.hooks) - 1; i >= 0; i-- {
+ mut = builder.hooks[i](mut)
+ }
+ mutators[i] = mut
+ }(i, ctx)
+ }
+ if len(mutators) > 0 {
+ if _, err := mutators[0].Mutate(ctx, bqcb.builders[0].mutation); err != nil {
+ return nil, err
+ }
+ }
+ return nodes, nil
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (bqcb *BillingQuotaCreateBulk) SaveX(ctx context.Context) []*BillingQuota {
+ v, err := bqcb.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return v
+}
+
+// Exec executes the query.
+func (bqcb *BillingQuotaCreateBulk) Exec(ctx context.Context) error {
+ _, err := bqcb.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (bqcb *BillingQuotaCreateBulk) ExecX(ctx context.Context) {
+ if err := bqcb.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
+// of the `INSERT` statement. For example:
+//
+// client.BillingQuota.CreateBulk(builders...).
+// OnConflict(
+// // Update the row with the new values
+// // the was proposed for insertion.
+// sql.ResolveWithNewValues(),
+// ).
+// // Override some of the fields with custom
+// // update values.
+// Update(func(u *ent.BillingQuotaUpsert) {
+// SetDeletedAt(v+v).
+// }).
+// Exec(ctx)
+func (bqcb *BillingQuotaCreateBulk) OnConflict(opts ...sql.ConflictOption) *BillingQuotaUpsertBulk {
+ bqcb.conflict = opts
+ return &BillingQuotaUpsertBulk{
+ create: bqcb,
+ }
+}
+
+// OnConflictColumns calls `OnConflict` and configures the columns
+// as conflict target. Using this option is equivalent to using:
+//
+// client.BillingQuota.Create().
+// OnConflict(sql.ConflictColumns(columns...)).
+// Exec(ctx)
+func (bqcb *BillingQuotaCreateBulk) OnConflictColumns(columns ...string) *BillingQuotaUpsertBulk {
+ bqcb.conflict = append(bqcb.conflict, sql.ConflictColumns(columns...))
+ return &BillingQuotaUpsertBulk{
+ create: bqcb,
+ }
+}
+
+// BillingQuotaUpsertBulk is the builder for "upsert"-ing
+// a bulk of BillingQuota nodes.
+type BillingQuotaUpsertBulk struct {
+ create *BillingQuotaCreateBulk
+}
+
+// UpdateNewValues updates the mutable fields using the new values that
+// were set on create. Using this option is equivalent to using:
+//
+// client.BillingQuota.Create().
+// OnConflict(
+// sql.ResolveWithNewValues(),
+// sql.ResolveWith(func(u *sql.UpdateSet) {
+// u.SetIgnore(billingquota.FieldID)
+// }),
+// ).
+// Exec(ctx)
+func (u *BillingQuotaUpsertBulk) UpdateNewValues() *BillingQuotaUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
+ for _, b := range u.create.builders {
+ if _, exists := b.mutation.ID(); exists {
+ s.SetIgnore(billingquota.FieldID)
+ }
+ }
+ }))
+ return u
+}
+
+// Ignore sets each column to itself in case of conflict.
+// Using this option is equivalent to using:
+//
+// client.BillingQuota.Create().
+// OnConflict(sql.ResolveWithIgnore()).
+// Exec(ctx)
+func (u *BillingQuotaUpsertBulk) Ignore() *BillingQuotaUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
+ return u
+}
+
+// DoNothing configures the conflict_action to `DO NOTHING`.
+// Supported only by SQLite and PostgreSQL.
+func (u *BillingQuotaUpsertBulk) DoNothing() *BillingQuotaUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.DoNothing())
+ return u
+}
+
+// Update allows overriding fields `UPDATE` values. See the BillingQuotaCreateBulk.OnConflict
+// documentation for more info.
+func (u *BillingQuotaUpsertBulk) Update(set func(*BillingQuotaUpsert)) *BillingQuotaUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
+ set(&BillingQuotaUpsert{UpdateSet: update})
+ }))
+ return u
+}
+
+// SetDeletedAt sets the "deleted_at" field.
+func (u *BillingQuotaUpsertBulk) SetDeletedAt(v time.Time) *BillingQuotaUpsertBulk {
+ return u.Update(func(s *BillingQuotaUpsert) {
+ s.SetDeletedAt(v)
+ })
+}
+
+// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create.
+func (u *BillingQuotaUpsertBulk) UpdateDeletedAt() *BillingQuotaUpsertBulk {
+ return u.Update(func(s *BillingQuotaUpsert) {
+ s.UpdateDeletedAt()
+ })
+}
+
+// ClearDeletedAt clears the value of the "deleted_at" field.
+func (u *BillingQuotaUpsertBulk) ClearDeletedAt() *BillingQuotaUpsertBulk {
+ return u.Update(func(s *BillingQuotaUpsert) {
+ s.ClearDeletedAt()
+ })
+}
+
+// SetUserID sets the "user_id" field.
+func (u *BillingQuotaUpsertBulk) SetUserID(v string) *BillingQuotaUpsertBulk {
+ return u.Update(func(s *BillingQuotaUpsert) {
+ s.SetUserID(v)
+ })
+}
+
+// UpdateUserID sets the "user_id" field to the value that was provided on create.
+func (u *BillingQuotaUpsertBulk) UpdateUserID() *BillingQuotaUpsertBulk {
+ return u.Update(func(s *BillingQuotaUpsert) {
+ s.UpdateUserID()
+ })
+}
+
+// SetTotal sets the "total" field.
+func (u *BillingQuotaUpsertBulk) SetTotal(v int64) *BillingQuotaUpsertBulk {
+ return u.Update(func(s *BillingQuotaUpsert) {
+ s.SetTotal(v)
+ })
+}
+
+// AddTotal adds v to the "total" field.
+func (u *BillingQuotaUpsertBulk) AddTotal(v int64) *BillingQuotaUpsertBulk {
+ return u.Update(func(s *BillingQuotaUpsert) {
+ s.AddTotal(v)
+ })
+}
+
+// UpdateTotal sets the "total" field to the value that was provided on create.
+func (u *BillingQuotaUpsertBulk) UpdateTotal() *BillingQuotaUpsertBulk {
+ return u.Update(func(s *BillingQuotaUpsert) {
+ s.UpdateTotal()
+ })
+}
+
+// SetUsed sets the "used" field.
+func (u *BillingQuotaUpsertBulk) SetUsed(v int64) *BillingQuotaUpsertBulk {
+ return u.Update(func(s *BillingQuotaUpsert) {
+ s.SetUsed(v)
+ })
+}
+
+// AddUsed adds v to the "used" field.
+func (u *BillingQuotaUpsertBulk) AddUsed(v int64) *BillingQuotaUpsertBulk {
+ return u.Update(func(s *BillingQuotaUpsert) {
+ s.AddUsed(v)
+ })
+}
+
+// UpdateUsed sets the "used" field to the value that was provided on create.
+func (u *BillingQuotaUpsertBulk) UpdateUsed() *BillingQuotaUpsertBulk {
+ return u.Update(func(s *BillingQuotaUpsert) {
+ s.UpdateUsed()
+ })
+}
+
+// SetRemain sets the "remain" field.
+func (u *BillingQuotaUpsertBulk) SetRemain(v int64) *BillingQuotaUpsertBulk {
+ return u.Update(func(s *BillingQuotaUpsert) {
+ s.SetRemain(v)
+ })
+}
+
+// AddRemain adds v to the "remain" field.
+func (u *BillingQuotaUpsertBulk) AddRemain(v int64) *BillingQuotaUpsertBulk {
+ return u.Update(func(s *BillingQuotaUpsert) {
+ s.AddRemain(v)
+ })
+}
+
+// UpdateRemain sets the "remain" field to the value that was provided on create.
+func (u *BillingQuotaUpsertBulk) UpdateRemain() *BillingQuotaUpsertBulk {
+ return u.Update(func(s *BillingQuotaUpsert) {
+ s.UpdateRemain()
+ })
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (u *BillingQuotaUpsertBulk) SetCreatedAt(v time.Time) *BillingQuotaUpsertBulk {
+ return u.Update(func(s *BillingQuotaUpsert) {
+ s.SetCreatedAt(v)
+ })
+}
+
+// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
+func (u *BillingQuotaUpsertBulk) UpdateCreatedAt() *BillingQuotaUpsertBulk {
+ return u.Update(func(s *BillingQuotaUpsert) {
+ s.UpdateCreatedAt()
+ })
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (u *BillingQuotaUpsertBulk) SetUpdatedAt(v time.Time) *BillingQuotaUpsertBulk {
+ return u.Update(func(s *BillingQuotaUpsert) {
+ s.SetUpdatedAt(v)
+ })
+}
+
+// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
+func (u *BillingQuotaUpsertBulk) UpdateUpdatedAt() *BillingQuotaUpsertBulk {
+ return u.Update(func(s *BillingQuotaUpsert) {
+ s.UpdateUpdatedAt()
+ })
+}
+
+// Exec executes the query.
+func (u *BillingQuotaUpsertBulk) Exec(ctx context.Context) error {
+ if u.create.err != nil {
+ return u.create.err
+ }
+ for i, b := range u.create.builders {
+ if len(b.conflict) != 0 {
+ return fmt.Errorf("db: OnConflict was set for builder %d. Set it on the BillingQuotaCreateBulk instead", i)
+ }
+ }
+ if len(u.create.conflict) == 0 {
+ return errors.New("db: missing options for BillingQuotaCreateBulk.OnConflict")
+ }
+ return u.create.Exec(ctx)
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (u *BillingQuotaUpsertBulk) ExecX(ctx context.Context) {
+ if err := u.create.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
diff --git a/backend/db/billingquota_delete.go b/backend/db/billingquota_delete.go
new file mode 100644
index 0000000..4810243
--- /dev/null
+++ b/backend/db/billingquota_delete.go
@@ -0,0 +1,88 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/billingquota"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+)
+
+// BillingQuotaDelete is the builder for deleting a BillingQuota entity.
+type BillingQuotaDelete struct {
+ config
+ hooks []Hook
+ mutation *BillingQuotaMutation
+}
+
+// Where appends a list predicates to the BillingQuotaDelete builder.
+func (bqd *BillingQuotaDelete) Where(ps ...predicate.BillingQuota) *BillingQuotaDelete {
+ bqd.mutation.Where(ps...)
+ return bqd
+}
+
+// Exec executes the deletion query and returns how many vertices were deleted.
+func (bqd *BillingQuotaDelete) Exec(ctx context.Context) (int, error) {
+ return withHooks(ctx, bqd.sqlExec, bqd.mutation, bqd.hooks)
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (bqd *BillingQuotaDelete) ExecX(ctx context.Context) int {
+ n, err := bqd.Exec(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return n
+}
+
+func (bqd *BillingQuotaDelete) sqlExec(ctx context.Context) (int, error) {
+ _spec := sqlgraph.NewDeleteSpec(billingquota.Table, sqlgraph.NewFieldSpec(billingquota.FieldID, field.TypeString))
+ if ps := bqd.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ affected, err := sqlgraph.DeleteNodes(ctx, bqd.driver, _spec)
+ if err != nil && sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ bqd.mutation.done = true
+ return affected, err
+}
+
+// BillingQuotaDeleteOne is the builder for deleting a single BillingQuota entity.
+type BillingQuotaDeleteOne struct {
+ bqd *BillingQuotaDelete
+}
+
+// Where appends a list predicates to the BillingQuotaDelete builder.
+func (bqdo *BillingQuotaDeleteOne) Where(ps ...predicate.BillingQuota) *BillingQuotaDeleteOne {
+ bqdo.bqd.mutation.Where(ps...)
+ return bqdo
+}
+
+// Exec executes the deletion query.
+func (bqdo *BillingQuotaDeleteOne) Exec(ctx context.Context) error {
+ n, err := bqdo.bqd.Exec(ctx)
+ switch {
+ case err != nil:
+ return err
+ case n == 0:
+ return &NotFoundError{billingquota.Label}
+ default:
+ return nil
+ }
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (bqdo *BillingQuotaDeleteOne) ExecX(ctx context.Context) {
+ if err := bqdo.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
diff --git a/backend/db/billingquota_query.go b/backend/db/billingquota_query.go
new file mode 100644
index 0000000..a92dd90
--- /dev/null
+++ b/backend/db/billingquota_query.go
@@ -0,0 +1,577 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "fmt"
+ "math"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect"
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/billingquota"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+)
+
+// BillingQuotaQuery is the builder for querying BillingQuota entities.
+type BillingQuotaQuery struct {
+ config
+ ctx *QueryContext
+ order []billingquota.OrderOption
+ inters []Interceptor
+ predicates []predicate.BillingQuota
+ modifiers []func(*sql.Selector)
+ // intermediate query (i.e. traversal path).
+ sql *sql.Selector
+ path func(context.Context) (*sql.Selector, error)
+}
+
+// Where adds a new predicate for the BillingQuotaQuery builder.
+func (bqq *BillingQuotaQuery) Where(ps ...predicate.BillingQuota) *BillingQuotaQuery {
+ bqq.predicates = append(bqq.predicates, ps...)
+ return bqq
+}
+
+// Limit the number of records to be returned by this query.
+func (bqq *BillingQuotaQuery) Limit(limit int) *BillingQuotaQuery {
+ bqq.ctx.Limit = &limit
+ return bqq
+}
+
+// Offset to start from.
+func (bqq *BillingQuotaQuery) Offset(offset int) *BillingQuotaQuery {
+ bqq.ctx.Offset = &offset
+ return bqq
+}
+
+// Unique configures the query builder to filter duplicate records on query.
+// By default, unique is set to true, and can be disabled using this method.
+func (bqq *BillingQuotaQuery) Unique(unique bool) *BillingQuotaQuery {
+ bqq.ctx.Unique = &unique
+ return bqq
+}
+
+// Order specifies how the records should be ordered.
+func (bqq *BillingQuotaQuery) Order(o ...billingquota.OrderOption) *BillingQuotaQuery {
+ bqq.order = append(bqq.order, o...)
+ return bqq
+}
+
+// First returns the first BillingQuota entity from the query.
+// Returns a *NotFoundError when no BillingQuota was found.
+func (bqq *BillingQuotaQuery) First(ctx context.Context) (*BillingQuota, error) {
+ nodes, err := bqq.Limit(1).All(setContextOp(ctx, bqq.ctx, ent.OpQueryFirst))
+ if err != nil {
+ return nil, err
+ }
+ if len(nodes) == 0 {
+ return nil, &NotFoundError{billingquota.Label}
+ }
+ return nodes[0], nil
+}
+
+// FirstX is like First, but panics if an error occurs.
+func (bqq *BillingQuotaQuery) FirstX(ctx context.Context) *BillingQuota {
+ node, err := bqq.First(ctx)
+ if err != nil && !IsNotFound(err) {
+ panic(err)
+ }
+ return node
+}
+
+// FirstID returns the first BillingQuota ID from the query.
+// Returns a *NotFoundError when no BillingQuota ID was found.
+func (bqq *BillingQuotaQuery) FirstID(ctx context.Context) (id string, err error) {
+ var ids []string
+ if ids, err = bqq.Limit(1).IDs(setContextOp(ctx, bqq.ctx, ent.OpQueryFirstID)); err != nil {
+ return
+ }
+ if len(ids) == 0 {
+ err = &NotFoundError{billingquota.Label}
+ return
+ }
+ return ids[0], nil
+}
+
+// FirstIDX is like FirstID, but panics if an error occurs.
+func (bqq *BillingQuotaQuery) FirstIDX(ctx context.Context) string {
+ id, err := bqq.FirstID(ctx)
+ if err != nil && !IsNotFound(err) {
+ panic(err)
+ }
+ return id
+}
+
+// Only returns a single BillingQuota entity found by the query, ensuring it only returns one.
+// Returns a *NotSingularError when more than one BillingQuota entity is found.
+// Returns a *NotFoundError when no BillingQuota entities are found.
+func (bqq *BillingQuotaQuery) Only(ctx context.Context) (*BillingQuota, error) {
+ nodes, err := bqq.Limit(2).All(setContextOp(ctx, bqq.ctx, ent.OpQueryOnly))
+ if err != nil {
+ return nil, err
+ }
+ switch len(nodes) {
+ case 1:
+ return nodes[0], nil
+ case 0:
+ return nil, &NotFoundError{billingquota.Label}
+ default:
+ return nil, &NotSingularError{billingquota.Label}
+ }
+}
+
+// OnlyX is like Only, but panics if an error occurs.
+func (bqq *BillingQuotaQuery) OnlyX(ctx context.Context) *BillingQuota {
+ node, err := bqq.Only(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return node
+}
+
+// OnlyID is like Only, but returns the only BillingQuota ID in the query.
+// Returns a *NotSingularError when more than one BillingQuota ID is found.
+// Returns a *NotFoundError when no entities are found.
+func (bqq *BillingQuotaQuery) OnlyID(ctx context.Context) (id string, err error) {
+ var ids []string
+ if ids, err = bqq.Limit(2).IDs(setContextOp(ctx, bqq.ctx, ent.OpQueryOnlyID)); err != nil {
+ return
+ }
+ switch len(ids) {
+ case 1:
+ id = ids[0]
+ case 0:
+ err = &NotFoundError{billingquota.Label}
+ default:
+ err = &NotSingularError{billingquota.Label}
+ }
+ return
+}
+
+// OnlyIDX is like OnlyID, but panics if an error occurs.
+func (bqq *BillingQuotaQuery) OnlyIDX(ctx context.Context) string {
+ id, err := bqq.OnlyID(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return id
+}
+
+// All executes the query and returns a list of BillingQuotaSlice.
+func (bqq *BillingQuotaQuery) All(ctx context.Context) ([]*BillingQuota, error) {
+ ctx = setContextOp(ctx, bqq.ctx, ent.OpQueryAll)
+ if err := bqq.prepareQuery(ctx); err != nil {
+ return nil, err
+ }
+ qr := querierAll[[]*BillingQuota, *BillingQuotaQuery]()
+ return withInterceptors[[]*BillingQuota](ctx, bqq, qr, bqq.inters)
+}
+
+// AllX is like All, but panics if an error occurs.
+func (bqq *BillingQuotaQuery) AllX(ctx context.Context) []*BillingQuota {
+ nodes, err := bqq.All(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return nodes
+}
+
+// IDs executes the query and returns a list of BillingQuota IDs.
+func (bqq *BillingQuotaQuery) IDs(ctx context.Context) (ids []string, err error) {
+ if bqq.ctx.Unique == nil && bqq.path != nil {
+ bqq.Unique(true)
+ }
+ ctx = setContextOp(ctx, bqq.ctx, ent.OpQueryIDs)
+ if err = bqq.Select(billingquota.FieldID).Scan(ctx, &ids); err != nil {
+ return nil, err
+ }
+ return ids, nil
+}
+
+// IDsX is like IDs, but panics if an error occurs.
+func (bqq *BillingQuotaQuery) IDsX(ctx context.Context) []string {
+ ids, err := bqq.IDs(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return ids
+}
+
+// Count returns the count of the given query.
+func (bqq *BillingQuotaQuery) Count(ctx context.Context) (int, error) {
+ ctx = setContextOp(ctx, bqq.ctx, ent.OpQueryCount)
+ if err := bqq.prepareQuery(ctx); err != nil {
+ return 0, err
+ }
+ return withInterceptors[int](ctx, bqq, querierCount[*BillingQuotaQuery](), bqq.inters)
+}
+
+// CountX is like Count, but panics if an error occurs.
+func (bqq *BillingQuotaQuery) CountX(ctx context.Context) int {
+ count, err := bqq.Count(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return count
+}
+
+// Exist returns true if the query has elements in the graph.
+func (bqq *BillingQuotaQuery) Exist(ctx context.Context) (bool, error) {
+ ctx = setContextOp(ctx, bqq.ctx, ent.OpQueryExist)
+ switch _, err := bqq.FirstID(ctx); {
+ case IsNotFound(err):
+ return false, nil
+ case err != nil:
+ return false, fmt.Errorf("db: check existence: %w", err)
+ default:
+ return true, nil
+ }
+}
+
+// ExistX is like Exist, but panics if an error occurs.
+func (bqq *BillingQuotaQuery) ExistX(ctx context.Context) bool {
+ exist, err := bqq.Exist(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return exist
+}
+
+// Clone returns a duplicate of the BillingQuotaQuery builder, including all associated steps. It can be
+// used to prepare common query builders and use them differently after the clone is made.
+func (bqq *BillingQuotaQuery) Clone() *BillingQuotaQuery {
+ if bqq == nil {
+ return nil
+ }
+ return &BillingQuotaQuery{
+ config: bqq.config,
+ ctx: bqq.ctx.Clone(),
+ order: append([]billingquota.OrderOption{}, bqq.order...),
+ inters: append([]Interceptor{}, bqq.inters...),
+ predicates: append([]predicate.BillingQuota{}, bqq.predicates...),
+ // clone intermediate query.
+ sql: bqq.sql.Clone(),
+ path: bqq.path,
+ modifiers: append([]func(*sql.Selector){}, bqq.modifiers...),
+ }
+}
+
+// GroupBy is used to group vertices by one or more fields/columns.
+// It is often used with aggregate functions, like: count, max, mean, min, sum.
+//
+// Example:
+//
+// var v []struct {
+// DeletedAt time.Time `json:"deleted_at,omitempty"`
+// Count int `json:"count,omitempty"`
+// }
+//
+// client.BillingQuota.Query().
+// GroupBy(billingquota.FieldDeletedAt).
+// Aggregate(db.Count()).
+// Scan(ctx, &v)
+func (bqq *BillingQuotaQuery) GroupBy(field string, fields ...string) *BillingQuotaGroupBy {
+ bqq.ctx.Fields = append([]string{field}, fields...)
+ grbuild := &BillingQuotaGroupBy{build: bqq}
+ grbuild.flds = &bqq.ctx.Fields
+ grbuild.label = billingquota.Label
+ grbuild.scan = grbuild.Scan
+ return grbuild
+}
+
+// Select allows the selection one or more fields/columns for the given query,
+// instead of selecting all fields in the entity.
+//
+// Example:
+//
+// var v []struct {
+// DeletedAt time.Time `json:"deleted_at,omitempty"`
+// }
+//
+// client.BillingQuota.Query().
+// Select(billingquota.FieldDeletedAt).
+// Scan(ctx, &v)
+func (bqq *BillingQuotaQuery) Select(fields ...string) *BillingQuotaSelect {
+ bqq.ctx.Fields = append(bqq.ctx.Fields, fields...)
+ sbuild := &BillingQuotaSelect{BillingQuotaQuery: bqq}
+ sbuild.label = billingquota.Label
+ sbuild.flds, sbuild.scan = &bqq.ctx.Fields, sbuild.Scan
+ return sbuild
+}
+
+// Aggregate returns a BillingQuotaSelect configured with the given aggregations.
+func (bqq *BillingQuotaQuery) Aggregate(fns ...AggregateFunc) *BillingQuotaSelect {
+ return bqq.Select().Aggregate(fns...)
+}
+
+func (bqq *BillingQuotaQuery) prepareQuery(ctx context.Context) error {
+ for _, inter := range bqq.inters {
+ if inter == nil {
+ return fmt.Errorf("db: uninitialized interceptor (forgotten import db/runtime?)")
+ }
+ if trv, ok := inter.(Traverser); ok {
+ if err := trv.Traverse(ctx, bqq); err != nil {
+ return err
+ }
+ }
+ }
+ for _, f := range bqq.ctx.Fields {
+ if !billingquota.ValidColumn(f) {
+ return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
+ }
+ }
+ if bqq.path != nil {
+ prev, err := bqq.path(ctx)
+ if err != nil {
+ return err
+ }
+ bqq.sql = prev
+ }
+ return nil
+}
+
+func (bqq *BillingQuotaQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*BillingQuota, error) {
+ var (
+ nodes = []*BillingQuota{}
+ _spec = bqq.querySpec()
+ )
+ _spec.ScanValues = func(columns []string) ([]any, error) {
+ return (*BillingQuota).scanValues(nil, columns)
+ }
+ _spec.Assign = func(columns []string, values []any) error {
+ node := &BillingQuota{config: bqq.config}
+ nodes = append(nodes, node)
+ return node.assignValues(columns, values)
+ }
+ if len(bqq.modifiers) > 0 {
+ _spec.Modifiers = bqq.modifiers
+ }
+ for i := range hooks {
+ hooks[i](ctx, _spec)
+ }
+ if err := sqlgraph.QueryNodes(ctx, bqq.driver, _spec); err != nil {
+ return nil, err
+ }
+ if len(nodes) == 0 {
+ return nodes, nil
+ }
+ return nodes, nil
+}
+
+func (bqq *BillingQuotaQuery) sqlCount(ctx context.Context) (int, error) {
+ _spec := bqq.querySpec()
+ if len(bqq.modifiers) > 0 {
+ _spec.Modifiers = bqq.modifiers
+ }
+ _spec.Node.Columns = bqq.ctx.Fields
+ if len(bqq.ctx.Fields) > 0 {
+ _spec.Unique = bqq.ctx.Unique != nil && *bqq.ctx.Unique
+ }
+ return sqlgraph.CountNodes(ctx, bqq.driver, _spec)
+}
+
+func (bqq *BillingQuotaQuery) querySpec() *sqlgraph.QuerySpec {
+ _spec := sqlgraph.NewQuerySpec(billingquota.Table, billingquota.Columns, sqlgraph.NewFieldSpec(billingquota.FieldID, field.TypeString))
+ _spec.From = bqq.sql
+ if unique := bqq.ctx.Unique; unique != nil {
+ _spec.Unique = *unique
+ } else if bqq.path != nil {
+ _spec.Unique = true
+ }
+ if fields := bqq.ctx.Fields; len(fields) > 0 {
+ _spec.Node.Columns = make([]string, 0, len(fields))
+ _spec.Node.Columns = append(_spec.Node.Columns, billingquota.FieldID)
+ for i := range fields {
+ if fields[i] != billingquota.FieldID {
+ _spec.Node.Columns = append(_spec.Node.Columns, fields[i])
+ }
+ }
+ }
+ if ps := bqq.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if limit := bqq.ctx.Limit; limit != nil {
+ _spec.Limit = *limit
+ }
+ if offset := bqq.ctx.Offset; offset != nil {
+ _spec.Offset = *offset
+ }
+ if ps := bqq.order; len(ps) > 0 {
+ _spec.Order = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ return _spec
+}
+
+func (bqq *BillingQuotaQuery) sqlQuery(ctx context.Context) *sql.Selector {
+ builder := sql.Dialect(bqq.driver.Dialect())
+ t1 := builder.Table(billingquota.Table)
+ columns := bqq.ctx.Fields
+ if len(columns) == 0 {
+ columns = billingquota.Columns
+ }
+ selector := builder.Select(t1.Columns(columns...)...).From(t1)
+ if bqq.sql != nil {
+ selector = bqq.sql
+ selector.Select(selector.Columns(columns...)...)
+ }
+ if bqq.ctx.Unique != nil && *bqq.ctx.Unique {
+ selector.Distinct()
+ }
+ for _, m := range bqq.modifiers {
+ m(selector)
+ }
+ for _, p := range bqq.predicates {
+ p(selector)
+ }
+ for _, p := range bqq.order {
+ p(selector)
+ }
+ if offset := bqq.ctx.Offset; offset != nil {
+ // limit is mandatory for offset clause. We start
+ // with default value, and override it below if needed.
+ selector.Offset(*offset).Limit(math.MaxInt32)
+ }
+ if limit := bqq.ctx.Limit; limit != nil {
+ selector.Limit(*limit)
+ }
+ return selector
+}
+
+// ForUpdate locks the selected rows against concurrent updates, and prevent them from being
+// updated, deleted or "selected ... for update" by other sessions, until the transaction is
+// either committed or rolled-back.
+func (bqq *BillingQuotaQuery) ForUpdate(opts ...sql.LockOption) *BillingQuotaQuery {
+ if bqq.driver.Dialect() == dialect.Postgres {
+ bqq.Unique(false)
+ }
+ bqq.modifiers = append(bqq.modifiers, func(s *sql.Selector) {
+ s.ForUpdate(opts...)
+ })
+ return bqq
+}
+
+// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock
+// on any rows that are read. Other sessions can read the rows, but cannot modify them
+// until your transaction commits.
+func (bqq *BillingQuotaQuery) ForShare(opts ...sql.LockOption) *BillingQuotaQuery {
+ if bqq.driver.Dialect() == dialect.Postgres {
+ bqq.Unique(false)
+ }
+ bqq.modifiers = append(bqq.modifiers, func(s *sql.Selector) {
+ s.ForShare(opts...)
+ })
+ return bqq
+}
+
+// Modify adds a query modifier for attaching custom logic to queries.
+func (bqq *BillingQuotaQuery) Modify(modifiers ...func(s *sql.Selector)) *BillingQuotaSelect {
+ bqq.modifiers = append(bqq.modifiers, modifiers...)
+ return bqq.Select()
+}
+
+// BillingQuotaGroupBy is the group-by builder for BillingQuota entities.
+type BillingQuotaGroupBy struct {
+ selector
+ build *BillingQuotaQuery
+}
+
+// Aggregate adds the given aggregation functions to the group-by query.
+func (bqgb *BillingQuotaGroupBy) Aggregate(fns ...AggregateFunc) *BillingQuotaGroupBy {
+ bqgb.fns = append(bqgb.fns, fns...)
+ return bqgb
+}
+
+// Scan applies the selector query and scans the result into the given value.
+func (bqgb *BillingQuotaGroupBy) Scan(ctx context.Context, v any) error {
+ ctx = setContextOp(ctx, bqgb.build.ctx, ent.OpQueryGroupBy)
+ if err := bqgb.build.prepareQuery(ctx); err != nil {
+ return err
+ }
+ return scanWithInterceptors[*BillingQuotaQuery, *BillingQuotaGroupBy](ctx, bqgb.build, bqgb, bqgb.build.inters, v)
+}
+
+func (bqgb *BillingQuotaGroupBy) sqlScan(ctx context.Context, root *BillingQuotaQuery, v any) error {
+ selector := root.sqlQuery(ctx).Select()
+ aggregation := make([]string, 0, len(bqgb.fns))
+ for _, fn := range bqgb.fns {
+ aggregation = append(aggregation, fn(selector))
+ }
+ if len(selector.SelectedColumns()) == 0 {
+ columns := make([]string, 0, len(*bqgb.flds)+len(bqgb.fns))
+ for _, f := range *bqgb.flds {
+ columns = append(columns, selector.C(f))
+ }
+ columns = append(columns, aggregation...)
+ selector.Select(columns...)
+ }
+ selector.GroupBy(selector.Columns(*bqgb.flds...)...)
+ if err := selector.Err(); err != nil {
+ return err
+ }
+ rows := &sql.Rows{}
+ query, args := selector.Query()
+ if err := bqgb.build.driver.Query(ctx, query, args, rows); err != nil {
+ return err
+ }
+ defer rows.Close()
+ return sql.ScanSlice(rows, v)
+}
+
+// BillingQuotaSelect is the builder for selecting fields of BillingQuota entities.
+type BillingQuotaSelect struct {
+ *BillingQuotaQuery
+ selector
+}
+
+// Aggregate adds the given aggregation functions to the selector query.
+func (bqs *BillingQuotaSelect) Aggregate(fns ...AggregateFunc) *BillingQuotaSelect {
+ bqs.fns = append(bqs.fns, fns...)
+ return bqs
+}
+
+// Scan applies the selector query and scans the result into the given value.
+func (bqs *BillingQuotaSelect) Scan(ctx context.Context, v any) error {
+ ctx = setContextOp(ctx, bqs.ctx, ent.OpQuerySelect)
+ if err := bqs.prepareQuery(ctx); err != nil {
+ return err
+ }
+ return scanWithInterceptors[*BillingQuotaQuery, *BillingQuotaSelect](ctx, bqs.BillingQuotaQuery, bqs, bqs.inters, v)
+}
+
+func (bqs *BillingQuotaSelect) sqlScan(ctx context.Context, root *BillingQuotaQuery, v any) error {
+ selector := root.sqlQuery(ctx)
+ aggregation := make([]string, 0, len(bqs.fns))
+ for _, fn := range bqs.fns {
+ aggregation = append(aggregation, fn(selector))
+ }
+ switch n := len(*bqs.selector.flds); {
+ case n == 0 && len(aggregation) > 0:
+ selector.Select(aggregation...)
+ case n != 0 && len(aggregation) > 0:
+ selector.AppendSelect(aggregation...)
+ }
+ rows := &sql.Rows{}
+ query, args := selector.Query()
+ if err := bqs.driver.Query(ctx, query, args, rows); err != nil {
+ return err
+ }
+ defer rows.Close()
+ return sql.ScanSlice(rows, v)
+}
+
+// Modify adds a query modifier for attaching custom logic to queries.
+func (bqs *BillingQuotaSelect) Modify(modifiers ...func(s *sql.Selector)) *BillingQuotaSelect {
+ bqs.modifiers = append(bqs.modifiers, modifiers...)
+ return bqs
+}
diff --git a/backend/db/billingquota_update.go b/backend/db/billingquota_update.go
new file mode 100644
index 0000000..7669468
--- /dev/null
+++ b/backend/db/billingquota_update.go
@@ -0,0 +1,522 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "time"
+
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/billingquota"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+)
+
+// BillingQuotaUpdate is the builder for updating BillingQuota entities.
+type BillingQuotaUpdate struct {
+ config
+ hooks []Hook
+ mutation *BillingQuotaMutation
+ modifiers []func(*sql.UpdateBuilder)
+}
+
+// Where appends a list predicates to the BillingQuotaUpdate builder.
+func (bqu *BillingQuotaUpdate) Where(ps ...predicate.BillingQuota) *BillingQuotaUpdate {
+ bqu.mutation.Where(ps...)
+ return bqu
+}
+
+// SetDeletedAt sets the "deleted_at" field.
+func (bqu *BillingQuotaUpdate) SetDeletedAt(t time.Time) *BillingQuotaUpdate {
+ bqu.mutation.SetDeletedAt(t)
+ return bqu
+}
+
+// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil.
+func (bqu *BillingQuotaUpdate) SetNillableDeletedAt(t *time.Time) *BillingQuotaUpdate {
+ if t != nil {
+ bqu.SetDeletedAt(*t)
+ }
+ return bqu
+}
+
+// ClearDeletedAt clears the value of the "deleted_at" field.
+func (bqu *BillingQuotaUpdate) ClearDeletedAt() *BillingQuotaUpdate {
+ bqu.mutation.ClearDeletedAt()
+ return bqu
+}
+
+// SetUserID sets the "user_id" field.
+func (bqu *BillingQuotaUpdate) SetUserID(s string) *BillingQuotaUpdate {
+ bqu.mutation.SetUserID(s)
+ return bqu
+}
+
+// SetNillableUserID sets the "user_id" field if the given value is not nil.
+func (bqu *BillingQuotaUpdate) SetNillableUserID(s *string) *BillingQuotaUpdate {
+ if s != nil {
+ bqu.SetUserID(*s)
+ }
+ return bqu
+}
+
+// SetTotal sets the "total" field.
+func (bqu *BillingQuotaUpdate) SetTotal(i int64) *BillingQuotaUpdate {
+ bqu.mutation.ResetTotal()
+ bqu.mutation.SetTotal(i)
+ return bqu
+}
+
+// SetNillableTotal sets the "total" field if the given value is not nil.
+func (bqu *BillingQuotaUpdate) SetNillableTotal(i *int64) *BillingQuotaUpdate {
+ if i != nil {
+ bqu.SetTotal(*i)
+ }
+ return bqu
+}
+
+// AddTotal adds i to the "total" field.
+func (bqu *BillingQuotaUpdate) AddTotal(i int64) *BillingQuotaUpdate {
+ bqu.mutation.AddTotal(i)
+ return bqu
+}
+
+// SetUsed sets the "used" field.
+func (bqu *BillingQuotaUpdate) SetUsed(i int64) *BillingQuotaUpdate {
+ bqu.mutation.ResetUsed()
+ bqu.mutation.SetUsed(i)
+ return bqu
+}
+
+// SetNillableUsed sets the "used" field if the given value is not nil.
+func (bqu *BillingQuotaUpdate) SetNillableUsed(i *int64) *BillingQuotaUpdate {
+ if i != nil {
+ bqu.SetUsed(*i)
+ }
+ return bqu
+}
+
+// AddUsed adds i to the "used" field.
+func (bqu *BillingQuotaUpdate) AddUsed(i int64) *BillingQuotaUpdate {
+ bqu.mutation.AddUsed(i)
+ return bqu
+}
+
+// SetRemain sets the "remain" field.
+func (bqu *BillingQuotaUpdate) SetRemain(i int64) *BillingQuotaUpdate {
+ bqu.mutation.ResetRemain()
+ bqu.mutation.SetRemain(i)
+ return bqu
+}
+
+// SetNillableRemain sets the "remain" field if the given value is not nil.
+func (bqu *BillingQuotaUpdate) SetNillableRemain(i *int64) *BillingQuotaUpdate {
+ if i != nil {
+ bqu.SetRemain(*i)
+ }
+ return bqu
+}
+
+// AddRemain adds i to the "remain" field.
+func (bqu *BillingQuotaUpdate) AddRemain(i int64) *BillingQuotaUpdate {
+ bqu.mutation.AddRemain(i)
+ return bqu
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (bqu *BillingQuotaUpdate) SetCreatedAt(t time.Time) *BillingQuotaUpdate {
+ bqu.mutation.SetCreatedAt(t)
+ return bqu
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (bqu *BillingQuotaUpdate) SetNillableCreatedAt(t *time.Time) *BillingQuotaUpdate {
+ if t != nil {
+ bqu.SetCreatedAt(*t)
+ }
+ return bqu
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (bqu *BillingQuotaUpdate) SetUpdatedAt(t time.Time) *BillingQuotaUpdate {
+ bqu.mutation.SetUpdatedAt(t)
+ return bqu
+}
+
+// Mutation returns the BillingQuotaMutation object of the builder.
+func (bqu *BillingQuotaUpdate) Mutation() *BillingQuotaMutation {
+ return bqu.mutation
+}
+
+// Save executes the query and returns the number of nodes affected by the update operation.
+func (bqu *BillingQuotaUpdate) Save(ctx context.Context) (int, error) {
+ if err := bqu.defaults(); err != nil {
+ return 0, err
+ }
+ return withHooks(ctx, bqu.sqlSave, bqu.mutation, bqu.hooks)
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (bqu *BillingQuotaUpdate) SaveX(ctx context.Context) int {
+ affected, err := bqu.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return affected
+}
+
+// Exec executes the query.
+func (bqu *BillingQuotaUpdate) Exec(ctx context.Context) error {
+ _, err := bqu.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (bqu *BillingQuotaUpdate) ExecX(ctx context.Context) {
+ if err := bqu.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// defaults sets the default values of the builder before save.
+func (bqu *BillingQuotaUpdate) defaults() error {
+ if _, ok := bqu.mutation.UpdatedAt(); !ok {
+ if billingquota.UpdateDefaultUpdatedAt == nil {
+ return fmt.Errorf("db: uninitialized billingquota.UpdateDefaultUpdatedAt (forgotten import db/runtime?)")
+ }
+ v := billingquota.UpdateDefaultUpdatedAt()
+ bqu.mutation.SetUpdatedAt(v)
+ }
+ return nil
+}
+
+// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
+func (bqu *BillingQuotaUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *BillingQuotaUpdate {
+ bqu.modifiers = append(bqu.modifiers, modifiers...)
+ return bqu
+}
+
+func (bqu *BillingQuotaUpdate) sqlSave(ctx context.Context) (n int, err error) {
+ _spec := sqlgraph.NewUpdateSpec(billingquota.Table, billingquota.Columns, sqlgraph.NewFieldSpec(billingquota.FieldID, field.TypeString))
+ if ps := bqu.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if value, ok := bqu.mutation.DeletedAt(); ok {
+ _spec.SetField(billingquota.FieldDeletedAt, field.TypeTime, value)
+ }
+ if bqu.mutation.DeletedAtCleared() {
+ _spec.ClearField(billingquota.FieldDeletedAt, field.TypeTime)
+ }
+ if value, ok := bqu.mutation.UserID(); ok {
+ _spec.SetField(billingquota.FieldUserID, field.TypeString, value)
+ }
+ if value, ok := bqu.mutation.Total(); ok {
+ _spec.SetField(billingquota.FieldTotal, field.TypeInt64, value)
+ }
+ if value, ok := bqu.mutation.AddedTotal(); ok {
+ _spec.AddField(billingquota.FieldTotal, field.TypeInt64, value)
+ }
+ if value, ok := bqu.mutation.Used(); ok {
+ _spec.SetField(billingquota.FieldUsed, field.TypeInt64, value)
+ }
+ if value, ok := bqu.mutation.AddedUsed(); ok {
+ _spec.AddField(billingquota.FieldUsed, field.TypeInt64, value)
+ }
+ if value, ok := bqu.mutation.Remain(); ok {
+ _spec.SetField(billingquota.FieldRemain, field.TypeInt64, value)
+ }
+ if value, ok := bqu.mutation.AddedRemain(); ok {
+ _spec.AddField(billingquota.FieldRemain, field.TypeInt64, value)
+ }
+ if value, ok := bqu.mutation.CreatedAt(); ok {
+ _spec.SetField(billingquota.FieldCreatedAt, field.TypeTime, value)
+ }
+ if value, ok := bqu.mutation.UpdatedAt(); ok {
+ _spec.SetField(billingquota.FieldUpdatedAt, field.TypeTime, value)
+ }
+ _spec.AddModifiers(bqu.modifiers...)
+ if n, err = sqlgraph.UpdateNodes(ctx, bqu.driver, _spec); err != nil {
+ if _, ok := err.(*sqlgraph.NotFoundError); ok {
+ err = &NotFoundError{billingquota.Label}
+ } else if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return 0, err
+ }
+ bqu.mutation.done = true
+ return n, nil
+}
+
+// BillingQuotaUpdateOne is the builder for updating a single BillingQuota entity.
+type BillingQuotaUpdateOne struct {
+ config
+ fields []string
+ hooks []Hook
+ mutation *BillingQuotaMutation
+ modifiers []func(*sql.UpdateBuilder)
+}
+
+// SetDeletedAt sets the "deleted_at" field.
+func (bquo *BillingQuotaUpdateOne) SetDeletedAt(t time.Time) *BillingQuotaUpdateOne {
+ bquo.mutation.SetDeletedAt(t)
+ return bquo
+}
+
+// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil.
+func (bquo *BillingQuotaUpdateOne) SetNillableDeletedAt(t *time.Time) *BillingQuotaUpdateOne {
+ if t != nil {
+ bquo.SetDeletedAt(*t)
+ }
+ return bquo
+}
+
+// ClearDeletedAt clears the value of the "deleted_at" field.
+func (bquo *BillingQuotaUpdateOne) ClearDeletedAt() *BillingQuotaUpdateOne {
+ bquo.mutation.ClearDeletedAt()
+ return bquo
+}
+
+// SetUserID sets the "user_id" field.
+func (bquo *BillingQuotaUpdateOne) SetUserID(s string) *BillingQuotaUpdateOne {
+ bquo.mutation.SetUserID(s)
+ return bquo
+}
+
+// SetNillableUserID sets the "user_id" field if the given value is not nil.
+func (bquo *BillingQuotaUpdateOne) SetNillableUserID(s *string) *BillingQuotaUpdateOne {
+ if s != nil {
+ bquo.SetUserID(*s)
+ }
+ return bquo
+}
+
+// SetTotal sets the "total" field.
+func (bquo *BillingQuotaUpdateOne) SetTotal(i int64) *BillingQuotaUpdateOne {
+ bquo.mutation.ResetTotal()
+ bquo.mutation.SetTotal(i)
+ return bquo
+}
+
+// SetNillableTotal sets the "total" field if the given value is not nil.
+func (bquo *BillingQuotaUpdateOne) SetNillableTotal(i *int64) *BillingQuotaUpdateOne {
+ if i != nil {
+ bquo.SetTotal(*i)
+ }
+ return bquo
+}
+
+// AddTotal adds i to the "total" field.
+func (bquo *BillingQuotaUpdateOne) AddTotal(i int64) *BillingQuotaUpdateOne {
+ bquo.mutation.AddTotal(i)
+ return bquo
+}
+
+// SetUsed sets the "used" field.
+func (bquo *BillingQuotaUpdateOne) SetUsed(i int64) *BillingQuotaUpdateOne {
+ bquo.mutation.ResetUsed()
+ bquo.mutation.SetUsed(i)
+ return bquo
+}
+
+// SetNillableUsed sets the "used" field if the given value is not nil.
+func (bquo *BillingQuotaUpdateOne) SetNillableUsed(i *int64) *BillingQuotaUpdateOne {
+ if i != nil {
+ bquo.SetUsed(*i)
+ }
+ return bquo
+}
+
+// AddUsed adds i to the "used" field.
+func (bquo *BillingQuotaUpdateOne) AddUsed(i int64) *BillingQuotaUpdateOne {
+ bquo.mutation.AddUsed(i)
+ return bquo
+}
+
+// SetRemain sets the "remain" field.
+func (bquo *BillingQuotaUpdateOne) SetRemain(i int64) *BillingQuotaUpdateOne {
+ bquo.mutation.ResetRemain()
+ bquo.mutation.SetRemain(i)
+ return bquo
+}
+
+// SetNillableRemain sets the "remain" field if the given value is not nil.
+func (bquo *BillingQuotaUpdateOne) SetNillableRemain(i *int64) *BillingQuotaUpdateOne {
+ if i != nil {
+ bquo.SetRemain(*i)
+ }
+ return bquo
+}
+
+// AddRemain adds i to the "remain" field.
+func (bquo *BillingQuotaUpdateOne) AddRemain(i int64) *BillingQuotaUpdateOne {
+ bquo.mutation.AddRemain(i)
+ return bquo
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (bquo *BillingQuotaUpdateOne) SetCreatedAt(t time.Time) *BillingQuotaUpdateOne {
+ bquo.mutation.SetCreatedAt(t)
+ return bquo
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (bquo *BillingQuotaUpdateOne) SetNillableCreatedAt(t *time.Time) *BillingQuotaUpdateOne {
+ if t != nil {
+ bquo.SetCreatedAt(*t)
+ }
+ return bquo
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (bquo *BillingQuotaUpdateOne) SetUpdatedAt(t time.Time) *BillingQuotaUpdateOne {
+ bquo.mutation.SetUpdatedAt(t)
+ return bquo
+}
+
+// Mutation returns the BillingQuotaMutation object of the builder.
+func (bquo *BillingQuotaUpdateOne) Mutation() *BillingQuotaMutation {
+ return bquo.mutation
+}
+
+// Where appends a list predicates to the BillingQuotaUpdate builder.
+func (bquo *BillingQuotaUpdateOne) Where(ps ...predicate.BillingQuota) *BillingQuotaUpdateOne {
+ bquo.mutation.Where(ps...)
+ return bquo
+}
+
+// Select allows selecting one or more fields (columns) of the returned entity.
+// The default is selecting all fields defined in the entity schema.
+func (bquo *BillingQuotaUpdateOne) Select(field string, fields ...string) *BillingQuotaUpdateOne {
+ bquo.fields = append([]string{field}, fields...)
+ return bquo
+}
+
+// Save executes the query and returns the updated BillingQuota entity.
+func (bquo *BillingQuotaUpdateOne) Save(ctx context.Context) (*BillingQuota, error) {
+ if err := bquo.defaults(); err != nil {
+ return nil, err
+ }
+ return withHooks(ctx, bquo.sqlSave, bquo.mutation, bquo.hooks)
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (bquo *BillingQuotaUpdateOne) SaveX(ctx context.Context) *BillingQuota {
+ node, err := bquo.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return node
+}
+
+// Exec executes the query on the entity.
+func (bquo *BillingQuotaUpdateOne) Exec(ctx context.Context) error {
+ _, err := bquo.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (bquo *BillingQuotaUpdateOne) ExecX(ctx context.Context) {
+ if err := bquo.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// defaults sets the default values of the builder before save.
+func (bquo *BillingQuotaUpdateOne) defaults() error {
+ if _, ok := bquo.mutation.UpdatedAt(); !ok {
+ if billingquota.UpdateDefaultUpdatedAt == nil {
+ return fmt.Errorf("db: uninitialized billingquota.UpdateDefaultUpdatedAt (forgotten import db/runtime?)")
+ }
+ v := billingquota.UpdateDefaultUpdatedAt()
+ bquo.mutation.SetUpdatedAt(v)
+ }
+ return nil
+}
+
+// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
+func (bquo *BillingQuotaUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *BillingQuotaUpdateOne {
+ bquo.modifiers = append(bquo.modifiers, modifiers...)
+ return bquo
+}
+
+func (bquo *BillingQuotaUpdateOne) sqlSave(ctx context.Context) (_node *BillingQuota, err error) {
+ _spec := sqlgraph.NewUpdateSpec(billingquota.Table, billingquota.Columns, sqlgraph.NewFieldSpec(billingquota.FieldID, field.TypeString))
+ id, ok := bquo.mutation.ID()
+ if !ok {
+ return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "BillingQuota.id" for update`)}
+ }
+ _spec.Node.ID.Value = id
+ if fields := bquo.fields; len(fields) > 0 {
+ _spec.Node.Columns = make([]string, 0, len(fields))
+ _spec.Node.Columns = append(_spec.Node.Columns, billingquota.FieldID)
+ for _, f := range fields {
+ if !billingquota.ValidColumn(f) {
+ return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
+ }
+ if f != billingquota.FieldID {
+ _spec.Node.Columns = append(_spec.Node.Columns, f)
+ }
+ }
+ }
+ if ps := bquo.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if value, ok := bquo.mutation.DeletedAt(); ok {
+ _spec.SetField(billingquota.FieldDeletedAt, field.TypeTime, value)
+ }
+ if bquo.mutation.DeletedAtCleared() {
+ _spec.ClearField(billingquota.FieldDeletedAt, field.TypeTime)
+ }
+ if value, ok := bquo.mutation.UserID(); ok {
+ _spec.SetField(billingquota.FieldUserID, field.TypeString, value)
+ }
+ if value, ok := bquo.mutation.Total(); ok {
+ _spec.SetField(billingquota.FieldTotal, field.TypeInt64, value)
+ }
+ if value, ok := bquo.mutation.AddedTotal(); ok {
+ _spec.AddField(billingquota.FieldTotal, field.TypeInt64, value)
+ }
+ if value, ok := bquo.mutation.Used(); ok {
+ _spec.SetField(billingquota.FieldUsed, field.TypeInt64, value)
+ }
+ if value, ok := bquo.mutation.AddedUsed(); ok {
+ _spec.AddField(billingquota.FieldUsed, field.TypeInt64, value)
+ }
+ if value, ok := bquo.mutation.Remain(); ok {
+ _spec.SetField(billingquota.FieldRemain, field.TypeInt64, value)
+ }
+ if value, ok := bquo.mutation.AddedRemain(); ok {
+ _spec.AddField(billingquota.FieldRemain, field.TypeInt64, value)
+ }
+ if value, ok := bquo.mutation.CreatedAt(); ok {
+ _spec.SetField(billingquota.FieldCreatedAt, field.TypeTime, value)
+ }
+ if value, ok := bquo.mutation.UpdatedAt(); ok {
+ _spec.SetField(billingquota.FieldUpdatedAt, field.TypeTime, value)
+ }
+ _spec.AddModifiers(bquo.modifiers...)
+ _node = &BillingQuota{config: bquo.config}
+ _spec.Assign = _node.assignValues
+ _spec.ScanValues = _node.scanValues
+ if err = sqlgraph.UpdateNode(ctx, bquo.driver, _spec); err != nil {
+ if _, ok := err.(*sqlgraph.NotFoundError); ok {
+ err = &NotFoundError{billingquota.Label}
+ } else if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return nil, err
+ }
+ bquo.mutation.done = true
+ return _node, nil
+}
diff --git a/backend/db/billingrecord.go b/backend/db/billingrecord.go
new file mode 100644
index 0000000..7b42edb
--- /dev/null
+++ b/backend/db/billingrecord.go
@@ -0,0 +1,221 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "encoding/json"
+ "fmt"
+ "strings"
+ "time"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect/sql"
+ "github.com/chaitin/MonkeyCode/backend/db/billingrecord"
+)
+
+// BillingRecord is the model entity for the BillingRecord schema.
+type BillingRecord struct {
+ config `json:"-"`
+ // ID of the ent.
+ ID string `json:"id,omitempty"`
+ // TenantID holds the value of the "tenant_id" field.
+ TenantID string `json:"tenant_id,omitempty"`
+ // UserID holds the value of the "user_id" field.
+ UserID string `json:"user_id,omitempty"`
+ // Model holds the value of the "model" field.
+ Model string `json:"model,omitempty"`
+ // Operation holds the value of the "operation" field.
+ Operation string `json:"operation,omitempty"`
+ // InputTokens holds the value of the "input_tokens" field.
+ InputTokens int64 `json:"input_tokens,omitempty"`
+ // OutputTokens holds the value of the "output_tokens" field.
+ OutputTokens int64 `json:"output_tokens,omitempty"`
+ // Cost holds the value of the "cost" field.
+ Cost int64 `json:"cost,omitempty"`
+ // RequestTime holds the value of the "request_time" field.
+ RequestTime time.Time `json:"request_time,omitempty"`
+ // Metadata holds the value of the "metadata" field.
+ Metadata map[string]interface{} `json:"metadata,omitempty"`
+ // CreatedAt holds the value of the "created_at" field.
+ CreatedAt time.Time `json:"created_at,omitempty"`
+ // UpdatedAt holds the value of the "updated_at" field.
+ UpdatedAt time.Time `json:"updated_at,omitempty"`
+ selectValues sql.SelectValues
+}
+
+// scanValues returns the types for scanning values from sql.Rows.
+func (*BillingRecord) scanValues(columns []string) ([]any, error) {
+ values := make([]any, len(columns))
+ for i := range columns {
+ switch columns[i] {
+ case billingrecord.FieldMetadata:
+ values[i] = new([]byte)
+ case billingrecord.FieldInputTokens, billingrecord.FieldOutputTokens, billingrecord.FieldCost:
+ values[i] = new(sql.NullInt64)
+ case billingrecord.FieldID, billingrecord.FieldTenantID, billingrecord.FieldUserID, billingrecord.FieldModel, billingrecord.FieldOperation:
+ values[i] = new(sql.NullString)
+ case billingrecord.FieldRequestTime, billingrecord.FieldCreatedAt, billingrecord.FieldUpdatedAt:
+ values[i] = new(sql.NullTime)
+ default:
+ values[i] = new(sql.UnknownType)
+ }
+ }
+ return values, nil
+}
+
+// assignValues assigns the values that were returned from sql.Rows (after scanning)
+// to the BillingRecord fields.
+func (br *BillingRecord) assignValues(columns []string, values []any) error {
+ if m, n := len(values), len(columns); m < n {
+ return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
+ }
+ for i := range columns {
+ switch columns[i] {
+ case billingrecord.FieldID:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field id", values[i])
+ } else if value.Valid {
+ br.ID = value.String
+ }
+ case billingrecord.FieldTenantID:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field tenant_id", values[i])
+ } else if value.Valid {
+ br.TenantID = value.String
+ }
+ case billingrecord.FieldUserID:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field user_id", values[i])
+ } else if value.Valid {
+ br.UserID = value.String
+ }
+ case billingrecord.FieldModel:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field model", values[i])
+ } else if value.Valid {
+ br.Model = value.String
+ }
+ case billingrecord.FieldOperation:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field operation", values[i])
+ } else if value.Valid {
+ br.Operation = value.String
+ }
+ case billingrecord.FieldInputTokens:
+ if value, ok := values[i].(*sql.NullInt64); !ok {
+ return fmt.Errorf("unexpected type %T for field input_tokens", values[i])
+ } else if value.Valid {
+ br.InputTokens = value.Int64
+ }
+ case billingrecord.FieldOutputTokens:
+ if value, ok := values[i].(*sql.NullInt64); !ok {
+ return fmt.Errorf("unexpected type %T for field output_tokens", values[i])
+ } else if value.Valid {
+ br.OutputTokens = value.Int64
+ }
+ case billingrecord.FieldCost:
+ if value, ok := values[i].(*sql.NullInt64); !ok {
+ return fmt.Errorf("unexpected type %T for field cost", values[i])
+ } else if value.Valid {
+ br.Cost = value.Int64
+ }
+ case billingrecord.FieldRequestTime:
+ if value, ok := values[i].(*sql.NullTime); !ok {
+ return fmt.Errorf("unexpected type %T for field request_time", values[i])
+ } else if value.Valid {
+ br.RequestTime = value.Time
+ }
+ case billingrecord.FieldMetadata:
+ if value, ok := values[i].(*[]byte); !ok {
+ return fmt.Errorf("unexpected type %T for field metadata", values[i])
+ } else if value != nil && len(*value) > 0 {
+ if err := json.Unmarshal(*value, &br.Metadata); err != nil {
+ return fmt.Errorf("unmarshal field metadata: %w", err)
+ }
+ }
+ case billingrecord.FieldCreatedAt:
+ if value, ok := values[i].(*sql.NullTime); !ok {
+ return fmt.Errorf("unexpected type %T for field created_at", values[i])
+ } else if value.Valid {
+ br.CreatedAt = value.Time
+ }
+ case billingrecord.FieldUpdatedAt:
+ if value, ok := values[i].(*sql.NullTime); !ok {
+ return fmt.Errorf("unexpected type %T for field updated_at", values[i])
+ } else if value.Valid {
+ br.UpdatedAt = value.Time
+ }
+ default:
+ br.selectValues.Set(columns[i], values[i])
+ }
+ }
+ return nil
+}
+
+// Value returns the ent.Value that was dynamically selected and assigned to the BillingRecord.
+// This includes values selected through modifiers, order, etc.
+func (br *BillingRecord) Value(name string) (ent.Value, error) {
+ return br.selectValues.Get(name)
+}
+
+// Update returns a builder for updating this BillingRecord.
+// Note that you need to call BillingRecord.Unwrap() before calling this method if this BillingRecord
+// was returned from a transaction, and the transaction was committed or rolled back.
+func (br *BillingRecord) Update() *BillingRecordUpdateOne {
+ return NewBillingRecordClient(br.config).UpdateOne(br)
+}
+
+// Unwrap unwraps the BillingRecord entity that was returned from a transaction after it was closed,
+// so that all future queries will be executed through the driver which created the transaction.
+func (br *BillingRecord) Unwrap() *BillingRecord {
+ _tx, ok := br.config.driver.(*txDriver)
+ if !ok {
+ panic("db: BillingRecord is not a transactional entity")
+ }
+ br.config.driver = _tx.drv
+ return br
+}
+
+// String implements the fmt.Stringer.
+func (br *BillingRecord) String() string {
+ var builder strings.Builder
+ builder.WriteString("BillingRecord(")
+ builder.WriteString(fmt.Sprintf("id=%v, ", br.ID))
+ builder.WriteString("tenant_id=")
+ builder.WriteString(br.TenantID)
+ builder.WriteString(", ")
+ builder.WriteString("user_id=")
+ builder.WriteString(br.UserID)
+ builder.WriteString(", ")
+ builder.WriteString("model=")
+ builder.WriteString(br.Model)
+ builder.WriteString(", ")
+ builder.WriteString("operation=")
+ builder.WriteString(br.Operation)
+ builder.WriteString(", ")
+ builder.WriteString("input_tokens=")
+ builder.WriteString(fmt.Sprintf("%v", br.InputTokens))
+ builder.WriteString(", ")
+ builder.WriteString("output_tokens=")
+ builder.WriteString(fmt.Sprintf("%v", br.OutputTokens))
+ builder.WriteString(", ")
+ builder.WriteString("cost=")
+ builder.WriteString(fmt.Sprintf("%v", br.Cost))
+ builder.WriteString(", ")
+ builder.WriteString("request_time=")
+ builder.WriteString(br.RequestTime.Format(time.ANSIC))
+ builder.WriteString(", ")
+ builder.WriteString("metadata=")
+ builder.WriteString(fmt.Sprintf("%v", br.Metadata))
+ builder.WriteString(", ")
+ builder.WriteString("created_at=")
+ builder.WriteString(br.CreatedAt.Format(time.ANSIC))
+ builder.WriteString(", ")
+ builder.WriteString("updated_at=")
+ builder.WriteString(br.UpdatedAt.Format(time.ANSIC))
+ builder.WriteByte(')')
+ return builder.String()
+}
+
+// BillingRecords is a parsable slice of BillingRecord.
+type BillingRecords []*BillingRecord
diff --git a/backend/db/billingrecord/billingrecord.go b/backend/db/billingrecord/billingrecord.go
new file mode 100644
index 0000000..0390763
--- /dev/null
+++ b/backend/db/billingrecord/billingrecord.go
@@ -0,0 +1,135 @@
+// Code generated by ent, DO NOT EDIT.
+
+package billingrecord
+
+import (
+ "time"
+
+ "entgo.io/ent/dialect/sql"
+)
+
+const (
+ // Label holds the string label denoting the billingrecord type in the database.
+ Label = "billing_record"
+ // FieldID holds the string denoting the id field in the database.
+ FieldID = "id"
+ // FieldTenantID holds the string denoting the tenant_id field in the database.
+ FieldTenantID = "tenant_id"
+ // FieldUserID holds the string denoting the user_id field in the database.
+ FieldUserID = "user_id"
+ // FieldModel holds the string denoting the model field in the database.
+ FieldModel = "model"
+ // FieldOperation holds the string denoting the operation field in the database.
+ FieldOperation = "operation"
+ // FieldInputTokens holds the string denoting the input_tokens field in the database.
+ FieldInputTokens = "input_tokens"
+ // FieldOutputTokens holds the string denoting the output_tokens field in the database.
+ FieldOutputTokens = "output_tokens"
+ // FieldCost holds the string denoting the cost field in the database.
+ FieldCost = "cost"
+ // FieldRequestTime holds the string denoting the request_time field in the database.
+ FieldRequestTime = "request_time"
+ // FieldMetadata holds the string denoting the metadata field in the database.
+ FieldMetadata = "metadata"
+ // FieldCreatedAt holds the string denoting the created_at field in the database.
+ FieldCreatedAt = "created_at"
+ // FieldUpdatedAt holds the string denoting the updated_at field in the database.
+ FieldUpdatedAt = "updated_at"
+ // Table holds the table name of the billingrecord in the database.
+ Table = "billing_records"
+)
+
+// Columns holds all SQL columns for billingrecord fields.
+var Columns = []string{
+ FieldID,
+ FieldTenantID,
+ FieldUserID,
+ FieldModel,
+ FieldOperation,
+ FieldInputTokens,
+ FieldOutputTokens,
+ FieldCost,
+ FieldRequestTime,
+ FieldMetadata,
+ FieldCreatedAt,
+ FieldUpdatedAt,
+}
+
+// ValidColumn reports if the column name is valid (part of the table columns).
+func ValidColumn(column string) bool {
+ for i := range Columns {
+ if column == Columns[i] {
+ return true
+ }
+ }
+ return false
+}
+
+var (
+ // DefaultRequestTime holds the default value on creation for the "request_time" field.
+ DefaultRequestTime func() time.Time
+ // DefaultCreatedAt holds the default value on creation for the "created_at" field.
+ DefaultCreatedAt func() time.Time
+ // DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
+ DefaultUpdatedAt func() time.Time
+ // UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field.
+ UpdateDefaultUpdatedAt func() time.Time
+)
+
+// OrderOption defines the ordering options for the BillingRecord queries.
+type OrderOption func(*sql.Selector)
+
+// ByID orders the results by the id field.
+func ByID(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldID, opts...).ToFunc()
+}
+
+// ByTenantID orders the results by the tenant_id field.
+func ByTenantID(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldTenantID, opts...).ToFunc()
+}
+
+// ByUserID orders the results by the user_id field.
+func ByUserID(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldUserID, opts...).ToFunc()
+}
+
+// ByModel orders the results by the model field.
+func ByModel(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldModel, opts...).ToFunc()
+}
+
+// ByOperation orders the results by the operation field.
+func ByOperation(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldOperation, opts...).ToFunc()
+}
+
+// ByInputTokens orders the results by the input_tokens field.
+func ByInputTokens(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldInputTokens, opts...).ToFunc()
+}
+
+// ByOutputTokens orders the results by the output_tokens field.
+func ByOutputTokens(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldOutputTokens, opts...).ToFunc()
+}
+
+// ByCost orders the results by the cost field.
+func ByCost(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldCost, opts...).ToFunc()
+}
+
+// ByRequestTime orders the results by the request_time field.
+func ByRequestTime(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldRequestTime, opts...).ToFunc()
+}
+
+// ByCreatedAt orders the results by the created_at field.
+func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
+}
+
+// ByUpdatedAt orders the results by the updated_at field.
+func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc()
+}
diff --git a/backend/db/billingrecord/where.go b/backend/db/billingrecord/where.go
new file mode 100644
index 0000000..0a3c124
--- /dev/null
+++ b/backend/db/billingrecord/where.go
@@ -0,0 +1,630 @@
+// Code generated by ent, DO NOT EDIT.
+
+package billingrecord
+
+import (
+ "time"
+
+ "entgo.io/ent/dialect/sql"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+)
+
+// ID filters vertices based on their ID field.
+func ID(id string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldEQ(FieldID, id))
+}
+
+// IDEQ applies the EQ predicate on the ID field.
+func IDEQ(id string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldEQ(FieldID, id))
+}
+
+// IDNEQ applies the NEQ predicate on the ID field.
+func IDNEQ(id string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldNEQ(FieldID, id))
+}
+
+// IDIn applies the In predicate on the ID field.
+func IDIn(ids ...string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldIn(FieldID, ids...))
+}
+
+// IDNotIn applies the NotIn predicate on the ID field.
+func IDNotIn(ids ...string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldNotIn(FieldID, ids...))
+}
+
+// IDGT applies the GT predicate on the ID field.
+func IDGT(id string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldGT(FieldID, id))
+}
+
+// IDGTE applies the GTE predicate on the ID field.
+func IDGTE(id string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldGTE(FieldID, id))
+}
+
+// IDLT applies the LT predicate on the ID field.
+func IDLT(id string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldLT(FieldID, id))
+}
+
+// IDLTE applies the LTE predicate on the ID field.
+func IDLTE(id string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldLTE(FieldID, id))
+}
+
+// IDEqualFold applies the EqualFold predicate on the ID field.
+func IDEqualFold(id string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldEqualFold(FieldID, id))
+}
+
+// IDContainsFold applies the ContainsFold predicate on the ID field.
+func IDContainsFold(id string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldContainsFold(FieldID, id))
+}
+
+// TenantID applies equality check predicate on the "tenant_id" field. It's identical to TenantIDEQ.
+func TenantID(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldEQ(FieldTenantID, v))
+}
+
+// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ.
+func UserID(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldEQ(FieldUserID, v))
+}
+
+// Model applies equality check predicate on the "model" field. It's identical to ModelEQ.
+func Model(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldEQ(FieldModel, v))
+}
+
+// Operation applies equality check predicate on the "operation" field. It's identical to OperationEQ.
+func Operation(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldEQ(FieldOperation, v))
+}
+
+// InputTokens applies equality check predicate on the "input_tokens" field. It's identical to InputTokensEQ.
+func InputTokens(v int64) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldEQ(FieldInputTokens, v))
+}
+
+// OutputTokens applies equality check predicate on the "output_tokens" field. It's identical to OutputTokensEQ.
+func OutputTokens(v int64) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldEQ(FieldOutputTokens, v))
+}
+
+// Cost applies equality check predicate on the "cost" field. It's identical to CostEQ.
+func Cost(v int64) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldEQ(FieldCost, v))
+}
+
+// RequestTime applies equality check predicate on the "request_time" field. It's identical to RequestTimeEQ.
+func RequestTime(v time.Time) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldEQ(FieldRequestTime, v))
+}
+
+// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
+func CreatedAt(v time.Time) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldEQ(FieldCreatedAt, v))
+}
+
+// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
+func UpdatedAt(v time.Time) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldEQ(FieldUpdatedAt, v))
+}
+
+// TenantIDEQ applies the EQ predicate on the "tenant_id" field.
+func TenantIDEQ(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldEQ(FieldTenantID, v))
+}
+
+// TenantIDNEQ applies the NEQ predicate on the "tenant_id" field.
+func TenantIDNEQ(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldNEQ(FieldTenantID, v))
+}
+
+// TenantIDIn applies the In predicate on the "tenant_id" field.
+func TenantIDIn(vs ...string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldIn(FieldTenantID, vs...))
+}
+
+// TenantIDNotIn applies the NotIn predicate on the "tenant_id" field.
+func TenantIDNotIn(vs ...string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldNotIn(FieldTenantID, vs...))
+}
+
+// TenantIDGT applies the GT predicate on the "tenant_id" field.
+func TenantIDGT(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldGT(FieldTenantID, v))
+}
+
+// TenantIDGTE applies the GTE predicate on the "tenant_id" field.
+func TenantIDGTE(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldGTE(FieldTenantID, v))
+}
+
+// TenantIDLT applies the LT predicate on the "tenant_id" field.
+func TenantIDLT(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldLT(FieldTenantID, v))
+}
+
+// TenantIDLTE applies the LTE predicate on the "tenant_id" field.
+func TenantIDLTE(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldLTE(FieldTenantID, v))
+}
+
+// TenantIDContains applies the Contains predicate on the "tenant_id" field.
+func TenantIDContains(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldContains(FieldTenantID, v))
+}
+
+// TenantIDHasPrefix applies the HasPrefix predicate on the "tenant_id" field.
+func TenantIDHasPrefix(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldHasPrefix(FieldTenantID, v))
+}
+
+// TenantIDHasSuffix applies the HasSuffix predicate on the "tenant_id" field.
+func TenantIDHasSuffix(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldHasSuffix(FieldTenantID, v))
+}
+
+// TenantIDEqualFold applies the EqualFold predicate on the "tenant_id" field.
+func TenantIDEqualFold(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldEqualFold(FieldTenantID, v))
+}
+
+// TenantIDContainsFold applies the ContainsFold predicate on the "tenant_id" field.
+func TenantIDContainsFold(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldContainsFold(FieldTenantID, v))
+}
+
+// UserIDEQ applies the EQ predicate on the "user_id" field.
+func UserIDEQ(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldEQ(FieldUserID, v))
+}
+
+// UserIDNEQ applies the NEQ predicate on the "user_id" field.
+func UserIDNEQ(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldNEQ(FieldUserID, v))
+}
+
+// UserIDIn applies the In predicate on the "user_id" field.
+func UserIDIn(vs ...string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldIn(FieldUserID, vs...))
+}
+
+// UserIDNotIn applies the NotIn predicate on the "user_id" field.
+func UserIDNotIn(vs ...string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldNotIn(FieldUserID, vs...))
+}
+
+// UserIDGT applies the GT predicate on the "user_id" field.
+func UserIDGT(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldGT(FieldUserID, v))
+}
+
+// UserIDGTE applies the GTE predicate on the "user_id" field.
+func UserIDGTE(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldGTE(FieldUserID, v))
+}
+
+// UserIDLT applies the LT predicate on the "user_id" field.
+func UserIDLT(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldLT(FieldUserID, v))
+}
+
+// UserIDLTE applies the LTE predicate on the "user_id" field.
+func UserIDLTE(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldLTE(FieldUserID, v))
+}
+
+// UserIDContains applies the Contains predicate on the "user_id" field.
+func UserIDContains(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldContains(FieldUserID, v))
+}
+
+// UserIDHasPrefix applies the HasPrefix predicate on the "user_id" field.
+func UserIDHasPrefix(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldHasPrefix(FieldUserID, v))
+}
+
+// UserIDHasSuffix applies the HasSuffix predicate on the "user_id" field.
+func UserIDHasSuffix(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldHasSuffix(FieldUserID, v))
+}
+
+// UserIDEqualFold applies the EqualFold predicate on the "user_id" field.
+func UserIDEqualFold(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldEqualFold(FieldUserID, v))
+}
+
+// UserIDContainsFold applies the ContainsFold predicate on the "user_id" field.
+func UserIDContainsFold(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldContainsFold(FieldUserID, v))
+}
+
+// ModelEQ applies the EQ predicate on the "model" field.
+func ModelEQ(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldEQ(FieldModel, v))
+}
+
+// ModelNEQ applies the NEQ predicate on the "model" field.
+func ModelNEQ(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldNEQ(FieldModel, v))
+}
+
+// ModelIn applies the In predicate on the "model" field.
+func ModelIn(vs ...string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldIn(FieldModel, vs...))
+}
+
+// ModelNotIn applies the NotIn predicate on the "model" field.
+func ModelNotIn(vs ...string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldNotIn(FieldModel, vs...))
+}
+
+// ModelGT applies the GT predicate on the "model" field.
+func ModelGT(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldGT(FieldModel, v))
+}
+
+// ModelGTE applies the GTE predicate on the "model" field.
+func ModelGTE(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldGTE(FieldModel, v))
+}
+
+// ModelLT applies the LT predicate on the "model" field.
+func ModelLT(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldLT(FieldModel, v))
+}
+
+// ModelLTE applies the LTE predicate on the "model" field.
+func ModelLTE(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldLTE(FieldModel, v))
+}
+
+// ModelContains applies the Contains predicate on the "model" field.
+func ModelContains(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldContains(FieldModel, v))
+}
+
+// ModelHasPrefix applies the HasPrefix predicate on the "model" field.
+func ModelHasPrefix(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldHasPrefix(FieldModel, v))
+}
+
+// ModelHasSuffix applies the HasSuffix predicate on the "model" field.
+func ModelHasSuffix(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldHasSuffix(FieldModel, v))
+}
+
+// ModelEqualFold applies the EqualFold predicate on the "model" field.
+func ModelEqualFold(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldEqualFold(FieldModel, v))
+}
+
+// ModelContainsFold applies the ContainsFold predicate on the "model" field.
+func ModelContainsFold(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldContainsFold(FieldModel, v))
+}
+
+// OperationEQ applies the EQ predicate on the "operation" field.
+func OperationEQ(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldEQ(FieldOperation, v))
+}
+
+// OperationNEQ applies the NEQ predicate on the "operation" field.
+func OperationNEQ(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldNEQ(FieldOperation, v))
+}
+
+// OperationIn applies the In predicate on the "operation" field.
+func OperationIn(vs ...string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldIn(FieldOperation, vs...))
+}
+
+// OperationNotIn applies the NotIn predicate on the "operation" field.
+func OperationNotIn(vs ...string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldNotIn(FieldOperation, vs...))
+}
+
+// OperationGT applies the GT predicate on the "operation" field.
+func OperationGT(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldGT(FieldOperation, v))
+}
+
+// OperationGTE applies the GTE predicate on the "operation" field.
+func OperationGTE(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldGTE(FieldOperation, v))
+}
+
+// OperationLT applies the LT predicate on the "operation" field.
+func OperationLT(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldLT(FieldOperation, v))
+}
+
+// OperationLTE applies the LTE predicate on the "operation" field.
+func OperationLTE(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldLTE(FieldOperation, v))
+}
+
+// OperationContains applies the Contains predicate on the "operation" field.
+func OperationContains(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldContains(FieldOperation, v))
+}
+
+// OperationHasPrefix applies the HasPrefix predicate on the "operation" field.
+func OperationHasPrefix(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldHasPrefix(FieldOperation, v))
+}
+
+// OperationHasSuffix applies the HasSuffix predicate on the "operation" field.
+func OperationHasSuffix(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldHasSuffix(FieldOperation, v))
+}
+
+// OperationEqualFold applies the EqualFold predicate on the "operation" field.
+func OperationEqualFold(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldEqualFold(FieldOperation, v))
+}
+
+// OperationContainsFold applies the ContainsFold predicate on the "operation" field.
+func OperationContainsFold(v string) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldContainsFold(FieldOperation, v))
+}
+
+// InputTokensEQ applies the EQ predicate on the "input_tokens" field.
+func InputTokensEQ(v int64) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldEQ(FieldInputTokens, v))
+}
+
+// InputTokensNEQ applies the NEQ predicate on the "input_tokens" field.
+func InputTokensNEQ(v int64) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldNEQ(FieldInputTokens, v))
+}
+
+// InputTokensIn applies the In predicate on the "input_tokens" field.
+func InputTokensIn(vs ...int64) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldIn(FieldInputTokens, vs...))
+}
+
+// InputTokensNotIn applies the NotIn predicate on the "input_tokens" field.
+func InputTokensNotIn(vs ...int64) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldNotIn(FieldInputTokens, vs...))
+}
+
+// InputTokensGT applies the GT predicate on the "input_tokens" field.
+func InputTokensGT(v int64) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldGT(FieldInputTokens, v))
+}
+
+// InputTokensGTE applies the GTE predicate on the "input_tokens" field.
+func InputTokensGTE(v int64) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldGTE(FieldInputTokens, v))
+}
+
+// InputTokensLT applies the LT predicate on the "input_tokens" field.
+func InputTokensLT(v int64) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldLT(FieldInputTokens, v))
+}
+
+// InputTokensLTE applies the LTE predicate on the "input_tokens" field.
+func InputTokensLTE(v int64) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldLTE(FieldInputTokens, v))
+}
+
+// OutputTokensEQ applies the EQ predicate on the "output_tokens" field.
+func OutputTokensEQ(v int64) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldEQ(FieldOutputTokens, v))
+}
+
+// OutputTokensNEQ applies the NEQ predicate on the "output_tokens" field.
+func OutputTokensNEQ(v int64) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldNEQ(FieldOutputTokens, v))
+}
+
+// OutputTokensIn applies the In predicate on the "output_tokens" field.
+func OutputTokensIn(vs ...int64) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldIn(FieldOutputTokens, vs...))
+}
+
+// OutputTokensNotIn applies the NotIn predicate on the "output_tokens" field.
+func OutputTokensNotIn(vs ...int64) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldNotIn(FieldOutputTokens, vs...))
+}
+
+// OutputTokensGT applies the GT predicate on the "output_tokens" field.
+func OutputTokensGT(v int64) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldGT(FieldOutputTokens, v))
+}
+
+// OutputTokensGTE applies the GTE predicate on the "output_tokens" field.
+func OutputTokensGTE(v int64) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldGTE(FieldOutputTokens, v))
+}
+
+// OutputTokensLT applies the LT predicate on the "output_tokens" field.
+func OutputTokensLT(v int64) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldLT(FieldOutputTokens, v))
+}
+
+// OutputTokensLTE applies the LTE predicate on the "output_tokens" field.
+func OutputTokensLTE(v int64) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldLTE(FieldOutputTokens, v))
+}
+
+// CostEQ applies the EQ predicate on the "cost" field.
+func CostEQ(v int64) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldEQ(FieldCost, v))
+}
+
+// CostNEQ applies the NEQ predicate on the "cost" field.
+func CostNEQ(v int64) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldNEQ(FieldCost, v))
+}
+
+// CostIn applies the In predicate on the "cost" field.
+func CostIn(vs ...int64) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldIn(FieldCost, vs...))
+}
+
+// CostNotIn applies the NotIn predicate on the "cost" field.
+func CostNotIn(vs ...int64) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldNotIn(FieldCost, vs...))
+}
+
+// CostGT applies the GT predicate on the "cost" field.
+func CostGT(v int64) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldGT(FieldCost, v))
+}
+
+// CostGTE applies the GTE predicate on the "cost" field.
+func CostGTE(v int64) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldGTE(FieldCost, v))
+}
+
+// CostLT applies the LT predicate on the "cost" field.
+func CostLT(v int64) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldLT(FieldCost, v))
+}
+
+// CostLTE applies the LTE predicate on the "cost" field.
+func CostLTE(v int64) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldLTE(FieldCost, v))
+}
+
+// RequestTimeEQ applies the EQ predicate on the "request_time" field.
+func RequestTimeEQ(v time.Time) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldEQ(FieldRequestTime, v))
+}
+
+// RequestTimeNEQ applies the NEQ predicate on the "request_time" field.
+func RequestTimeNEQ(v time.Time) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldNEQ(FieldRequestTime, v))
+}
+
+// RequestTimeIn applies the In predicate on the "request_time" field.
+func RequestTimeIn(vs ...time.Time) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldIn(FieldRequestTime, vs...))
+}
+
+// RequestTimeNotIn applies the NotIn predicate on the "request_time" field.
+func RequestTimeNotIn(vs ...time.Time) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldNotIn(FieldRequestTime, vs...))
+}
+
+// RequestTimeGT applies the GT predicate on the "request_time" field.
+func RequestTimeGT(v time.Time) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldGT(FieldRequestTime, v))
+}
+
+// RequestTimeGTE applies the GTE predicate on the "request_time" field.
+func RequestTimeGTE(v time.Time) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldGTE(FieldRequestTime, v))
+}
+
+// RequestTimeLT applies the LT predicate on the "request_time" field.
+func RequestTimeLT(v time.Time) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldLT(FieldRequestTime, v))
+}
+
+// RequestTimeLTE applies the LTE predicate on the "request_time" field.
+func RequestTimeLTE(v time.Time) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldLTE(FieldRequestTime, v))
+}
+
+// CreatedAtEQ applies the EQ predicate on the "created_at" field.
+func CreatedAtEQ(v time.Time) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldEQ(FieldCreatedAt, v))
+}
+
+// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
+func CreatedAtNEQ(v time.Time) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldNEQ(FieldCreatedAt, v))
+}
+
+// CreatedAtIn applies the In predicate on the "created_at" field.
+func CreatedAtIn(vs ...time.Time) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldIn(FieldCreatedAt, vs...))
+}
+
+// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
+func CreatedAtNotIn(vs ...time.Time) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldNotIn(FieldCreatedAt, vs...))
+}
+
+// CreatedAtGT applies the GT predicate on the "created_at" field.
+func CreatedAtGT(v time.Time) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldGT(FieldCreatedAt, v))
+}
+
+// CreatedAtGTE applies the GTE predicate on the "created_at" field.
+func CreatedAtGTE(v time.Time) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldGTE(FieldCreatedAt, v))
+}
+
+// CreatedAtLT applies the LT predicate on the "created_at" field.
+func CreatedAtLT(v time.Time) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldLT(FieldCreatedAt, v))
+}
+
+// CreatedAtLTE applies the LTE predicate on the "created_at" field.
+func CreatedAtLTE(v time.Time) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldLTE(FieldCreatedAt, v))
+}
+
+// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
+func UpdatedAtEQ(v time.Time) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldEQ(FieldUpdatedAt, v))
+}
+
+// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
+func UpdatedAtNEQ(v time.Time) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldNEQ(FieldUpdatedAt, v))
+}
+
+// UpdatedAtIn applies the In predicate on the "updated_at" field.
+func UpdatedAtIn(vs ...time.Time) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldIn(FieldUpdatedAt, vs...))
+}
+
+// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
+func UpdatedAtNotIn(vs ...time.Time) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldNotIn(FieldUpdatedAt, vs...))
+}
+
+// UpdatedAtGT applies the GT predicate on the "updated_at" field.
+func UpdatedAtGT(v time.Time) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldGT(FieldUpdatedAt, v))
+}
+
+// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
+func UpdatedAtGTE(v time.Time) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldGTE(FieldUpdatedAt, v))
+}
+
+// UpdatedAtLT applies the LT predicate on the "updated_at" field.
+func UpdatedAtLT(v time.Time) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldLT(FieldUpdatedAt, v))
+}
+
+// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
+func UpdatedAtLTE(v time.Time) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.FieldLTE(FieldUpdatedAt, v))
+}
+
+// And groups predicates with the AND operator between them.
+func And(predicates ...predicate.BillingRecord) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.AndPredicates(predicates...))
+}
+
+// Or groups predicates with the OR operator between them.
+func Or(predicates ...predicate.BillingRecord) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.OrPredicates(predicates...))
+}
+
+// Not applies the not operator on the given predicate.
+func Not(p predicate.BillingRecord) predicate.BillingRecord {
+ return predicate.BillingRecord(sql.NotPredicates(p))
+}
diff --git a/backend/db/billingrecord_create.go b/backend/db/billingrecord_create.go
new file mode 100644
index 0000000..b33b3ba
--- /dev/null
+++ b/backend/db/billingrecord_create.go
@@ -0,0 +1,1122 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "time"
+
+ "entgo.io/ent/dialect"
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/billingrecord"
+)
+
+// BillingRecordCreate is the builder for creating a BillingRecord entity.
+type BillingRecordCreate struct {
+ config
+ mutation *BillingRecordMutation
+ hooks []Hook
+ conflict []sql.ConflictOption
+}
+
+// SetTenantID sets the "tenant_id" field.
+func (brc *BillingRecordCreate) SetTenantID(s string) *BillingRecordCreate {
+ brc.mutation.SetTenantID(s)
+ return brc
+}
+
+// SetUserID sets the "user_id" field.
+func (brc *BillingRecordCreate) SetUserID(s string) *BillingRecordCreate {
+ brc.mutation.SetUserID(s)
+ return brc
+}
+
+// SetModel sets the "model" field.
+func (brc *BillingRecordCreate) SetModel(s string) *BillingRecordCreate {
+ brc.mutation.SetModel(s)
+ return brc
+}
+
+// SetOperation sets the "operation" field.
+func (brc *BillingRecordCreate) SetOperation(s string) *BillingRecordCreate {
+ brc.mutation.SetOperation(s)
+ return brc
+}
+
+// SetInputTokens sets the "input_tokens" field.
+func (brc *BillingRecordCreate) SetInputTokens(i int64) *BillingRecordCreate {
+ brc.mutation.SetInputTokens(i)
+ return brc
+}
+
+// SetOutputTokens sets the "output_tokens" field.
+func (brc *BillingRecordCreate) SetOutputTokens(i int64) *BillingRecordCreate {
+ brc.mutation.SetOutputTokens(i)
+ return brc
+}
+
+// SetCost sets the "cost" field.
+func (brc *BillingRecordCreate) SetCost(i int64) *BillingRecordCreate {
+ brc.mutation.SetCost(i)
+ return brc
+}
+
+// SetRequestTime sets the "request_time" field.
+func (brc *BillingRecordCreate) SetRequestTime(t time.Time) *BillingRecordCreate {
+ brc.mutation.SetRequestTime(t)
+ return brc
+}
+
+// SetNillableRequestTime sets the "request_time" field if the given value is not nil.
+func (brc *BillingRecordCreate) SetNillableRequestTime(t *time.Time) *BillingRecordCreate {
+ if t != nil {
+ brc.SetRequestTime(*t)
+ }
+ return brc
+}
+
+// SetMetadata sets the "metadata" field.
+func (brc *BillingRecordCreate) SetMetadata(m map[string]interface{}) *BillingRecordCreate {
+ brc.mutation.SetMetadata(m)
+ return brc
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (brc *BillingRecordCreate) SetCreatedAt(t time.Time) *BillingRecordCreate {
+ brc.mutation.SetCreatedAt(t)
+ return brc
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (brc *BillingRecordCreate) SetNillableCreatedAt(t *time.Time) *BillingRecordCreate {
+ if t != nil {
+ brc.SetCreatedAt(*t)
+ }
+ return brc
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (brc *BillingRecordCreate) SetUpdatedAt(t time.Time) *BillingRecordCreate {
+ brc.mutation.SetUpdatedAt(t)
+ return brc
+}
+
+// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
+func (brc *BillingRecordCreate) SetNillableUpdatedAt(t *time.Time) *BillingRecordCreate {
+ if t != nil {
+ brc.SetUpdatedAt(*t)
+ }
+ return brc
+}
+
+// SetID sets the "id" field.
+func (brc *BillingRecordCreate) SetID(s string) *BillingRecordCreate {
+ brc.mutation.SetID(s)
+ return brc
+}
+
+// Mutation returns the BillingRecordMutation object of the builder.
+func (brc *BillingRecordCreate) Mutation() *BillingRecordMutation {
+ return brc.mutation
+}
+
+// Save creates the BillingRecord in the database.
+func (brc *BillingRecordCreate) Save(ctx context.Context) (*BillingRecord, error) {
+ brc.defaults()
+ return withHooks(ctx, brc.sqlSave, brc.mutation, brc.hooks)
+}
+
+// SaveX calls Save and panics if Save returns an error.
+func (brc *BillingRecordCreate) SaveX(ctx context.Context) *BillingRecord {
+ v, err := brc.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return v
+}
+
+// Exec executes the query.
+func (brc *BillingRecordCreate) Exec(ctx context.Context) error {
+ _, err := brc.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (brc *BillingRecordCreate) ExecX(ctx context.Context) {
+ if err := brc.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// defaults sets the default values of the builder before save.
+func (brc *BillingRecordCreate) defaults() {
+ if _, ok := brc.mutation.RequestTime(); !ok {
+ v := billingrecord.DefaultRequestTime()
+ brc.mutation.SetRequestTime(v)
+ }
+ if _, ok := brc.mutation.CreatedAt(); !ok {
+ v := billingrecord.DefaultCreatedAt()
+ brc.mutation.SetCreatedAt(v)
+ }
+ if _, ok := brc.mutation.UpdatedAt(); !ok {
+ v := billingrecord.DefaultUpdatedAt()
+ brc.mutation.SetUpdatedAt(v)
+ }
+}
+
+// check runs all checks and user-defined validators on the builder.
+func (brc *BillingRecordCreate) check() error {
+ if _, ok := brc.mutation.TenantID(); !ok {
+ return &ValidationError{Name: "tenant_id", err: errors.New(`db: missing required field "BillingRecord.tenant_id"`)}
+ }
+ if _, ok := brc.mutation.UserID(); !ok {
+ return &ValidationError{Name: "user_id", err: errors.New(`db: missing required field "BillingRecord.user_id"`)}
+ }
+ if _, ok := brc.mutation.Model(); !ok {
+ return &ValidationError{Name: "model", err: errors.New(`db: missing required field "BillingRecord.model"`)}
+ }
+ if _, ok := brc.mutation.Operation(); !ok {
+ return &ValidationError{Name: "operation", err: errors.New(`db: missing required field "BillingRecord.operation"`)}
+ }
+ if _, ok := brc.mutation.InputTokens(); !ok {
+ return &ValidationError{Name: "input_tokens", err: errors.New(`db: missing required field "BillingRecord.input_tokens"`)}
+ }
+ if _, ok := brc.mutation.OutputTokens(); !ok {
+ return &ValidationError{Name: "output_tokens", err: errors.New(`db: missing required field "BillingRecord.output_tokens"`)}
+ }
+ if _, ok := brc.mutation.Cost(); !ok {
+ return &ValidationError{Name: "cost", err: errors.New(`db: missing required field "BillingRecord.cost"`)}
+ }
+ if _, ok := brc.mutation.RequestTime(); !ok {
+ return &ValidationError{Name: "request_time", err: errors.New(`db: missing required field "BillingRecord.request_time"`)}
+ }
+ if _, ok := brc.mutation.Metadata(); !ok {
+ return &ValidationError{Name: "metadata", err: errors.New(`db: missing required field "BillingRecord.metadata"`)}
+ }
+ if _, ok := brc.mutation.CreatedAt(); !ok {
+ return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "BillingRecord.created_at"`)}
+ }
+ if _, ok := brc.mutation.UpdatedAt(); !ok {
+ return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "BillingRecord.updated_at"`)}
+ }
+ return nil
+}
+
+func (brc *BillingRecordCreate) sqlSave(ctx context.Context) (*BillingRecord, error) {
+ if err := brc.check(); err != nil {
+ return nil, err
+ }
+ _node, _spec := brc.createSpec()
+ if err := sqlgraph.CreateNode(ctx, brc.driver, _spec); err != nil {
+ if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return nil, err
+ }
+ if _spec.ID.Value != nil {
+ if id, ok := _spec.ID.Value.(string); ok {
+ _node.ID = id
+ } else {
+ return nil, fmt.Errorf("unexpected BillingRecord.ID type: %T", _spec.ID.Value)
+ }
+ }
+ brc.mutation.id = &_node.ID
+ brc.mutation.done = true
+ return _node, nil
+}
+
+func (brc *BillingRecordCreate) createSpec() (*BillingRecord, *sqlgraph.CreateSpec) {
+ var (
+ _node = &BillingRecord{config: brc.config}
+ _spec = sqlgraph.NewCreateSpec(billingrecord.Table, sqlgraph.NewFieldSpec(billingrecord.FieldID, field.TypeString))
+ )
+ _spec.OnConflict = brc.conflict
+ if id, ok := brc.mutation.ID(); ok {
+ _node.ID = id
+ _spec.ID.Value = id
+ }
+ if value, ok := brc.mutation.TenantID(); ok {
+ _spec.SetField(billingrecord.FieldTenantID, field.TypeString, value)
+ _node.TenantID = value
+ }
+ if value, ok := brc.mutation.UserID(); ok {
+ _spec.SetField(billingrecord.FieldUserID, field.TypeString, value)
+ _node.UserID = value
+ }
+ if value, ok := brc.mutation.Model(); ok {
+ _spec.SetField(billingrecord.FieldModel, field.TypeString, value)
+ _node.Model = value
+ }
+ if value, ok := brc.mutation.Operation(); ok {
+ _spec.SetField(billingrecord.FieldOperation, field.TypeString, value)
+ _node.Operation = value
+ }
+ if value, ok := brc.mutation.InputTokens(); ok {
+ _spec.SetField(billingrecord.FieldInputTokens, field.TypeInt64, value)
+ _node.InputTokens = value
+ }
+ if value, ok := brc.mutation.OutputTokens(); ok {
+ _spec.SetField(billingrecord.FieldOutputTokens, field.TypeInt64, value)
+ _node.OutputTokens = value
+ }
+ if value, ok := brc.mutation.Cost(); ok {
+ _spec.SetField(billingrecord.FieldCost, field.TypeInt64, value)
+ _node.Cost = value
+ }
+ if value, ok := brc.mutation.RequestTime(); ok {
+ _spec.SetField(billingrecord.FieldRequestTime, field.TypeTime, value)
+ _node.RequestTime = value
+ }
+ if value, ok := brc.mutation.Metadata(); ok {
+ _spec.SetField(billingrecord.FieldMetadata, field.TypeJSON, value)
+ _node.Metadata = value
+ }
+ if value, ok := brc.mutation.CreatedAt(); ok {
+ _spec.SetField(billingrecord.FieldCreatedAt, field.TypeTime, value)
+ _node.CreatedAt = value
+ }
+ if value, ok := brc.mutation.UpdatedAt(); ok {
+ _spec.SetField(billingrecord.FieldUpdatedAt, field.TypeTime, value)
+ _node.UpdatedAt = value
+ }
+ return _node, _spec
+}
+
+// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
+// of the `INSERT` statement. For example:
+//
+// client.BillingRecord.Create().
+// SetTenantID(v).
+// OnConflict(
+// // Update the row with the new values
+// // the was proposed for insertion.
+// sql.ResolveWithNewValues(),
+// ).
+// // Override some of the fields with custom
+// // update values.
+// Update(func(u *ent.BillingRecordUpsert) {
+// SetTenantID(v+v).
+// }).
+// Exec(ctx)
+func (brc *BillingRecordCreate) OnConflict(opts ...sql.ConflictOption) *BillingRecordUpsertOne {
+ brc.conflict = opts
+ return &BillingRecordUpsertOne{
+ create: brc,
+ }
+}
+
+// OnConflictColumns calls `OnConflict` and configures the columns
+// as conflict target. Using this option is equivalent to using:
+//
+// client.BillingRecord.Create().
+// OnConflict(sql.ConflictColumns(columns...)).
+// Exec(ctx)
+func (brc *BillingRecordCreate) OnConflictColumns(columns ...string) *BillingRecordUpsertOne {
+ brc.conflict = append(brc.conflict, sql.ConflictColumns(columns...))
+ return &BillingRecordUpsertOne{
+ create: brc,
+ }
+}
+
+type (
+ // BillingRecordUpsertOne is the builder for "upsert"-ing
+ // one BillingRecord node.
+ BillingRecordUpsertOne struct {
+ create *BillingRecordCreate
+ }
+
+ // BillingRecordUpsert is the "OnConflict" setter.
+ BillingRecordUpsert struct {
+ *sql.UpdateSet
+ }
+)
+
+// SetTenantID sets the "tenant_id" field.
+func (u *BillingRecordUpsert) SetTenantID(v string) *BillingRecordUpsert {
+ u.Set(billingrecord.FieldTenantID, v)
+ return u
+}
+
+// UpdateTenantID sets the "tenant_id" field to the value that was provided on create.
+func (u *BillingRecordUpsert) UpdateTenantID() *BillingRecordUpsert {
+ u.SetExcluded(billingrecord.FieldTenantID)
+ return u
+}
+
+// SetUserID sets the "user_id" field.
+func (u *BillingRecordUpsert) SetUserID(v string) *BillingRecordUpsert {
+ u.Set(billingrecord.FieldUserID, v)
+ return u
+}
+
+// UpdateUserID sets the "user_id" field to the value that was provided on create.
+func (u *BillingRecordUpsert) UpdateUserID() *BillingRecordUpsert {
+ u.SetExcluded(billingrecord.FieldUserID)
+ return u
+}
+
+// SetModel sets the "model" field.
+func (u *BillingRecordUpsert) SetModel(v string) *BillingRecordUpsert {
+ u.Set(billingrecord.FieldModel, v)
+ return u
+}
+
+// UpdateModel sets the "model" field to the value that was provided on create.
+func (u *BillingRecordUpsert) UpdateModel() *BillingRecordUpsert {
+ u.SetExcluded(billingrecord.FieldModel)
+ return u
+}
+
+// SetOperation sets the "operation" field.
+func (u *BillingRecordUpsert) SetOperation(v string) *BillingRecordUpsert {
+ u.Set(billingrecord.FieldOperation, v)
+ return u
+}
+
+// UpdateOperation sets the "operation" field to the value that was provided on create.
+func (u *BillingRecordUpsert) UpdateOperation() *BillingRecordUpsert {
+ u.SetExcluded(billingrecord.FieldOperation)
+ return u
+}
+
+// SetInputTokens sets the "input_tokens" field.
+func (u *BillingRecordUpsert) SetInputTokens(v int64) *BillingRecordUpsert {
+ u.Set(billingrecord.FieldInputTokens, v)
+ return u
+}
+
+// UpdateInputTokens sets the "input_tokens" field to the value that was provided on create.
+func (u *BillingRecordUpsert) UpdateInputTokens() *BillingRecordUpsert {
+ u.SetExcluded(billingrecord.FieldInputTokens)
+ return u
+}
+
+// AddInputTokens adds v to the "input_tokens" field.
+func (u *BillingRecordUpsert) AddInputTokens(v int64) *BillingRecordUpsert {
+ u.Add(billingrecord.FieldInputTokens, v)
+ return u
+}
+
+// SetOutputTokens sets the "output_tokens" field.
+func (u *BillingRecordUpsert) SetOutputTokens(v int64) *BillingRecordUpsert {
+ u.Set(billingrecord.FieldOutputTokens, v)
+ return u
+}
+
+// UpdateOutputTokens sets the "output_tokens" field to the value that was provided on create.
+func (u *BillingRecordUpsert) UpdateOutputTokens() *BillingRecordUpsert {
+ u.SetExcluded(billingrecord.FieldOutputTokens)
+ return u
+}
+
+// AddOutputTokens adds v to the "output_tokens" field.
+func (u *BillingRecordUpsert) AddOutputTokens(v int64) *BillingRecordUpsert {
+ u.Add(billingrecord.FieldOutputTokens, v)
+ return u
+}
+
+// SetCost sets the "cost" field.
+func (u *BillingRecordUpsert) SetCost(v int64) *BillingRecordUpsert {
+ u.Set(billingrecord.FieldCost, v)
+ return u
+}
+
+// UpdateCost sets the "cost" field to the value that was provided on create.
+func (u *BillingRecordUpsert) UpdateCost() *BillingRecordUpsert {
+ u.SetExcluded(billingrecord.FieldCost)
+ return u
+}
+
+// AddCost adds v to the "cost" field.
+func (u *BillingRecordUpsert) AddCost(v int64) *BillingRecordUpsert {
+ u.Add(billingrecord.FieldCost, v)
+ return u
+}
+
+// SetRequestTime sets the "request_time" field.
+func (u *BillingRecordUpsert) SetRequestTime(v time.Time) *BillingRecordUpsert {
+ u.Set(billingrecord.FieldRequestTime, v)
+ return u
+}
+
+// UpdateRequestTime sets the "request_time" field to the value that was provided on create.
+func (u *BillingRecordUpsert) UpdateRequestTime() *BillingRecordUpsert {
+ u.SetExcluded(billingrecord.FieldRequestTime)
+ return u
+}
+
+// SetMetadata sets the "metadata" field.
+func (u *BillingRecordUpsert) SetMetadata(v map[string]interface{}) *BillingRecordUpsert {
+ u.Set(billingrecord.FieldMetadata, v)
+ return u
+}
+
+// UpdateMetadata sets the "metadata" field to the value that was provided on create.
+func (u *BillingRecordUpsert) UpdateMetadata() *BillingRecordUpsert {
+ u.SetExcluded(billingrecord.FieldMetadata)
+ return u
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (u *BillingRecordUpsert) SetCreatedAt(v time.Time) *BillingRecordUpsert {
+ u.Set(billingrecord.FieldCreatedAt, v)
+ return u
+}
+
+// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
+func (u *BillingRecordUpsert) UpdateCreatedAt() *BillingRecordUpsert {
+ u.SetExcluded(billingrecord.FieldCreatedAt)
+ return u
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (u *BillingRecordUpsert) SetUpdatedAt(v time.Time) *BillingRecordUpsert {
+ u.Set(billingrecord.FieldUpdatedAt, v)
+ return u
+}
+
+// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
+func (u *BillingRecordUpsert) UpdateUpdatedAt() *BillingRecordUpsert {
+ u.SetExcluded(billingrecord.FieldUpdatedAt)
+ return u
+}
+
+// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field.
+// Using this option is equivalent to using:
+//
+// client.BillingRecord.Create().
+// OnConflict(
+// sql.ResolveWithNewValues(),
+// sql.ResolveWith(func(u *sql.UpdateSet) {
+// u.SetIgnore(billingrecord.FieldID)
+// }),
+// ).
+// Exec(ctx)
+func (u *BillingRecordUpsertOne) UpdateNewValues() *BillingRecordUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
+ if _, exists := u.create.mutation.ID(); exists {
+ s.SetIgnore(billingrecord.FieldID)
+ }
+ }))
+ return u
+}
+
+// Ignore sets each column to itself in case of conflict.
+// Using this option is equivalent to using:
+//
+// client.BillingRecord.Create().
+// OnConflict(sql.ResolveWithIgnore()).
+// Exec(ctx)
+func (u *BillingRecordUpsertOne) Ignore() *BillingRecordUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
+ return u
+}
+
+// DoNothing configures the conflict_action to `DO NOTHING`.
+// Supported only by SQLite and PostgreSQL.
+func (u *BillingRecordUpsertOne) DoNothing() *BillingRecordUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.DoNothing())
+ return u
+}
+
+// Update allows overriding fields `UPDATE` values. See the BillingRecordCreate.OnConflict
+// documentation for more info.
+func (u *BillingRecordUpsertOne) Update(set func(*BillingRecordUpsert)) *BillingRecordUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
+ set(&BillingRecordUpsert{UpdateSet: update})
+ }))
+ return u
+}
+
+// SetTenantID sets the "tenant_id" field.
+func (u *BillingRecordUpsertOne) SetTenantID(v string) *BillingRecordUpsertOne {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.SetTenantID(v)
+ })
+}
+
+// UpdateTenantID sets the "tenant_id" field to the value that was provided on create.
+func (u *BillingRecordUpsertOne) UpdateTenantID() *BillingRecordUpsertOne {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.UpdateTenantID()
+ })
+}
+
+// SetUserID sets the "user_id" field.
+func (u *BillingRecordUpsertOne) SetUserID(v string) *BillingRecordUpsertOne {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.SetUserID(v)
+ })
+}
+
+// UpdateUserID sets the "user_id" field to the value that was provided on create.
+func (u *BillingRecordUpsertOne) UpdateUserID() *BillingRecordUpsertOne {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.UpdateUserID()
+ })
+}
+
+// SetModel sets the "model" field.
+func (u *BillingRecordUpsertOne) SetModel(v string) *BillingRecordUpsertOne {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.SetModel(v)
+ })
+}
+
+// UpdateModel sets the "model" field to the value that was provided on create.
+func (u *BillingRecordUpsertOne) UpdateModel() *BillingRecordUpsertOne {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.UpdateModel()
+ })
+}
+
+// SetOperation sets the "operation" field.
+func (u *BillingRecordUpsertOne) SetOperation(v string) *BillingRecordUpsertOne {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.SetOperation(v)
+ })
+}
+
+// UpdateOperation sets the "operation" field to the value that was provided on create.
+func (u *BillingRecordUpsertOne) UpdateOperation() *BillingRecordUpsertOne {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.UpdateOperation()
+ })
+}
+
+// SetInputTokens sets the "input_tokens" field.
+func (u *BillingRecordUpsertOne) SetInputTokens(v int64) *BillingRecordUpsertOne {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.SetInputTokens(v)
+ })
+}
+
+// AddInputTokens adds v to the "input_tokens" field.
+func (u *BillingRecordUpsertOne) AddInputTokens(v int64) *BillingRecordUpsertOne {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.AddInputTokens(v)
+ })
+}
+
+// UpdateInputTokens sets the "input_tokens" field to the value that was provided on create.
+func (u *BillingRecordUpsertOne) UpdateInputTokens() *BillingRecordUpsertOne {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.UpdateInputTokens()
+ })
+}
+
+// SetOutputTokens sets the "output_tokens" field.
+func (u *BillingRecordUpsertOne) SetOutputTokens(v int64) *BillingRecordUpsertOne {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.SetOutputTokens(v)
+ })
+}
+
+// AddOutputTokens adds v to the "output_tokens" field.
+func (u *BillingRecordUpsertOne) AddOutputTokens(v int64) *BillingRecordUpsertOne {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.AddOutputTokens(v)
+ })
+}
+
+// UpdateOutputTokens sets the "output_tokens" field to the value that was provided on create.
+func (u *BillingRecordUpsertOne) UpdateOutputTokens() *BillingRecordUpsertOne {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.UpdateOutputTokens()
+ })
+}
+
+// SetCost sets the "cost" field.
+func (u *BillingRecordUpsertOne) SetCost(v int64) *BillingRecordUpsertOne {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.SetCost(v)
+ })
+}
+
+// AddCost adds v to the "cost" field.
+func (u *BillingRecordUpsertOne) AddCost(v int64) *BillingRecordUpsertOne {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.AddCost(v)
+ })
+}
+
+// UpdateCost sets the "cost" field to the value that was provided on create.
+func (u *BillingRecordUpsertOne) UpdateCost() *BillingRecordUpsertOne {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.UpdateCost()
+ })
+}
+
+// SetRequestTime sets the "request_time" field.
+func (u *BillingRecordUpsertOne) SetRequestTime(v time.Time) *BillingRecordUpsertOne {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.SetRequestTime(v)
+ })
+}
+
+// UpdateRequestTime sets the "request_time" field to the value that was provided on create.
+func (u *BillingRecordUpsertOne) UpdateRequestTime() *BillingRecordUpsertOne {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.UpdateRequestTime()
+ })
+}
+
+// SetMetadata sets the "metadata" field.
+func (u *BillingRecordUpsertOne) SetMetadata(v map[string]interface{}) *BillingRecordUpsertOne {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.SetMetadata(v)
+ })
+}
+
+// UpdateMetadata sets the "metadata" field to the value that was provided on create.
+func (u *BillingRecordUpsertOne) UpdateMetadata() *BillingRecordUpsertOne {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.UpdateMetadata()
+ })
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (u *BillingRecordUpsertOne) SetCreatedAt(v time.Time) *BillingRecordUpsertOne {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.SetCreatedAt(v)
+ })
+}
+
+// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
+func (u *BillingRecordUpsertOne) UpdateCreatedAt() *BillingRecordUpsertOne {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.UpdateCreatedAt()
+ })
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (u *BillingRecordUpsertOne) SetUpdatedAt(v time.Time) *BillingRecordUpsertOne {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.SetUpdatedAt(v)
+ })
+}
+
+// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
+func (u *BillingRecordUpsertOne) UpdateUpdatedAt() *BillingRecordUpsertOne {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.UpdateUpdatedAt()
+ })
+}
+
+// Exec executes the query.
+func (u *BillingRecordUpsertOne) Exec(ctx context.Context) error {
+ if len(u.create.conflict) == 0 {
+ return errors.New("db: missing options for BillingRecordCreate.OnConflict")
+ }
+ return u.create.Exec(ctx)
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (u *BillingRecordUpsertOne) ExecX(ctx context.Context) {
+ if err := u.create.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// Exec executes the UPSERT query and returns the inserted/updated ID.
+func (u *BillingRecordUpsertOne) ID(ctx context.Context) (id string, err error) {
+ if u.create.driver.Dialect() == dialect.MySQL {
+ // In case of "ON CONFLICT", there is no way to get back non-numeric ID
+ // fields from the database since MySQL does not support the RETURNING clause.
+ return id, errors.New("db: BillingRecordUpsertOne.ID is not supported by MySQL driver. Use BillingRecordUpsertOne.Exec instead")
+ }
+ node, err := u.create.Save(ctx)
+ if err != nil {
+ return id, err
+ }
+ return node.ID, nil
+}
+
+// IDX is like ID, but panics if an error occurs.
+func (u *BillingRecordUpsertOne) IDX(ctx context.Context) string {
+ id, err := u.ID(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return id
+}
+
+// BillingRecordCreateBulk is the builder for creating many BillingRecord entities in bulk.
+type BillingRecordCreateBulk struct {
+ config
+ err error
+ builders []*BillingRecordCreate
+ conflict []sql.ConflictOption
+}
+
+// Save creates the BillingRecord entities in the database.
+func (brcb *BillingRecordCreateBulk) Save(ctx context.Context) ([]*BillingRecord, error) {
+ if brcb.err != nil {
+ return nil, brcb.err
+ }
+ specs := make([]*sqlgraph.CreateSpec, len(brcb.builders))
+ nodes := make([]*BillingRecord, len(brcb.builders))
+ mutators := make([]Mutator, len(brcb.builders))
+ for i := range brcb.builders {
+ func(i int, root context.Context) {
+ builder := brcb.builders[i]
+ builder.defaults()
+ var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
+ mutation, ok := m.(*BillingRecordMutation)
+ if !ok {
+ return nil, fmt.Errorf("unexpected mutation type %T", m)
+ }
+ if err := builder.check(); err != nil {
+ return nil, err
+ }
+ builder.mutation = mutation
+ var err error
+ nodes[i], specs[i] = builder.createSpec()
+ if i < len(mutators)-1 {
+ _, err = mutators[i+1].Mutate(root, brcb.builders[i+1].mutation)
+ } else {
+ spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
+ spec.OnConflict = brcb.conflict
+ // Invoke the actual operation on the latest mutation in the chain.
+ if err = sqlgraph.BatchCreate(ctx, brcb.driver, spec); err != nil {
+ if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ }
+ }
+ if err != nil {
+ return nil, err
+ }
+ mutation.id = &nodes[i].ID
+ mutation.done = true
+ return nodes[i], nil
+ })
+ for i := len(builder.hooks) - 1; i >= 0; i-- {
+ mut = builder.hooks[i](mut)
+ }
+ mutators[i] = mut
+ }(i, ctx)
+ }
+ if len(mutators) > 0 {
+ if _, err := mutators[0].Mutate(ctx, brcb.builders[0].mutation); err != nil {
+ return nil, err
+ }
+ }
+ return nodes, nil
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (brcb *BillingRecordCreateBulk) SaveX(ctx context.Context) []*BillingRecord {
+ v, err := brcb.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return v
+}
+
+// Exec executes the query.
+func (brcb *BillingRecordCreateBulk) Exec(ctx context.Context) error {
+ _, err := brcb.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (brcb *BillingRecordCreateBulk) ExecX(ctx context.Context) {
+ if err := brcb.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
+// of the `INSERT` statement. For example:
+//
+// client.BillingRecord.CreateBulk(builders...).
+// OnConflict(
+// // Update the row with the new values
+// // the was proposed for insertion.
+// sql.ResolveWithNewValues(),
+// ).
+// // Override some of the fields with custom
+// // update values.
+// Update(func(u *ent.BillingRecordUpsert) {
+// SetTenantID(v+v).
+// }).
+// Exec(ctx)
+func (brcb *BillingRecordCreateBulk) OnConflict(opts ...sql.ConflictOption) *BillingRecordUpsertBulk {
+ brcb.conflict = opts
+ return &BillingRecordUpsertBulk{
+ create: brcb,
+ }
+}
+
+// OnConflictColumns calls `OnConflict` and configures the columns
+// as conflict target. Using this option is equivalent to using:
+//
+// client.BillingRecord.Create().
+// OnConflict(sql.ConflictColumns(columns...)).
+// Exec(ctx)
+func (brcb *BillingRecordCreateBulk) OnConflictColumns(columns ...string) *BillingRecordUpsertBulk {
+ brcb.conflict = append(brcb.conflict, sql.ConflictColumns(columns...))
+ return &BillingRecordUpsertBulk{
+ create: brcb,
+ }
+}
+
+// BillingRecordUpsertBulk is the builder for "upsert"-ing
+// a bulk of BillingRecord nodes.
+type BillingRecordUpsertBulk struct {
+ create *BillingRecordCreateBulk
+}
+
+// UpdateNewValues updates the mutable fields using the new values that
+// were set on create. Using this option is equivalent to using:
+//
+// client.BillingRecord.Create().
+// OnConflict(
+// sql.ResolveWithNewValues(),
+// sql.ResolveWith(func(u *sql.UpdateSet) {
+// u.SetIgnore(billingrecord.FieldID)
+// }),
+// ).
+// Exec(ctx)
+func (u *BillingRecordUpsertBulk) UpdateNewValues() *BillingRecordUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
+ for _, b := range u.create.builders {
+ if _, exists := b.mutation.ID(); exists {
+ s.SetIgnore(billingrecord.FieldID)
+ }
+ }
+ }))
+ return u
+}
+
+// Ignore sets each column to itself in case of conflict.
+// Using this option is equivalent to using:
+//
+// client.BillingRecord.Create().
+// OnConflict(sql.ResolveWithIgnore()).
+// Exec(ctx)
+func (u *BillingRecordUpsertBulk) Ignore() *BillingRecordUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
+ return u
+}
+
+// DoNothing configures the conflict_action to `DO NOTHING`.
+// Supported only by SQLite and PostgreSQL.
+func (u *BillingRecordUpsertBulk) DoNothing() *BillingRecordUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.DoNothing())
+ return u
+}
+
+// Update allows overriding fields `UPDATE` values. See the BillingRecordCreateBulk.OnConflict
+// documentation for more info.
+func (u *BillingRecordUpsertBulk) Update(set func(*BillingRecordUpsert)) *BillingRecordUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
+ set(&BillingRecordUpsert{UpdateSet: update})
+ }))
+ return u
+}
+
+// SetTenantID sets the "tenant_id" field.
+func (u *BillingRecordUpsertBulk) SetTenantID(v string) *BillingRecordUpsertBulk {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.SetTenantID(v)
+ })
+}
+
+// UpdateTenantID sets the "tenant_id" field to the value that was provided on create.
+func (u *BillingRecordUpsertBulk) UpdateTenantID() *BillingRecordUpsertBulk {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.UpdateTenantID()
+ })
+}
+
+// SetUserID sets the "user_id" field.
+func (u *BillingRecordUpsertBulk) SetUserID(v string) *BillingRecordUpsertBulk {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.SetUserID(v)
+ })
+}
+
+// UpdateUserID sets the "user_id" field to the value that was provided on create.
+func (u *BillingRecordUpsertBulk) UpdateUserID() *BillingRecordUpsertBulk {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.UpdateUserID()
+ })
+}
+
+// SetModel sets the "model" field.
+func (u *BillingRecordUpsertBulk) SetModel(v string) *BillingRecordUpsertBulk {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.SetModel(v)
+ })
+}
+
+// UpdateModel sets the "model" field to the value that was provided on create.
+func (u *BillingRecordUpsertBulk) UpdateModel() *BillingRecordUpsertBulk {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.UpdateModel()
+ })
+}
+
+// SetOperation sets the "operation" field.
+func (u *BillingRecordUpsertBulk) SetOperation(v string) *BillingRecordUpsertBulk {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.SetOperation(v)
+ })
+}
+
+// UpdateOperation sets the "operation" field to the value that was provided on create.
+func (u *BillingRecordUpsertBulk) UpdateOperation() *BillingRecordUpsertBulk {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.UpdateOperation()
+ })
+}
+
+// SetInputTokens sets the "input_tokens" field.
+func (u *BillingRecordUpsertBulk) SetInputTokens(v int64) *BillingRecordUpsertBulk {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.SetInputTokens(v)
+ })
+}
+
+// AddInputTokens adds v to the "input_tokens" field.
+func (u *BillingRecordUpsertBulk) AddInputTokens(v int64) *BillingRecordUpsertBulk {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.AddInputTokens(v)
+ })
+}
+
+// UpdateInputTokens sets the "input_tokens" field to the value that was provided on create.
+func (u *BillingRecordUpsertBulk) UpdateInputTokens() *BillingRecordUpsertBulk {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.UpdateInputTokens()
+ })
+}
+
+// SetOutputTokens sets the "output_tokens" field.
+func (u *BillingRecordUpsertBulk) SetOutputTokens(v int64) *BillingRecordUpsertBulk {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.SetOutputTokens(v)
+ })
+}
+
+// AddOutputTokens adds v to the "output_tokens" field.
+func (u *BillingRecordUpsertBulk) AddOutputTokens(v int64) *BillingRecordUpsertBulk {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.AddOutputTokens(v)
+ })
+}
+
+// UpdateOutputTokens sets the "output_tokens" field to the value that was provided on create.
+func (u *BillingRecordUpsertBulk) UpdateOutputTokens() *BillingRecordUpsertBulk {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.UpdateOutputTokens()
+ })
+}
+
+// SetCost sets the "cost" field.
+func (u *BillingRecordUpsertBulk) SetCost(v int64) *BillingRecordUpsertBulk {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.SetCost(v)
+ })
+}
+
+// AddCost adds v to the "cost" field.
+func (u *BillingRecordUpsertBulk) AddCost(v int64) *BillingRecordUpsertBulk {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.AddCost(v)
+ })
+}
+
+// UpdateCost sets the "cost" field to the value that was provided on create.
+func (u *BillingRecordUpsertBulk) UpdateCost() *BillingRecordUpsertBulk {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.UpdateCost()
+ })
+}
+
+// SetRequestTime sets the "request_time" field.
+func (u *BillingRecordUpsertBulk) SetRequestTime(v time.Time) *BillingRecordUpsertBulk {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.SetRequestTime(v)
+ })
+}
+
+// UpdateRequestTime sets the "request_time" field to the value that was provided on create.
+func (u *BillingRecordUpsertBulk) UpdateRequestTime() *BillingRecordUpsertBulk {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.UpdateRequestTime()
+ })
+}
+
+// SetMetadata sets the "metadata" field.
+func (u *BillingRecordUpsertBulk) SetMetadata(v map[string]interface{}) *BillingRecordUpsertBulk {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.SetMetadata(v)
+ })
+}
+
+// UpdateMetadata sets the "metadata" field to the value that was provided on create.
+func (u *BillingRecordUpsertBulk) UpdateMetadata() *BillingRecordUpsertBulk {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.UpdateMetadata()
+ })
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (u *BillingRecordUpsertBulk) SetCreatedAt(v time.Time) *BillingRecordUpsertBulk {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.SetCreatedAt(v)
+ })
+}
+
+// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
+func (u *BillingRecordUpsertBulk) UpdateCreatedAt() *BillingRecordUpsertBulk {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.UpdateCreatedAt()
+ })
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (u *BillingRecordUpsertBulk) SetUpdatedAt(v time.Time) *BillingRecordUpsertBulk {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.SetUpdatedAt(v)
+ })
+}
+
+// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
+func (u *BillingRecordUpsertBulk) UpdateUpdatedAt() *BillingRecordUpsertBulk {
+ return u.Update(func(s *BillingRecordUpsert) {
+ s.UpdateUpdatedAt()
+ })
+}
+
+// Exec executes the query.
+func (u *BillingRecordUpsertBulk) Exec(ctx context.Context) error {
+ if u.create.err != nil {
+ return u.create.err
+ }
+ for i, b := range u.create.builders {
+ if len(b.conflict) != 0 {
+ return fmt.Errorf("db: OnConflict was set for builder %d. Set it on the BillingRecordCreateBulk instead", i)
+ }
+ }
+ if len(u.create.conflict) == 0 {
+ return errors.New("db: missing options for BillingRecordCreateBulk.OnConflict")
+ }
+ return u.create.Exec(ctx)
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (u *BillingRecordUpsertBulk) ExecX(ctx context.Context) {
+ if err := u.create.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
diff --git a/backend/db/billingrecord_delete.go b/backend/db/billingrecord_delete.go
new file mode 100644
index 0000000..10489d4
--- /dev/null
+++ b/backend/db/billingrecord_delete.go
@@ -0,0 +1,88 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/billingrecord"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+)
+
+// BillingRecordDelete is the builder for deleting a BillingRecord entity.
+type BillingRecordDelete struct {
+ config
+ hooks []Hook
+ mutation *BillingRecordMutation
+}
+
+// Where appends a list predicates to the BillingRecordDelete builder.
+func (brd *BillingRecordDelete) Where(ps ...predicate.BillingRecord) *BillingRecordDelete {
+ brd.mutation.Where(ps...)
+ return brd
+}
+
+// Exec executes the deletion query and returns how many vertices were deleted.
+func (brd *BillingRecordDelete) Exec(ctx context.Context) (int, error) {
+ return withHooks(ctx, brd.sqlExec, brd.mutation, brd.hooks)
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (brd *BillingRecordDelete) ExecX(ctx context.Context) int {
+ n, err := brd.Exec(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return n
+}
+
+func (brd *BillingRecordDelete) sqlExec(ctx context.Context) (int, error) {
+ _spec := sqlgraph.NewDeleteSpec(billingrecord.Table, sqlgraph.NewFieldSpec(billingrecord.FieldID, field.TypeString))
+ if ps := brd.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ affected, err := sqlgraph.DeleteNodes(ctx, brd.driver, _spec)
+ if err != nil && sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ brd.mutation.done = true
+ return affected, err
+}
+
+// BillingRecordDeleteOne is the builder for deleting a single BillingRecord entity.
+type BillingRecordDeleteOne struct {
+ brd *BillingRecordDelete
+}
+
+// Where appends a list predicates to the BillingRecordDelete builder.
+func (brdo *BillingRecordDeleteOne) Where(ps ...predicate.BillingRecord) *BillingRecordDeleteOne {
+ brdo.brd.mutation.Where(ps...)
+ return brdo
+}
+
+// Exec executes the deletion query.
+func (brdo *BillingRecordDeleteOne) Exec(ctx context.Context) error {
+ n, err := brdo.brd.Exec(ctx)
+ switch {
+ case err != nil:
+ return err
+ case n == 0:
+ return &NotFoundError{billingrecord.Label}
+ default:
+ return nil
+ }
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (brdo *BillingRecordDeleteOne) ExecX(ctx context.Context) {
+ if err := brdo.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
diff --git a/backend/db/billingrecord_query.go b/backend/db/billingrecord_query.go
new file mode 100644
index 0000000..ca6222d
--- /dev/null
+++ b/backend/db/billingrecord_query.go
@@ -0,0 +1,577 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "fmt"
+ "math"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect"
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/billingrecord"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+)
+
+// BillingRecordQuery is the builder for querying BillingRecord entities.
+type BillingRecordQuery struct {
+ config
+ ctx *QueryContext
+ order []billingrecord.OrderOption
+ inters []Interceptor
+ predicates []predicate.BillingRecord
+ modifiers []func(*sql.Selector)
+ // intermediate query (i.e. traversal path).
+ sql *sql.Selector
+ path func(context.Context) (*sql.Selector, error)
+}
+
+// Where adds a new predicate for the BillingRecordQuery builder.
+func (brq *BillingRecordQuery) Where(ps ...predicate.BillingRecord) *BillingRecordQuery {
+ brq.predicates = append(brq.predicates, ps...)
+ return brq
+}
+
+// Limit the number of records to be returned by this query.
+func (brq *BillingRecordQuery) Limit(limit int) *BillingRecordQuery {
+ brq.ctx.Limit = &limit
+ return brq
+}
+
+// Offset to start from.
+func (brq *BillingRecordQuery) Offset(offset int) *BillingRecordQuery {
+ brq.ctx.Offset = &offset
+ return brq
+}
+
+// Unique configures the query builder to filter duplicate records on query.
+// By default, unique is set to true, and can be disabled using this method.
+func (brq *BillingRecordQuery) Unique(unique bool) *BillingRecordQuery {
+ brq.ctx.Unique = &unique
+ return brq
+}
+
+// Order specifies how the records should be ordered.
+func (brq *BillingRecordQuery) Order(o ...billingrecord.OrderOption) *BillingRecordQuery {
+ brq.order = append(brq.order, o...)
+ return brq
+}
+
+// First returns the first BillingRecord entity from the query.
+// Returns a *NotFoundError when no BillingRecord was found.
+func (brq *BillingRecordQuery) First(ctx context.Context) (*BillingRecord, error) {
+ nodes, err := brq.Limit(1).All(setContextOp(ctx, brq.ctx, ent.OpQueryFirst))
+ if err != nil {
+ return nil, err
+ }
+ if len(nodes) == 0 {
+ return nil, &NotFoundError{billingrecord.Label}
+ }
+ return nodes[0], nil
+}
+
+// FirstX is like First, but panics if an error occurs.
+func (brq *BillingRecordQuery) FirstX(ctx context.Context) *BillingRecord {
+ node, err := brq.First(ctx)
+ if err != nil && !IsNotFound(err) {
+ panic(err)
+ }
+ return node
+}
+
+// FirstID returns the first BillingRecord ID from the query.
+// Returns a *NotFoundError when no BillingRecord ID was found.
+func (brq *BillingRecordQuery) FirstID(ctx context.Context) (id string, err error) {
+ var ids []string
+ if ids, err = brq.Limit(1).IDs(setContextOp(ctx, brq.ctx, ent.OpQueryFirstID)); err != nil {
+ return
+ }
+ if len(ids) == 0 {
+ err = &NotFoundError{billingrecord.Label}
+ return
+ }
+ return ids[0], nil
+}
+
+// FirstIDX is like FirstID, but panics if an error occurs.
+func (brq *BillingRecordQuery) FirstIDX(ctx context.Context) string {
+ id, err := brq.FirstID(ctx)
+ if err != nil && !IsNotFound(err) {
+ panic(err)
+ }
+ return id
+}
+
+// Only returns a single BillingRecord entity found by the query, ensuring it only returns one.
+// Returns a *NotSingularError when more than one BillingRecord entity is found.
+// Returns a *NotFoundError when no BillingRecord entities are found.
+func (brq *BillingRecordQuery) Only(ctx context.Context) (*BillingRecord, error) {
+ nodes, err := brq.Limit(2).All(setContextOp(ctx, brq.ctx, ent.OpQueryOnly))
+ if err != nil {
+ return nil, err
+ }
+ switch len(nodes) {
+ case 1:
+ return nodes[0], nil
+ case 0:
+ return nil, &NotFoundError{billingrecord.Label}
+ default:
+ return nil, &NotSingularError{billingrecord.Label}
+ }
+}
+
+// OnlyX is like Only, but panics if an error occurs.
+func (brq *BillingRecordQuery) OnlyX(ctx context.Context) *BillingRecord {
+ node, err := brq.Only(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return node
+}
+
+// OnlyID is like Only, but returns the only BillingRecord ID in the query.
+// Returns a *NotSingularError when more than one BillingRecord ID is found.
+// Returns a *NotFoundError when no entities are found.
+func (brq *BillingRecordQuery) OnlyID(ctx context.Context) (id string, err error) {
+ var ids []string
+ if ids, err = brq.Limit(2).IDs(setContextOp(ctx, brq.ctx, ent.OpQueryOnlyID)); err != nil {
+ return
+ }
+ switch len(ids) {
+ case 1:
+ id = ids[0]
+ case 0:
+ err = &NotFoundError{billingrecord.Label}
+ default:
+ err = &NotSingularError{billingrecord.Label}
+ }
+ return
+}
+
+// OnlyIDX is like OnlyID, but panics if an error occurs.
+func (brq *BillingRecordQuery) OnlyIDX(ctx context.Context) string {
+ id, err := brq.OnlyID(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return id
+}
+
+// All executes the query and returns a list of BillingRecords.
+func (brq *BillingRecordQuery) All(ctx context.Context) ([]*BillingRecord, error) {
+ ctx = setContextOp(ctx, brq.ctx, ent.OpQueryAll)
+ if err := brq.prepareQuery(ctx); err != nil {
+ return nil, err
+ }
+ qr := querierAll[[]*BillingRecord, *BillingRecordQuery]()
+ return withInterceptors[[]*BillingRecord](ctx, brq, qr, brq.inters)
+}
+
+// AllX is like All, but panics if an error occurs.
+func (brq *BillingRecordQuery) AllX(ctx context.Context) []*BillingRecord {
+ nodes, err := brq.All(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return nodes
+}
+
+// IDs executes the query and returns a list of BillingRecord IDs.
+func (brq *BillingRecordQuery) IDs(ctx context.Context) (ids []string, err error) {
+ if brq.ctx.Unique == nil && brq.path != nil {
+ brq.Unique(true)
+ }
+ ctx = setContextOp(ctx, brq.ctx, ent.OpQueryIDs)
+ if err = brq.Select(billingrecord.FieldID).Scan(ctx, &ids); err != nil {
+ return nil, err
+ }
+ return ids, nil
+}
+
+// IDsX is like IDs, but panics if an error occurs.
+func (brq *BillingRecordQuery) IDsX(ctx context.Context) []string {
+ ids, err := brq.IDs(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return ids
+}
+
+// Count returns the count of the given query.
+func (brq *BillingRecordQuery) Count(ctx context.Context) (int, error) {
+ ctx = setContextOp(ctx, brq.ctx, ent.OpQueryCount)
+ if err := brq.prepareQuery(ctx); err != nil {
+ return 0, err
+ }
+ return withInterceptors[int](ctx, brq, querierCount[*BillingRecordQuery](), brq.inters)
+}
+
+// CountX is like Count, but panics if an error occurs.
+func (brq *BillingRecordQuery) CountX(ctx context.Context) int {
+ count, err := brq.Count(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return count
+}
+
+// Exist returns true if the query has elements in the graph.
+func (brq *BillingRecordQuery) Exist(ctx context.Context) (bool, error) {
+ ctx = setContextOp(ctx, brq.ctx, ent.OpQueryExist)
+ switch _, err := brq.FirstID(ctx); {
+ case IsNotFound(err):
+ return false, nil
+ case err != nil:
+ return false, fmt.Errorf("db: check existence: %w", err)
+ default:
+ return true, nil
+ }
+}
+
+// ExistX is like Exist, but panics if an error occurs.
+func (brq *BillingRecordQuery) ExistX(ctx context.Context) bool {
+ exist, err := brq.Exist(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return exist
+}
+
+// Clone returns a duplicate of the BillingRecordQuery builder, including all associated steps. It can be
+// used to prepare common query builders and use them differently after the clone is made.
+func (brq *BillingRecordQuery) Clone() *BillingRecordQuery {
+ if brq == nil {
+ return nil
+ }
+ return &BillingRecordQuery{
+ config: brq.config,
+ ctx: brq.ctx.Clone(),
+ order: append([]billingrecord.OrderOption{}, brq.order...),
+ inters: append([]Interceptor{}, brq.inters...),
+ predicates: append([]predicate.BillingRecord{}, brq.predicates...),
+ // clone intermediate query.
+ sql: brq.sql.Clone(),
+ path: brq.path,
+ modifiers: append([]func(*sql.Selector){}, brq.modifiers...),
+ }
+}
+
+// GroupBy is used to group vertices by one or more fields/columns.
+// It is often used with aggregate functions, like: count, max, mean, min, sum.
+//
+// Example:
+//
+// var v []struct {
+// TenantID string `json:"tenant_id,omitempty"`
+// Count int `json:"count,omitempty"`
+// }
+//
+// client.BillingRecord.Query().
+// GroupBy(billingrecord.FieldTenantID).
+// Aggregate(db.Count()).
+// Scan(ctx, &v)
+func (brq *BillingRecordQuery) GroupBy(field string, fields ...string) *BillingRecordGroupBy {
+ brq.ctx.Fields = append([]string{field}, fields...)
+ grbuild := &BillingRecordGroupBy{build: brq}
+ grbuild.flds = &brq.ctx.Fields
+ grbuild.label = billingrecord.Label
+ grbuild.scan = grbuild.Scan
+ return grbuild
+}
+
+// Select allows the selection one or more fields/columns for the given query,
+// instead of selecting all fields in the entity.
+//
+// Example:
+//
+// var v []struct {
+// TenantID string `json:"tenant_id,omitempty"`
+// }
+//
+// client.BillingRecord.Query().
+// Select(billingrecord.FieldTenantID).
+// Scan(ctx, &v)
+func (brq *BillingRecordQuery) Select(fields ...string) *BillingRecordSelect {
+ brq.ctx.Fields = append(brq.ctx.Fields, fields...)
+ sbuild := &BillingRecordSelect{BillingRecordQuery: brq}
+ sbuild.label = billingrecord.Label
+ sbuild.flds, sbuild.scan = &brq.ctx.Fields, sbuild.Scan
+ return sbuild
+}
+
+// Aggregate returns a BillingRecordSelect configured with the given aggregations.
+func (brq *BillingRecordQuery) Aggregate(fns ...AggregateFunc) *BillingRecordSelect {
+ return brq.Select().Aggregate(fns...)
+}
+
+func (brq *BillingRecordQuery) prepareQuery(ctx context.Context) error {
+ for _, inter := range brq.inters {
+ if inter == nil {
+ return fmt.Errorf("db: uninitialized interceptor (forgotten import db/runtime?)")
+ }
+ if trv, ok := inter.(Traverser); ok {
+ if err := trv.Traverse(ctx, brq); err != nil {
+ return err
+ }
+ }
+ }
+ for _, f := range brq.ctx.Fields {
+ if !billingrecord.ValidColumn(f) {
+ return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
+ }
+ }
+ if brq.path != nil {
+ prev, err := brq.path(ctx)
+ if err != nil {
+ return err
+ }
+ brq.sql = prev
+ }
+ return nil
+}
+
+func (brq *BillingRecordQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*BillingRecord, error) {
+ var (
+ nodes = []*BillingRecord{}
+ _spec = brq.querySpec()
+ )
+ _spec.ScanValues = func(columns []string) ([]any, error) {
+ return (*BillingRecord).scanValues(nil, columns)
+ }
+ _spec.Assign = func(columns []string, values []any) error {
+ node := &BillingRecord{config: brq.config}
+ nodes = append(nodes, node)
+ return node.assignValues(columns, values)
+ }
+ if len(brq.modifiers) > 0 {
+ _spec.Modifiers = brq.modifiers
+ }
+ for i := range hooks {
+ hooks[i](ctx, _spec)
+ }
+ if err := sqlgraph.QueryNodes(ctx, brq.driver, _spec); err != nil {
+ return nil, err
+ }
+ if len(nodes) == 0 {
+ return nodes, nil
+ }
+ return nodes, nil
+}
+
+func (brq *BillingRecordQuery) sqlCount(ctx context.Context) (int, error) {
+ _spec := brq.querySpec()
+ if len(brq.modifiers) > 0 {
+ _spec.Modifiers = brq.modifiers
+ }
+ _spec.Node.Columns = brq.ctx.Fields
+ if len(brq.ctx.Fields) > 0 {
+ _spec.Unique = brq.ctx.Unique != nil && *brq.ctx.Unique
+ }
+ return sqlgraph.CountNodes(ctx, brq.driver, _spec)
+}
+
+func (brq *BillingRecordQuery) querySpec() *sqlgraph.QuerySpec {
+ _spec := sqlgraph.NewQuerySpec(billingrecord.Table, billingrecord.Columns, sqlgraph.NewFieldSpec(billingrecord.FieldID, field.TypeString))
+ _spec.From = brq.sql
+ if unique := brq.ctx.Unique; unique != nil {
+ _spec.Unique = *unique
+ } else if brq.path != nil {
+ _spec.Unique = true
+ }
+ if fields := brq.ctx.Fields; len(fields) > 0 {
+ _spec.Node.Columns = make([]string, 0, len(fields))
+ _spec.Node.Columns = append(_spec.Node.Columns, billingrecord.FieldID)
+ for i := range fields {
+ if fields[i] != billingrecord.FieldID {
+ _spec.Node.Columns = append(_spec.Node.Columns, fields[i])
+ }
+ }
+ }
+ if ps := brq.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if limit := brq.ctx.Limit; limit != nil {
+ _spec.Limit = *limit
+ }
+ if offset := brq.ctx.Offset; offset != nil {
+ _spec.Offset = *offset
+ }
+ if ps := brq.order; len(ps) > 0 {
+ _spec.Order = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ return _spec
+}
+
+func (brq *BillingRecordQuery) sqlQuery(ctx context.Context) *sql.Selector {
+ builder := sql.Dialect(brq.driver.Dialect())
+ t1 := builder.Table(billingrecord.Table)
+ columns := brq.ctx.Fields
+ if len(columns) == 0 {
+ columns = billingrecord.Columns
+ }
+ selector := builder.Select(t1.Columns(columns...)...).From(t1)
+ if brq.sql != nil {
+ selector = brq.sql
+ selector.Select(selector.Columns(columns...)...)
+ }
+ if brq.ctx.Unique != nil && *brq.ctx.Unique {
+ selector.Distinct()
+ }
+ for _, m := range brq.modifiers {
+ m(selector)
+ }
+ for _, p := range brq.predicates {
+ p(selector)
+ }
+ for _, p := range brq.order {
+ p(selector)
+ }
+ if offset := brq.ctx.Offset; offset != nil {
+ // limit is mandatory for offset clause. We start
+ // with default value, and override it below if needed.
+ selector.Offset(*offset).Limit(math.MaxInt32)
+ }
+ if limit := brq.ctx.Limit; limit != nil {
+ selector.Limit(*limit)
+ }
+ return selector
+}
+
+// ForUpdate locks the selected rows against concurrent updates, and prevent them from being
+// updated, deleted or "selected ... for update" by other sessions, until the transaction is
+// either committed or rolled-back.
+func (brq *BillingRecordQuery) ForUpdate(opts ...sql.LockOption) *BillingRecordQuery {
+ if brq.driver.Dialect() == dialect.Postgres {
+ brq.Unique(false)
+ }
+ brq.modifiers = append(brq.modifiers, func(s *sql.Selector) {
+ s.ForUpdate(opts...)
+ })
+ return brq
+}
+
+// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock
+// on any rows that are read. Other sessions can read the rows, but cannot modify them
+// until your transaction commits.
+func (brq *BillingRecordQuery) ForShare(opts ...sql.LockOption) *BillingRecordQuery {
+ if brq.driver.Dialect() == dialect.Postgres {
+ brq.Unique(false)
+ }
+ brq.modifiers = append(brq.modifiers, func(s *sql.Selector) {
+ s.ForShare(opts...)
+ })
+ return brq
+}
+
+// Modify adds a query modifier for attaching custom logic to queries.
+func (brq *BillingRecordQuery) Modify(modifiers ...func(s *sql.Selector)) *BillingRecordSelect {
+ brq.modifiers = append(brq.modifiers, modifiers...)
+ return brq.Select()
+}
+
+// BillingRecordGroupBy is the group-by builder for BillingRecord entities.
+type BillingRecordGroupBy struct {
+ selector
+ build *BillingRecordQuery
+}
+
+// Aggregate adds the given aggregation functions to the group-by query.
+func (brgb *BillingRecordGroupBy) Aggregate(fns ...AggregateFunc) *BillingRecordGroupBy {
+ brgb.fns = append(brgb.fns, fns...)
+ return brgb
+}
+
+// Scan applies the selector query and scans the result into the given value.
+func (brgb *BillingRecordGroupBy) Scan(ctx context.Context, v any) error {
+ ctx = setContextOp(ctx, brgb.build.ctx, ent.OpQueryGroupBy)
+ if err := brgb.build.prepareQuery(ctx); err != nil {
+ return err
+ }
+ return scanWithInterceptors[*BillingRecordQuery, *BillingRecordGroupBy](ctx, brgb.build, brgb, brgb.build.inters, v)
+}
+
+func (brgb *BillingRecordGroupBy) sqlScan(ctx context.Context, root *BillingRecordQuery, v any) error {
+ selector := root.sqlQuery(ctx).Select()
+ aggregation := make([]string, 0, len(brgb.fns))
+ for _, fn := range brgb.fns {
+ aggregation = append(aggregation, fn(selector))
+ }
+ if len(selector.SelectedColumns()) == 0 {
+ columns := make([]string, 0, len(*brgb.flds)+len(brgb.fns))
+ for _, f := range *brgb.flds {
+ columns = append(columns, selector.C(f))
+ }
+ columns = append(columns, aggregation...)
+ selector.Select(columns...)
+ }
+ selector.GroupBy(selector.Columns(*brgb.flds...)...)
+ if err := selector.Err(); err != nil {
+ return err
+ }
+ rows := &sql.Rows{}
+ query, args := selector.Query()
+ if err := brgb.build.driver.Query(ctx, query, args, rows); err != nil {
+ return err
+ }
+ defer rows.Close()
+ return sql.ScanSlice(rows, v)
+}
+
+// BillingRecordSelect is the builder for selecting fields of BillingRecord entities.
+type BillingRecordSelect struct {
+ *BillingRecordQuery
+ selector
+}
+
+// Aggregate adds the given aggregation functions to the selector query.
+func (brs *BillingRecordSelect) Aggregate(fns ...AggregateFunc) *BillingRecordSelect {
+ brs.fns = append(brs.fns, fns...)
+ return brs
+}
+
+// Scan applies the selector query and scans the result into the given value.
+func (brs *BillingRecordSelect) Scan(ctx context.Context, v any) error {
+ ctx = setContextOp(ctx, brs.ctx, ent.OpQuerySelect)
+ if err := brs.prepareQuery(ctx); err != nil {
+ return err
+ }
+ return scanWithInterceptors[*BillingRecordQuery, *BillingRecordSelect](ctx, brs.BillingRecordQuery, brs, brs.inters, v)
+}
+
+func (brs *BillingRecordSelect) sqlScan(ctx context.Context, root *BillingRecordQuery, v any) error {
+ selector := root.sqlQuery(ctx)
+ aggregation := make([]string, 0, len(brs.fns))
+ for _, fn := range brs.fns {
+ aggregation = append(aggregation, fn(selector))
+ }
+ switch n := len(*brs.selector.flds); {
+ case n == 0 && len(aggregation) > 0:
+ selector.Select(aggregation...)
+ case n != 0 && len(aggregation) > 0:
+ selector.AppendSelect(aggregation...)
+ }
+ rows := &sql.Rows{}
+ query, args := selector.Query()
+ if err := brs.driver.Query(ctx, query, args, rows); err != nil {
+ return err
+ }
+ defer rows.Close()
+ return sql.ScanSlice(rows, v)
+}
+
+// Modify adds a query modifier for attaching custom logic to queries.
+func (brs *BillingRecordSelect) Modify(modifiers ...func(s *sql.Selector)) *BillingRecordSelect {
+ brs.modifiers = append(brs.modifiers, modifiers...)
+ return brs
+}
diff --git a/backend/db/billingrecord_update.go b/backend/db/billingrecord_update.go
new file mode 100644
index 0000000..42b64ff
--- /dev/null
+++ b/backend/db/billingrecord_update.go
@@ -0,0 +1,612 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "time"
+
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/billingrecord"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+)
+
+// BillingRecordUpdate is the builder for updating BillingRecord entities.
+type BillingRecordUpdate struct {
+ config
+ hooks []Hook
+ mutation *BillingRecordMutation
+ modifiers []func(*sql.UpdateBuilder)
+}
+
+// Where appends a list predicates to the BillingRecordUpdate builder.
+func (bru *BillingRecordUpdate) Where(ps ...predicate.BillingRecord) *BillingRecordUpdate {
+ bru.mutation.Where(ps...)
+ return bru
+}
+
+// SetTenantID sets the "tenant_id" field.
+func (bru *BillingRecordUpdate) SetTenantID(s string) *BillingRecordUpdate {
+ bru.mutation.SetTenantID(s)
+ return bru
+}
+
+// SetNillableTenantID sets the "tenant_id" field if the given value is not nil.
+func (bru *BillingRecordUpdate) SetNillableTenantID(s *string) *BillingRecordUpdate {
+ if s != nil {
+ bru.SetTenantID(*s)
+ }
+ return bru
+}
+
+// SetUserID sets the "user_id" field.
+func (bru *BillingRecordUpdate) SetUserID(s string) *BillingRecordUpdate {
+ bru.mutation.SetUserID(s)
+ return bru
+}
+
+// SetNillableUserID sets the "user_id" field if the given value is not nil.
+func (bru *BillingRecordUpdate) SetNillableUserID(s *string) *BillingRecordUpdate {
+ if s != nil {
+ bru.SetUserID(*s)
+ }
+ return bru
+}
+
+// SetModel sets the "model" field.
+func (bru *BillingRecordUpdate) SetModel(s string) *BillingRecordUpdate {
+ bru.mutation.SetModel(s)
+ return bru
+}
+
+// SetNillableModel sets the "model" field if the given value is not nil.
+func (bru *BillingRecordUpdate) SetNillableModel(s *string) *BillingRecordUpdate {
+ if s != nil {
+ bru.SetModel(*s)
+ }
+ return bru
+}
+
+// SetOperation sets the "operation" field.
+func (bru *BillingRecordUpdate) SetOperation(s string) *BillingRecordUpdate {
+ bru.mutation.SetOperation(s)
+ return bru
+}
+
+// SetNillableOperation sets the "operation" field if the given value is not nil.
+func (bru *BillingRecordUpdate) SetNillableOperation(s *string) *BillingRecordUpdate {
+ if s != nil {
+ bru.SetOperation(*s)
+ }
+ return bru
+}
+
+// SetInputTokens sets the "input_tokens" field.
+func (bru *BillingRecordUpdate) SetInputTokens(i int64) *BillingRecordUpdate {
+ bru.mutation.ResetInputTokens()
+ bru.mutation.SetInputTokens(i)
+ return bru
+}
+
+// SetNillableInputTokens sets the "input_tokens" field if the given value is not nil.
+func (bru *BillingRecordUpdate) SetNillableInputTokens(i *int64) *BillingRecordUpdate {
+ if i != nil {
+ bru.SetInputTokens(*i)
+ }
+ return bru
+}
+
+// AddInputTokens adds i to the "input_tokens" field.
+func (bru *BillingRecordUpdate) AddInputTokens(i int64) *BillingRecordUpdate {
+ bru.mutation.AddInputTokens(i)
+ return bru
+}
+
+// SetOutputTokens sets the "output_tokens" field.
+func (bru *BillingRecordUpdate) SetOutputTokens(i int64) *BillingRecordUpdate {
+ bru.mutation.ResetOutputTokens()
+ bru.mutation.SetOutputTokens(i)
+ return bru
+}
+
+// SetNillableOutputTokens sets the "output_tokens" field if the given value is not nil.
+func (bru *BillingRecordUpdate) SetNillableOutputTokens(i *int64) *BillingRecordUpdate {
+ if i != nil {
+ bru.SetOutputTokens(*i)
+ }
+ return bru
+}
+
+// AddOutputTokens adds i to the "output_tokens" field.
+func (bru *BillingRecordUpdate) AddOutputTokens(i int64) *BillingRecordUpdate {
+ bru.mutation.AddOutputTokens(i)
+ return bru
+}
+
+// SetCost sets the "cost" field.
+func (bru *BillingRecordUpdate) SetCost(i int64) *BillingRecordUpdate {
+ bru.mutation.ResetCost()
+ bru.mutation.SetCost(i)
+ return bru
+}
+
+// SetNillableCost sets the "cost" field if the given value is not nil.
+func (bru *BillingRecordUpdate) SetNillableCost(i *int64) *BillingRecordUpdate {
+ if i != nil {
+ bru.SetCost(*i)
+ }
+ return bru
+}
+
+// AddCost adds i to the "cost" field.
+func (bru *BillingRecordUpdate) AddCost(i int64) *BillingRecordUpdate {
+ bru.mutation.AddCost(i)
+ return bru
+}
+
+// SetRequestTime sets the "request_time" field.
+func (bru *BillingRecordUpdate) SetRequestTime(t time.Time) *BillingRecordUpdate {
+ bru.mutation.SetRequestTime(t)
+ return bru
+}
+
+// SetNillableRequestTime sets the "request_time" field if the given value is not nil.
+func (bru *BillingRecordUpdate) SetNillableRequestTime(t *time.Time) *BillingRecordUpdate {
+ if t != nil {
+ bru.SetRequestTime(*t)
+ }
+ return bru
+}
+
+// SetMetadata sets the "metadata" field.
+func (bru *BillingRecordUpdate) SetMetadata(m map[string]interface{}) *BillingRecordUpdate {
+ bru.mutation.SetMetadata(m)
+ return bru
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (bru *BillingRecordUpdate) SetCreatedAt(t time.Time) *BillingRecordUpdate {
+ bru.mutation.SetCreatedAt(t)
+ return bru
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (bru *BillingRecordUpdate) SetNillableCreatedAt(t *time.Time) *BillingRecordUpdate {
+ if t != nil {
+ bru.SetCreatedAt(*t)
+ }
+ return bru
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (bru *BillingRecordUpdate) SetUpdatedAt(t time.Time) *BillingRecordUpdate {
+ bru.mutation.SetUpdatedAt(t)
+ return bru
+}
+
+// Mutation returns the BillingRecordMutation object of the builder.
+func (bru *BillingRecordUpdate) Mutation() *BillingRecordMutation {
+ return bru.mutation
+}
+
+// Save executes the query and returns the number of nodes affected by the update operation.
+func (bru *BillingRecordUpdate) Save(ctx context.Context) (int, error) {
+ bru.defaults()
+ return withHooks(ctx, bru.sqlSave, bru.mutation, bru.hooks)
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (bru *BillingRecordUpdate) SaveX(ctx context.Context) int {
+ affected, err := bru.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return affected
+}
+
+// Exec executes the query.
+func (bru *BillingRecordUpdate) Exec(ctx context.Context) error {
+ _, err := bru.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (bru *BillingRecordUpdate) ExecX(ctx context.Context) {
+ if err := bru.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// defaults sets the default values of the builder before save.
+func (bru *BillingRecordUpdate) defaults() {
+ if _, ok := bru.mutation.UpdatedAt(); !ok {
+ v := billingrecord.UpdateDefaultUpdatedAt()
+ bru.mutation.SetUpdatedAt(v)
+ }
+}
+
+// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
+func (bru *BillingRecordUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *BillingRecordUpdate {
+ bru.modifiers = append(bru.modifiers, modifiers...)
+ return bru
+}
+
+func (bru *BillingRecordUpdate) sqlSave(ctx context.Context) (n int, err error) {
+ _spec := sqlgraph.NewUpdateSpec(billingrecord.Table, billingrecord.Columns, sqlgraph.NewFieldSpec(billingrecord.FieldID, field.TypeString))
+ if ps := bru.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if value, ok := bru.mutation.TenantID(); ok {
+ _spec.SetField(billingrecord.FieldTenantID, field.TypeString, value)
+ }
+ if value, ok := bru.mutation.UserID(); ok {
+ _spec.SetField(billingrecord.FieldUserID, field.TypeString, value)
+ }
+ if value, ok := bru.mutation.Model(); ok {
+ _spec.SetField(billingrecord.FieldModel, field.TypeString, value)
+ }
+ if value, ok := bru.mutation.Operation(); ok {
+ _spec.SetField(billingrecord.FieldOperation, field.TypeString, value)
+ }
+ if value, ok := bru.mutation.InputTokens(); ok {
+ _spec.SetField(billingrecord.FieldInputTokens, field.TypeInt64, value)
+ }
+ if value, ok := bru.mutation.AddedInputTokens(); ok {
+ _spec.AddField(billingrecord.FieldInputTokens, field.TypeInt64, value)
+ }
+ if value, ok := bru.mutation.OutputTokens(); ok {
+ _spec.SetField(billingrecord.FieldOutputTokens, field.TypeInt64, value)
+ }
+ if value, ok := bru.mutation.AddedOutputTokens(); ok {
+ _spec.AddField(billingrecord.FieldOutputTokens, field.TypeInt64, value)
+ }
+ if value, ok := bru.mutation.Cost(); ok {
+ _spec.SetField(billingrecord.FieldCost, field.TypeInt64, value)
+ }
+ if value, ok := bru.mutation.AddedCost(); ok {
+ _spec.AddField(billingrecord.FieldCost, field.TypeInt64, value)
+ }
+ if value, ok := bru.mutation.RequestTime(); ok {
+ _spec.SetField(billingrecord.FieldRequestTime, field.TypeTime, value)
+ }
+ if value, ok := bru.mutation.Metadata(); ok {
+ _spec.SetField(billingrecord.FieldMetadata, field.TypeJSON, value)
+ }
+ if value, ok := bru.mutation.CreatedAt(); ok {
+ _spec.SetField(billingrecord.FieldCreatedAt, field.TypeTime, value)
+ }
+ if value, ok := bru.mutation.UpdatedAt(); ok {
+ _spec.SetField(billingrecord.FieldUpdatedAt, field.TypeTime, value)
+ }
+ _spec.AddModifiers(bru.modifiers...)
+ if n, err = sqlgraph.UpdateNodes(ctx, bru.driver, _spec); err != nil {
+ if _, ok := err.(*sqlgraph.NotFoundError); ok {
+ err = &NotFoundError{billingrecord.Label}
+ } else if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return 0, err
+ }
+ bru.mutation.done = true
+ return n, nil
+}
+
+// BillingRecordUpdateOne is the builder for updating a single BillingRecord entity.
+type BillingRecordUpdateOne struct {
+ config
+ fields []string
+ hooks []Hook
+ mutation *BillingRecordMutation
+ modifiers []func(*sql.UpdateBuilder)
+}
+
+// SetTenantID sets the "tenant_id" field.
+func (bruo *BillingRecordUpdateOne) SetTenantID(s string) *BillingRecordUpdateOne {
+ bruo.mutation.SetTenantID(s)
+ return bruo
+}
+
+// SetNillableTenantID sets the "tenant_id" field if the given value is not nil.
+func (bruo *BillingRecordUpdateOne) SetNillableTenantID(s *string) *BillingRecordUpdateOne {
+ if s != nil {
+ bruo.SetTenantID(*s)
+ }
+ return bruo
+}
+
+// SetUserID sets the "user_id" field.
+func (bruo *BillingRecordUpdateOne) SetUserID(s string) *BillingRecordUpdateOne {
+ bruo.mutation.SetUserID(s)
+ return bruo
+}
+
+// SetNillableUserID sets the "user_id" field if the given value is not nil.
+func (bruo *BillingRecordUpdateOne) SetNillableUserID(s *string) *BillingRecordUpdateOne {
+ if s != nil {
+ bruo.SetUserID(*s)
+ }
+ return bruo
+}
+
+// SetModel sets the "model" field.
+func (bruo *BillingRecordUpdateOne) SetModel(s string) *BillingRecordUpdateOne {
+ bruo.mutation.SetModel(s)
+ return bruo
+}
+
+// SetNillableModel sets the "model" field if the given value is not nil.
+func (bruo *BillingRecordUpdateOne) SetNillableModel(s *string) *BillingRecordUpdateOne {
+ if s != nil {
+ bruo.SetModel(*s)
+ }
+ return bruo
+}
+
+// SetOperation sets the "operation" field.
+func (bruo *BillingRecordUpdateOne) SetOperation(s string) *BillingRecordUpdateOne {
+ bruo.mutation.SetOperation(s)
+ return bruo
+}
+
+// SetNillableOperation sets the "operation" field if the given value is not nil.
+func (bruo *BillingRecordUpdateOne) SetNillableOperation(s *string) *BillingRecordUpdateOne {
+ if s != nil {
+ bruo.SetOperation(*s)
+ }
+ return bruo
+}
+
+// SetInputTokens sets the "input_tokens" field.
+func (bruo *BillingRecordUpdateOne) SetInputTokens(i int64) *BillingRecordUpdateOne {
+ bruo.mutation.ResetInputTokens()
+ bruo.mutation.SetInputTokens(i)
+ return bruo
+}
+
+// SetNillableInputTokens sets the "input_tokens" field if the given value is not nil.
+func (bruo *BillingRecordUpdateOne) SetNillableInputTokens(i *int64) *BillingRecordUpdateOne {
+ if i != nil {
+ bruo.SetInputTokens(*i)
+ }
+ return bruo
+}
+
+// AddInputTokens adds i to the "input_tokens" field.
+func (bruo *BillingRecordUpdateOne) AddInputTokens(i int64) *BillingRecordUpdateOne {
+ bruo.mutation.AddInputTokens(i)
+ return bruo
+}
+
+// SetOutputTokens sets the "output_tokens" field.
+func (bruo *BillingRecordUpdateOne) SetOutputTokens(i int64) *BillingRecordUpdateOne {
+ bruo.mutation.ResetOutputTokens()
+ bruo.mutation.SetOutputTokens(i)
+ return bruo
+}
+
+// SetNillableOutputTokens sets the "output_tokens" field if the given value is not nil.
+func (bruo *BillingRecordUpdateOne) SetNillableOutputTokens(i *int64) *BillingRecordUpdateOne {
+ if i != nil {
+ bruo.SetOutputTokens(*i)
+ }
+ return bruo
+}
+
+// AddOutputTokens adds i to the "output_tokens" field.
+func (bruo *BillingRecordUpdateOne) AddOutputTokens(i int64) *BillingRecordUpdateOne {
+ bruo.mutation.AddOutputTokens(i)
+ return bruo
+}
+
+// SetCost sets the "cost" field.
+func (bruo *BillingRecordUpdateOne) SetCost(i int64) *BillingRecordUpdateOne {
+ bruo.mutation.ResetCost()
+ bruo.mutation.SetCost(i)
+ return bruo
+}
+
+// SetNillableCost sets the "cost" field if the given value is not nil.
+func (bruo *BillingRecordUpdateOne) SetNillableCost(i *int64) *BillingRecordUpdateOne {
+ if i != nil {
+ bruo.SetCost(*i)
+ }
+ return bruo
+}
+
+// AddCost adds i to the "cost" field.
+func (bruo *BillingRecordUpdateOne) AddCost(i int64) *BillingRecordUpdateOne {
+ bruo.mutation.AddCost(i)
+ return bruo
+}
+
+// SetRequestTime sets the "request_time" field.
+func (bruo *BillingRecordUpdateOne) SetRequestTime(t time.Time) *BillingRecordUpdateOne {
+ bruo.mutation.SetRequestTime(t)
+ return bruo
+}
+
+// SetNillableRequestTime sets the "request_time" field if the given value is not nil.
+func (bruo *BillingRecordUpdateOne) SetNillableRequestTime(t *time.Time) *BillingRecordUpdateOne {
+ if t != nil {
+ bruo.SetRequestTime(*t)
+ }
+ return bruo
+}
+
+// SetMetadata sets the "metadata" field.
+func (bruo *BillingRecordUpdateOne) SetMetadata(m map[string]interface{}) *BillingRecordUpdateOne {
+ bruo.mutation.SetMetadata(m)
+ return bruo
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (bruo *BillingRecordUpdateOne) SetCreatedAt(t time.Time) *BillingRecordUpdateOne {
+ bruo.mutation.SetCreatedAt(t)
+ return bruo
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (bruo *BillingRecordUpdateOne) SetNillableCreatedAt(t *time.Time) *BillingRecordUpdateOne {
+ if t != nil {
+ bruo.SetCreatedAt(*t)
+ }
+ return bruo
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (bruo *BillingRecordUpdateOne) SetUpdatedAt(t time.Time) *BillingRecordUpdateOne {
+ bruo.mutation.SetUpdatedAt(t)
+ return bruo
+}
+
+// Mutation returns the BillingRecordMutation object of the builder.
+func (bruo *BillingRecordUpdateOne) Mutation() *BillingRecordMutation {
+ return bruo.mutation
+}
+
+// Where appends a list predicates to the BillingRecordUpdate builder.
+func (bruo *BillingRecordUpdateOne) Where(ps ...predicate.BillingRecord) *BillingRecordUpdateOne {
+ bruo.mutation.Where(ps...)
+ return bruo
+}
+
+// Select allows selecting one or more fields (columns) of the returned entity.
+// The default is selecting all fields defined in the entity schema.
+func (bruo *BillingRecordUpdateOne) Select(field string, fields ...string) *BillingRecordUpdateOne {
+ bruo.fields = append([]string{field}, fields...)
+ return bruo
+}
+
+// Save executes the query and returns the updated BillingRecord entity.
+func (bruo *BillingRecordUpdateOne) Save(ctx context.Context) (*BillingRecord, error) {
+ bruo.defaults()
+ return withHooks(ctx, bruo.sqlSave, bruo.mutation, bruo.hooks)
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (bruo *BillingRecordUpdateOne) SaveX(ctx context.Context) *BillingRecord {
+ node, err := bruo.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return node
+}
+
+// Exec executes the query on the entity.
+func (bruo *BillingRecordUpdateOne) Exec(ctx context.Context) error {
+ _, err := bruo.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (bruo *BillingRecordUpdateOne) ExecX(ctx context.Context) {
+ if err := bruo.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// defaults sets the default values of the builder before save.
+func (bruo *BillingRecordUpdateOne) defaults() {
+ if _, ok := bruo.mutation.UpdatedAt(); !ok {
+ v := billingrecord.UpdateDefaultUpdatedAt()
+ bruo.mutation.SetUpdatedAt(v)
+ }
+}
+
+// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
+func (bruo *BillingRecordUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *BillingRecordUpdateOne {
+ bruo.modifiers = append(bruo.modifiers, modifiers...)
+ return bruo
+}
+
+func (bruo *BillingRecordUpdateOne) sqlSave(ctx context.Context) (_node *BillingRecord, err error) {
+ _spec := sqlgraph.NewUpdateSpec(billingrecord.Table, billingrecord.Columns, sqlgraph.NewFieldSpec(billingrecord.FieldID, field.TypeString))
+ id, ok := bruo.mutation.ID()
+ if !ok {
+ return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "BillingRecord.id" for update`)}
+ }
+ _spec.Node.ID.Value = id
+ if fields := bruo.fields; len(fields) > 0 {
+ _spec.Node.Columns = make([]string, 0, len(fields))
+ _spec.Node.Columns = append(_spec.Node.Columns, billingrecord.FieldID)
+ for _, f := range fields {
+ if !billingrecord.ValidColumn(f) {
+ return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
+ }
+ if f != billingrecord.FieldID {
+ _spec.Node.Columns = append(_spec.Node.Columns, f)
+ }
+ }
+ }
+ if ps := bruo.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if value, ok := bruo.mutation.TenantID(); ok {
+ _spec.SetField(billingrecord.FieldTenantID, field.TypeString, value)
+ }
+ if value, ok := bruo.mutation.UserID(); ok {
+ _spec.SetField(billingrecord.FieldUserID, field.TypeString, value)
+ }
+ if value, ok := bruo.mutation.Model(); ok {
+ _spec.SetField(billingrecord.FieldModel, field.TypeString, value)
+ }
+ if value, ok := bruo.mutation.Operation(); ok {
+ _spec.SetField(billingrecord.FieldOperation, field.TypeString, value)
+ }
+ if value, ok := bruo.mutation.InputTokens(); ok {
+ _spec.SetField(billingrecord.FieldInputTokens, field.TypeInt64, value)
+ }
+ if value, ok := bruo.mutation.AddedInputTokens(); ok {
+ _spec.AddField(billingrecord.FieldInputTokens, field.TypeInt64, value)
+ }
+ if value, ok := bruo.mutation.OutputTokens(); ok {
+ _spec.SetField(billingrecord.FieldOutputTokens, field.TypeInt64, value)
+ }
+ if value, ok := bruo.mutation.AddedOutputTokens(); ok {
+ _spec.AddField(billingrecord.FieldOutputTokens, field.TypeInt64, value)
+ }
+ if value, ok := bruo.mutation.Cost(); ok {
+ _spec.SetField(billingrecord.FieldCost, field.TypeInt64, value)
+ }
+ if value, ok := bruo.mutation.AddedCost(); ok {
+ _spec.AddField(billingrecord.FieldCost, field.TypeInt64, value)
+ }
+ if value, ok := bruo.mutation.RequestTime(); ok {
+ _spec.SetField(billingrecord.FieldRequestTime, field.TypeTime, value)
+ }
+ if value, ok := bruo.mutation.Metadata(); ok {
+ _spec.SetField(billingrecord.FieldMetadata, field.TypeJSON, value)
+ }
+ if value, ok := bruo.mutation.CreatedAt(); ok {
+ _spec.SetField(billingrecord.FieldCreatedAt, field.TypeTime, value)
+ }
+ if value, ok := bruo.mutation.UpdatedAt(); ok {
+ _spec.SetField(billingrecord.FieldUpdatedAt, field.TypeTime, value)
+ }
+ _spec.AddModifiers(bruo.modifiers...)
+ _node = &BillingRecord{config: bruo.config}
+ _spec.Assign = _node.assignValues
+ _spec.ScanValues = _node.scanValues
+ if err = sqlgraph.UpdateNode(ctx, bruo.driver, _spec); err != nil {
+ if _, ok := err.(*sqlgraph.NotFoundError); ok {
+ err = &NotFoundError{billingrecord.Label}
+ } else if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return nil, err
+ }
+ bruo.mutation.done = true
+ return _node, nil
+}
diff --git a/backend/db/billingusage.go b/backend/db/billingusage.go
new file mode 100644
index 0000000..ee899b9
--- /dev/null
+++ b/backend/db/billingusage.go
@@ -0,0 +1,172 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "fmt"
+ "strings"
+ "time"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect/sql"
+ "github.com/chaitin/MonkeyCode/backend/db/billingusage"
+)
+
+// BillingUsage is the model entity for the BillingUsage schema.
+type BillingUsage struct {
+ config `json:"-"`
+ // ID of the ent.
+ ID string `json:"id,omitempty"`
+ // DeletedAt holds the value of the "deleted_at" field.
+ DeletedAt time.Time `json:"deleted_at,omitempty"`
+ // UserID holds the value of the "user_id" field.
+ UserID string `json:"user_id,omitempty"`
+ // ModelName holds the value of the "model_name" field.
+ ModelName string `json:"model_name,omitempty"`
+ // Tokens holds the value of the "tokens" field.
+ Tokens int64 `json:"tokens,omitempty"`
+ // Operation holds the value of the "operation" field.
+ Operation string `json:"operation,omitempty"`
+ // CreatedAt holds the value of the "created_at" field.
+ CreatedAt time.Time `json:"created_at,omitempty"`
+ // UpdatedAt holds the value of the "updated_at" field.
+ UpdatedAt time.Time `json:"updated_at,omitempty"`
+ selectValues sql.SelectValues
+}
+
+// scanValues returns the types for scanning values from sql.Rows.
+func (*BillingUsage) scanValues(columns []string) ([]any, error) {
+ values := make([]any, len(columns))
+ for i := range columns {
+ switch columns[i] {
+ case billingusage.FieldTokens:
+ values[i] = new(sql.NullInt64)
+ case billingusage.FieldID, billingusage.FieldUserID, billingusage.FieldModelName, billingusage.FieldOperation:
+ values[i] = new(sql.NullString)
+ case billingusage.FieldDeletedAt, billingusage.FieldCreatedAt, billingusage.FieldUpdatedAt:
+ values[i] = new(sql.NullTime)
+ default:
+ values[i] = new(sql.UnknownType)
+ }
+ }
+ return values, nil
+}
+
+// assignValues assigns the values that were returned from sql.Rows (after scanning)
+// to the BillingUsage fields.
+func (bu *BillingUsage) assignValues(columns []string, values []any) error {
+ if m, n := len(values), len(columns); m < n {
+ return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
+ }
+ for i := range columns {
+ switch columns[i] {
+ case billingusage.FieldID:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field id", values[i])
+ } else if value.Valid {
+ bu.ID = value.String
+ }
+ case billingusage.FieldDeletedAt:
+ if value, ok := values[i].(*sql.NullTime); !ok {
+ return fmt.Errorf("unexpected type %T for field deleted_at", values[i])
+ } else if value.Valid {
+ bu.DeletedAt = value.Time
+ }
+ case billingusage.FieldUserID:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field user_id", values[i])
+ } else if value.Valid {
+ bu.UserID = value.String
+ }
+ case billingusage.FieldModelName:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field model_name", values[i])
+ } else if value.Valid {
+ bu.ModelName = value.String
+ }
+ case billingusage.FieldTokens:
+ if value, ok := values[i].(*sql.NullInt64); !ok {
+ return fmt.Errorf("unexpected type %T for field tokens", values[i])
+ } else if value.Valid {
+ bu.Tokens = value.Int64
+ }
+ case billingusage.FieldOperation:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field operation", values[i])
+ } else if value.Valid {
+ bu.Operation = value.String
+ }
+ case billingusage.FieldCreatedAt:
+ if value, ok := values[i].(*sql.NullTime); !ok {
+ return fmt.Errorf("unexpected type %T for field created_at", values[i])
+ } else if value.Valid {
+ bu.CreatedAt = value.Time
+ }
+ case billingusage.FieldUpdatedAt:
+ if value, ok := values[i].(*sql.NullTime); !ok {
+ return fmt.Errorf("unexpected type %T for field updated_at", values[i])
+ } else if value.Valid {
+ bu.UpdatedAt = value.Time
+ }
+ default:
+ bu.selectValues.Set(columns[i], values[i])
+ }
+ }
+ return nil
+}
+
+// Value returns the ent.Value that was dynamically selected and assigned to the BillingUsage.
+// This includes values selected through modifiers, order, etc.
+func (bu *BillingUsage) Value(name string) (ent.Value, error) {
+ return bu.selectValues.Get(name)
+}
+
+// Update returns a builder for updating this BillingUsage.
+// Note that you need to call BillingUsage.Unwrap() before calling this method if this BillingUsage
+// was returned from a transaction, and the transaction was committed or rolled back.
+func (bu *BillingUsage) Update() *BillingUsageUpdateOne {
+ return NewBillingUsageClient(bu.config).UpdateOne(bu)
+}
+
+// Unwrap unwraps the BillingUsage entity that was returned from a transaction after it was closed,
+// so that all future queries will be executed through the driver which created the transaction.
+func (bu *BillingUsage) Unwrap() *BillingUsage {
+ _tx, ok := bu.config.driver.(*txDriver)
+ if !ok {
+ panic("db: BillingUsage is not a transactional entity")
+ }
+ bu.config.driver = _tx.drv
+ return bu
+}
+
+// String implements the fmt.Stringer.
+func (bu *BillingUsage) String() string {
+ var builder strings.Builder
+ builder.WriteString("BillingUsage(")
+ builder.WriteString(fmt.Sprintf("id=%v, ", bu.ID))
+ builder.WriteString("deleted_at=")
+ builder.WriteString(bu.DeletedAt.Format(time.ANSIC))
+ builder.WriteString(", ")
+ builder.WriteString("user_id=")
+ builder.WriteString(bu.UserID)
+ builder.WriteString(", ")
+ builder.WriteString("model_name=")
+ builder.WriteString(bu.ModelName)
+ builder.WriteString(", ")
+ builder.WriteString("tokens=")
+ builder.WriteString(fmt.Sprintf("%v", bu.Tokens))
+ builder.WriteString(", ")
+ builder.WriteString("operation=")
+ builder.WriteString(bu.Operation)
+ builder.WriteString(", ")
+ builder.WriteString("created_at=")
+ builder.WriteString(bu.CreatedAt.Format(time.ANSIC))
+ builder.WriteString(", ")
+ builder.WriteString("updated_at=")
+ builder.WriteString(bu.UpdatedAt.Format(time.ANSIC))
+ builder.WriteByte(')')
+ return builder.String()
+}
+
+// BillingUsages is a parsable slice of BillingUsage.
+type BillingUsages []*BillingUsage
diff --git a/backend/db/billingusage/billingusage.go b/backend/db/billingusage/billingusage.go
new file mode 100644
index 0000000..4a42a8c
--- /dev/null
+++ b/backend/db/billingusage/billingusage.go
@@ -0,0 +1,114 @@
+// Code generated by ent, DO NOT EDIT.
+
+package billingusage
+
+import (
+ "time"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect/sql"
+)
+
+const (
+ // Label holds the string label denoting the billingusage type in the database.
+ Label = "billing_usage"
+ // FieldID holds the string denoting the id field in the database.
+ FieldID = "id"
+ // FieldDeletedAt holds the string denoting the deleted_at field in the database.
+ FieldDeletedAt = "deleted_at"
+ // FieldUserID holds the string denoting the user_id field in the database.
+ FieldUserID = "user_id"
+ // FieldModelName holds the string denoting the model_name field in the database.
+ FieldModelName = "model_name"
+ // FieldTokens holds the string denoting the tokens field in the database.
+ FieldTokens = "tokens"
+ // FieldOperation holds the string denoting the operation field in the database.
+ FieldOperation = "operation"
+ // FieldCreatedAt holds the string denoting the created_at field in the database.
+ FieldCreatedAt = "created_at"
+ // FieldUpdatedAt holds the string denoting the updated_at field in the database.
+ FieldUpdatedAt = "updated_at"
+ // Table holds the table name of the billingusage in the database.
+ Table = "billing_usages"
+)
+
+// Columns holds all SQL columns for billingusage fields.
+var Columns = []string{
+ FieldID,
+ FieldDeletedAt,
+ FieldUserID,
+ FieldModelName,
+ FieldTokens,
+ FieldOperation,
+ FieldCreatedAt,
+ FieldUpdatedAt,
+}
+
+// ValidColumn reports if the column name is valid (part of the table columns).
+func ValidColumn(column string) bool {
+ for i := range Columns {
+ if column == Columns[i] {
+ return true
+ }
+ }
+ return false
+}
+
+// Note that the variables below are initialized by the runtime
+// package on the initialization of the application. Therefore,
+// it should be imported in the main as follows:
+//
+// import _ "github.com/chaitin/MonkeyCode/backend/db/runtime"
+var (
+ Hooks [1]ent.Hook
+ Interceptors [1]ent.Interceptor
+ // DefaultCreatedAt holds the default value on creation for the "created_at" field.
+ DefaultCreatedAt func() time.Time
+ // DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
+ DefaultUpdatedAt func() time.Time
+ // UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field.
+ UpdateDefaultUpdatedAt func() time.Time
+)
+
+// OrderOption defines the ordering options for the BillingUsage queries.
+type OrderOption func(*sql.Selector)
+
+// ByID orders the results by the id field.
+func ByID(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldID, opts...).ToFunc()
+}
+
+// ByDeletedAt orders the results by the deleted_at field.
+func ByDeletedAt(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldDeletedAt, opts...).ToFunc()
+}
+
+// ByUserID orders the results by the user_id field.
+func ByUserID(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldUserID, opts...).ToFunc()
+}
+
+// ByModelName orders the results by the model_name field.
+func ByModelName(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldModelName, opts...).ToFunc()
+}
+
+// ByTokens orders the results by the tokens field.
+func ByTokens(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldTokens, opts...).ToFunc()
+}
+
+// ByOperation orders the results by the operation field.
+func ByOperation(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldOperation, opts...).ToFunc()
+}
+
+// ByCreatedAt orders the results by the created_at field.
+func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
+}
+
+// ByUpdatedAt orders the results by the updated_at field.
+func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc()
+}
diff --git a/backend/db/billingusage/where.go b/backend/db/billingusage/where.go
new file mode 100644
index 0000000..621a7f2
--- /dev/null
+++ b/backend/db/billingusage/where.go
@@ -0,0 +1,480 @@
+// Code generated by ent, DO NOT EDIT.
+
+package billingusage
+
+import (
+ "time"
+
+ "entgo.io/ent/dialect/sql"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+)
+
+// ID filters vertices based on their ID field.
+func ID(id string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldEQ(FieldID, id))
+}
+
+// IDEQ applies the EQ predicate on the ID field.
+func IDEQ(id string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldEQ(FieldID, id))
+}
+
+// IDNEQ applies the NEQ predicate on the ID field.
+func IDNEQ(id string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldNEQ(FieldID, id))
+}
+
+// IDIn applies the In predicate on the ID field.
+func IDIn(ids ...string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldIn(FieldID, ids...))
+}
+
+// IDNotIn applies the NotIn predicate on the ID field.
+func IDNotIn(ids ...string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldNotIn(FieldID, ids...))
+}
+
+// IDGT applies the GT predicate on the ID field.
+func IDGT(id string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldGT(FieldID, id))
+}
+
+// IDGTE applies the GTE predicate on the ID field.
+func IDGTE(id string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldGTE(FieldID, id))
+}
+
+// IDLT applies the LT predicate on the ID field.
+func IDLT(id string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldLT(FieldID, id))
+}
+
+// IDLTE applies the LTE predicate on the ID field.
+func IDLTE(id string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldLTE(FieldID, id))
+}
+
+// IDEqualFold applies the EqualFold predicate on the ID field.
+func IDEqualFold(id string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldEqualFold(FieldID, id))
+}
+
+// IDContainsFold applies the ContainsFold predicate on the ID field.
+func IDContainsFold(id string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldContainsFold(FieldID, id))
+}
+
+// DeletedAt applies equality check predicate on the "deleted_at" field. It's identical to DeletedAtEQ.
+func DeletedAt(v time.Time) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldEQ(FieldDeletedAt, v))
+}
+
+// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ.
+func UserID(v string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldEQ(FieldUserID, v))
+}
+
+// ModelName applies equality check predicate on the "model_name" field. It's identical to ModelNameEQ.
+func ModelName(v string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldEQ(FieldModelName, v))
+}
+
+// Tokens applies equality check predicate on the "tokens" field. It's identical to TokensEQ.
+func Tokens(v int64) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldEQ(FieldTokens, v))
+}
+
+// Operation applies equality check predicate on the "operation" field. It's identical to OperationEQ.
+func Operation(v string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldEQ(FieldOperation, v))
+}
+
+// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
+func CreatedAt(v time.Time) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldEQ(FieldCreatedAt, v))
+}
+
+// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
+func UpdatedAt(v time.Time) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldEQ(FieldUpdatedAt, v))
+}
+
+// DeletedAtEQ applies the EQ predicate on the "deleted_at" field.
+func DeletedAtEQ(v time.Time) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldEQ(FieldDeletedAt, v))
+}
+
+// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field.
+func DeletedAtNEQ(v time.Time) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldNEQ(FieldDeletedAt, v))
+}
+
+// DeletedAtIn applies the In predicate on the "deleted_at" field.
+func DeletedAtIn(vs ...time.Time) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldIn(FieldDeletedAt, vs...))
+}
+
+// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field.
+func DeletedAtNotIn(vs ...time.Time) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldNotIn(FieldDeletedAt, vs...))
+}
+
+// DeletedAtGT applies the GT predicate on the "deleted_at" field.
+func DeletedAtGT(v time.Time) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldGT(FieldDeletedAt, v))
+}
+
+// DeletedAtGTE applies the GTE predicate on the "deleted_at" field.
+func DeletedAtGTE(v time.Time) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldGTE(FieldDeletedAt, v))
+}
+
+// DeletedAtLT applies the LT predicate on the "deleted_at" field.
+func DeletedAtLT(v time.Time) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldLT(FieldDeletedAt, v))
+}
+
+// DeletedAtLTE applies the LTE predicate on the "deleted_at" field.
+func DeletedAtLTE(v time.Time) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldLTE(FieldDeletedAt, v))
+}
+
+// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field.
+func DeletedAtIsNil() predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldIsNull(FieldDeletedAt))
+}
+
+// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field.
+func DeletedAtNotNil() predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldNotNull(FieldDeletedAt))
+}
+
+// UserIDEQ applies the EQ predicate on the "user_id" field.
+func UserIDEQ(v string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldEQ(FieldUserID, v))
+}
+
+// UserIDNEQ applies the NEQ predicate on the "user_id" field.
+func UserIDNEQ(v string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldNEQ(FieldUserID, v))
+}
+
+// UserIDIn applies the In predicate on the "user_id" field.
+func UserIDIn(vs ...string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldIn(FieldUserID, vs...))
+}
+
+// UserIDNotIn applies the NotIn predicate on the "user_id" field.
+func UserIDNotIn(vs ...string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldNotIn(FieldUserID, vs...))
+}
+
+// UserIDGT applies the GT predicate on the "user_id" field.
+func UserIDGT(v string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldGT(FieldUserID, v))
+}
+
+// UserIDGTE applies the GTE predicate on the "user_id" field.
+func UserIDGTE(v string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldGTE(FieldUserID, v))
+}
+
+// UserIDLT applies the LT predicate on the "user_id" field.
+func UserIDLT(v string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldLT(FieldUserID, v))
+}
+
+// UserIDLTE applies the LTE predicate on the "user_id" field.
+func UserIDLTE(v string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldLTE(FieldUserID, v))
+}
+
+// UserIDContains applies the Contains predicate on the "user_id" field.
+func UserIDContains(v string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldContains(FieldUserID, v))
+}
+
+// UserIDHasPrefix applies the HasPrefix predicate on the "user_id" field.
+func UserIDHasPrefix(v string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldHasPrefix(FieldUserID, v))
+}
+
+// UserIDHasSuffix applies the HasSuffix predicate on the "user_id" field.
+func UserIDHasSuffix(v string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldHasSuffix(FieldUserID, v))
+}
+
+// UserIDEqualFold applies the EqualFold predicate on the "user_id" field.
+func UserIDEqualFold(v string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldEqualFold(FieldUserID, v))
+}
+
+// UserIDContainsFold applies the ContainsFold predicate on the "user_id" field.
+func UserIDContainsFold(v string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldContainsFold(FieldUserID, v))
+}
+
+// ModelNameEQ applies the EQ predicate on the "model_name" field.
+func ModelNameEQ(v string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldEQ(FieldModelName, v))
+}
+
+// ModelNameNEQ applies the NEQ predicate on the "model_name" field.
+func ModelNameNEQ(v string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldNEQ(FieldModelName, v))
+}
+
+// ModelNameIn applies the In predicate on the "model_name" field.
+func ModelNameIn(vs ...string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldIn(FieldModelName, vs...))
+}
+
+// ModelNameNotIn applies the NotIn predicate on the "model_name" field.
+func ModelNameNotIn(vs ...string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldNotIn(FieldModelName, vs...))
+}
+
+// ModelNameGT applies the GT predicate on the "model_name" field.
+func ModelNameGT(v string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldGT(FieldModelName, v))
+}
+
+// ModelNameGTE applies the GTE predicate on the "model_name" field.
+func ModelNameGTE(v string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldGTE(FieldModelName, v))
+}
+
+// ModelNameLT applies the LT predicate on the "model_name" field.
+func ModelNameLT(v string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldLT(FieldModelName, v))
+}
+
+// ModelNameLTE applies the LTE predicate on the "model_name" field.
+func ModelNameLTE(v string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldLTE(FieldModelName, v))
+}
+
+// ModelNameContains applies the Contains predicate on the "model_name" field.
+func ModelNameContains(v string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldContains(FieldModelName, v))
+}
+
+// ModelNameHasPrefix applies the HasPrefix predicate on the "model_name" field.
+func ModelNameHasPrefix(v string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldHasPrefix(FieldModelName, v))
+}
+
+// ModelNameHasSuffix applies the HasSuffix predicate on the "model_name" field.
+func ModelNameHasSuffix(v string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldHasSuffix(FieldModelName, v))
+}
+
+// ModelNameEqualFold applies the EqualFold predicate on the "model_name" field.
+func ModelNameEqualFold(v string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldEqualFold(FieldModelName, v))
+}
+
+// ModelNameContainsFold applies the ContainsFold predicate on the "model_name" field.
+func ModelNameContainsFold(v string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldContainsFold(FieldModelName, v))
+}
+
+// TokensEQ applies the EQ predicate on the "tokens" field.
+func TokensEQ(v int64) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldEQ(FieldTokens, v))
+}
+
+// TokensNEQ applies the NEQ predicate on the "tokens" field.
+func TokensNEQ(v int64) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldNEQ(FieldTokens, v))
+}
+
+// TokensIn applies the In predicate on the "tokens" field.
+func TokensIn(vs ...int64) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldIn(FieldTokens, vs...))
+}
+
+// TokensNotIn applies the NotIn predicate on the "tokens" field.
+func TokensNotIn(vs ...int64) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldNotIn(FieldTokens, vs...))
+}
+
+// TokensGT applies the GT predicate on the "tokens" field.
+func TokensGT(v int64) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldGT(FieldTokens, v))
+}
+
+// TokensGTE applies the GTE predicate on the "tokens" field.
+func TokensGTE(v int64) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldGTE(FieldTokens, v))
+}
+
+// TokensLT applies the LT predicate on the "tokens" field.
+func TokensLT(v int64) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldLT(FieldTokens, v))
+}
+
+// TokensLTE applies the LTE predicate on the "tokens" field.
+func TokensLTE(v int64) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldLTE(FieldTokens, v))
+}
+
+// OperationEQ applies the EQ predicate on the "operation" field.
+func OperationEQ(v string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldEQ(FieldOperation, v))
+}
+
+// OperationNEQ applies the NEQ predicate on the "operation" field.
+func OperationNEQ(v string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldNEQ(FieldOperation, v))
+}
+
+// OperationIn applies the In predicate on the "operation" field.
+func OperationIn(vs ...string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldIn(FieldOperation, vs...))
+}
+
+// OperationNotIn applies the NotIn predicate on the "operation" field.
+func OperationNotIn(vs ...string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldNotIn(FieldOperation, vs...))
+}
+
+// OperationGT applies the GT predicate on the "operation" field.
+func OperationGT(v string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldGT(FieldOperation, v))
+}
+
+// OperationGTE applies the GTE predicate on the "operation" field.
+func OperationGTE(v string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldGTE(FieldOperation, v))
+}
+
+// OperationLT applies the LT predicate on the "operation" field.
+func OperationLT(v string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldLT(FieldOperation, v))
+}
+
+// OperationLTE applies the LTE predicate on the "operation" field.
+func OperationLTE(v string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldLTE(FieldOperation, v))
+}
+
+// OperationContains applies the Contains predicate on the "operation" field.
+func OperationContains(v string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldContains(FieldOperation, v))
+}
+
+// OperationHasPrefix applies the HasPrefix predicate on the "operation" field.
+func OperationHasPrefix(v string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldHasPrefix(FieldOperation, v))
+}
+
+// OperationHasSuffix applies the HasSuffix predicate on the "operation" field.
+func OperationHasSuffix(v string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldHasSuffix(FieldOperation, v))
+}
+
+// OperationEqualFold applies the EqualFold predicate on the "operation" field.
+func OperationEqualFold(v string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldEqualFold(FieldOperation, v))
+}
+
+// OperationContainsFold applies the ContainsFold predicate on the "operation" field.
+func OperationContainsFold(v string) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldContainsFold(FieldOperation, v))
+}
+
+// CreatedAtEQ applies the EQ predicate on the "created_at" field.
+func CreatedAtEQ(v time.Time) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldEQ(FieldCreatedAt, v))
+}
+
+// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
+func CreatedAtNEQ(v time.Time) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldNEQ(FieldCreatedAt, v))
+}
+
+// CreatedAtIn applies the In predicate on the "created_at" field.
+func CreatedAtIn(vs ...time.Time) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldIn(FieldCreatedAt, vs...))
+}
+
+// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
+func CreatedAtNotIn(vs ...time.Time) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldNotIn(FieldCreatedAt, vs...))
+}
+
+// CreatedAtGT applies the GT predicate on the "created_at" field.
+func CreatedAtGT(v time.Time) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldGT(FieldCreatedAt, v))
+}
+
+// CreatedAtGTE applies the GTE predicate on the "created_at" field.
+func CreatedAtGTE(v time.Time) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldGTE(FieldCreatedAt, v))
+}
+
+// CreatedAtLT applies the LT predicate on the "created_at" field.
+func CreatedAtLT(v time.Time) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldLT(FieldCreatedAt, v))
+}
+
+// CreatedAtLTE applies the LTE predicate on the "created_at" field.
+func CreatedAtLTE(v time.Time) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldLTE(FieldCreatedAt, v))
+}
+
+// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
+func UpdatedAtEQ(v time.Time) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldEQ(FieldUpdatedAt, v))
+}
+
+// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
+func UpdatedAtNEQ(v time.Time) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldNEQ(FieldUpdatedAt, v))
+}
+
+// UpdatedAtIn applies the In predicate on the "updated_at" field.
+func UpdatedAtIn(vs ...time.Time) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldIn(FieldUpdatedAt, vs...))
+}
+
+// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
+func UpdatedAtNotIn(vs ...time.Time) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldNotIn(FieldUpdatedAt, vs...))
+}
+
+// UpdatedAtGT applies the GT predicate on the "updated_at" field.
+func UpdatedAtGT(v time.Time) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldGT(FieldUpdatedAt, v))
+}
+
+// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
+func UpdatedAtGTE(v time.Time) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldGTE(FieldUpdatedAt, v))
+}
+
+// UpdatedAtLT applies the LT predicate on the "updated_at" field.
+func UpdatedAtLT(v time.Time) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldLT(FieldUpdatedAt, v))
+}
+
+// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
+func UpdatedAtLTE(v time.Time) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.FieldLTE(FieldUpdatedAt, v))
+}
+
+// And groups predicates with the AND operator between them.
+func And(predicates ...predicate.BillingUsage) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.AndPredicates(predicates...))
+}
+
+// Or groups predicates with the OR operator between them.
+func Or(predicates ...predicate.BillingUsage) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.OrPredicates(predicates...))
+}
+
+// Not applies the not operator on the given predicate.
+func Not(p predicate.BillingUsage) predicate.BillingUsage {
+ return predicate.BillingUsage(sql.NotPredicates(p))
+}
diff --git a/backend/db/billingusage_create.go b/backend/db/billingusage_create.go
new file mode 100644
index 0000000..9a4d205
--- /dev/null
+++ b/backend/db/billingusage_create.go
@@ -0,0 +1,892 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "time"
+
+ "entgo.io/ent/dialect"
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/billingusage"
+)
+
+// BillingUsageCreate is the builder for creating a BillingUsage entity.
+type BillingUsageCreate struct {
+ config
+ mutation *BillingUsageMutation
+ hooks []Hook
+ conflict []sql.ConflictOption
+}
+
+// SetDeletedAt sets the "deleted_at" field.
+func (buc *BillingUsageCreate) SetDeletedAt(t time.Time) *BillingUsageCreate {
+ buc.mutation.SetDeletedAt(t)
+ return buc
+}
+
+// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil.
+func (buc *BillingUsageCreate) SetNillableDeletedAt(t *time.Time) *BillingUsageCreate {
+ if t != nil {
+ buc.SetDeletedAt(*t)
+ }
+ return buc
+}
+
+// SetUserID sets the "user_id" field.
+func (buc *BillingUsageCreate) SetUserID(s string) *BillingUsageCreate {
+ buc.mutation.SetUserID(s)
+ return buc
+}
+
+// SetModelName sets the "model_name" field.
+func (buc *BillingUsageCreate) SetModelName(s string) *BillingUsageCreate {
+ buc.mutation.SetModelName(s)
+ return buc
+}
+
+// SetTokens sets the "tokens" field.
+func (buc *BillingUsageCreate) SetTokens(i int64) *BillingUsageCreate {
+ buc.mutation.SetTokens(i)
+ return buc
+}
+
+// SetOperation sets the "operation" field.
+func (buc *BillingUsageCreate) SetOperation(s string) *BillingUsageCreate {
+ buc.mutation.SetOperation(s)
+ return buc
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (buc *BillingUsageCreate) SetCreatedAt(t time.Time) *BillingUsageCreate {
+ buc.mutation.SetCreatedAt(t)
+ return buc
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (buc *BillingUsageCreate) SetNillableCreatedAt(t *time.Time) *BillingUsageCreate {
+ if t != nil {
+ buc.SetCreatedAt(*t)
+ }
+ return buc
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (buc *BillingUsageCreate) SetUpdatedAt(t time.Time) *BillingUsageCreate {
+ buc.mutation.SetUpdatedAt(t)
+ return buc
+}
+
+// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
+func (buc *BillingUsageCreate) SetNillableUpdatedAt(t *time.Time) *BillingUsageCreate {
+ if t != nil {
+ buc.SetUpdatedAt(*t)
+ }
+ return buc
+}
+
+// SetID sets the "id" field.
+func (buc *BillingUsageCreate) SetID(s string) *BillingUsageCreate {
+ buc.mutation.SetID(s)
+ return buc
+}
+
+// Mutation returns the BillingUsageMutation object of the builder.
+func (buc *BillingUsageCreate) Mutation() *BillingUsageMutation {
+ return buc.mutation
+}
+
+// Save creates the BillingUsage in the database.
+func (buc *BillingUsageCreate) Save(ctx context.Context) (*BillingUsage, error) {
+ if err := buc.defaults(); err != nil {
+ return nil, err
+ }
+ return withHooks(ctx, buc.sqlSave, buc.mutation, buc.hooks)
+}
+
+// SaveX calls Save and panics if Save returns an error.
+func (buc *BillingUsageCreate) SaveX(ctx context.Context) *BillingUsage {
+ v, err := buc.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return v
+}
+
+// Exec executes the query.
+func (buc *BillingUsageCreate) Exec(ctx context.Context) error {
+ _, err := buc.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (buc *BillingUsageCreate) ExecX(ctx context.Context) {
+ if err := buc.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// defaults sets the default values of the builder before save.
+func (buc *BillingUsageCreate) defaults() error {
+ if _, ok := buc.mutation.CreatedAt(); !ok {
+ if billingusage.DefaultCreatedAt == nil {
+ return fmt.Errorf("db: uninitialized billingusage.DefaultCreatedAt (forgotten import db/runtime?)")
+ }
+ v := billingusage.DefaultCreatedAt()
+ buc.mutation.SetCreatedAt(v)
+ }
+ if _, ok := buc.mutation.UpdatedAt(); !ok {
+ if billingusage.DefaultUpdatedAt == nil {
+ return fmt.Errorf("db: uninitialized billingusage.DefaultUpdatedAt (forgotten import db/runtime?)")
+ }
+ v := billingusage.DefaultUpdatedAt()
+ buc.mutation.SetUpdatedAt(v)
+ }
+ return nil
+}
+
+// check runs all checks and user-defined validators on the builder.
+func (buc *BillingUsageCreate) check() error {
+ if _, ok := buc.mutation.UserID(); !ok {
+ return &ValidationError{Name: "user_id", err: errors.New(`db: missing required field "BillingUsage.user_id"`)}
+ }
+ if _, ok := buc.mutation.ModelName(); !ok {
+ return &ValidationError{Name: "model_name", err: errors.New(`db: missing required field "BillingUsage.model_name"`)}
+ }
+ if _, ok := buc.mutation.Tokens(); !ok {
+ return &ValidationError{Name: "tokens", err: errors.New(`db: missing required field "BillingUsage.tokens"`)}
+ }
+ if _, ok := buc.mutation.Operation(); !ok {
+ return &ValidationError{Name: "operation", err: errors.New(`db: missing required field "BillingUsage.operation"`)}
+ }
+ if _, ok := buc.mutation.CreatedAt(); !ok {
+ return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "BillingUsage.created_at"`)}
+ }
+ if _, ok := buc.mutation.UpdatedAt(); !ok {
+ return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "BillingUsage.updated_at"`)}
+ }
+ return nil
+}
+
+func (buc *BillingUsageCreate) sqlSave(ctx context.Context) (*BillingUsage, error) {
+ if err := buc.check(); err != nil {
+ return nil, err
+ }
+ _node, _spec := buc.createSpec()
+ if err := sqlgraph.CreateNode(ctx, buc.driver, _spec); err != nil {
+ if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return nil, err
+ }
+ if _spec.ID.Value != nil {
+ if id, ok := _spec.ID.Value.(string); ok {
+ _node.ID = id
+ } else {
+ return nil, fmt.Errorf("unexpected BillingUsage.ID type: %T", _spec.ID.Value)
+ }
+ }
+ buc.mutation.id = &_node.ID
+ buc.mutation.done = true
+ return _node, nil
+}
+
+func (buc *BillingUsageCreate) createSpec() (*BillingUsage, *sqlgraph.CreateSpec) {
+ var (
+ _node = &BillingUsage{config: buc.config}
+ _spec = sqlgraph.NewCreateSpec(billingusage.Table, sqlgraph.NewFieldSpec(billingusage.FieldID, field.TypeString))
+ )
+ _spec.OnConflict = buc.conflict
+ if id, ok := buc.mutation.ID(); ok {
+ _node.ID = id
+ _spec.ID.Value = id
+ }
+ if value, ok := buc.mutation.DeletedAt(); ok {
+ _spec.SetField(billingusage.FieldDeletedAt, field.TypeTime, value)
+ _node.DeletedAt = value
+ }
+ if value, ok := buc.mutation.UserID(); ok {
+ _spec.SetField(billingusage.FieldUserID, field.TypeString, value)
+ _node.UserID = value
+ }
+ if value, ok := buc.mutation.ModelName(); ok {
+ _spec.SetField(billingusage.FieldModelName, field.TypeString, value)
+ _node.ModelName = value
+ }
+ if value, ok := buc.mutation.Tokens(); ok {
+ _spec.SetField(billingusage.FieldTokens, field.TypeInt64, value)
+ _node.Tokens = value
+ }
+ if value, ok := buc.mutation.Operation(); ok {
+ _spec.SetField(billingusage.FieldOperation, field.TypeString, value)
+ _node.Operation = value
+ }
+ if value, ok := buc.mutation.CreatedAt(); ok {
+ _spec.SetField(billingusage.FieldCreatedAt, field.TypeTime, value)
+ _node.CreatedAt = value
+ }
+ if value, ok := buc.mutation.UpdatedAt(); ok {
+ _spec.SetField(billingusage.FieldUpdatedAt, field.TypeTime, value)
+ _node.UpdatedAt = value
+ }
+ return _node, _spec
+}
+
+// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
+// of the `INSERT` statement. For example:
+//
+// client.BillingUsage.Create().
+// SetDeletedAt(v).
+// OnConflict(
+// // Update the row with the new values
+// // the was proposed for insertion.
+// sql.ResolveWithNewValues(),
+// ).
+// // Override some of the fields with custom
+// // update values.
+// Update(func(u *ent.BillingUsageUpsert) {
+// SetDeletedAt(v+v).
+// }).
+// Exec(ctx)
+func (buc *BillingUsageCreate) OnConflict(opts ...sql.ConflictOption) *BillingUsageUpsertOne {
+ buc.conflict = opts
+ return &BillingUsageUpsertOne{
+ create: buc,
+ }
+}
+
+// OnConflictColumns calls `OnConflict` and configures the columns
+// as conflict target. Using this option is equivalent to using:
+//
+// client.BillingUsage.Create().
+// OnConflict(sql.ConflictColumns(columns...)).
+// Exec(ctx)
+func (buc *BillingUsageCreate) OnConflictColumns(columns ...string) *BillingUsageUpsertOne {
+ buc.conflict = append(buc.conflict, sql.ConflictColumns(columns...))
+ return &BillingUsageUpsertOne{
+ create: buc,
+ }
+}
+
+type (
+ // BillingUsageUpsertOne is the builder for "upsert"-ing
+ // one BillingUsage node.
+ BillingUsageUpsertOne struct {
+ create *BillingUsageCreate
+ }
+
+ // BillingUsageUpsert is the "OnConflict" setter.
+ BillingUsageUpsert struct {
+ *sql.UpdateSet
+ }
+)
+
+// SetDeletedAt sets the "deleted_at" field.
+func (u *BillingUsageUpsert) SetDeletedAt(v time.Time) *BillingUsageUpsert {
+ u.Set(billingusage.FieldDeletedAt, v)
+ return u
+}
+
+// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create.
+func (u *BillingUsageUpsert) UpdateDeletedAt() *BillingUsageUpsert {
+ u.SetExcluded(billingusage.FieldDeletedAt)
+ return u
+}
+
+// ClearDeletedAt clears the value of the "deleted_at" field.
+func (u *BillingUsageUpsert) ClearDeletedAt() *BillingUsageUpsert {
+ u.SetNull(billingusage.FieldDeletedAt)
+ return u
+}
+
+// SetUserID sets the "user_id" field.
+func (u *BillingUsageUpsert) SetUserID(v string) *BillingUsageUpsert {
+ u.Set(billingusage.FieldUserID, v)
+ return u
+}
+
+// UpdateUserID sets the "user_id" field to the value that was provided on create.
+func (u *BillingUsageUpsert) UpdateUserID() *BillingUsageUpsert {
+ u.SetExcluded(billingusage.FieldUserID)
+ return u
+}
+
+// SetModelName sets the "model_name" field.
+func (u *BillingUsageUpsert) SetModelName(v string) *BillingUsageUpsert {
+ u.Set(billingusage.FieldModelName, v)
+ return u
+}
+
+// UpdateModelName sets the "model_name" field to the value that was provided on create.
+func (u *BillingUsageUpsert) UpdateModelName() *BillingUsageUpsert {
+ u.SetExcluded(billingusage.FieldModelName)
+ return u
+}
+
+// SetTokens sets the "tokens" field.
+func (u *BillingUsageUpsert) SetTokens(v int64) *BillingUsageUpsert {
+ u.Set(billingusage.FieldTokens, v)
+ return u
+}
+
+// UpdateTokens sets the "tokens" field to the value that was provided on create.
+func (u *BillingUsageUpsert) UpdateTokens() *BillingUsageUpsert {
+ u.SetExcluded(billingusage.FieldTokens)
+ return u
+}
+
+// AddTokens adds v to the "tokens" field.
+func (u *BillingUsageUpsert) AddTokens(v int64) *BillingUsageUpsert {
+ u.Add(billingusage.FieldTokens, v)
+ return u
+}
+
+// SetOperation sets the "operation" field.
+func (u *BillingUsageUpsert) SetOperation(v string) *BillingUsageUpsert {
+ u.Set(billingusage.FieldOperation, v)
+ return u
+}
+
+// UpdateOperation sets the "operation" field to the value that was provided on create.
+func (u *BillingUsageUpsert) UpdateOperation() *BillingUsageUpsert {
+ u.SetExcluded(billingusage.FieldOperation)
+ return u
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (u *BillingUsageUpsert) SetCreatedAt(v time.Time) *BillingUsageUpsert {
+ u.Set(billingusage.FieldCreatedAt, v)
+ return u
+}
+
+// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
+func (u *BillingUsageUpsert) UpdateCreatedAt() *BillingUsageUpsert {
+ u.SetExcluded(billingusage.FieldCreatedAt)
+ return u
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (u *BillingUsageUpsert) SetUpdatedAt(v time.Time) *BillingUsageUpsert {
+ u.Set(billingusage.FieldUpdatedAt, v)
+ return u
+}
+
+// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
+func (u *BillingUsageUpsert) UpdateUpdatedAt() *BillingUsageUpsert {
+ u.SetExcluded(billingusage.FieldUpdatedAt)
+ return u
+}
+
+// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field.
+// Using this option is equivalent to using:
+//
+// client.BillingUsage.Create().
+// OnConflict(
+// sql.ResolveWithNewValues(),
+// sql.ResolveWith(func(u *sql.UpdateSet) {
+// u.SetIgnore(billingusage.FieldID)
+// }),
+// ).
+// Exec(ctx)
+func (u *BillingUsageUpsertOne) UpdateNewValues() *BillingUsageUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
+ if _, exists := u.create.mutation.ID(); exists {
+ s.SetIgnore(billingusage.FieldID)
+ }
+ }))
+ return u
+}
+
+// Ignore sets each column to itself in case of conflict.
+// Using this option is equivalent to using:
+//
+// client.BillingUsage.Create().
+// OnConflict(sql.ResolveWithIgnore()).
+// Exec(ctx)
+func (u *BillingUsageUpsertOne) Ignore() *BillingUsageUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
+ return u
+}
+
+// DoNothing configures the conflict_action to `DO NOTHING`.
+// Supported only by SQLite and PostgreSQL.
+func (u *BillingUsageUpsertOne) DoNothing() *BillingUsageUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.DoNothing())
+ return u
+}
+
+// Update allows overriding fields `UPDATE` values. See the BillingUsageCreate.OnConflict
+// documentation for more info.
+func (u *BillingUsageUpsertOne) Update(set func(*BillingUsageUpsert)) *BillingUsageUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
+ set(&BillingUsageUpsert{UpdateSet: update})
+ }))
+ return u
+}
+
+// SetDeletedAt sets the "deleted_at" field.
+func (u *BillingUsageUpsertOne) SetDeletedAt(v time.Time) *BillingUsageUpsertOne {
+ return u.Update(func(s *BillingUsageUpsert) {
+ s.SetDeletedAt(v)
+ })
+}
+
+// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create.
+func (u *BillingUsageUpsertOne) UpdateDeletedAt() *BillingUsageUpsertOne {
+ return u.Update(func(s *BillingUsageUpsert) {
+ s.UpdateDeletedAt()
+ })
+}
+
+// ClearDeletedAt clears the value of the "deleted_at" field.
+func (u *BillingUsageUpsertOne) ClearDeletedAt() *BillingUsageUpsertOne {
+ return u.Update(func(s *BillingUsageUpsert) {
+ s.ClearDeletedAt()
+ })
+}
+
+// SetUserID sets the "user_id" field.
+func (u *BillingUsageUpsertOne) SetUserID(v string) *BillingUsageUpsertOne {
+ return u.Update(func(s *BillingUsageUpsert) {
+ s.SetUserID(v)
+ })
+}
+
+// UpdateUserID sets the "user_id" field to the value that was provided on create.
+func (u *BillingUsageUpsertOne) UpdateUserID() *BillingUsageUpsertOne {
+ return u.Update(func(s *BillingUsageUpsert) {
+ s.UpdateUserID()
+ })
+}
+
+// SetModelName sets the "model_name" field.
+func (u *BillingUsageUpsertOne) SetModelName(v string) *BillingUsageUpsertOne {
+ return u.Update(func(s *BillingUsageUpsert) {
+ s.SetModelName(v)
+ })
+}
+
+// UpdateModelName sets the "model_name" field to the value that was provided on create.
+func (u *BillingUsageUpsertOne) UpdateModelName() *BillingUsageUpsertOne {
+ return u.Update(func(s *BillingUsageUpsert) {
+ s.UpdateModelName()
+ })
+}
+
+// SetTokens sets the "tokens" field.
+func (u *BillingUsageUpsertOne) SetTokens(v int64) *BillingUsageUpsertOne {
+ return u.Update(func(s *BillingUsageUpsert) {
+ s.SetTokens(v)
+ })
+}
+
+// AddTokens adds v to the "tokens" field.
+func (u *BillingUsageUpsertOne) AddTokens(v int64) *BillingUsageUpsertOne {
+ return u.Update(func(s *BillingUsageUpsert) {
+ s.AddTokens(v)
+ })
+}
+
+// UpdateTokens sets the "tokens" field to the value that was provided on create.
+func (u *BillingUsageUpsertOne) UpdateTokens() *BillingUsageUpsertOne {
+ return u.Update(func(s *BillingUsageUpsert) {
+ s.UpdateTokens()
+ })
+}
+
+// SetOperation sets the "operation" field.
+func (u *BillingUsageUpsertOne) SetOperation(v string) *BillingUsageUpsertOne {
+ return u.Update(func(s *BillingUsageUpsert) {
+ s.SetOperation(v)
+ })
+}
+
+// UpdateOperation sets the "operation" field to the value that was provided on create.
+func (u *BillingUsageUpsertOne) UpdateOperation() *BillingUsageUpsertOne {
+ return u.Update(func(s *BillingUsageUpsert) {
+ s.UpdateOperation()
+ })
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (u *BillingUsageUpsertOne) SetCreatedAt(v time.Time) *BillingUsageUpsertOne {
+ return u.Update(func(s *BillingUsageUpsert) {
+ s.SetCreatedAt(v)
+ })
+}
+
+// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
+func (u *BillingUsageUpsertOne) UpdateCreatedAt() *BillingUsageUpsertOne {
+ return u.Update(func(s *BillingUsageUpsert) {
+ s.UpdateCreatedAt()
+ })
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (u *BillingUsageUpsertOne) SetUpdatedAt(v time.Time) *BillingUsageUpsertOne {
+ return u.Update(func(s *BillingUsageUpsert) {
+ s.SetUpdatedAt(v)
+ })
+}
+
+// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
+func (u *BillingUsageUpsertOne) UpdateUpdatedAt() *BillingUsageUpsertOne {
+ return u.Update(func(s *BillingUsageUpsert) {
+ s.UpdateUpdatedAt()
+ })
+}
+
+// Exec executes the query.
+func (u *BillingUsageUpsertOne) Exec(ctx context.Context) error {
+ if len(u.create.conflict) == 0 {
+ return errors.New("db: missing options for BillingUsageCreate.OnConflict")
+ }
+ return u.create.Exec(ctx)
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (u *BillingUsageUpsertOne) ExecX(ctx context.Context) {
+ if err := u.create.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// Exec executes the UPSERT query and returns the inserted/updated ID.
+func (u *BillingUsageUpsertOne) ID(ctx context.Context) (id string, err error) {
+ if u.create.driver.Dialect() == dialect.MySQL {
+ // In case of "ON CONFLICT", there is no way to get back non-numeric ID
+ // fields from the database since MySQL does not support the RETURNING clause.
+ return id, errors.New("db: BillingUsageUpsertOne.ID is not supported by MySQL driver. Use BillingUsageUpsertOne.Exec instead")
+ }
+ node, err := u.create.Save(ctx)
+ if err != nil {
+ return id, err
+ }
+ return node.ID, nil
+}
+
+// IDX is like ID, but panics if an error occurs.
+func (u *BillingUsageUpsertOne) IDX(ctx context.Context) string {
+ id, err := u.ID(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return id
+}
+
+// BillingUsageCreateBulk is the builder for creating many BillingUsage entities in bulk.
+type BillingUsageCreateBulk struct {
+ config
+ err error
+ builders []*BillingUsageCreate
+ conflict []sql.ConflictOption
+}
+
+// Save creates the BillingUsage entities in the database.
+func (bucb *BillingUsageCreateBulk) Save(ctx context.Context) ([]*BillingUsage, error) {
+ if bucb.err != nil {
+ return nil, bucb.err
+ }
+ specs := make([]*sqlgraph.CreateSpec, len(bucb.builders))
+ nodes := make([]*BillingUsage, len(bucb.builders))
+ mutators := make([]Mutator, len(bucb.builders))
+ for i := range bucb.builders {
+ func(i int, root context.Context) {
+ builder := bucb.builders[i]
+ builder.defaults()
+ var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
+ mutation, ok := m.(*BillingUsageMutation)
+ if !ok {
+ return nil, fmt.Errorf("unexpected mutation type %T", m)
+ }
+ if err := builder.check(); err != nil {
+ return nil, err
+ }
+ builder.mutation = mutation
+ var err error
+ nodes[i], specs[i] = builder.createSpec()
+ if i < len(mutators)-1 {
+ _, err = mutators[i+1].Mutate(root, bucb.builders[i+1].mutation)
+ } else {
+ spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
+ spec.OnConflict = bucb.conflict
+ // Invoke the actual operation on the latest mutation in the chain.
+ if err = sqlgraph.BatchCreate(ctx, bucb.driver, spec); err != nil {
+ if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ }
+ }
+ if err != nil {
+ return nil, err
+ }
+ mutation.id = &nodes[i].ID
+ mutation.done = true
+ return nodes[i], nil
+ })
+ for i := len(builder.hooks) - 1; i >= 0; i-- {
+ mut = builder.hooks[i](mut)
+ }
+ mutators[i] = mut
+ }(i, ctx)
+ }
+ if len(mutators) > 0 {
+ if _, err := mutators[0].Mutate(ctx, bucb.builders[0].mutation); err != nil {
+ return nil, err
+ }
+ }
+ return nodes, nil
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (bucb *BillingUsageCreateBulk) SaveX(ctx context.Context) []*BillingUsage {
+ v, err := bucb.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return v
+}
+
+// Exec executes the query.
+func (bucb *BillingUsageCreateBulk) Exec(ctx context.Context) error {
+ _, err := bucb.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (bucb *BillingUsageCreateBulk) ExecX(ctx context.Context) {
+ if err := bucb.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
+// of the `INSERT` statement. For example:
+//
+// client.BillingUsage.CreateBulk(builders...).
+// OnConflict(
+// // Update the row with the new values
+// // the was proposed for insertion.
+// sql.ResolveWithNewValues(),
+// ).
+// // Override some of the fields with custom
+// // update values.
+// Update(func(u *ent.BillingUsageUpsert) {
+// SetDeletedAt(v+v).
+// }).
+// Exec(ctx)
+func (bucb *BillingUsageCreateBulk) OnConflict(opts ...sql.ConflictOption) *BillingUsageUpsertBulk {
+ bucb.conflict = opts
+ return &BillingUsageUpsertBulk{
+ create: bucb,
+ }
+}
+
+// OnConflictColumns calls `OnConflict` and configures the columns
+// as conflict target. Using this option is equivalent to using:
+//
+// client.BillingUsage.Create().
+// OnConflict(sql.ConflictColumns(columns...)).
+// Exec(ctx)
+func (bucb *BillingUsageCreateBulk) OnConflictColumns(columns ...string) *BillingUsageUpsertBulk {
+ bucb.conflict = append(bucb.conflict, sql.ConflictColumns(columns...))
+ return &BillingUsageUpsertBulk{
+ create: bucb,
+ }
+}
+
+// BillingUsageUpsertBulk is the builder for "upsert"-ing
+// a bulk of BillingUsage nodes.
+type BillingUsageUpsertBulk struct {
+ create *BillingUsageCreateBulk
+}
+
+// UpdateNewValues updates the mutable fields using the new values that
+// were set on create. Using this option is equivalent to using:
+//
+// client.BillingUsage.Create().
+// OnConflict(
+// sql.ResolveWithNewValues(),
+// sql.ResolveWith(func(u *sql.UpdateSet) {
+// u.SetIgnore(billingusage.FieldID)
+// }),
+// ).
+// Exec(ctx)
+func (u *BillingUsageUpsertBulk) UpdateNewValues() *BillingUsageUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
+ for _, b := range u.create.builders {
+ if _, exists := b.mutation.ID(); exists {
+ s.SetIgnore(billingusage.FieldID)
+ }
+ }
+ }))
+ return u
+}
+
+// Ignore sets each column to itself in case of conflict.
+// Using this option is equivalent to using:
+//
+// client.BillingUsage.Create().
+// OnConflict(sql.ResolveWithIgnore()).
+// Exec(ctx)
+func (u *BillingUsageUpsertBulk) Ignore() *BillingUsageUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
+ return u
+}
+
+// DoNothing configures the conflict_action to `DO NOTHING`.
+// Supported only by SQLite and PostgreSQL.
+func (u *BillingUsageUpsertBulk) DoNothing() *BillingUsageUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.DoNothing())
+ return u
+}
+
+// Update allows overriding fields `UPDATE` values. See the BillingUsageCreateBulk.OnConflict
+// documentation for more info.
+func (u *BillingUsageUpsertBulk) Update(set func(*BillingUsageUpsert)) *BillingUsageUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
+ set(&BillingUsageUpsert{UpdateSet: update})
+ }))
+ return u
+}
+
+// SetDeletedAt sets the "deleted_at" field.
+func (u *BillingUsageUpsertBulk) SetDeletedAt(v time.Time) *BillingUsageUpsertBulk {
+ return u.Update(func(s *BillingUsageUpsert) {
+ s.SetDeletedAt(v)
+ })
+}
+
+// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create.
+func (u *BillingUsageUpsertBulk) UpdateDeletedAt() *BillingUsageUpsertBulk {
+ return u.Update(func(s *BillingUsageUpsert) {
+ s.UpdateDeletedAt()
+ })
+}
+
+// ClearDeletedAt clears the value of the "deleted_at" field.
+func (u *BillingUsageUpsertBulk) ClearDeletedAt() *BillingUsageUpsertBulk {
+ return u.Update(func(s *BillingUsageUpsert) {
+ s.ClearDeletedAt()
+ })
+}
+
+// SetUserID sets the "user_id" field.
+func (u *BillingUsageUpsertBulk) SetUserID(v string) *BillingUsageUpsertBulk {
+ return u.Update(func(s *BillingUsageUpsert) {
+ s.SetUserID(v)
+ })
+}
+
+// UpdateUserID sets the "user_id" field to the value that was provided on create.
+func (u *BillingUsageUpsertBulk) UpdateUserID() *BillingUsageUpsertBulk {
+ return u.Update(func(s *BillingUsageUpsert) {
+ s.UpdateUserID()
+ })
+}
+
+// SetModelName sets the "model_name" field.
+func (u *BillingUsageUpsertBulk) SetModelName(v string) *BillingUsageUpsertBulk {
+ return u.Update(func(s *BillingUsageUpsert) {
+ s.SetModelName(v)
+ })
+}
+
+// UpdateModelName sets the "model_name" field to the value that was provided on create.
+func (u *BillingUsageUpsertBulk) UpdateModelName() *BillingUsageUpsertBulk {
+ return u.Update(func(s *BillingUsageUpsert) {
+ s.UpdateModelName()
+ })
+}
+
+// SetTokens sets the "tokens" field.
+func (u *BillingUsageUpsertBulk) SetTokens(v int64) *BillingUsageUpsertBulk {
+ return u.Update(func(s *BillingUsageUpsert) {
+ s.SetTokens(v)
+ })
+}
+
+// AddTokens adds v to the "tokens" field.
+func (u *BillingUsageUpsertBulk) AddTokens(v int64) *BillingUsageUpsertBulk {
+ return u.Update(func(s *BillingUsageUpsert) {
+ s.AddTokens(v)
+ })
+}
+
+// UpdateTokens sets the "tokens" field to the value that was provided on create.
+func (u *BillingUsageUpsertBulk) UpdateTokens() *BillingUsageUpsertBulk {
+ return u.Update(func(s *BillingUsageUpsert) {
+ s.UpdateTokens()
+ })
+}
+
+// SetOperation sets the "operation" field.
+func (u *BillingUsageUpsertBulk) SetOperation(v string) *BillingUsageUpsertBulk {
+ return u.Update(func(s *BillingUsageUpsert) {
+ s.SetOperation(v)
+ })
+}
+
+// UpdateOperation sets the "operation" field to the value that was provided on create.
+func (u *BillingUsageUpsertBulk) UpdateOperation() *BillingUsageUpsertBulk {
+ return u.Update(func(s *BillingUsageUpsert) {
+ s.UpdateOperation()
+ })
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (u *BillingUsageUpsertBulk) SetCreatedAt(v time.Time) *BillingUsageUpsertBulk {
+ return u.Update(func(s *BillingUsageUpsert) {
+ s.SetCreatedAt(v)
+ })
+}
+
+// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
+func (u *BillingUsageUpsertBulk) UpdateCreatedAt() *BillingUsageUpsertBulk {
+ return u.Update(func(s *BillingUsageUpsert) {
+ s.UpdateCreatedAt()
+ })
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (u *BillingUsageUpsertBulk) SetUpdatedAt(v time.Time) *BillingUsageUpsertBulk {
+ return u.Update(func(s *BillingUsageUpsert) {
+ s.SetUpdatedAt(v)
+ })
+}
+
+// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
+func (u *BillingUsageUpsertBulk) UpdateUpdatedAt() *BillingUsageUpsertBulk {
+ return u.Update(func(s *BillingUsageUpsert) {
+ s.UpdateUpdatedAt()
+ })
+}
+
+// Exec executes the query.
+func (u *BillingUsageUpsertBulk) Exec(ctx context.Context) error {
+ if u.create.err != nil {
+ return u.create.err
+ }
+ for i, b := range u.create.builders {
+ if len(b.conflict) != 0 {
+ return fmt.Errorf("db: OnConflict was set for builder %d. Set it on the BillingUsageCreateBulk instead", i)
+ }
+ }
+ if len(u.create.conflict) == 0 {
+ return errors.New("db: missing options for BillingUsageCreateBulk.OnConflict")
+ }
+ return u.create.Exec(ctx)
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (u *BillingUsageUpsertBulk) ExecX(ctx context.Context) {
+ if err := u.create.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
diff --git a/backend/db/billingusage_delete.go b/backend/db/billingusage_delete.go
new file mode 100644
index 0000000..e6be81c
--- /dev/null
+++ b/backend/db/billingusage_delete.go
@@ -0,0 +1,88 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/billingusage"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+)
+
+// BillingUsageDelete is the builder for deleting a BillingUsage entity.
+type BillingUsageDelete struct {
+ config
+ hooks []Hook
+ mutation *BillingUsageMutation
+}
+
+// Where appends a list predicates to the BillingUsageDelete builder.
+func (bud *BillingUsageDelete) Where(ps ...predicate.BillingUsage) *BillingUsageDelete {
+ bud.mutation.Where(ps...)
+ return bud
+}
+
+// Exec executes the deletion query and returns how many vertices were deleted.
+func (bud *BillingUsageDelete) Exec(ctx context.Context) (int, error) {
+ return withHooks(ctx, bud.sqlExec, bud.mutation, bud.hooks)
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (bud *BillingUsageDelete) ExecX(ctx context.Context) int {
+ n, err := bud.Exec(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return n
+}
+
+func (bud *BillingUsageDelete) sqlExec(ctx context.Context) (int, error) {
+ _spec := sqlgraph.NewDeleteSpec(billingusage.Table, sqlgraph.NewFieldSpec(billingusage.FieldID, field.TypeString))
+ if ps := bud.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ affected, err := sqlgraph.DeleteNodes(ctx, bud.driver, _spec)
+ if err != nil && sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ bud.mutation.done = true
+ return affected, err
+}
+
+// BillingUsageDeleteOne is the builder for deleting a single BillingUsage entity.
+type BillingUsageDeleteOne struct {
+ bud *BillingUsageDelete
+}
+
+// Where appends a list predicates to the BillingUsageDelete builder.
+func (budo *BillingUsageDeleteOne) Where(ps ...predicate.BillingUsage) *BillingUsageDeleteOne {
+ budo.bud.mutation.Where(ps...)
+ return budo
+}
+
+// Exec executes the deletion query.
+func (budo *BillingUsageDeleteOne) Exec(ctx context.Context) error {
+ n, err := budo.bud.Exec(ctx)
+ switch {
+ case err != nil:
+ return err
+ case n == 0:
+ return &NotFoundError{billingusage.Label}
+ default:
+ return nil
+ }
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (budo *BillingUsageDeleteOne) ExecX(ctx context.Context) {
+ if err := budo.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
diff --git a/backend/db/billingusage_query.go b/backend/db/billingusage_query.go
new file mode 100644
index 0000000..03ecb4f
--- /dev/null
+++ b/backend/db/billingusage_query.go
@@ -0,0 +1,577 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "fmt"
+ "math"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect"
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/billingusage"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+)
+
+// BillingUsageQuery is the builder for querying BillingUsage entities.
+type BillingUsageQuery struct {
+ config
+ ctx *QueryContext
+ order []billingusage.OrderOption
+ inters []Interceptor
+ predicates []predicate.BillingUsage
+ modifiers []func(*sql.Selector)
+ // intermediate query (i.e. traversal path).
+ sql *sql.Selector
+ path func(context.Context) (*sql.Selector, error)
+}
+
+// Where adds a new predicate for the BillingUsageQuery builder.
+func (buq *BillingUsageQuery) Where(ps ...predicate.BillingUsage) *BillingUsageQuery {
+ buq.predicates = append(buq.predicates, ps...)
+ return buq
+}
+
+// Limit the number of records to be returned by this query.
+func (buq *BillingUsageQuery) Limit(limit int) *BillingUsageQuery {
+ buq.ctx.Limit = &limit
+ return buq
+}
+
+// Offset to start from.
+func (buq *BillingUsageQuery) Offset(offset int) *BillingUsageQuery {
+ buq.ctx.Offset = &offset
+ return buq
+}
+
+// Unique configures the query builder to filter duplicate records on query.
+// By default, unique is set to true, and can be disabled using this method.
+func (buq *BillingUsageQuery) Unique(unique bool) *BillingUsageQuery {
+ buq.ctx.Unique = &unique
+ return buq
+}
+
+// Order specifies how the records should be ordered.
+func (buq *BillingUsageQuery) Order(o ...billingusage.OrderOption) *BillingUsageQuery {
+ buq.order = append(buq.order, o...)
+ return buq
+}
+
+// First returns the first BillingUsage entity from the query.
+// Returns a *NotFoundError when no BillingUsage was found.
+func (buq *BillingUsageQuery) First(ctx context.Context) (*BillingUsage, error) {
+ nodes, err := buq.Limit(1).All(setContextOp(ctx, buq.ctx, ent.OpQueryFirst))
+ if err != nil {
+ return nil, err
+ }
+ if len(nodes) == 0 {
+ return nil, &NotFoundError{billingusage.Label}
+ }
+ return nodes[0], nil
+}
+
+// FirstX is like First, but panics if an error occurs.
+func (buq *BillingUsageQuery) FirstX(ctx context.Context) *BillingUsage {
+ node, err := buq.First(ctx)
+ if err != nil && !IsNotFound(err) {
+ panic(err)
+ }
+ return node
+}
+
+// FirstID returns the first BillingUsage ID from the query.
+// Returns a *NotFoundError when no BillingUsage ID was found.
+func (buq *BillingUsageQuery) FirstID(ctx context.Context) (id string, err error) {
+ var ids []string
+ if ids, err = buq.Limit(1).IDs(setContextOp(ctx, buq.ctx, ent.OpQueryFirstID)); err != nil {
+ return
+ }
+ if len(ids) == 0 {
+ err = &NotFoundError{billingusage.Label}
+ return
+ }
+ return ids[0], nil
+}
+
+// FirstIDX is like FirstID, but panics if an error occurs.
+func (buq *BillingUsageQuery) FirstIDX(ctx context.Context) string {
+ id, err := buq.FirstID(ctx)
+ if err != nil && !IsNotFound(err) {
+ panic(err)
+ }
+ return id
+}
+
+// Only returns a single BillingUsage entity found by the query, ensuring it only returns one.
+// Returns a *NotSingularError when more than one BillingUsage entity is found.
+// Returns a *NotFoundError when no BillingUsage entities are found.
+func (buq *BillingUsageQuery) Only(ctx context.Context) (*BillingUsage, error) {
+ nodes, err := buq.Limit(2).All(setContextOp(ctx, buq.ctx, ent.OpQueryOnly))
+ if err != nil {
+ return nil, err
+ }
+ switch len(nodes) {
+ case 1:
+ return nodes[0], nil
+ case 0:
+ return nil, &NotFoundError{billingusage.Label}
+ default:
+ return nil, &NotSingularError{billingusage.Label}
+ }
+}
+
+// OnlyX is like Only, but panics if an error occurs.
+func (buq *BillingUsageQuery) OnlyX(ctx context.Context) *BillingUsage {
+ node, err := buq.Only(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return node
+}
+
+// OnlyID is like Only, but returns the only BillingUsage ID in the query.
+// Returns a *NotSingularError when more than one BillingUsage ID is found.
+// Returns a *NotFoundError when no entities are found.
+func (buq *BillingUsageQuery) OnlyID(ctx context.Context) (id string, err error) {
+ var ids []string
+ if ids, err = buq.Limit(2).IDs(setContextOp(ctx, buq.ctx, ent.OpQueryOnlyID)); err != nil {
+ return
+ }
+ switch len(ids) {
+ case 1:
+ id = ids[0]
+ case 0:
+ err = &NotFoundError{billingusage.Label}
+ default:
+ err = &NotSingularError{billingusage.Label}
+ }
+ return
+}
+
+// OnlyIDX is like OnlyID, but panics if an error occurs.
+func (buq *BillingUsageQuery) OnlyIDX(ctx context.Context) string {
+ id, err := buq.OnlyID(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return id
+}
+
+// All executes the query and returns a list of BillingUsages.
+func (buq *BillingUsageQuery) All(ctx context.Context) ([]*BillingUsage, error) {
+ ctx = setContextOp(ctx, buq.ctx, ent.OpQueryAll)
+ if err := buq.prepareQuery(ctx); err != nil {
+ return nil, err
+ }
+ qr := querierAll[[]*BillingUsage, *BillingUsageQuery]()
+ return withInterceptors[[]*BillingUsage](ctx, buq, qr, buq.inters)
+}
+
+// AllX is like All, but panics if an error occurs.
+func (buq *BillingUsageQuery) AllX(ctx context.Context) []*BillingUsage {
+ nodes, err := buq.All(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return nodes
+}
+
+// IDs executes the query and returns a list of BillingUsage IDs.
+func (buq *BillingUsageQuery) IDs(ctx context.Context) (ids []string, err error) {
+ if buq.ctx.Unique == nil && buq.path != nil {
+ buq.Unique(true)
+ }
+ ctx = setContextOp(ctx, buq.ctx, ent.OpQueryIDs)
+ if err = buq.Select(billingusage.FieldID).Scan(ctx, &ids); err != nil {
+ return nil, err
+ }
+ return ids, nil
+}
+
+// IDsX is like IDs, but panics if an error occurs.
+func (buq *BillingUsageQuery) IDsX(ctx context.Context) []string {
+ ids, err := buq.IDs(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return ids
+}
+
+// Count returns the count of the given query.
+func (buq *BillingUsageQuery) Count(ctx context.Context) (int, error) {
+ ctx = setContextOp(ctx, buq.ctx, ent.OpQueryCount)
+ if err := buq.prepareQuery(ctx); err != nil {
+ return 0, err
+ }
+ return withInterceptors[int](ctx, buq, querierCount[*BillingUsageQuery](), buq.inters)
+}
+
+// CountX is like Count, but panics if an error occurs.
+func (buq *BillingUsageQuery) CountX(ctx context.Context) int {
+ count, err := buq.Count(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return count
+}
+
+// Exist returns true if the query has elements in the graph.
+func (buq *BillingUsageQuery) Exist(ctx context.Context) (bool, error) {
+ ctx = setContextOp(ctx, buq.ctx, ent.OpQueryExist)
+ switch _, err := buq.FirstID(ctx); {
+ case IsNotFound(err):
+ return false, nil
+ case err != nil:
+ return false, fmt.Errorf("db: check existence: %w", err)
+ default:
+ return true, nil
+ }
+}
+
+// ExistX is like Exist, but panics if an error occurs.
+func (buq *BillingUsageQuery) ExistX(ctx context.Context) bool {
+ exist, err := buq.Exist(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return exist
+}
+
+// Clone returns a duplicate of the BillingUsageQuery builder, including all associated steps. It can be
+// used to prepare common query builders and use them differently after the clone is made.
+func (buq *BillingUsageQuery) Clone() *BillingUsageQuery {
+ if buq == nil {
+ return nil
+ }
+ return &BillingUsageQuery{
+ config: buq.config,
+ ctx: buq.ctx.Clone(),
+ order: append([]billingusage.OrderOption{}, buq.order...),
+ inters: append([]Interceptor{}, buq.inters...),
+ predicates: append([]predicate.BillingUsage{}, buq.predicates...),
+ // clone intermediate query.
+ sql: buq.sql.Clone(),
+ path: buq.path,
+ modifiers: append([]func(*sql.Selector){}, buq.modifiers...),
+ }
+}
+
+// GroupBy is used to group vertices by one or more fields/columns.
+// It is often used with aggregate functions, like: count, max, mean, min, sum.
+//
+// Example:
+//
+// var v []struct {
+// DeletedAt time.Time `json:"deleted_at,omitempty"`
+// Count int `json:"count,omitempty"`
+// }
+//
+// client.BillingUsage.Query().
+// GroupBy(billingusage.FieldDeletedAt).
+// Aggregate(db.Count()).
+// Scan(ctx, &v)
+func (buq *BillingUsageQuery) GroupBy(field string, fields ...string) *BillingUsageGroupBy {
+ buq.ctx.Fields = append([]string{field}, fields...)
+ grbuild := &BillingUsageGroupBy{build: buq}
+ grbuild.flds = &buq.ctx.Fields
+ grbuild.label = billingusage.Label
+ grbuild.scan = grbuild.Scan
+ return grbuild
+}
+
+// Select allows the selection one or more fields/columns for the given query,
+// instead of selecting all fields in the entity.
+//
+// Example:
+//
+// var v []struct {
+// DeletedAt time.Time `json:"deleted_at,omitempty"`
+// }
+//
+// client.BillingUsage.Query().
+// Select(billingusage.FieldDeletedAt).
+// Scan(ctx, &v)
+func (buq *BillingUsageQuery) Select(fields ...string) *BillingUsageSelect {
+ buq.ctx.Fields = append(buq.ctx.Fields, fields...)
+ sbuild := &BillingUsageSelect{BillingUsageQuery: buq}
+ sbuild.label = billingusage.Label
+ sbuild.flds, sbuild.scan = &buq.ctx.Fields, sbuild.Scan
+ return sbuild
+}
+
+// Aggregate returns a BillingUsageSelect configured with the given aggregations.
+func (buq *BillingUsageQuery) Aggregate(fns ...AggregateFunc) *BillingUsageSelect {
+ return buq.Select().Aggregate(fns...)
+}
+
+func (buq *BillingUsageQuery) prepareQuery(ctx context.Context) error {
+ for _, inter := range buq.inters {
+ if inter == nil {
+ return fmt.Errorf("db: uninitialized interceptor (forgotten import db/runtime?)")
+ }
+ if trv, ok := inter.(Traverser); ok {
+ if err := trv.Traverse(ctx, buq); err != nil {
+ return err
+ }
+ }
+ }
+ for _, f := range buq.ctx.Fields {
+ if !billingusage.ValidColumn(f) {
+ return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
+ }
+ }
+ if buq.path != nil {
+ prev, err := buq.path(ctx)
+ if err != nil {
+ return err
+ }
+ buq.sql = prev
+ }
+ return nil
+}
+
+func (buq *BillingUsageQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*BillingUsage, error) {
+ var (
+ nodes = []*BillingUsage{}
+ _spec = buq.querySpec()
+ )
+ _spec.ScanValues = func(columns []string) ([]any, error) {
+ return (*BillingUsage).scanValues(nil, columns)
+ }
+ _spec.Assign = func(columns []string, values []any) error {
+ node := &BillingUsage{config: buq.config}
+ nodes = append(nodes, node)
+ return node.assignValues(columns, values)
+ }
+ if len(buq.modifiers) > 0 {
+ _spec.Modifiers = buq.modifiers
+ }
+ for i := range hooks {
+ hooks[i](ctx, _spec)
+ }
+ if err := sqlgraph.QueryNodes(ctx, buq.driver, _spec); err != nil {
+ return nil, err
+ }
+ if len(nodes) == 0 {
+ return nodes, nil
+ }
+ return nodes, nil
+}
+
+func (buq *BillingUsageQuery) sqlCount(ctx context.Context) (int, error) {
+ _spec := buq.querySpec()
+ if len(buq.modifiers) > 0 {
+ _spec.Modifiers = buq.modifiers
+ }
+ _spec.Node.Columns = buq.ctx.Fields
+ if len(buq.ctx.Fields) > 0 {
+ _spec.Unique = buq.ctx.Unique != nil && *buq.ctx.Unique
+ }
+ return sqlgraph.CountNodes(ctx, buq.driver, _spec)
+}
+
+func (buq *BillingUsageQuery) querySpec() *sqlgraph.QuerySpec {
+ _spec := sqlgraph.NewQuerySpec(billingusage.Table, billingusage.Columns, sqlgraph.NewFieldSpec(billingusage.FieldID, field.TypeString))
+ _spec.From = buq.sql
+ if unique := buq.ctx.Unique; unique != nil {
+ _spec.Unique = *unique
+ } else if buq.path != nil {
+ _spec.Unique = true
+ }
+ if fields := buq.ctx.Fields; len(fields) > 0 {
+ _spec.Node.Columns = make([]string, 0, len(fields))
+ _spec.Node.Columns = append(_spec.Node.Columns, billingusage.FieldID)
+ for i := range fields {
+ if fields[i] != billingusage.FieldID {
+ _spec.Node.Columns = append(_spec.Node.Columns, fields[i])
+ }
+ }
+ }
+ if ps := buq.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if limit := buq.ctx.Limit; limit != nil {
+ _spec.Limit = *limit
+ }
+ if offset := buq.ctx.Offset; offset != nil {
+ _spec.Offset = *offset
+ }
+ if ps := buq.order; len(ps) > 0 {
+ _spec.Order = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ return _spec
+}
+
+func (buq *BillingUsageQuery) sqlQuery(ctx context.Context) *sql.Selector {
+ builder := sql.Dialect(buq.driver.Dialect())
+ t1 := builder.Table(billingusage.Table)
+ columns := buq.ctx.Fields
+ if len(columns) == 0 {
+ columns = billingusage.Columns
+ }
+ selector := builder.Select(t1.Columns(columns...)...).From(t1)
+ if buq.sql != nil {
+ selector = buq.sql
+ selector.Select(selector.Columns(columns...)...)
+ }
+ if buq.ctx.Unique != nil && *buq.ctx.Unique {
+ selector.Distinct()
+ }
+ for _, m := range buq.modifiers {
+ m(selector)
+ }
+ for _, p := range buq.predicates {
+ p(selector)
+ }
+ for _, p := range buq.order {
+ p(selector)
+ }
+ if offset := buq.ctx.Offset; offset != nil {
+ // limit is mandatory for offset clause. We start
+ // with default value, and override it below if needed.
+ selector.Offset(*offset).Limit(math.MaxInt32)
+ }
+ if limit := buq.ctx.Limit; limit != nil {
+ selector.Limit(*limit)
+ }
+ return selector
+}
+
+// ForUpdate locks the selected rows against concurrent updates, and prevent them from being
+// updated, deleted or "selected ... for update" by other sessions, until the transaction is
+// either committed or rolled-back.
+func (buq *BillingUsageQuery) ForUpdate(opts ...sql.LockOption) *BillingUsageQuery {
+ if buq.driver.Dialect() == dialect.Postgres {
+ buq.Unique(false)
+ }
+ buq.modifiers = append(buq.modifiers, func(s *sql.Selector) {
+ s.ForUpdate(opts...)
+ })
+ return buq
+}
+
+// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock
+// on any rows that are read. Other sessions can read the rows, but cannot modify them
+// until your transaction commits.
+func (buq *BillingUsageQuery) ForShare(opts ...sql.LockOption) *BillingUsageQuery {
+ if buq.driver.Dialect() == dialect.Postgres {
+ buq.Unique(false)
+ }
+ buq.modifiers = append(buq.modifiers, func(s *sql.Selector) {
+ s.ForShare(opts...)
+ })
+ return buq
+}
+
+// Modify adds a query modifier for attaching custom logic to queries.
+func (buq *BillingUsageQuery) Modify(modifiers ...func(s *sql.Selector)) *BillingUsageSelect {
+ buq.modifiers = append(buq.modifiers, modifiers...)
+ return buq.Select()
+}
+
+// BillingUsageGroupBy is the group-by builder for BillingUsage entities.
+type BillingUsageGroupBy struct {
+ selector
+ build *BillingUsageQuery
+}
+
+// Aggregate adds the given aggregation functions to the group-by query.
+func (bugb *BillingUsageGroupBy) Aggregate(fns ...AggregateFunc) *BillingUsageGroupBy {
+ bugb.fns = append(bugb.fns, fns...)
+ return bugb
+}
+
+// Scan applies the selector query and scans the result into the given value.
+func (bugb *BillingUsageGroupBy) Scan(ctx context.Context, v any) error {
+ ctx = setContextOp(ctx, bugb.build.ctx, ent.OpQueryGroupBy)
+ if err := bugb.build.prepareQuery(ctx); err != nil {
+ return err
+ }
+ return scanWithInterceptors[*BillingUsageQuery, *BillingUsageGroupBy](ctx, bugb.build, bugb, bugb.build.inters, v)
+}
+
+func (bugb *BillingUsageGroupBy) sqlScan(ctx context.Context, root *BillingUsageQuery, v any) error {
+ selector := root.sqlQuery(ctx).Select()
+ aggregation := make([]string, 0, len(bugb.fns))
+ for _, fn := range bugb.fns {
+ aggregation = append(aggregation, fn(selector))
+ }
+ if len(selector.SelectedColumns()) == 0 {
+ columns := make([]string, 0, len(*bugb.flds)+len(bugb.fns))
+ for _, f := range *bugb.flds {
+ columns = append(columns, selector.C(f))
+ }
+ columns = append(columns, aggregation...)
+ selector.Select(columns...)
+ }
+ selector.GroupBy(selector.Columns(*bugb.flds...)...)
+ if err := selector.Err(); err != nil {
+ return err
+ }
+ rows := &sql.Rows{}
+ query, args := selector.Query()
+ if err := bugb.build.driver.Query(ctx, query, args, rows); err != nil {
+ return err
+ }
+ defer rows.Close()
+ return sql.ScanSlice(rows, v)
+}
+
+// BillingUsageSelect is the builder for selecting fields of BillingUsage entities.
+type BillingUsageSelect struct {
+ *BillingUsageQuery
+ selector
+}
+
+// Aggregate adds the given aggregation functions to the selector query.
+func (bus *BillingUsageSelect) Aggregate(fns ...AggregateFunc) *BillingUsageSelect {
+ bus.fns = append(bus.fns, fns...)
+ return bus
+}
+
+// Scan applies the selector query and scans the result into the given value.
+func (bus *BillingUsageSelect) Scan(ctx context.Context, v any) error {
+ ctx = setContextOp(ctx, bus.ctx, ent.OpQuerySelect)
+ if err := bus.prepareQuery(ctx); err != nil {
+ return err
+ }
+ return scanWithInterceptors[*BillingUsageQuery, *BillingUsageSelect](ctx, bus.BillingUsageQuery, bus, bus.inters, v)
+}
+
+func (bus *BillingUsageSelect) sqlScan(ctx context.Context, root *BillingUsageQuery, v any) error {
+ selector := root.sqlQuery(ctx)
+ aggregation := make([]string, 0, len(bus.fns))
+ for _, fn := range bus.fns {
+ aggregation = append(aggregation, fn(selector))
+ }
+ switch n := len(*bus.selector.flds); {
+ case n == 0 && len(aggregation) > 0:
+ selector.Select(aggregation...)
+ case n != 0 && len(aggregation) > 0:
+ selector.AppendSelect(aggregation...)
+ }
+ rows := &sql.Rows{}
+ query, args := selector.Query()
+ if err := bus.driver.Query(ctx, query, args, rows); err != nil {
+ return err
+ }
+ defer rows.Close()
+ return sql.ScanSlice(rows, v)
+}
+
+// Modify adds a query modifier for attaching custom logic to queries.
+func (bus *BillingUsageSelect) Modify(modifiers ...func(s *sql.Selector)) *BillingUsageSelect {
+ bus.modifiers = append(bus.modifiers, modifiers...)
+ return bus
+}
diff --git a/backend/db/billingusage_update.go b/backend/db/billingusage_update.go
new file mode 100644
index 0000000..6a3e745
--- /dev/null
+++ b/backend/db/billingusage_update.go
@@ -0,0 +1,482 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "time"
+
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/billingusage"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+)
+
+// BillingUsageUpdate is the builder for updating BillingUsage entities.
+type BillingUsageUpdate struct {
+ config
+ hooks []Hook
+ mutation *BillingUsageMutation
+ modifiers []func(*sql.UpdateBuilder)
+}
+
+// Where appends a list predicates to the BillingUsageUpdate builder.
+func (buu *BillingUsageUpdate) Where(ps ...predicate.BillingUsage) *BillingUsageUpdate {
+ buu.mutation.Where(ps...)
+ return buu
+}
+
+// SetDeletedAt sets the "deleted_at" field.
+func (buu *BillingUsageUpdate) SetDeletedAt(t time.Time) *BillingUsageUpdate {
+ buu.mutation.SetDeletedAt(t)
+ return buu
+}
+
+// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil.
+func (buu *BillingUsageUpdate) SetNillableDeletedAt(t *time.Time) *BillingUsageUpdate {
+ if t != nil {
+ buu.SetDeletedAt(*t)
+ }
+ return buu
+}
+
+// ClearDeletedAt clears the value of the "deleted_at" field.
+func (buu *BillingUsageUpdate) ClearDeletedAt() *BillingUsageUpdate {
+ buu.mutation.ClearDeletedAt()
+ return buu
+}
+
+// SetUserID sets the "user_id" field.
+func (buu *BillingUsageUpdate) SetUserID(s string) *BillingUsageUpdate {
+ buu.mutation.SetUserID(s)
+ return buu
+}
+
+// SetNillableUserID sets the "user_id" field if the given value is not nil.
+func (buu *BillingUsageUpdate) SetNillableUserID(s *string) *BillingUsageUpdate {
+ if s != nil {
+ buu.SetUserID(*s)
+ }
+ return buu
+}
+
+// SetModelName sets the "model_name" field.
+func (buu *BillingUsageUpdate) SetModelName(s string) *BillingUsageUpdate {
+ buu.mutation.SetModelName(s)
+ return buu
+}
+
+// SetNillableModelName sets the "model_name" field if the given value is not nil.
+func (buu *BillingUsageUpdate) SetNillableModelName(s *string) *BillingUsageUpdate {
+ if s != nil {
+ buu.SetModelName(*s)
+ }
+ return buu
+}
+
+// SetTokens sets the "tokens" field.
+func (buu *BillingUsageUpdate) SetTokens(i int64) *BillingUsageUpdate {
+ buu.mutation.ResetTokens()
+ buu.mutation.SetTokens(i)
+ return buu
+}
+
+// SetNillableTokens sets the "tokens" field if the given value is not nil.
+func (buu *BillingUsageUpdate) SetNillableTokens(i *int64) *BillingUsageUpdate {
+ if i != nil {
+ buu.SetTokens(*i)
+ }
+ return buu
+}
+
+// AddTokens adds i to the "tokens" field.
+func (buu *BillingUsageUpdate) AddTokens(i int64) *BillingUsageUpdate {
+ buu.mutation.AddTokens(i)
+ return buu
+}
+
+// SetOperation sets the "operation" field.
+func (buu *BillingUsageUpdate) SetOperation(s string) *BillingUsageUpdate {
+ buu.mutation.SetOperation(s)
+ return buu
+}
+
+// SetNillableOperation sets the "operation" field if the given value is not nil.
+func (buu *BillingUsageUpdate) SetNillableOperation(s *string) *BillingUsageUpdate {
+ if s != nil {
+ buu.SetOperation(*s)
+ }
+ return buu
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (buu *BillingUsageUpdate) SetCreatedAt(t time.Time) *BillingUsageUpdate {
+ buu.mutation.SetCreatedAt(t)
+ return buu
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (buu *BillingUsageUpdate) SetNillableCreatedAt(t *time.Time) *BillingUsageUpdate {
+ if t != nil {
+ buu.SetCreatedAt(*t)
+ }
+ return buu
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (buu *BillingUsageUpdate) SetUpdatedAt(t time.Time) *BillingUsageUpdate {
+ buu.mutation.SetUpdatedAt(t)
+ return buu
+}
+
+// Mutation returns the BillingUsageMutation object of the builder.
+func (buu *BillingUsageUpdate) Mutation() *BillingUsageMutation {
+ return buu.mutation
+}
+
+// Save executes the query and returns the number of nodes affected by the update operation.
+func (buu *BillingUsageUpdate) Save(ctx context.Context) (int, error) {
+ if err := buu.defaults(); err != nil {
+ return 0, err
+ }
+ return withHooks(ctx, buu.sqlSave, buu.mutation, buu.hooks)
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (buu *BillingUsageUpdate) SaveX(ctx context.Context) int {
+ affected, err := buu.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return affected
+}
+
+// Exec executes the query.
+func (buu *BillingUsageUpdate) Exec(ctx context.Context) error {
+ _, err := buu.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (buu *BillingUsageUpdate) ExecX(ctx context.Context) {
+ if err := buu.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// defaults sets the default values of the builder before save.
+func (buu *BillingUsageUpdate) defaults() error {
+ if _, ok := buu.mutation.UpdatedAt(); !ok {
+ if billingusage.UpdateDefaultUpdatedAt == nil {
+ return fmt.Errorf("db: uninitialized billingusage.UpdateDefaultUpdatedAt (forgotten import db/runtime?)")
+ }
+ v := billingusage.UpdateDefaultUpdatedAt()
+ buu.mutation.SetUpdatedAt(v)
+ }
+ return nil
+}
+
+// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
+func (buu *BillingUsageUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *BillingUsageUpdate {
+ buu.modifiers = append(buu.modifiers, modifiers...)
+ return buu
+}
+
+func (buu *BillingUsageUpdate) sqlSave(ctx context.Context) (n int, err error) {
+ _spec := sqlgraph.NewUpdateSpec(billingusage.Table, billingusage.Columns, sqlgraph.NewFieldSpec(billingusage.FieldID, field.TypeString))
+ if ps := buu.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if value, ok := buu.mutation.DeletedAt(); ok {
+ _spec.SetField(billingusage.FieldDeletedAt, field.TypeTime, value)
+ }
+ if buu.mutation.DeletedAtCleared() {
+ _spec.ClearField(billingusage.FieldDeletedAt, field.TypeTime)
+ }
+ if value, ok := buu.mutation.UserID(); ok {
+ _spec.SetField(billingusage.FieldUserID, field.TypeString, value)
+ }
+ if value, ok := buu.mutation.ModelName(); ok {
+ _spec.SetField(billingusage.FieldModelName, field.TypeString, value)
+ }
+ if value, ok := buu.mutation.Tokens(); ok {
+ _spec.SetField(billingusage.FieldTokens, field.TypeInt64, value)
+ }
+ if value, ok := buu.mutation.AddedTokens(); ok {
+ _spec.AddField(billingusage.FieldTokens, field.TypeInt64, value)
+ }
+ if value, ok := buu.mutation.Operation(); ok {
+ _spec.SetField(billingusage.FieldOperation, field.TypeString, value)
+ }
+ if value, ok := buu.mutation.CreatedAt(); ok {
+ _spec.SetField(billingusage.FieldCreatedAt, field.TypeTime, value)
+ }
+ if value, ok := buu.mutation.UpdatedAt(); ok {
+ _spec.SetField(billingusage.FieldUpdatedAt, field.TypeTime, value)
+ }
+ _spec.AddModifiers(buu.modifiers...)
+ if n, err = sqlgraph.UpdateNodes(ctx, buu.driver, _spec); err != nil {
+ if _, ok := err.(*sqlgraph.NotFoundError); ok {
+ err = &NotFoundError{billingusage.Label}
+ } else if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return 0, err
+ }
+ buu.mutation.done = true
+ return n, nil
+}
+
+// BillingUsageUpdateOne is the builder for updating a single BillingUsage entity.
+type BillingUsageUpdateOne struct {
+ config
+ fields []string
+ hooks []Hook
+ mutation *BillingUsageMutation
+ modifiers []func(*sql.UpdateBuilder)
+}
+
+// SetDeletedAt sets the "deleted_at" field.
+func (buuo *BillingUsageUpdateOne) SetDeletedAt(t time.Time) *BillingUsageUpdateOne {
+ buuo.mutation.SetDeletedAt(t)
+ return buuo
+}
+
+// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil.
+func (buuo *BillingUsageUpdateOne) SetNillableDeletedAt(t *time.Time) *BillingUsageUpdateOne {
+ if t != nil {
+ buuo.SetDeletedAt(*t)
+ }
+ return buuo
+}
+
+// ClearDeletedAt clears the value of the "deleted_at" field.
+func (buuo *BillingUsageUpdateOne) ClearDeletedAt() *BillingUsageUpdateOne {
+ buuo.mutation.ClearDeletedAt()
+ return buuo
+}
+
+// SetUserID sets the "user_id" field.
+func (buuo *BillingUsageUpdateOne) SetUserID(s string) *BillingUsageUpdateOne {
+ buuo.mutation.SetUserID(s)
+ return buuo
+}
+
+// SetNillableUserID sets the "user_id" field if the given value is not nil.
+func (buuo *BillingUsageUpdateOne) SetNillableUserID(s *string) *BillingUsageUpdateOne {
+ if s != nil {
+ buuo.SetUserID(*s)
+ }
+ return buuo
+}
+
+// SetModelName sets the "model_name" field.
+func (buuo *BillingUsageUpdateOne) SetModelName(s string) *BillingUsageUpdateOne {
+ buuo.mutation.SetModelName(s)
+ return buuo
+}
+
+// SetNillableModelName sets the "model_name" field if the given value is not nil.
+func (buuo *BillingUsageUpdateOne) SetNillableModelName(s *string) *BillingUsageUpdateOne {
+ if s != nil {
+ buuo.SetModelName(*s)
+ }
+ return buuo
+}
+
+// SetTokens sets the "tokens" field.
+func (buuo *BillingUsageUpdateOne) SetTokens(i int64) *BillingUsageUpdateOne {
+ buuo.mutation.ResetTokens()
+ buuo.mutation.SetTokens(i)
+ return buuo
+}
+
+// SetNillableTokens sets the "tokens" field if the given value is not nil.
+func (buuo *BillingUsageUpdateOne) SetNillableTokens(i *int64) *BillingUsageUpdateOne {
+ if i != nil {
+ buuo.SetTokens(*i)
+ }
+ return buuo
+}
+
+// AddTokens adds i to the "tokens" field.
+func (buuo *BillingUsageUpdateOne) AddTokens(i int64) *BillingUsageUpdateOne {
+ buuo.mutation.AddTokens(i)
+ return buuo
+}
+
+// SetOperation sets the "operation" field.
+func (buuo *BillingUsageUpdateOne) SetOperation(s string) *BillingUsageUpdateOne {
+ buuo.mutation.SetOperation(s)
+ return buuo
+}
+
+// SetNillableOperation sets the "operation" field if the given value is not nil.
+func (buuo *BillingUsageUpdateOne) SetNillableOperation(s *string) *BillingUsageUpdateOne {
+ if s != nil {
+ buuo.SetOperation(*s)
+ }
+ return buuo
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (buuo *BillingUsageUpdateOne) SetCreatedAt(t time.Time) *BillingUsageUpdateOne {
+ buuo.mutation.SetCreatedAt(t)
+ return buuo
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (buuo *BillingUsageUpdateOne) SetNillableCreatedAt(t *time.Time) *BillingUsageUpdateOne {
+ if t != nil {
+ buuo.SetCreatedAt(*t)
+ }
+ return buuo
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (buuo *BillingUsageUpdateOne) SetUpdatedAt(t time.Time) *BillingUsageUpdateOne {
+ buuo.mutation.SetUpdatedAt(t)
+ return buuo
+}
+
+// Mutation returns the BillingUsageMutation object of the builder.
+func (buuo *BillingUsageUpdateOne) Mutation() *BillingUsageMutation {
+ return buuo.mutation
+}
+
+// Where appends a list predicates to the BillingUsageUpdate builder.
+func (buuo *BillingUsageUpdateOne) Where(ps ...predicate.BillingUsage) *BillingUsageUpdateOne {
+ buuo.mutation.Where(ps...)
+ return buuo
+}
+
+// Select allows selecting one or more fields (columns) of the returned entity.
+// The default is selecting all fields defined in the entity schema.
+func (buuo *BillingUsageUpdateOne) Select(field string, fields ...string) *BillingUsageUpdateOne {
+ buuo.fields = append([]string{field}, fields...)
+ return buuo
+}
+
+// Save executes the query and returns the updated BillingUsage entity.
+func (buuo *BillingUsageUpdateOne) Save(ctx context.Context) (*BillingUsage, error) {
+ if err := buuo.defaults(); err != nil {
+ return nil, err
+ }
+ return withHooks(ctx, buuo.sqlSave, buuo.mutation, buuo.hooks)
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (buuo *BillingUsageUpdateOne) SaveX(ctx context.Context) *BillingUsage {
+ node, err := buuo.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return node
+}
+
+// Exec executes the query on the entity.
+func (buuo *BillingUsageUpdateOne) Exec(ctx context.Context) error {
+ _, err := buuo.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (buuo *BillingUsageUpdateOne) ExecX(ctx context.Context) {
+ if err := buuo.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// defaults sets the default values of the builder before save.
+func (buuo *BillingUsageUpdateOne) defaults() error {
+ if _, ok := buuo.mutation.UpdatedAt(); !ok {
+ if billingusage.UpdateDefaultUpdatedAt == nil {
+ return fmt.Errorf("db: uninitialized billingusage.UpdateDefaultUpdatedAt (forgotten import db/runtime?)")
+ }
+ v := billingusage.UpdateDefaultUpdatedAt()
+ buuo.mutation.SetUpdatedAt(v)
+ }
+ return nil
+}
+
+// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
+func (buuo *BillingUsageUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *BillingUsageUpdateOne {
+ buuo.modifiers = append(buuo.modifiers, modifiers...)
+ return buuo
+}
+
+func (buuo *BillingUsageUpdateOne) sqlSave(ctx context.Context) (_node *BillingUsage, err error) {
+ _spec := sqlgraph.NewUpdateSpec(billingusage.Table, billingusage.Columns, sqlgraph.NewFieldSpec(billingusage.FieldID, field.TypeString))
+ id, ok := buuo.mutation.ID()
+ if !ok {
+ return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "BillingUsage.id" for update`)}
+ }
+ _spec.Node.ID.Value = id
+ if fields := buuo.fields; len(fields) > 0 {
+ _spec.Node.Columns = make([]string, 0, len(fields))
+ _spec.Node.Columns = append(_spec.Node.Columns, billingusage.FieldID)
+ for _, f := range fields {
+ if !billingusage.ValidColumn(f) {
+ return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
+ }
+ if f != billingusage.FieldID {
+ _spec.Node.Columns = append(_spec.Node.Columns, f)
+ }
+ }
+ }
+ if ps := buuo.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if value, ok := buuo.mutation.DeletedAt(); ok {
+ _spec.SetField(billingusage.FieldDeletedAt, field.TypeTime, value)
+ }
+ if buuo.mutation.DeletedAtCleared() {
+ _spec.ClearField(billingusage.FieldDeletedAt, field.TypeTime)
+ }
+ if value, ok := buuo.mutation.UserID(); ok {
+ _spec.SetField(billingusage.FieldUserID, field.TypeString, value)
+ }
+ if value, ok := buuo.mutation.ModelName(); ok {
+ _spec.SetField(billingusage.FieldModelName, field.TypeString, value)
+ }
+ if value, ok := buuo.mutation.Tokens(); ok {
+ _spec.SetField(billingusage.FieldTokens, field.TypeInt64, value)
+ }
+ if value, ok := buuo.mutation.AddedTokens(); ok {
+ _spec.AddField(billingusage.FieldTokens, field.TypeInt64, value)
+ }
+ if value, ok := buuo.mutation.Operation(); ok {
+ _spec.SetField(billingusage.FieldOperation, field.TypeString, value)
+ }
+ if value, ok := buuo.mutation.CreatedAt(); ok {
+ _spec.SetField(billingusage.FieldCreatedAt, field.TypeTime, value)
+ }
+ if value, ok := buuo.mutation.UpdatedAt(); ok {
+ _spec.SetField(billingusage.FieldUpdatedAt, field.TypeTime, value)
+ }
+ _spec.AddModifiers(buuo.modifiers...)
+ _node = &BillingUsage{config: buuo.config}
+ _spec.Assign = _node.assignValues
+ _spec.ScanValues = _node.scanValues
+ if err = sqlgraph.UpdateNode(ctx, buuo.driver, _spec); err != nil {
+ if _, ok := err.(*sqlgraph.NotFoundError); ok {
+ err = &NotFoundError{billingusage.Label}
+ } else if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return nil, err
+ }
+ buuo.mutation.done = true
+ return _node, nil
+}
diff --git a/backend/db/client.go b/backend/db/client.go
new file mode 100644
index 0000000..b617f83
--- /dev/null
+++ b/backend/db/client.go
@@ -0,0 +1,2240 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "log"
+ "reflect"
+
+ "github.com/chaitin/MonkeyCode/backend/db/migrate"
+ "github.com/google/uuid"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect"
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "github.com/chaitin/MonkeyCode/backend/db/admin"
+ "github.com/chaitin/MonkeyCode/backend/db/adminloginhistory"
+ "github.com/chaitin/MonkeyCode/backend/db/apikey"
+ "github.com/chaitin/MonkeyCode/backend/db/billingplan"
+ "github.com/chaitin/MonkeyCode/backend/db/billingquota"
+ "github.com/chaitin/MonkeyCode/backend/db/billingrecord"
+ "github.com/chaitin/MonkeyCode/backend/db/billingusage"
+ "github.com/chaitin/MonkeyCode/backend/db/invitecode"
+ "github.com/chaitin/MonkeyCode/backend/db/model"
+ "github.com/chaitin/MonkeyCode/backend/db/record"
+ "github.com/chaitin/MonkeyCode/backend/db/setting"
+ "github.com/chaitin/MonkeyCode/backend/db/user"
+ "github.com/chaitin/MonkeyCode/backend/db/userloginhistory"
+
+ stdsql "database/sql"
+)
+
+// Client is the client that holds all ent builders.
+type Client struct {
+ config
+ // Schema is the client for creating, migrating and dropping schema.
+ Schema *migrate.Schema
+ // Admin is the client for interacting with the Admin builders.
+ Admin *AdminClient
+ // AdminLoginHistory is the client for interacting with the AdminLoginHistory builders.
+ AdminLoginHistory *AdminLoginHistoryClient
+ // ApiKey is the client for interacting with the ApiKey builders.
+ ApiKey *ApiKeyClient
+ // BillingPlan is the client for interacting with the BillingPlan builders.
+ BillingPlan *BillingPlanClient
+ // BillingQuota is the client for interacting with the BillingQuota builders.
+ BillingQuota *BillingQuotaClient
+ // BillingRecord is the client for interacting with the BillingRecord builders.
+ BillingRecord *BillingRecordClient
+ // BillingUsage is the client for interacting with the BillingUsage builders.
+ BillingUsage *BillingUsageClient
+ // InviteCode is the client for interacting with the InviteCode builders.
+ InviteCode *InviteCodeClient
+ // Model is the client for interacting with the Model builders.
+ Model *ModelClient
+ // Record is the client for interacting with the Record builders.
+ Record *RecordClient
+ // Setting is the client for interacting with the Setting builders.
+ Setting *SettingClient
+ // User is the client for interacting with the User builders.
+ User *UserClient
+ // UserLoginHistory is the client for interacting with the UserLoginHistory builders.
+ UserLoginHistory *UserLoginHistoryClient
+}
+
+// NewClient creates a new client configured with the given options.
+func NewClient(opts ...Option) *Client {
+ client := &Client{config: newConfig(opts...)}
+ client.init()
+ return client
+}
+
+func (c *Client) init() {
+ c.Schema = migrate.NewSchema(c.driver)
+ c.Admin = NewAdminClient(c.config)
+ c.AdminLoginHistory = NewAdminLoginHistoryClient(c.config)
+ c.ApiKey = NewApiKeyClient(c.config)
+ c.BillingPlan = NewBillingPlanClient(c.config)
+ c.BillingQuota = NewBillingQuotaClient(c.config)
+ c.BillingRecord = NewBillingRecordClient(c.config)
+ c.BillingUsage = NewBillingUsageClient(c.config)
+ c.InviteCode = NewInviteCodeClient(c.config)
+ c.Model = NewModelClient(c.config)
+ c.Record = NewRecordClient(c.config)
+ c.Setting = NewSettingClient(c.config)
+ c.User = NewUserClient(c.config)
+ c.UserLoginHistory = NewUserLoginHistoryClient(c.config)
+}
+
+type (
+ // config is the configuration for the client and its builder.
+ config struct {
+ // driver used for executing database requests.
+ driver dialect.Driver
+ // debug enable a debug logging.
+ debug bool
+ // log used for logging on debug mode.
+ log func(...any)
+ // hooks to execute on mutations.
+ hooks *hooks
+ // interceptors to execute on queries.
+ inters *inters
+ }
+ // Option function to configure the client.
+ Option func(*config)
+)
+
+// newConfig creates a new config for the client.
+func newConfig(opts ...Option) config {
+ cfg := config{log: log.Println, hooks: &hooks{}, inters: &inters{}}
+ cfg.options(opts...)
+ return cfg
+}
+
+// options applies the options on the config object.
+func (c *config) options(opts ...Option) {
+ for _, opt := range opts {
+ opt(c)
+ }
+ if c.debug {
+ c.driver = dialect.Debug(c.driver, c.log)
+ }
+}
+
+// Debug enables debug logging on the ent.Driver.
+func Debug() Option {
+ return func(c *config) {
+ c.debug = true
+ }
+}
+
+// Log sets the logging function for debug mode.
+func Log(fn func(...any)) Option {
+ return func(c *config) {
+ c.log = fn
+ }
+}
+
+// Driver configures the client driver.
+func Driver(driver dialect.Driver) Option {
+ return func(c *config) {
+ c.driver = driver
+ }
+}
+
+// Open opens a database/sql.DB specified by the driver name and
+// the data source name, and returns a new client attached to it.
+// Optional parameters can be added for configuring the client.
+func Open(driverName, dataSourceName string, options ...Option) (*Client, error) {
+ switch driverName {
+ case dialect.MySQL, dialect.Postgres, dialect.SQLite:
+ drv, err := sql.Open(driverName, dataSourceName)
+ if err != nil {
+ return nil, err
+ }
+ return NewClient(append(options, Driver(drv))...), nil
+ default:
+ return nil, fmt.Errorf("unsupported driver: %q", driverName)
+ }
+}
+
+// ErrTxStarted is returned when trying to start a new transaction from a transactional client.
+var ErrTxStarted = errors.New("db: cannot start a transaction within a transaction")
+
+// Tx returns a new transactional client. The provided context
+// is used until the transaction is committed or rolled back.
+func (c *Client) Tx(ctx context.Context) (*Tx, error) {
+ if _, ok := c.driver.(*txDriver); ok {
+ return nil, ErrTxStarted
+ }
+ tx, err := newTx(ctx, c.driver)
+ if err != nil {
+ return nil, fmt.Errorf("db: starting a transaction: %w", err)
+ }
+ cfg := c.config
+ cfg.driver = tx
+ return &Tx{
+ ctx: ctx,
+ config: cfg,
+ Admin: NewAdminClient(cfg),
+ AdminLoginHistory: NewAdminLoginHistoryClient(cfg),
+ ApiKey: NewApiKeyClient(cfg),
+ BillingPlan: NewBillingPlanClient(cfg),
+ BillingQuota: NewBillingQuotaClient(cfg),
+ BillingRecord: NewBillingRecordClient(cfg),
+ BillingUsage: NewBillingUsageClient(cfg),
+ InviteCode: NewInviteCodeClient(cfg),
+ Model: NewModelClient(cfg),
+ Record: NewRecordClient(cfg),
+ Setting: NewSettingClient(cfg),
+ User: NewUserClient(cfg),
+ UserLoginHistory: NewUserLoginHistoryClient(cfg),
+ }, nil
+}
+
+// BeginTx returns a transactional client with specified options.
+func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) {
+ if _, ok := c.driver.(*txDriver); ok {
+ return nil, errors.New("ent: cannot start a transaction within a transaction")
+ }
+ tx, err := c.driver.(interface {
+ BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error)
+ }).BeginTx(ctx, opts)
+ if err != nil {
+ return nil, fmt.Errorf("ent: starting a transaction: %w", err)
+ }
+ cfg := c.config
+ cfg.driver = &txDriver{tx: tx, drv: c.driver}
+ return &Tx{
+ ctx: ctx,
+ config: cfg,
+ Admin: NewAdminClient(cfg),
+ AdminLoginHistory: NewAdminLoginHistoryClient(cfg),
+ ApiKey: NewApiKeyClient(cfg),
+ BillingPlan: NewBillingPlanClient(cfg),
+ BillingQuota: NewBillingQuotaClient(cfg),
+ BillingRecord: NewBillingRecordClient(cfg),
+ BillingUsage: NewBillingUsageClient(cfg),
+ InviteCode: NewInviteCodeClient(cfg),
+ Model: NewModelClient(cfg),
+ Record: NewRecordClient(cfg),
+ Setting: NewSettingClient(cfg),
+ User: NewUserClient(cfg),
+ UserLoginHistory: NewUserLoginHistoryClient(cfg),
+ }, nil
+}
+
+// Debug returns a new debug-client. It's used to get verbose logging on specific operations.
+//
+// client.Debug().
+// Admin.
+// Query().
+// Count(ctx)
+func (c *Client) Debug() *Client {
+ if c.debug {
+ return c
+ }
+ cfg := c.config
+ cfg.driver = dialect.Debug(c.driver, c.log)
+ client := &Client{config: cfg}
+ client.init()
+ return client
+}
+
+// Close closes the database connection and prevents new queries from starting.
+func (c *Client) Close() error {
+ return c.driver.Close()
+}
+
+// Use adds the mutation hooks to all the entity clients.
+// In order to add hooks to a specific client, call: `client.Node.Use(...)`.
+func (c *Client) Use(hooks ...Hook) {
+ for _, n := range []interface{ Use(...Hook) }{
+ c.Admin, c.AdminLoginHistory, c.ApiKey, c.BillingPlan, c.BillingQuota,
+ c.BillingRecord, c.BillingUsage, c.InviteCode, c.Model, c.Record, c.Setting,
+ c.User, c.UserLoginHistory,
+ } {
+ n.Use(hooks...)
+ }
+}
+
+// Intercept adds the query interceptors to all the entity clients.
+// In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`.
+func (c *Client) Intercept(interceptors ...Interceptor) {
+ for _, n := range []interface{ Intercept(...Interceptor) }{
+ c.Admin, c.AdminLoginHistory, c.ApiKey, c.BillingPlan, c.BillingQuota,
+ c.BillingRecord, c.BillingUsage, c.InviteCode, c.Model, c.Record, c.Setting,
+ c.User, c.UserLoginHistory,
+ } {
+ n.Intercept(interceptors...)
+ }
+}
+
+// Mutate implements the ent.Mutator interface.
+func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) {
+ switch m := m.(type) {
+ case *AdminMutation:
+ return c.Admin.mutate(ctx, m)
+ case *AdminLoginHistoryMutation:
+ return c.AdminLoginHistory.mutate(ctx, m)
+ case *ApiKeyMutation:
+ return c.ApiKey.mutate(ctx, m)
+ case *BillingPlanMutation:
+ return c.BillingPlan.mutate(ctx, m)
+ case *BillingQuotaMutation:
+ return c.BillingQuota.mutate(ctx, m)
+ case *BillingRecordMutation:
+ return c.BillingRecord.mutate(ctx, m)
+ case *BillingUsageMutation:
+ return c.BillingUsage.mutate(ctx, m)
+ case *InviteCodeMutation:
+ return c.InviteCode.mutate(ctx, m)
+ case *ModelMutation:
+ return c.Model.mutate(ctx, m)
+ case *RecordMutation:
+ return c.Record.mutate(ctx, m)
+ case *SettingMutation:
+ return c.Setting.mutate(ctx, m)
+ case *UserMutation:
+ return c.User.mutate(ctx, m)
+ case *UserLoginHistoryMutation:
+ return c.UserLoginHistory.mutate(ctx, m)
+ default:
+ return nil, fmt.Errorf("db: unknown mutation type %T", m)
+ }
+}
+
+// AdminClient is a client for the Admin schema.
+type AdminClient struct {
+ config
+}
+
+// NewAdminClient returns a client for the Admin from the given config.
+func NewAdminClient(c config) *AdminClient {
+ return &AdminClient{config: c}
+}
+
+// Use adds a list of mutation hooks to the hooks stack.
+// A call to `Use(f, g, h)` equals to `admin.Hooks(f(g(h())))`.
+func (c *AdminClient) Use(hooks ...Hook) {
+ c.hooks.Admin = append(c.hooks.Admin, hooks...)
+}
+
+// Intercept adds a list of query interceptors to the interceptors stack.
+// A call to `Intercept(f, g, h)` equals to `admin.Intercept(f(g(h())))`.
+func (c *AdminClient) Intercept(interceptors ...Interceptor) {
+ c.inters.Admin = append(c.inters.Admin, interceptors...)
+}
+
+// Create returns a builder for creating a Admin entity.
+func (c *AdminClient) Create() *AdminCreate {
+ mutation := newAdminMutation(c.config, OpCreate)
+ return &AdminCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// CreateBulk returns a builder for creating a bulk of Admin entities.
+func (c *AdminClient) CreateBulk(builders ...*AdminCreate) *AdminCreateBulk {
+ return &AdminCreateBulk{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 *AdminClient) MapCreateBulk(slice any, setFunc func(*AdminCreate, int)) *AdminCreateBulk {
+ rv := reflect.ValueOf(slice)
+ if rv.Kind() != reflect.Slice {
+ return &AdminCreateBulk{err: fmt.Errorf("calling to AdminClient.MapCreateBulk with wrong type %T, need slice", slice)}
+ }
+ builders := make([]*AdminCreate, rv.Len())
+ for i := 0; i < rv.Len(); i++ {
+ builders[i] = c.Create()
+ setFunc(builders[i], i)
+ }
+ return &AdminCreateBulk{config: c.config, builders: builders}
+}
+
+// Update returns an update builder for Admin.
+func (c *AdminClient) Update() *AdminUpdate {
+ mutation := newAdminMutation(c.config, OpUpdate)
+ return &AdminUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// UpdateOne returns an update builder for the given entity.
+func (c *AdminClient) UpdateOne(a *Admin) *AdminUpdateOne {
+ mutation := newAdminMutation(c.config, OpUpdateOne, withAdmin(a))
+ return &AdminUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// UpdateOneID returns an update builder for the given id.
+func (c *AdminClient) UpdateOneID(id uuid.UUID) *AdminUpdateOne {
+ mutation := newAdminMutation(c.config, OpUpdateOne, withAdminID(id))
+ return &AdminUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// Delete returns a delete builder for Admin.
+func (c *AdminClient) Delete() *AdminDelete {
+ mutation := newAdminMutation(c.config, OpDelete)
+ return &AdminDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// DeleteOne returns a builder for deleting the given entity.
+func (c *AdminClient) DeleteOne(a *Admin) *AdminDeleteOne {
+ return c.DeleteOneID(a.ID)
+}
+
+// DeleteOneID returns a builder for deleting the given entity by its id.
+func (c *AdminClient) DeleteOneID(id uuid.UUID) *AdminDeleteOne {
+ builder := c.Delete().Where(admin.ID(id))
+ builder.mutation.id = &id
+ builder.mutation.op = OpDeleteOne
+ return &AdminDeleteOne{builder}
+}
+
+// Query returns a query builder for Admin.
+func (c *AdminClient) Query() *AdminQuery {
+ return &AdminQuery{
+ config: c.config,
+ ctx: &QueryContext{Type: TypeAdmin},
+ inters: c.Interceptors(),
+ }
+}
+
+// Get returns a Admin entity by its id.
+func (c *AdminClient) Get(ctx context.Context, id uuid.UUID) (*Admin, error) {
+ return c.Query().Where(admin.ID(id)).Only(ctx)
+}
+
+// GetX is like Get, but panics if an error occurs.
+func (c *AdminClient) GetX(ctx context.Context, id uuid.UUID) *Admin {
+ obj, err := c.Get(ctx, id)
+ if err != nil {
+ panic(err)
+ }
+ return obj
+}
+
+// QueryLoginHistories queries the login_histories edge of a Admin.
+func (c *AdminClient) QueryLoginHistories(a *Admin) *AdminLoginHistoryQuery {
+ query := (&AdminLoginHistoryClient{config: c.config}).Query()
+ query.path = func(context.Context) (fromV *sql.Selector, _ error) {
+ id := a.ID
+ step := sqlgraph.NewStep(
+ sqlgraph.From(admin.Table, admin.FieldID, id),
+ sqlgraph.To(adminloginhistory.Table, adminloginhistory.FieldID),
+ sqlgraph.Edge(sqlgraph.O2M, false, admin.LoginHistoriesTable, admin.LoginHistoriesColumn),
+ )
+ fromV = sqlgraph.Neighbors(a.driver.Dialect(), step)
+ return fromV, nil
+ }
+ return query
+}
+
+// Hooks returns the client hooks.
+func (c *AdminClient) Hooks() []Hook {
+ return c.hooks.Admin
+}
+
+// Interceptors returns the client interceptors.
+func (c *AdminClient) Interceptors() []Interceptor {
+ return c.inters.Admin
+}
+
+func (c *AdminClient) mutate(ctx context.Context, m *AdminMutation) (Value, error) {
+ switch m.Op() {
+ case OpCreate:
+ return (&AdminCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpUpdate:
+ return (&AdminUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpUpdateOne:
+ return (&AdminUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpDelete, OpDeleteOne:
+ return (&AdminDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
+ default:
+ return nil, fmt.Errorf("db: unknown Admin mutation op: %q", m.Op())
+ }
+}
+
+// AdminLoginHistoryClient is a client for the AdminLoginHistory schema.
+type AdminLoginHistoryClient struct {
+ config
+}
+
+// NewAdminLoginHistoryClient returns a client for the AdminLoginHistory from the given config.
+func NewAdminLoginHistoryClient(c config) *AdminLoginHistoryClient {
+ return &AdminLoginHistoryClient{config: c}
+}
+
+// Use adds a list of mutation hooks to the hooks stack.
+// A call to `Use(f, g, h)` equals to `adminloginhistory.Hooks(f(g(h())))`.
+func (c *AdminLoginHistoryClient) Use(hooks ...Hook) {
+ c.hooks.AdminLoginHistory = append(c.hooks.AdminLoginHistory, hooks...)
+}
+
+// Intercept adds a list of query interceptors to the interceptors stack.
+// A call to `Intercept(f, g, h)` equals to `adminloginhistory.Intercept(f(g(h())))`.
+func (c *AdminLoginHistoryClient) Intercept(interceptors ...Interceptor) {
+ c.inters.AdminLoginHistory = append(c.inters.AdminLoginHistory, interceptors...)
+}
+
+// Create returns a builder for creating a AdminLoginHistory entity.
+func (c *AdminLoginHistoryClient) Create() *AdminLoginHistoryCreate {
+ mutation := newAdminLoginHistoryMutation(c.config, OpCreate)
+ return &AdminLoginHistoryCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// CreateBulk returns a builder for creating a bulk of AdminLoginHistory entities.
+func (c *AdminLoginHistoryClient) CreateBulk(builders ...*AdminLoginHistoryCreate) *AdminLoginHistoryCreateBulk {
+ return &AdminLoginHistoryCreateBulk{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 *AdminLoginHistoryClient) MapCreateBulk(slice any, setFunc func(*AdminLoginHistoryCreate, int)) *AdminLoginHistoryCreateBulk {
+ rv := reflect.ValueOf(slice)
+ if rv.Kind() != reflect.Slice {
+ return &AdminLoginHistoryCreateBulk{err: fmt.Errorf("calling to AdminLoginHistoryClient.MapCreateBulk with wrong type %T, need slice", slice)}
+ }
+ builders := make([]*AdminLoginHistoryCreate, rv.Len())
+ for i := 0; i < rv.Len(); i++ {
+ builders[i] = c.Create()
+ setFunc(builders[i], i)
+ }
+ return &AdminLoginHistoryCreateBulk{config: c.config, builders: builders}
+}
+
+// Update returns an update builder for AdminLoginHistory.
+func (c *AdminLoginHistoryClient) Update() *AdminLoginHistoryUpdate {
+ mutation := newAdminLoginHistoryMutation(c.config, OpUpdate)
+ return &AdminLoginHistoryUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// UpdateOne returns an update builder for the given entity.
+func (c *AdminLoginHistoryClient) UpdateOne(alh *AdminLoginHistory) *AdminLoginHistoryUpdateOne {
+ mutation := newAdminLoginHistoryMutation(c.config, OpUpdateOne, withAdminLoginHistory(alh))
+ return &AdminLoginHistoryUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// UpdateOneID returns an update builder for the given id.
+func (c *AdminLoginHistoryClient) UpdateOneID(id uuid.UUID) *AdminLoginHistoryUpdateOne {
+ mutation := newAdminLoginHistoryMutation(c.config, OpUpdateOne, withAdminLoginHistoryID(id))
+ return &AdminLoginHistoryUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// Delete returns a delete builder for AdminLoginHistory.
+func (c *AdminLoginHistoryClient) Delete() *AdminLoginHistoryDelete {
+ mutation := newAdminLoginHistoryMutation(c.config, OpDelete)
+ return &AdminLoginHistoryDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// DeleteOne returns a builder for deleting the given entity.
+func (c *AdminLoginHistoryClient) DeleteOne(alh *AdminLoginHistory) *AdminLoginHistoryDeleteOne {
+ return c.DeleteOneID(alh.ID)
+}
+
+// DeleteOneID returns a builder for deleting the given entity by its id.
+func (c *AdminLoginHistoryClient) DeleteOneID(id uuid.UUID) *AdminLoginHistoryDeleteOne {
+ builder := c.Delete().Where(adminloginhistory.ID(id))
+ builder.mutation.id = &id
+ builder.mutation.op = OpDeleteOne
+ return &AdminLoginHistoryDeleteOne{builder}
+}
+
+// Query returns a query builder for AdminLoginHistory.
+func (c *AdminLoginHistoryClient) Query() *AdminLoginHistoryQuery {
+ return &AdminLoginHistoryQuery{
+ config: c.config,
+ ctx: &QueryContext{Type: TypeAdminLoginHistory},
+ inters: c.Interceptors(),
+ }
+}
+
+// Get returns a AdminLoginHistory entity by its id.
+func (c *AdminLoginHistoryClient) Get(ctx context.Context, id uuid.UUID) (*AdminLoginHistory, error) {
+ return c.Query().Where(adminloginhistory.ID(id)).Only(ctx)
+}
+
+// GetX is like Get, but panics if an error occurs.
+func (c *AdminLoginHistoryClient) GetX(ctx context.Context, id uuid.UUID) *AdminLoginHistory {
+ obj, err := c.Get(ctx, id)
+ if err != nil {
+ panic(err)
+ }
+ return obj
+}
+
+// QueryOwner queries the owner edge of a AdminLoginHistory.
+func (c *AdminLoginHistoryClient) QueryOwner(alh *AdminLoginHistory) *AdminQuery {
+ query := (&AdminClient{config: c.config}).Query()
+ query.path = func(context.Context) (fromV *sql.Selector, _ error) {
+ id := alh.ID
+ step := sqlgraph.NewStep(
+ sqlgraph.From(adminloginhistory.Table, adminloginhistory.FieldID, id),
+ sqlgraph.To(admin.Table, admin.FieldID),
+ sqlgraph.Edge(sqlgraph.M2O, true, adminloginhistory.OwnerTable, adminloginhistory.OwnerColumn),
+ )
+ fromV = sqlgraph.Neighbors(alh.driver.Dialect(), step)
+ return fromV, nil
+ }
+ return query
+}
+
+// Hooks returns the client hooks.
+func (c *AdminLoginHistoryClient) Hooks() []Hook {
+ return c.hooks.AdminLoginHistory
+}
+
+// Interceptors returns the client interceptors.
+func (c *AdminLoginHistoryClient) Interceptors() []Interceptor {
+ return c.inters.AdminLoginHistory
+}
+
+func (c *AdminLoginHistoryClient) mutate(ctx context.Context, m *AdminLoginHistoryMutation) (Value, error) {
+ switch m.Op() {
+ case OpCreate:
+ return (&AdminLoginHistoryCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpUpdate:
+ return (&AdminLoginHistoryUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpUpdateOne:
+ return (&AdminLoginHistoryUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpDelete, OpDeleteOne:
+ return (&AdminLoginHistoryDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
+ default:
+ return nil, fmt.Errorf("db: unknown AdminLoginHistory mutation op: %q", m.Op())
+ }
+}
+
+// ApiKeyClient is a client for the ApiKey schema.
+type ApiKeyClient struct {
+ config
+}
+
+// NewApiKeyClient returns a client for the ApiKey from the given config.
+func NewApiKeyClient(c config) *ApiKeyClient {
+ return &ApiKeyClient{config: c}
+}
+
+// Use adds a list of mutation hooks to the hooks stack.
+// A call to `Use(f, g, h)` equals to `apikey.Hooks(f(g(h())))`.
+func (c *ApiKeyClient) Use(hooks ...Hook) {
+ c.hooks.ApiKey = append(c.hooks.ApiKey, hooks...)
+}
+
+// Intercept adds a list of query interceptors to the interceptors stack.
+// A call to `Intercept(f, g, h)` equals to `apikey.Intercept(f(g(h())))`.
+func (c *ApiKeyClient) Intercept(interceptors ...Interceptor) {
+ c.inters.ApiKey = append(c.inters.ApiKey, interceptors...)
+}
+
+// Create returns a builder for creating a ApiKey entity.
+func (c *ApiKeyClient) Create() *ApiKeyCreate {
+ mutation := newApiKeyMutation(c.config, OpCreate)
+ return &ApiKeyCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// CreateBulk returns a builder for creating a bulk of ApiKey entities.
+func (c *ApiKeyClient) CreateBulk(builders ...*ApiKeyCreate) *ApiKeyCreateBulk {
+ return &ApiKeyCreateBulk{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 *ApiKeyClient) MapCreateBulk(slice any, setFunc func(*ApiKeyCreate, int)) *ApiKeyCreateBulk {
+ rv := reflect.ValueOf(slice)
+ if rv.Kind() != reflect.Slice {
+ return &ApiKeyCreateBulk{err: fmt.Errorf("calling to ApiKeyClient.MapCreateBulk with wrong type %T, need slice", slice)}
+ }
+ builders := make([]*ApiKeyCreate, rv.Len())
+ for i := 0; i < rv.Len(); i++ {
+ builders[i] = c.Create()
+ setFunc(builders[i], i)
+ }
+ return &ApiKeyCreateBulk{config: c.config, builders: builders}
+}
+
+// Update returns an update builder for ApiKey.
+func (c *ApiKeyClient) Update() *ApiKeyUpdate {
+ mutation := newApiKeyMutation(c.config, OpUpdate)
+ return &ApiKeyUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// UpdateOne returns an update builder for the given entity.
+func (c *ApiKeyClient) UpdateOne(ak *ApiKey) *ApiKeyUpdateOne {
+ mutation := newApiKeyMutation(c.config, OpUpdateOne, withApiKey(ak))
+ return &ApiKeyUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// UpdateOneID returns an update builder for the given id.
+func (c *ApiKeyClient) UpdateOneID(id uuid.UUID) *ApiKeyUpdateOne {
+ mutation := newApiKeyMutation(c.config, OpUpdateOne, withApiKeyID(id))
+ return &ApiKeyUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// Delete returns a delete builder for ApiKey.
+func (c *ApiKeyClient) Delete() *ApiKeyDelete {
+ mutation := newApiKeyMutation(c.config, OpDelete)
+ return &ApiKeyDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// DeleteOne returns a builder for deleting the given entity.
+func (c *ApiKeyClient) DeleteOne(ak *ApiKey) *ApiKeyDeleteOne {
+ return c.DeleteOneID(ak.ID)
+}
+
+// DeleteOneID returns a builder for deleting the given entity by its id.
+func (c *ApiKeyClient) DeleteOneID(id uuid.UUID) *ApiKeyDeleteOne {
+ builder := c.Delete().Where(apikey.ID(id))
+ builder.mutation.id = &id
+ builder.mutation.op = OpDeleteOne
+ return &ApiKeyDeleteOne{builder}
+}
+
+// Query returns a query builder for ApiKey.
+func (c *ApiKeyClient) Query() *ApiKeyQuery {
+ return &ApiKeyQuery{
+ config: c.config,
+ ctx: &QueryContext{Type: TypeApiKey},
+ inters: c.Interceptors(),
+ }
+}
+
+// Get returns a ApiKey entity by its id.
+func (c *ApiKeyClient) Get(ctx context.Context, id uuid.UUID) (*ApiKey, error) {
+ return c.Query().Where(apikey.ID(id)).Only(ctx)
+}
+
+// GetX is like Get, but panics if an error occurs.
+func (c *ApiKeyClient) GetX(ctx context.Context, id uuid.UUID) *ApiKey {
+ obj, err := c.Get(ctx, id)
+ if err != nil {
+ panic(err)
+ }
+ return obj
+}
+
+// Hooks returns the client hooks.
+func (c *ApiKeyClient) Hooks() []Hook {
+ return c.hooks.ApiKey
+}
+
+// Interceptors returns the client interceptors.
+func (c *ApiKeyClient) Interceptors() []Interceptor {
+ return c.inters.ApiKey
+}
+
+func (c *ApiKeyClient) mutate(ctx context.Context, m *ApiKeyMutation) (Value, error) {
+ switch m.Op() {
+ case OpCreate:
+ return (&ApiKeyCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpUpdate:
+ return (&ApiKeyUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpUpdateOne:
+ return (&ApiKeyUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpDelete, OpDeleteOne:
+ return (&ApiKeyDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
+ default:
+ return nil, fmt.Errorf("db: unknown ApiKey mutation op: %q", m.Op())
+ }
+}
+
+// BillingPlanClient is a client for the BillingPlan schema.
+type BillingPlanClient struct {
+ config
+}
+
+// NewBillingPlanClient returns a client for the BillingPlan from the given config.
+func NewBillingPlanClient(c config) *BillingPlanClient {
+ return &BillingPlanClient{config: c}
+}
+
+// Use adds a list of mutation hooks to the hooks stack.
+// A call to `Use(f, g, h)` equals to `billingplan.Hooks(f(g(h())))`.
+func (c *BillingPlanClient) Use(hooks ...Hook) {
+ c.hooks.BillingPlan = append(c.hooks.BillingPlan, hooks...)
+}
+
+// Intercept adds a list of query interceptors to the interceptors stack.
+// A call to `Intercept(f, g, h)` equals to `billingplan.Intercept(f(g(h())))`.
+func (c *BillingPlanClient) Intercept(interceptors ...Interceptor) {
+ c.inters.BillingPlan = append(c.inters.BillingPlan, interceptors...)
+}
+
+// Create returns a builder for creating a BillingPlan entity.
+func (c *BillingPlanClient) Create() *BillingPlanCreate {
+ mutation := newBillingPlanMutation(c.config, OpCreate)
+ return &BillingPlanCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// CreateBulk returns a builder for creating a bulk of BillingPlan entities.
+func (c *BillingPlanClient) CreateBulk(builders ...*BillingPlanCreate) *BillingPlanCreateBulk {
+ return &BillingPlanCreateBulk{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 *BillingPlanClient) MapCreateBulk(slice any, setFunc func(*BillingPlanCreate, int)) *BillingPlanCreateBulk {
+ rv := reflect.ValueOf(slice)
+ if rv.Kind() != reflect.Slice {
+ return &BillingPlanCreateBulk{err: fmt.Errorf("calling to BillingPlanClient.MapCreateBulk with wrong type %T, need slice", slice)}
+ }
+ builders := make([]*BillingPlanCreate, rv.Len())
+ for i := 0; i < rv.Len(); i++ {
+ builders[i] = c.Create()
+ setFunc(builders[i], i)
+ }
+ return &BillingPlanCreateBulk{config: c.config, builders: builders}
+}
+
+// Update returns an update builder for BillingPlan.
+func (c *BillingPlanClient) Update() *BillingPlanUpdate {
+ mutation := newBillingPlanMutation(c.config, OpUpdate)
+ return &BillingPlanUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// UpdateOne returns an update builder for the given entity.
+func (c *BillingPlanClient) UpdateOne(bp *BillingPlan) *BillingPlanUpdateOne {
+ mutation := newBillingPlanMutation(c.config, OpUpdateOne, withBillingPlan(bp))
+ return &BillingPlanUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// UpdateOneID returns an update builder for the given id.
+func (c *BillingPlanClient) UpdateOneID(id string) *BillingPlanUpdateOne {
+ mutation := newBillingPlanMutation(c.config, OpUpdateOne, withBillingPlanID(id))
+ return &BillingPlanUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// Delete returns a delete builder for BillingPlan.
+func (c *BillingPlanClient) Delete() *BillingPlanDelete {
+ mutation := newBillingPlanMutation(c.config, OpDelete)
+ return &BillingPlanDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// DeleteOne returns a builder for deleting the given entity.
+func (c *BillingPlanClient) DeleteOne(bp *BillingPlan) *BillingPlanDeleteOne {
+ return c.DeleteOneID(bp.ID)
+}
+
+// DeleteOneID returns a builder for deleting the given entity by its id.
+func (c *BillingPlanClient) DeleteOneID(id string) *BillingPlanDeleteOne {
+ builder := c.Delete().Where(billingplan.ID(id))
+ builder.mutation.id = &id
+ builder.mutation.op = OpDeleteOne
+ return &BillingPlanDeleteOne{builder}
+}
+
+// Query returns a query builder for BillingPlan.
+func (c *BillingPlanClient) Query() *BillingPlanQuery {
+ return &BillingPlanQuery{
+ config: c.config,
+ ctx: &QueryContext{Type: TypeBillingPlan},
+ inters: c.Interceptors(),
+ }
+}
+
+// Get returns a BillingPlan entity by its id.
+func (c *BillingPlanClient) Get(ctx context.Context, id string) (*BillingPlan, error) {
+ return c.Query().Where(billingplan.ID(id)).Only(ctx)
+}
+
+// GetX is like Get, but panics if an error occurs.
+func (c *BillingPlanClient) GetX(ctx context.Context, id string) *BillingPlan {
+ obj, err := c.Get(ctx, id)
+ if err != nil {
+ panic(err)
+ }
+ return obj
+}
+
+// Hooks returns the client hooks.
+func (c *BillingPlanClient) Hooks() []Hook {
+ return c.hooks.BillingPlan
+}
+
+// Interceptors returns the client interceptors.
+func (c *BillingPlanClient) Interceptors() []Interceptor {
+ return c.inters.BillingPlan
+}
+
+func (c *BillingPlanClient) mutate(ctx context.Context, m *BillingPlanMutation) (Value, error) {
+ switch m.Op() {
+ case OpCreate:
+ return (&BillingPlanCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpUpdate:
+ return (&BillingPlanUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpUpdateOne:
+ return (&BillingPlanUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpDelete, OpDeleteOne:
+ return (&BillingPlanDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
+ default:
+ return nil, fmt.Errorf("db: unknown BillingPlan mutation op: %q", m.Op())
+ }
+}
+
+// BillingQuotaClient is a client for the BillingQuota schema.
+type BillingQuotaClient struct {
+ config
+}
+
+// NewBillingQuotaClient returns a client for the BillingQuota from the given config.
+func NewBillingQuotaClient(c config) *BillingQuotaClient {
+ return &BillingQuotaClient{config: c}
+}
+
+// Use adds a list of mutation hooks to the hooks stack.
+// A call to `Use(f, g, h)` equals to `billingquota.Hooks(f(g(h())))`.
+func (c *BillingQuotaClient) Use(hooks ...Hook) {
+ c.hooks.BillingQuota = append(c.hooks.BillingQuota, hooks...)
+}
+
+// Intercept adds a list of query interceptors to the interceptors stack.
+// A call to `Intercept(f, g, h)` equals to `billingquota.Intercept(f(g(h())))`.
+func (c *BillingQuotaClient) Intercept(interceptors ...Interceptor) {
+ c.inters.BillingQuota = append(c.inters.BillingQuota, interceptors...)
+}
+
+// Create returns a builder for creating a BillingQuota entity.
+func (c *BillingQuotaClient) Create() *BillingQuotaCreate {
+ mutation := newBillingQuotaMutation(c.config, OpCreate)
+ return &BillingQuotaCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// CreateBulk returns a builder for creating a bulk of BillingQuota entities.
+func (c *BillingQuotaClient) CreateBulk(builders ...*BillingQuotaCreate) *BillingQuotaCreateBulk {
+ return &BillingQuotaCreateBulk{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 *BillingQuotaClient) MapCreateBulk(slice any, setFunc func(*BillingQuotaCreate, int)) *BillingQuotaCreateBulk {
+ rv := reflect.ValueOf(slice)
+ if rv.Kind() != reflect.Slice {
+ return &BillingQuotaCreateBulk{err: fmt.Errorf("calling to BillingQuotaClient.MapCreateBulk with wrong type %T, need slice", slice)}
+ }
+ builders := make([]*BillingQuotaCreate, rv.Len())
+ for i := 0; i < rv.Len(); i++ {
+ builders[i] = c.Create()
+ setFunc(builders[i], i)
+ }
+ return &BillingQuotaCreateBulk{config: c.config, builders: builders}
+}
+
+// Update returns an update builder for BillingQuota.
+func (c *BillingQuotaClient) Update() *BillingQuotaUpdate {
+ mutation := newBillingQuotaMutation(c.config, OpUpdate)
+ return &BillingQuotaUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// UpdateOne returns an update builder for the given entity.
+func (c *BillingQuotaClient) UpdateOne(bq *BillingQuota) *BillingQuotaUpdateOne {
+ mutation := newBillingQuotaMutation(c.config, OpUpdateOne, withBillingQuota(bq))
+ return &BillingQuotaUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// UpdateOneID returns an update builder for the given id.
+func (c *BillingQuotaClient) UpdateOneID(id string) *BillingQuotaUpdateOne {
+ mutation := newBillingQuotaMutation(c.config, OpUpdateOne, withBillingQuotaID(id))
+ return &BillingQuotaUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// Delete returns a delete builder for BillingQuota.
+func (c *BillingQuotaClient) Delete() *BillingQuotaDelete {
+ mutation := newBillingQuotaMutation(c.config, OpDelete)
+ return &BillingQuotaDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// DeleteOne returns a builder for deleting the given entity.
+func (c *BillingQuotaClient) DeleteOne(bq *BillingQuota) *BillingQuotaDeleteOne {
+ return c.DeleteOneID(bq.ID)
+}
+
+// DeleteOneID returns a builder for deleting the given entity by its id.
+func (c *BillingQuotaClient) DeleteOneID(id string) *BillingQuotaDeleteOne {
+ builder := c.Delete().Where(billingquota.ID(id))
+ builder.mutation.id = &id
+ builder.mutation.op = OpDeleteOne
+ return &BillingQuotaDeleteOne{builder}
+}
+
+// Query returns a query builder for BillingQuota.
+func (c *BillingQuotaClient) Query() *BillingQuotaQuery {
+ return &BillingQuotaQuery{
+ config: c.config,
+ ctx: &QueryContext{Type: TypeBillingQuota},
+ inters: c.Interceptors(),
+ }
+}
+
+// Get returns a BillingQuota entity by its id.
+func (c *BillingQuotaClient) Get(ctx context.Context, id string) (*BillingQuota, error) {
+ return c.Query().Where(billingquota.ID(id)).Only(ctx)
+}
+
+// GetX is like Get, but panics if an error occurs.
+func (c *BillingQuotaClient) GetX(ctx context.Context, id string) *BillingQuota {
+ obj, err := c.Get(ctx, id)
+ if err != nil {
+ panic(err)
+ }
+ return obj
+}
+
+// Hooks returns the client hooks.
+func (c *BillingQuotaClient) Hooks() []Hook {
+ hooks := c.hooks.BillingQuota
+ return append(hooks[:len(hooks):len(hooks)], billingquota.Hooks[:]...)
+}
+
+// Interceptors returns the client interceptors.
+func (c *BillingQuotaClient) Interceptors() []Interceptor {
+ inters := c.inters.BillingQuota
+ return append(inters[:len(inters):len(inters)], billingquota.Interceptors[:]...)
+}
+
+func (c *BillingQuotaClient) mutate(ctx context.Context, m *BillingQuotaMutation) (Value, error) {
+ switch m.Op() {
+ case OpCreate:
+ return (&BillingQuotaCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpUpdate:
+ return (&BillingQuotaUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpUpdateOne:
+ return (&BillingQuotaUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpDelete, OpDeleteOne:
+ return (&BillingQuotaDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
+ default:
+ return nil, fmt.Errorf("db: unknown BillingQuota mutation op: %q", m.Op())
+ }
+}
+
+// BillingRecordClient is a client for the BillingRecord schema.
+type BillingRecordClient struct {
+ config
+}
+
+// NewBillingRecordClient returns a client for the BillingRecord from the given config.
+func NewBillingRecordClient(c config) *BillingRecordClient {
+ return &BillingRecordClient{config: c}
+}
+
+// Use adds a list of mutation hooks to the hooks stack.
+// A call to `Use(f, g, h)` equals to `billingrecord.Hooks(f(g(h())))`.
+func (c *BillingRecordClient) Use(hooks ...Hook) {
+ c.hooks.BillingRecord = append(c.hooks.BillingRecord, hooks...)
+}
+
+// Intercept adds a list of query interceptors to the interceptors stack.
+// A call to `Intercept(f, g, h)` equals to `billingrecord.Intercept(f(g(h())))`.
+func (c *BillingRecordClient) Intercept(interceptors ...Interceptor) {
+ c.inters.BillingRecord = append(c.inters.BillingRecord, interceptors...)
+}
+
+// Create returns a builder for creating a BillingRecord entity.
+func (c *BillingRecordClient) Create() *BillingRecordCreate {
+ mutation := newBillingRecordMutation(c.config, OpCreate)
+ return &BillingRecordCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// CreateBulk returns a builder for creating a bulk of BillingRecord entities.
+func (c *BillingRecordClient) CreateBulk(builders ...*BillingRecordCreate) *BillingRecordCreateBulk {
+ return &BillingRecordCreateBulk{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 *BillingRecordClient) MapCreateBulk(slice any, setFunc func(*BillingRecordCreate, int)) *BillingRecordCreateBulk {
+ rv := reflect.ValueOf(slice)
+ if rv.Kind() != reflect.Slice {
+ return &BillingRecordCreateBulk{err: fmt.Errorf("calling to BillingRecordClient.MapCreateBulk with wrong type %T, need slice", slice)}
+ }
+ builders := make([]*BillingRecordCreate, rv.Len())
+ for i := 0; i < rv.Len(); i++ {
+ builders[i] = c.Create()
+ setFunc(builders[i], i)
+ }
+ return &BillingRecordCreateBulk{config: c.config, builders: builders}
+}
+
+// Update returns an update builder for BillingRecord.
+func (c *BillingRecordClient) Update() *BillingRecordUpdate {
+ mutation := newBillingRecordMutation(c.config, OpUpdate)
+ return &BillingRecordUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// UpdateOne returns an update builder for the given entity.
+func (c *BillingRecordClient) UpdateOne(br *BillingRecord) *BillingRecordUpdateOne {
+ mutation := newBillingRecordMutation(c.config, OpUpdateOne, withBillingRecord(br))
+ return &BillingRecordUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// UpdateOneID returns an update builder for the given id.
+func (c *BillingRecordClient) UpdateOneID(id string) *BillingRecordUpdateOne {
+ mutation := newBillingRecordMutation(c.config, OpUpdateOne, withBillingRecordID(id))
+ return &BillingRecordUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// Delete returns a delete builder for BillingRecord.
+func (c *BillingRecordClient) Delete() *BillingRecordDelete {
+ mutation := newBillingRecordMutation(c.config, OpDelete)
+ return &BillingRecordDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// DeleteOne returns a builder for deleting the given entity.
+func (c *BillingRecordClient) DeleteOne(br *BillingRecord) *BillingRecordDeleteOne {
+ return c.DeleteOneID(br.ID)
+}
+
+// DeleteOneID returns a builder for deleting the given entity by its id.
+func (c *BillingRecordClient) DeleteOneID(id string) *BillingRecordDeleteOne {
+ builder := c.Delete().Where(billingrecord.ID(id))
+ builder.mutation.id = &id
+ builder.mutation.op = OpDeleteOne
+ return &BillingRecordDeleteOne{builder}
+}
+
+// Query returns a query builder for BillingRecord.
+func (c *BillingRecordClient) Query() *BillingRecordQuery {
+ return &BillingRecordQuery{
+ config: c.config,
+ ctx: &QueryContext{Type: TypeBillingRecord},
+ inters: c.Interceptors(),
+ }
+}
+
+// Get returns a BillingRecord entity by its id.
+func (c *BillingRecordClient) Get(ctx context.Context, id string) (*BillingRecord, error) {
+ return c.Query().Where(billingrecord.ID(id)).Only(ctx)
+}
+
+// GetX is like Get, but panics if an error occurs.
+func (c *BillingRecordClient) GetX(ctx context.Context, id string) *BillingRecord {
+ obj, err := c.Get(ctx, id)
+ if err != nil {
+ panic(err)
+ }
+ return obj
+}
+
+// Hooks returns the client hooks.
+func (c *BillingRecordClient) Hooks() []Hook {
+ return c.hooks.BillingRecord
+}
+
+// Interceptors returns the client interceptors.
+func (c *BillingRecordClient) Interceptors() []Interceptor {
+ return c.inters.BillingRecord
+}
+
+func (c *BillingRecordClient) mutate(ctx context.Context, m *BillingRecordMutation) (Value, error) {
+ switch m.Op() {
+ case OpCreate:
+ return (&BillingRecordCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpUpdate:
+ return (&BillingRecordUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpUpdateOne:
+ return (&BillingRecordUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpDelete, OpDeleteOne:
+ return (&BillingRecordDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
+ default:
+ return nil, fmt.Errorf("db: unknown BillingRecord mutation op: %q", m.Op())
+ }
+}
+
+// BillingUsageClient is a client for the BillingUsage schema.
+type BillingUsageClient struct {
+ config
+}
+
+// NewBillingUsageClient returns a client for the BillingUsage from the given config.
+func NewBillingUsageClient(c config) *BillingUsageClient {
+ return &BillingUsageClient{config: c}
+}
+
+// Use adds a list of mutation hooks to the hooks stack.
+// A call to `Use(f, g, h)` equals to `billingusage.Hooks(f(g(h())))`.
+func (c *BillingUsageClient) Use(hooks ...Hook) {
+ c.hooks.BillingUsage = append(c.hooks.BillingUsage, hooks...)
+}
+
+// Intercept adds a list of query interceptors to the interceptors stack.
+// A call to `Intercept(f, g, h)` equals to `billingusage.Intercept(f(g(h())))`.
+func (c *BillingUsageClient) Intercept(interceptors ...Interceptor) {
+ c.inters.BillingUsage = append(c.inters.BillingUsage, interceptors...)
+}
+
+// Create returns a builder for creating a BillingUsage entity.
+func (c *BillingUsageClient) Create() *BillingUsageCreate {
+ mutation := newBillingUsageMutation(c.config, OpCreate)
+ return &BillingUsageCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// CreateBulk returns a builder for creating a bulk of BillingUsage entities.
+func (c *BillingUsageClient) CreateBulk(builders ...*BillingUsageCreate) *BillingUsageCreateBulk {
+ return &BillingUsageCreateBulk{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 *BillingUsageClient) MapCreateBulk(slice any, setFunc func(*BillingUsageCreate, int)) *BillingUsageCreateBulk {
+ rv := reflect.ValueOf(slice)
+ if rv.Kind() != reflect.Slice {
+ return &BillingUsageCreateBulk{err: fmt.Errorf("calling to BillingUsageClient.MapCreateBulk with wrong type %T, need slice", slice)}
+ }
+ builders := make([]*BillingUsageCreate, rv.Len())
+ for i := 0; i < rv.Len(); i++ {
+ builders[i] = c.Create()
+ setFunc(builders[i], i)
+ }
+ return &BillingUsageCreateBulk{config: c.config, builders: builders}
+}
+
+// Update returns an update builder for BillingUsage.
+func (c *BillingUsageClient) Update() *BillingUsageUpdate {
+ mutation := newBillingUsageMutation(c.config, OpUpdate)
+ return &BillingUsageUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// UpdateOne returns an update builder for the given entity.
+func (c *BillingUsageClient) UpdateOne(bu *BillingUsage) *BillingUsageUpdateOne {
+ mutation := newBillingUsageMutation(c.config, OpUpdateOne, withBillingUsage(bu))
+ return &BillingUsageUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// UpdateOneID returns an update builder for the given id.
+func (c *BillingUsageClient) UpdateOneID(id string) *BillingUsageUpdateOne {
+ mutation := newBillingUsageMutation(c.config, OpUpdateOne, withBillingUsageID(id))
+ return &BillingUsageUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// Delete returns a delete builder for BillingUsage.
+func (c *BillingUsageClient) Delete() *BillingUsageDelete {
+ mutation := newBillingUsageMutation(c.config, OpDelete)
+ return &BillingUsageDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// DeleteOne returns a builder for deleting the given entity.
+func (c *BillingUsageClient) DeleteOne(bu *BillingUsage) *BillingUsageDeleteOne {
+ return c.DeleteOneID(bu.ID)
+}
+
+// DeleteOneID returns a builder for deleting the given entity by its id.
+func (c *BillingUsageClient) DeleteOneID(id string) *BillingUsageDeleteOne {
+ builder := c.Delete().Where(billingusage.ID(id))
+ builder.mutation.id = &id
+ builder.mutation.op = OpDeleteOne
+ return &BillingUsageDeleteOne{builder}
+}
+
+// Query returns a query builder for BillingUsage.
+func (c *BillingUsageClient) Query() *BillingUsageQuery {
+ return &BillingUsageQuery{
+ config: c.config,
+ ctx: &QueryContext{Type: TypeBillingUsage},
+ inters: c.Interceptors(),
+ }
+}
+
+// Get returns a BillingUsage entity by its id.
+func (c *BillingUsageClient) Get(ctx context.Context, id string) (*BillingUsage, error) {
+ return c.Query().Where(billingusage.ID(id)).Only(ctx)
+}
+
+// GetX is like Get, but panics if an error occurs.
+func (c *BillingUsageClient) GetX(ctx context.Context, id string) *BillingUsage {
+ obj, err := c.Get(ctx, id)
+ if err != nil {
+ panic(err)
+ }
+ return obj
+}
+
+// Hooks returns the client hooks.
+func (c *BillingUsageClient) Hooks() []Hook {
+ hooks := c.hooks.BillingUsage
+ return append(hooks[:len(hooks):len(hooks)], billingusage.Hooks[:]...)
+}
+
+// Interceptors returns the client interceptors.
+func (c *BillingUsageClient) Interceptors() []Interceptor {
+ inters := c.inters.BillingUsage
+ return append(inters[:len(inters):len(inters)], billingusage.Interceptors[:]...)
+}
+
+func (c *BillingUsageClient) mutate(ctx context.Context, m *BillingUsageMutation) (Value, error) {
+ switch m.Op() {
+ case OpCreate:
+ return (&BillingUsageCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpUpdate:
+ return (&BillingUsageUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpUpdateOne:
+ return (&BillingUsageUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpDelete, OpDeleteOne:
+ return (&BillingUsageDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
+ default:
+ return nil, fmt.Errorf("db: unknown BillingUsage mutation op: %q", m.Op())
+ }
+}
+
+// InviteCodeClient is a client for the InviteCode schema.
+type InviteCodeClient struct {
+ config
+}
+
+// NewInviteCodeClient returns a client for the InviteCode from the given config.
+func NewInviteCodeClient(c config) *InviteCodeClient {
+ return &InviteCodeClient{config: c}
+}
+
+// Use adds a list of mutation hooks to the hooks stack.
+// A call to `Use(f, g, h)` equals to `invitecode.Hooks(f(g(h())))`.
+func (c *InviteCodeClient) Use(hooks ...Hook) {
+ c.hooks.InviteCode = append(c.hooks.InviteCode, hooks...)
+}
+
+// Intercept adds a list of query interceptors to the interceptors stack.
+// A call to `Intercept(f, g, h)` equals to `invitecode.Intercept(f(g(h())))`.
+func (c *InviteCodeClient) Intercept(interceptors ...Interceptor) {
+ c.inters.InviteCode = append(c.inters.InviteCode, interceptors...)
+}
+
+// Create returns a builder for creating a InviteCode entity.
+func (c *InviteCodeClient) Create() *InviteCodeCreate {
+ mutation := newInviteCodeMutation(c.config, OpCreate)
+ return &InviteCodeCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// CreateBulk returns a builder for creating a bulk of InviteCode entities.
+func (c *InviteCodeClient) CreateBulk(builders ...*InviteCodeCreate) *InviteCodeCreateBulk {
+ return &InviteCodeCreateBulk{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 *InviteCodeClient) MapCreateBulk(slice any, setFunc func(*InviteCodeCreate, int)) *InviteCodeCreateBulk {
+ rv := reflect.ValueOf(slice)
+ if rv.Kind() != reflect.Slice {
+ return &InviteCodeCreateBulk{err: fmt.Errorf("calling to InviteCodeClient.MapCreateBulk with wrong type %T, need slice", slice)}
+ }
+ builders := make([]*InviteCodeCreate, rv.Len())
+ for i := 0; i < rv.Len(); i++ {
+ builders[i] = c.Create()
+ setFunc(builders[i], i)
+ }
+ return &InviteCodeCreateBulk{config: c.config, builders: builders}
+}
+
+// Update returns an update builder for InviteCode.
+func (c *InviteCodeClient) Update() *InviteCodeUpdate {
+ mutation := newInviteCodeMutation(c.config, OpUpdate)
+ return &InviteCodeUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// UpdateOne returns an update builder for the given entity.
+func (c *InviteCodeClient) UpdateOne(ic *InviteCode) *InviteCodeUpdateOne {
+ mutation := newInviteCodeMutation(c.config, OpUpdateOne, withInviteCode(ic))
+ return &InviteCodeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// UpdateOneID returns an update builder for the given id.
+func (c *InviteCodeClient) UpdateOneID(id uuid.UUID) *InviteCodeUpdateOne {
+ mutation := newInviteCodeMutation(c.config, OpUpdateOne, withInviteCodeID(id))
+ return &InviteCodeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// Delete returns a delete builder for InviteCode.
+func (c *InviteCodeClient) Delete() *InviteCodeDelete {
+ mutation := newInviteCodeMutation(c.config, OpDelete)
+ return &InviteCodeDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// DeleteOne returns a builder for deleting the given entity.
+func (c *InviteCodeClient) DeleteOne(ic *InviteCode) *InviteCodeDeleteOne {
+ return c.DeleteOneID(ic.ID)
+}
+
+// DeleteOneID returns a builder for deleting the given entity by its id.
+func (c *InviteCodeClient) DeleteOneID(id uuid.UUID) *InviteCodeDeleteOne {
+ builder := c.Delete().Where(invitecode.ID(id))
+ builder.mutation.id = &id
+ builder.mutation.op = OpDeleteOne
+ return &InviteCodeDeleteOne{builder}
+}
+
+// Query returns a query builder for InviteCode.
+func (c *InviteCodeClient) Query() *InviteCodeQuery {
+ return &InviteCodeQuery{
+ config: c.config,
+ ctx: &QueryContext{Type: TypeInviteCode},
+ inters: c.Interceptors(),
+ }
+}
+
+// Get returns a InviteCode entity by its id.
+func (c *InviteCodeClient) Get(ctx context.Context, id uuid.UUID) (*InviteCode, error) {
+ return c.Query().Where(invitecode.ID(id)).Only(ctx)
+}
+
+// GetX is like Get, but panics if an error occurs.
+func (c *InviteCodeClient) GetX(ctx context.Context, id uuid.UUID) *InviteCode {
+ obj, err := c.Get(ctx, id)
+ if err != nil {
+ panic(err)
+ }
+ return obj
+}
+
+// Hooks returns the client hooks.
+func (c *InviteCodeClient) Hooks() []Hook {
+ return c.hooks.InviteCode
+}
+
+// Interceptors returns the client interceptors.
+func (c *InviteCodeClient) Interceptors() []Interceptor {
+ return c.inters.InviteCode
+}
+
+func (c *InviteCodeClient) mutate(ctx context.Context, m *InviteCodeMutation) (Value, error) {
+ switch m.Op() {
+ case OpCreate:
+ return (&InviteCodeCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpUpdate:
+ return (&InviteCodeUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpUpdateOne:
+ return (&InviteCodeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpDelete, OpDeleteOne:
+ return (&InviteCodeDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
+ default:
+ return nil, fmt.Errorf("db: unknown InviteCode mutation op: %q", m.Op())
+ }
+}
+
+// ModelClient is a client for the Model schema.
+type ModelClient struct {
+ config
+}
+
+// NewModelClient returns a client for the Model from the given config.
+func NewModelClient(c config) *ModelClient {
+ return &ModelClient{config: c}
+}
+
+// Use adds a list of mutation hooks to the hooks stack.
+// A call to `Use(f, g, h)` equals to `model.Hooks(f(g(h())))`.
+func (c *ModelClient) Use(hooks ...Hook) {
+ c.hooks.Model = append(c.hooks.Model, hooks...)
+}
+
+// Intercept adds a list of query interceptors to the interceptors stack.
+// A call to `Intercept(f, g, h)` equals to `model.Intercept(f(g(h())))`.
+func (c *ModelClient) Intercept(interceptors ...Interceptor) {
+ c.inters.Model = append(c.inters.Model, interceptors...)
+}
+
+// Create returns a builder for creating a Model entity.
+func (c *ModelClient) Create() *ModelCreate {
+ mutation := newModelMutation(c.config, OpCreate)
+ return &ModelCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// CreateBulk returns a builder for creating a bulk of Model entities.
+func (c *ModelClient) CreateBulk(builders ...*ModelCreate) *ModelCreateBulk {
+ return &ModelCreateBulk{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 *ModelClient) MapCreateBulk(slice any, setFunc func(*ModelCreate, int)) *ModelCreateBulk {
+ rv := reflect.ValueOf(slice)
+ if rv.Kind() != reflect.Slice {
+ return &ModelCreateBulk{err: fmt.Errorf("calling to ModelClient.MapCreateBulk with wrong type %T, need slice", slice)}
+ }
+ builders := make([]*ModelCreate, rv.Len())
+ for i := 0; i < rv.Len(); i++ {
+ builders[i] = c.Create()
+ setFunc(builders[i], i)
+ }
+ return &ModelCreateBulk{config: c.config, builders: builders}
+}
+
+// Update returns an update builder for Model.
+func (c *ModelClient) Update() *ModelUpdate {
+ mutation := newModelMutation(c.config, OpUpdate)
+ return &ModelUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// UpdateOne returns an update builder for the given entity.
+func (c *ModelClient) UpdateOne(m *Model) *ModelUpdateOne {
+ mutation := newModelMutation(c.config, OpUpdateOne, withModel(m))
+ return &ModelUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// UpdateOneID returns an update builder for the given id.
+func (c *ModelClient) UpdateOneID(id uuid.UUID) *ModelUpdateOne {
+ mutation := newModelMutation(c.config, OpUpdateOne, withModelID(id))
+ return &ModelUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// Delete returns a delete builder for Model.
+func (c *ModelClient) Delete() *ModelDelete {
+ mutation := newModelMutation(c.config, OpDelete)
+ return &ModelDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// DeleteOne returns a builder for deleting the given entity.
+func (c *ModelClient) DeleteOne(m *Model) *ModelDeleteOne {
+ return c.DeleteOneID(m.ID)
+}
+
+// DeleteOneID returns a builder for deleting the given entity by its id.
+func (c *ModelClient) DeleteOneID(id uuid.UUID) *ModelDeleteOne {
+ builder := c.Delete().Where(model.ID(id))
+ builder.mutation.id = &id
+ builder.mutation.op = OpDeleteOne
+ return &ModelDeleteOne{builder}
+}
+
+// Query returns a query builder for Model.
+func (c *ModelClient) Query() *ModelQuery {
+ return &ModelQuery{
+ config: c.config,
+ ctx: &QueryContext{Type: TypeModel},
+ inters: c.Interceptors(),
+ }
+}
+
+// Get returns a Model entity by its id.
+func (c *ModelClient) Get(ctx context.Context, id uuid.UUID) (*Model, error) {
+ return c.Query().Where(model.ID(id)).Only(ctx)
+}
+
+// GetX is like Get, but panics if an error occurs.
+func (c *ModelClient) GetX(ctx context.Context, id uuid.UUID) *Model {
+ obj, err := c.Get(ctx, id)
+ if err != nil {
+ panic(err)
+ }
+ return obj
+}
+
+// QueryRecords queries the records edge of a Model.
+func (c *ModelClient) QueryRecords(m *Model) *RecordQuery {
+ query := (&RecordClient{config: c.config}).Query()
+ query.path = func(context.Context) (fromV *sql.Selector, _ error) {
+ id := m.ID
+ step := sqlgraph.NewStep(
+ sqlgraph.From(model.Table, model.FieldID, id),
+ sqlgraph.To(record.Table, record.FieldID),
+ sqlgraph.Edge(sqlgraph.O2M, false, model.RecordsTable, model.RecordsColumn),
+ )
+ fromV = sqlgraph.Neighbors(m.driver.Dialect(), step)
+ return fromV, nil
+ }
+ return query
+}
+
+// QueryUser queries the user edge of a Model.
+func (c *ModelClient) QueryUser(m *Model) *UserQuery {
+ query := (&UserClient{config: c.config}).Query()
+ query.path = func(context.Context) (fromV *sql.Selector, _ error) {
+ id := m.ID
+ step := sqlgraph.NewStep(
+ sqlgraph.From(model.Table, model.FieldID, id),
+ sqlgraph.To(user.Table, user.FieldID),
+ sqlgraph.Edge(sqlgraph.M2O, true, model.UserTable, model.UserColumn),
+ )
+ fromV = sqlgraph.Neighbors(m.driver.Dialect(), step)
+ return fromV, nil
+ }
+ return query
+}
+
+// Hooks returns the client hooks.
+func (c *ModelClient) Hooks() []Hook {
+ return c.hooks.Model
+}
+
+// Interceptors returns the client interceptors.
+func (c *ModelClient) Interceptors() []Interceptor {
+ return c.inters.Model
+}
+
+func (c *ModelClient) mutate(ctx context.Context, m *ModelMutation) (Value, error) {
+ switch m.Op() {
+ case OpCreate:
+ return (&ModelCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpUpdate:
+ return (&ModelUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpUpdateOne:
+ return (&ModelUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpDelete, OpDeleteOne:
+ return (&ModelDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
+ default:
+ return nil, fmt.Errorf("db: unknown Model mutation op: %q", m.Op())
+ }
+}
+
+// RecordClient is a client for the Record schema.
+type RecordClient struct {
+ config
+}
+
+// NewRecordClient returns a client for the Record from the given config.
+func NewRecordClient(c config) *RecordClient {
+ return &RecordClient{config: c}
+}
+
+// Use adds a list of mutation hooks to the hooks stack.
+// A call to `Use(f, g, h)` equals to `record.Hooks(f(g(h())))`.
+func (c *RecordClient) Use(hooks ...Hook) {
+ c.hooks.Record = append(c.hooks.Record, hooks...)
+}
+
+// Intercept adds a list of query interceptors to the interceptors stack.
+// A call to `Intercept(f, g, h)` equals to `record.Intercept(f(g(h())))`.
+func (c *RecordClient) Intercept(interceptors ...Interceptor) {
+ c.inters.Record = append(c.inters.Record, interceptors...)
+}
+
+// Create returns a builder for creating a Record entity.
+func (c *RecordClient) Create() *RecordCreate {
+ mutation := newRecordMutation(c.config, OpCreate)
+ return &RecordCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// CreateBulk returns a builder for creating a bulk of Record entities.
+func (c *RecordClient) CreateBulk(builders ...*RecordCreate) *RecordCreateBulk {
+ return &RecordCreateBulk{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 *RecordClient) MapCreateBulk(slice any, setFunc func(*RecordCreate, int)) *RecordCreateBulk {
+ rv := reflect.ValueOf(slice)
+ if rv.Kind() != reflect.Slice {
+ return &RecordCreateBulk{err: fmt.Errorf("calling to RecordClient.MapCreateBulk with wrong type %T, need slice", slice)}
+ }
+ builders := make([]*RecordCreate, rv.Len())
+ for i := 0; i < rv.Len(); i++ {
+ builders[i] = c.Create()
+ setFunc(builders[i], i)
+ }
+ return &RecordCreateBulk{config: c.config, builders: builders}
+}
+
+// Update returns an update builder for Record.
+func (c *RecordClient) Update() *RecordUpdate {
+ mutation := newRecordMutation(c.config, OpUpdate)
+ return &RecordUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// UpdateOne returns an update builder for the given entity.
+func (c *RecordClient) UpdateOne(r *Record) *RecordUpdateOne {
+ mutation := newRecordMutation(c.config, OpUpdateOne, withRecord(r))
+ return &RecordUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// UpdateOneID returns an update builder for the given id.
+func (c *RecordClient) UpdateOneID(id uuid.UUID) *RecordUpdateOne {
+ mutation := newRecordMutation(c.config, OpUpdateOne, withRecordID(id))
+ return &RecordUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// Delete returns a delete builder for Record.
+func (c *RecordClient) Delete() *RecordDelete {
+ mutation := newRecordMutation(c.config, OpDelete)
+ return &RecordDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// DeleteOne returns a builder for deleting the given entity.
+func (c *RecordClient) DeleteOne(r *Record) *RecordDeleteOne {
+ return c.DeleteOneID(r.ID)
+}
+
+// DeleteOneID returns a builder for deleting the given entity by its id.
+func (c *RecordClient) DeleteOneID(id uuid.UUID) *RecordDeleteOne {
+ builder := c.Delete().Where(record.ID(id))
+ builder.mutation.id = &id
+ builder.mutation.op = OpDeleteOne
+ return &RecordDeleteOne{builder}
+}
+
+// Query returns a query builder for Record.
+func (c *RecordClient) Query() *RecordQuery {
+ return &RecordQuery{
+ config: c.config,
+ ctx: &QueryContext{Type: TypeRecord},
+ inters: c.Interceptors(),
+ }
+}
+
+// Get returns a Record entity by its id.
+func (c *RecordClient) Get(ctx context.Context, id uuid.UUID) (*Record, error) {
+ return c.Query().Where(record.ID(id)).Only(ctx)
+}
+
+// GetX is like Get, but panics if an error occurs.
+func (c *RecordClient) GetX(ctx context.Context, id uuid.UUID) *Record {
+ obj, err := c.Get(ctx, id)
+ if err != nil {
+ panic(err)
+ }
+ return obj
+}
+
+// QueryUser queries the user edge of a Record.
+func (c *RecordClient) QueryUser(r *Record) *UserQuery {
+ query := (&UserClient{config: c.config}).Query()
+ query.path = func(context.Context) (fromV *sql.Selector, _ error) {
+ id := r.ID
+ step := sqlgraph.NewStep(
+ sqlgraph.From(record.Table, record.FieldID, id),
+ sqlgraph.To(user.Table, user.FieldID),
+ sqlgraph.Edge(sqlgraph.M2O, true, record.UserTable, record.UserColumn),
+ )
+ fromV = sqlgraph.Neighbors(r.driver.Dialect(), step)
+ return fromV, nil
+ }
+ return query
+}
+
+// QueryModel queries the model edge of a Record.
+func (c *RecordClient) QueryModel(r *Record) *ModelQuery {
+ query := (&ModelClient{config: c.config}).Query()
+ query.path = func(context.Context) (fromV *sql.Selector, _ error) {
+ id := r.ID
+ step := sqlgraph.NewStep(
+ sqlgraph.From(record.Table, record.FieldID, id),
+ sqlgraph.To(model.Table, model.FieldID),
+ sqlgraph.Edge(sqlgraph.M2O, true, record.ModelTable, record.ModelColumn),
+ )
+ fromV = sqlgraph.Neighbors(r.driver.Dialect(), step)
+ return fromV, nil
+ }
+ return query
+}
+
+// Hooks returns the client hooks.
+func (c *RecordClient) Hooks() []Hook {
+ return c.hooks.Record
+}
+
+// Interceptors returns the client interceptors.
+func (c *RecordClient) Interceptors() []Interceptor {
+ return c.inters.Record
+}
+
+func (c *RecordClient) mutate(ctx context.Context, m *RecordMutation) (Value, error) {
+ switch m.Op() {
+ case OpCreate:
+ return (&RecordCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpUpdate:
+ return (&RecordUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpUpdateOne:
+ return (&RecordUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpDelete, OpDeleteOne:
+ return (&RecordDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
+ default:
+ return nil, fmt.Errorf("db: unknown Record mutation op: %q", m.Op())
+ }
+}
+
+// SettingClient is a client for the Setting schema.
+type SettingClient struct {
+ config
+}
+
+// NewSettingClient returns a client for the Setting from the given config.
+func NewSettingClient(c config) *SettingClient {
+ return &SettingClient{config: c}
+}
+
+// Use adds a list of mutation hooks to the hooks stack.
+// A call to `Use(f, g, h)` equals to `setting.Hooks(f(g(h())))`.
+func (c *SettingClient) Use(hooks ...Hook) {
+ c.hooks.Setting = append(c.hooks.Setting, hooks...)
+}
+
+// Intercept adds a list of query interceptors to the interceptors stack.
+// A call to `Intercept(f, g, h)` equals to `setting.Intercept(f(g(h())))`.
+func (c *SettingClient) Intercept(interceptors ...Interceptor) {
+ c.inters.Setting = append(c.inters.Setting, interceptors...)
+}
+
+// Create returns a builder for creating a Setting entity.
+func (c *SettingClient) Create() *SettingCreate {
+ mutation := newSettingMutation(c.config, OpCreate)
+ return &SettingCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// CreateBulk returns a builder for creating a bulk of Setting entities.
+func (c *SettingClient) CreateBulk(builders ...*SettingCreate) *SettingCreateBulk {
+ return &SettingCreateBulk{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 *SettingClient) MapCreateBulk(slice any, setFunc func(*SettingCreate, int)) *SettingCreateBulk {
+ rv := reflect.ValueOf(slice)
+ if rv.Kind() != reflect.Slice {
+ return &SettingCreateBulk{err: fmt.Errorf("calling to SettingClient.MapCreateBulk with wrong type %T, need slice", slice)}
+ }
+ builders := make([]*SettingCreate, rv.Len())
+ for i := 0; i < rv.Len(); i++ {
+ builders[i] = c.Create()
+ setFunc(builders[i], i)
+ }
+ return &SettingCreateBulk{config: c.config, builders: builders}
+}
+
+// Update returns an update builder for Setting.
+func (c *SettingClient) Update() *SettingUpdate {
+ mutation := newSettingMutation(c.config, OpUpdate)
+ return &SettingUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// UpdateOne returns an update builder for the given entity.
+func (c *SettingClient) UpdateOne(s *Setting) *SettingUpdateOne {
+ mutation := newSettingMutation(c.config, OpUpdateOne, withSetting(s))
+ return &SettingUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// UpdateOneID returns an update builder for the given id.
+func (c *SettingClient) UpdateOneID(id uuid.UUID) *SettingUpdateOne {
+ mutation := newSettingMutation(c.config, OpUpdateOne, withSettingID(id))
+ return &SettingUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// Delete returns a delete builder for Setting.
+func (c *SettingClient) Delete() *SettingDelete {
+ mutation := newSettingMutation(c.config, OpDelete)
+ return &SettingDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// DeleteOne returns a builder for deleting the given entity.
+func (c *SettingClient) DeleteOne(s *Setting) *SettingDeleteOne {
+ return c.DeleteOneID(s.ID)
+}
+
+// DeleteOneID returns a builder for deleting the given entity by its id.
+func (c *SettingClient) DeleteOneID(id uuid.UUID) *SettingDeleteOne {
+ builder := c.Delete().Where(setting.ID(id))
+ builder.mutation.id = &id
+ builder.mutation.op = OpDeleteOne
+ return &SettingDeleteOne{builder}
+}
+
+// Query returns a query builder for Setting.
+func (c *SettingClient) Query() *SettingQuery {
+ return &SettingQuery{
+ config: c.config,
+ ctx: &QueryContext{Type: TypeSetting},
+ inters: c.Interceptors(),
+ }
+}
+
+// Get returns a Setting entity by its id.
+func (c *SettingClient) Get(ctx context.Context, id uuid.UUID) (*Setting, error) {
+ return c.Query().Where(setting.ID(id)).Only(ctx)
+}
+
+// GetX is like Get, but panics if an error occurs.
+func (c *SettingClient) GetX(ctx context.Context, id uuid.UUID) *Setting {
+ obj, err := c.Get(ctx, id)
+ if err != nil {
+ panic(err)
+ }
+ return obj
+}
+
+// Hooks returns the client hooks.
+func (c *SettingClient) Hooks() []Hook {
+ return c.hooks.Setting
+}
+
+// Interceptors returns the client interceptors.
+func (c *SettingClient) Interceptors() []Interceptor {
+ return c.inters.Setting
+}
+
+func (c *SettingClient) mutate(ctx context.Context, m *SettingMutation) (Value, error) {
+ switch m.Op() {
+ case OpCreate:
+ return (&SettingCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpUpdate:
+ return (&SettingUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpUpdateOne:
+ return (&SettingUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpDelete, OpDeleteOne:
+ return (&SettingDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
+ default:
+ return nil, fmt.Errorf("db: unknown Setting mutation op: %q", m.Op())
+ }
+}
+
+// UserClient is a client for the User schema.
+type UserClient struct {
+ config
+}
+
+// NewUserClient returns a client for the User from the given config.
+func NewUserClient(c config) *UserClient {
+ return &UserClient{config: c}
+}
+
+// Use adds a list of mutation hooks to the hooks stack.
+// A call to `Use(f, g, h)` equals to `user.Hooks(f(g(h())))`.
+func (c *UserClient) Use(hooks ...Hook) {
+ c.hooks.User = append(c.hooks.User, hooks...)
+}
+
+// Intercept adds a list of query interceptors to the interceptors stack.
+// A call to `Intercept(f, g, h)` equals to `user.Intercept(f(g(h())))`.
+func (c *UserClient) Intercept(interceptors ...Interceptor) {
+ c.inters.User = append(c.inters.User, interceptors...)
+}
+
+// Create returns a builder for creating a User entity.
+func (c *UserClient) Create() *UserCreate {
+ mutation := newUserMutation(c.config, OpCreate)
+ return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// CreateBulk returns a builder for creating a bulk of User entities.
+func (c *UserClient) CreateBulk(builders ...*UserCreate) *UserCreateBulk {
+ return &UserCreateBulk{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 *UserClient) MapCreateBulk(slice any, setFunc func(*UserCreate, int)) *UserCreateBulk {
+ rv := reflect.ValueOf(slice)
+ if rv.Kind() != reflect.Slice {
+ return &UserCreateBulk{err: fmt.Errorf("calling to UserClient.MapCreateBulk with wrong type %T, need slice", slice)}
+ }
+ builders := make([]*UserCreate, rv.Len())
+ for i := 0; i < rv.Len(); i++ {
+ builders[i] = c.Create()
+ setFunc(builders[i], i)
+ }
+ return &UserCreateBulk{config: c.config, builders: builders}
+}
+
+// Update returns an update builder for User.
+func (c *UserClient) Update() *UserUpdate {
+ mutation := newUserMutation(c.config, OpUpdate)
+ return &UserUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// UpdateOne returns an update builder for the given entity.
+func (c *UserClient) UpdateOne(u *User) *UserUpdateOne {
+ mutation := newUserMutation(c.config, OpUpdateOne, withUser(u))
+ return &UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// UpdateOneID returns an update builder for the given id.
+func (c *UserClient) UpdateOneID(id uuid.UUID) *UserUpdateOne {
+ mutation := newUserMutation(c.config, OpUpdateOne, withUserID(id))
+ return &UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// Delete returns a delete builder for User.
+func (c *UserClient) Delete() *UserDelete {
+ mutation := newUserMutation(c.config, OpDelete)
+ return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// DeleteOne returns a builder for deleting the given entity.
+func (c *UserClient) DeleteOne(u *User) *UserDeleteOne {
+ return c.DeleteOneID(u.ID)
+}
+
+// DeleteOneID returns a builder for deleting the given entity by its id.
+func (c *UserClient) DeleteOneID(id uuid.UUID) *UserDeleteOne {
+ builder := c.Delete().Where(user.ID(id))
+ builder.mutation.id = &id
+ builder.mutation.op = OpDeleteOne
+ return &UserDeleteOne{builder}
+}
+
+// Query returns a query builder for User.
+func (c *UserClient) Query() *UserQuery {
+ return &UserQuery{
+ config: c.config,
+ ctx: &QueryContext{Type: TypeUser},
+ inters: c.Interceptors(),
+ }
+}
+
+// Get returns a User entity by its id.
+func (c *UserClient) Get(ctx context.Context, id uuid.UUID) (*User, error) {
+ return c.Query().Where(user.ID(id)).Only(ctx)
+}
+
+// GetX is like Get, but panics if an error occurs.
+func (c *UserClient) GetX(ctx context.Context, id uuid.UUID) *User {
+ obj, err := c.Get(ctx, id)
+ if err != nil {
+ panic(err)
+ }
+ return obj
+}
+
+// QueryRecords queries the records edge of a User.
+func (c *UserClient) QueryRecords(u *User) *RecordQuery {
+ query := (&RecordClient{config: c.config}).Query()
+ query.path = func(context.Context) (fromV *sql.Selector, _ error) {
+ id := u.ID
+ step := sqlgraph.NewStep(
+ sqlgraph.From(user.Table, user.FieldID, id),
+ sqlgraph.To(record.Table, record.FieldID),
+ sqlgraph.Edge(sqlgraph.O2M, false, user.RecordsTable, user.RecordsColumn),
+ )
+ fromV = sqlgraph.Neighbors(u.driver.Dialect(), step)
+ return fromV, nil
+ }
+ return query
+}
+
+// QueryLoginHistories queries the login_histories edge of a User.
+func (c *UserClient) QueryLoginHistories(u *User) *UserLoginHistoryQuery {
+ query := (&UserLoginHistoryClient{config: c.config}).Query()
+ query.path = func(context.Context) (fromV *sql.Selector, _ error) {
+ id := u.ID
+ step := sqlgraph.NewStep(
+ sqlgraph.From(user.Table, user.FieldID, id),
+ sqlgraph.To(userloginhistory.Table, userloginhistory.FieldID),
+ sqlgraph.Edge(sqlgraph.O2M, false, user.LoginHistoriesTable, user.LoginHistoriesColumn),
+ )
+ fromV = sqlgraph.Neighbors(u.driver.Dialect(), step)
+ return fromV, nil
+ }
+ return query
+}
+
+// QueryModels queries the models edge of a User.
+func (c *UserClient) QueryModels(u *User) *ModelQuery {
+ query := (&ModelClient{config: c.config}).Query()
+ query.path = func(context.Context) (fromV *sql.Selector, _ error) {
+ id := u.ID
+ step := sqlgraph.NewStep(
+ sqlgraph.From(user.Table, user.FieldID, id),
+ sqlgraph.To(model.Table, model.FieldID),
+ sqlgraph.Edge(sqlgraph.O2M, false, user.ModelsTable, user.ModelsColumn),
+ )
+ fromV = sqlgraph.Neighbors(u.driver.Dialect(), step)
+ return fromV, nil
+ }
+ return query
+}
+
+// Hooks returns the client hooks.
+func (c *UserClient) Hooks() []Hook {
+ return c.hooks.User
+}
+
+// Interceptors returns the client interceptors.
+func (c *UserClient) Interceptors() []Interceptor {
+ return c.inters.User
+}
+
+func (c *UserClient) mutate(ctx context.Context, m *UserMutation) (Value, error) {
+ switch m.Op() {
+ case OpCreate:
+ return (&UserCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpUpdate:
+ return (&UserUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpUpdateOne:
+ return (&UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpDelete, OpDeleteOne:
+ return (&UserDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
+ default:
+ return nil, fmt.Errorf("db: unknown User mutation op: %q", m.Op())
+ }
+}
+
+// UserLoginHistoryClient is a client for the UserLoginHistory schema.
+type UserLoginHistoryClient struct {
+ config
+}
+
+// NewUserLoginHistoryClient returns a client for the UserLoginHistory from the given config.
+func NewUserLoginHistoryClient(c config) *UserLoginHistoryClient {
+ return &UserLoginHistoryClient{config: c}
+}
+
+// Use adds a list of mutation hooks to the hooks stack.
+// A call to `Use(f, g, h)` equals to `userloginhistory.Hooks(f(g(h())))`.
+func (c *UserLoginHistoryClient) Use(hooks ...Hook) {
+ c.hooks.UserLoginHistory = append(c.hooks.UserLoginHistory, hooks...)
+}
+
+// Intercept adds a list of query interceptors to the interceptors stack.
+// A call to `Intercept(f, g, h)` equals to `userloginhistory.Intercept(f(g(h())))`.
+func (c *UserLoginHistoryClient) Intercept(interceptors ...Interceptor) {
+ c.inters.UserLoginHistory = append(c.inters.UserLoginHistory, interceptors...)
+}
+
+// Create returns a builder for creating a UserLoginHistory entity.
+func (c *UserLoginHistoryClient) Create() *UserLoginHistoryCreate {
+ mutation := newUserLoginHistoryMutation(c.config, OpCreate)
+ return &UserLoginHistoryCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// CreateBulk returns a builder for creating a bulk of UserLoginHistory entities.
+func (c *UserLoginHistoryClient) CreateBulk(builders ...*UserLoginHistoryCreate) *UserLoginHistoryCreateBulk {
+ return &UserLoginHistoryCreateBulk{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 *UserLoginHistoryClient) MapCreateBulk(slice any, setFunc func(*UserLoginHistoryCreate, int)) *UserLoginHistoryCreateBulk {
+ rv := reflect.ValueOf(slice)
+ if rv.Kind() != reflect.Slice {
+ return &UserLoginHistoryCreateBulk{err: fmt.Errorf("calling to UserLoginHistoryClient.MapCreateBulk with wrong type %T, need slice", slice)}
+ }
+ builders := make([]*UserLoginHistoryCreate, rv.Len())
+ for i := 0; i < rv.Len(); i++ {
+ builders[i] = c.Create()
+ setFunc(builders[i], i)
+ }
+ return &UserLoginHistoryCreateBulk{config: c.config, builders: builders}
+}
+
+// Update returns an update builder for UserLoginHistory.
+func (c *UserLoginHistoryClient) Update() *UserLoginHistoryUpdate {
+ mutation := newUserLoginHistoryMutation(c.config, OpUpdate)
+ return &UserLoginHistoryUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// UpdateOne returns an update builder for the given entity.
+func (c *UserLoginHistoryClient) UpdateOne(ulh *UserLoginHistory) *UserLoginHistoryUpdateOne {
+ mutation := newUserLoginHistoryMutation(c.config, OpUpdateOne, withUserLoginHistory(ulh))
+ return &UserLoginHistoryUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// UpdateOneID returns an update builder for the given id.
+func (c *UserLoginHistoryClient) UpdateOneID(id uuid.UUID) *UserLoginHistoryUpdateOne {
+ mutation := newUserLoginHistoryMutation(c.config, OpUpdateOne, withUserLoginHistoryID(id))
+ return &UserLoginHistoryUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// Delete returns a delete builder for UserLoginHistory.
+func (c *UserLoginHistoryClient) Delete() *UserLoginHistoryDelete {
+ mutation := newUserLoginHistoryMutation(c.config, OpDelete)
+ return &UserLoginHistoryDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// DeleteOne returns a builder for deleting the given entity.
+func (c *UserLoginHistoryClient) DeleteOne(ulh *UserLoginHistory) *UserLoginHistoryDeleteOne {
+ return c.DeleteOneID(ulh.ID)
+}
+
+// DeleteOneID returns a builder for deleting the given entity by its id.
+func (c *UserLoginHistoryClient) DeleteOneID(id uuid.UUID) *UserLoginHistoryDeleteOne {
+ builder := c.Delete().Where(userloginhistory.ID(id))
+ builder.mutation.id = &id
+ builder.mutation.op = OpDeleteOne
+ return &UserLoginHistoryDeleteOne{builder}
+}
+
+// Query returns a query builder for UserLoginHistory.
+func (c *UserLoginHistoryClient) Query() *UserLoginHistoryQuery {
+ return &UserLoginHistoryQuery{
+ config: c.config,
+ ctx: &QueryContext{Type: TypeUserLoginHistory},
+ inters: c.Interceptors(),
+ }
+}
+
+// Get returns a UserLoginHistory entity by its id.
+func (c *UserLoginHistoryClient) Get(ctx context.Context, id uuid.UUID) (*UserLoginHistory, error) {
+ return c.Query().Where(userloginhistory.ID(id)).Only(ctx)
+}
+
+// GetX is like Get, but panics if an error occurs.
+func (c *UserLoginHistoryClient) GetX(ctx context.Context, id uuid.UUID) *UserLoginHistory {
+ obj, err := c.Get(ctx, id)
+ if err != nil {
+ panic(err)
+ }
+ return obj
+}
+
+// QueryOwner queries the owner edge of a UserLoginHistory.
+func (c *UserLoginHistoryClient) QueryOwner(ulh *UserLoginHistory) *UserQuery {
+ query := (&UserClient{config: c.config}).Query()
+ query.path = func(context.Context) (fromV *sql.Selector, _ error) {
+ id := ulh.ID
+ step := sqlgraph.NewStep(
+ sqlgraph.From(userloginhistory.Table, userloginhistory.FieldID, id),
+ sqlgraph.To(user.Table, user.FieldID),
+ sqlgraph.Edge(sqlgraph.M2O, true, userloginhistory.OwnerTable, userloginhistory.OwnerColumn),
+ )
+ fromV = sqlgraph.Neighbors(ulh.driver.Dialect(), step)
+ return fromV, nil
+ }
+ return query
+}
+
+// Hooks returns the client hooks.
+func (c *UserLoginHistoryClient) Hooks() []Hook {
+ return c.hooks.UserLoginHistory
+}
+
+// Interceptors returns the client interceptors.
+func (c *UserLoginHistoryClient) Interceptors() []Interceptor {
+ return c.inters.UserLoginHistory
+}
+
+func (c *UserLoginHistoryClient) mutate(ctx context.Context, m *UserLoginHistoryMutation) (Value, error) {
+ switch m.Op() {
+ case OpCreate:
+ return (&UserLoginHistoryCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpUpdate:
+ return (&UserLoginHistoryUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpUpdateOne:
+ return (&UserLoginHistoryUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+ case OpDelete, OpDeleteOne:
+ return (&UserLoginHistoryDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
+ default:
+ return nil, fmt.Errorf("db: unknown UserLoginHistory mutation op: %q", m.Op())
+ }
+}
+
+// hooks and interceptors per client, for fast access.
+type (
+ hooks struct {
+ Admin, AdminLoginHistory, ApiKey, BillingPlan, BillingQuota, BillingRecord,
+ BillingUsage, InviteCode, Model, Record, Setting, User,
+ UserLoginHistory []ent.Hook
+ }
+ inters struct {
+ Admin, AdminLoginHistory, ApiKey, BillingPlan, BillingQuota, BillingRecord,
+ BillingUsage, InviteCode, Model, Record, Setting, User,
+ UserLoginHistory []ent.Interceptor
+ }
+)
+
+// ExecContext allows calling the underlying ExecContext method of the driver if it is supported by it.
+// See, database/sql#DB.ExecContext for more information.
+func (c *config) ExecContext(ctx context.Context, query string, args ...any) (stdsql.Result, error) {
+ ex, ok := c.driver.(interface {
+ ExecContext(context.Context, string, ...any) (stdsql.Result, error)
+ })
+ if !ok {
+ return nil, fmt.Errorf("Driver.ExecContext is not supported")
+ }
+ return ex.ExecContext(ctx, query, args...)
+}
+
+// QueryContext allows calling the underlying QueryContext method of the driver if it is supported by it.
+// See, database/sql#DB.QueryContext for more information.
+func (c *config) QueryContext(ctx context.Context, query string, args ...any) (*stdsql.Rows, error) {
+ q, ok := c.driver.(interface {
+ QueryContext(context.Context, string, ...any) (*stdsql.Rows, error)
+ })
+ if !ok {
+ return nil, fmt.Errorf("Driver.QueryContext is not supported")
+ }
+ return q.QueryContext(ctx, query, args...)
+}
diff --git a/backend/db/ent.go b/backend/db/ent.go
new file mode 100644
index 0000000..d8ec291
--- /dev/null
+++ b/backend/db/ent.go
@@ -0,0 +1,632 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "reflect"
+ "sync"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "github.com/chaitin/MonkeyCode/backend/db/admin"
+ "github.com/chaitin/MonkeyCode/backend/db/adminloginhistory"
+ "github.com/chaitin/MonkeyCode/backend/db/apikey"
+ "github.com/chaitin/MonkeyCode/backend/db/billingplan"
+ "github.com/chaitin/MonkeyCode/backend/db/billingquota"
+ "github.com/chaitin/MonkeyCode/backend/db/billingrecord"
+ "github.com/chaitin/MonkeyCode/backend/db/billingusage"
+ "github.com/chaitin/MonkeyCode/backend/db/invitecode"
+ "github.com/chaitin/MonkeyCode/backend/db/model"
+ "github.com/chaitin/MonkeyCode/backend/db/record"
+ "github.com/chaitin/MonkeyCode/backend/db/setting"
+ "github.com/chaitin/MonkeyCode/backend/db/user"
+ "github.com/chaitin/MonkeyCode/backend/db/userloginhistory"
+)
+
+// ent aliases to avoid import conflicts in user's code.
+type (
+ Op = ent.Op
+ Hook = ent.Hook
+ Value = ent.Value
+ Query = ent.Query
+ QueryContext = ent.QueryContext
+ Querier = ent.Querier
+ QuerierFunc = ent.QuerierFunc
+ Interceptor = ent.Interceptor
+ InterceptFunc = ent.InterceptFunc
+ Traverser = ent.Traverser
+ TraverseFunc = ent.TraverseFunc
+ Policy = ent.Policy
+ Mutator = ent.Mutator
+ Mutation = ent.Mutation
+ MutateFunc = ent.MutateFunc
+)
+
+type clientCtxKey struct{}
+
+// FromContext returns a Client stored inside a context, or nil if there isn't one.
+func FromContext(ctx context.Context) *Client {
+ c, _ := ctx.Value(clientCtxKey{}).(*Client)
+ return c
+}
+
+// NewContext returns a new context with the given Client attached.
+func NewContext(parent context.Context, c *Client) context.Context {
+ return context.WithValue(parent, clientCtxKey{}, c)
+}
+
+type txCtxKey struct{}
+
+// TxFromContext returns a Tx stored inside a context, or nil if there isn't one.
+func TxFromContext(ctx context.Context) *Tx {
+ tx, _ := ctx.Value(txCtxKey{}).(*Tx)
+ return tx
+}
+
+// NewTxContext returns a new context with the given Tx attached.
+func NewTxContext(parent context.Context, tx *Tx) context.Context {
+ return context.WithValue(parent, txCtxKey{}, tx)
+}
+
+// OrderFunc applies an ordering on the sql selector.
+// Deprecated: Use Asc/Desc functions or the package builders instead.
+type OrderFunc func(*sql.Selector)
+
+var (
+ initCheck sync.Once
+ columnCheck sql.ColumnCheck
+)
+
+// checkColumn checks if the column exists in the given table.
+func checkColumn(table, column string) error {
+ initCheck.Do(func() {
+ columnCheck = sql.NewColumnCheck(map[string]func(string) bool{
+ admin.Table: admin.ValidColumn,
+ adminloginhistory.Table: adminloginhistory.ValidColumn,
+ apikey.Table: apikey.ValidColumn,
+ billingplan.Table: billingplan.ValidColumn,
+ billingquota.Table: billingquota.ValidColumn,
+ billingrecord.Table: billingrecord.ValidColumn,
+ billingusage.Table: billingusage.ValidColumn,
+ invitecode.Table: invitecode.ValidColumn,
+ model.Table: model.ValidColumn,
+ record.Table: record.ValidColumn,
+ setting.Table: setting.ValidColumn,
+ user.Table: user.ValidColumn,
+ userloginhistory.Table: userloginhistory.ValidColumn,
+ })
+ })
+ return columnCheck(table, column)
+}
+
+// Asc applies the given fields in ASC order.
+func Asc(fields ...string) func(*sql.Selector) {
+ return func(s *sql.Selector) {
+ for _, f := range fields {
+ if err := checkColumn(s.TableName(), f); err != nil {
+ s.AddError(&ValidationError{Name: f, err: fmt.Errorf("db: %w", err)})
+ }
+ s.OrderBy(sql.Asc(s.C(f)))
+ }
+ }
+}
+
+// Desc applies the given fields in DESC order.
+func Desc(fields ...string) func(*sql.Selector) {
+ return func(s *sql.Selector) {
+ for _, f := range fields {
+ if err := checkColumn(s.TableName(), f); err != nil {
+ s.AddError(&ValidationError{Name: f, err: fmt.Errorf("db: %w", err)})
+ }
+ s.OrderBy(sql.Desc(s.C(f)))
+ }
+ }
+}
+
+// AggregateFunc applies an aggregation step on the group-by traversal/selector.
+type AggregateFunc func(*sql.Selector) string
+
+// As is a pseudo aggregation function for renaming another other functions with custom names. For example:
+//
+// GroupBy(field1, field2).
+// Aggregate(db.As(db.Sum(field1), "sum_field1"), (db.As(db.Sum(field2), "sum_field2")).
+// Scan(ctx, &v)
+func As(fn AggregateFunc, end string) AggregateFunc {
+ return func(s *sql.Selector) string {
+ return sql.As(fn(s), end)
+ }
+}
+
+// Count applies the "count" aggregation function on each group.
+func Count() AggregateFunc {
+ return func(s *sql.Selector) string {
+ return sql.Count("*")
+ }
+}
+
+// Max applies the "max" aggregation function on the given field of each group.
+func Max(field string) AggregateFunc {
+ return func(s *sql.Selector) string {
+ if err := checkColumn(s.TableName(), field); err != nil {
+ s.AddError(&ValidationError{Name: field, err: fmt.Errorf("db: %w", err)})
+ return ""
+ }
+ return sql.Max(s.C(field))
+ }
+}
+
+// Mean applies the "mean" aggregation function on the given field of each group.
+func Mean(field string) AggregateFunc {
+ return func(s *sql.Selector) string {
+ if err := checkColumn(s.TableName(), field); err != nil {
+ s.AddError(&ValidationError{Name: field, err: fmt.Errorf("db: %w", err)})
+ return ""
+ }
+ return sql.Avg(s.C(field))
+ }
+}
+
+// Min applies the "min" aggregation function on the given field of each group.
+func Min(field string) AggregateFunc {
+ return func(s *sql.Selector) string {
+ if err := checkColumn(s.TableName(), field); err != nil {
+ s.AddError(&ValidationError{Name: field, err: fmt.Errorf("db: %w", err)})
+ return ""
+ }
+ return sql.Min(s.C(field))
+ }
+}
+
+// Sum applies the "sum" aggregation function on the given field of each group.
+func Sum(field string) AggregateFunc {
+ return func(s *sql.Selector) string {
+ if err := checkColumn(s.TableName(), field); err != nil {
+ s.AddError(&ValidationError{Name: field, err: fmt.Errorf("db: %w", err)})
+ return ""
+ }
+ return sql.Sum(s.C(field))
+ }
+}
+
+// ValidationError returns when validating a field or edge fails.
+type ValidationError struct {
+ Name string // Field or edge name.
+ err error
+}
+
+// Error implements the error interface.
+func (e *ValidationError) Error() string {
+ return e.err.Error()
+}
+
+// Unwrap implements the errors.Wrapper interface.
+func (e *ValidationError) Unwrap() error {
+ return e.err
+}
+
+// IsValidationError returns a boolean indicating whether the error is a validation error.
+func IsValidationError(err error) bool {
+ if err == nil {
+ return false
+ }
+ var e *ValidationError
+ return errors.As(err, &e)
+}
+
+// NotFoundError returns when trying to fetch a specific entity and it was not found in the database.
+type NotFoundError struct {
+ label string
+}
+
+// Error implements the error interface.
+func (e *NotFoundError) Error() string {
+ return "db: " + e.label + " not found"
+}
+
+// IsNotFound returns a boolean indicating whether the error is a not found error.
+func IsNotFound(err error) bool {
+ if err == nil {
+ return false
+ }
+ var e *NotFoundError
+ return errors.As(err, &e)
+}
+
+// MaskNotFound masks not found error.
+func MaskNotFound(err error) error {
+ if IsNotFound(err) {
+ return nil
+ }
+ return err
+}
+
+// NotSingularError returns when trying to fetch a singular entity and more then one was found in the database.
+type NotSingularError struct {
+ label string
+}
+
+// Error implements the error interface.
+func (e *NotSingularError) Error() string {
+ return "db: " + e.label + " not singular"
+}
+
+// IsNotSingular returns a boolean indicating whether the error is a not singular error.
+func IsNotSingular(err error) bool {
+ if err == nil {
+ return false
+ }
+ var e *NotSingularError
+ return errors.As(err, &e)
+}
+
+// NotLoadedError returns when trying to get a node that was not loaded by the query.
+type NotLoadedError struct {
+ edge string
+}
+
+// Error implements the error interface.
+func (e *NotLoadedError) Error() string {
+ return "db: " + e.edge + " edge was not loaded"
+}
+
+// IsNotLoaded returns a boolean indicating whether the error is a not loaded error.
+func IsNotLoaded(err error) bool {
+ if err == nil {
+ return false
+ }
+ var e *NotLoadedError
+ return errors.As(err, &e)
+}
+
+// ConstraintError returns when trying to create/update one or more entities and
+// one or more of their constraints failed. For example, violation of edge or
+// field uniqueness.
+type ConstraintError struct {
+ msg string
+ wrap error
+}
+
+// Error implements the error interface.
+func (e ConstraintError) Error() string {
+ return "db: constraint failed: " + e.msg
+}
+
+// Unwrap implements the errors.Wrapper interface.
+func (e *ConstraintError) Unwrap() error {
+ return e.wrap
+}
+
+// IsConstraintError returns a boolean indicating whether the error is a constraint failure.
+func IsConstraintError(err error) bool {
+ if err == nil {
+ return false
+ }
+ var e *ConstraintError
+ return errors.As(err, &e)
+}
+
+// selector embedded by the different Select/GroupBy builders.
+type selector struct {
+ label string
+ flds *[]string
+ fns []AggregateFunc
+ scan func(context.Context, any) error
+}
+
+// ScanX is like Scan, but panics if an error occurs.
+func (s *selector) ScanX(ctx context.Context, v any) {
+ if err := s.scan(ctx, v); err != nil {
+ panic(err)
+ }
+}
+
+// Strings returns list of strings from a selector. It is only allowed when selecting one field.
+func (s *selector) Strings(ctx context.Context) ([]string, error) {
+ if len(*s.flds) > 1 {
+ return nil, errors.New("db: Strings is not achievable when selecting more than 1 field")
+ }
+ var v []string
+ if err := s.scan(ctx, &v); err != nil {
+ return nil, err
+ }
+ return v, nil
+}
+
+// StringsX is like Strings, but panics if an error occurs.
+func (s *selector) StringsX(ctx context.Context) []string {
+ v, err := s.Strings(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return v
+}
+
+// String returns a single string from a selector. It is only allowed when selecting one field.
+func (s *selector) String(ctx context.Context) (_ string, err error) {
+ var v []string
+ if v, err = s.Strings(ctx); err != nil {
+ return
+ }
+ switch len(v) {
+ case 1:
+ return v[0], nil
+ case 0:
+ err = &NotFoundError{s.label}
+ default:
+ err = fmt.Errorf("db: Strings returned %d results when one was expected", len(v))
+ }
+ return
+}
+
+// StringX is like String, but panics if an error occurs.
+func (s *selector) StringX(ctx context.Context) string {
+ v, err := s.String(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return v
+}
+
+// Ints returns list of ints from a selector. It is only allowed when selecting one field.
+func (s *selector) Ints(ctx context.Context) ([]int, error) {
+ if len(*s.flds) > 1 {
+ return nil, errors.New("db: Ints is not achievable when selecting more than 1 field")
+ }
+ var v []int
+ if err := s.scan(ctx, &v); err != nil {
+ return nil, err
+ }
+ return v, nil
+}
+
+// IntsX is like Ints, but panics if an error occurs.
+func (s *selector) IntsX(ctx context.Context) []int {
+ v, err := s.Ints(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return v
+}
+
+// Int returns a single int from a selector. It is only allowed when selecting one field.
+func (s *selector) Int(ctx context.Context) (_ int, err error) {
+ var v []int
+ if v, err = s.Ints(ctx); err != nil {
+ return
+ }
+ switch len(v) {
+ case 1:
+ return v[0], nil
+ case 0:
+ err = &NotFoundError{s.label}
+ default:
+ err = fmt.Errorf("db: Ints returned %d results when one was expected", len(v))
+ }
+ return
+}
+
+// IntX is like Int, but panics if an error occurs.
+func (s *selector) IntX(ctx context.Context) int {
+ v, err := s.Int(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return v
+}
+
+// Float64s returns list of float64s from a selector. It is only allowed when selecting one field.
+func (s *selector) Float64s(ctx context.Context) ([]float64, error) {
+ if len(*s.flds) > 1 {
+ return nil, errors.New("db: Float64s is not achievable when selecting more than 1 field")
+ }
+ var v []float64
+ if err := s.scan(ctx, &v); err != nil {
+ return nil, err
+ }
+ return v, nil
+}
+
+// Float64sX is like Float64s, but panics if an error occurs.
+func (s *selector) Float64sX(ctx context.Context) []float64 {
+ v, err := s.Float64s(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return v
+}
+
+// Float64 returns a single float64 from a selector. It is only allowed when selecting one field.
+func (s *selector) Float64(ctx context.Context) (_ float64, err error) {
+ var v []float64
+ if v, err = s.Float64s(ctx); err != nil {
+ return
+ }
+ switch len(v) {
+ case 1:
+ return v[0], nil
+ case 0:
+ err = &NotFoundError{s.label}
+ default:
+ err = fmt.Errorf("db: Float64s returned %d results when one was expected", len(v))
+ }
+ return
+}
+
+// Float64X is like Float64, but panics if an error occurs.
+func (s *selector) Float64X(ctx context.Context) float64 {
+ v, err := s.Float64(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return v
+}
+
+// Bools returns list of bools from a selector. It is only allowed when selecting one field.
+func (s *selector) Bools(ctx context.Context) ([]bool, error) {
+ if len(*s.flds) > 1 {
+ return nil, errors.New("db: Bools is not achievable when selecting more than 1 field")
+ }
+ var v []bool
+ if err := s.scan(ctx, &v); err != nil {
+ return nil, err
+ }
+ return v, nil
+}
+
+// BoolsX is like Bools, but panics if an error occurs.
+func (s *selector) BoolsX(ctx context.Context) []bool {
+ v, err := s.Bools(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return v
+}
+
+// Bool returns a single bool from a selector. It is only allowed when selecting one field.
+func (s *selector) Bool(ctx context.Context) (_ bool, err error) {
+ var v []bool
+ if v, err = s.Bools(ctx); err != nil {
+ return
+ }
+ switch len(v) {
+ case 1:
+ return v[0], nil
+ case 0:
+ err = &NotFoundError{s.label}
+ default:
+ err = fmt.Errorf("db: Bools returned %d results when one was expected", len(v))
+ }
+ return
+}
+
+// BoolX is like Bool, but panics if an error occurs.
+func (s *selector) BoolX(ctx context.Context) bool {
+ v, err := s.Bool(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return v
+}
+
+// withHooks invokes the builder operation with the given hooks, if any.
+func withHooks[V Value, M any, PM interface {
+ *M
+ Mutation
+}](ctx context.Context, exec func(context.Context) (V, error), mutation PM, hooks []Hook) (value V, err error) {
+ if len(hooks) == 0 {
+ return exec(ctx)
+ }
+ var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
+ mutationT, ok := any(m).(PM)
+ if !ok {
+ return nil, fmt.Errorf("unexpected mutation type %T", m)
+ }
+ // Set the mutation to the builder.
+ *mutation = *mutationT
+ return exec(ctx)
+ })
+ for i := len(hooks) - 1; i >= 0; i-- {
+ if hooks[i] == nil {
+ return value, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
+ }
+ mut = hooks[i](mut)
+ }
+ v, err := mut.Mutate(ctx, mutation)
+ if err != nil {
+ return value, err
+ }
+ nv, ok := v.(V)
+ if !ok {
+ return value, fmt.Errorf("unexpected node type %T returned from %T", v, mutation)
+ }
+ return nv, nil
+}
+
+// setContextOp returns a new context with the given QueryContext attached (including its op) in case it does not exist.
+func setContextOp(ctx context.Context, qc *QueryContext, op string) context.Context {
+ if ent.QueryFromContext(ctx) == nil {
+ qc.Op = op
+ ctx = ent.NewQueryContext(ctx, qc)
+ }
+ return ctx
+}
+
+func querierAll[V Value, Q interface {
+ sqlAll(context.Context, ...queryHook) (V, error)
+}]() Querier {
+ return QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
+ query, ok := q.(Q)
+ if !ok {
+ return nil, fmt.Errorf("unexpected query type %T", q)
+ }
+ return query.sqlAll(ctx)
+ })
+}
+
+func querierCount[Q interface {
+ sqlCount(context.Context) (int, error)
+}]() Querier {
+ return QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
+ query, ok := q.(Q)
+ if !ok {
+ return nil, fmt.Errorf("unexpected query type %T", q)
+ }
+ return query.sqlCount(ctx)
+ })
+}
+
+func withInterceptors[V Value](ctx context.Context, q Query, qr Querier, inters []Interceptor) (v V, err error) {
+ for i := len(inters) - 1; i >= 0; i-- {
+ qr = inters[i].Intercept(qr)
+ }
+ rv, err := qr.Query(ctx, q)
+ if err != nil {
+ return v, err
+ }
+ vt, ok := rv.(V)
+ if !ok {
+ return v, fmt.Errorf("unexpected type %T returned from %T. expected type: %T", vt, q, v)
+ }
+ return vt, nil
+}
+
+func scanWithInterceptors[Q1 ent.Query, Q2 interface {
+ sqlScan(context.Context, Q1, any) error
+}](ctx context.Context, rootQuery Q1, selectOrGroup Q2, inters []Interceptor, v any) error {
+ rv := reflect.ValueOf(v)
+ var qr Querier = QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
+ query, ok := q.(Q1)
+ if !ok {
+ return nil, fmt.Errorf("unexpected query type %T", q)
+ }
+ if err := selectOrGroup.sqlScan(ctx, query, v); err != nil {
+ return nil, err
+ }
+ if k := rv.Kind(); k == reflect.Pointer && rv.Elem().CanInterface() {
+ return rv.Elem().Interface(), nil
+ }
+ return v, nil
+ })
+ for i := len(inters) - 1; i >= 0; i-- {
+ qr = inters[i].Intercept(qr)
+ }
+ vv, err := qr.Query(ctx, rootQuery)
+ if err != nil {
+ return err
+ }
+ switch rv2 := reflect.ValueOf(vv); {
+ case rv.IsNil(), rv2.IsNil(), rv.Kind() != reflect.Pointer:
+ case rv.Type() == rv2.Type():
+ rv.Elem().Set(rv2.Elem())
+ case rv.Elem().Type() == rv2.Type():
+ rv.Elem().Set(rv2)
+ }
+ return nil
+}
+
+// queryHook describes an internal hook for the different sqlAll methods.
+type queryHook func(context.Context, *sqlgraph.QuerySpec)
diff --git a/backend/db/enttest/enttest.go b/backend/db/enttest/enttest.go
new file mode 100644
index 0000000..de0e36a
--- /dev/null
+++ b/backend/db/enttest/enttest.go
@@ -0,0 +1,84 @@
+// Code generated by ent, DO NOT EDIT.
+
+package enttest
+
+import (
+ "context"
+
+ "github.com/chaitin/MonkeyCode/backend/db"
+ // required by schema hooks.
+ _ "github.com/chaitin/MonkeyCode/backend/db/runtime"
+
+ "entgo.io/ent/dialect/sql/schema"
+ "github.com/chaitin/MonkeyCode/backend/db/migrate"
+)
+
+type (
+ // TestingT is the interface that is shared between
+ // testing.T and testing.B and used by enttest.
+ TestingT interface {
+ FailNow()
+ Error(...any)
+ }
+
+ // Option configures client creation.
+ Option func(*options)
+
+ options struct {
+ opts []db.Option
+ migrateOpts []schema.MigrateOption
+ }
+)
+
+// WithOptions forwards options to client creation.
+func WithOptions(opts ...db.Option) Option {
+ return func(o *options) {
+ o.opts = append(o.opts, opts...)
+ }
+}
+
+// WithMigrateOptions forwards options to auto migration.
+func WithMigrateOptions(opts ...schema.MigrateOption) Option {
+ return func(o *options) {
+ o.migrateOpts = append(o.migrateOpts, opts...)
+ }
+}
+
+func newOptions(opts []Option) *options {
+ o := &options{}
+ for _, opt := range opts {
+ opt(o)
+ }
+ return o
+}
+
+// Open calls db.Open and auto-run migration.
+func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *db.Client {
+ o := newOptions(opts)
+ c, err := db.Open(driverName, dataSourceName, o.opts...)
+ if err != nil {
+ t.Error(err)
+ t.FailNow()
+ }
+ migrateSchema(t, c, o)
+ return c
+}
+
+// NewClient calls db.NewClient and auto-run migration.
+func NewClient(t TestingT, opts ...Option) *db.Client {
+ o := newOptions(opts)
+ c := db.NewClient(o.opts...)
+ migrateSchema(t, c, o)
+ return c
+}
+func migrateSchema(t TestingT, c *db.Client, o *options) {
+ tables, err := schema.CopyTables(migrate.Tables)
+ if err != nil {
+ t.Error(err)
+ t.FailNow()
+ }
+ if err := migrate.Create(context.Background(), c.Schema, tables, o.migrateOpts...); err != nil {
+ t.Error(err)
+ t.FailNow()
+ }
+}
diff --git a/backend/db/hook/hook.go b/backend/db/hook/hook.go
new file mode 100644
index 0000000..92d1829
--- /dev/null
+++ b/backend/db/hook/hook.go
@@ -0,0 +1,343 @@
+// Code generated by ent, DO NOT EDIT.
+
+package hook
+
+import (
+ "context"
+ "fmt"
+
+ "github.com/chaitin/MonkeyCode/backend/db"
+)
+
+// The AdminFunc type is an adapter to allow the use of ordinary
+// function as Admin mutator.
+type AdminFunc func(context.Context, *db.AdminMutation) (db.Value, error)
+
+// Mutate calls f(ctx, m).
+func (f AdminFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) {
+ if mv, ok := m.(*db.AdminMutation); ok {
+ return f(ctx, mv)
+ }
+ return nil, fmt.Errorf("unexpected mutation type %T. expect *db.AdminMutation", m)
+}
+
+// The AdminLoginHistoryFunc type is an adapter to allow the use of ordinary
+// function as AdminLoginHistory mutator.
+type AdminLoginHistoryFunc func(context.Context, *db.AdminLoginHistoryMutation) (db.Value, error)
+
+// Mutate calls f(ctx, m).
+func (f AdminLoginHistoryFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) {
+ if mv, ok := m.(*db.AdminLoginHistoryMutation); ok {
+ return f(ctx, mv)
+ }
+ return nil, fmt.Errorf("unexpected mutation type %T. expect *db.AdminLoginHistoryMutation", m)
+}
+
+// The ApiKeyFunc type is an adapter to allow the use of ordinary
+// function as ApiKey mutator.
+type ApiKeyFunc func(context.Context, *db.ApiKeyMutation) (db.Value, error)
+
+// Mutate calls f(ctx, m).
+func (f ApiKeyFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) {
+ if mv, ok := m.(*db.ApiKeyMutation); ok {
+ return f(ctx, mv)
+ }
+ return nil, fmt.Errorf("unexpected mutation type %T. expect *db.ApiKeyMutation", m)
+}
+
+// The BillingPlanFunc type is an adapter to allow the use of ordinary
+// function as BillingPlan mutator.
+type BillingPlanFunc func(context.Context, *db.BillingPlanMutation) (db.Value, error)
+
+// Mutate calls f(ctx, m).
+func (f BillingPlanFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) {
+ if mv, ok := m.(*db.BillingPlanMutation); ok {
+ return f(ctx, mv)
+ }
+ return nil, fmt.Errorf("unexpected mutation type %T. expect *db.BillingPlanMutation", m)
+}
+
+// The BillingQuotaFunc type is an adapter to allow the use of ordinary
+// function as BillingQuota mutator.
+type BillingQuotaFunc func(context.Context, *db.BillingQuotaMutation) (db.Value, error)
+
+// Mutate calls f(ctx, m).
+func (f BillingQuotaFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) {
+ if mv, ok := m.(*db.BillingQuotaMutation); ok {
+ return f(ctx, mv)
+ }
+ return nil, fmt.Errorf("unexpected mutation type %T. expect *db.BillingQuotaMutation", m)
+}
+
+// The BillingRecordFunc type is an adapter to allow the use of ordinary
+// function as BillingRecord mutator.
+type BillingRecordFunc func(context.Context, *db.BillingRecordMutation) (db.Value, error)
+
+// Mutate calls f(ctx, m).
+func (f BillingRecordFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) {
+ if mv, ok := m.(*db.BillingRecordMutation); ok {
+ return f(ctx, mv)
+ }
+ return nil, fmt.Errorf("unexpected mutation type %T. expect *db.BillingRecordMutation", m)
+}
+
+// The BillingUsageFunc type is an adapter to allow the use of ordinary
+// function as BillingUsage mutator.
+type BillingUsageFunc func(context.Context, *db.BillingUsageMutation) (db.Value, error)
+
+// Mutate calls f(ctx, m).
+func (f BillingUsageFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) {
+ if mv, ok := m.(*db.BillingUsageMutation); ok {
+ return f(ctx, mv)
+ }
+ return nil, fmt.Errorf("unexpected mutation type %T. expect *db.BillingUsageMutation", m)
+}
+
+// The InviteCodeFunc type is an adapter to allow the use of ordinary
+// function as InviteCode mutator.
+type InviteCodeFunc func(context.Context, *db.InviteCodeMutation) (db.Value, error)
+
+// Mutate calls f(ctx, m).
+func (f InviteCodeFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) {
+ if mv, ok := m.(*db.InviteCodeMutation); ok {
+ return f(ctx, mv)
+ }
+ return nil, fmt.Errorf("unexpected mutation type %T. expect *db.InviteCodeMutation", m)
+}
+
+// The ModelFunc type is an adapter to allow the use of ordinary
+// function as Model mutator.
+type ModelFunc func(context.Context, *db.ModelMutation) (db.Value, error)
+
+// Mutate calls f(ctx, m).
+func (f ModelFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) {
+ if mv, ok := m.(*db.ModelMutation); ok {
+ return f(ctx, mv)
+ }
+ return nil, fmt.Errorf("unexpected mutation type %T. expect *db.ModelMutation", m)
+}
+
+// The RecordFunc type is an adapter to allow the use of ordinary
+// function as Record mutator.
+type RecordFunc func(context.Context, *db.RecordMutation) (db.Value, error)
+
+// Mutate calls f(ctx, m).
+func (f RecordFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) {
+ if mv, ok := m.(*db.RecordMutation); ok {
+ return f(ctx, mv)
+ }
+ return nil, fmt.Errorf("unexpected mutation type %T. expect *db.RecordMutation", m)
+}
+
+// The SettingFunc type is an adapter to allow the use of ordinary
+// function as Setting mutator.
+type SettingFunc func(context.Context, *db.SettingMutation) (db.Value, error)
+
+// Mutate calls f(ctx, m).
+func (f SettingFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) {
+ if mv, ok := m.(*db.SettingMutation); ok {
+ return f(ctx, mv)
+ }
+ return nil, fmt.Errorf("unexpected mutation type %T. expect *db.SettingMutation", m)
+}
+
+// The UserFunc type is an adapter to allow the use of ordinary
+// function as User mutator.
+type UserFunc func(context.Context, *db.UserMutation) (db.Value, error)
+
+// Mutate calls f(ctx, m).
+func (f UserFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) {
+ if mv, ok := m.(*db.UserMutation); ok {
+ return f(ctx, mv)
+ }
+ return nil, fmt.Errorf("unexpected mutation type %T. expect *db.UserMutation", m)
+}
+
+// The UserLoginHistoryFunc type is an adapter to allow the use of ordinary
+// function as UserLoginHistory mutator.
+type UserLoginHistoryFunc func(context.Context, *db.UserLoginHistoryMutation) (db.Value, error)
+
+// Mutate calls f(ctx, m).
+func (f UserLoginHistoryFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) {
+ if mv, ok := m.(*db.UserLoginHistoryMutation); ok {
+ return f(ctx, mv)
+ }
+ return nil, fmt.Errorf("unexpected mutation type %T. expect *db.UserLoginHistoryMutation", m)
+}
+
+// Condition is a hook condition function.
+type Condition func(context.Context, db.Mutation) bool
+
+// And groups conditions with the AND operator.
+func And(first, second Condition, rest ...Condition) Condition {
+ return func(ctx context.Context, m db.Mutation) bool {
+ if !first(ctx, m) || !second(ctx, m) {
+ return false
+ }
+ for _, cond := range rest {
+ if !cond(ctx, m) {
+ return false
+ }
+ }
+ return true
+ }
+}
+
+// Or groups conditions with the OR operator.
+func Or(first, second Condition, rest ...Condition) Condition {
+ return func(ctx context.Context, m db.Mutation) bool {
+ if first(ctx, m) || second(ctx, m) {
+ return true
+ }
+ for _, cond := range rest {
+ if cond(ctx, m) {
+ return true
+ }
+ }
+ return false
+ }
+}
+
+// Not negates a given condition.
+func Not(cond Condition) Condition {
+ return func(ctx context.Context, m db.Mutation) bool {
+ return !cond(ctx, m)
+ }
+}
+
+// HasOp is a condition testing mutation operation.
+func HasOp(op db.Op) Condition {
+ return func(_ context.Context, m db.Mutation) bool {
+ return m.Op().Is(op)
+ }
+}
+
+// HasAddedFields is a condition validating `.AddedField` on fields.
+func HasAddedFields(field string, fields ...string) Condition {
+ return func(_ context.Context, m db.Mutation) bool {
+ if _, exists := m.AddedField(field); !exists {
+ return false
+ }
+ for _, field := range fields {
+ if _, exists := m.AddedField(field); !exists {
+ return false
+ }
+ }
+ return true
+ }
+}
+
+// HasClearedFields is a condition validating `.FieldCleared` on fields.
+func HasClearedFields(field string, fields ...string) Condition {
+ return func(_ context.Context, m db.Mutation) bool {
+ if exists := m.FieldCleared(field); !exists {
+ return false
+ }
+ for _, field := range fields {
+ if exists := m.FieldCleared(field); !exists {
+ return false
+ }
+ }
+ return true
+ }
+}
+
+// HasFields is a condition validating `.Field` on fields.
+func HasFields(field string, fields ...string) Condition {
+ return func(_ context.Context, m db.Mutation) bool {
+ if _, exists := m.Field(field); !exists {
+ return false
+ }
+ for _, field := range fields {
+ if _, exists := m.Field(field); !exists {
+ return false
+ }
+ }
+ return true
+ }
+}
+
+// If executes the given hook under condition.
+//
+// hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...)))
+func If(hk db.Hook, cond Condition) db.Hook {
+ return func(next db.Mutator) db.Mutator {
+ return db.MutateFunc(func(ctx context.Context, m db.Mutation) (db.Value, error) {
+ if cond(ctx, m) {
+ return hk(next).Mutate(ctx, m)
+ }
+ return next.Mutate(ctx, m)
+ })
+ }
+}
+
+// On executes the given hook only for the given operation.
+//
+// hook.On(Log, db.Delete|db.Create)
+func On(hk db.Hook, op db.Op) db.Hook {
+ return If(hk, HasOp(op))
+}
+
+// Unless skips the given hook only for the given operation.
+//
+// hook.Unless(Log, db.Update|db.UpdateOne)
+func Unless(hk db.Hook, op db.Op) db.Hook {
+ return If(hk, Not(HasOp(op)))
+}
+
+// FixedError is a hook returning a fixed error.
+func FixedError(err error) db.Hook {
+ return func(db.Mutator) db.Mutator {
+ return db.MutateFunc(func(context.Context, db.Mutation) (db.Value, error) {
+ return nil, err
+ })
+ }
+}
+
+// Reject returns a hook that rejects all operations that match op.
+//
+// func (T) Hooks() []db.Hook {
+// return []db.Hook{
+// Reject(db.Delete|db.Update),
+// }
+// }
+func Reject(op db.Op) db.Hook {
+ hk := FixedError(fmt.Errorf("%s operation is not allowed", op))
+ return On(hk, op)
+}
+
+// Chain acts as a list of hooks and is effectively immutable.
+// Once created, it will always hold the same set of hooks in the same order.
+type Chain struct {
+ hooks []db.Hook
+}
+
+// NewChain creates a new chain of hooks.
+func NewChain(hooks ...db.Hook) Chain {
+ return Chain{append([]db.Hook(nil), hooks...)}
+}
+
+// Hook chains the list of hooks and returns the final hook.
+func (c Chain) Hook() db.Hook {
+ return func(mutator db.Mutator) db.Mutator {
+ for i := len(c.hooks) - 1; i >= 0; i-- {
+ mutator = c.hooks[i](mutator)
+ }
+ return mutator
+ }
+}
+
+// Append extends a chain, adding the specified hook
+// as the last ones in the mutation flow.
+func (c Chain) Append(hooks ...db.Hook) Chain {
+ newHooks := make([]db.Hook, 0, len(c.hooks)+len(hooks))
+ newHooks = append(newHooks, c.hooks...)
+ newHooks = append(newHooks, hooks...)
+ return Chain{newHooks}
+}
+
+// Extend extends a chain, adding the specified chain
+// as the last ones in the mutation flow.
+func (c Chain) Extend(chain Chain) Chain {
+ return c.Append(chain.hooks...)
+}
diff --git a/backend/db/intercept/intercept.go b/backend/db/intercept/intercept.go
new file mode 100644
index 0000000..925b277
--- /dev/null
+++ b/backend/db/intercept/intercept.go
@@ -0,0 +1,509 @@
+// Code generated by ent, DO NOT EDIT.
+
+package intercept
+
+import (
+ "context"
+ "fmt"
+
+ "entgo.io/ent/dialect/sql"
+ "github.com/chaitin/MonkeyCode/backend/db"
+ "github.com/chaitin/MonkeyCode/backend/db/admin"
+ "github.com/chaitin/MonkeyCode/backend/db/adminloginhistory"
+ "github.com/chaitin/MonkeyCode/backend/db/apikey"
+ "github.com/chaitin/MonkeyCode/backend/db/billingplan"
+ "github.com/chaitin/MonkeyCode/backend/db/billingquota"
+ "github.com/chaitin/MonkeyCode/backend/db/billingrecord"
+ "github.com/chaitin/MonkeyCode/backend/db/billingusage"
+ "github.com/chaitin/MonkeyCode/backend/db/invitecode"
+ "github.com/chaitin/MonkeyCode/backend/db/model"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+ "github.com/chaitin/MonkeyCode/backend/db/record"
+ "github.com/chaitin/MonkeyCode/backend/db/setting"
+ "github.com/chaitin/MonkeyCode/backend/db/user"
+ "github.com/chaitin/MonkeyCode/backend/db/userloginhistory"
+)
+
+// The Query interface represents an operation that queries a graph.
+// By using this interface, users can write generic code that manipulates
+// query builders of different types.
+type Query interface {
+ // Type returns the string representation of the query type.
+ Type() string
+ // Limit the number of records to be returned by this query.
+ Limit(int)
+ // Offset to start from.
+ Offset(int)
+ // Unique configures the query builder to filter duplicate records.
+ Unique(bool)
+ // Order specifies how the records should be ordered.
+ Order(...func(*sql.Selector))
+ // WhereP appends storage-level predicates to the query builder. Using this method, users
+ // can use type-assertion to append predicates that do not depend on any generated package.
+ WhereP(...func(*sql.Selector))
+}
+
+// The Func type is an adapter that allows ordinary functions to be used as interceptors.
+// Unlike traversal functions, interceptors are skipped during graph traversals. Note that the
+// implementation of Func is different from the one defined in entgo.io/ent.InterceptFunc.
+type Func func(context.Context, Query) error
+
+// Intercept calls f(ctx, q) and then applied the next Querier.
+func (f Func) Intercept(next db.Querier) db.Querier {
+ return db.QuerierFunc(func(ctx context.Context, q db.Query) (db.Value, error) {
+ query, err := NewQuery(q)
+ if err != nil {
+ return nil, err
+ }
+ if err := f(ctx, query); err != nil {
+ return nil, err
+ }
+ return next.Query(ctx, q)
+ })
+}
+
+// The TraverseFunc type is an adapter to allow the use of ordinary function as Traverser.
+// If f is a function with the appropriate signature, TraverseFunc(f) is a Traverser that calls f.
+type TraverseFunc func(context.Context, Query) error
+
+// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
+func (f TraverseFunc) Intercept(next db.Querier) db.Querier {
+ return next
+}
+
+// Traverse calls f(ctx, q).
+func (f TraverseFunc) Traverse(ctx context.Context, q db.Query) error {
+ query, err := NewQuery(q)
+ if err != nil {
+ return err
+ }
+ return f(ctx, query)
+}
+
+// The AdminFunc type is an adapter to allow the use of ordinary function as a Querier.
+type AdminFunc func(context.Context, *db.AdminQuery) (db.Value, error)
+
+// Query calls f(ctx, q).
+func (f AdminFunc) Query(ctx context.Context, q db.Query) (db.Value, error) {
+ if q, ok := q.(*db.AdminQuery); ok {
+ return f(ctx, q)
+ }
+ return nil, fmt.Errorf("unexpected query type %T. expect *db.AdminQuery", q)
+}
+
+// The TraverseAdmin type is an adapter to allow the use of ordinary function as Traverser.
+type TraverseAdmin func(context.Context, *db.AdminQuery) error
+
+// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
+func (f TraverseAdmin) Intercept(next db.Querier) db.Querier {
+ return next
+}
+
+// Traverse calls f(ctx, q).
+func (f TraverseAdmin) Traverse(ctx context.Context, q db.Query) error {
+ if q, ok := q.(*db.AdminQuery); ok {
+ return f(ctx, q)
+ }
+ return fmt.Errorf("unexpected query type %T. expect *db.AdminQuery", q)
+}
+
+// The AdminLoginHistoryFunc type is an adapter to allow the use of ordinary function as a Querier.
+type AdminLoginHistoryFunc func(context.Context, *db.AdminLoginHistoryQuery) (db.Value, error)
+
+// Query calls f(ctx, q).
+func (f AdminLoginHistoryFunc) Query(ctx context.Context, q db.Query) (db.Value, error) {
+ if q, ok := q.(*db.AdminLoginHistoryQuery); ok {
+ return f(ctx, q)
+ }
+ return nil, fmt.Errorf("unexpected query type %T. expect *db.AdminLoginHistoryQuery", q)
+}
+
+// The TraverseAdminLoginHistory type is an adapter to allow the use of ordinary function as Traverser.
+type TraverseAdminLoginHistory func(context.Context, *db.AdminLoginHistoryQuery) error
+
+// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
+func (f TraverseAdminLoginHistory) Intercept(next db.Querier) db.Querier {
+ return next
+}
+
+// Traverse calls f(ctx, q).
+func (f TraverseAdminLoginHistory) Traverse(ctx context.Context, q db.Query) error {
+ if q, ok := q.(*db.AdminLoginHistoryQuery); ok {
+ return f(ctx, q)
+ }
+ return fmt.Errorf("unexpected query type %T. expect *db.AdminLoginHistoryQuery", q)
+}
+
+// The ApiKeyFunc type is an adapter to allow the use of ordinary function as a Querier.
+type ApiKeyFunc func(context.Context, *db.ApiKeyQuery) (db.Value, error)
+
+// Query calls f(ctx, q).
+func (f ApiKeyFunc) Query(ctx context.Context, q db.Query) (db.Value, error) {
+ if q, ok := q.(*db.ApiKeyQuery); ok {
+ return f(ctx, q)
+ }
+ return nil, fmt.Errorf("unexpected query type %T. expect *db.ApiKeyQuery", q)
+}
+
+// The TraverseApiKey type is an adapter to allow the use of ordinary function as Traverser.
+type TraverseApiKey func(context.Context, *db.ApiKeyQuery) error
+
+// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
+func (f TraverseApiKey) Intercept(next db.Querier) db.Querier {
+ return next
+}
+
+// Traverse calls f(ctx, q).
+func (f TraverseApiKey) Traverse(ctx context.Context, q db.Query) error {
+ if q, ok := q.(*db.ApiKeyQuery); ok {
+ return f(ctx, q)
+ }
+ return fmt.Errorf("unexpected query type %T. expect *db.ApiKeyQuery", q)
+}
+
+// The BillingPlanFunc type is an adapter to allow the use of ordinary function as a Querier.
+type BillingPlanFunc func(context.Context, *db.BillingPlanQuery) (db.Value, error)
+
+// Query calls f(ctx, q).
+func (f BillingPlanFunc) Query(ctx context.Context, q db.Query) (db.Value, error) {
+ if q, ok := q.(*db.BillingPlanQuery); ok {
+ return f(ctx, q)
+ }
+ return nil, fmt.Errorf("unexpected query type %T. expect *db.BillingPlanQuery", q)
+}
+
+// The TraverseBillingPlan type is an adapter to allow the use of ordinary function as Traverser.
+type TraverseBillingPlan func(context.Context, *db.BillingPlanQuery) error
+
+// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
+func (f TraverseBillingPlan) Intercept(next db.Querier) db.Querier {
+ return next
+}
+
+// Traverse calls f(ctx, q).
+func (f TraverseBillingPlan) Traverse(ctx context.Context, q db.Query) error {
+ if q, ok := q.(*db.BillingPlanQuery); ok {
+ return f(ctx, q)
+ }
+ return fmt.Errorf("unexpected query type %T. expect *db.BillingPlanQuery", q)
+}
+
+// The BillingQuotaFunc type is an adapter to allow the use of ordinary function as a Querier.
+type BillingQuotaFunc func(context.Context, *db.BillingQuotaQuery) (db.Value, error)
+
+// Query calls f(ctx, q).
+func (f BillingQuotaFunc) Query(ctx context.Context, q db.Query) (db.Value, error) {
+ if q, ok := q.(*db.BillingQuotaQuery); ok {
+ return f(ctx, q)
+ }
+ return nil, fmt.Errorf("unexpected query type %T. expect *db.BillingQuotaQuery", q)
+}
+
+// The TraverseBillingQuota type is an adapter to allow the use of ordinary function as Traverser.
+type TraverseBillingQuota func(context.Context, *db.BillingQuotaQuery) error
+
+// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
+func (f TraverseBillingQuota) Intercept(next db.Querier) db.Querier {
+ return next
+}
+
+// Traverse calls f(ctx, q).
+func (f TraverseBillingQuota) Traverse(ctx context.Context, q db.Query) error {
+ if q, ok := q.(*db.BillingQuotaQuery); ok {
+ return f(ctx, q)
+ }
+ return fmt.Errorf("unexpected query type %T. expect *db.BillingQuotaQuery", q)
+}
+
+// The BillingRecordFunc type is an adapter to allow the use of ordinary function as a Querier.
+type BillingRecordFunc func(context.Context, *db.BillingRecordQuery) (db.Value, error)
+
+// Query calls f(ctx, q).
+func (f BillingRecordFunc) Query(ctx context.Context, q db.Query) (db.Value, error) {
+ if q, ok := q.(*db.BillingRecordQuery); ok {
+ return f(ctx, q)
+ }
+ return nil, fmt.Errorf("unexpected query type %T. expect *db.BillingRecordQuery", q)
+}
+
+// The TraverseBillingRecord type is an adapter to allow the use of ordinary function as Traverser.
+type TraverseBillingRecord func(context.Context, *db.BillingRecordQuery) error
+
+// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
+func (f TraverseBillingRecord) Intercept(next db.Querier) db.Querier {
+ return next
+}
+
+// Traverse calls f(ctx, q).
+func (f TraverseBillingRecord) Traverse(ctx context.Context, q db.Query) error {
+ if q, ok := q.(*db.BillingRecordQuery); ok {
+ return f(ctx, q)
+ }
+ return fmt.Errorf("unexpected query type %T. expect *db.BillingRecordQuery", q)
+}
+
+// The BillingUsageFunc type is an adapter to allow the use of ordinary function as a Querier.
+type BillingUsageFunc func(context.Context, *db.BillingUsageQuery) (db.Value, error)
+
+// Query calls f(ctx, q).
+func (f BillingUsageFunc) Query(ctx context.Context, q db.Query) (db.Value, error) {
+ if q, ok := q.(*db.BillingUsageQuery); ok {
+ return f(ctx, q)
+ }
+ return nil, fmt.Errorf("unexpected query type %T. expect *db.BillingUsageQuery", q)
+}
+
+// The TraverseBillingUsage type is an adapter to allow the use of ordinary function as Traverser.
+type TraverseBillingUsage func(context.Context, *db.BillingUsageQuery) error
+
+// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
+func (f TraverseBillingUsage) Intercept(next db.Querier) db.Querier {
+ return next
+}
+
+// Traverse calls f(ctx, q).
+func (f TraverseBillingUsage) Traverse(ctx context.Context, q db.Query) error {
+ if q, ok := q.(*db.BillingUsageQuery); ok {
+ return f(ctx, q)
+ }
+ return fmt.Errorf("unexpected query type %T. expect *db.BillingUsageQuery", q)
+}
+
+// The InviteCodeFunc type is an adapter to allow the use of ordinary function as a Querier.
+type InviteCodeFunc func(context.Context, *db.InviteCodeQuery) (db.Value, error)
+
+// Query calls f(ctx, q).
+func (f InviteCodeFunc) Query(ctx context.Context, q db.Query) (db.Value, error) {
+ if q, ok := q.(*db.InviteCodeQuery); ok {
+ return f(ctx, q)
+ }
+ return nil, fmt.Errorf("unexpected query type %T. expect *db.InviteCodeQuery", q)
+}
+
+// The TraverseInviteCode type is an adapter to allow the use of ordinary function as Traverser.
+type TraverseInviteCode func(context.Context, *db.InviteCodeQuery) error
+
+// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
+func (f TraverseInviteCode) Intercept(next db.Querier) db.Querier {
+ return next
+}
+
+// Traverse calls f(ctx, q).
+func (f TraverseInviteCode) Traverse(ctx context.Context, q db.Query) error {
+ if q, ok := q.(*db.InviteCodeQuery); ok {
+ return f(ctx, q)
+ }
+ return fmt.Errorf("unexpected query type %T. expect *db.InviteCodeQuery", q)
+}
+
+// The ModelFunc type is an adapter to allow the use of ordinary function as a Querier.
+type ModelFunc func(context.Context, *db.ModelQuery) (db.Value, error)
+
+// Query calls f(ctx, q).
+func (f ModelFunc) Query(ctx context.Context, q db.Query) (db.Value, error) {
+ if q, ok := q.(*db.ModelQuery); ok {
+ return f(ctx, q)
+ }
+ return nil, fmt.Errorf("unexpected query type %T. expect *db.ModelQuery", q)
+}
+
+// The TraverseModel type is an adapter to allow the use of ordinary function as Traverser.
+type TraverseModel func(context.Context, *db.ModelQuery) error
+
+// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
+func (f TraverseModel) Intercept(next db.Querier) db.Querier {
+ return next
+}
+
+// Traverse calls f(ctx, q).
+func (f TraverseModel) Traverse(ctx context.Context, q db.Query) error {
+ if q, ok := q.(*db.ModelQuery); ok {
+ return f(ctx, q)
+ }
+ return fmt.Errorf("unexpected query type %T. expect *db.ModelQuery", q)
+}
+
+// The RecordFunc type is an adapter to allow the use of ordinary function as a Querier.
+type RecordFunc func(context.Context, *db.RecordQuery) (db.Value, error)
+
+// Query calls f(ctx, q).
+func (f RecordFunc) Query(ctx context.Context, q db.Query) (db.Value, error) {
+ if q, ok := q.(*db.RecordQuery); ok {
+ return f(ctx, q)
+ }
+ return nil, fmt.Errorf("unexpected query type %T. expect *db.RecordQuery", q)
+}
+
+// The TraverseRecord type is an adapter to allow the use of ordinary function as Traverser.
+type TraverseRecord func(context.Context, *db.RecordQuery) error
+
+// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
+func (f TraverseRecord) Intercept(next db.Querier) db.Querier {
+ return next
+}
+
+// Traverse calls f(ctx, q).
+func (f TraverseRecord) Traverse(ctx context.Context, q db.Query) error {
+ if q, ok := q.(*db.RecordQuery); ok {
+ return f(ctx, q)
+ }
+ return fmt.Errorf("unexpected query type %T. expect *db.RecordQuery", q)
+}
+
+// The SettingFunc type is an adapter to allow the use of ordinary function as a Querier.
+type SettingFunc func(context.Context, *db.SettingQuery) (db.Value, error)
+
+// Query calls f(ctx, q).
+func (f SettingFunc) Query(ctx context.Context, q db.Query) (db.Value, error) {
+ if q, ok := q.(*db.SettingQuery); ok {
+ return f(ctx, q)
+ }
+ return nil, fmt.Errorf("unexpected query type %T. expect *db.SettingQuery", q)
+}
+
+// The TraverseSetting type is an adapter to allow the use of ordinary function as Traverser.
+type TraverseSetting func(context.Context, *db.SettingQuery) error
+
+// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
+func (f TraverseSetting) Intercept(next db.Querier) db.Querier {
+ return next
+}
+
+// Traverse calls f(ctx, q).
+func (f TraverseSetting) Traverse(ctx context.Context, q db.Query) error {
+ if q, ok := q.(*db.SettingQuery); ok {
+ return f(ctx, q)
+ }
+ return fmt.Errorf("unexpected query type %T. expect *db.SettingQuery", q)
+}
+
+// The UserFunc type is an adapter to allow the use of ordinary function as a Querier.
+type UserFunc func(context.Context, *db.UserQuery) (db.Value, error)
+
+// Query calls f(ctx, q).
+func (f UserFunc) Query(ctx context.Context, q db.Query) (db.Value, error) {
+ if q, ok := q.(*db.UserQuery); ok {
+ return f(ctx, q)
+ }
+ return nil, fmt.Errorf("unexpected query type %T. expect *db.UserQuery", q)
+}
+
+// The TraverseUser type is an adapter to allow the use of ordinary function as Traverser.
+type TraverseUser func(context.Context, *db.UserQuery) error
+
+// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
+func (f TraverseUser) Intercept(next db.Querier) db.Querier {
+ return next
+}
+
+// Traverse calls f(ctx, q).
+func (f TraverseUser) Traverse(ctx context.Context, q db.Query) error {
+ if q, ok := q.(*db.UserQuery); ok {
+ return f(ctx, q)
+ }
+ return fmt.Errorf("unexpected query type %T. expect *db.UserQuery", q)
+}
+
+// The UserLoginHistoryFunc type is an adapter to allow the use of ordinary function as a Querier.
+type UserLoginHistoryFunc func(context.Context, *db.UserLoginHistoryQuery) (db.Value, error)
+
+// Query calls f(ctx, q).
+func (f UserLoginHistoryFunc) Query(ctx context.Context, q db.Query) (db.Value, error) {
+ if q, ok := q.(*db.UserLoginHistoryQuery); ok {
+ return f(ctx, q)
+ }
+ return nil, fmt.Errorf("unexpected query type %T. expect *db.UserLoginHistoryQuery", q)
+}
+
+// The TraverseUserLoginHistory type is an adapter to allow the use of ordinary function as Traverser.
+type TraverseUserLoginHistory func(context.Context, *db.UserLoginHistoryQuery) error
+
+// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
+func (f TraverseUserLoginHistory) Intercept(next db.Querier) db.Querier {
+ return next
+}
+
+// Traverse calls f(ctx, q).
+func (f TraverseUserLoginHistory) Traverse(ctx context.Context, q db.Query) error {
+ if q, ok := q.(*db.UserLoginHistoryQuery); ok {
+ return f(ctx, q)
+ }
+ return fmt.Errorf("unexpected query type %T. expect *db.UserLoginHistoryQuery", q)
+}
+
+// NewQuery returns the generic Query interface for the given typed query.
+func NewQuery(q db.Query) (Query, error) {
+ switch q := q.(type) {
+ case *db.AdminQuery:
+ return &query[*db.AdminQuery, predicate.Admin, admin.OrderOption]{typ: db.TypeAdmin, tq: q}, nil
+ case *db.AdminLoginHistoryQuery:
+ return &query[*db.AdminLoginHistoryQuery, predicate.AdminLoginHistory, adminloginhistory.OrderOption]{typ: db.TypeAdminLoginHistory, tq: q}, nil
+ case *db.ApiKeyQuery:
+ return &query[*db.ApiKeyQuery, predicate.ApiKey, apikey.OrderOption]{typ: db.TypeApiKey, tq: q}, nil
+ case *db.BillingPlanQuery:
+ return &query[*db.BillingPlanQuery, predicate.BillingPlan, billingplan.OrderOption]{typ: db.TypeBillingPlan, tq: q}, nil
+ case *db.BillingQuotaQuery:
+ return &query[*db.BillingQuotaQuery, predicate.BillingQuota, billingquota.OrderOption]{typ: db.TypeBillingQuota, tq: q}, nil
+ case *db.BillingRecordQuery:
+ return &query[*db.BillingRecordQuery, predicate.BillingRecord, billingrecord.OrderOption]{typ: db.TypeBillingRecord, tq: q}, nil
+ case *db.BillingUsageQuery:
+ return &query[*db.BillingUsageQuery, predicate.BillingUsage, billingusage.OrderOption]{typ: db.TypeBillingUsage, tq: q}, nil
+ case *db.InviteCodeQuery:
+ return &query[*db.InviteCodeQuery, predicate.InviteCode, invitecode.OrderOption]{typ: db.TypeInviteCode, tq: q}, nil
+ case *db.ModelQuery:
+ return &query[*db.ModelQuery, predicate.Model, model.OrderOption]{typ: db.TypeModel, tq: q}, nil
+ case *db.RecordQuery:
+ return &query[*db.RecordQuery, predicate.Record, record.OrderOption]{typ: db.TypeRecord, tq: q}, nil
+ case *db.SettingQuery:
+ return &query[*db.SettingQuery, predicate.Setting, setting.OrderOption]{typ: db.TypeSetting, tq: q}, nil
+ case *db.UserQuery:
+ return &query[*db.UserQuery, predicate.User, user.OrderOption]{typ: db.TypeUser, tq: q}, nil
+ case *db.UserLoginHistoryQuery:
+ return &query[*db.UserLoginHistoryQuery, predicate.UserLoginHistory, userloginhistory.OrderOption]{typ: db.TypeUserLoginHistory, tq: q}, nil
+ default:
+ return nil, fmt.Errorf("unknown query type %T", q)
+ }
+}
+
+type query[T any, P ~func(*sql.Selector), R ~func(*sql.Selector)] struct {
+ typ string
+ tq interface {
+ Limit(int) T
+ Offset(int) T
+ Unique(bool) T
+ Order(...R) T
+ Where(...P) T
+ }
+}
+
+func (q query[T, P, R]) Type() string {
+ return q.typ
+}
+
+func (q query[T, P, R]) Limit(limit int) {
+ q.tq.Limit(limit)
+}
+
+func (q query[T, P, R]) Offset(offset int) {
+ q.tq.Offset(offset)
+}
+
+func (q query[T, P, R]) Unique(unique bool) {
+ q.tq.Unique(unique)
+}
+
+func (q query[T, P, R]) Order(orders ...func(*sql.Selector)) {
+ rs := make([]R, len(orders))
+ for i := range orders {
+ rs[i] = orders[i]
+ }
+ q.tq.Order(rs...)
+}
+
+func (q query[T, P, R]) WhereP(ps ...func(*sql.Selector)) {
+ p := make([]P, len(ps))
+ for i := range ps {
+ p[i] = ps[i]
+ }
+ q.tq.Where(p...)
+}
diff --git a/backend/db/invitecode.go b/backend/db/invitecode.go
new file mode 100644
index 0000000..3235da8
--- /dev/null
+++ b/backend/db/invitecode.go
@@ -0,0 +1,140 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "fmt"
+ "strings"
+ "time"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect/sql"
+ "github.com/chaitin/MonkeyCode/backend/db/invitecode"
+ "github.com/google/uuid"
+)
+
+// InviteCode is the model entity for the InviteCode schema.
+type InviteCode struct {
+ config `json:"-"`
+ // ID of the ent.
+ ID uuid.UUID `json:"id,omitempty"`
+ // AdminID holds the value of the "admin_id" field.
+ AdminID uuid.UUID `json:"admin_id,omitempty"`
+ // Code holds the value of the "code" field.
+ Code string `json:"code,omitempty"`
+ // CreatedAt holds the value of the "created_at" field.
+ CreatedAt time.Time `json:"created_at,omitempty"`
+ // UpdatedAt holds the value of the "updated_at" field.
+ UpdatedAt time.Time `json:"updated_at,omitempty"`
+ selectValues sql.SelectValues
+}
+
+// scanValues returns the types for scanning values from sql.Rows.
+func (*InviteCode) scanValues(columns []string) ([]any, error) {
+ values := make([]any, len(columns))
+ for i := range columns {
+ switch columns[i] {
+ case invitecode.FieldCode:
+ values[i] = new(sql.NullString)
+ case invitecode.FieldCreatedAt, invitecode.FieldUpdatedAt:
+ values[i] = new(sql.NullTime)
+ case invitecode.FieldID, invitecode.FieldAdminID:
+ values[i] = new(uuid.UUID)
+ default:
+ values[i] = new(sql.UnknownType)
+ }
+ }
+ return values, nil
+}
+
+// assignValues assigns the values that were returned from sql.Rows (after scanning)
+// to the InviteCode fields.
+func (ic *InviteCode) assignValues(columns []string, values []any) error {
+ if m, n := len(values), len(columns); m < n {
+ return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
+ }
+ for i := range columns {
+ switch columns[i] {
+ case invitecode.FieldID:
+ if value, ok := values[i].(*uuid.UUID); !ok {
+ return fmt.Errorf("unexpected type %T for field id", values[i])
+ } else if value != nil {
+ ic.ID = *value
+ }
+ case invitecode.FieldAdminID:
+ if value, ok := values[i].(*uuid.UUID); !ok {
+ return fmt.Errorf("unexpected type %T for field admin_id", values[i])
+ } else if value != nil {
+ ic.AdminID = *value
+ }
+ case invitecode.FieldCode:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field code", values[i])
+ } else if value.Valid {
+ ic.Code = value.String
+ }
+ case invitecode.FieldCreatedAt:
+ if value, ok := values[i].(*sql.NullTime); !ok {
+ return fmt.Errorf("unexpected type %T for field created_at", values[i])
+ } else if value.Valid {
+ ic.CreatedAt = value.Time
+ }
+ case invitecode.FieldUpdatedAt:
+ if value, ok := values[i].(*sql.NullTime); !ok {
+ return fmt.Errorf("unexpected type %T for field updated_at", values[i])
+ } else if value.Valid {
+ ic.UpdatedAt = value.Time
+ }
+ default:
+ ic.selectValues.Set(columns[i], values[i])
+ }
+ }
+ return nil
+}
+
+// Value returns the ent.Value that was dynamically selected and assigned to the InviteCode.
+// This includes values selected through modifiers, order, etc.
+func (ic *InviteCode) Value(name string) (ent.Value, error) {
+ return ic.selectValues.Get(name)
+}
+
+// Update returns a builder for updating this InviteCode.
+// Note that you need to call InviteCode.Unwrap() before calling this method if this InviteCode
+// was returned from a transaction, and the transaction was committed or rolled back.
+func (ic *InviteCode) Update() *InviteCodeUpdateOne {
+ return NewInviteCodeClient(ic.config).UpdateOne(ic)
+}
+
+// Unwrap unwraps the InviteCode entity that was returned from a transaction after it was closed,
+// so that all future queries will be executed through the driver which created the transaction.
+func (ic *InviteCode) Unwrap() *InviteCode {
+ _tx, ok := ic.config.driver.(*txDriver)
+ if !ok {
+ panic("db: InviteCode is not a transactional entity")
+ }
+ ic.config.driver = _tx.drv
+ return ic
+}
+
+// String implements the fmt.Stringer.
+func (ic *InviteCode) String() string {
+ var builder strings.Builder
+ builder.WriteString("InviteCode(")
+ builder.WriteString(fmt.Sprintf("id=%v, ", ic.ID))
+ builder.WriteString("admin_id=")
+ builder.WriteString(fmt.Sprintf("%v", ic.AdminID))
+ builder.WriteString(", ")
+ builder.WriteString("code=")
+ builder.WriteString(ic.Code)
+ builder.WriteString(", ")
+ builder.WriteString("created_at=")
+ builder.WriteString(ic.CreatedAt.Format(time.ANSIC))
+ builder.WriteString(", ")
+ builder.WriteString("updated_at=")
+ builder.WriteString(ic.UpdatedAt.Format(time.ANSIC))
+ builder.WriteByte(')')
+ return builder.String()
+}
+
+// InviteCodes is a parsable slice of InviteCode.
+type InviteCodes []*InviteCode
diff --git a/backend/db/invitecode/invitecode.go b/backend/db/invitecode/invitecode.go
new file mode 100644
index 0000000..c376405
--- /dev/null
+++ b/backend/db/invitecode/invitecode.go
@@ -0,0 +1,82 @@
+// Code generated by ent, DO NOT EDIT.
+
+package invitecode
+
+import (
+ "time"
+
+ "entgo.io/ent/dialect/sql"
+)
+
+const (
+ // Label holds the string label denoting the invitecode type in the database.
+ Label = "invite_code"
+ // FieldID holds the string denoting the id field in the database.
+ FieldID = "id"
+ // FieldAdminID holds the string denoting the admin_id field in the database.
+ FieldAdminID = "admin_id"
+ // FieldCode holds the string denoting the code field in the database.
+ FieldCode = "code"
+ // FieldCreatedAt holds the string denoting the created_at field in the database.
+ FieldCreatedAt = "created_at"
+ // FieldUpdatedAt holds the string denoting the updated_at field in the database.
+ FieldUpdatedAt = "updated_at"
+ // Table holds the table name of the invitecode in the database.
+ Table = "invite_codes"
+)
+
+// Columns holds all SQL columns for invitecode fields.
+var Columns = []string{
+ FieldID,
+ FieldAdminID,
+ FieldCode,
+ FieldCreatedAt,
+ FieldUpdatedAt,
+}
+
+// ValidColumn reports if the column name is valid (part of the table columns).
+func ValidColumn(column string) bool {
+ for i := range Columns {
+ if column == Columns[i] {
+ return true
+ }
+ }
+ return false
+}
+
+var (
+ // DefaultCreatedAt holds the default value on creation for the "created_at" field.
+ DefaultCreatedAt func() time.Time
+ // DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
+ DefaultUpdatedAt func() time.Time
+ // UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field.
+ UpdateDefaultUpdatedAt func() time.Time
+)
+
+// OrderOption defines the ordering options for the InviteCode queries.
+type OrderOption func(*sql.Selector)
+
+// ByID orders the results by the id field.
+func ByID(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldID, opts...).ToFunc()
+}
+
+// ByAdminID orders the results by the admin_id field.
+func ByAdminID(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldAdminID, opts...).ToFunc()
+}
+
+// ByCode orders the results by the code field.
+func ByCode(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldCode, opts...).ToFunc()
+}
+
+// ByCreatedAt orders the results by the created_at field.
+func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
+}
+
+// ByUpdatedAt orders the results by the updated_at field.
+func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc()
+}
diff --git a/backend/db/invitecode/where.go b/backend/db/invitecode/where.go
new file mode 100644
index 0000000..0503279
--- /dev/null
+++ b/backend/db/invitecode/where.go
@@ -0,0 +1,276 @@
+// Code generated by ent, DO NOT EDIT.
+
+package invitecode
+
+import (
+ "time"
+
+ "entgo.io/ent/dialect/sql"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+ "github.com/google/uuid"
+)
+
+// ID filters vertices based on their ID field.
+func ID(id uuid.UUID) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldEQ(FieldID, id))
+}
+
+// IDEQ applies the EQ predicate on the ID field.
+func IDEQ(id uuid.UUID) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldEQ(FieldID, id))
+}
+
+// IDNEQ applies the NEQ predicate on the ID field.
+func IDNEQ(id uuid.UUID) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldNEQ(FieldID, id))
+}
+
+// IDIn applies the In predicate on the ID field.
+func IDIn(ids ...uuid.UUID) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldIn(FieldID, ids...))
+}
+
+// IDNotIn applies the NotIn predicate on the ID field.
+func IDNotIn(ids ...uuid.UUID) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldNotIn(FieldID, ids...))
+}
+
+// IDGT applies the GT predicate on the ID field.
+func IDGT(id uuid.UUID) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldGT(FieldID, id))
+}
+
+// IDGTE applies the GTE predicate on the ID field.
+func IDGTE(id uuid.UUID) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldGTE(FieldID, id))
+}
+
+// IDLT applies the LT predicate on the ID field.
+func IDLT(id uuid.UUID) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldLT(FieldID, id))
+}
+
+// IDLTE applies the LTE predicate on the ID field.
+func IDLTE(id uuid.UUID) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldLTE(FieldID, id))
+}
+
+// AdminID applies equality check predicate on the "admin_id" field. It's identical to AdminIDEQ.
+func AdminID(v uuid.UUID) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldEQ(FieldAdminID, v))
+}
+
+// Code applies equality check predicate on the "code" field. It's identical to CodeEQ.
+func Code(v string) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldEQ(FieldCode, v))
+}
+
+// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
+func CreatedAt(v time.Time) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldEQ(FieldCreatedAt, v))
+}
+
+// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
+func UpdatedAt(v time.Time) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldEQ(FieldUpdatedAt, v))
+}
+
+// AdminIDEQ applies the EQ predicate on the "admin_id" field.
+func AdminIDEQ(v uuid.UUID) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldEQ(FieldAdminID, v))
+}
+
+// AdminIDNEQ applies the NEQ predicate on the "admin_id" field.
+func AdminIDNEQ(v uuid.UUID) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldNEQ(FieldAdminID, v))
+}
+
+// AdminIDIn applies the In predicate on the "admin_id" field.
+func AdminIDIn(vs ...uuid.UUID) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldIn(FieldAdminID, vs...))
+}
+
+// AdminIDNotIn applies the NotIn predicate on the "admin_id" field.
+func AdminIDNotIn(vs ...uuid.UUID) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldNotIn(FieldAdminID, vs...))
+}
+
+// AdminIDGT applies the GT predicate on the "admin_id" field.
+func AdminIDGT(v uuid.UUID) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldGT(FieldAdminID, v))
+}
+
+// AdminIDGTE applies the GTE predicate on the "admin_id" field.
+func AdminIDGTE(v uuid.UUID) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldGTE(FieldAdminID, v))
+}
+
+// AdminIDLT applies the LT predicate on the "admin_id" field.
+func AdminIDLT(v uuid.UUID) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldLT(FieldAdminID, v))
+}
+
+// AdminIDLTE applies the LTE predicate on the "admin_id" field.
+func AdminIDLTE(v uuid.UUID) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldLTE(FieldAdminID, v))
+}
+
+// CodeEQ applies the EQ predicate on the "code" field.
+func CodeEQ(v string) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldEQ(FieldCode, v))
+}
+
+// CodeNEQ applies the NEQ predicate on the "code" field.
+func CodeNEQ(v string) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldNEQ(FieldCode, v))
+}
+
+// CodeIn applies the In predicate on the "code" field.
+func CodeIn(vs ...string) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldIn(FieldCode, vs...))
+}
+
+// CodeNotIn applies the NotIn predicate on the "code" field.
+func CodeNotIn(vs ...string) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldNotIn(FieldCode, vs...))
+}
+
+// CodeGT applies the GT predicate on the "code" field.
+func CodeGT(v string) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldGT(FieldCode, v))
+}
+
+// CodeGTE applies the GTE predicate on the "code" field.
+func CodeGTE(v string) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldGTE(FieldCode, v))
+}
+
+// CodeLT applies the LT predicate on the "code" field.
+func CodeLT(v string) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldLT(FieldCode, v))
+}
+
+// CodeLTE applies the LTE predicate on the "code" field.
+func CodeLTE(v string) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldLTE(FieldCode, v))
+}
+
+// CodeContains applies the Contains predicate on the "code" field.
+func CodeContains(v string) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldContains(FieldCode, v))
+}
+
+// CodeHasPrefix applies the HasPrefix predicate on the "code" field.
+func CodeHasPrefix(v string) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldHasPrefix(FieldCode, v))
+}
+
+// CodeHasSuffix applies the HasSuffix predicate on the "code" field.
+func CodeHasSuffix(v string) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldHasSuffix(FieldCode, v))
+}
+
+// CodeEqualFold applies the EqualFold predicate on the "code" field.
+func CodeEqualFold(v string) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldEqualFold(FieldCode, v))
+}
+
+// CodeContainsFold applies the ContainsFold predicate on the "code" field.
+func CodeContainsFold(v string) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldContainsFold(FieldCode, v))
+}
+
+// CreatedAtEQ applies the EQ predicate on the "created_at" field.
+func CreatedAtEQ(v time.Time) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldEQ(FieldCreatedAt, v))
+}
+
+// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
+func CreatedAtNEQ(v time.Time) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldNEQ(FieldCreatedAt, v))
+}
+
+// CreatedAtIn applies the In predicate on the "created_at" field.
+func CreatedAtIn(vs ...time.Time) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldIn(FieldCreatedAt, vs...))
+}
+
+// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
+func CreatedAtNotIn(vs ...time.Time) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldNotIn(FieldCreatedAt, vs...))
+}
+
+// CreatedAtGT applies the GT predicate on the "created_at" field.
+func CreatedAtGT(v time.Time) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldGT(FieldCreatedAt, v))
+}
+
+// CreatedAtGTE applies the GTE predicate on the "created_at" field.
+func CreatedAtGTE(v time.Time) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldGTE(FieldCreatedAt, v))
+}
+
+// CreatedAtLT applies the LT predicate on the "created_at" field.
+func CreatedAtLT(v time.Time) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldLT(FieldCreatedAt, v))
+}
+
+// CreatedAtLTE applies the LTE predicate on the "created_at" field.
+func CreatedAtLTE(v time.Time) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldLTE(FieldCreatedAt, v))
+}
+
+// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
+func UpdatedAtEQ(v time.Time) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldEQ(FieldUpdatedAt, v))
+}
+
+// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
+func UpdatedAtNEQ(v time.Time) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldNEQ(FieldUpdatedAt, v))
+}
+
+// UpdatedAtIn applies the In predicate on the "updated_at" field.
+func UpdatedAtIn(vs ...time.Time) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldIn(FieldUpdatedAt, vs...))
+}
+
+// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
+func UpdatedAtNotIn(vs ...time.Time) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldNotIn(FieldUpdatedAt, vs...))
+}
+
+// UpdatedAtGT applies the GT predicate on the "updated_at" field.
+func UpdatedAtGT(v time.Time) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldGT(FieldUpdatedAt, v))
+}
+
+// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
+func UpdatedAtGTE(v time.Time) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldGTE(FieldUpdatedAt, v))
+}
+
+// UpdatedAtLT applies the LT predicate on the "updated_at" field.
+func UpdatedAtLT(v time.Time) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldLT(FieldUpdatedAt, v))
+}
+
+// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
+func UpdatedAtLTE(v time.Time) predicate.InviteCode {
+ return predicate.InviteCode(sql.FieldLTE(FieldUpdatedAt, v))
+}
+
+// And groups predicates with the AND operator between them.
+func And(predicates ...predicate.InviteCode) predicate.InviteCode {
+ return predicate.InviteCode(sql.AndPredicates(predicates...))
+}
+
+// Or groups predicates with the OR operator between them.
+func Or(predicates ...predicate.InviteCode) predicate.InviteCode {
+ return predicate.InviteCode(sql.OrPredicates(predicates...))
+}
+
+// Not applies the not operator on the given predicate.
+func Not(p predicate.InviteCode) predicate.InviteCode {
+ return predicate.InviteCode(sql.NotPredicates(p))
+}
diff --git a/backend/db/invitecode_create.go b/backend/db/invitecode_create.go
new file mode 100644
index 0000000..1c249d3
--- /dev/null
+++ b/backend/db/invitecode_create.go
@@ -0,0 +1,680 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "time"
+
+ "entgo.io/ent/dialect"
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/invitecode"
+ "github.com/google/uuid"
+)
+
+// InviteCodeCreate is the builder for creating a InviteCode entity.
+type InviteCodeCreate struct {
+ config
+ mutation *InviteCodeMutation
+ hooks []Hook
+ conflict []sql.ConflictOption
+}
+
+// SetAdminID sets the "admin_id" field.
+func (icc *InviteCodeCreate) SetAdminID(u uuid.UUID) *InviteCodeCreate {
+ icc.mutation.SetAdminID(u)
+ return icc
+}
+
+// SetCode sets the "code" field.
+func (icc *InviteCodeCreate) SetCode(s string) *InviteCodeCreate {
+ icc.mutation.SetCode(s)
+ return icc
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (icc *InviteCodeCreate) SetCreatedAt(t time.Time) *InviteCodeCreate {
+ icc.mutation.SetCreatedAt(t)
+ return icc
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (icc *InviteCodeCreate) SetNillableCreatedAt(t *time.Time) *InviteCodeCreate {
+ if t != nil {
+ icc.SetCreatedAt(*t)
+ }
+ return icc
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (icc *InviteCodeCreate) SetUpdatedAt(t time.Time) *InviteCodeCreate {
+ icc.mutation.SetUpdatedAt(t)
+ return icc
+}
+
+// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
+func (icc *InviteCodeCreate) SetNillableUpdatedAt(t *time.Time) *InviteCodeCreate {
+ if t != nil {
+ icc.SetUpdatedAt(*t)
+ }
+ return icc
+}
+
+// SetID sets the "id" field.
+func (icc *InviteCodeCreate) SetID(u uuid.UUID) *InviteCodeCreate {
+ icc.mutation.SetID(u)
+ return icc
+}
+
+// Mutation returns the InviteCodeMutation object of the builder.
+func (icc *InviteCodeCreate) Mutation() *InviteCodeMutation {
+ return icc.mutation
+}
+
+// Save creates the InviteCode in the database.
+func (icc *InviteCodeCreate) Save(ctx context.Context) (*InviteCode, error) {
+ icc.defaults()
+ return withHooks(ctx, icc.sqlSave, icc.mutation, icc.hooks)
+}
+
+// SaveX calls Save and panics if Save returns an error.
+func (icc *InviteCodeCreate) SaveX(ctx context.Context) *InviteCode {
+ v, err := icc.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return v
+}
+
+// Exec executes the query.
+func (icc *InviteCodeCreate) Exec(ctx context.Context) error {
+ _, err := icc.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (icc *InviteCodeCreate) ExecX(ctx context.Context) {
+ if err := icc.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// defaults sets the default values of the builder before save.
+func (icc *InviteCodeCreate) defaults() {
+ if _, ok := icc.mutation.CreatedAt(); !ok {
+ v := invitecode.DefaultCreatedAt()
+ icc.mutation.SetCreatedAt(v)
+ }
+ if _, ok := icc.mutation.UpdatedAt(); !ok {
+ v := invitecode.DefaultUpdatedAt()
+ icc.mutation.SetUpdatedAt(v)
+ }
+}
+
+// check runs all checks and user-defined validators on the builder.
+func (icc *InviteCodeCreate) check() error {
+ if _, ok := icc.mutation.AdminID(); !ok {
+ return &ValidationError{Name: "admin_id", err: errors.New(`db: missing required field "InviteCode.admin_id"`)}
+ }
+ if _, ok := icc.mutation.Code(); !ok {
+ return &ValidationError{Name: "code", err: errors.New(`db: missing required field "InviteCode.code"`)}
+ }
+ if _, ok := icc.mutation.CreatedAt(); !ok {
+ return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "InviteCode.created_at"`)}
+ }
+ if _, ok := icc.mutation.UpdatedAt(); !ok {
+ return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "InviteCode.updated_at"`)}
+ }
+ return nil
+}
+
+func (icc *InviteCodeCreate) sqlSave(ctx context.Context) (*InviteCode, error) {
+ if err := icc.check(); err != nil {
+ return nil, err
+ }
+ _node, _spec := icc.createSpec()
+ if err := sqlgraph.CreateNode(ctx, icc.driver, _spec); err != nil {
+ if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return nil, err
+ }
+ if _spec.ID.Value != nil {
+ if id, ok := _spec.ID.Value.(*uuid.UUID); ok {
+ _node.ID = *id
+ } else if err := _node.ID.Scan(_spec.ID.Value); err != nil {
+ return nil, err
+ }
+ }
+ icc.mutation.id = &_node.ID
+ icc.mutation.done = true
+ return _node, nil
+}
+
+func (icc *InviteCodeCreate) createSpec() (*InviteCode, *sqlgraph.CreateSpec) {
+ var (
+ _node = &InviteCode{config: icc.config}
+ _spec = sqlgraph.NewCreateSpec(invitecode.Table, sqlgraph.NewFieldSpec(invitecode.FieldID, field.TypeUUID))
+ )
+ _spec.OnConflict = icc.conflict
+ if id, ok := icc.mutation.ID(); ok {
+ _node.ID = id
+ _spec.ID.Value = &id
+ }
+ if value, ok := icc.mutation.AdminID(); ok {
+ _spec.SetField(invitecode.FieldAdminID, field.TypeUUID, value)
+ _node.AdminID = value
+ }
+ if value, ok := icc.mutation.Code(); ok {
+ _spec.SetField(invitecode.FieldCode, field.TypeString, value)
+ _node.Code = value
+ }
+ if value, ok := icc.mutation.CreatedAt(); ok {
+ _spec.SetField(invitecode.FieldCreatedAt, field.TypeTime, value)
+ _node.CreatedAt = value
+ }
+ if value, ok := icc.mutation.UpdatedAt(); ok {
+ _spec.SetField(invitecode.FieldUpdatedAt, field.TypeTime, value)
+ _node.UpdatedAt = value
+ }
+ return _node, _spec
+}
+
+// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
+// of the `INSERT` statement. For example:
+//
+// client.InviteCode.Create().
+// SetAdminID(v).
+// OnConflict(
+// // Update the row with the new values
+// // the was proposed for insertion.
+// sql.ResolveWithNewValues(),
+// ).
+// // Override some of the fields with custom
+// // update values.
+// Update(func(u *ent.InviteCodeUpsert) {
+// SetAdminID(v+v).
+// }).
+// Exec(ctx)
+func (icc *InviteCodeCreate) OnConflict(opts ...sql.ConflictOption) *InviteCodeUpsertOne {
+ icc.conflict = opts
+ return &InviteCodeUpsertOne{
+ create: icc,
+ }
+}
+
+// OnConflictColumns calls `OnConflict` and configures the columns
+// as conflict target. Using this option is equivalent to using:
+//
+// client.InviteCode.Create().
+// OnConflict(sql.ConflictColumns(columns...)).
+// Exec(ctx)
+func (icc *InviteCodeCreate) OnConflictColumns(columns ...string) *InviteCodeUpsertOne {
+ icc.conflict = append(icc.conflict, sql.ConflictColumns(columns...))
+ return &InviteCodeUpsertOne{
+ create: icc,
+ }
+}
+
+type (
+ // InviteCodeUpsertOne is the builder for "upsert"-ing
+ // one InviteCode node.
+ InviteCodeUpsertOne struct {
+ create *InviteCodeCreate
+ }
+
+ // InviteCodeUpsert is the "OnConflict" setter.
+ InviteCodeUpsert struct {
+ *sql.UpdateSet
+ }
+)
+
+// SetAdminID sets the "admin_id" field.
+func (u *InviteCodeUpsert) SetAdminID(v uuid.UUID) *InviteCodeUpsert {
+ u.Set(invitecode.FieldAdminID, v)
+ return u
+}
+
+// UpdateAdminID sets the "admin_id" field to the value that was provided on create.
+func (u *InviteCodeUpsert) UpdateAdminID() *InviteCodeUpsert {
+ u.SetExcluded(invitecode.FieldAdminID)
+ return u
+}
+
+// SetCode sets the "code" field.
+func (u *InviteCodeUpsert) SetCode(v string) *InviteCodeUpsert {
+ u.Set(invitecode.FieldCode, v)
+ return u
+}
+
+// UpdateCode sets the "code" field to the value that was provided on create.
+func (u *InviteCodeUpsert) UpdateCode() *InviteCodeUpsert {
+ u.SetExcluded(invitecode.FieldCode)
+ return u
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (u *InviteCodeUpsert) SetCreatedAt(v time.Time) *InviteCodeUpsert {
+ u.Set(invitecode.FieldCreatedAt, v)
+ return u
+}
+
+// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
+func (u *InviteCodeUpsert) UpdateCreatedAt() *InviteCodeUpsert {
+ u.SetExcluded(invitecode.FieldCreatedAt)
+ return u
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (u *InviteCodeUpsert) SetUpdatedAt(v time.Time) *InviteCodeUpsert {
+ u.Set(invitecode.FieldUpdatedAt, v)
+ return u
+}
+
+// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
+func (u *InviteCodeUpsert) UpdateUpdatedAt() *InviteCodeUpsert {
+ u.SetExcluded(invitecode.FieldUpdatedAt)
+ return u
+}
+
+// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field.
+// Using this option is equivalent to using:
+//
+// client.InviteCode.Create().
+// OnConflict(
+// sql.ResolveWithNewValues(),
+// sql.ResolveWith(func(u *sql.UpdateSet) {
+// u.SetIgnore(invitecode.FieldID)
+// }),
+// ).
+// Exec(ctx)
+func (u *InviteCodeUpsertOne) UpdateNewValues() *InviteCodeUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
+ if _, exists := u.create.mutation.ID(); exists {
+ s.SetIgnore(invitecode.FieldID)
+ }
+ }))
+ return u
+}
+
+// Ignore sets each column to itself in case of conflict.
+// Using this option is equivalent to using:
+//
+// client.InviteCode.Create().
+// OnConflict(sql.ResolveWithIgnore()).
+// Exec(ctx)
+func (u *InviteCodeUpsertOne) Ignore() *InviteCodeUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
+ return u
+}
+
+// DoNothing configures the conflict_action to `DO NOTHING`.
+// Supported only by SQLite and PostgreSQL.
+func (u *InviteCodeUpsertOne) DoNothing() *InviteCodeUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.DoNothing())
+ return u
+}
+
+// Update allows overriding fields `UPDATE` values. See the InviteCodeCreate.OnConflict
+// documentation for more info.
+func (u *InviteCodeUpsertOne) Update(set func(*InviteCodeUpsert)) *InviteCodeUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
+ set(&InviteCodeUpsert{UpdateSet: update})
+ }))
+ return u
+}
+
+// SetAdminID sets the "admin_id" field.
+func (u *InviteCodeUpsertOne) SetAdminID(v uuid.UUID) *InviteCodeUpsertOne {
+ return u.Update(func(s *InviteCodeUpsert) {
+ s.SetAdminID(v)
+ })
+}
+
+// UpdateAdminID sets the "admin_id" field to the value that was provided on create.
+func (u *InviteCodeUpsertOne) UpdateAdminID() *InviteCodeUpsertOne {
+ return u.Update(func(s *InviteCodeUpsert) {
+ s.UpdateAdminID()
+ })
+}
+
+// SetCode sets the "code" field.
+func (u *InviteCodeUpsertOne) SetCode(v string) *InviteCodeUpsertOne {
+ return u.Update(func(s *InviteCodeUpsert) {
+ s.SetCode(v)
+ })
+}
+
+// UpdateCode sets the "code" field to the value that was provided on create.
+func (u *InviteCodeUpsertOne) UpdateCode() *InviteCodeUpsertOne {
+ return u.Update(func(s *InviteCodeUpsert) {
+ s.UpdateCode()
+ })
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (u *InviteCodeUpsertOne) SetCreatedAt(v time.Time) *InviteCodeUpsertOne {
+ return u.Update(func(s *InviteCodeUpsert) {
+ s.SetCreatedAt(v)
+ })
+}
+
+// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
+func (u *InviteCodeUpsertOne) UpdateCreatedAt() *InviteCodeUpsertOne {
+ return u.Update(func(s *InviteCodeUpsert) {
+ s.UpdateCreatedAt()
+ })
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (u *InviteCodeUpsertOne) SetUpdatedAt(v time.Time) *InviteCodeUpsertOne {
+ return u.Update(func(s *InviteCodeUpsert) {
+ s.SetUpdatedAt(v)
+ })
+}
+
+// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
+func (u *InviteCodeUpsertOne) UpdateUpdatedAt() *InviteCodeUpsertOne {
+ return u.Update(func(s *InviteCodeUpsert) {
+ s.UpdateUpdatedAt()
+ })
+}
+
+// Exec executes the query.
+func (u *InviteCodeUpsertOne) Exec(ctx context.Context) error {
+ if len(u.create.conflict) == 0 {
+ return errors.New("db: missing options for InviteCodeCreate.OnConflict")
+ }
+ return u.create.Exec(ctx)
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (u *InviteCodeUpsertOne) ExecX(ctx context.Context) {
+ if err := u.create.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// Exec executes the UPSERT query and returns the inserted/updated ID.
+func (u *InviteCodeUpsertOne) ID(ctx context.Context) (id uuid.UUID, err error) {
+ if u.create.driver.Dialect() == dialect.MySQL {
+ // In case of "ON CONFLICT", there is no way to get back non-numeric ID
+ // fields from the database since MySQL does not support the RETURNING clause.
+ return id, errors.New("db: InviteCodeUpsertOne.ID is not supported by MySQL driver. Use InviteCodeUpsertOne.Exec instead")
+ }
+ node, err := u.create.Save(ctx)
+ if err != nil {
+ return id, err
+ }
+ return node.ID, nil
+}
+
+// IDX is like ID, but panics if an error occurs.
+func (u *InviteCodeUpsertOne) IDX(ctx context.Context) uuid.UUID {
+ id, err := u.ID(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return id
+}
+
+// InviteCodeCreateBulk is the builder for creating many InviteCode entities in bulk.
+type InviteCodeCreateBulk struct {
+ config
+ err error
+ builders []*InviteCodeCreate
+ conflict []sql.ConflictOption
+}
+
+// Save creates the InviteCode entities in the database.
+func (iccb *InviteCodeCreateBulk) Save(ctx context.Context) ([]*InviteCode, error) {
+ if iccb.err != nil {
+ return nil, iccb.err
+ }
+ specs := make([]*sqlgraph.CreateSpec, len(iccb.builders))
+ nodes := make([]*InviteCode, len(iccb.builders))
+ mutators := make([]Mutator, len(iccb.builders))
+ for i := range iccb.builders {
+ func(i int, root context.Context) {
+ builder := iccb.builders[i]
+ builder.defaults()
+ var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
+ mutation, ok := m.(*InviteCodeMutation)
+ if !ok {
+ return nil, fmt.Errorf("unexpected mutation type %T", m)
+ }
+ if err := builder.check(); err != nil {
+ return nil, err
+ }
+ builder.mutation = mutation
+ var err error
+ nodes[i], specs[i] = builder.createSpec()
+ if i < len(mutators)-1 {
+ _, err = mutators[i+1].Mutate(root, iccb.builders[i+1].mutation)
+ } else {
+ spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
+ spec.OnConflict = iccb.conflict
+ // Invoke the actual operation on the latest mutation in the chain.
+ if err = sqlgraph.BatchCreate(ctx, iccb.driver, spec); err != nil {
+ if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ }
+ }
+ if err != nil {
+ return nil, err
+ }
+ mutation.id = &nodes[i].ID
+ mutation.done = true
+ return nodes[i], nil
+ })
+ for i := len(builder.hooks) - 1; i >= 0; i-- {
+ mut = builder.hooks[i](mut)
+ }
+ mutators[i] = mut
+ }(i, ctx)
+ }
+ if len(mutators) > 0 {
+ if _, err := mutators[0].Mutate(ctx, iccb.builders[0].mutation); err != nil {
+ return nil, err
+ }
+ }
+ return nodes, nil
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (iccb *InviteCodeCreateBulk) SaveX(ctx context.Context) []*InviteCode {
+ v, err := iccb.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return v
+}
+
+// Exec executes the query.
+func (iccb *InviteCodeCreateBulk) Exec(ctx context.Context) error {
+ _, err := iccb.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (iccb *InviteCodeCreateBulk) ExecX(ctx context.Context) {
+ if err := iccb.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
+// of the `INSERT` statement. For example:
+//
+// client.InviteCode.CreateBulk(builders...).
+// OnConflict(
+// // Update the row with the new values
+// // the was proposed for insertion.
+// sql.ResolveWithNewValues(),
+// ).
+// // Override some of the fields with custom
+// // update values.
+// Update(func(u *ent.InviteCodeUpsert) {
+// SetAdminID(v+v).
+// }).
+// Exec(ctx)
+func (iccb *InviteCodeCreateBulk) OnConflict(opts ...sql.ConflictOption) *InviteCodeUpsertBulk {
+ iccb.conflict = opts
+ return &InviteCodeUpsertBulk{
+ create: iccb,
+ }
+}
+
+// OnConflictColumns calls `OnConflict` and configures the columns
+// as conflict target. Using this option is equivalent to using:
+//
+// client.InviteCode.Create().
+// OnConflict(sql.ConflictColumns(columns...)).
+// Exec(ctx)
+func (iccb *InviteCodeCreateBulk) OnConflictColumns(columns ...string) *InviteCodeUpsertBulk {
+ iccb.conflict = append(iccb.conflict, sql.ConflictColumns(columns...))
+ return &InviteCodeUpsertBulk{
+ create: iccb,
+ }
+}
+
+// InviteCodeUpsertBulk is the builder for "upsert"-ing
+// a bulk of InviteCode nodes.
+type InviteCodeUpsertBulk struct {
+ create *InviteCodeCreateBulk
+}
+
+// UpdateNewValues updates the mutable fields using the new values that
+// were set on create. Using this option is equivalent to using:
+//
+// client.InviteCode.Create().
+// OnConflict(
+// sql.ResolveWithNewValues(),
+// sql.ResolveWith(func(u *sql.UpdateSet) {
+// u.SetIgnore(invitecode.FieldID)
+// }),
+// ).
+// Exec(ctx)
+func (u *InviteCodeUpsertBulk) UpdateNewValues() *InviteCodeUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
+ for _, b := range u.create.builders {
+ if _, exists := b.mutation.ID(); exists {
+ s.SetIgnore(invitecode.FieldID)
+ }
+ }
+ }))
+ return u
+}
+
+// Ignore sets each column to itself in case of conflict.
+// Using this option is equivalent to using:
+//
+// client.InviteCode.Create().
+// OnConflict(sql.ResolveWithIgnore()).
+// Exec(ctx)
+func (u *InviteCodeUpsertBulk) Ignore() *InviteCodeUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
+ return u
+}
+
+// DoNothing configures the conflict_action to `DO NOTHING`.
+// Supported only by SQLite and PostgreSQL.
+func (u *InviteCodeUpsertBulk) DoNothing() *InviteCodeUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.DoNothing())
+ return u
+}
+
+// Update allows overriding fields `UPDATE` values. See the InviteCodeCreateBulk.OnConflict
+// documentation for more info.
+func (u *InviteCodeUpsertBulk) Update(set func(*InviteCodeUpsert)) *InviteCodeUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
+ set(&InviteCodeUpsert{UpdateSet: update})
+ }))
+ return u
+}
+
+// SetAdminID sets the "admin_id" field.
+func (u *InviteCodeUpsertBulk) SetAdminID(v uuid.UUID) *InviteCodeUpsertBulk {
+ return u.Update(func(s *InviteCodeUpsert) {
+ s.SetAdminID(v)
+ })
+}
+
+// UpdateAdminID sets the "admin_id" field to the value that was provided on create.
+func (u *InviteCodeUpsertBulk) UpdateAdminID() *InviteCodeUpsertBulk {
+ return u.Update(func(s *InviteCodeUpsert) {
+ s.UpdateAdminID()
+ })
+}
+
+// SetCode sets the "code" field.
+func (u *InviteCodeUpsertBulk) SetCode(v string) *InviteCodeUpsertBulk {
+ return u.Update(func(s *InviteCodeUpsert) {
+ s.SetCode(v)
+ })
+}
+
+// UpdateCode sets the "code" field to the value that was provided on create.
+func (u *InviteCodeUpsertBulk) UpdateCode() *InviteCodeUpsertBulk {
+ return u.Update(func(s *InviteCodeUpsert) {
+ s.UpdateCode()
+ })
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (u *InviteCodeUpsertBulk) SetCreatedAt(v time.Time) *InviteCodeUpsertBulk {
+ return u.Update(func(s *InviteCodeUpsert) {
+ s.SetCreatedAt(v)
+ })
+}
+
+// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
+func (u *InviteCodeUpsertBulk) UpdateCreatedAt() *InviteCodeUpsertBulk {
+ return u.Update(func(s *InviteCodeUpsert) {
+ s.UpdateCreatedAt()
+ })
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (u *InviteCodeUpsertBulk) SetUpdatedAt(v time.Time) *InviteCodeUpsertBulk {
+ return u.Update(func(s *InviteCodeUpsert) {
+ s.SetUpdatedAt(v)
+ })
+}
+
+// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
+func (u *InviteCodeUpsertBulk) UpdateUpdatedAt() *InviteCodeUpsertBulk {
+ return u.Update(func(s *InviteCodeUpsert) {
+ s.UpdateUpdatedAt()
+ })
+}
+
+// Exec executes the query.
+func (u *InviteCodeUpsertBulk) Exec(ctx context.Context) error {
+ if u.create.err != nil {
+ return u.create.err
+ }
+ for i, b := range u.create.builders {
+ if len(b.conflict) != 0 {
+ return fmt.Errorf("db: OnConflict was set for builder %d. Set it on the InviteCodeCreateBulk instead", i)
+ }
+ }
+ if len(u.create.conflict) == 0 {
+ return errors.New("db: missing options for InviteCodeCreateBulk.OnConflict")
+ }
+ return u.create.Exec(ctx)
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (u *InviteCodeUpsertBulk) ExecX(ctx context.Context) {
+ if err := u.create.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
diff --git a/backend/db/invitecode_delete.go b/backend/db/invitecode_delete.go
new file mode 100644
index 0000000..2e68319
--- /dev/null
+++ b/backend/db/invitecode_delete.go
@@ -0,0 +1,88 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/invitecode"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+)
+
+// InviteCodeDelete is the builder for deleting a InviteCode entity.
+type InviteCodeDelete struct {
+ config
+ hooks []Hook
+ mutation *InviteCodeMutation
+}
+
+// Where appends a list predicates to the InviteCodeDelete builder.
+func (icd *InviteCodeDelete) Where(ps ...predicate.InviteCode) *InviteCodeDelete {
+ icd.mutation.Where(ps...)
+ return icd
+}
+
+// Exec executes the deletion query and returns how many vertices were deleted.
+func (icd *InviteCodeDelete) Exec(ctx context.Context) (int, error) {
+ return withHooks(ctx, icd.sqlExec, icd.mutation, icd.hooks)
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (icd *InviteCodeDelete) ExecX(ctx context.Context) int {
+ n, err := icd.Exec(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return n
+}
+
+func (icd *InviteCodeDelete) sqlExec(ctx context.Context) (int, error) {
+ _spec := sqlgraph.NewDeleteSpec(invitecode.Table, sqlgraph.NewFieldSpec(invitecode.FieldID, field.TypeUUID))
+ if ps := icd.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ affected, err := sqlgraph.DeleteNodes(ctx, icd.driver, _spec)
+ if err != nil && sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ icd.mutation.done = true
+ return affected, err
+}
+
+// InviteCodeDeleteOne is the builder for deleting a single InviteCode entity.
+type InviteCodeDeleteOne struct {
+ icd *InviteCodeDelete
+}
+
+// Where appends a list predicates to the InviteCodeDelete builder.
+func (icdo *InviteCodeDeleteOne) Where(ps ...predicate.InviteCode) *InviteCodeDeleteOne {
+ icdo.icd.mutation.Where(ps...)
+ return icdo
+}
+
+// Exec executes the deletion query.
+func (icdo *InviteCodeDeleteOne) Exec(ctx context.Context) error {
+ n, err := icdo.icd.Exec(ctx)
+ switch {
+ case err != nil:
+ return err
+ case n == 0:
+ return &NotFoundError{invitecode.Label}
+ default:
+ return nil
+ }
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (icdo *InviteCodeDeleteOne) ExecX(ctx context.Context) {
+ if err := icdo.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
diff --git a/backend/db/invitecode_query.go b/backend/db/invitecode_query.go
new file mode 100644
index 0000000..2494005
--- /dev/null
+++ b/backend/db/invitecode_query.go
@@ -0,0 +1,578 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "fmt"
+ "math"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect"
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/invitecode"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+ "github.com/google/uuid"
+)
+
+// InviteCodeQuery is the builder for querying InviteCode entities.
+type InviteCodeQuery struct {
+ config
+ ctx *QueryContext
+ order []invitecode.OrderOption
+ inters []Interceptor
+ predicates []predicate.InviteCode
+ modifiers []func(*sql.Selector)
+ // intermediate query (i.e. traversal path).
+ sql *sql.Selector
+ path func(context.Context) (*sql.Selector, error)
+}
+
+// Where adds a new predicate for the InviteCodeQuery builder.
+func (icq *InviteCodeQuery) Where(ps ...predicate.InviteCode) *InviteCodeQuery {
+ icq.predicates = append(icq.predicates, ps...)
+ return icq
+}
+
+// Limit the number of records to be returned by this query.
+func (icq *InviteCodeQuery) Limit(limit int) *InviteCodeQuery {
+ icq.ctx.Limit = &limit
+ return icq
+}
+
+// Offset to start from.
+func (icq *InviteCodeQuery) Offset(offset int) *InviteCodeQuery {
+ icq.ctx.Offset = &offset
+ return icq
+}
+
+// Unique configures the query builder to filter duplicate records on query.
+// By default, unique is set to true, and can be disabled using this method.
+func (icq *InviteCodeQuery) Unique(unique bool) *InviteCodeQuery {
+ icq.ctx.Unique = &unique
+ return icq
+}
+
+// Order specifies how the records should be ordered.
+func (icq *InviteCodeQuery) Order(o ...invitecode.OrderOption) *InviteCodeQuery {
+ icq.order = append(icq.order, o...)
+ return icq
+}
+
+// First returns the first InviteCode entity from the query.
+// Returns a *NotFoundError when no InviteCode was found.
+func (icq *InviteCodeQuery) First(ctx context.Context) (*InviteCode, error) {
+ nodes, err := icq.Limit(1).All(setContextOp(ctx, icq.ctx, ent.OpQueryFirst))
+ if err != nil {
+ return nil, err
+ }
+ if len(nodes) == 0 {
+ return nil, &NotFoundError{invitecode.Label}
+ }
+ return nodes[0], nil
+}
+
+// FirstX is like First, but panics if an error occurs.
+func (icq *InviteCodeQuery) FirstX(ctx context.Context) *InviteCode {
+ node, err := icq.First(ctx)
+ if err != nil && !IsNotFound(err) {
+ panic(err)
+ }
+ return node
+}
+
+// FirstID returns the first InviteCode ID from the query.
+// Returns a *NotFoundError when no InviteCode ID was found.
+func (icq *InviteCodeQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
+ var ids []uuid.UUID
+ if ids, err = icq.Limit(1).IDs(setContextOp(ctx, icq.ctx, ent.OpQueryFirstID)); err != nil {
+ return
+ }
+ if len(ids) == 0 {
+ err = &NotFoundError{invitecode.Label}
+ return
+ }
+ return ids[0], nil
+}
+
+// FirstIDX is like FirstID, but panics if an error occurs.
+func (icq *InviteCodeQuery) FirstIDX(ctx context.Context) uuid.UUID {
+ id, err := icq.FirstID(ctx)
+ if err != nil && !IsNotFound(err) {
+ panic(err)
+ }
+ return id
+}
+
+// Only returns a single InviteCode entity found by the query, ensuring it only returns one.
+// Returns a *NotSingularError when more than one InviteCode entity is found.
+// Returns a *NotFoundError when no InviteCode entities are found.
+func (icq *InviteCodeQuery) Only(ctx context.Context) (*InviteCode, error) {
+ nodes, err := icq.Limit(2).All(setContextOp(ctx, icq.ctx, ent.OpQueryOnly))
+ if err != nil {
+ return nil, err
+ }
+ switch len(nodes) {
+ case 1:
+ return nodes[0], nil
+ case 0:
+ return nil, &NotFoundError{invitecode.Label}
+ default:
+ return nil, &NotSingularError{invitecode.Label}
+ }
+}
+
+// OnlyX is like Only, but panics if an error occurs.
+func (icq *InviteCodeQuery) OnlyX(ctx context.Context) *InviteCode {
+ node, err := icq.Only(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return node
+}
+
+// OnlyID is like Only, but returns the only InviteCode ID in the query.
+// Returns a *NotSingularError when more than one InviteCode ID is found.
+// Returns a *NotFoundError when no entities are found.
+func (icq *InviteCodeQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
+ var ids []uuid.UUID
+ if ids, err = icq.Limit(2).IDs(setContextOp(ctx, icq.ctx, ent.OpQueryOnlyID)); err != nil {
+ return
+ }
+ switch len(ids) {
+ case 1:
+ id = ids[0]
+ case 0:
+ err = &NotFoundError{invitecode.Label}
+ default:
+ err = &NotSingularError{invitecode.Label}
+ }
+ return
+}
+
+// OnlyIDX is like OnlyID, but panics if an error occurs.
+func (icq *InviteCodeQuery) OnlyIDX(ctx context.Context) uuid.UUID {
+ id, err := icq.OnlyID(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return id
+}
+
+// All executes the query and returns a list of InviteCodes.
+func (icq *InviteCodeQuery) All(ctx context.Context) ([]*InviteCode, error) {
+ ctx = setContextOp(ctx, icq.ctx, ent.OpQueryAll)
+ if err := icq.prepareQuery(ctx); err != nil {
+ return nil, err
+ }
+ qr := querierAll[[]*InviteCode, *InviteCodeQuery]()
+ return withInterceptors[[]*InviteCode](ctx, icq, qr, icq.inters)
+}
+
+// AllX is like All, but panics if an error occurs.
+func (icq *InviteCodeQuery) AllX(ctx context.Context) []*InviteCode {
+ nodes, err := icq.All(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return nodes
+}
+
+// IDs executes the query and returns a list of InviteCode IDs.
+func (icq *InviteCodeQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) {
+ if icq.ctx.Unique == nil && icq.path != nil {
+ icq.Unique(true)
+ }
+ ctx = setContextOp(ctx, icq.ctx, ent.OpQueryIDs)
+ if err = icq.Select(invitecode.FieldID).Scan(ctx, &ids); err != nil {
+ return nil, err
+ }
+ return ids, nil
+}
+
+// IDsX is like IDs, but panics if an error occurs.
+func (icq *InviteCodeQuery) IDsX(ctx context.Context) []uuid.UUID {
+ ids, err := icq.IDs(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return ids
+}
+
+// Count returns the count of the given query.
+func (icq *InviteCodeQuery) Count(ctx context.Context) (int, error) {
+ ctx = setContextOp(ctx, icq.ctx, ent.OpQueryCount)
+ if err := icq.prepareQuery(ctx); err != nil {
+ return 0, err
+ }
+ return withInterceptors[int](ctx, icq, querierCount[*InviteCodeQuery](), icq.inters)
+}
+
+// CountX is like Count, but panics if an error occurs.
+func (icq *InviteCodeQuery) CountX(ctx context.Context) int {
+ count, err := icq.Count(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return count
+}
+
+// Exist returns true if the query has elements in the graph.
+func (icq *InviteCodeQuery) Exist(ctx context.Context) (bool, error) {
+ ctx = setContextOp(ctx, icq.ctx, ent.OpQueryExist)
+ switch _, err := icq.FirstID(ctx); {
+ case IsNotFound(err):
+ return false, nil
+ case err != nil:
+ return false, fmt.Errorf("db: check existence: %w", err)
+ default:
+ return true, nil
+ }
+}
+
+// ExistX is like Exist, but panics if an error occurs.
+func (icq *InviteCodeQuery) ExistX(ctx context.Context) bool {
+ exist, err := icq.Exist(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return exist
+}
+
+// Clone returns a duplicate of the InviteCodeQuery builder, including all associated steps. It can be
+// used to prepare common query builders and use them differently after the clone is made.
+func (icq *InviteCodeQuery) Clone() *InviteCodeQuery {
+ if icq == nil {
+ return nil
+ }
+ return &InviteCodeQuery{
+ config: icq.config,
+ ctx: icq.ctx.Clone(),
+ order: append([]invitecode.OrderOption{}, icq.order...),
+ inters: append([]Interceptor{}, icq.inters...),
+ predicates: append([]predicate.InviteCode{}, icq.predicates...),
+ // clone intermediate query.
+ sql: icq.sql.Clone(),
+ path: icq.path,
+ modifiers: append([]func(*sql.Selector){}, icq.modifiers...),
+ }
+}
+
+// GroupBy is used to group vertices by one or more fields/columns.
+// It is often used with aggregate functions, like: count, max, mean, min, sum.
+//
+// Example:
+//
+// var v []struct {
+// AdminID uuid.UUID `json:"admin_id,omitempty"`
+// Count int `json:"count,omitempty"`
+// }
+//
+// client.InviteCode.Query().
+// GroupBy(invitecode.FieldAdminID).
+// Aggregate(db.Count()).
+// Scan(ctx, &v)
+func (icq *InviteCodeQuery) GroupBy(field string, fields ...string) *InviteCodeGroupBy {
+ icq.ctx.Fields = append([]string{field}, fields...)
+ grbuild := &InviteCodeGroupBy{build: icq}
+ grbuild.flds = &icq.ctx.Fields
+ grbuild.label = invitecode.Label
+ grbuild.scan = grbuild.Scan
+ return grbuild
+}
+
+// Select allows the selection one or more fields/columns for the given query,
+// instead of selecting all fields in the entity.
+//
+// Example:
+//
+// var v []struct {
+// AdminID uuid.UUID `json:"admin_id,omitempty"`
+// }
+//
+// client.InviteCode.Query().
+// Select(invitecode.FieldAdminID).
+// Scan(ctx, &v)
+func (icq *InviteCodeQuery) Select(fields ...string) *InviteCodeSelect {
+ icq.ctx.Fields = append(icq.ctx.Fields, fields...)
+ sbuild := &InviteCodeSelect{InviteCodeQuery: icq}
+ sbuild.label = invitecode.Label
+ sbuild.flds, sbuild.scan = &icq.ctx.Fields, sbuild.Scan
+ return sbuild
+}
+
+// Aggregate returns a InviteCodeSelect configured with the given aggregations.
+func (icq *InviteCodeQuery) Aggregate(fns ...AggregateFunc) *InviteCodeSelect {
+ return icq.Select().Aggregate(fns...)
+}
+
+func (icq *InviteCodeQuery) prepareQuery(ctx context.Context) error {
+ for _, inter := range icq.inters {
+ if inter == nil {
+ return fmt.Errorf("db: uninitialized interceptor (forgotten import db/runtime?)")
+ }
+ if trv, ok := inter.(Traverser); ok {
+ if err := trv.Traverse(ctx, icq); err != nil {
+ return err
+ }
+ }
+ }
+ for _, f := range icq.ctx.Fields {
+ if !invitecode.ValidColumn(f) {
+ return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
+ }
+ }
+ if icq.path != nil {
+ prev, err := icq.path(ctx)
+ if err != nil {
+ return err
+ }
+ icq.sql = prev
+ }
+ return nil
+}
+
+func (icq *InviteCodeQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*InviteCode, error) {
+ var (
+ nodes = []*InviteCode{}
+ _spec = icq.querySpec()
+ )
+ _spec.ScanValues = func(columns []string) ([]any, error) {
+ return (*InviteCode).scanValues(nil, columns)
+ }
+ _spec.Assign = func(columns []string, values []any) error {
+ node := &InviteCode{config: icq.config}
+ nodes = append(nodes, node)
+ return node.assignValues(columns, values)
+ }
+ if len(icq.modifiers) > 0 {
+ _spec.Modifiers = icq.modifiers
+ }
+ for i := range hooks {
+ hooks[i](ctx, _spec)
+ }
+ if err := sqlgraph.QueryNodes(ctx, icq.driver, _spec); err != nil {
+ return nil, err
+ }
+ if len(nodes) == 0 {
+ return nodes, nil
+ }
+ return nodes, nil
+}
+
+func (icq *InviteCodeQuery) sqlCount(ctx context.Context) (int, error) {
+ _spec := icq.querySpec()
+ if len(icq.modifiers) > 0 {
+ _spec.Modifiers = icq.modifiers
+ }
+ _spec.Node.Columns = icq.ctx.Fields
+ if len(icq.ctx.Fields) > 0 {
+ _spec.Unique = icq.ctx.Unique != nil && *icq.ctx.Unique
+ }
+ return sqlgraph.CountNodes(ctx, icq.driver, _spec)
+}
+
+func (icq *InviteCodeQuery) querySpec() *sqlgraph.QuerySpec {
+ _spec := sqlgraph.NewQuerySpec(invitecode.Table, invitecode.Columns, sqlgraph.NewFieldSpec(invitecode.FieldID, field.TypeUUID))
+ _spec.From = icq.sql
+ if unique := icq.ctx.Unique; unique != nil {
+ _spec.Unique = *unique
+ } else if icq.path != nil {
+ _spec.Unique = true
+ }
+ if fields := icq.ctx.Fields; len(fields) > 0 {
+ _spec.Node.Columns = make([]string, 0, len(fields))
+ _spec.Node.Columns = append(_spec.Node.Columns, invitecode.FieldID)
+ for i := range fields {
+ if fields[i] != invitecode.FieldID {
+ _spec.Node.Columns = append(_spec.Node.Columns, fields[i])
+ }
+ }
+ }
+ if ps := icq.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if limit := icq.ctx.Limit; limit != nil {
+ _spec.Limit = *limit
+ }
+ if offset := icq.ctx.Offset; offset != nil {
+ _spec.Offset = *offset
+ }
+ if ps := icq.order; len(ps) > 0 {
+ _spec.Order = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ return _spec
+}
+
+func (icq *InviteCodeQuery) sqlQuery(ctx context.Context) *sql.Selector {
+ builder := sql.Dialect(icq.driver.Dialect())
+ t1 := builder.Table(invitecode.Table)
+ columns := icq.ctx.Fields
+ if len(columns) == 0 {
+ columns = invitecode.Columns
+ }
+ selector := builder.Select(t1.Columns(columns...)...).From(t1)
+ if icq.sql != nil {
+ selector = icq.sql
+ selector.Select(selector.Columns(columns...)...)
+ }
+ if icq.ctx.Unique != nil && *icq.ctx.Unique {
+ selector.Distinct()
+ }
+ for _, m := range icq.modifiers {
+ m(selector)
+ }
+ for _, p := range icq.predicates {
+ p(selector)
+ }
+ for _, p := range icq.order {
+ p(selector)
+ }
+ if offset := icq.ctx.Offset; offset != nil {
+ // limit is mandatory for offset clause. We start
+ // with default value, and override it below if needed.
+ selector.Offset(*offset).Limit(math.MaxInt32)
+ }
+ if limit := icq.ctx.Limit; limit != nil {
+ selector.Limit(*limit)
+ }
+ return selector
+}
+
+// ForUpdate locks the selected rows against concurrent updates, and prevent them from being
+// updated, deleted or "selected ... for update" by other sessions, until the transaction is
+// either committed or rolled-back.
+func (icq *InviteCodeQuery) ForUpdate(opts ...sql.LockOption) *InviteCodeQuery {
+ if icq.driver.Dialect() == dialect.Postgres {
+ icq.Unique(false)
+ }
+ icq.modifiers = append(icq.modifiers, func(s *sql.Selector) {
+ s.ForUpdate(opts...)
+ })
+ return icq
+}
+
+// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock
+// on any rows that are read. Other sessions can read the rows, but cannot modify them
+// until your transaction commits.
+func (icq *InviteCodeQuery) ForShare(opts ...sql.LockOption) *InviteCodeQuery {
+ if icq.driver.Dialect() == dialect.Postgres {
+ icq.Unique(false)
+ }
+ icq.modifiers = append(icq.modifiers, func(s *sql.Selector) {
+ s.ForShare(opts...)
+ })
+ return icq
+}
+
+// Modify adds a query modifier for attaching custom logic to queries.
+func (icq *InviteCodeQuery) Modify(modifiers ...func(s *sql.Selector)) *InviteCodeSelect {
+ icq.modifiers = append(icq.modifiers, modifiers...)
+ return icq.Select()
+}
+
+// InviteCodeGroupBy is the group-by builder for InviteCode entities.
+type InviteCodeGroupBy struct {
+ selector
+ build *InviteCodeQuery
+}
+
+// Aggregate adds the given aggregation functions to the group-by query.
+func (icgb *InviteCodeGroupBy) Aggregate(fns ...AggregateFunc) *InviteCodeGroupBy {
+ icgb.fns = append(icgb.fns, fns...)
+ return icgb
+}
+
+// Scan applies the selector query and scans the result into the given value.
+func (icgb *InviteCodeGroupBy) Scan(ctx context.Context, v any) error {
+ ctx = setContextOp(ctx, icgb.build.ctx, ent.OpQueryGroupBy)
+ if err := icgb.build.prepareQuery(ctx); err != nil {
+ return err
+ }
+ return scanWithInterceptors[*InviteCodeQuery, *InviteCodeGroupBy](ctx, icgb.build, icgb, icgb.build.inters, v)
+}
+
+func (icgb *InviteCodeGroupBy) sqlScan(ctx context.Context, root *InviteCodeQuery, v any) error {
+ selector := root.sqlQuery(ctx).Select()
+ aggregation := make([]string, 0, len(icgb.fns))
+ for _, fn := range icgb.fns {
+ aggregation = append(aggregation, fn(selector))
+ }
+ if len(selector.SelectedColumns()) == 0 {
+ columns := make([]string, 0, len(*icgb.flds)+len(icgb.fns))
+ for _, f := range *icgb.flds {
+ columns = append(columns, selector.C(f))
+ }
+ columns = append(columns, aggregation...)
+ selector.Select(columns...)
+ }
+ selector.GroupBy(selector.Columns(*icgb.flds...)...)
+ if err := selector.Err(); err != nil {
+ return err
+ }
+ rows := &sql.Rows{}
+ query, args := selector.Query()
+ if err := icgb.build.driver.Query(ctx, query, args, rows); err != nil {
+ return err
+ }
+ defer rows.Close()
+ return sql.ScanSlice(rows, v)
+}
+
+// InviteCodeSelect is the builder for selecting fields of InviteCode entities.
+type InviteCodeSelect struct {
+ *InviteCodeQuery
+ selector
+}
+
+// Aggregate adds the given aggregation functions to the selector query.
+func (ics *InviteCodeSelect) Aggregate(fns ...AggregateFunc) *InviteCodeSelect {
+ ics.fns = append(ics.fns, fns...)
+ return ics
+}
+
+// Scan applies the selector query and scans the result into the given value.
+func (ics *InviteCodeSelect) Scan(ctx context.Context, v any) error {
+ ctx = setContextOp(ctx, ics.ctx, ent.OpQuerySelect)
+ if err := ics.prepareQuery(ctx); err != nil {
+ return err
+ }
+ return scanWithInterceptors[*InviteCodeQuery, *InviteCodeSelect](ctx, ics.InviteCodeQuery, ics, ics.inters, v)
+}
+
+func (ics *InviteCodeSelect) sqlScan(ctx context.Context, root *InviteCodeQuery, v any) error {
+ selector := root.sqlQuery(ctx)
+ aggregation := make([]string, 0, len(ics.fns))
+ for _, fn := range ics.fns {
+ aggregation = append(aggregation, fn(selector))
+ }
+ switch n := len(*ics.selector.flds); {
+ case n == 0 && len(aggregation) > 0:
+ selector.Select(aggregation...)
+ case n != 0 && len(aggregation) > 0:
+ selector.AppendSelect(aggregation...)
+ }
+ rows := &sql.Rows{}
+ query, args := selector.Query()
+ if err := ics.driver.Query(ctx, query, args, rows); err != nil {
+ return err
+ }
+ defer rows.Close()
+ return sql.ScanSlice(rows, v)
+}
+
+// Modify adds a query modifier for attaching custom logic to queries.
+func (ics *InviteCodeSelect) Modify(modifiers ...func(s *sql.Selector)) *InviteCodeSelect {
+ ics.modifiers = append(ics.modifiers, modifiers...)
+ return ics
+}
diff --git a/backend/db/invitecode_update.go b/backend/db/invitecode_update.go
new file mode 100644
index 0000000..6862245
--- /dev/null
+++ b/backend/db/invitecode_update.go
@@ -0,0 +1,331 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "time"
+
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/invitecode"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+ "github.com/google/uuid"
+)
+
+// InviteCodeUpdate is the builder for updating InviteCode entities.
+type InviteCodeUpdate struct {
+ config
+ hooks []Hook
+ mutation *InviteCodeMutation
+ modifiers []func(*sql.UpdateBuilder)
+}
+
+// Where appends a list predicates to the InviteCodeUpdate builder.
+func (icu *InviteCodeUpdate) Where(ps ...predicate.InviteCode) *InviteCodeUpdate {
+ icu.mutation.Where(ps...)
+ return icu
+}
+
+// SetAdminID sets the "admin_id" field.
+func (icu *InviteCodeUpdate) SetAdminID(u uuid.UUID) *InviteCodeUpdate {
+ icu.mutation.SetAdminID(u)
+ return icu
+}
+
+// SetNillableAdminID sets the "admin_id" field if the given value is not nil.
+func (icu *InviteCodeUpdate) SetNillableAdminID(u *uuid.UUID) *InviteCodeUpdate {
+ if u != nil {
+ icu.SetAdminID(*u)
+ }
+ return icu
+}
+
+// SetCode sets the "code" field.
+func (icu *InviteCodeUpdate) SetCode(s string) *InviteCodeUpdate {
+ icu.mutation.SetCode(s)
+ return icu
+}
+
+// SetNillableCode sets the "code" field if the given value is not nil.
+func (icu *InviteCodeUpdate) SetNillableCode(s *string) *InviteCodeUpdate {
+ if s != nil {
+ icu.SetCode(*s)
+ }
+ return icu
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (icu *InviteCodeUpdate) SetCreatedAt(t time.Time) *InviteCodeUpdate {
+ icu.mutation.SetCreatedAt(t)
+ return icu
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (icu *InviteCodeUpdate) SetNillableCreatedAt(t *time.Time) *InviteCodeUpdate {
+ if t != nil {
+ icu.SetCreatedAt(*t)
+ }
+ return icu
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (icu *InviteCodeUpdate) SetUpdatedAt(t time.Time) *InviteCodeUpdate {
+ icu.mutation.SetUpdatedAt(t)
+ return icu
+}
+
+// Mutation returns the InviteCodeMutation object of the builder.
+func (icu *InviteCodeUpdate) Mutation() *InviteCodeMutation {
+ return icu.mutation
+}
+
+// Save executes the query and returns the number of nodes affected by the update operation.
+func (icu *InviteCodeUpdate) Save(ctx context.Context) (int, error) {
+ icu.defaults()
+ return withHooks(ctx, icu.sqlSave, icu.mutation, icu.hooks)
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (icu *InviteCodeUpdate) SaveX(ctx context.Context) int {
+ affected, err := icu.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return affected
+}
+
+// Exec executes the query.
+func (icu *InviteCodeUpdate) Exec(ctx context.Context) error {
+ _, err := icu.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (icu *InviteCodeUpdate) ExecX(ctx context.Context) {
+ if err := icu.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// defaults sets the default values of the builder before save.
+func (icu *InviteCodeUpdate) defaults() {
+ if _, ok := icu.mutation.UpdatedAt(); !ok {
+ v := invitecode.UpdateDefaultUpdatedAt()
+ icu.mutation.SetUpdatedAt(v)
+ }
+}
+
+// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
+func (icu *InviteCodeUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *InviteCodeUpdate {
+ icu.modifiers = append(icu.modifiers, modifiers...)
+ return icu
+}
+
+func (icu *InviteCodeUpdate) sqlSave(ctx context.Context) (n int, err error) {
+ _spec := sqlgraph.NewUpdateSpec(invitecode.Table, invitecode.Columns, sqlgraph.NewFieldSpec(invitecode.FieldID, field.TypeUUID))
+ if ps := icu.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if value, ok := icu.mutation.AdminID(); ok {
+ _spec.SetField(invitecode.FieldAdminID, field.TypeUUID, value)
+ }
+ if value, ok := icu.mutation.Code(); ok {
+ _spec.SetField(invitecode.FieldCode, field.TypeString, value)
+ }
+ if value, ok := icu.mutation.CreatedAt(); ok {
+ _spec.SetField(invitecode.FieldCreatedAt, field.TypeTime, value)
+ }
+ if value, ok := icu.mutation.UpdatedAt(); ok {
+ _spec.SetField(invitecode.FieldUpdatedAt, field.TypeTime, value)
+ }
+ _spec.AddModifiers(icu.modifiers...)
+ if n, err = sqlgraph.UpdateNodes(ctx, icu.driver, _spec); err != nil {
+ if _, ok := err.(*sqlgraph.NotFoundError); ok {
+ err = &NotFoundError{invitecode.Label}
+ } else if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return 0, err
+ }
+ icu.mutation.done = true
+ return n, nil
+}
+
+// InviteCodeUpdateOne is the builder for updating a single InviteCode entity.
+type InviteCodeUpdateOne struct {
+ config
+ fields []string
+ hooks []Hook
+ mutation *InviteCodeMutation
+ modifiers []func(*sql.UpdateBuilder)
+}
+
+// SetAdminID sets the "admin_id" field.
+func (icuo *InviteCodeUpdateOne) SetAdminID(u uuid.UUID) *InviteCodeUpdateOne {
+ icuo.mutation.SetAdminID(u)
+ return icuo
+}
+
+// SetNillableAdminID sets the "admin_id" field if the given value is not nil.
+func (icuo *InviteCodeUpdateOne) SetNillableAdminID(u *uuid.UUID) *InviteCodeUpdateOne {
+ if u != nil {
+ icuo.SetAdminID(*u)
+ }
+ return icuo
+}
+
+// SetCode sets the "code" field.
+func (icuo *InviteCodeUpdateOne) SetCode(s string) *InviteCodeUpdateOne {
+ icuo.mutation.SetCode(s)
+ return icuo
+}
+
+// SetNillableCode sets the "code" field if the given value is not nil.
+func (icuo *InviteCodeUpdateOne) SetNillableCode(s *string) *InviteCodeUpdateOne {
+ if s != nil {
+ icuo.SetCode(*s)
+ }
+ return icuo
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (icuo *InviteCodeUpdateOne) SetCreatedAt(t time.Time) *InviteCodeUpdateOne {
+ icuo.mutation.SetCreatedAt(t)
+ return icuo
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (icuo *InviteCodeUpdateOne) SetNillableCreatedAt(t *time.Time) *InviteCodeUpdateOne {
+ if t != nil {
+ icuo.SetCreatedAt(*t)
+ }
+ return icuo
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (icuo *InviteCodeUpdateOne) SetUpdatedAt(t time.Time) *InviteCodeUpdateOne {
+ icuo.mutation.SetUpdatedAt(t)
+ return icuo
+}
+
+// Mutation returns the InviteCodeMutation object of the builder.
+func (icuo *InviteCodeUpdateOne) Mutation() *InviteCodeMutation {
+ return icuo.mutation
+}
+
+// Where appends a list predicates to the InviteCodeUpdate builder.
+func (icuo *InviteCodeUpdateOne) Where(ps ...predicate.InviteCode) *InviteCodeUpdateOne {
+ icuo.mutation.Where(ps...)
+ return icuo
+}
+
+// Select allows selecting one or more fields (columns) of the returned entity.
+// The default is selecting all fields defined in the entity schema.
+func (icuo *InviteCodeUpdateOne) Select(field string, fields ...string) *InviteCodeUpdateOne {
+ icuo.fields = append([]string{field}, fields...)
+ return icuo
+}
+
+// Save executes the query and returns the updated InviteCode entity.
+func (icuo *InviteCodeUpdateOne) Save(ctx context.Context) (*InviteCode, error) {
+ icuo.defaults()
+ return withHooks(ctx, icuo.sqlSave, icuo.mutation, icuo.hooks)
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (icuo *InviteCodeUpdateOne) SaveX(ctx context.Context) *InviteCode {
+ node, err := icuo.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return node
+}
+
+// Exec executes the query on the entity.
+func (icuo *InviteCodeUpdateOne) Exec(ctx context.Context) error {
+ _, err := icuo.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (icuo *InviteCodeUpdateOne) ExecX(ctx context.Context) {
+ if err := icuo.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// defaults sets the default values of the builder before save.
+func (icuo *InviteCodeUpdateOne) defaults() {
+ if _, ok := icuo.mutation.UpdatedAt(); !ok {
+ v := invitecode.UpdateDefaultUpdatedAt()
+ icuo.mutation.SetUpdatedAt(v)
+ }
+}
+
+// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
+func (icuo *InviteCodeUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *InviteCodeUpdateOne {
+ icuo.modifiers = append(icuo.modifiers, modifiers...)
+ return icuo
+}
+
+func (icuo *InviteCodeUpdateOne) sqlSave(ctx context.Context) (_node *InviteCode, err error) {
+ _spec := sqlgraph.NewUpdateSpec(invitecode.Table, invitecode.Columns, sqlgraph.NewFieldSpec(invitecode.FieldID, field.TypeUUID))
+ id, ok := icuo.mutation.ID()
+ if !ok {
+ return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "InviteCode.id" for update`)}
+ }
+ _spec.Node.ID.Value = id
+ if fields := icuo.fields; len(fields) > 0 {
+ _spec.Node.Columns = make([]string, 0, len(fields))
+ _spec.Node.Columns = append(_spec.Node.Columns, invitecode.FieldID)
+ for _, f := range fields {
+ if !invitecode.ValidColumn(f) {
+ return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
+ }
+ if f != invitecode.FieldID {
+ _spec.Node.Columns = append(_spec.Node.Columns, f)
+ }
+ }
+ }
+ if ps := icuo.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if value, ok := icuo.mutation.AdminID(); ok {
+ _spec.SetField(invitecode.FieldAdminID, field.TypeUUID, value)
+ }
+ if value, ok := icuo.mutation.Code(); ok {
+ _spec.SetField(invitecode.FieldCode, field.TypeString, value)
+ }
+ if value, ok := icuo.mutation.CreatedAt(); ok {
+ _spec.SetField(invitecode.FieldCreatedAt, field.TypeTime, value)
+ }
+ if value, ok := icuo.mutation.UpdatedAt(); ok {
+ _spec.SetField(invitecode.FieldUpdatedAt, field.TypeTime, value)
+ }
+ _spec.AddModifiers(icuo.modifiers...)
+ _node = &InviteCode{config: icuo.config}
+ _spec.Assign = _node.assignValues
+ _spec.ScanValues = _node.scanValues
+ if err = sqlgraph.UpdateNode(ctx, icuo.driver, _spec); err != nil {
+ if _, ok := err.(*sqlgraph.NotFoundError); ok {
+ err = &NotFoundError{invitecode.Label}
+ } else if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return nil, err
+ }
+ icuo.mutation.done = true
+ return _node, nil
+}
diff --git a/backend/db/migrate/migrate.go b/backend/db/migrate/migrate.go
new file mode 100644
index 0000000..1956a6b
--- /dev/null
+++ b/backend/db/migrate/migrate.go
@@ -0,0 +1,64 @@
+// Code generated by ent, DO NOT EDIT.
+
+package migrate
+
+import (
+ "context"
+ "fmt"
+ "io"
+
+ "entgo.io/ent/dialect"
+ "entgo.io/ent/dialect/sql/schema"
+)
+
+var (
+ // WithGlobalUniqueID sets the universal ids options to the migration.
+ // If this option is enabled, ent migration will allocate a 1<<32 range
+ // for the ids of each entity (table).
+ // Note that this option cannot be applied on tables that already exist.
+ WithGlobalUniqueID = schema.WithGlobalUniqueID
+ // WithDropColumn sets the drop column option to the migration.
+ // If this option is enabled, ent migration will drop old columns
+ // that were used for both fields and edges. This defaults to false.
+ WithDropColumn = schema.WithDropColumn
+ // WithDropIndex sets the drop index option to the migration.
+ // If this option is enabled, ent migration will drop old indexes
+ // that were defined in the schema. This defaults to false.
+ // Note that unique constraints are defined using `UNIQUE INDEX`,
+ // and therefore, it's recommended to enable this option to get more
+ // flexibility in the schema changes.
+ WithDropIndex = schema.WithDropIndex
+ // WithForeignKeys enables creating foreign-key in schema DDL. This defaults to true.
+ WithForeignKeys = schema.WithForeignKeys
+)
+
+// Schema is the API for creating, migrating and dropping a schema.
+type Schema struct {
+ drv dialect.Driver
+}
+
+// NewSchema creates a new schema client.
+func NewSchema(drv dialect.Driver) *Schema { return &Schema{drv: drv} }
+
+// Create creates all schema resources.
+func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error {
+ return Create(ctx, s, Tables, opts...)
+}
+
+// Create creates all table resources using the given schema driver.
+func Create(ctx context.Context, s *Schema, tables []*schema.Table, opts ...schema.MigrateOption) error {
+ migrate, err := schema.NewMigrate(s.drv, opts...)
+ if err != nil {
+ return fmt.Errorf("ent/migrate: %w", err)
+ }
+ return migrate.Create(ctx, tables...)
+}
+
+// WriteTo writes the schema changes to w instead of running them against the database.
+//
+// if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil {
+// log.Fatal(err)
+// }
+func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error {
+ return Create(ctx, &Schema{drv: &schema.WriteDriver{Writer: w, Driver: s.drv}}, Tables, opts...)
+}
diff --git a/backend/db/migrate/schema.go b/backend/db/migrate/schema.go
new file mode 100644
index 0000000..42e5bb9
--- /dev/null
+++ b/backend/db/migrate/schema.go
@@ -0,0 +1,349 @@
+// Code generated by ent, DO NOT EDIT.
+
+package migrate
+
+import (
+ "entgo.io/ent/dialect/entsql"
+ "entgo.io/ent/dialect/sql/schema"
+ "entgo.io/ent/schema/field"
+)
+
+var (
+ // AdminsColumns holds the columns for the "admins" table.
+ AdminsColumns = []*schema.Column{
+ {Name: "id", Type: field.TypeUUID},
+ {Name: "username", Type: field.TypeString, Unique: true},
+ {Name: "password", Type: field.TypeString},
+ {Name: "status", Type: field.TypeString},
+ {Name: "last_active_at", Type: field.TypeTime},
+ {Name: "created_at", Type: field.TypeTime},
+ {Name: "updated_at", Type: field.TypeTime},
+ }
+ // AdminsTable holds the schema information for the "admins" table.
+ AdminsTable = &schema.Table{
+ Name: "admins",
+ Columns: AdminsColumns,
+ PrimaryKey: []*schema.Column{AdminsColumns[0]},
+ }
+ // AdminLoginHistoriesColumns holds the columns for the "admin_login_histories" table.
+ AdminLoginHistoriesColumns = []*schema.Column{
+ {Name: "id", Type: field.TypeUUID},
+ {Name: "admin_id", Type: field.TypeUUID},
+ {Name: "ip", Type: field.TypeString},
+ {Name: "country", Type: field.TypeString},
+ {Name: "province", Type: field.TypeString},
+ {Name: "city", Type: field.TypeString},
+ {Name: "isp", Type: field.TypeString},
+ {Name: "asn", Type: field.TypeString},
+ {Name: "client_version", Type: field.TypeString},
+ {Name: "device", Type: field.TypeString},
+ {Name: "created_at", Type: field.TypeTime},
+ {Name: "admin_login_histories", Type: field.TypeUUID, Nullable: true},
+ }
+ // AdminLoginHistoriesTable holds the schema information for the "admin_login_histories" table.
+ AdminLoginHistoriesTable = &schema.Table{
+ Name: "admin_login_histories",
+ Columns: AdminLoginHistoriesColumns,
+ PrimaryKey: []*schema.Column{AdminLoginHistoriesColumns[0]},
+ ForeignKeys: []*schema.ForeignKey{
+ {
+ Symbol: "admin_login_histories_admins_login_histories",
+ Columns: []*schema.Column{AdminLoginHistoriesColumns[11]},
+ RefColumns: []*schema.Column{AdminsColumns[0]},
+ OnDelete: schema.SetNull,
+ },
+ },
+ }
+ // APIKeysColumns holds the columns for the "api_keys" table.
+ APIKeysColumns = []*schema.Column{
+ {Name: "id", Type: field.TypeUUID},
+ {Name: "user_id", Type: field.TypeUUID},
+ {Name: "key", Type: field.TypeString},
+ {Name: "name", Type: field.TypeString},
+ {Name: "status", Type: field.TypeString, Default: "active"},
+ {Name: "last_used", Type: field.TypeTime, Nullable: true},
+ {Name: "created_at", Type: field.TypeTime},
+ {Name: "updated_at", Type: field.TypeTime},
+ }
+ // APIKeysTable holds the schema information for the "api_keys" table.
+ APIKeysTable = &schema.Table{
+ Name: "api_keys",
+ Columns: APIKeysColumns,
+ PrimaryKey: []*schema.Column{APIKeysColumns[0]},
+ }
+ // BillingPlansColumns holds the columns for the "billing_plans" table.
+ BillingPlansColumns = []*schema.Column{
+ {Name: "id", Type: field.TypeString, Unique: true},
+ {Name: "name", Type: field.TypeString, Unique: true},
+ {Name: "description", Type: field.TypeString},
+ {Name: "rules", Type: field.TypeJSON},
+ {Name: "created_at", Type: field.TypeTime},
+ {Name: "updated_at", Type: field.TypeTime},
+ }
+ // BillingPlansTable holds the schema information for the "billing_plans" table.
+ BillingPlansTable = &schema.Table{
+ Name: "billing_plans",
+ Columns: BillingPlansColumns,
+ PrimaryKey: []*schema.Column{BillingPlansColumns[0]},
+ }
+ // BillingQuotasColumns holds the columns for the "billing_quotas" table.
+ BillingQuotasColumns = []*schema.Column{
+ {Name: "id", Type: field.TypeString, Unique: true},
+ {Name: "deleted_at", Type: field.TypeTime, Nullable: true},
+ {Name: "user_id", Type: field.TypeString, Unique: true},
+ {Name: "total", Type: field.TypeInt64},
+ {Name: "used", Type: field.TypeInt64},
+ {Name: "remain", Type: field.TypeInt64},
+ {Name: "created_at", Type: field.TypeTime},
+ {Name: "updated_at", Type: field.TypeTime},
+ }
+ // BillingQuotasTable holds the schema information for the "billing_quotas" table.
+ BillingQuotasTable = &schema.Table{
+ Name: "billing_quotas",
+ Columns: BillingQuotasColumns,
+ PrimaryKey: []*schema.Column{BillingQuotasColumns[0]},
+ }
+ // BillingRecordsColumns holds the columns for the "billing_records" table.
+ BillingRecordsColumns = []*schema.Column{
+ {Name: "id", Type: field.TypeString, Unique: true},
+ {Name: "tenant_id", Type: field.TypeString, Unique: true},
+ {Name: "user_id", Type: field.TypeString, Unique: true},
+ {Name: "model", Type: field.TypeString},
+ {Name: "operation", Type: field.TypeString},
+ {Name: "input_tokens", Type: field.TypeInt64},
+ {Name: "output_tokens", Type: field.TypeInt64},
+ {Name: "cost", Type: field.TypeInt64},
+ {Name: "request_time", Type: field.TypeTime},
+ {Name: "metadata", Type: field.TypeJSON},
+ {Name: "created_at", Type: field.TypeTime},
+ {Name: "updated_at", Type: field.TypeTime},
+ }
+ // BillingRecordsTable holds the schema information for the "billing_records" table.
+ BillingRecordsTable = &schema.Table{
+ Name: "billing_records",
+ Columns: BillingRecordsColumns,
+ PrimaryKey: []*schema.Column{BillingRecordsColumns[0]},
+ }
+ // BillingUsagesColumns holds the columns for the "billing_usages" table.
+ BillingUsagesColumns = []*schema.Column{
+ {Name: "id", Type: field.TypeString, Unique: true},
+ {Name: "deleted_at", Type: field.TypeTime, Nullable: true},
+ {Name: "user_id", Type: field.TypeString, Unique: true},
+ {Name: "model_name", Type: field.TypeString},
+ {Name: "tokens", Type: field.TypeInt64},
+ {Name: "operation", Type: field.TypeString},
+ {Name: "created_at", Type: field.TypeTime},
+ {Name: "updated_at", Type: field.TypeTime},
+ }
+ // BillingUsagesTable holds the schema information for the "billing_usages" table.
+ BillingUsagesTable = &schema.Table{
+ Name: "billing_usages",
+ Columns: BillingUsagesColumns,
+ PrimaryKey: []*schema.Column{BillingUsagesColumns[0]},
+ }
+ // InviteCodesColumns holds the columns for the "invite_codes" table.
+ InviteCodesColumns = []*schema.Column{
+ {Name: "id", Type: field.TypeUUID},
+ {Name: "admin_id", Type: field.TypeUUID},
+ {Name: "code", Type: field.TypeString, Unique: true},
+ {Name: "created_at", Type: field.TypeTime},
+ {Name: "updated_at", Type: field.TypeTime},
+ }
+ // InviteCodesTable holds the schema information for the "invite_codes" table.
+ InviteCodesTable = &schema.Table{
+ Name: "invite_codes",
+ Columns: InviteCodesColumns,
+ PrimaryKey: []*schema.Column{InviteCodesColumns[0]},
+ }
+ // ModelsColumns holds the columns for the "models" table.
+ ModelsColumns = []*schema.Column{
+ {Name: "id", Type: field.TypeUUID},
+ {Name: "model_name", Type: field.TypeString},
+ {Name: "model_type", Type: field.TypeString},
+ {Name: "api_base", Type: field.TypeString},
+ {Name: "api_key", Type: field.TypeString},
+ {Name: "api_version", Type: field.TypeString, Nullable: true},
+ {Name: "description", Type: field.TypeString, Nullable: true},
+ {Name: "provider", Type: field.TypeString},
+ {Name: "status", Type: field.TypeString, Default: "active"},
+ {Name: "context_length", Type: field.TypeInt, Nullable: true},
+ {Name: "created_at", Type: field.TypeTime},
+ {Name: "updated_at", Type: field.TypeTime},
+ {Name: "user_id", Type: field.TypeUUID, Nullable: true},
+ }
+ // ModelsTable holds the schema information for the "models" table.
+ ModelsTable = &schema.Table{
+ Name: "models",
+ Columns: ModelsColumns,
+ PrimaryKey: []*schema.Column{ModelsColumns[0]},
+ ForeignKeys: []*schema.ForeignKey{
+ {
+ Symbol: "models_users_models",
+ Columns: []*schema.Column{ModelsColumns[12]},
+ RefColumns: []*schema.Column{UsersColumns[0]},
+ OnDelete: schema.SetNull,
+ },
+ },
+ }
+ // RecordsColumns holds the columns for the "records" table.
+ RecordsColumns = []*schema.Column{
+ {Name: "id", Type: field.TypeUUID},
+ {Name: "task_id", Type: field.TypeString},
+ {Name: "model_type", Type: field.TypeString, Nullable: true},
+ {Name: "prompt", Type: field.TypeString, Nullable: true},
+ {Name: "completion", Type: field.TypeString, Nullable: true},
+ {Name: "is_accept", Type: field.TypeBool, Default: false},
+ {Name: "program_language", Type: field.TypeString, Nullable: true},
+ {Name: "work_mode", Type: field.TypeString, Nullable: true},
+ {Name: "code_lines", Type: field.TypeInt64, Nullable: true},
+ {Name: "input_tokens", Type: field.TypeInt64},
+ {Name: "output_tokens", Type: field.TypeInt64},
+ {Name: "created_at", Type: field.TypeTime},
+ {Name: "updated_at", Type: field.TypeTime},
+ {Name: "model_id", Type: field.TypeUUID, Nullable: true},
+ {Name: "user_id", Type: field.TypeUUID, Nullable: true},
+ }
+ // RecordsTable holds the schema information for the "records" table.
+ RecordsTable = &schema.Table{
+ Name: "records",
+ Columns: RecordsColumns,
+ PrimaryKey: []*schema.Column{RecordsColumns[0]},
+ ForeignKeys: []*schema.ForeignKey{
+ {
+ Symbol: "records_models_records",
+ Columns: []*schema.Column{RecordsColumns[13]},
+ RefColumns: []*schema.Column{ModelsColumns[0]},
+ OnDelete: schema.SetNull,
+ },
+ {
+ Symbol: "records_users_records",
+ Columns: []*schema.Column{RecordsColumns[14]},
+ RefColumns: []*schema.Column{UsersColumns[0]},
+ OnDelete: schema.SetNull,
+ },
+ },
+ }
+ // SettingsColumns holds the columns for the "settings" table.
+ SettingsColumns = []*schema.Column{
+ {Name: "id", Type: field.TypeUUID},
+ {Name: "enable_sso", Type: field.TypeBool, Default: false},
+ {Name: "force_two_factor_auth", Type: field.TypeBool, Default: false},
+ {Name: "disable_password_login", Type: field.TypeBool, Default: false},
+ {Name: "created_at", Type: field.TypeTime},
+ {Name: "updated_at", Type: field.TypeTime},
+ }
+ // SettingsTable holds the schema information for the "settings" table.
+ SettingsTable = &schema.Table{
+ Name: "settings",
+ Columns: SettingsColumns,
+ PrimaryKey: []*schema.Column{SettingsColumns[0]},
+ }
+ // UsersColumns holds the columns for the "users" table.
+ UsersColumns = []*schema.Column{
+ {Name: "id", Type: field.TypeUUID},
+ {Name: "username", Type: field.TypeString, Unique: true},
+ {Name: "password", Type: field.TypeString},
+ {Name: "email", Type: field.TypeString, Unique: true},
+ {Name: "status", Type: field.TypeString, Default: "active"},
+ {Name: "created_at", Type: field.TypeTime},
+ {Name: "updated_at", Type: field.TypeTime},
+ }
+ // UsersTable holds the schema information for the "users" table.
+ UsersTable = &schema.Table{
+ Name: "users",
+ Columns: UsersColumns,
+ PrimaryKey: []*schema.Column{UsersColumns[0]},
+ }
+ // UserLoginHistoriesColumns holds the columns for the "user_login_histories" table.
+ UserLoginHistoriesColumns = []*schema.Column{
+ {Name: "id", Type: field.TypeUUID},
+ {Name: "user_id", Type: field.TypeUUID},
+ {Name: "ip", Type: field.TypeString},
+ {Name: "country", Type: field.TypeString},
+ {Name: "province", Type: field.TypeString},
+ {Name: "city", Type: field.TypeString},
+ {Name: "isp", Type: field.TypeString},
+ {Name: "asn", Type: field.TypeString},
+ {Name: "client_version", Type: field.TypeString},
+ {Name: "device", Type: field.TypeString},
+ {Name: "created_at", Type: field.TypeTime},
+ {Name: "user_login_histories", Type: field.TypeUUID, Nullable: true},
+ }
+ // UserLoginHistoriesTable holds the schema information for the "user_login_histories" table.
+ UserLoginHistoriesTable = &schema.Table{
+ Name: "user_login_histories",
+ Columns: UserLoginHistoriesColumns,
+ PrimaryKey: []*schema.Column{UserLoginHistoriesColumns[0]},
+ ForeignKeys: []*schema.ForeignKey{
+ {
+ Symbol: "user_login_histories_users_login_histories",
+ Columns: []*schema.Column{UserLoginHistoriesColumns[11]},
+ RefColumns: []*schema.Column{UsersColumns[0]},
+ OnDelete: schema.SetNull,
+ },
+ },
+ }
+ // Tables holds all the tables in the schema.
+ Tables = []*schema.Table{
+ AdminsTable,
+ AdminLoginHistoriesTable,
+ APIKeysTable,
+ BillingPlansTable,
+ BillingQuotasTable,
+ BillingRecordsTable,
+ BillingUsagesTable,
+ InviteCodesTable,
+ ModelsTable,
+ RecordsTable,
+ SettingsTable,
+ UsersTable,
+ UserLoginHistoriesTable,
+ }
+)
+
+func init() {
+ AdminsTable.Annotation = &entsql.Annotation{
+ Table: "admins",
+ }
+ AdminLoginHistoriesTable.ForeignKeys[0].RefTable = AdminsTable
+ AdminLoginHistoriesTable.Annotation = &entsql.Annotation{
+ Table: "admin_login_histories",
+ }
+ APIKeysTable.Annotation = &entsql.Annotation{
+ Table: "api_keys",
+ }
+ BillingPlansTable.Annotation = &entsql.Annotation{
+ Table: "billing_plans",
+ }
+ BillingQuotasTable.Annotation = &entsql.Annotation{
+ Table: "billing_quotas",
+ }
+ BillingRecordsTable.Annotation = &entsql.Annotation{
+ Table: "billing_records",
+ }
+ BillingUsagesTable.Annotation = &entsql.Annotation{
+ Table: "billing_usages",
+ }
+ InviteCodesTable.Annotation = &entsql.Annotation{
+ Table: "invite_codes",
+ }
+ ModelsTable.ForeignKeys[0].RefTable = UsersTable
+ ModelsTable.Annotation = &entsql.Annotation{
+ Table: "models",
+ }
+ RecordsTable.ForeignKeys[0].RefTable = ModelsTable
+ RecordsTable.ForeignKeys[1].RefTable = UsersTable
+ RecordsTable.Annotation = &entsql.Annotation{
+ Table: "records",
+ }
+ SettingsTable.Annotation = &entsql.Annotation{
+ Table: "settings",
+ }
+ UsersTable.Annotation = &entsql.Annotation{
+ Table: "users",
+ }
+ UserLoginHistoriesTable.ForeignKeys[0].RefTable = UsersTable
+ UserLoginHistoriesTable.Annotation = &entsql.Annotation{
+ Table: "user_login_histories",
+ }
+}
diff --git a/backend/db/model.go b/backend/db/model.go
new file mode 100644
index 0000000..a25d520
--- /dev/null
+++ b/backend/db/model.go
@@ -0,0 +1,276 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "fmt"
+ "strings"
+ "time"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect/sql"
+ "github.com/chaitin/MonkeyCode/backend/consts"
+ "github.com/chaitin/MonkeyCode/backend/db/model"
+ "github.com/chaitin/MonkeyCode/backend/db/user"
+ "github.com/google/uuid"
+)
+
+// Model is the model entity for the Model schema.
+type Model struct {
+ config `json:"-"`
+ // ID of the ent.
+ ID uuid.UUID `json:"id,omitempty"`
+ // UserID holds the value of the "user_id" field.
+ UserID uuid.UUID `json:"user_id,omitempty"`
+ // ModelName holds the value of the "model_name" field.
+ ModelName string `json:"model_name,omitempty"`
+ // ModelType holds the value of the "model_type" field.
+ ModelType consts.ModelType `json:"model_type,omitempty"`
+ // APIBase holds the value of the "api_base" field.
+ APIBase string `json:"api_base,omitempty"`
+ // APIKey holds the value of the "api_key" field.
+ APIKey string `json:"api_key,omitempty"`
+ // APIVersion holds the value of the "api_version" field.
+ APIVersion string `json:"api_version,omitempty"`
+ // Description holds the value of the "description" field.
+ Description string `json:"description,omitempty"`
+ // Provider holds the value of the "provider" field.
+ Provider string `json:"provider,omitempty"`
+ // Status holds the value of the "status" field.
+ Status consts.ModelStatus `json:"status,omitempty"`
+ // ContextLength holds the value of the "context_length" field.
+ ContextLength int `json:"context_length,omitempty"`
+ // CreatedAt holds the value of the "created_at" field.
+ CreatedAt time.Time `json:"created_at,omitempty"`
+ // UpdatedAt holds the value of the "updated_at" field.
+ UpdatedAt time.Time `json:"updated_at,omitempty"`
+ // Edges holds the relations/edges for other nodes in the graph.
+ // The values are being populated by the ModelQuery when eager-loading is set.
+ Edges ModelEdges `json:"edges"`
+ selectValues sql.SelectValues
+}
+
+// ModelEdges holds the relations/edges for other nodes in the graph.
+type ModelEdges struct {
+ // Records holds the value of the records edge.
+ Records []*Record `json:"records,omitempty"`
+ // User holds the value of the user edge.
+ User *User `json:"user,omitempty"`
+ // loadedTypes holds the information for reporting if a
+ // type was loaded (or requested) in eager-loading or not.
+ loadedTypes [2]bool
+}
+
+// RecordsOrErr returns the Records value or an error if the edge
+// was not loaded in eager-loading.
+func (e ModelEdges) RecordsOrErr() ([]*Record, error) {
+ if e.loadedTypes[0] {
+ return e.Records, nil
+ }
+ return nil, &NotLoadedError{edge: "records"}
+}
+
+// UserOrErr returns the User value or an error if the edge
+// was not loaded in eager-loading, or loaded but was not found.
+func (e ModelEdges) UserOrErr() (*User, error) {
+ if e.User != nil {
+ return e.User, nil
+ } else if e.loadedTypes[1] {
+ return nil, &NotFoundError{label: user.Label}
+ }
+ return nil, &NotLoadedError{edge: "user"}
+}
+
+// scanValues returns the types for scanning values from sql.Rows.
+func (*Model) scanValues(columns []string) ([]any, error) {
+ values := make([]any, len(columns))
+ for i := range columns {
+ switch columns[i] {
+ case model.FieldContextLength:
+ values[i] = new(sql.NullInt64)
+ case model.FieldModelName, model.FieldModelType, model.FieldAPIBase, model.FieldAPIKey, model.FieldAPIVersion, model.FieldDescription, model.FieldProvider, model.FieldStatus:
+ values[i] = new(sql.NullString)
+ case model.FieldCreatedAt, model.FieldUpdatedAt:
+ values[i] = new(sql.NullTime)
+ case model.FieldID, model.FieldUserID:
+ values[i] = new(uuid.UUID)
+ default:
+ values[i] = new(sql.UnknownType)
+ }
+ }
+ return values, nil
+}
+
+// assignValues assigns the values that were returned from sql.Rows (after scanning)
+// to the Model fields.
+func (m *Model) assignValues(columns []string, values []any) error {
+ if m, n := len(values), len(columns); m < n {
+ return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
+ }
+ for i := range columns {
+ switch columns[i] {
+ case model.FieldID:
+ if value, ok := values[i].(*uuid.UUID); !ok {
+ return fmt.Errorf("unexpected type %T for field id", values[i])
+ } else if value != nil {
+ m.ID = *value
+ }
+ case model.FieldUserID:
+ if value, ok := values[i].(*uuid.UUID); !ok {
+ return fmt.Errorf("unexpected type %T for field user_id", values[i])
+ } else if value != nil {
+ m.UserID = *value
+ }
+ case model.FieldModelName:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field model_name", values[i])
+ } else if value.Valid {
+ m.ModelName = value.String
+ }
+ case model.FieldModelType:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field model_type", values[i])
+ } else if value.Valid {
+ m.ModelType = consts.ModelType(value.String)
+ }
+ case model.FieldAPIBase:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field api_base", values[i])
+ } else if value.Valid {
+ m.APIBase = value.String
+ }
+ case model.FieldAPIKey:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field api_key", values[i])
+ } else if value.Valid {
+ m.APIKey = value.String
+ }
+ case model.FieldAPIVersion:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field api_version", values[i])
+ } else if value.Valid {
+ m.APIVersion = value.String
+ }
+ case model.FieldDescription:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field description", values[i])
+ } else if value.Valid {
+ m.Description = value.String
+ }
+ case model.FieldProvider:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field provider", values[i])
+ } else if value.Valid {
+ m.Provider = value.String
+ }
+ case model.FieldStatus:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field status", values[i])
+ } else if value.Valid {
+ m.Status = consts.ModelStatus(value.String)
+ }
+ case model.FieldContextLength:
+ if value, ok := values[i].(*sql.NullInt64); !ok {
+ return fmt.Errorf("unexpected type %T for field context_length", values[i])
+ } else if value.Valid {
+ m.ContextLength = int(value.Int64)
+ }
+ case model.FieldCreatedAt:
+ if value, ok := values[i].(*sql.NullTime); !ok {
+ return fmt.Errorf("unexpected type %T for field created_at", values[i])
+ } else if value.Valid {
+ m.CreatedAt = value.Time
+ }
+ case model.FieldUpdatedAt:
+ if value, ok := values[i].(*sql.NullTime); !ok {
+ return fmt.Errorf("unexpected type %T for field updated_at", values[i])
+ } else if value.Valid {
+ m.UpdatedAt = value.Time
+ }
+ default:
+ m.selectValues.Set(columns[i], values[i])
+ }
+ }
+ return nil
+}
+
+// Value returns the ent.Value that was dynamically selected and assigned to the Model.
+// This includes values selected through modifiers, order, etc.
+func (m *Model) Value(name string) (ent.Value, error) {
+ return m.selectValues.Get(name)
+}
+
+// QueryRecords queries the "records" edge of the Model entity.
+func (m *Model) QueryRecords() *RecordQuery {
+ return NewModelClient(m.config).QueryRecords(m)
+}
+
+// QueryUser queries the "user" edge of the Model entity.
+func (m *Model) QueryUser() *UserQuery {
+ return NewModelClient(m.config).QueryUser(m)
+}
+
+// Update returns a builder for updating this Model.
+// Note that you need to call Model.Unwrap() before calling this method if this Model
+// was returned from a transaction, and the transaction was committed or rolled back.
+func (m *Model) Update() *ModelUpdateOne {
+ return NewModelClient(m.config).UpdateOne(m)
+}
+
+// Unwrap unwraps the Model entity that was returned from a transaction after it was closed,
+// so that all future queries will be executed through the driver which created the transaction.
+func (m *Model) Unwrap() *Model {
+ _tx, ok := m.config.driver.(*txDriver)
+ if !ok {
+ panic("db: Model is not a transactional entity")
+ }
+ m.config.driver = _tx.drv
+ return m
+}
+
+// String implements the fmt.Stringer.
+func (m *Model) String() string {
+ var builder strings.Builder
+ builder.WriteString("Model(")
+ builder.WriteString(fmt.Sprintf("id=%v, ", m.ID))
+ builder.WriteString("user_id=")
+ builder.WriteString(fmt.Sprintf("%v", m.UserID))
+ builder.WriteString(", ")
+ builder.WriteString("model_name=")
+ builder.WriteString(m.ModelName)
+ builder.WriteString(", ")
+ builder.WriteString("model_type=")
+ builder.WriteString(fmt.Sprintf("%v", m.ModelType))
+ builder.WriteString(", ")
+ builder.WriteString("api_base=")
+ builder.WriteString(m.APIBase)
+ builder.WriteString(", ")
+ builder.WriteString("api_key=")
+ builder.WriteString(m.APIKey)
+ builder.WriteString(", ")
+ builder.WriteString("api_version=")
+ builder.WriteString(m.APIVersion)
+ builder.WriteString(", ")
+ builder.WriteString("description=")
+ builder.WriteString(m.Description)
+ builder.WriteString(", ")
+ builder.WriteString("provider=")
+ builder.WriteString(m.Provider)
+ builder.WriteString(", ")
+ builder.WriteString("status=")
+ builder.WriteString(fmt.Sprintf("%v", m.Status))
+ builder.WriteString(", ")
+ builder.WriteString("context_length=")
+ builder.WriteString(fmt.Sprintf("%v", m.ContextLength))
+ builder.WriteString(", ")
+ builder.WriteString("created_at=")
+ builder.WriteString(m.CreatedAt.Format(time.ANSIC))
+ builder.WriteString(", ")
+ builder.WriteString("updated_at=")
+ builder.WriteString(m.UpdatedAt.Format(time.ANSIC))
+ builder.WriteByte(')')
+ return builder.String()
+}
+
+// Models is a parsable slice of Model.
+type Models []*Model
diff --git a/backend/db/model/model.go b/backend/db/model/model.go
new file mode 100644
index 0000000..5aa0e14
--- /dev/null
+++ b/backend/db/model/model.go
@@ -0,0 +1,203 @@
+// Code generated by ent, DO NOT EDIT.
+
+package model
+
+import (
+ "time"
+
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "github.com/chaitin/MonkeyCode/backend/consts"
+)
+
+const (
+ // Label holds the string label denoting the model type in the database.
+ Label = "model"
+ // FieldID holds the string denoting the id field in the database.
+ FieldID = "id"
+ // FieldUserID holds the string denoting the user_id field in the database.
+ FieldUserID = "user_id"
+ // FieldModelName holds the string denoting the model_name field in the database.
+ FieldModelName = "model_name"
+ // FieldModelType holds the string denoting the model_type field in the database.
+ FieldModelType = "model_type"
+ // FieldAPIBase holds the string denoting the api_base field in the database.
+ FieldAPIBase = "api_base"
+ // FieldAPIKey holds the string denoting the api_key field in the database.
+ FieldAPIKey = "api_key"
+ // FieldAPIVersion holds the string denoting the api_version field in the database.
+ FieldAPIVersion = "api_version"
+ // FieldDescription holds the string denoting the description field in the database.
+ FieldDescription = "description"
+ // FieldProvider holds the string denoting the provider field in the database.
+ FieldProvider = "provider"
+ // FieldStatus holds the string denoting the status field in the database.
+ FieldStatus = "status"
+ // FieldContextLength holds the string denoting the context_length field in the database.
+ FieldContextLength = "context_length"
+ // FieldCreatedAt holds the string denoting the created_at field in the database.
+ FieldCreatedAt = "created_at"
+ // FieldUpdatedAt holds the string denoting the updated_at field in the database.
+ FieldUpdatedAt = "updated_at"
+ // EdgeRecords holds the string denoting the records edge name in mutations.
+ EdgeRecords = "records"
+ // EdgeUser holds the string denoting the user edge name in mutations.
+ EdgeUser = "user"
+ // Table holds the table name of the model in the database.
+ Table = "models"
+ // RecordsTable is the table that holds the records relation/edge.
+ RecordsTable = "records"
+ // RecordsInverseTable is the table name for the Record entity.
+ // It exists in this package in order to avoid circular dependency with the "record" package.
+ RecordsInverseTable = "records"
+ // RecordsColumn is the table column denoting the records relation/edge.
+ RecordsColumn = "model_id"
+ // UserTable is the table that holds the user relation/edge.
+ UserTable = "models"
+ // UserInverseTable is the table name for the User entity.
+ // It exists in this package in order to avoid circular dependency with the "user" package.
+ UserInverseTable = "users"
+ // UserColumn is the table column denoting the user relation/edge.
+ UserColumn = "user_id"
+)
+
+// Columns holds all SQL columns for model fields.
+var Columns = []string{
+ FieldID,
+ FieldUserID,
+ FieldModelName,
+ FieldModelType,
+ FieldAPIBase,
+ FieldAPIKey,
+ FieldAPIVersion,
+ FieldDescription,
+ FieldProvider,
+ FieldStatus,
+ FieldContextLength,
+ FieldCreatedAt,
+ FieldUpdatedAt,
+}
+
+// ValidColumn reports if the column name is valid (part of the table columns).
+func ValidColumn(column string) bool {
+ for i := range Columns {
+ if column == Columns[i] {
+ return true
+ }
+ }
+ return false
+}
+
+var (
+ // DefaultStatus holds the default value on creation for the "status" field.
+ DefaultStatus consts.ModelStatus
+ // DefaultCreatedAt holds the default value on creation for the "created_at" field.
+ DefaultCreatedAt func() time.Time
+ // DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
+ DefaultUpdatedAt func() time.Time
+ // UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field.
+ UpdateDefaultUpdatedAt func() time.Time
+)
+
+// OrderOption defines the ordering options for the Model queries.
+type OrderOption func(*sql.Selector)
+
+// ByID orders the results by the id field.
+func ByID(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldID, opts...).ToFunc()
+}
+
+// ByUserID orders the results by the user_id field.
+func ByUserID(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldUserID, opts...).ToFunc()
+}
+
+// ByModelName orders the results by the model_name field.
+func ByModelName(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldModelName, opts...).ToFunc()
+}
+
+// ByModelType orders the results by the model_type field.
+func ByModelType(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldModelType, opts...).ToFunc()
+}
+
+// ByAPIBase orders the results by the api_base field.
+func ByAPIBase(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldAPIBase, opts...).ToFunc()
+}
+
+// ByAPIKey orders the results by the api_key field.
+func ByAPIKey(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldAPIKey, opts...).ToFunc()
+}
+
+// ByAPIVersion orders the results by the api_version field.
+func ByAPIVersion(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldAPIVersion, opts...).ToFunc()
+}
+
+// ByDescription orders the results by the description field.
+func ByDescription(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldDescription, opts...).ToFunc()
+}
+
+// ByProvider orders the results by the provider field.
+func ByProvider(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldProvider, opts...).ToFunc()
+}
+
+// ByStatus orders the results by the status field.
+func ByStatus(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldStatus, opts...).ToFunc()
+}
+
+// ByContextLength orders the results by the context_length field.
+func ByContextLength(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldContextLength, opts...).ToFunc()
+}
+
+// ByCreatedAt orders the results by the created_at field.
+func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
+}
+
+// ByUpdatedAt orders the results by the updated_at field.
+func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc()
+}
+
+// ByRecordsCount orders the results by records count.
+func ByRecordsCount(opts ...sql.OrderTermOption) OrderOption {
+ return func(s *sql.Selector) {
+ sqlgraph.OrderByNeighborsCount(s, newRecordsStep(), opts...)
+ }
+}
+
+// ByRecords orders the results by records terms.
+func ByRecords(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
+ return func(s *sql.Selector) {
+ sqlgraph.OrderByNeighborTerms(s, newRecordsStep(), append([]sql.OrderTerm{term}, terms...)...)
+ }
+}
+
+// ByUserField orders the results by user field.
+func ByUserField(field string, opts ...sql.OrderTermOption) OrderOption {
+ return func(s *sql.Selector) {
+ sqlgraph.OrderByNeighborTerms(s, newUserStep(), sql.OrderByField(field, opts...))
+ }
+}
+func newRecordsStep() *sqlgraph.Step {
+ return sqlgraph.NewStep(
+ sqlgraph.From(Table, FieldID),
+ sqlgraph.To(RecordsInverseTable, FieldID),
+ sqlgraph.Edge(sqlgraph.O2M, false, RecordsTable, RecordsColumn),
+ )
+}
+func newUserStep() *sqlgraph.Step {
+ return sqlgraph.NewStep(
+ sqlgraph.From(Table, FieldID),
+ sqlgraph.To(UserInverseTable, FieldID),
+ sqlgraph.Edge(sqlgraph.M2O, true, UserTable, UserColumn),
+ )
+}
diff --git a/backend/db/model/where.go b/backend/db/model/where.go
new file mode 100644
index 0000000..17d222d
--- /dev/null
+++ b/backend/db/model/where.go
@@ -0,0 +1,919 @@
+// Code generated by ent, DO NOT EDIT.
+
+package model
+
+import (
+ "time"
+
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "github.com/chaitin/MonkeyCode/backend/consts"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+ "github.com/google/uuid"
+)
+
+// ID filters vertices based on their ID field.
+func ID(id uuid.UUID) predicate.Model {
+ return predicate.Model(sql.FieldEQ(FieldID, id))
+}
+
+// IDEQ applies the EQ predicate on the ID field.
+func IDEQ(id uuid.UUID) predicate.Model {
+ return predicate.Model(sql.FieldEQ(FieldID, id))
+}
+
+// IDNEQ applies the NEQ predicate on the ID field.
+func IDNEQ(id uuid.UUID) predicate.Model {
+ return predicate.Model(sql.FieldNEQ(FieldID, id))
+}
+
+// IDIn applies the In predicate on the ID field.
+func IDIn(ids ...uuid.UUID) predicate.Model {
+ return predicate.Model(sql.FieldIn(FieldID, ids...))
+}
+
+// IDNotIn applies the NotIn predicate on the ID field.
+func IDNotIn(ids ...uuid.UUID) predicate.Model {
+ return predicate.Model(sql.FieldNotIn(FieldID, ids...))
+}
+
+// IDGT applies the GT predicate on the ID field.
+func IDGT(id uuid.UUID) predicate.Model {
+ return predicate.Model(sql.FieldGT(FieldID, id))
+}
+
+// IDGTE applies the GTE predicate on the ID field.
+func IDGTE(id uuid.UUID) predicate.Model {
+ return predicate.Model(sql.FieldGTE(FieldID, id))
+}
+
+// IDLT applies the LT predicate on the ID field.
+func IDLT(id uuid.UUID) predicate.Model {
+ return predicate.Model(sql.FieldLT(FieldID, id))
+}
+
+// IDLTE applies the LTE predicate on the ID field.
+func IDLTE(id uuid.UUID) predicate.Model {
+ return predicate.Model(sql.FieldLTE(FieldID, id))
+}
+
+// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ.
+func UserID(v uuid.UUID) predicate.Model {
+ return predicate.Model(sql.FieldEQ(FieldUserID, v))
+}
+
+// ModelName applies equality check predicate on the "model_name" field. It's identical to ModelNameEQ.
+func ModelName(v string) predicate.Model {
+ return predicate.Model(sql.FieldEQ(FieldModelName, v))
+}
+
+// ModelType applies equality check predicate on the "model_type" field. It's identical to ModelTypeEQ.
+func ModelType(v consts.ModelType) predicate.Model {
+ vc := string(v)
+ return predicate.Model(sql.FieldEQ(FieldModelType, vc))
+}
+
+// APIBase applies equality check predicate on the "api_base" field. It's identical to APIBaseEQ.
+func APIBase(v string) predicate.Model {
+ return predicate.Model(sql.FieldEQ(FieldAPIBase, v))
+}
+
+// APIKey applies equality check predicate on the "api_key" field. It's identical to APIKeyEQ.
+func APIKey(v string) predicate.Model {
+ return predicate.Model(sql.FieldEQ(FieldAPIKey, v))
+}
+
+// APIVersion applies equality check predicate on the "api_version" field. It's identical to APIVersionEQ.
+func APIVersion(v string) predicate.Model {
+ return predicate.Model(sql.FieldEQ(FieldAPIVersion, v))
+}
+
+// Description applies equality check predicate on the "description" field. It's identical to DescriptionEQ.
+func Description(v string) predicate.Model {
+ return predicate.Model(sql.FieldEQ(FieldDescription, v))
+}
+
+// Provider applies equality check predicate on the "provider" field. It's identical to ProviderEQ.
+func Provider(v string) predicate.Model {
+ return predicate.Model(sql.FieldEQ(FieldProvider, v))
+}
+
+// Status applies equality check predicate on the "status" field. It's identical to StatusEQ.
+func Status(v consts.ModelStatus) predicate.Model {
+ vc := string(v)
+ return predicate.Model(sql.FieldEQ(FieldStatus, vc))
+}
+
+// ContextLength applies equality check predicate on the "context_length" field. It's identical to ContextLengthEQ.
+func ContextLength(v int) predicate.Model {
+ return predicate.Model(sql.FieldEQ(FieldContextLength, v))
+}
+
+// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
+func CreatedAt(v time.Time) predicate.Model {
+ return predicate.Model(sql.FieldEQ(FieldCreatedAt, v))
+}
+
+// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
+func UpdatedAt(v time.Time) predicate.Model {
+ return predicate.Model(sql.FieldEQ(FieldUpdatedAt, v))
+}
+
+// UserIDEQ applies the EQ predicate on the "user_id" field.
+func UserIDEQ(v uuid.UUID) predicate.Model {
+ return predicate.Model(sql.FieldEQ(FieldUserID, v))
+}
+
+// UserIDNEQ applies the NEQ predicate on the "user_id" field.
+func UserIDNEQ(v uuid.UUID) predicate.Model {
+ return predicate.Model(sql.FieldNEQ(FieldUserID, v))
+}
+
+// UserIDIn applies the In predicate on the "user_id" field.
+func UserIDIn(vs ...uuid.UUID) predicate.Model {
+ return predicate.Model(sql.FieldIn(FieldUserID, vs...))
+}
+
+// UserIDNotIn applies the NotIn predicate on the "user_id" field.
+func UserIDNotIn(vs ...uuid.UUID) predicate.Model {
+ return predicate.Model(sql.FieldNotIn(FieldUserID, vs...))
+}
+
+// UserIDIsNil applies the IsNil predicate on the "user_id" field.
+func UserIDIsNil() predicate.Model {
+ return predicate.Model(sql.FieldIsNull(FieldUserID))
+}
+
+// UserIDNotNil applies the NotNil predicate on the "user_id" field.
+func UserIDNotNil() predicate.Model {
+ return predicate.Model(sql.FieldNotNull(FieldUserID))
+}
+
+// ModelNameEQ applies the EQ predicate on the "model_name" field.
+func ModelNameEQ(v string) predicate.Model {
+ return predicate.Model(sql.FieldEQ(FieldModelName, v))
+}
+
+// ModelNameNEQ applies the NEQ predicate on the "model_name" field.
+func ModelNameNEQ(v string) predicate.Model {
+ return predicate.Model(sql.FieldNEQ(FieldModelName, v))
+}
+
+// ModelNameIn applies the In predicate on the "model_name" field.
+func ModelNameIn(vs ...string) predicate.Model {
+ return predicate.Model(sql.FieldIn(FieldModelName, vs...))
+}
+
+// ModelNameNotIn applies the NotIn predicate on the "model_name" field.
+func ModelNameNotIn(vs ...string) predicate.Model {
+ return predicate.Model(sql.FieldNotIn(FieldModelName, vs...))
+}
+
+// ModelNameGT applies the GT predicate on the "model_name" field.
+func ModelNameGT(v string) predicate.Model {
+ return predicate.Model(sql.FieldGT(FieldModelName, v))
+}
+
+// ModelNameGTE applies the GTE predicate on the "model_name" field.
+func ModelNameGTE(v string) predicate.Model {
+ return predicate.Model(sql.FieldGTE(FieldModelName, v))
+}
+
+// ModelNameLT applies the LT predicate on the "model_name" field.
+func ModelNameLT(v string) predicate.Model {
+ return predicate.Model(sql.FieldLT(FieldModelName, v))
+}
+
+// ModelNameLTE applies the LTE predicate on the "model_name" field.
+func ModelNameLTE(v string) predicate.Model {
+ return predicate.Model(sql.FieldLTE(FieldModelName, v))
+}
+
+// ModelNameContains applies the Contains predicate on the "model_name" field.
+func ModelNameContains(v string) predicate.Model {
+ return predicate.Model(sql.FieldContains(FieldModelName, v))
+}
+
+// ModelNameHasPrefix applies the HasPrefix predicate on the "model_name" field.
+func ModelNameHasPrefix(v string) predicate.Model {
+ return predicate.Model(sql.FieldHasPrefix(FieldModelName, v))
+}
+
+// ModelNameHasSuffix applies the HasSuffix predicate on the "model_name" field.
+func ModelNameHasSuffix(v string) predicate.Model {
+ return predicate.Model(sql.FieldHasSuffix(FieldModelName, v))
+}
+
+// ModelNameEqualFold applies the EqualFold predicate on the "model_name" field.
+func ModelNameEqualFold(v string) predicate.Model {
+ return predicate.Model(sql.FieldEqualFold(FieldModelName, v))
+}
+
+// ModelNameContainsFold applies the ContainsFold predicate on the "model_name" field.
+func ModelNameContainsFold(v string) predicate.Model {
+ return predicate.Model(sql.FieldContainsFold(FieldModelName, v))
+}
+
+// ModelTypeEQ applies the EQ predicate on the "model_type" field.
+func ModelTypeEQ(v consts.ModelType) predicate.Model {
+ vc := string(v)
+ return predicate.Model(sql.FieldEQ(FieldModelType, vc))
+}
+
+// ModelTypeNEQ applies the NEQ predicate on the "model_type" field.
+func ModelTypeNEQ(v consts.ModelType) predicate.Model {
+ vc := string(v)
+ return predicate.Model(sql.FieldNEQ(FieldModelType, vc))
+}
+
+// ModelTypeIn applies the In predicate on the "model_type" field.
+func ModelTypeIn(vs ...consts.ModelType) predicate.Model {
+ v := make([]any, len(vs))
+ for i := range v {
+ v[i] = string(vs[i])
+ }
+ return predicate.Model(sql.FieldIn(FieldModelType, v...))
+}
+
+// ModelTypeNotIn applies the NotIn predicate on the "model_type" field.
+func ModelTypeNotIn(vs ...consts.ModelType) predicate.Model {
+ v := make([]any, len(vs))
+ for i := range v {
+ v[i] = string(vs[i])
+ }
+ return predicate.Model(sql.FieldNotIn(FieldModelType, v...))
+}
+
+// ModelTypeGT applies the GT predicate on the "model_type" field.
+func ModelTypeGT(v consts.ModelType) predicate.Model {
+ vc := string(v)
+ return predicate.Model(sql.FieldGT(FieldModelType, vc))
+}
+
+// ModelTypeGTE applies the GTE predicate on the "model_type" field.
+func ModelTypeGTE(v consts.ModelType) predicate.Model {
+ vc := string(v)
+ return predicate.Model(sql.FieldGTE(FieldModelType, vc))
+}
+
+// ModelTypeLT applies the LT predicate on the "model_type" field.
+func ModelTypeLT(v consts.ModelType) predicate.Model {
+ vc := string(v)
+ return predicate.Model(sql.FieldLT(FieldModelType, vc))
+}
+
+// ModelTypeLTE applies the LTE predicate on the "model_type" field.
+func ModelTypeLTE(v consts.ModelType) predicate.Model {
+ vc := string(v)
+ return predicate.Model(sql.FieldLTE(FieldModelType, vc))
+}
+
+// ModelTypeContains applies the Contains predicate on the "model_type" field.
+func ModelTypeContains(v consts.ModelType) predicate.Model {
+ vc := string(v)
+ return predicate.Model(sql.FieldContains(FieldModelType, vc))
+}
+
+// ModelTypeHasPrefix applies the HasPrefix predicate on the "model_type" field.
+func ModelTypeHasPrefix(v consts.ModelType) predicate.Model {
+ vc := string(v)
+ return predicate.Model(sql.FieldHasPrefix(FieldModelType, vc))
+}
+
+// ModelTypeHasSuffix applies the HasSuffix predicate on the "model_type" field.
+func ModelTypeHasSuffix(v consts.ModelType) predicate.Model {
+ vc := string(v)
+ return predicate.Model(sql.FieldHasSuffix(FieldModelType, vc))
+}
+
+// ModelTypeEqualFold applies the EqualFold predicate on the "model_type" field.
+func ModelTypeEqualFold(v consts.ModelType) predicate.Model {
+ vc := string(v)
+ return predicate.Model(sql.FieldEqualFold(FieldModelType, vc))
+}
+
+// ModelTypeContainsFold applies the ContainsFold predicate on the "model_type" field.
+func ModelTypeContainsFold(v consts.ModelType) predicate.Model {
+ vc := string(v)
+ return predicate.Model(sql.FieldContainsFold(FieldModelType, vc))
+}
+
+// APIBaseEQ applies the EQ predicate on the "api_base" field.
+func APIBaseEQ(v string) predicate.Model {
+ return predicate.Model(sql.FieldEQ(FieldAPIBase, v))
+}
+
+// APIBaseNEQ applies the NEQ predicate on the "api_base" field.
+func APIBaseNEQ(v string) predicate.Model {
+ return predicate.Model(sql.FieldNEQ(FieldAPIBase, v))
+}
+
+// APIBaseIn applies the In predicate on the "api_base" field.
+func APIBaseIn(vs ...string) predicate.Model {
+ return predicate.Model(sql.FieldIn(FieldAPIBase, vs...))
+}
+
+// APIBaseNotIn applies the NotIn predicate on the "api_base" field.
+func APIBaseNotIn(vs ...string) predicate.Model {
+ return predicate.Model(sql.FieldNotIn(FieldAPIBase, vs...))
+}
+
+// APIBaseGT applies the GT predicate on the "api_base" field.
+func APIBaseGT(v string) predicate.Model {
+ return predicate.Model(sql.FieldGT(FieldAPIBase, v))
+}
+
+// APIBaseGTE applies the GTE predicate on the "api_base" field.
+func APIBaseGTE(v string) predicate.Model {
+ return predicate.Model(sql.FieldGTE(FieldAPIBase, v))
+}
+
+// APIBaseLT applies the LT predicate on the "api_base" field.
+func APIBaseLT(v string) predicate.Model {
+ return predicate.Model(sql.FieldLT(FieldAPIBase, v))
+}
+
+// APIBaseLTE applies the LTE predicate on the "api_base" field.
+func APIBaseLTE(v string) predicate.Model {
+ return predicate.Model(sql.FieldLTE(FieldAPIBase, v))
+}
+
+// APIBaseContains applies the Contains predicate on the "api_base" field.
+func APIBaseContains(v string) predicate.Model {
+ return predicate.Model(sql.FieldContains(FieldAPIBase, v))
+}
+
+// APIBaseHasPrefix applies the HasPrefix predicate on the "api_base" field.
+func APIBaseHasPrefix(v string) predicate.Model {
+ return predicate.Model(sql.FieldHasPrefix(FieldAPIBase, v))
+}
+
+// APIBaseHasSuffix applies the HasSuffix predicate on the "api_base" field.
+func APIBaseHasSuffix(v string) predicate.Model {
+ return predicate.Model(sql.FieldHasSuffix(FieldAPIBase, v))
+}
+
+// APIBaseEqualFold applies the EqualFold predicate on the "api_base" field.
+func APIBaseEqualFold(v string) predicate.Model {
+ return predicate.Model(sql.FieldEqualFold(FieldAPIBase, v))
+}
+
+// APIBaseContainsFold applies the ContainsFold predicate on the "api_base" field.
+func APIBaseContainsFold(v string) predicate.Model {
+ return predicate.Model(sql.FieldContainsFold(FieldAPIBase, v))
+}
+
+// APIKeyEQ applies the EQ predicate on the "api_key" field.
+func APIKeyEQ(v string) predicate.Model {
+ return predicate.Model(sql.FieldEQ(FieldAPIKey, v))
+}
+
+// APIKeyNEQ applies the NEQ predicate on the "api_key" field.
+func APIKeyNEQ(v string) predicate.Model {
+ return predicate.Model(sql.FieldNEQ(FieldAPIKey, v))
+}
+
+// APIKeyIn applies the In predicate on the "api_key" field.
+func APIKeyIn(vs ...string) predicate.Model {
+ return predicate.Model(sql.FieldIn(FieldAPIKey, vs...))
+}
+
+// APIKeyNotIn applies the NotIn predicate on the "api_key" field.
+func APIKeyNotIn(vs ...string) predicate.Model {
+ return predicate.Model(sql.FieldNotIn(FieldAPIKey, vs...))
+}
+
+// APIKeyGT applies the GT predicate on the "api_key" field.
+func APIKeyGT(v string) predicate.Model {
+ return predicate.Model(sql.FieldGT(FieldAPIKey, v))
+}
+
+// APIKeyGTE applies the GTE predicate on the "api_key" field.
+func APIKeyGTE(v string) predicate.Model {
+ return predicate.Model(sql.FieldGTE(FieldAPIKey, v))
+}
+
+// APIKeyLT applies the LT predicate on the "api_key" field.
+func APIKeyLT(v string) predicate.Model {
+ return predicate.Model(sql.FieldLT(FieldAPIKey, v))
+}
+
+// APIKeyLTE applies the LTE predicate on the "api_key" field.
+func APIKeyLTE(v string) predicate.Model {
+ return predicate.Model(sql.FieldLTE(FieldAPIKey, v))
+}
+
+// APIKeyContains applies the Contains predicate on the "api_key" field.
+func APIKeyContains(v string) predicate.Model {
+ return predicate.Model(sql.FieldContains(FieldAPIKey, v))
+}
+
+// APIKeyHasPrefix applies the HasPrefix predicate on the "api_key" field.
+func APIKeyHasPrefix(v string) predicate.Model {
+ return predicate.Model(sql.FieldHasPrefix(FieldAPIKey, v))
+}
+
+// APIKeyHasSuffix applies the HasSuffix predicate on the "api_key" field.
+func APIKeyHasSuffix(v string) predicate.Model {
+ return predicate.Model(sql.FieldHasSuffix(FieldAPIKey, v))
+}
+
+// APIKeyEqualFold applies the EqualFold predicate on the "api_key" field.
+func APIKeyEqualFold(v string) predicate.Model {
+ return predicate.Model(sql.FieldEqualFold(FieldAPIKey, v))
+}
+
+// APIKeyContainsFold applies the ContainsFold predicate on the "api_key" field.
+func APIKeyContainsFold(v string) predicate.Model {
+ return predicate.Model(sql.FieldContainsFold(FieldAPIKey, v))
+}
+
+// APIVersionEQ applies the EQ predicate on the "api_version" field.
+func APIVersionEQ(v string) predicate.Model {
+ return predicate.Model(sql.FieldEQ(FieldAPIVersion, v))
+}
+
+// APIVersionNEQ applies the NEQ predicate on the "api_version" field.
+func APIVersionNEQ(v string) predicate.Model {
+ return predicate.Model(sql.FieldNEQ(FieldAPIVersion, v))
+}
+
+// APIVersionIn applies the In predicate on the "api_version" field.
+func APIVersionIn(vs ...string) predicate.Model {
+ return predicate.Model(sql.FieldIn(FieldAPIVersion, vs...))
+}
+
+// APIVersionNotIn applies the NotIn predicate on the "api_version" field.
+func APIVersionNotIn(vs ...string) predicate.Model {
+ return predicate.Model(sql.FieldNotIn(FieldAPIVersion, vs...))
+}
+
+// APIVersionGT applies the GT predicate on the "api_version" field.
+func APIVersionGT(v string) predicate.Model {
+ return predicate.Model(sql.FieldGT(FieldAPIVersion, v))
+}
+
+// APIVersionGTE applies the GTE predicate on the "api_version" field.
+func APIVersionGTE(v string) predicate.Model {
+ return predicate.Model(sql.FieldGTE(FieldAPIVersion, v))
+}
+
+// APIVersionLT applies the LT predicate on the "api_version" field.
+func APIVersionLT(v string) predicate.Model {
+ return predicate.Model(sql.FieldLT(FieldAPIVersion, v))
+}
+
+// APIVersionLTE applies the LTE predicate on the "api_version" field.
+func APIVersionLTE(v string) predicate.Model {
+ return predicate.Model(sql.FieldLTE(FieldAPIVersion, v))
+}
+
+// APIVersionContains applies the Contains predicate on the "api_version" field.
+func APIVersionContains(v string) predicate.Model {
+ return predicate.Model(sql.FieldContains(FieldAPIVersion, v))
+}
+
+// APIVersionHasPrefix applies the HasPrefix predicate on the "api_version" field.
+func APIVersionHasPrefix(v string) predicate.Model {
+ return predicate.Model(sql.FieldHasPrefix(FieldAPIVersion, v))
+}
+
+// APIVersionHasSuffix applies the HasSuffix predicate on the "api_version" field.
+func APIVersionHasSuffix(v string) predicate.Model {
+ return predicate.Model(sql.FieldHasSuffix(FieldAPIVersion, v))
+}
+
+// APIVersionIsNil applies the IsNil predicate on the "api_version" field.
+func APIVersionIsNil() predicate.Model {
+ return predicate.Model(sql.FieldIsNull(FieldAPIVersion))
+}
+
+// APIVersionNotNil applies the NotNil predicate on the "api_version" field.
+func APIVersionNotNil() predicate.Model {
+ return predicate.Model(sql.FieldNotNull(FieldAPIVersion))
+}
+
+// APIVersionEqualFold applies the EqualFold predicate on the "api_version" field.
+func APIVersionEqualFold(v string) predicate.Model {
+ return predicate.Model(sql.FieldEqualFold(FieldAPIVersion, v))
+}
+
+// APIVersionContainsFold applies the ContainsFold predicate on the "api_version" field.
+func APIVersionContainsFold(v string) predicate.Model {
+ return predicate.Model(sql.FieldContainsFold(FieldAPIVersion, v))
+}
+
+// DescriptionEQ applies the EQ predicate on the "description" field.
+func DescriptionEQ(v string) predicate.Model {
+ return predicate.Model(sql.FieldEQ(FieldDescription, v))
+}
+
+// DescriptionNEQ applies the NEQ predicate on the "description" field.
+func DescriptionNEQ(v string) predicate.Model {
+ return predicate.Model(sql.FieldNEQ(FieldDescription, v))
+}
+
+// DescriptionIn applies the In predicate on the "description" field.
+func DescriptionIn(vs ...string) predicate.Model {
+ return predicate.Model(sql.FieldIn(FieldDescription, vs...))
+}
+
+// DescriptionNotIn applies the NotIn predicate on the "description" field.
+func DescriptionNotIn(vs ...string) predicate.Model {
+ return predicate.Model(sql.FieldNotIn(FieldDescription, vs...))
+}
+
+// DescriptionGT applies the GT predicate on the "description" field.
+func DescriptionGT(v string) predicate.Model {
+ return predicate.Model(sql.FieldGT(FieldDescription, v))
+}
+
+// DescriptionGTE applies the GTE predicate on the "description" field.
+func DescriptionGTE(v string) predicate.Model {
+ return predicate.Model(sql.FieldGTE(FieldDescription, v))
+}
+
+// DescriptionLT applies the LT predicate on the "description" field.
+func DescriptionLT(v string) predicate.Model {
+ return predicate.Model(sql.FieldLT(FieldDescription, v))
+}
+
+// DescriptionLTE applies the LTE predicate on the "description" field.
+func DescriptionLTE(v string) predicate.Model {
+ return predicate.Model(sql.FieldLTE(FieldDescription, v))
+}
+
+// DescriptionContains applies the Contains predicate on the "description" field.
+func DescriptionContains(v string) predicate.Model {
+ return predicate.Model(sql.FieldContains(FieldDescription, v))
+}
+
+// DescriptionHasPrefix applies the HasPrefix predicate on the "description" field.
+func DescriptionHasPrefix(v string) predicate.Model {
+ return predicate.Model(sql.FieldHasPrefix(FieldDescription, v))
+}
+
+// DescriptionHasSuffix applies the HasSuffix predicate on the "description" field.
+func DescriptionHasSuffix(v string) predicate.Model {
+ return predicate.Model(sql.FieldHasSuffix(FieldDescription, v))
+}
+
+// DescriptionIsNil applies the IsNil predicate on the "description" field.
+func DescriptionIsNil() predicate.Model {
+ return predicate.Model(sql.FieldIsNull(FieldDescription))
+}
+
+// DescriptionNotNil applies the NotNil predicate on the "description" field.
+func DescriptionNotNil() predicate.Model {
+ return predicate.Model(sql.FieldNotNull(FieldDescription))
+}
+
+// DescriptionEqualFold applies the EqualFold predicate on the "description" field.
+func DescriptionEqualFold(v string) predicate.Model {
+ return predicate.Model(sql.FieldEqualFold(FieldDescription, v))
+}
+
+// DescriptionContainsFold applies the ContainsFold predicate on the "description" field.
+func DescriptionContainsFold(v string) predicate.Model {
+ return predicate.Model(sql.FieldContainsFold(FieldDescription, v))
+}
+
+// ProviderEQ applies the EQ predicate on the "provider" field.
+func ProviderEQ(v string) predicate.Model {
+ return predicate.Model(sql.FieldEQ(FieldProvider, v))
+}
+
+// ProviderNEQ applies the NEQ predicate on the "provider" field.
+func ProviderNEQ(v string) predicate.Model {
+ return predicate.Model(sql.FieldNEQ(FieldProvider, v))
+}
+
+// ProviderIn applies the In predicate on the "provider" field.
+func ProviderIn(vs ...string) predicate.Model {
+ return predicate.Model(sql.FieldIn(FieldProvider, vs...))
+}
+
+// ProviderNotIn applies the NotIn predicate on the "provider" field.
+func ProviderNotIn(vs ...string) predicate.Model {
+ return predicate.Model(sql.FieldNotIn(FieldProvider, vs...))
+}
+
+// ProviderGT applies the GT predicate on the "provider" field.
+func ProviderGT(v string) predicate.Model {
+ return predicate.Model(sql.FieldGT(FieldProvider, v))
+}
+
+// ProviderGTE applies the GTE predicate on the "provider" field.
+func ProviderGTE(v string) predicate.Model {
+ return predicate.Model(sql.FieldGTE(FieldProvider, v))
+}
+
+// ProviderLT applies the LT predicate on the "provider" field.
+func ProviderLT(v string) predicate.Model {
+ return predicate.Model(sql.FieldLT(FieldProvider, v))
+}
+
+// ProviderLTE applies the LTE predicate on the "provider" field.
+func ProviderLTE(v string) predicate.Model {
+ return predicate.Model(sql.FieldLTE(FieldProvider, v))
+}
+
+// ProviderContains applies the Contains predicate on the "provider" field.
+func ProviderContains(v string) predicate.Model {
+ return predicate.Model(sql.FieldContains(FieldProvider, v))
+}
+
+// ProviderHasPrefix applies the HasPrefix predicate on the "provider" field.
+func ProviderHasPrefix(v string) predicate.Model {
+ return predicate.Model(sql.FieldHasPrefix(FieldProvider, v))
+}
+
+// ProviderHasSuffix applies the HasSuffix predicate on the "provider" field.
+func ProviderHasSuffix(v string) predicate.Model {
+ return predicate.Model(sql.FieldHasSuffix(FieldProvider, v))
+}
+
+// ProviderEqualFold applies the EqualFold predicate on the "provider" field.
+func ProviderEqualFold(v string) predicate.Model {
+ return predicate.Model(sql.FieldEqualFold(FieldProvider, v))
+}
+
+// ProviderContainsFold applies the ContainsFold predicate on the "provider" field.
+func ProviderContainsFold(v string) predicate.Model {
+ return predicate.Model(sql.FieldContainsFold(FieldProvider, v))
+}
+
+// StatusEQ applies the EQ predicate on the "status" field.
+func StatusEQ(v consts.ModelStatus) predicate.Model {
+ vc := string(v)
+ return predicate.Model(sql.FieldEQ(FieldStatus, vc))
+}
+
+// StatusNEQ applies the NEQ predicate on the "status" field.
+func StatusNEQ(v consts.ModelStatus) predicate.Model {
+ vc := string(v)
+ return predicate.Model(sql.FieldNEQ(FieldStatus, vc))
+}
+
+// StatusIn applies the In predicate on the "status" field.
+func StatusIn(vs ...consts.ModelStatus) predicate.Model {
+ v := make([]any, len(vs))
+ for i := range v {
+ v[i] = string(vs[i])
+ }
+ return predicate.Model(sql.FieldIn(FieldStatus, v...))
+}
+
+// StatusNotIn applies the NotIn predicate on the "status" field.
+func StatusNotIn(vs ...consts.ModelStatus) predicate.Model {
+ v := make([]any, len(vs))
+ for i := range v {
+ v[i] = string(vs[i])
+ }
+ return predicate.Model(sql.FieldNotIn(FieldStatus, v...))
+}
+
+// StatusGT applies the GT predicate on the "status" field.
+func StatusGT(v consts.ModelStatus) predicate.Model {
+ vc := string(v)
+ return predicate.Model(sql.FieldGT(FieldStatus, vc))
+}
+
+// StatusGTE applies the GTE predicate on the "status" field.
+func StatusGTE(v consts.ModelStatus) predicate.Model {
+ vc := string(v)
+ return predicate.Model(sql.FieldGTE(FieldStatus, vc))
+}
+
+// StatusLT applies the LT predicate on the "status" field.
+func StatusLT(v consts.ModelStatus) predicate.Model {
+ vc := string(v)
+ return predicate.Model(sql.FieldLT(FieldStatus, vc))
+}
+
+// StatusLTE applies the LTE predicate on the "status" field.
+func StatusLTE(v consts.ModelStatus) predicate.Model {
+ vc := string(v)
+ return predicate.Model(sql.FieldLTE(FieldStatus, vc))
+}
+
+// StatusContains applies the Contains predicate on the "status" field.
+func StatusContains(v consts.ModelStatus) predicate.Model {
+ vc := string(v)
+ return predicate.Model(sql.FieldContains(FieldStatus, vc))
+}
+
+// StatusHasPrefix applies the HasPrefix predicate on the "status" field.
+func StatusHasPrefix(v consts.ModelStatus) predicate.Model {
+ vc := string(v)
+ return predicate.Model(sql.FieldHasPrefix(FieldStatus, vc))
+}
+
+// StatusHasSuffix applies the HasSuffix predicate on the "status" field.
+func StatusHasSuffix(v consts.ModelStatus) predicate.Model {
+ vc := string(v)
+ return predicate.Model(sql.FieldHasSuffix(FieldStatus, vc))
+}
+
+// StatusEqualFold applies the EqualFold predicate on the "status" field.
+func StatusEqualFold(v consts.ModelStatus) predicate.Model {
+ vc := string(v)
+ return predicate.Model(sql.FieldEqualFold(FieldStatus, vc))
+}
+
+// StatusContainsFold applies the ContainsFold predicate on the "status" field.
+func StatusContainsFold(v consts.ModelStatus) predicate.Model {
+ vc := string(v)
+ return predicate.Model(sql.FieldContainsFold(FieldStatus, vc))
+}
+
+// ContextLengthEQ applies the EQ predicate on the "context_length" field.
+func ContextLengthEQ(v int) predicate.Model {
+ return predicate.Model(sql.FieldEQ(FieldContextLength, v))
+}
+
+// ContextLengthNEQ applies the NEQ predicate on the "context_length" field.
+func ContextLengthNEQ(v int) predicate.Model {
+ return predicate.Model(sql.FieldNEQ(FieldContextLength, v))
+}
+
+// ContextLengthIn applies the In predicate on the "context_length" field.
+func ContextLengthIn(vs ...int) predicate.Model {
+ return predicate.Model(sql.FieldIn(FieldContextLength, vs...))
+}
+
+// ContextLengthNotIn applies the NotIn predicate on the "context_length" field.
+func ContextLengthNotIn(vs ...int) predicate.Model {
+ return predicate.Model(sql.FieldNotIn(FieldContextLength, vs...))
+}
+
+// ContextLengthGT applies the GT predicate on the "context_length" field.
+func ContextLengthGT(v int) predicate.Model {
+ return predicate.Model(sql.FieldGT(FieldContextLength, v))
+}
+
+// ContextLengthGTE applies the GTE predicate on the "context_length" field.
+func ContextLengthGTE(v int) predicate.Model {
+ return predicate.Model(sql.FieldGTE(FieldContextLength, v))
+}
+
+// ContextLengthLT applies the LT predicate on the "context_length" field.
+func ContextLengthLT(v int) predicate.Model {
+ return predicate.Model(sql.FieldLT(FieldContextLength, v))
+}
+
+// ContextLengthLTE applies the LTE predicate on the "context_length" field.
+func ContextLengthLTE(v int) predicate.Model {
+ return predicate.Model(sql.FieldLTE(FieldContextLength, v))
+}
+
+// ContextLengthIsNil applies the IsNil predicate on the "context_length" field.
+func ContextLengthIsNil() predicate.Model {
+ return predicate.Model(sql.FieldIsNull(FieldContextLength))
+}
+
+// ContextLengthNotNil applies the NotNil predicate on the "context_length" field.
+func ContextLengthNotNil() predicate.Model {
+ return predicate.Model(sql.FieldNotNull(FieldContextLength))
+}
+
+// CreatedAtEQ applies the EQ predicate on the "created_at" field.
+func CreatedAtEQ(v time.Time) predicate.Model {
+ return predicate.Model(sql.FieldEQ(FieldCreatedAt, v))
+}
+
+// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
+func CreatedAtNEQ(v time.Time) predicate.Model {
+ return predicate.Model(sql.FieldNEQ(FieldCreatedAt, v))
+}
+
+// CreatedAtIn applies the In predicate on the "created_at" field.
+func CreatedAtIn(vs ...time.Time) predicate.Model {
+ return predicate.Model(sql.FieldIn(FieldCreatedAt, vs...))
+}
+
+// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
+func CreatedAtNotIn(vs ...time.Time) predicate.Model {
+ return predicate.Model(sql.FieldNotIn(FieldCreatedAt, vs...))
+}
+
+// CreatedAtGT applies the GT predicate on the "created_at" field.
+func CreatedAtGT(v time.Time) predicate.Model {
+ return predicate.Model(sql.FieldGT(FieldCreatedAt, v))
+}
+
+// CreatedAtGTE applies the GTE predicate on the "created_at" field.
+func CreatedAtGTE(v time.Time) predicate.Model {
+ return predicate.Model(sql.FieldGTE(FieldCreatedAt, v))
+}
+
+// CreatedAtLT applies the LT predicate on the "created_at" field.
+func CreatedAtLT(v time.Time) predicate.Model {
+ return predicate.Model(sql.FieldLT(FieldCreatedAt, v))
+}
+
+// CreatedAtLTE applies the LTE predicate on the "created_at" field.
+func CreatedAtLTE(v time.Time) predicate.Model {
+ return predicate.Model(sql.FieldLTE(FieldCreatedAt, v))
+}
+
+// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
+func UpdatedAtEQ(v time.Time) predicate.Model {
+ return predicate.Model(sql.FieldEQ(FieldUpdatedAt, v))
+}
+
+// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
+func UpdatedAtNEQ(v time.Time) predicate.Model {
+ return predicate.Model(sql.FieldNEQ(FieldUpdatedAt, v))
+}
+
+// UpdatedAtIn applies the In predicate on the "updated_at" field.
+func UpdatedAtIn(vs ...time.Time) predicate.Model {
+ return predicate.Model(sql.FieldIn(FieldUpdatedAt, vs...))
+}
+
+// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
+func UpdatedAtNotIn(vs ...time.Time) predicate.Model {
+ return predicate.Model(sql.FieldNotIn(FieldUpdatedAt, vs...))
+}
+
+// UpdatedAtGT applies the GT predicate on the "updated_at" field.
+func UpdatedAtGT(v time.Time) predicate.Model {
+ return predicate.Model(sql.FieldGT(FieldUpdatedAt, v))
+}
+
+// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
+func UpdatedAtGTE(v time.Time) predicate.Model {
+ return predicate.Model(sql.FieldGTE(FieldUpdatedAt, v))
+}
+
+// UpdatedAtLT applies the LT predicate on the "updated_at" field.
+func UpdatedAtLT(v time.Time) predicate.Model {
+ return predicate.Model(sql.FieldLT(FieldUpdatedAt, v))
+}
+
+// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
+func UpdatedAtLTE(v time.Time) predicate.Model {
+ return predicate.Model(sql.FieldLTE(FieldUpdatedAt, v))
+}
+
+// HasRecords applies the HasEdge predicate on the "records" edge.
+func HasRecords() predicate.Model {
+ return predicate.Model(func(s *sql.Selector) {
+ step := sqlgraph.NewStep(
+ sqlgraph.From(Table, FieldID),
+ sqlgraph.Edge(sqlgraph.O2M, false, RecordsTable, RecordsColumn),
+ )
+ sqlgraph.HasNeighbors(s, step)
+ })
+}
+
+// HasRecordsWith applies the HasEdge predicate on the "records" edge with a given conditions (other predicates).
+func HasRecordsWith(preds ...predicate.Record) predicate.Model {
+ return predicate.Model(func(s *sql.Selector) {
+ step := newRecordsStep()
+ sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
+ for _, p := range preds {
+ p(s)
+ }
+ })
+ })
+}
+
+// HasUser applies the HasEdge predicate on the "user" edge.
+func HasUser() predicate.Model {
+ return predicate.Model(func(s *sql.Selector) {
+ step := sqlgraph.NewStep(
+ sqlgraph.From(Table, FieldID),
+ sqlgraph.Edge(sqlgraph.M2O, true, UserTable, UserColumn),
+ )
+ sqlgraph.HasNeighbors(s, step)
+ })
+}
+
+// HasUserWith applies the HasEdge predicate on the "user" edge with a given conditions (other predicates).
+func HasUserWith(preds ...predicate.User) predicate.Model {
+ return predicate.Model(func(s *sql.Selector) {
+ step := newUserStep()
+ sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
+ for _, p := range preds {
+ p(s)
+ }
+ })
+ })
+}
+
+// And groups predicates with the AND operator between them.
+func And(predicates ...predicate.Model) predicate.Model {
+ return predicate.Model(sql.AndPredicates(predicates...))
+}
+
+// Or groups predicates with the OR operator between them.
+func Or(predicates ...predicate.Model) predicate.Model {
+ return predicate.Model(sql.OrPredicates(predicates...))
+}
+
+// Not applies the not operator on the given predicate.
+func Not(p predicate.Model) predicate.Model {
+ return predicate.Model(sql.NotPredicates(p))
+}
diff --git a/backend/db/model_create.go b/backend/db/model_create.go
new file mode 100644
index 0000000..035b6e8
--- /dev/null
+++ b/backend/db/model_create.go
@@ -0,0 +1,1288 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "time"
+
+ "entgo.io/ent/dialect"
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/consts"
+ "github.com/chaitin/MonkeyCode/backend/db/model"
+ "github.com/chaitin/MonkeyCode/backend/db/record"
+ "github.com/chaitin/MonkeyCode/backend/db/user"
+ "github.com/google/uuid"
+)
+
+// ModelCreate is the builder for creating a Model entity.
+type ModelCreate struct {
+ config
+ mutation *ModelMutation
+ hooks []Hook
+ conflict []sql.ConflictOption
+}
+
+// SetUserID sets the "user_id" field.
+func (mc *ModelCreate) SetUserID(u uuid.UUID) *ModelCreate {
+ mc.mutation.SetUserID(u)
+ return mc
+}
+
+// SetNillableUserID sets the "user_id" field if the given value is not nil.
+func (mc *ModelCreate) SetNillableUserID(u *uuid.UUID) *ModelCreate {
+ if u != nil {
+ mc.SetUserID(*u)
+ }
+ return mc
+}
+
+// SetModelName sets the "model_name" field.
+func (mc *ModelCreate) SetModelName(s string) *ModelCreate {
+ mc.mutation.SetModelName(s)
+ return mc
+}
+
+// SetModelType sets the "model_type" field.
+func (mc *ModelCreate) SetModelType(ct consts.ModelType) *ModelCreate {
+ mc.mutation.SetModelType(ct)
+ return mc
+}
+
+// SetAPIBase sets the "api_base" field.
+func (mc *ModelCreate) SetAPIBase(s string) *ModelCreate {
+ mc.mutation.SetAPIBase(s)
+ return mc
+}
+
+// SetAPIKey sets the "api_key" field.
+func (mc *ModelCreate) SetAPIKey(s string) *ModelCreate {
+ mc.mutation.SetAPIKey(s)
+ return mc
+}
+
+// SetAPIVersion sets the "api_version" field.
+func (mc *ModelCreate) SetAPIVersion(s string) *ModelCreate {
+ mc.mutation.SetAPIVersion(s)
+ return mc
+}
+
+// SetNillableAPIVersion sets the "api_version" field if the given value is not nil.
+func (mc *ModelCreate) SetNillableAPIVersion(s *string) *ModelCreate {
+ if s != nil {
+ mc.SetAPIVersion(*s)
+ }
+ return mc
+}
+
+// SetDescription sets the "description" field.
+func (mc *ModelCreate) SetDescription(s string) *ModelCreate {
+ mc.mutation.SetDescription(s)
+ return mc
+}
+
+// SetNillableDescription sets the "description" field if the given value is not nil.
+func (mc *ModelCreate) SetNillableDescription(s *string) *ModelCreate {
+ if s != nil {
+ mc.SetDescription(*s)
+ }
+ return mc
+}
+
+// SetProvider sets the "provider" field.
+func (mc *ModelCreate) SetProvider(s string) *ModelCreate {
+ mc.mutation.SetProvider(s)
+ return mc
+}
+
+// SetStatus sets the "status" field.
+func (mc *ModelCreate) SetStatus(cs consts.ModelStatus) *ModelCreate {
+ mc.mutation.SetStatus(cs)
+ return mc
+}
+
+// SetNillableStatus sets the "status" field if the given value is not nil.
+func (mc *ModelCreate) SetNillableStatus(cs *consts.ModelStatus) *ModelCreate {
+ if cs != nil {
+ mc.SetStatus(*cs)
+ }
+ return mc
+}
+
+// SetContextLength sets the "context_length" field.
+func (mc *ModelCreate) SetContextLength(i int) *ModelCreate {
+ mc.mutation.SetContextLength(i)
+ return mc
+}
+
+// SetNillableContextLength sets the "context_length" field if the given value is not nil.
+func (mc *ModelCreate) SetNillableContextLength(i *int) *ModelCreate {
+ if i != nil {
+ mc.SetContextLength(*i)
+ }
+ return mc
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (mc *ModelCreate) SetCreatedAt(t time.Time) *ModelCreate {
+ mc.mutation.SetCreatedAt(t)
+ return mc
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (mc *ModelCreate) SetNillableCreatedAt(t *time.Time) *ModelCreate {
+ if t != nil {
+ mc.SetCreatedAt(*t)
+ }
+ return mc
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (mc *ModelCreate) SetUpdatedAt(t time.Time) *ModelCreate {
+ mc.mutation.SetUpdatedAt(t)
+ return mc
+}
+
+// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
+func (mc *ModelCreate) SetNillableUpdatedAt(t *time.Time) *ModelCreate {
+ if t != nil {
+ mc.SetUpdatedAt(*t)
+ }
+ return mc
+}
+
+// SetID sets the "id" field.
+func (mc *ModelCreate) SetID(u uuid.UUID) *ModelCreate {
+ mc.mutation.SetID(u)
+ return mc
+}
+
+// AddRecordIDs adds the "records" edge to the Record entity by IDs.
+func (mc *ModelCreate) AddRecordIDs(ids ...uuid.UUID) *ModelCreate {
+ mc.mutation.AddRecordIDs(ids...)
+ return mc
+}
+
+// AddRecords adds the "records" edges to the Record entity.
+func (mc *ModelCreate) AddRecords(r ...*Record) *ModelCreate {
+ ids := make([]uuid.UUID, len(r))
+ for i := range r {
+ ids[i] = r[i].ID
+ }
+ return mc.AddRecordIDs(ids...)
+}
+
+// SetUser sets the "user" edge to the User entity.
+func (mc *ModelCreate) SetUser(u *User) *ModelCreate {
+ return mc.SetUserID(u.ID)
+}
+
+// Mutation returns the ModelMutation object of the builder.
+func (mc *ModelCreate) Mutation() *ModelMutation {
+ return mc.mutation
+}
+
+// Save creates the Model in the database.
+func (mc *ModelCreate) Save(ctx context.Context) (*Model, error) {
+ mc.defaults()
+ return withHooks(ctx, mc.sqlSave, mc.mutation, mc.hooks)
+}
+
+// SaveX calls Save and panics if Save returns an error.
+func (mc *ModelCreate) SaveX(ctx context.Context) *Model {
+ v, err := mc.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return v
+}
+
+// Exec executes the query.
+func (mc *ModelCreate) Exec(ctx context.Context) error {
+ _, err := mc.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (mc *ModelCreate) ExecX(ctx context.Context) {
+ if err := mc.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// defaults sets the default values of the builder before save.
+func (mc *ModelCreate) defaults() {
+ if _, ok := mc.mutation.Status(); !ok {
+ v := model.DefaultStatus
+ mc.mutation.SetStatus(v)
+ }
+ if _, ok := mc.mutation.CreatedAt(); !ok {
+ v := model.DefaultCreatedAt()
+ mc.mutation.SetCreatedAt(v)
+ }
+ if _, ok := mc.mutation.UpdatedAt(); !ok {
+ v := model.DefaultUpdatedAt()
+ mc.mutation.SetUpdatedAt(v)
+ }
+}
+
+// check runs all checks and user-defined validators on the builder.
+func (mc *ModelCreate) check() error {
+ if _, ok := mc.mutation.ModelName(); !ok {
+ return &ValidationError{Name: "model_name", err: errors.New(`db: missing required field "Model.model_name"`)}
+ }
+ if _, ok := mc.mutation.ModelType(); !ok {
+ return &ValidationError{Name: "model_type", err: errors.New(`db: missing required field "Model.model_type"`)}
+ }
+ if _, ok := mc.mutation.APIBase(); !ok {
+ return &ValidationError{Name: "api_base", err: errors.New(`db: missing required field "Model.api_base"`)}
+ }
+ if _, ok := mc.mutation.APIKey(); !ok {
+ return &ValidationError{Name: "api_key", err: errors.New(`db: missing required field "Model.api_key"`)}
+ }
+ if _, ok := mc.mutation.Provider(); !ok {
+ return &ValidationError{Name: "provider", err: errors.New(`db: missing required field "Model.provider"`)}
+ }
+ if _, ok := mc.mutation.Status(); !ok {
+ return &ValidationError{Name: "status", err: errors.New(`db: missing required field "Model.status"`)}
+ }
+ if _, ok := mc.mutation.CreatedAt(); !ok {
+ return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "Model.created_at"`)}
+ }
+ if _, ok := mc.mutation.UpdatedAt(); !ok {
+ return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "Model.updated_at"`)}
+ }
+ return nil
+}
+
+func (mc *ModelCreate) sqlSave(ctx context.Context) (*Model, error) {
+ if err := mc.check(); err != nil {
+ return nil, err
+ }
+ _node, _spec := mc.createSpec()
+ if err := sqlgraph.CreateNode(ctx, mc.driver, _spec); err != nil {
+ if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return nil, err
+ }
+ if _spec.ID.Value != nil {
+ if id, ok := _spec.ID.Value.(*uuid.UUID); ok {
+ _node.ID = *id
+ } else if err := _node.ID.Scan(_spec.ID.Value); err != nil {
+ return nil, err
+ }
+ }
+ mc.mutation.id = &_node.ID
+ mc.mutation.done = true
+ return _node, nil
+}
+
+func (mc *ModelCreate) createSpec() (*Model, *sqlgraph.CreateSpec) {
+ var (
+ _node = &Model{config: mc.config}
+ _spec = sqlgraph.NewCreateSpec(model.Table, sqlgraph.NewFieldSpec(model.FieldID, field.TypeUUID))
+ )
+ _spec.OnConflict = mc.conflict
+ if id, ok := mc.mutation.ID(); ok {
+ _node.ID = id
+ _spec.ID.Value = &id
+ }
+ if value, ok := mc.mutation.ModelName(); ok {
+ _spec.SetField(model.FieldModelName, field.TypeString, value)
+ _node.ModelName = value
+ }
+ if value, ok := mc.mutation.ModelType(); ok {
+ _spec.SetField(model.FieldModelType, field.TypeString, value)
+ _node.ModelType = value
+ }
+ if value, ok := mc.mutation.APIBase(); ok {
+ _spec.SetField(model.FieldAPIBase, field.TypeString, value)
+ _node.APIBase = value
+ }
+ if value, ok := mc.mutation.APIKey(); ok {
+ _spec.SetField(model.FieldAPIKey, field.TypeString, value)
+ _node.APIKey = value
+ }
+ if value, ok := mc.mutation.APIVersion(); ok {
+ _spec.SetField(model.FieldAPIVersion, field.TypeString, value)
+ _node.APIVersion = value
+ }
+ if value, ok := mc.mutation.Description(); ok {
+ _spec.SetField(model.FieldDescription, field.TypeString, value)
+ _node.Description = value
+ }
+ if value, ok := mc.mutation.Provider(); ok {
+ _spec.SetField(model.FieldProvider, field.TypeString, value)
+ _node.Provider = value
+ }
+ if value, ok := mc.mutation.Status(); ok {
+ _spec.SetField(model.FieldStatus, field.TypeString, value)
+ _node.Status = value
+ }
+ if value, ok := mc.mutation.ContextLength(); ok {
+ _spec.SetField(model.FieldContextLength, field.TypeInt, value)
+ _node.ContextLength = value
+ }
+ if value, ok := mc.mutation.CreatedAt(); ok {
+ _spec.SetField(model.FieldCreatedAt, field.TypeTime, value)
+ _node.CreatedAt = value
+ }
+ if value, ok := mc.mutation.UpdatedAt(); ok {
+ _spec.SetField(model.FieldUpdatedAt, field.TypeTime, value)
+ _node.UpdatedAt = value
+ }
+ if nodes := mc.mutation.RecordsIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: model.RecordsTable,
+ Columns: []string{model.RecordsColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(record.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges = append(_spec.Edges, edge)
+ }
+ if nodes := mc.mutation.UserIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: true,
+ Table: model.UserTable,
+ Columns: []string{model.UserColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _node.UserID = nodes[0]
+ _spec.Edges = append(_spec.Edges, edge)
+ }
+ return _node, _spec
+}
+
+// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
+// of the `INSERT` statement. For example:
+//
+// client.Model.Create().
+// SetUserID(v).
+// OnConflict(
+// // Update the row with the new values
+// // the was proposed for insertion.
+// sql.ResolveWithNewValues(),
+// ).
+// // Override some of the fields with custom
+// // update values.
+// Update(func(u *ent.ModelUpsert) {
+// SetUserID(v+v).
+// }).
+// Exec(ctx)
+func (mc *ModelCreate) OnConflict(opts ...sql.ConflictOption) *ModelUpsertOne {
+ mc.conflict = opts
+ return &ModelUpsertOne{
+ create: mc,
+ }
+}
+
+// OnConflictColumns calls `OnConflict` and configures the columns
+// as conflict target. Using this option is equivalent to using:
+//
+// client.Model.Create().
+// OnConflict(sql.ConflictColumns(columns...)).
+// Exec(ctx)
+func (mc *ModelCreate) OnConflictColumns(columns ...string) *ModelUpsertOne {
+ mc.conflict = append(mc.conflict, sql.ConflictColumns(columns...))
+ return &ModelUpsertOne{
+ create: mc,
+ }
+}
+
+type (
+ // ModelUpsertOne is the builder for "upsert"-ing
+ // one Model node.
+ ModelUpsertOne struct {
+ create *ModelCreate
+ }
+
+ // ModelUpsert is the "OnConflict" setter.
+ ModelUpsert struct {
+ *sql.UpdateSet
+ }
+)
+
+// SetUserID sets the "user_id" field.
+func (u *ModelUpsert) SetUserID(v uuid.UUID) *ModelUpsert {
+ u.Set(model.FieldUserID, v)
+ return u
+}
+
+// UpdateUserID sets the "user_id" field to the value that was provided on create.
+func (u *ModelUpsert) UpdateUserID() *ModelUpsert {
+ u.SetExcluded(model.FieldUserID)
+ return u
+}
+
+// ClearUserID clears the value of the "user_id" field.
+func (u *ModelUpsert) ClearUserID() *ModelUpsert {
+ u.SetNull(model.FieldUserID)
+ return u
+}
+
+// SetModelName sets the "model_name" field.
+func (u *ModelUpsert) SetModelName(v string) *ModelUpsert {
+ u.Set(model.FieldModelName, v)
+ return u
+}
+
+// UpdateModelName sets the "model_name" field to the value that was provided on create.
+func (u *ModelUpsert) UpdateModelName() *ModelUpsert {
+ u.SetExcluded(model.FieldModelName)
+ return u
+}
+
+// SetModelType sets the "model_type" field.
+func (u *ModelUpsert) SetModelType(v consts.ModelType) *ModelUpsert {
+ u.Set(model.FieldModelType, v)
+ return u
+}
+
+// UpdateModelType sets the "model_type" field to the value that was provided on create.
+func (u *ModelUpsert) UpdateModelType() *ModelUpsert {
+ u.SetExcluded(model.FieldModelType)
+ return u
+}
+
+// SetAPIBase sets the "api_base" field.
+func (u *ModelUpsert) SetAPIBase(v string) *ModelUpsert {
+ u.Set(model.FieldAPIBase, v)
+ return u
+}
+
+// UpdateAPIBase sets the "api_base" field to the value that was provided on create.
+func (u *ModelUpsert) UpdateAPIBase() *ModelUpsert {
+ u.SetExcluded(model.FieldAPIBase)
+ return u
+}
+
+// SetAPIKey sets the "api_key" field.
+func (u *ModelUpsert) SetAPIKey(v string) *ModelUpsert {
+ u.Set(model.FieldAPIKey, v)
+ return u
+}
+
+// UpdateAPIKey sets the "api_key" field to the value that was provided on create.
+func (u *ModelUpsert) UpdateAPIKey() *ModelUpsert {
+ u.SetExcluded(model.FieldAPIKey)
+ return u
+}
+
+// SetAPIVersion sets the "api_version" field.
+func (u *ModelUpsert) SetAPIVersion(v string) *ModelUpsert {
+ u.Set(model.FieldAPIVersion, v)
+ return u
+}
+
+// UpdateAPIVersion sets the "api_version" field to the value that was provided on create.
+func (u *ModelUpsert) UpdateAPIVersion() *ModelUpsert {
+ u.SetExcluded(model.FieldAPIVersion)
+ return u
+}
+
+// ClearAPIVersion clears the value of the "api_version" field.
+func (u *ModelUpsert) ClearAPIVersion() *ModelUpsert {
+ u.SetNull(model.FieldAPIVersion)
+ return u
+}
+
+// SetDescription sets the "description" field.
+func (u *ModelUpsert) SetDescription(v string) *ModelUpsert {
+ u.Set(model.FieldDescription, v)
+ return u
+}
+
+// UpdateDescription sets the "description" field to the value that was provided on create.
+func (u *ModelUpsert) UpdateDescription() *ModelUpsert {
+ u.SetExcluded(model.FieldDescription)
+ return u
+}
+
+// ClearDescription clears the value of the "description" field.
+func (u *ModelUpsert) ClearDescription() *ModelUpsert {
+ u.SetNull(model.FieldDescription)
+ return u
+}
+
+// SetProvider sets the "provider" field.
+func (u *ModelUpsert) SetProvider(v string) *ModelUpsert {
+ u.Set(model.FieldProvider, v)
+ return u
+}
+
+// UpdateProvider sets the "provider" field to the value that was provided on create.
+func (u *ModelUpsert) UpdateProvider() *ModelUpsert {
+ u.SetExcluded(model.FieldProvider)
+ return u
+}
+
+// SetStatus sets the "status" field.
+func (u *ModelUpsert) SetStatus(v consts.ModelStatus) *ModelUpsert {
+ u.Set(model.FieldStatus, v)
+ return u
+}
+
+// UpdateStatus sets the "status" field to the value that was provided on create.
+func (u *ModelUpsert) UpdateStatus() *ModelUpsert {
+ u.SetExcluded(model.FieldStatus)
+ return u
+}
+
+// SetContextLength sets the "context_length" field.
+func (u *ModelUpsert) SetContextLength(v int) *ModelUpsert {
+ u.Set(model.FieldContextLength, v)
+ return u
+}
+
+// UpdateContextLength sets the "context_length" field to the value that was provided on create.
+func (u *ModelUpsert) UpdateContextLength() *ModelUpsert {
+ u.SetExcluded(model.FieldContextLength)
+ return u
+}
+
+// AddContextLength adds v to the "context_length" field.
+func (u *ModelUpsert) AddContextLength(v int) *ModelUpsert {
+ u.Add(model.FieldContextLength, v)
+ return u
+}
+
+// ClearContextLength clears the value of the "context_length" field.
+func (u *ModelUpsert) ClearContextLength() *ModelUpsert {
+ u.SetNull(model.FieldContextLength)
+ return u
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (u *ModelUpsert) SetCreatedAt(v time.Time) *ModelUpsert {
+ u.Set(model.FieldCreatedAt, v)
+ return u
+}
+
+// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
+func (u *ModelUpsert) UpdateCreatedAt() *ModelUpsert {
+ u.SetExcluded(model.FieldCreatedAt)
+ return u
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (u *ModelUpsert) SetUpdatedAt(v time.Time) *ModelUpsert {
+ u.Set(model.FieldUpdatedAt, v)
+ return u
+}
+
+// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
+func (u *ModelUpsert) UpdateUpdatedAt() *ModelUpsert {
+ u.SetExcluded(model.FieldUpdatedAt)
+ return u
+}
+
+// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field.
+// Using this option is equivalent to using:
+//
+// client.Model.Create().
+// OnConflict(
+// sql.ResolveWithNewValues(),
+// sql.ResolveWith(func(u *sql.UpdateSet) {
+// u.SetIgnore(model.FieldID)
+// }),
+// ).
+// Exec(ctx)
+func (u *ModelUpsertOne) UpdateNewValues() *ModelUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
+ if _, exists := u.create.mutation.ID(); exists {
+ s.SetIgnore(model.FieldID)
+ }
+ }))
+ return u
+}
+
+// Ignore sets each column to itself in case of conflict.
+// Using this option is equivalent to using:
+//
+// client.Model.Create().
+// OnConflict(sql.ResolveWithIgnore()).
+// Exec(ctx)
+func (u *ModelUpsertOne) Ignore() *ModelUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
+ return u
+}
+
+// DoNothing configures the conflict_action to `DO NOTHING`.
+// Supported only by SQLite and PostgreSQL.
+func (u *ModelUpsertOne) DoNothing() *ModelUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.DoNothing())
+ return u
+}
+
+// Update allows overriding fields `UPDATE` values. See the ModelCreate.OnConflict
+// documentation for more info.
+func (u *ModelUpsertOne) Update(set func(*ModelUpsert)) *ModelUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
+ set(&ModelUpsert{UpdateSet: update})
+ }))
+ return u
+}
+
+// SetUserID sets the "user_id" field.
+func (u *ModelUpsertOne) SetUserID(v uuid.UUID) *ModelUpsertOne {
+ return u.Update(func(s *ModelUpsert) {
+ s.SetUserID(v)
+ })
+}
+
+// UpdateUserID sets the "user_id" field to the value that was provided on create.
+func (u *ModelUpsertOne) UpdateUserID() *ModelUpsertOne {
+ return u.Update(func(s *ModelUpsert) {
+ s.UpdateUserID()
+ })
+}
+
+// ClearUserID clears the value of the "user_id" field.
+func (u *ModelUpsertOne) ClearUserID() *ModelUpsertOne {
+ return u.Update(func(s *ModelUpsert) {
+ s.ClearUserID()
+ })
+}
+
+// SetModelName sets the "model_name" field.
+func (u *ModelUpsertOne) SetModelName(v string) *ModelUpsertOne {
+ return u.Update(func(s *ModelUpsert) {
+ s.SetModelName(v)
+ })
+}
+
+// UpdateModelName sets the "model_name" field to the value that was provided on create.
+func (u *ModelUpsertOne) UpdateModelName() *ModelUpsertOne {
+ return u.Update(func(s *ModelUpsert) {
+ s.UpdateModelName()
+ })
+}
+
+// SetModelType sets the "model_type" field.
+func (u *ModelUpsertOne) SetModelType(v consts.ModelType) *ModelUpsertOne {
+ return u.Update(func(s *ModelUpsert) {
+ s.SetModelType(v)
+ })
+}
+
+// UpdateModelType sets the "model_type" field to the value that was provided on create.
+func (u *ModelUpsertOne) UpdateModelType() *ModelUpsertOne {
+ return u.Update(func(s *ModelUpsert) {
+ s.UpdateModelType()
+ })
+}
+
+// SetAPIBase sets the "api_base" field.
+func (u *ModelUpsertOne) SetAPIBase(v string) *ModelUpsertOne {
+ return u.Update(func(s *ModelUpsert) {
+ s.SetAPIBase(v)
+ })
+}
+
+// UpdateAPIBase sets the "api_base" field to the value that was provided on create.
+func (u *ModelUpsertOne) UpdateAPIBase() *ModelUpsertOne {
+ return u.Update(func(s *ModelUpsert) {
+ s.UpdateAPIBase()
+ })
+}
+
+// SetAPIKey sets the "api_key" field.
+func (u *ModelUpsertOne) SetAPIKey(v string) *ModelUpsertOne {
+ return u.Update(func(s *ModelUpsert) {
+ s.SetAPIKey(v)
+ })
+}
+
+// UpdateAPIKey sets the "api_key" field to the value that was provided on create.
+func (u *ModelUpsertOne) UpdateAPIKey() *ModelUpsertOne {
+ return u.Update(func(s *ModelUpsert) {
+ s.UpdateAPIKey()
+ })
+}
+
+// SetAPIVersion sets the "api_version" field.
+func (u *ModelUpsertOne) SetAPIVersion(v string) *ModelUpsertOne {
+ return u.Update(func(s *ModelUpsert) {
+ s.SetAPIVersion(v)
+ })
+}
+
+// UpdateAPIVersion sets the "api_version" field to the value that was provided on create.
+func (u *ModelUpsertOne) UpdateAPIVersion() *ModelUpsertOne {
+ return u.Update(func(s *ModelUpsert) {
+ s.UpdateAPIVersion()
+ })
+}
+
+// ClearAPIVersion clears the value of the "api_version" field.
+func (u *ModelUpsertOne) ClearAPIVersion() *ModelUpsertOne {
+ return u.Update(func(s *ModelUpsert) {
+ s.ClearAPIVersion()
+ })
+}
+
+// SetDescription sets the "description" field.
+func (u *ModelUpsertOne) SetDescription(v string) *ModelUpsertOne {
+ return u.Update(func(s *ModelUpsert) {
+ s.SetDescription(v)
+ })
+}
+
+// UpdateDescription sets the "description" field to the value that was provided on create.
+func (u *ModelUpsertOne) UpdateDescription() *ModelUpsertOne {
+ return u.Update(func(s *ModelUpsert) {
+ s.UpdateDescription()
+ })
+}
+
+// ClearDescription clears the value of the "description" field.
+func (u *ModelUpsertOne) ClearDescription() *ModelUpsertOne {
+ return u.Update(func(s *ModelUpsert) {
+ s.ClearDescription()
+ })
+}
+
+// SetProvider sets the "provider" field.
+func (u *ModelUpsertOne) SetProvider(v string) *ModelUpsertOne {
+ return u.Update(func(s *ModelUpsert) {
+ s.SetProvider(v)
+ })
+}
+
+// UpdateProvider sets the "provider" field to the value that was provided on create.
+func (u *ModelUpsertOne) UpdateProvider() *ModelUpsertOne {
+ return u.Update(func(s *ModelUpsert) {
+ s.UpdateProvider()
+ })
+}
+
+// SetStatus sets the "status" field.
+func (u *ModelUpsertOne) SetStatus(v consts.ModelStatus) *ModelUpsertOne {
+ return u.Update(func(s *ModelUpsert) {
+ s.SetStatus(v)
+ })
+}
+
+// UpdateStatus sets the "status" field to the value that was provided on create.
+func (u *ModelUpsertOne) UpdateStatus() *ModelUpsertOne {
+ return u.Update(func(s *ModelUpsert) {
+ s.UpdateStatus()
+ })
+}
+
+// SetContextLength sets the "context_length" field.
+func (u *ModelUpsertOne) SetContextLength(v int) *ModelUpsertOne {
+ return u.Update(func(s *ModelUpsert) {
+ s.SetContextLength(v)
+ })
+}
+
+// AddContextLength adds v to the "context_length" field.
+func (u *ModelUpsertOne) AddContextLength(v int) *ModelUpsertOne {
+ return u.Update(func(s *ModelUpsert) {
+ s.AddContextLength(v)
+ })
+}
+
+// UpdateContextLength sets the "context_length" field to the value that was provided on create.
+func (u *ModelUpsertOne) UpdateContextLength() *ModelUpsertOne {
+ return u.Update(func(s *ModelUpsert) {
+ s.UpdateContextLength()
+ })
+}
+
+// ClearContextLength clears the value of the "context_length" field.
+func (u *ModelUpsertOne) ClearContextLength() *ModelUpsertOne {
+ return u.Update(func(s *ModelUpsert) {
+ s.ClearContextLength()
+ })
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (u *ModelUpsertOne) SetCreatedAt(v time.Time) *ModelUpsertOne {
+ return u.Update(func(s *ModelUpsert) {
+ s.SetCreatedAt(v)
+ })
+}
+
+// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
+func (u *ModelUpsertOne) UpdateCreatedAt() *ModelUpsertOne {
+ return u.Update(func(s *ModelUpsert) {
+ s.UpdateCreatedAt()
+ })
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (u *ModelUpsertOne) SetUpdatedAt(v time.Time) *ModelUpsertOne {
+ return u.Update(func(s *ModelUpsert) {
+ s.SetUpdatedAt(v)
+ })
+}
+
+// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
+func (u *ModelUpsertOne) UpdateUpdatedAt() *ModelUpsertOne {
+ return u.Update(func(s *ModelUpsert) {
+ s.UpdateUpdatedAt()
+ })
+}
+
+// Exec executes the query.
+func (u *ModelUpsertOne) Exec(ctx context.Context) error {
+ if len(u.create.conflict) == 0 {
+ return errors.New("db: missing options for ModelCreate.OnConflict")
+ }
+ return u.create.Exec(ctx)
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (u *ModelUpsertOne) ExecX(ctx context.Context) {
+ if err := u.create.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// Exec executes the UPSERT query and returns the inserted/updated ID.
+func (u *ModelUpsertOne) ID(ctx context.Context) (id uuid.UUID, err error) {
+ if u.create.driver.Dialect() == dialect.MySQL {
+ // In case of "ON CONFLICT", there is no way to get back non-numeric ID
+ // fields from the database since MySQL does not support the RETURNING clause.
+ return id, errors.New("db: ModelUpsertOne.ID is not supported by MySQL driver. Use ModelUpsertOne.Exec instead")
+ }
+ node, err := u.create.Save(ctx)
+ if err != nil {
+ return id, err
+ }
+ return node.ID, nil
+}
+
+// IDX is like ID, but panics if an error occurs.
+func (u *ModelUpsertOne) IDX(ctx context.Context) uuid.UUID {
+ id, err := u.ID(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return id
+}
+
+// ModelCreateBulk is the builder for creating many Model entities in bulk.
+type ModelCreateBulk struct {
+ config
+ err error
+ builders []*ModelCreate
+ conflict []sql.ConflictOption
+}
+
+// Save creates the Model entities in the database.
+func (mcb *ModelCreateBulk) Save(ctx context.Context) ([]*Model, error) {
+ if mcb.err != nil {
+ return nil, mcb.err
+ }
+ specs := make([]*sqlgraph.CreateSpec, len(mcb.builders))
+ nodes := make([]*Model, len(mcb.builders))
+ mutators := make([]Mutator, len(mcb.builders))
+ for i := range mcb.builders {
+ func(i int, root context.Context) {
+ builder := mcb.builders[i]
+ builder.defaults()
+ var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
+ mutation, ok := m.(*ModelMutation)
+ if !ok {
+ return nil, fmt.Errorf("unexpected mutation type %T", m)
+ }
+ if err := builder.check(); err != nil {
+ return nil, err
+ }
+ builder.mutation = mutation
+ var err error
+ nodes[i], specs[i] = builder.createSpec()
+ if i < len(mutators)-1 {
+ _, err = mutators[i+1].Mutate(root, mcb.builders[i+1].mutation)
+ } else {
+ spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
+ spec.OnConflict = mcb.conflict
+ // Invoke the actual operation on the latest mutation in the chain.
+ if err = sqlgraph.BatchCreate(ctx, mcb.driver, spec); err != nil {
+ if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ }
+ }
+ if err != nil {
+ return nil, err
+ }
+ mutation.id = &nodes[i].ID
+ mutation.done = true
+ return nodes[i], nil
+ })
+ for i := len(builder.hooks) - 1; i >= 0; i-- {
+ mut = builder.hooks[i](mut)
+ }
+ mutators[i] = mut
+ }(i, ctx)
+ }
+ if len(mutators) > 0 {
+ if _, err := mutators[0].Mutate(ctx, mcb.builders[0].mutation); err != nil {
+ return nil, err
+ }
+ }
+ return nodes, nil
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (mcb *ModelCreateBulk) SaveX(ctx context.Context) []*Model {
+ v, err := mcb.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return v
+}
+
+// Exec executes the query.
+func (mcb *ModelCreateBulk) Exec(ctx context.Context) error {
+ _, err := mcb.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (mcb *ModelCreateBulk) ExecX(ctx context.Context) {
+ if err := mcb.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
+// of the `INSERT` statement. For example:
+//
+// client.Model.CreateBulk(builders...).
+// OnConflict(
+// // Update the row with the new values
+// // the was proposed for insertion.
+// sql.ResolveWithNewValues(),
+// ).
+// // Override some of the fields with custom
+// // update values.
+// Update(func(u *ent.ModelUpsert) {
+// SetUserID(v+v).
+// }).
+// Exec(ctx)
+func (mcb *ModelCreateBulk) OnConflict(opts ...sql.ConflictOption) *ModelUpsertBulk {
+ mcb.conflict = opts
+ return &ModelUpsertBulk{
+ create: mcb,
+ }
+}
+
+// OnConflictColumns calls `OnConflict` and configures the columns
+// as conflict target. Using this option is equivalent to using:
+//
+// client.Model.Create().
+// OnConflict(sql.ConflictColumns(columns...)).
+// Exec(ctx)
+func (mcb *ModelCreateBulk) OnConflictColumns(columns ...string) *ModelUpsertBulk {
+ mcb.conflict = append(mcb.conflict, sql.ConflictColumns(columns...))
+ return &ModelUpsertBulk{
+ create: mcb,
+ }
+}
+
+// ModelUpsertBulk is the builder for "upsert"-ing
+// a bulk of Model nodes.
+type ModelUpsertBulk struct {
+ create *ModelCreateBulk
+}
+
+// UpdateNewValues updates the mutable fields using the new values that
+// were set on create. Using this option is equivalent to using:
+//
+// client.Model.Create().
+// OnConflict(
+// sql.ResolveWithNewValues(),
+// sql.ResolveWith(func(u *sql.UpdateSet) {
+// u.SetIgnore(model.FieldID)
+// }),
+// ).
+// Exec(ctx)
+func (u *ModelUpsertBulk) UpdateNewValues() *ModelUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
+ for _, b := range u.create.builders {
+ if _, exists := b.mutation.ID(); exists {
+ s.SetIgnore(model.FieldID)
+ }
+ }
+ }))
+ return u
+}
+
+// Ignore sets each column to itself in case of conflict.
+// Using this option is equivalent to using:
+//
+// client.Model.Create().
+// OnConflict(sql.ResolveWithIgnore()).
+// Exec(ctx)
+func (u *ModelUpsertBulk) Ignore() *ModelUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
+ return u
+}
+
+// DoNothing configures the conflict_action to `DO NOTHING`.
+// Supported only by SQLite and PostgreSQL.
+func (u *ModelUpsertBulk) DoNothing() *ModelUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.DoNothing())
+ return u
+}
+
+// Update allows overriding fields `UPDATE` values. See the ModelCreateBulk.OnConflict
+// documentation for more info.
+func (u *ModelUpsertBulk) Update(set func(*ModelUpsert)) *ModelUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
+ set(&ModelUpsert{UpdateSet: update})
+ }))
+ return u
+}
+
+// SetUserID sets the "user_id" field.
+func (u *ModelUpsertBulk) SetUserID(v uuid.UUID) *ModelUpsertBulk {
+ return u.Update(func(s *ModelUpsert) {
+ s.SetUserID(v)
+ })
+}
+
+// UpdateUserID sets the "user_id" field to the value that was provided on create.
+func (u *ModelUpsertBulk) UpdateUserID() *ModelUpsertBulk {
+ return u.Update(func(s *ModelUpsert) {
+ s.UpdateUserID()
+ })
+}
+
+// ClearUserID clears the value of the "user_id" field.
+func (u *ModelUpsertBulk) ClearUserID() *ModelUpsertBulk {
+ return u.Update(func(s *ModelUpsert) {
+ s.ClearUserID()
+ })
+}
+
+// SetModelName sets the "model_name" field.
+func (u *ModelUpsertBulk) SetModelName(v string) *ModelUpsertBulk {
+ return u.Update(func(s *ModelUpsert) {
+ s.SetModelName(v)
+ })
+}
+
+// UpdateModelName sets the "model_name" field to the value that was provided on create.
+func (u *ModelUpsertBulk) UpdateModelName() *ModelUpsertBulk {
+ return u.Update(func(s *ModelUpsert) {
+ s.UpdateModelName()
+ })
+}
+
+// SetModelType sets the "model_type" field.
+func (u *ModelUpsertBulk) SetModelType(v consts.ModelType) *ModelUpsertBulk {
+ return u.Update(func(s *ModelUpsert) {
+ s.SetModelType(v)
+ })
+}
+
+// UpdateModelType sets the "model_type" field to the value that was provided on create.
+func (u *ModelUpsertBulk) UpdateModelType() *ModelUpsertBulk {
+ return u.Update(func(s *ModelUpsert) {
+ s.UpdateModelType()
+ })
+}
+
+// SetAPIBase sets the "api_base" field.
+func (u *ModelUpsertBulk) SetAPIBase(v string) *ModelUpsertBulk {
+ return u.Update(func(s *ModelUpsert) {
+ s.SetAPIBase(v)
+ })
+}
+
+// UpdateAPIBase sets the "api_base" field to the value that was provided on create.
+func (u *ModelUpsertBulk) UpdateAPIBase() *ModelUpsertBulk {
+ return u.Update(func(s *ModelUpsert) {
+ s.UpdateAPIBase()
+ })
+}
+
+// SetAPIKey sets the "api_key" field.
+func (u *ModelUpsertBulk) SetAPIKey(v string) *ModelUpsertBulk {
+ return u.Update(func(s *ModelUpsert) {
+ s.SetAPIKey(v)
+ })
+}
+
+// UpdateAPIKey sets the "api_key" field to the value that was provided on create.
+func (u *ModelUpsertBulk) UpdateAPIKey() *ModelUpsertBulk {
+ return u.Update(func(s *ModelUpsert) {
+ s.UpdateAPIKey()
+ })
+}
+
+// SetAPIVersion sets the "api_version" field.
+func (u *ModelUpsertBulk) SetAPIVersion(v string) *ModelUpsertBulk {
+ return u.Update(func(s *ModelUpsert) {
+ s.SetAPIVersion(v)
+ })
+}
+
+// UpdateAPIVersion sets the "api_version" field to the value that was provided on create.
+func (u *ModelUpsertBulk) UpdateAPIVersion() *ModelUpsertBulk {
+ return u.Update(func(s *ModelUpsert) {
+ s.UpdateAPIVersion()
+ })
+}
+
+// ClearAPIVersion clears the value of the "api_version" field.
+func (u *ModelUpsertBulk) ClearAPIVersion() *ModelUpsertBulk {
+ return u.Update(func(s *ModelUpsert) {
+ s.ClearAPIVersion()
+ })
+}
+
+// SetDescription sets the "description" field.
+func (u *ModelUpsertBulk) SetDescription(v string) *ModelUpsertBulk {
+ return u.Update(func(s *ModelUpsert) {
+ s.SetDescription(v)
+ })
+}
+
+// UpdateDescription sets the "description" field to the value that was provided on create.
+func (u *ModelUpsertBulk) UpdateDescription() *ModelUpsertBulk {
+ return u.Update(func(s *ModelUpsert) {
+ s.UpdateDescription()
+ })
+}
+
+// ClearDescription clears the value of the "description" field.
+func (u *ModelUpsertBulk) ClearDescription() *ModelUpsertBulk {
+ return u.Update(func(s *ModelUpsert) {
+ s.ClearDescription()
+ })
+}
+
+// SetProvider sets the "provider" field.
+func (u *ModelUpsertBulk) SetProvider(v string) *ModelUpsertBulk {
+ return u.Update(func(s *ModelUpsert) {
+ s.SetProvider(v)
+ })
+}
+
+// UpdateProvider sets the "provider" field to the value that was provided on create.
+func (u *ModelUpsertBulk) UpdateProvider() *ModelUpsertBulk {
+ return u.Update(func(s *ModelUpsert) {
+ s.UpdateProvider()
+ })
+}
+
+// SetStatus sets the "status" field.
+func (u *ModelUpsertBulk) SetStatus(v consts.ModelStatus) *ModelUpsertBulk {
+ return u.Update(func(s *ModelUpsert) {
+ s.SetStatus(v)
+ })
+}
+
+// UpdateStatus sets the "status" field to the value that was provided on create.
+func (u *ModelUpsertBulk) UpdateStatus() *ModelUpsertBulk {
+ return u.Update(func(s *ModelUpsert) {
+ s.UpdateStatus()
+ })
+}
+
+// SetContextLength sets the "context_length" field.
+func (u *ModelUpsertBulk) SetContextLength(v int) *ModelUpsertBulk {
+ return u.Update(func(s *ModelUpsert) {
+ s.SetContextLength(v)
+ })
+}
+
+// AddContextLength adds v to the "context_length" field.
+func (u *ModelUpsertBulk) AddContextLength(v int) *ModelUpsertBulk {
+ return u.Update(func(s *ModelUpsert) {
+ s.AddContextLength(v)
+ })
+}
+
+// UpdateContextLength sets the "context_length" field to the value that was provided on create.
+func (u *ModelUpsertBulk) UpdateContextLength() *ModelUpsertBulk {
+ return u.Update(func(s *ModelUpsert) {
+ s.UpdateContextLength()
+ })
+}
+
+// ClearContextLength clears the value of the "context_length" field.
+func (u *ModelUpsertBulk) ClearContextLength() *ModelUpsertBulk {
+ return u.Update(func(s *ModelUpsert) {
+ s.ClearContextLength()
+ })
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (u *ModelUpsertBulk) SetCreatedAt(v time.Time) *ModelUpsertBulk {
+ return u.Update(func(s *ModelUpsert) {
+ s.SetCreatedAt(v)
+ })
+}
+
+// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
+func (u *ModelUpsertBulk) UpdateCreatedAt() *ModelUpsertBulk {
+ return u.Update(func(s *ModelUpsert) {
+ s.UpdateCreatedAt()
+ })
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (u *ModelUpsertBulk) SetUpdatedAt(v time.Time) *ModelUpsertBulk {
+ return u.Update(func(s *ModelUpsert) {
+ s.SetUpdatedAt(v)
+ })
+}
+
+// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
+func (u *ModelUpsertBulk) UpdateUpdatedAt() *ModelUpsertBulk {
+ return u.Update(func(s *ModelUpsert) {
+ s.UpdateUpdatedAt()
+ })
+}
+
+// Exec executes the query.
+func (u *ModelUpsertBulk) Exec(ctx context.Context) error {
+ if u.create.err != nil {
+ return u.create.err
+ }
+ for i, b := range u.create.builders {
+ if len(b.conflict) != 0 {
+ return fmt.Errorf("db: OnConflict was set for builder %d. Set it on the ModelCreateBulk instead", i)
+ }
+ }
+ if len(u.create.conflict) == 0 {
+ return errors.New("db: missing options for ModelCreateBulk.OnConflict")
+ }
+ return u.create.Exec(ctx)
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (u *ModelUpsertBulk) ExecX(ctx context.Context) {
+ if err := u.create.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
diff --git a/backend/db/model_delete.go b/backend/db/model_delete.go
new file mode 100644
index 0000000..67c647c
--- /dev/null
+++ b/backend/db/model_delete.go
@@ -0,0 +1,88 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/model"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+)
+
+// ModelDelete is the builder for deleting a Model entity.
+type ModelDelete struct {
+ config
+ hooks []Hook
+ mutation *ModelMutation
+}
+
+// Where appends a list predicates to the ModelDelete builder.
+func (md *ModelDelete) Where(ps ...predicate.Model) *ModelDelete {
+ md.mutation.Where(ps...)
+ return md
+}
+
+// Exec executes the deletion query and returns how many vertices were deleted.
+func (md *ModelDelete) Exec(ctx context.Context) (int, error) {
+ return withHooks(ctx, md.sqlExec, md.mutation, md.hooks)
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (md *ModelDelete) ExecX(ctx context.Context) int {
+ n, err := md.Exec(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return n
+}
+
+func (md *ModelDelete) sqlExec(ctx context.Context) (int, error) {
+ _spec := sqlgraph.NewDeleteSpec(model.Table, sqlgraph.NewFieldSpec(model.FieldID, field.TypeUUID))
+ if ps := md.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ affected, err := sqlgraph.DeleteNodes(ctx, md.driver, _spec)
+ if err != nil && sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ md.mutation.done = true
+ return affected, err
+}
+
+// ModelDeleteOne is the builder for deleting a single Model entity.
+type ModelDeleteOne struct {
+ md *ModelDelete
+}
+
+// Where appends a list predicates to the ModelDelete builder.
+func (mdo *ModelDeleteOne) Where(ps ...predicate.Model) *ModelDeleteOne {
+ mdo.md.mutation.Where(ps...)
+ return mdo
+}
+
+// Exec executes the deletion query.
+func (mdo *ModelDeleteOne) Exec(ctx context.Context) error {
+ n, err := mdo.md.Exec(ctx)
+ switch {
+ case err != nil:
+ return err
+ case n == 0:
+ return &NotFoundError{model.Label}
+ default:
+ return nil
+ }
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (mdo *ModelDeleteOne) ExecX(ctx context.Context) {
+ if err := mdo.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
diff --git a/backend/db/model_query.go b/backend/db/model_query.go
new file mode 100644
index 0000000..e28cb33
--- /dev/null
+++ b/backend/db/model_query.go
@@ -0,0 +1,732 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "database/sql/driver"
+ "fmt"
+ "math"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect"
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/model"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+ "github.com/chaitin/MonkeyCode/backend/db/record"
+ "github.com/chaitin/MonkeyCode/backend/db/user"
+ "github.com/google/uuid"
+)
+
+// ModelQuery is the builder for querying Model entities.
+type ModelQuery struct {
+ config
+ ctx *QueryContext
+ order []model.OrderOption
+ inters []Interceptor
+ predicates []predicate.Model
+ withRecords *RecordQuery
+ withUser *UserQuery
+ modifiers []func(*sql.Selector)
+ // intermediate query (i.e. traversal path).
+ sql *sql.Selector
+ path func(context.Context) (*sql.Selector, error)
+}
+
+// Where adds a new predicate for the ModelQuery builder.
+func (mq *ModelQuery) Where(ps ...predicate.Model) *ModelQuery {
+ mq.predicates = append(mq.predicates, ps...)
+ return mq
+}
+
+// Limit the number of records to be returned by this query.
+func (mq *ModelQuery) Limit(limit int) *ModelQuery {
+ mq.ctx.Limit = &limit
+ return mq
+}
+
+// Offset to start from.
+func (mq *ModelQuery) Offset(offset int) *ModelQuery {
+ mq.ctx.Offset = &offset
+ return mq
+}
+
+// Unique configures the query builder to filter duplicate records on query.
+// By default, unique is set to true, and can be disabled using this method.
+func (mq *ModelQuery) Unique(unique bool) *ModelQuery {
+ mq.ctx.Unique = &unique
+ return mq
+}
+
+// Order specifies how the records should be ordered.
+func (mq *ModelQuery) Order(o ...model.OrderOption) *ModelQuery {
+ mq.order = append(mq.order, o...)
+ return mq
+}
+
+// QueryRecords chains the current query on the "records" edge.
+func (mq *ModelQuery) QueryRecords() *RecordQuery {
+ query := (&RecordClient{config: mq.config}).Query()
+ query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
+ if err := mq.prepareQuery(ctx); err != nil {
+ return nil, err
+ }
+ selector := mq.sqlQuery(ctx)
+ if err := selector.Err(); err != nil {
+ return nil, err
+ }
+ step := sqlgraph.NewStep(
+ sqlgraph.From(model.Table, model.FieldID, selector),
+ sqlgraph.To(record.Table, record.FieldID),
+ sqlgraph.Edge(sqlgraph.O2M, false, model.RecordsTable, model.RecordsColumn),
+ )
+ fromU = sqlgraph.SetNeighbors(mq.driver.Dialect(), step)
+ return fromU, nil
+ }
+ return query
+}
+
+// QueryUser chains the current query on the "user" edge.
+func (mq *ModelQuery) QueryUser() *UserQuery {
+ query := (&UserClient{config: mq.config}).Query()
+ query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
+ if err := mq.prepareQuery(ctx); err != nil {
+ return nil, err
+ }
+ selector := mq.sqlQuery(ctx)
+ if err := selector.Err(); err != nil {
+ return nil, err
+ }
+ step := sqlgraph.NewStep(
+ sqlgraph.From(model.Table, model.FieldID, selector),
+ sqlgraph.To(user.Table, user.FieldID),
+ sqlgraph.Edge(sqlgraph.M2O, true, model.UserTable, model.UserColumn),
+ )
+ fromU = sqlgraph.SetNeighbors(mq.driver.Dialect(), step)
+ return fromU, nil
+ }
+ return query
+}
+
+// First returns the first Model entity from the query.
+// Returns a *NotFoundError when no Model was found.
+func (mq *ModelQuery) First(ctx context.Context) (*Model, error) {
+ nodes, err := mq.Limit(1).All(setContextOp(ctx, mq.ctx, ent.OpQueryFirst))
+ if err != nil {
+ return nil, err
+ }
+ if len(nodes) == 0 {
+ return nil, &NotFoundError{model.Label}
+ }
+ return nodes[0], nil
+}
+
+// FirstX is like First, but panics if an error occurs.
+func (mq *ModelQuery) FirstX(ctx context.Context) *Model {
+ node, err := mq.First(ctx)
+ if err != nil && !IsNotFound(err) {
+ panic(err)
+ }
+ return node
+}
+
+// FirstID returns the first Model ID from the query.
+// Returns a *NotFoundError when no Model ID was found.
+func (mq *ModelQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
+ var ids []uuid.UUID
+ if ids, err = mq.Limit(1).IDs(setContextOp(ctx, mq.ctx, ent.OpQueryFirstID)); err != nil {
+ return
+ }
+ if len(ids) == 0 {
+ err = &NotFoundError{model.Label}
+ return
+ }
+ return ids[0], nil
+}
+
+// FirstIDX is like FirstID, but panics if an error occurs.
+func (mq *ModelQuery) FirstIDX(ctx context.Context) uuid.UUID {
+ id, err := mq.FirstID(ctx)
+ if err != nil && !IsNotFound(err) {
+ panic(err)
+ }
+ return id
+}
+
+// Only returns a single Model entity found by the query, ensuring it only returns one.
+// Returns a *NotSingularError when more than one Model entity is found.
+// Returns a *NotFoundError when no Model entities are found.
+func (mq *ModelQuery) Only(ctx context.Context) (*Model, error) {
+ nodes, err := mq.Limit(2).All(setContextOp(ctx, mq.ctx, ent.OpQueryOnly))
+ if err != nil {
+ return nil, err
+ }
+ switch len(nodes) {
+ case 1:
+ return nodes[0], nil
+ case 0:
+ return nil, &NotFoundError{model.Label}
+ default:
+ return nil, &NotSingularError{model.Label}
+ }
+}
+
+// OnlyX is like Only, but panics if an error occurs.
+func (mq *ModelQuery) OnlyX(ctx context.Context) *Model {
+ node, err := mq.Only(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return node
+}
+
+// OnlyID is like Only, but returns the only Model ID in the query.
+// Returns a *NotSingularError when more than one Model ID is found.
+// Returns a *NotFoundError when no entities are found.
+func (mq *ModelQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
+ var ids []uuid.UUID
+ if ids, err = mq.Limit(2).IDs(setContextOp(ctx, mq.ctx, ent.OpQueryOnlyID)); err != nil {
+ return
+ }
+ switch len(ids) {
+ case 1:
+ id = ids[0]
+ case 0:
+ err = &NotFoundError{model.Label}
+ default:
+ err = &NotSingularError{model.Label}
+ }
+ return
+}
+
+// OnlyIDX is like OnlyID, but panics if an error occurs.
+func (mq *ModelQuery) OnlyIDX(ctx context.Context) uuid.UUID {
+ id, err := mq.OnlyID(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return id
+}
+
+// All executes the query and returns a list of Models.
+func (mq *ModelQuery) All(ctx context.Context) ([]*Model, error) {
+ ctx = setContextOp(ctx, mq.ctx, ent.OpQueryAll)
+ if err := mq.prepareQuery(ctx); err != nil {
+ return nil, err
+ }
+ qr := querierAll[[]*Model, *ModelQuery]()
+ return withInterceptors[[]*Model](ctx, mq, qr, mq.inters)
+}
+
+// AllX is like All, but panics if an error occurs.
+func (mq *ModelQuery) AllX(ctx context.Context) []*Model {
+ nodes, err := mq.All(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return nodes
+}
+
+// IDs executes the query and returns a list of Model IDs.
+func (mq *ModelQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) {
+ if mq.ctx.Unique == nil && mq.path != nil {
+ mq.Unique(true)
+ }
+ ctx = setContextOp(ctx, mq.ctx, ent.OpQueryIDs)
+ if err = mq.Select(model.FieldID).Scan(ctx, &ids); err != nil {
+ return nil, err
+ }
+ return ids, nil
+}
+
+// IDsX is like IDs, but panics if an error occurs.
+func (mq *ModelQuery) IDsX(ctx context.Context) []uuid.UUID {
+ ids, err := mq.IDs(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return ids
+}
+
+// Count returns the count of the given query.
+func (mq *ModelQuery) Count(ctx context.Context) (int, error) {
+ ctx = setContextOp(ctx, mq.ctx, ent.OpQueryCount)
+ if err := mq.prepareQuery(ctx); err != nil {
+ return 0, err
+ }
+ return withInterceptors[int](ctx, mq, querierCount[*ModelQuery](), mq.inters)
+}
+
+// CountX is like Count, but panics if an error occurs.
+func (mq *ModelQuery) CountX(ctx context.Context) int {
+ count, err := mq.Count(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return count
+}
+
+// Exist returns true if the query has elements in the graph.
+func (mq *ModelQuery) Exist(ctx context.Context) (bool, error) {
+ ctx = setContextOp(ctx, mq.ctx, ent.OpQueryExist)
+ switch _, err := mq.FirstID(ctx); {
+ case IsNotFound(err):
+ return false, nil
+ case err != nil:
+ return false, fmt.Errorf("db: check existence: %w", err)
+ default:
+ return true, nil
+ }
+}
+
+// ExistX is like Exist, but panics if an error occurs.
+func (mq *ModelQuery) ExistX(ctx context.Context) bool {
+ exist, err := mq.Exist(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return exist
+}
+
+// Clone returns a duplicate of the ModelQuery builder, including all associated steps. It can be
+// used to prepare common query builders and use them differently after the clone is made.
+func (mq *ModelQuery) Clone() *ModelQuery {
+ if mq == nil {
+ return nil
+ }
+ return &ModelQuery{
+ config: mq.config,
+ ctx: mq.ctx.Clone(),
+ order: append([]model.OrderOption{}, mq.order...),
+ inters: append([]Interceptor{}, mq.inters...),
+ predicates: append([]predicate.Model{}, mq.predicates...),
+ withRecords: mq.withRecords.Clone(),
+ withUser: mq.withUser.Clone(),
+ // clone intermediate query.
+ sql: mq.sql.Clone(),
+ path: mq.path,
+ modifiers: append([]func(*sql.Selector){}, mq.modifiers...),
+ }
+}
+
+// WithRecords tells the query-builder to eager-load the nodes that are connected to
+// the "records" edge. The optional arguments are used to configure the query builder of the edge.
+func (mq *ModelQuery) WithRecords(opts ...func(*RecordQuery)) *ModelQuery {
+ query := (&RecordClient{config: mq.config}).Query()
+ for _, opt := range opts {
+ opt(query)
+ }
+ mq.withRecords = query
+ return mq
+}
+
+// WithUser tells the query-builder to eager-load the nodes that are connected to
+// the "user" edge. The optional arguments are used to configure the query builder of the edge.
+func (mq *ModelQuery) WithUser(opts ...func(*UserQuery)) *ModelQuery {
+ query := (&UserClient{config: mq.config}).Query()
+ for _, opt := range opts {
+ opt(query)
+ }
+ mq.withUser = query
+ return mq
+}
+
+// GroupBy is used to group vertices by one or more fields/columns.
+// It is often used with aggregate functions, like: count, max, mean, min, sum.
+//
+// Example:
+//
+// var v []struct {
+// UserID uuid.UUID `json:"user_id,omitempty"`
+// Count int `json:"count,omitempty"`
+// }
+//
+// client.Model.Query().
+// GroupBy(model.FieldUserID).
+// Aggregate(db.Count()).
+// Scan(ctx, &v)
+func (mq *ModelQuery) GroupBy(field string, fields ...string) *ModelGroupBy {
+ mq.ctx.Fields = append([]string{field}, fields...)
+ grbuild := &ModelGroupBy{build: mq}
+ grbuild.flds = &mq.ctx.Fields
+ grbuild.label = model.Label
+ grbuild.scan = grbuild.Scan
+ return grbuild
+}
+
+// Select allows the selection one or more fields/columns for the given query,
+// instead of selecting all fields in the entity.
+//
+// Example:
+//
+// var v []struct {
+// UserID uuid.UUID `json:"user_id,omitempty"`
+// }
+//
+// client.Model.Query().
+// Select(model.FieldUserID).
+// Scan(ctx, &v)
+func (mq *ModelQuery) Select(fields ...string) *ModelSelect {
+ mq.ctx.Fields = append(mq.ctx.Fields, fields...)
+ sbuild := &ModelSelect{ModelQuery: mq}
+ sbuild.label = model.Label
+ sbuild.flds, sbuild.scan = &mq.ctx.Fields, sbuild.Scan
+ return sbuild
+}
+
+// Aggregate returns a ModelSelect configured with the given aggregations.
+func (mq *ModelQuery) Aggregate(fns ...AggregateFunc) *ModelSelect {
+ return mq.Select().Aggregate(fns...)
+}
+
+func (mq *ModelQuery) prepareQuery(ctx context.Context) error {
+ for _, inter := range mq.inters {
+ if inter == nil {
+ return fmt.Errorf("db: uninitialized interceptor (forgotten import db/runtime?)")
+ }
+ if trv, ok := inter.(Traverser); ok {
+ if err := trv.Traverse(ctx, mq); err != nil {
+ return err
+ }
+ }
+ }
+ for _, f := range mq.ctx.Fields {
+ if !model.ValidColumn(f) {
+ return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
+ }
+ }
+ if mq.path != nil {
+ prev, err := mq.path(ctx)
+ if err != nil {
+ return err
+ }
+ mq.sql = prev
+ }
+ return nil
+}
+
+func (mq *ModelQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Model, error) {
+ var (
+ nodes = []*Model{}
+ _spec = mq.querySpec()
+ loadedTypes = [2]bool{
+ mq.withRecords != nil,
+ mq.withUser != nil,
+ }
+ )
+ _spec.ScanValues = func(columns []string) ([]any, error) {
+ return (*Model).scanValues(nil, columns)
+ }
+ _spec.Assign = func(columns []string, values []any) error {
+ node := &Model{config: mq.config}
+ nodes = append(nodes, node)
+ node.Edges.loadedTypes = loadedTypes
+ return node.assignValues(columns, values)
+ }
+ if len(mq.modifiers) > 0 {
+ _spec.Modifiers = mq.modifiers
+ }
+ for i := range hooks {
+ hooks[i](ctx, _spec)
+ }
+ if err := sqlgraph.QueryNodes(ctx, mq.driver, _spec); err != nil {
+ return nil, err
+ }
+ if len(nodes) == 0 {
+ return nodes, nil
+ }
+ if query := mq.withRecords; query != nil {
+ if err := mq.loadRecords(ctx, query, nodes,
+ func(n *Model) { n.Edges.Records = []*Record{} },
+ func(n *Model, e *Record) { n.Edges.Records = append(n.Edges.Records, e) }); err != nil {
+ return nil, err
+ }
+ }
+ if query := mq.withUser; query != nil {
+ if err := mq.loadUser(ctx, query, nodes, nil,
+ func(n *Model, e *User) { n.Edges.User = e }); err != nil {
+ return nil, err
+ }
+ }
+ return nodes, nil
+}
+
+func (mq *ModelQuery) loadRecords(ctx context.Context, query *RecordQuery, nodes []*Model, init func(*Model), assign func(*Model, *Record)) error {
+ fks := make([]driver.Value, 0, len(nodes))
+ nodeids := make(map[uuid.UUID]*Model)
+ for i := range nodes {
+ fks = append(fks, nodes[i].ID)
+ nodeids[nodes[i].ID] = nodes[i]
+ if init != nil {
+ init(nodes[i])
+ }
+ }
+ if len(query.ctx.Fields) > 0 {
+ query.ctx.AppendFieldOnce(record.FieldModelID)
+ }
+ query.Where(predicate.Record(func(s *sql.Selector) {
+ s.Where(sql.InValues(s.C(model.RecordsColumn), fks...))
+ }))
+ neighbors, err := query.All(ctx)
+ if err != nil {
+ return err
+ }
+ for _, n := range neighbors {
+ fk := n.ModelID
+ node, ok := nodeids[fk]
+ if !ok {
+ return fmt.Errorf(`unexpected referenced foreign-key "model_id" returned %v for node %v`, fk, n.ID)
+ }
+ assign(node, n)
+ }
+ return nil
+}
+func (mq *ModelQuery) loadUser(ctx context.Context, query *UserQuery, nodes []*Model, init func(*Model), assign func(*Model, *User)) error {
+ ids := make([]uuid.UUID, 0, len(nodes))
+ nodeids := make(map[uuid.UUID][]*Model)
+ for i := range nodes {
+ fk := nodes[i].UserID
+ if _, ok := nodeids[fk]; !ok {
+ ids = append(ids, fk)
+ }
+ nodeids[fk] = append(nodeids[fk], nodes[i])
+ }
+ if len(ids) == 0 {
+ return nil
+ }
+ query.Where(user.IDIn(ids...))
+ neighbors, err := query.All(ctx)
+ if err != nil {
+ return err
+ }
+ for _, n := range neighbors {
+ nodes, ok := nodeids[n.ID]
+ if !ok {
+ return fmt.Errorf(`unexpected foreign-key "user_id" returned %v`, n.ID)
+ }
+ for i := range nodes {
+ assign(nodes[i], n)
+ }
+ }
+ return nil
+}
+
+func (mq *ModelQuery) sqlCount(ctx context.Context) (int, error) {
+ _spec := mq.querySpec()
+ if len(mq.modifiers) > 0 {
+ _spec.Modifiers = mq.modifiers
+ }
+ _spec.Node.Columns = mq.ctx.Fields
+ if len(mq.ctx.Fields) > 0 {
+ _spec.Unique = mq.ctx.Unique != nil && *mq.ctx.Unique
+ }
+ return sqlgraph.CountNodes(ctx, mq.driver, _spec)
+}
+
+func (mq *ModelQuery) querySpec() *sqlgraph.QuerySpec {
+ _spec := sqlgraph.NewQuerySpec(model.Table, model.Columns, sqlgraph.NewFieldSpec(model.FieldID, field.TypeUUID))
+ _spec.From = mq.sql
+ if unique := mq.ctx.Unique; unique != nil {
+ _spec.Unique = *unique
+ } else if mq.path != nil {
+ _spec.Unique = true
+ }
+ if fields := mq.ctx.Fields; len(fields) > 0 {
+ _spec.Node.Columns = make([]string, 0, len(fields))
+ _spec.Node.Columns = append(_spec.Node.Columns, model.FieldID)
+ for i := range fields {
+ if fields[i] != model.FieldID {
+ _spec.Node.Columns = append(_spec.Node.Columns, fields[i])
+ }
+ }
+ if mq.withUser != nil {
+ _spec.Node.AddColumnOnce(model.FieldUserID)
+ }
+ }
+ if ps := mq.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if limit := mq.ctx.Limit; limit != nil {
+ _spec.Limit = *limit
+ }
+ if offset := mq.ctx.Offset; offset != nil {
+ _spec.Offset = *offset
+ }
+ if ps := mq.order; len(ps) > 0 {
+ _spec.Order = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ return _spec
+}
+
+func (mq *ModelQuery) sqlQuery(ctx context.Context) *sql.Selector {
+ builder := sql.Dialect(mq.driver.Dialect())
+ t1 := builder.Table(model.Table)
+ columns := mq.ctx.Fields
+ if len(columns) == 0 {
+ columns = model.Columns
+ }
+ selector := builder.Select(t1.Columns(columns...)...).From(t1)
+ if mq.sql != nil {
+ selector = mq.sql
+ selector.Select(selector.Columns(columns...)...)
+ }
+ if mq.ctx.Unique != nil && *mq.ctx.Unique {
+ selector.Distinct()
+ }
+ for _, m := range mq.modifiers {
+ m(selector)
+ }
+ for _, p := range mq.predicates {
+ p(selector)
+ }
+ for _, p := range mq.order {
+ p(selector)
+ }
+ if offset := mq.ctx.Offset; offset != nil {
+ // limit is mandatory for offset clause. We start
+ // with default value, and override it below if needed.
+ selector.Offset(*offset).Limit(math.MaxInt32)
+ }
+ if limit := mq.ctx.Limit; limit != nil {
+ selector.Limit(*limit)
+ }
+ return selector
+}
+
+// ForUpdate locks the selected rows against concurrent updates, and prevent them from being
+// updated, deleted or "selected ... for update" by other sessions, until the transaction is
+// either committed or rolled-back.
+func (mq *ModelQuery) ForUpdate(opts ...sql.LockOption) *ModelQuery {
+ if mq.driver.Dialect() == dialect.Postgres {
+ mq.Unique(false)
+ }
+ mq.modifiers = append(mq.modifiers, func(s *sql.Selector) {
+ s.ForUpdate(opts...)
+ })
+ return mq
+}
+
+// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock
+// on any rows that are read. Other sessions can read the rows, but cannot modify them
+// until your transaction commits.
+func (mq *ModelQuery) ForShare(opts ...sql.LockOption) *ModelQuery {
+ if mq.driver.Dialect() == dialect.Postgres {
+ mq.Unique(false)
+ }
+ mq.modifiers = append(mq.modifiers, func(s *sql.Selector) {
+ s.ForShare(opts...)
+ })
+ return mq
+}
+
+// Modify adds a query modifier for attaching custom logic to queries.
+func (mq *ModelQuery) Modify(modifiers ...func(s *sql.Selector)) *ModelSelect {
+ mq.modifiers = append(mq.modifiers, modifiers...)
+ return mq.Select()
+}
+
+// ModelGroupBy is the group-by builder for Model entities.
+type ModelGroupBy struct {
+ selector
+ build *ModelQuery
+}
+
+// Aggregate adds the given aggregation functions to the group-by query.
+func (mgb *ModelGroupBy) Aggregate(fns ...AggregateFunc) *ModelGroupBy {
+ mgb.fns = append(mgb.fns, fns...)
+ return mgb
+}
+
+// Scan applies the selector query and scans the result into the given value.
+func (mgb *ModelGroupBy) Scan(ctx context.Context, v any) error {
+ ctx = setContextOp(ctx, mgb.build.ctx, ent.OpQueryGroupBy)
+ if err := mgb.build.prepareQuery(ctx); err != nil {
+ return err
+ }
+ return scanWithInterceptors[*ModelQuery, *ModelGroupBy](ctx, mgb.build, mgb, mgb.build.inters, v)
+}
+
+func (mgb *ModelGroupBy) sqlScan(ctx context.Context, root *ModelQuery, v any) error {
+ selector := root.sqlQuery(ctx).Select()
+ aggregation := make([]string, 0, len(mgb.fns))
+ for _, fn := range mgb.fns {
+ aggregation = append(aggregation, fn(selector))
+ }
+ if len(selector.SelectedColumns()) == 0 {
+ columns := make([]string, 0, len(*mgb.flds)+len(mgb.fns))
+ for _, f := range *mgb.flds {
+ columns = append(columns, selector.C(f))
+ }
+ columns = append(columns, aggregation...)
+ selector.Select(columns...)
+ }
+ selector.GroupBy(selector.Columns(*mgb.flds...)...)
+ if err := selector.Err(); err != nil {
+ return err
+ }
+ rows := &sql.Rows{}
+ query, args := selector.Query()
+ if err := mgb.build.driver.Query(ctx, query, args, rows); err != nil {
+ return err
+ }
+ defer rows.Close()
+ return sql.ScanSlice(rows, v)
+}
+
+// ModelSelect is the builder for selecting fields of Model entities.
+type ModelSelect struct {
+ *ModelQuery
+ selector
+}
+
+// Aggregate adds the given aggregation functions to the selector query.
+func (ms *ModelSelect) Aggregate(fns ...AggregateFunc) *ModelSelect {
+ ms.fns = append(ms.fns, fns...)
+ return ms
+}
+
+// Scan applies the selector query and scans the result into the given value.
+func (ms *ModelSelect) Scan(ctx context.Context, v any) error {
+ ctx = setContextOp(ctx, ms.ctx, ent.OpQuerySelect)
+ if err := ms.prepareQuery(ctx); err != nil {
+ return err
+ }
+ return scanWithInterceptors[*ModelQuery, *ModelSelect](ctx, ms.ModelQuery, ms, ms.inters, v)
+}
+
+func (ms *ModelSelect) sqlScan(ctx context.Context, root *ModelQuery, v any) error {
+ selector := root.sqlQuery(ctx)
+ aggregation := make([]string, 0, len(ms.fns))
+ for _, fn := range ms.fns {
+ aggregation = append(aggregation, fn(selector))
+ }
+ switch n := len(*ms.selector.flds); {
+ case n == 0 && len(aggregation) > 0:
+ selector.Select(aggregation...)
+ case n != 0 && len(aggregation) > 0:
+ selector.AppendSelect(aggregation...)
+ }
+ rows := &sql.Rows{}
+ query, args := selector.Query()
+ if err := ms.driver.Query(ctx, query, args, rows); err != nil {
+ return err
+ }
+ defer rows.Close()
+ return sql.ScanSlice(rows, v)
+}
+
+// Modify adds a query modifier for attaching custom logic to queries.
+func (ms *ModelSelect) Modify(modifiers ...func(s *sql.Selector)) *ModelSelect {
+ ms.modifiers = append(ms.modifiers, modifiers...)
+ return ms
+}
diff --git a/backend/db/model_update.go b/backend/db/model_update.go
new file mode 100644
index 0000000..3f3e0ae
--- /dev/null
+++ b/backend/db/model_update.go
@@ -0,0 +1,928 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "time"
+
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/consts"
+ "github.com/chaitin/MonkeyCode/backend/db/model"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+ "github.com/chaitin/MonkeyCode/backend/db/record"
+ "github.com/chaitin/MonkeyCode/backend/db/user"
+ "github.com/google/uuid"
+)
+
+// ModelUpdate is the builder for updating Model entities.
+type ModelUpdate struct {
+ config
+ hooks []Hook
+ mutation *ModelMutation
+ modifiers []func(*sql.UpdateBuilder)
+}
+
+// Where appends a list predicates to the ModelUpdate builder.
+func (mu *ModelUpdate) Where(ps ...predicate.Model) *ModelUpdate {
+ mu.mutation.Where(ps...)
+ return mu
+}
+
+// SetUserID sets the "user_id" field.
+func (mu *ModelUpdate) SetUserID(u uuid.UUID) *ModelUpdate {
+ mu.mutation.SetUserID(u)
+ return mu
+}
+
+// SetNillableUserID sets the "user_id" field if the given value is not nil.
+func (mu *ModelUpdate) SetNillableUserID(u *uuid.UUID) *ModelUpdate {
+ if u != nil {
+ mu.SetUserID(*u)
+ }
+ return mu
+}
+
+// ClearUserID clears the value of the "user_id" field.
+func (mu *ModelUpdate) ClearUserID() *ModelUpdate {
+ mu.mutation.ClearUserID()
+ return mu
+}
+
+// SetModelName sets the "model_name" field.
+func (mu *ModelUpdate) SetModelName(s string) *ModelUpdate {
+ mu.mutation.SetModelName(s)
+ return mu
+}
+
+// SetNillableModelName sets the "model_name" field if the given value is not nil.
+func (mu *ModelUpdate) SetNillableModelName(s *string) *ModelUpdate {
+ if s != nil {
+ mu.SetModelName(*s)
+ }
+ return mu
+}
+
+// SetModelType sets the "model_type" field.
+func (mu *ModelUpdate) SetModelType(ct consts.ModelType) *ModelUpdate {
+ mu.mutation.SetModelType(ct)
+ return mu
+}
+
+// SetNillableModelType sets the "model_type" field if the given value is not nil.
+func (mu *ModelUpdate) SetNillableModelType(ct *consts.ModelType) *ModelUpdate {
+ if ct != nil {
+ mu.SetModelType(*ct)
+ }
+ return mu
+}
+
+// SetAPIBase sets the "api_base" field.
+func (mu *ModelUpdate) SetAPIBase(s string) *ModelUpdate {
+ mu.mutation.SetAPIBase(s)
+ return mu
+}
+
+// SetNillableAPIBase sets the "api_base" field if the given value is not nil.
+func (mu *ModelUpdate) SetNillableAPIBase(s *string) *ModelUpdate {
+ if s != nil {
+ mu.SetAPIBase(*s)
+ }
+ return mu
+}
+
+// SetAPIKey sets the "api_key" field.
+func (mu *ModelUpdate) SetAPIKey(s string) *ModelUpdate {
+ mu.mutation.SetAPIKey(s)
+ return mu
+}
+
+// SetNillableAPIKey sets the "api_key" field if the given value is not nil.
+func (mu *ModelUpdate) SetNillableAPIKey(s *string) *ModelUpdate {
+ if s != nil {
+ mu.SetAPIKey(*s)
+ }
+ return mu
+}
+
+// SetAPIVersion sets the "api_version" field.
+func (mu *ModelUpdate) SetAPIVersion(s string) *ModelUpdate {
+ mu.mutation.SetAPIVersion(s)
+ return mu
+}
+
+// SetNillableAPIVersion sets the "api_version" field if the given value is not nil.
+func (mu *ModelUpdate) SetNillableAPIVersion(s *string) *ModelUpdate {
+ if s != nil {
+ mu.SetAPIVersion(*s)
+ }
+ return mu
+}
+
+// ClearAPIVersion clears the value of the "api_version" field.
+func (mu *ModelUpdate) ClearAPIVersion() *ModelUpdate {
+ mu.mutation.ClearAPIVersion()
+ return mu
+}
+
+// SetDescription sets the "description" field.
+func (mu *ModelUpdate) SetDescription(s string) *ModelUpdate {
+ mu.mutation.SetDescription(s)
+ return mu
+}
+
+// SetNillableDescription sets the "description" field if the given value is not nil.
+func (mu *ModelUpdate) SetNillableDescription(s *string) *ModelUpdate {
+ if s != nil {
+ mu.SetDescription(*s)
+ }
+ return mu
+}
+
+// ClearDescription clears the value of the "description" field.
+func (mu *ModelUpdate) ClearDescription() *ModelUpdate {
+ mu.mutation.ClearDescription()
+ return mu
+}
+
+// SetProvider sets the "provider" field.
+func (mu *ModelUpdate) SetProvider(s string) *ModelUpdate {
+ mu.mutation.SetProvider(s)
+ return mu
+}
+
+// SetNillableProvider sets the "provider" field if the given value is not nil.
+func (mu *ModelUpdate) SetNillableProvider(s *string) *ModelUpdate {
+ if s != nil {
+ mu.SetProvider(*s)
+ }
+ return mu
+}
+
+// SetStatus sets the "status" field.
+func (mu *ModelUpdate) SetStatus(cs consts.ModelStatus) *ModelUpdate {
+ mu.mutation.SetStatus(cs)
+ return mu
+}
+
+// SetNillableStatus sets the "status" field if the given value is not nil.
+func (mu *ModelUpdate) SetNillableStatus(cs *consts.ModelStatus) *ModelUpdate {
+ if cs != nil {
+ mu.SetStatus(*cs)
+ }
+ return mu
+}
+
+// SetContextLength sets the "context_length" field.
+func (mu *ModelUpdate) SetContextLength(i int) *ModelUpdate {
+ mu.mutation.ResetContextLength()
+ mu.mutation.SetContextLength(i)
+ return mu
+}
+
+// SetNillableContextLength sets the "context_length" field if the given value is not nil.
+func (mu *ModelUpdate) SetNillableContextLength(i *int) *ModelUpdate {
+ if i != nil {
+ mu.SetContextLength(*i)
+ }
+ return mu
+}
+
+// AddContextLength adds i to the "context_length" field.
+func (mu *ModelUpdate) AddContextLength(i int) *ModelUpdate {
+ mu.mutation.AddContextLength(i)
+ return mu
+}
+
+// ClearContextLength clears the value of the "context_length" field.
+func (mu *ModelUpdate) ClearContextLength() *ModelUpdate {
+ mu.mutation.ClearContextLength()
+ return mu
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (mu *ModelUpdate) SetCreatedAt(t time.Time) *ModelUpdate {
+ mu.mutation.SetCreatedAt(t)
+ return mu
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (mu *ModelUpdate) SetNillableCreatedAt(t *time.Time) *ModelUpdate {
+ if t != nil {
+ mu.SetCreatedAt(*t)
+ }
+ return mu
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (mu *ModelUpdate) SetUpdatedAt(t time.Time) *ModelUpdate {
+ mu.mutation.SetUpdatedAt(t)
+ return mu
+}
+
+// AddRecordIDs adds the "records" edge to the Record entity by IDs.
+func (mu *ModelUpdate) AddRecordIDs(ids ...uuid.UUID) *ModelUpdate {
+ mu.mutation.AddRecordIDs(ids...)
+ return mu
+}
+
+// AddRecords adds the "records" edges to the Record entity.
+func (mu *ModelUpdate) AddRecords(r ...*Record) *ModelUpdate {
+ ids := make([]uuid.UUID, len(r))
+ for i := range r {
+ ids[i] = r[i].ID
+ }
+ return mu.AddRecordIDs(ids...)
+}
+
+// SetUser sets the "user" edge to the User entity.
+func (mu *ModelUpdate) SetUser(u *User) *ModelUpdate {
+ return mu.SetUserID(u.ID)
+}
+
+// Mutation returns the ModelMutation object of the builder.
+func (mu *ModelUpdate) Mutation() *ModelMutation {
+ return mu.mutation
+}
+
+// ClearRecords clears all "records" edges to the Record entity.
+func (mu *ModelUpdate) ClearRecords() *ModelUpdate {
+ mu.mutation.ClearRecords()
+ return mu
+}
+
+// RemoveRecordIDs removes the "records" edge to Record entities by IDs.
+func (mu *ModelUpdate) RemoveRecordIDs(ids ...uuid.UUID) *ModelUpdate {
+ mu.mutation.RemoveRecordIDs(ids...)
+ return mu
+}
+
+// RemoveRecords removes "records" edges to Record entities.
+func (mu *ModelUpdate) RemoveRecords(r ...*Record) *ModelUpdate {
+ ids := make([]uuid.UUID, len(r))
+ for i := range r {
+ ids[i] = r[i].ID
+ }
+ return mu.RemoveRecordIDs(ids...)
+}
+
+// ClearUser clears the "user" edge to the User entity.
+func (mu *ModelUpdate) ClearUser() *ModelUpdate {
+ mu.mutation.ClearUser()
+ return mu
+}
+
+// Save executes the query and returns the number of nodes affected by the update operation.
+func (mu *ModelUpdate) Save(ctx context.Context) (int, error) {
+ mu.defaults()
+ return withHooks(ctx, mu.sqlSave, mu.mutation, mu.hooks)
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (mu *ModelUpdate) SaveX(ctx context.Context) int {
+ affected, err := mu.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return affected
+}
+
+// Exec executes the query.
+func (mu *ModelUpdate) Exec(ctx context.Context) error {
+ _, err := mu.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (mu *ModelUpdate) ExecX(ctx context.Context) {
+ if err := mu.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// defaults sets the default values of the builder before save.
+func (mu *ModelUpdate) defaults() {
+ if _, ok := mu.mutation.UpdatedAt(); !ok {
+ v := model.UpdateDefaultUpdatedAt()
+ mu.mutation.SetUpdatedAt(v)
+ }
+}
+
+// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
+func (mu *ModelUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *ModelUpdate {
+ mu.modifiers = append(mu.modifiers, modifiers...)
+ return mu
+}
+
+func (mu *ModelUpdate) sqlSave(ctx context.Context) (n int, err error) {
+ _spec := sqlgraph.NewUpdateSpec(model.Table, model.Columns, sqlgraph.NewFieldSpec(model.FieldID, field.TypeUUID))
+ if ps := mu.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if value, ok := mu.mutation.ModelName(); ok {
+ _spec.SetField(model.FieldModelName, field.TypeString, value)
+ }
+ if value, ok := mu.mutation.ModelType(); ok {
+ _spec.SetField(model.FieldModelType, field.TypeString, value)
+ }
+ if value, ok := mu.mutation.APIBase(); ok {
+ _spec.SetField(model.FieldAPIBase, field.TypeString, value)
+ }
+ if value, ok := mu.mutation.APIKey(); ok {
+ _spec.SetField(model.FieldAPIKey, field.TypeString, value)
+ }
+ if value, ok := mu.mutation.APIVersion(); ok {
+ _spec.SetField(model.FieldAPIVersion, field.TypeString, value)
+ }
+ if mu.mutation.APIVersionCleared() {
+ _spec.ClearField(model.FieldAPIVersion, field.TypeString)
+ }
+ if value, ok := mu.mutation.Description(); ok {
+ _spec.SetField(model.FieldDescription, field.TypeString, value)
+ }
+ if mu.mutation.DescriptionCleared() {
+ _spec.ClearField(model.FieldDescription, field.TypeString)
+ }
+ if value, ok := mu.mutation.Provider(); ok {
+ _spec.SetField(model.FieldProvider, field.TypeString, value)
+ }
+ if value, ok := mu.mutation.Status(); ok {
+ _spec.SetField(model.FieldStatus, field.TypeString, value)
+ }
+ if value, ok := mu.mutation.ContextLength(); ok {
+ _spec.SetField(model.FieldContextLength, field.TypeInt, value)
+ }
+ if value, ok := mu.mutation.AddedContextLength(); ok {
+ _spec.AddField(model.FieldContextLength, field.TypeInt, value)
+ }
+ if mu.mutation.ContextLengthCleared() {
+ _spec.ClearField(model.FieldContextLength, field.TypeInt)
+ }
+ if value, ok := mu.mutation.CreatedAt(); ok {
+ _spec.SetField(model.FieldCreatedAt, field.TypeTime, value)
+ }
+ if value, ok := mu.mutation.UpdatedAt(); ok {
+ _spec.SetField(model.FieldUpdatedAt, field.TypeTime, value)
+ }
+ if mu.mutation.RecordsCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: model.RecordsTable,
+ Columns: []string{model.RecordsColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(record.FieldID, field.TypeUUID),
+ },
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := mu.mutation.RemovedRecordsIDs(); len(nodes) > 0 && !mu.mutation.RecordsCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: model.RecordsTable,
+ Columns: []string{model.RecordsColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(record.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := mu.mutation.RecordsIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: model.RecordsTable,
+ Columns: []string{model.RecordsColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(record.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Add = append(_spec.Edges.Add, edge)
+ }
+ if mu.mutation.UserCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: true,
+ Table: model.UserTable,
+ Columns: []string{model.UserColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID),
+ },
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := mu.mutation.UserIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: true,
+ Table: model.UserTable,
+ Columns: []string{model.UserColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Add = append(_spec.Edges.Add, edge)
+ }
+ _spec.AddModifiers(mu.modifiers...)
+ if n, err = sqlgraph.UpdateNodes(ctx, mu.driver, _spec); err != nil {
+ if _, ok := err.(*sqlgraph.NotFoundError); ok {
+ err = &NotFoundError{model.Label}
+ } else if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return 0, err
+ }
+ mu.mutation.done = true
+ return n, nil
+}
+
+// ModelUpdateOne is the builder for updating a single Model entity.
+type ModelUpdateOne struct {
+ config
+ fields []string
+ hooks []Hook
+ mutation *ModelMutation
+ modifiers []func(*sql.UpdateBuilder)
+}
+
+// SetUserID sets the "user_id" field.
+func (muo *ModelUpdateOne) SetUserID(u uuid.UUID) *ModelUpdateOne {
+ muo.mutation.SetUserID(u)
+ return muo
+}
+
+// SetNillableUserID sets the "user_id" field if the given value is not nil.
+func (muo *ModelUpdateOne) SetNillableUserID(u *uuid.UUID) *ModelUpdateOne {
+ if u != nil {
+ muo.SetUserID(*u)
+ }
+ return muo
+}
+
+// ClearUserID clears the value of the "user_id" field.
+func (muo *ModelUpdateOne) ClearUserID() *ModelUpdateOne {
+ muo.mutation.ClearUserID()
+ return muo
+}
+
+// SetModelName sets the "model_name" field.
+func (muo *ModelUpdateOne) SetModelName(s string) *ModelUpdateOne {
+ muo.mutation.SetModelName(s)
+ return muo
+}
+
+// SetNillableModelName sets the "model_name" field if the given value is not nil.
+func (muo *ModelUpdateOne) SetNillableModelName(s *string) *ModelUpdateOne {
+ if s != nil {
+ muo.SetModelName(*s)
+ }
+ return muo
+}
+
+// SetModelType sets the "model_type" field.
+func (muo *ModelUpdateOne) SetModelType(ct consts.ModelType) *ModelUpdateOne {
+ muo.mutation.SetModelType(ct)
+ return muo
+}
+
+// SetNillableModelType sets the "model_type" field if the given value is not nil.
+func (muo *ModelUpdateOne) SetNillableModelType(ct *consts.ModelType) *ModelUpdateOne {
+ if ct != nil {
+ muo.SetModelType(*ct)
+ }
+ return muo
+}
+
+// SetAPIBase sets the "api_base" field.
+func (muo *ModelUpdateOne) SetAPIBase(s string) *ModelUpdateOne {
+ muo.mutation.SetAPIBase(s)
+ return muo
+}
+
+// SetNillableAPIBase sets the "api_base" field if the given value is not nil.
+func (muo *ModelUpdateOne) SetNillableAPIBase(s *string) *ModelUpdateOne {
+ if s != nil {
+ muo.SetAPIBase(*s)
+ }
+ return muo
+}
+
+// SetAPIKey sets the "api_key" field.
+func (muo *ModelUpdateOne) SetAPIKey(s string) *ModelUpdateOne {
+ muo.mutation.SetAPIKey(s)
+ return muo
+}
+
+// SetNillableAPIKey sets the "api_key" field if the given value is not nil.
+func (muo *ModelUpdateOne) SetNillableAPIKey(s *string) *ModelUpdateOne {
+ if s != nil {
+ muo.SetAPIKey(*s)
+ }
+ return muo
+}
+
+// SetAPIVersion sets the "api_version" field.
+func (muo *ModelUpdateOne) SetAPIVersion(s string) *ModelUpdateOne {
+ muo.mutation.SetAPIVersion(s)
+ return muo
+}
+
+// SetNillableAPIVersion sets the "api_version" field if the given value is not nil.
+func (muo *ModelUpdateOne) SetNillableAPIVersion(s *string) *ModelUpdateOne {
+ if s != nil {
+ muo.SetAPIVersion(*s)
+ }
+ return muo
+}
+
+// ClearAPIVersion clears the value of the "api_version" field.
+func (muo *ModelUpdateOne) ClearAPIVersion() *ModelUpdateOne {
+ muo.mutation.ClearAPIVersion()
+ return muo
+}
+
+// SetDescription sets the "description" field.
+func (muo *ModelUpdateOne) SetDescription(s string) *ModelUpdateOne {
+ muo.mutation.SetDescription(s)
+ return muo
+}
+
+// SetNillableDescription sets the "description" field if the given value is not nil.
+func (muo *ModelUpdateOne) SetNillableDescription(s *string) *ModelUpdateOne {
+ if s != nil {
+ muo.SetDescription(*s)
+ }
+ return muo
+}
+
+// ClearDescription clears the value of the "description" field.
+func (muo *ModelUpdateOne) ClearDescription() *ModelUpdateOne {
+ muo.mutation.ClearDescription()
+ return muo
+}
+
+// SetProvider sets the "provider" field.
+func (muo *ModelUpdateOne) SetProvider(s string) *ModelUpdateOne {
+ muo.mutation.SetProvider(s)
+ return muo
+}
+
+// SetNillableProvider sets the "provider" field if the given value is not nil.
+func (muo *ModelUpdateOne) SetNillableProvider(s *string) *ModelUpdateOne {
+ if s != nil {
+ muo.SetProvider(*s)
+ }
+ return muo
+}
+
+// SetStatus sets the "status" field.
+func (muo *ModelUpdateOne) SetStatus(cs consts.ModelStatus) *ModelUpdateOne {
+ muo.mutation.SetStatus(cs)
+ return muo
+}
+
+// SetNillableStatus sets the "status" field if the given value is not nil.
+func (muo *ModelUpdateOne) SetNillableStatus(cs *consts.ModelStatus) *ModelUpdateOne {
+ if cs != nil {
+ muo.SetStatus(*cs)
+ }
+ return muo
+}
+
+// SetContextLength sets the "context_length" field.
+func (muo *ModelUpdateOne) SetContextLength(i int) *ModelUpdateOne {
+ muo.mutation.ResetContextLength()
+ muo.mutation.SetContextLength(i)
+ return muo
+}
+
+// SetNillableContextLength sets the "context_length" field if the given value is not nil.
+func (muo *ModelUpdateOne) SetNillableContextLength(i *int) *ModelUpdateOne {
+ if i != nil {
+ muo.SetContextLength(*i)
+ }
+ return muo
+}
+
+// AddContextLength adds i to the "context_length" field.
+func (muo *ModelUpdateOne) AddContextLength(i int) *ModelUpdateOne {
+ muo.mutation.AddContextLength(i)
+ return muo
+}
+
+// ClearContextLength clears the value of the "context_length" field.
+func (muo *ModelUpdateOne) ClearContextLength() *ModelUpdateOne {
+ muo.mutation.ClearContextLength()
+ return muo
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (muo *ModelUpdateOne) SetCreatedAt(t time.Time) *ModelUpdateOne {
+ muo.mutation.SetCreatedAt(t)
+ return muo
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (muo *ModelUpdateOne) SetNillableCreatedAt(t *time.Time) *ModelUpdateOne {
+ if t != nil {
+ muo.SetCreatedAt(*t)
+ }
+ return muo
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (muo *ModelUpdateOne) SetUpdatedAt(t time.Time) *ModelUpdateOne {
+ muo.mutation.SetUpdatedAt(t)
+ return muo
+}
+
+// AddRecordIDs adds the "records" edge to the Record entity by IDs.
+func (muo *ModelUpdateOne) AddRecordIDs(ids ...uuid.UUID) *ModelUpdateOne {
+ muo.mutation.AddRecordIDs(ids...)
+ return muo
+}
+
+// AddRecords adds the "records" edges to the Record entity.
+func (muo *ModelUpdateOne) AddRecords(r ...*Record) *ModelUpdateOne {
+ ids := make([]uuid.UUID, len(r))
+ for i := range r {
+ ids[i] = r[i].ID
+ }
+ return muo.AddRecordIDs(ids...)
+}
+
+// SetUser sets the "user" edge to the User entity.
+func (muo *ModelUpdateOne) SetUser(u *User) *ModelUpdateOne {
+ return muo.SetUserID(u.ID)
+}
+
+// Mutation returns the ModelMutation object of the builder.
+func (muo *ModelUpdateOne) Mutation() *ModelMutation {
+ return muo.mutation
+}
+
+// ClearRecords clears all "records" edges to the Record entity.
+func (muo *ModelUpdateOne) ClearRecords() *ModelUpdateOne {
+ muo.mutation.ClearRecords()
+ return muo
+}
+
+// RemoveRecordIDs removes the "records" edge to Record entities by IDs.
+func (muo *ModelUpdateOne) RemoveRecordIDs(ids ...uuid.UUID) *ModelUpdateOne {
+ muo.mutation.RemoveRecordIDs(ids...)
+ return muo
+}
+
+// RemoveRecords removes "records" edges to Record entities.
+func (muo *ModelUpdateOne) RemoveRecords(r ...*Record) *ModelUpdateOne {
+ ids := make([]uuid.UUID, len(r))
+ for i := range r {
+ ids[i] = r[i].ID
+ }
+ return muo.RemoveRecordIDs(ids...)
+}
+
+// ClearUser clears the "user" edge to the User entity.
+func (muo *ModelUpdateOne) ClearUser() *ModelUpdateOne {
+ muo.mutation.ClearUser()
+ return muo
+}
+
+// Where appends a list predicates to the ModelUpdate builder.
+func (muo *ModelUpdateOne) Where(ps ...predicate.Model) *ModelUpdateOne {
+ muo.mutation.Where(ps...)
+ return muo
+}
+
+// Select allows selecting one or more fields (columns) of the returned entity.
+// The default is selecting all fields defined in the entity schema.
+func (muo *ModelUpdateOne) Select(field string, fields ...string) *ModelUpdateOne {
+ muo.fields = append([]string{field}, fields...)
+ return muo
+}
+
+// Save executes the query and returns the updated Model entity.
+func (muo *ModelUpdateOne) Save(ctx context.Context) (*Model, error) {
+ muo.defaults()
+ return withHooks(ctx, muo.sqlSave, muo.mutation, muo.hooks)
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (muo *ModelUpdateOne) SaveX(ctx context.Context) *Model {
+ node, err := muo.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return node
+}
+
+// Exec executes the query on the entity.
+func (muo *ModelUpdateOne) Exec(ctx context.Context) error {
+ _, err := muo.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (muo *ModelUpdateOne) ExecX(ctx context.Context) {
+ if err := muo.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// defaults sets the default values of the builder before save.
+func (muo *ModelUpdateOne) defaults() {
+ if _, ok := muo.mutation.UpdatedAt(); !ok {
+ v := model.UpdateDefaultUpdatedAt()
+ muo.mutation.SetUpdatedAt(v)
+ }
+}
+
+// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
+func (muo *ModelUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *ModelUpdateOne {
+ muo.modifiers = append(muo.modifiers, modifiers...)
+ return muo
+}
+
+func (muo *ModelUpdateOne) sqlSave(ctx context.Context) (_node *Model, err error) {
+ _spec := sqlgraph.NewUpdateSpec(model.Table, model.Columns, sqlgraph.NewFieldSpec(model.FieldID, field.TypeUUID))
+ id, ok := muo.mutation.ID()
+ if !ok {
+ return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "Model.id" for update`)}
+ }
+ _spec.Node.ID.Value = id
+ if fields := muo.fields; len(fields) > 0 {
+ _spec.Node.Columns = make([]string, 0, len(fields))
+ _spec.Node.Columns = append(_spec.Node.Columns, model.FieldID)
+ for _, f := range fields {
+ if !model.ValidColumn(f) {
+ return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
+ }
+ if f != model.FieldID {
+ _spec.Node.Columns = append(_spec.Node.Columns, f)
+ }
+ }
+ }
+ if ps := muo.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if value, ok := muo.mutation.ModelName(); ok {
+ _spec.SetField(model.FieldModelName, field.TypeString, value)
+ }
+ if value, ok := muo.mutation.ModelType(); ok {
+ _spec.SetField(model.FieldModelType, field.TypeString, value)
+ }
+ if value, ok := muo.mutation.APIBase(); ok {
+ _spec.SetField(model.FieldAPIBase, field.TypeString, value)
+ }
+ if value, ok := muo.mutation.APIKey(); ok {
+ _spec.SetField(model.FieldAPIKey, field.TypeString, value)
+ }
+ if value, ok := muo.mutation.APIVersion(); ok {
+ _spec.SetField(model.FieldAPIVersion, field.TypeString, value)
+ }
+ if muo.mutation.APIVersionCleared() {
+ _spec.ClearField(model.FieldAPIVersion, field.TypeString)
+ }
+ if value, ok := muo.mutation.Description(); ok {
+ _spec.SetField(model.FieldDescription, field.TypeString, value)
+ }
+ if muo.mutation.DescriptionCleared() {
+ _spec.ClearField(model.FieldDescription, field.TypeString)
+ }
+ if value, ok := muo.mutation.Provider(); ok {
+ _spec.SetField(model.FieldProvider, field.TypeString, value)
+ }
+ if value, ok := muo.mutation.Status(); ok {
+ _spec.SetField(model.FieldStatus, field.TypeString, value)
+ }
+ if value, ok := muo.mutation.ContextLength(); ok {
+ _spec.SetField(model.FieldContextLength, field.TypeInt, value)
+ }
+ if value, ok := muo.mutation.AddedContextLength(); ok {
+ _spec.AddField(model.FieldContextLength, field.TypeInt, value)
+ }
+ if muo.mutation.ContextLengthCleared() {
+ _spec.ClearField(model.FieldContextLength, field.TypeInt)
+ }
+ if value, ok := muo.mutation.CreatedAt(); ok {
+ _spec.SetField(model.FieldCreatedAt, field.TypeTime, value)
+ }
+ if value, ok := muo.mutation.UpdatedAt(); ok {
+ _spec.SetField(model.FieldUpdatedAt, field.TypeTime, value)
+ }
+ if muo.mutation.RecordsCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: model.RecordsTable,
+ Columns: []string{model.RecordsColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(record.FieldID, field.TypeUUID),
+ },
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := muo.mutation.RemovedRecordsIDs(); len(nodes) > 0 && !muo.mutation.RecordsCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: model.RecordsTable,
+ Columns: []string{model.RecordsColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(record.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := muo.mutation.RecordsIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: model.RecordsTable,
+ Columns: []string{model.RecordsColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(record.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Add = append(_spec.Edges.Add, edge)
+ }
+ if muo.mutation.UserCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: true,
+ Table: model.UserTable,
+ Columns: []string{model.UserColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID),
+ },
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := muo.mutation.UserIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: true,
+ Table: model.UserTable,
+ Columns: []string{model.UserColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Add = append(_spec.Edges.Add, edge)
+ }
+ _spec.AddModifiers(muo.modifiers...)
+ _node = &Model{config: muo.config}
+ _spec.Assign = _node.assignValues
+ _spec.ScanValues = _node.scanValues
+ if err = sqlgraph.UpdateNode(ctx, muo.driver, _spec); err != nil {
+ if _, ok := err.(*sqlgraph.NotFoundError); ok {
+ err = &NotFoundError{model.Label}
+ } else if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return nil, err
+ }
+ muo.mutation.done = true
+ return _node, nil
+}
diff --git a/backend/db/mutation.go b/backend/db/mutation.go
new file mode 100644
index 0000000..bc82c28
--- /dev/null
+++ b/backend/db/mutation.go
@@ -0,0 +1,10689 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "sync"
+ "time"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect/sql"
+ "github.com/chaitin/MonkeyCode/backend/consts"
+ "github.com/chaitin/MonkeyCode/backend/db/admin"
+ "github.com/chaitin/MonkeyCode/backend/db/adminloginhistory"
+ "github.com/chaitin/MonkeyCode/backend/db/apikey"
+ "github.com/chaitin/MonkeyCode/backend/db/billingplan"
+ "github.com/chaitin/MonkeyCode/backend/db/billingquota"
+ "github.com/chaitin/MonkeyCode/backend/db/billingrecord"
+ "github.com/chaitin/MonkeyCode/backend/db/billingusage"
+ "github.com/chaitin/MonkeyCode/backend/db/invitecode"
+ "github.com/chaitin/MonkeyCode/backend/db/model"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+ "github.com/chaitin/MonkeyCode/backend/db/record"
+ "github.com/chaitin/MonkeyCode/backend/db/setting"
+ "github.com/chaitin/MonkeyCode/backend/db/user"
+ "github.com/chaitin/MonkeyCode/backend/db/userloginhistory"
+ "github.com/google/uuid"
+)
+
+const (
+ // Operation types.
+ OpCreate = ent.OpCreate
+ OpDelete = ent.OpDelete
+ OpDeleteOne = ent.OpDeleteOne
+ OpUpdate = ent.OpUpdate
+ OpUpdateOne = ent.OpUpdateOne
+
+ // Node types.
+ TypeAdmin = "Admin"
+ TypeAdminLoginHistory = "AdminLoginHistory"
+ TypeApiKey = "ApiKey"
+ TypeBillingPlan = "BillingPlan"
+ TypeBillingQuota = "BillingQuota"
+ TypeBillingRecord = "BillingRecord"
+ TypeBillingUsage = "BillingUsage"
+ TypeInviteCode = "InviteCode"
+ TypeModel = "Model"
+ TypeRecord = "Record"
+ TypeSetting = "Setting"
+ TypeUser = "User"
+ TypeUserLoginHistory = "UserLoginHistory"
+)
+
+// AdminMutation represents an operation that mutates the Admin nodes in the graph.
+type AdminMutation struct {
+ config
+ op Op
+ typ string
+ id *uuid.UUID
+ username *string
+ password *string
+ status *consts.AdminStatus
+ last_active_at *time.Time
+ created_at *time.Time
+ updated_at *time.Time
+ clearedFields map[string]struct{}
+ login_histories map[uuid.UUID]struct{}
+ removedlogin_histories map[uuid.UUID]struct{}
+ clearedlogin_histories bool
+ done bool
+ oldValue func(context.Context) (*Admin, error)
+ predicates []predicate.Admin
+}
+
+var _ ent.Mutation = (*AdminMutation)(nil)
+
+// adminOption allows management of the mutation configuration using functional options.
+type adminOption func(*AdminMutation)
+
+// newAdminMutation creates new mutation for the Admin entity.
+func newAdminMutation(c config, op Op, opts ...adminOption) *AdminMutation {
+ m := &AdminMutation{
+ config: c,
+ op: op,
+ typ: TypeAdmin,
+ clearedFields: make(map[string]struct{}),
+ }
+ for _, opt := range opts {
+ opt(m)
+ }
+ return m
+}
+
+// withAdminID sets the ID field of the mutation.
+func withAdminID(id uuid.UUID) adminOption {
+ return func(m *AdminMutation) {
+ var (
+ err error
+ once sync.Once
+ value *Admin
+ )
+ m.oldValue = func(ctx context.Context) (*Admin, error) {
+ once.Do(func() {
+ if m.done {
+ err = errors.New("querying old values post mutation is not allowed")
+ } else {
+ value, err = m.Client().Admin.Get(ctx, id)
+ }
+ })
+ return value, err
+ }
+ m.id = &id
+ }
+}
+
+// withAdmin sets the old Admin of the mutation.
+func withAdmin(node *Admin) adminOption {
+ return func(m *AdminMutation) {
+ m.oldValue = func(context.Context) (*Admin, 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 AdminMutation) 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 AdminMutation) Tx() (*Tx, error) {
+ if _, ok := m.driver.(*txDriver); !ok {
+ return nil, errors.New("db: mutation is not running in a transaction")
+ }
+ tx := &Tx{config: m.config}
+ tx.init()
+ return tx, nil
+}
+
+// SetID sets the value of the id field. Note that this
+// operation is only accepted on creation of Admin entities.
+func (m *AdminMutation) SetID(id uuid.UUID) {
+ m.id = &id
+}
+
+// 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 *AdminMutation) ID() (id uuid.UUID, 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 *AdminMutation) IDs(ctx context.Context) ([]uuid.UUID, error) {
+ switch {
+ case m.op.Is(OpUpdateOne | OpDeleteOne):
+ id, exists := m.ID()
+ if exists {
+ return []uuid.UUID{id}, nil
+ }
+ fallthrough
+ case m.op.Is(OpUpdate | OpDelete):
+ return m.Client().Admin.Query().Where(m.predicates...).IDs(ctx)
+ default:
+ return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op)
+ }
+}
+
+// SetUsername sets the "username" field.
+func (m *AdminMutation) SetUsername(s string) {
+ m.username = &s
+}
+
+// Username returns the value of the "username" field in the mutation.
+func (m *AdminMutation) Username() (r string, exists bool) {
+ v := m.username
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldUsername returns the old "username" field's value of the Admin entity.
+// If the Admin 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 *AdminMutation) OldUsername(ctx context.Context) (v string, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldUsername is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldUsername requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldUsername: %w", err)
+ }
+ return oldValue.Username, nil
+}
+
+// ResetUsername resets all changes to the "username" field.
+func (m *AdminMutation) ResetUsername() {
+ m.username = nil
+}
+
+// SetPassword sets the "password" field.
+func (m *AdminMutation) SetPassword(s string) {
+ m.password = &s
+}
+
+// Password returns the value of the "password" field in the mutation.
+func (m *AdminMutation) Password() (r string, exists bool) {
+ v := m.password
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldPassword returns the old "password" field's value of the Admin entity.
+// If the Admin 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 *AdminMutation) OldPassword(ctx context.Context) (v string, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldPassword is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldPassword requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldPassword: %w", err)
+ }
+ return oldValue.Password, nil
+}
+
+// ResetPassword resets all changes to the "password" field.
+func (m *AdminMutation) ResetPassword() {
+ m.password = nil
+}
+
+// SetStatus sets the "status" field.
+func (m *AdminMutation) SetStatus(cs consts.AdminStatus) {
+ m.status = &cs
+}
+
+// Status returns the value of the "status" field in the mutation.
+func (m *AdminMutation) Status() (r consts.AdminStatus, exists bool) {
+ v := m.status
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldStatus returns the old "status" field's value of the Admin entity.
+// If the Admin 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 *AdminMutation) OldStatus(ctx context.Context) (v consts.AdminStatus, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldStatus is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldStatus requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldStatus: %w", err)
+ }
+ return oldValue.Status, nil
+}
+
+// ResetStatus resets all changes to the "status" field.
+func (m *AdminMutation) ResetStatus() {
+ m.status = nil
+}
+
+// SetLastActiveAt sets the "last_active_at" field.
+func (m *AdminMutation) SetLastActiveAt(t time.Time) {
+ m.last_active_at = &t
+}
+
+// LastActiveAt returns the value of the "last_active_at" field in the mutation.
+func (m *AdminMutation) LastActiveAt() (r time.Time, exists bool) {
+ v := m.last_active_at
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldLastActiveAt returns the old "last_active_at" field's value of the Admin entity.
+// If the Admin 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 *AdminMutation) OldLastActiveAt(ctx context.Context) (v time.Time, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldLastActiveAt is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldLastActiveAt requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldLastActiveAt: %w", err)
+ }
+ return oldValue.LastActiveAt, nil
+}
+
+// ResetLastActiveAt resets all changes to the "last_active_at" field.
+func (m *AdminMutation) ResetLastActiveAt() {
+ m.last_active_at = nil
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (m *AdminMutation) SetCreatedAt(t time.Time) {
+ m.created_at = &t
+}
+
+// CreatedAt returns the value of the "created_at" field in the mutation.
+func (m *AdminMutation) 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 Admin entity.
+// If the Admin 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 *AdminMutation) 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 *AdminMutation) ResetCreatedAt() {
+ m.created_at = nil
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (m *AdminMutation) SetUpdatedAt(t time.Time) {
+ m.updated_at = &t
+}
+
+// UpdatedAt returns the value of the "updated_at" field in the mutation.
+func (m *AdminMutation) 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 Admin entity.
+// If the Admin 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 *AdminMutation) 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 *AdminMutation) ResetUpdatedAt() {
+ m.updated_at = nil
+}
+
+// AddLoginHistoryIDs adds the "login_histories" edge to the AdminLoginHistory entity by ids.
+func (m *AdminMutation) AddLoginHistoryIDs(ids ...uuid.UUID) {
+ if m.login_histories == nil {
+ m.login_histories = make(map[uuid.UUID]struct{})
+ }
+ for i := range ids {
+ m.login_histories[ids[i]] = struct{}{}
+ }
+}
+
+// ClearLoginHistories clears the "login_histories" edge to the AdminLoginHistory entity.
+func (m *AdminMutation) ClearLoginHistories() {
+ m.clearedlogin_histories = true
+}
+
+// LoginHistoriesCleared reports if the "login_histories" edge to the AdminLoginHistory entity was cleared.
+func (m *AdminMutation) LoginHistoriesCleared() bool {
+ return m.clearedlogin_histories
+}
+
+// RemoveLoginHistoryIDs removes the "login_histories" edge to the AdminLoginHistory entity by IDs.
+func (m *AdminMutation) RemoveLoginHistoryIDs(ids ...uuid.UUID) {
+ if m.removedlogin_histories == nil {
+ m.removedlogin_histories = make(map[uuid.UUID]struct{})
+ }
+ for i := range ids {
+ delete(m.login_histories, ids[i])
+ m.removedlogin_histories[ids[i]] = struct{}{}
+ }
+}
+
+// RemovedLoginHistories returns the removed IDs of the "login_histories" edge to the AdminLoginHistory entity.
+func (m *AdminMutation) RemovedLoginHistoriesIDs() (ids []uuid.UUID) {
+ for id := range m.removedlogin_histories {
+ ids = append(ids, id)
+ }
+ return
+}
+
+// LoginHistoriesIDs returns the "login_histories" edge IDs in the mutation.
+func (m *AdminMutation) LoginHistoriesIDs() (ids []uuid.UUID) {
+ for id := range m.login_histories {
+ ids = append(ids, id)
+ }
+ return
+}
+
+// ResetLoginHistories resets all changes to the "login_histories" edge.
+func (m *AdminMutation) ResetLoginHistories() {
+ m.login_histories = nil
+ m.clearedlogin_histories = false
+ m.removedlogin_histories = nil
+}
+
+// Where appends a list predicates to the AdminMutation builder.
+func (m *AdminMutation) Where(ps ...predicate.Admin) {
+ m.predicates = append(m.predicates, ps...)
+}
+
+// WhereP appends storage-level predicates to the AdminMutation builder. Using this method,
+// users can use type-assertion to append predicates that do not depend on any generated package.
+func (m *AdminMutation) WhereP(ps ...func(*sql.Selector)) {
+ p := make([]predicate.Admin, len(ps))
+ for i := range ps {
+ p[i] = ps[i]
+ }
+ m.Where(p...)
+}
+
+// Op returns the operation name.
+func (m *AdminMutation) Op() Op {
+ return m.op
+}
+
+// SetOp allows setting the mutation operation.
+func (m *AdminMutation) SetOp(op Op) {
+ m.op = op
+}
+
+// Type returns the node type of this mutation (Admin).
+func (m *AdminMutation) 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 *AdminMutation) Fields() []string {
+ fields := make([]string, 0, 6)
+ if m.username != nil {
+ fields = append(fields, admin.FieldUsername)
+ }
+ if m.password != nil {
+ fields = append(fields, admin.FieldPassword)
+ }
+ if m.status != nil {
+ fields = append(fields, admin.FieldStatus)
+ }
+ if m.last_active_at != nil {
+ fields = append(fields, admin.FieldLastActiveAt)
+ }
+ if m.created_at != nil {
+ fields = append(fields, admin.FieldCreatedAt)
+ }
+ if m.updated_at != nil {
+ fields = append(fields, admin.FieldUpdatedAt)
+ }
+ 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 *AdminMutation) Field(name string) (ent.Value, bool) {
+ switch name {
+ case admin.FieldUsername:
+ return m.Username()
+ case admin.FieldPassword:
+ return m.Password()
+ case admin.FieldStatus:
+ return m.Status()
+ case admin.FieldLastActiveAt:
+ return m.LastActiveAt()
+ case admin.FieldCreatedAt:
+ return m.CreatedAt()
+ case admin.FieldUpdatedAt:
+ return m.UpdatedAt()
+ }
+ 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 *AdminMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
+ switch name {
+ case admin.FieldUsername:
+ return m.OldUsername(ctx)
+ case admin.FieldPassword:
+ return m.OldPassword(ctx)
+ case admin.FieldStatus:
+ return m.OldStatus(ctx)
+ case admin.FieldLastActiveAt:
+ return m.OldLastActiveAt(ctx)
+ case admin.FieldCreatedAt:
+ return m.OldCreatedAt(ctx)
+ case admin.FieldUpdatedAt:
+ return m.OldUpdatedAt(ctx)
+ }
+ return nil, fmt.Errorf("unknown Admin 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 *AdminMutation) SetField(name string, value ent.Value) error {
+ switch name {
+ case admin.FieldUsername:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetUsername(v)
+ return nil
+ case admin.FieldPassword:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetPassword(v)
+ return nil
+ case admin.FieldStatus:
+ v, ok := value.(consts.AdminStatus)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetStatus(v)
+ return nil
+ case admin.FieldLastActiveAt:
+ v, ok := value.(time.Time)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetLastActiveAt(v)
+ return nil
+ case admin.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 admin.FieldUpdatedAt:
+ v, ok := value.(time.Time)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetUpdatedAt(v)
+ return nil
+ }
+ return fmt.Errorf("unknown Admin field %s", name)
+}
+
+// AddedFields returns all numeric fields that were incremented/decremented during
+// this mutation.
+func (m *AdminMutation) AddedFields() []string {
+ return nil
+}
+
+// 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 *AdminMutation) AddedField(name string) (ent.Value, bool) {
+ 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 *AdminMutation) AddField(name string, value ent.Value) error {
+ switch name {
+ }
+ return fmt.Errorf("unknown Admin numeric field %s", name)
+}
+
+// ClearedFields returns all nullable fields that were cleared during this
+// mutation.
+func (m *AdminMutation) ClearedFields() []string {
+ return nil
+}
+
+// FieldCleared returns a boolean indicating if a field with the given name was
+// cleared in this mutation.
+func (m *AdminMutation) 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 *AdminMutation) ClearField(name string) error {
+ return fmt.Errorf("unknown Admin 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 *AdminMutation) ResetField(name string) error {
+ switch name {
+ case admin.FieldUsername:
+ m.ResetUsername()
+ return nil
+ case admin.FieldPassword:
+ m.ResetPassword()
+ return nil
+ case admin.FieldStatus:
+ m.ResetStatus()
+ return nil
+ case admin.FieldLastActiveAt:
+ m.ResetLastActiveAt()
+ return nil
+ case admin.FieldCreatedAt:
+ m.ResetCreatedAt()
+ return nil
+ case admin.FieldUpdatedAt:
+ m.ResetUpdatedAt()
+ return nil
+ }
+ return fmt.Errorf("unknown Admin field %s", name)
+}
+
+// AddedEdges returns all edge names that were set/added in this mutation.
+func (m *AdminMutation) AddedEdges() []string {
+ edges := make([]string, 0, 1)
+ if m.login_histories != nil {
+ edges = append(edges, admin.EdgeLoginHistories)
+ }
+ return edges
+}
+
+// AddedIDs returns all IDs (to other nodes) that were added for the given edge
+// name in this mutation.
+func (m *AdminMutation) AddedIDs(name string) []ent.Value {
+ switch name {
+ case admin.EdgeLoginHistories:
+ ids := make([]ent.Value, 0, len(m.login_histories))
+ for id := range m.login_histories {
+ ids = append(ids, id)
+ }
+ return ids
+ }
+ return nil
+}
+
+// RemovedEdges returns all edge names that were removed in this mutation.
+func (m *AdminMutation) RemovedEdges() []string {
+ edges := make([]string, 0, 1)
+ if m.removedlogin_histories != nil {
+ edges = append(edges, admin.EdgeLoginHistories)
+ }
+ return edges
+}
+
+// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with
+// the given name in this mutation.
+func (m *AdminMutation) RemovedIDs(name string) []ent.Value {
+ switch name {
+ case admin.EdgeLoginHistories:
+ ids := make([]ent.Value, 0, len(m.removedlogin_histories))
+ for id := range m.removedlogin_histories {
+ ids = append(ids, id)
+ }
+ return ids
+ }
+ return nil
+}
+
+// ClearedEdges returns all edge names that were cleared in this mutation.
+func (m *AdminMutation) ClearedEdges() []string {
+ edges := make([]string, 0, 1)
+ if m.clearedlogin_histories {
+ edges = append(edges, admin.EdgeLoginHistories)
+ }
+ return edges
+}
+
+// EdgeCleared returns a boolean which indicates if the edge with the given name
+// was cleared in this mutation.
+func (m *AdminMutation) EdgeCleared(name string) bool {
+ switch name {
+ case admin.EdgeLoginHistories:
+ return m.clearedlogin_histories
+ }
+ 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 *AdminMutation) ClearEdge(name string) error {
+ switch name {
+ }
+ return fmt.Errorf("unknown Admin 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 *AdminMutation) ResetEdge(name string) error {
+ switch name {
+ case admin.EdgeLoginHistories:
+ m.ResetLoginHistories()
+ return nil
+ }
+ return fmt.Errorf("unknown Admin edge %s", name)
+}
+
+// AdminLoginHistoryMutation represents an operation that mutates the AdminLoginHistory nodes in the graph.
+type AdminLoginHistoryMutation struct {
+ config
+ op Op
+ typ string
+ id *uuid.UUID
+ admin_id *uuid.UUID
+ ip *string
+ country *string
+ province *string
+ city *string
+ isp *string
+ asn *string
+ client_version *string
+ device *string
+ created_at *time.Time
+ clearedFields map[string]struct{}
+ owner *uuid.UUID
+ clearedowner bool
+ done bool
+ oldValue func(context.Context) (*AdminLoginHistory, error)
+ predicates []predicate.AdminLoginHistory
+}
+
+var _ ent.Mutation = (*AdminLoginHistoryMutation)(nil)
+
+// adminloginhistoryOption allows management of the mutation configuration using functional options.
+type adminloginhistoryOption func(*AdminLoginHistoryMutation)
+
+// newAdminLoginHistoryMutation creates new mutation for the AdminLoginHistory entity.
+func newAdminLoginHistoryMutation(c config, op Op, opts ...adminloginhistoryOption) *AdminLoginHistoryMutation {
+ m := &AdminLoginHistoryMutation{
+ config: c,
+ op: op,
+ typ: TypeAdminLoginHistory,
+ clearedFields: make(map[string]struct{}),
+ }
+ for _, opt := range opts {
+ opt(m)
+ }
+ return m
+}
+
+// withAdminLoginHistoryID sets the ID field of the mutation.
+func withAdminLoginHistoryID(id uuid.UUID) adminloginhistoryOption {
+ return func(m *AdminLoginHistoryMutation) {
+ var (
+ err error
+ once sync.Once
+ value *AdminLoginHistory
+ )
+ m.oldValue = func(ctx context.Context) (*AdminLoginHistory, error) {
+ once.Do(func() {
+ if m.done {
+ err = errors.New("querying old values post mutation is not allowed")
+ } else {
+ value, err = m.Client().AdminLoginHistory.Get(ctx, id)
+ }
+ })
+ return value, err
+ }
+ m.id = &id
+ }
+}
+
+// withAdminLoginHistory sets the old AdminLoginHistory of the mutation.
+func withAdminLoginHistory(node *AdminLoginHistory) adminloginhistoryOption {
+ return func(m *AdminLoginHistoryMutation) {
+ m.oldValue = func(context.Context) (*AdminLoginHistory, 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 AdminLoginHistoryMutation) 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 AdminLoginHistoryMutation) Tx() (*Tx, error) {
+ if _, ok := m.driver.(*txDriver); !ok {
+ return nil, errors.New("db: mutation is not running in a transaction")
+ }
+ tx := &Tx{config: m.config}
+ tx.init()
+ return tx, nil
+}
+
+// SetID sets the value of the id field. Note that this
+// operation is only accepted on creation of AdminLoginHistory entities.
+func (m *AdminLoginHistoryMutation) SetID(id uuid.UUID) {
+ m.id = &id
+}
+
+// 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 *AdminLoginHistoryMutation) ID() (id uuid.UUID, 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 *AdminLoginHistoryMutation) IDs(ctx context.Context) ([]uuid.UUID, error) {
+ switch {
+ case m.op.Is(OpUpdateOne | OpDeleteOne):
+ id, exists := m.ID()
+ if exists {
+ return []uuid.UUID{id}, nil
+ }
+ fallthrough
+ case m.op.Is(OpUpdate | OpDelete):
+ return m.Client().AdminLoginHistory.Query().Where(m.predicates...).IDs(ctx)
+ default:
+ return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op)
+ }
+}
+
+// SetAdminID sets the "admin_id" field.
+func (m *AdminLoginHistoryMutation) SetAdminID(u uuid.UUID) {
+ m.admin_id = &u
+}
+
+// AdminID returns the value of the "admin_id" field in the mutation.
+func (m *AdminLoginHistoryMutation) AdminID() (r uuid.UUID, exists bool) {
+ v := m.admin_id
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldAdminID returns the old "admin_id" field's value of the AdminLoginHistory entity.
+// If the AdminLoginHistory 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 *AdminLoginHistoryMutation) OldAdminID(ctx context.Context) (v uuid.UUID, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldAdminID is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldAdminID requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldAdminID: %w", err)
+ }
+ return oldValue.AdminID, nil
+}
+
+// ResetAdminID resets all changes to the "admin_id" field.
+func (m *AdminLoginHistoryMutation) ResetAdminID() {
+ m.admin_id = nil
+}
+
+// SetIP sets the "ip" field.
+func (m *AdminLoginHistoryMutation) SetIP(s string) {
+ m.ip = &s
+}
+
+// IP returns the value of the "ip" field in the mutation.
+func (m *AdminLoginHistoryMutation) IP() (r string, exists bool) {
+ v := m.ip
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldIP returns the old "ip" field's value of the AdminLoginHistory entity.
+// If the AdminLoginHistory 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 *AdminLoginHistoryMutation) OldIP(ctx context.Context) (v string, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldIP is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldIP requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldIP: %w", err)
+ }
+ return oldValue.IP, nil
+}
+
+// ResetIP resets all changes to the "ip" field.
+func (m *AdminLoginHistoryMutation) ResetIP() {
+ m.ip = nil
+}
+
+// SetCountry sets the "country" field.
+func (m *AdminLoginHistoryMutation) SetCountry(s string) {
+ m.country = &s
+}
+
+// Country returns the value of the "country" field in the mutation.
+func (m *AdminLoginHistoryMutation) Country() (r string, exists bool) {
+ v := m.country
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldCountry returns the old "country" field's value of the AdminLoginHistory entity.
+// If the AdminLoginHistory 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 *AdminLoginHistoryMutation) OldCountry(ctx context.Context) (v string, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldCountry is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldCountry requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldCountry: %w", err)
+ }
+ return oldValue.Country, nil
+}
+
+// ResetCountry resets all changes to the "country" field.
+func (m *AdminLoginHistoryMutation) ResetCountry() {
+ m.country = nil
+}
+
+// SetProvince sets the "province" field.
+func (m *AdminLoginHistoryMutation) SetProvince(s string) {
+ m.province = &s
+}
+
+// Province returns the value of the "province" field in the mutation.
+func (m *AdminLoginHistoryMutation) Province() (r string, exists bool) {
+ v := m.province
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldProvince returns the old "province" field's value of the AdminLoginHistory entity.
+// If the AdminLoginHistory 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 *AdminLoginHistoryMutation) OldProvince(ctx context.Context) (v string, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldProvince is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldProvince requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldProvince: %w", err)
+ }
+ return oldValue.Province, nil
+}
+
+// ResetProvince resets all changes to the "province" field.
+func (m *AdminLoginHistoryMutation) ResetProvince() {
+ m.province = nil
+}
+
+// SetCity sets the "city" field.
+func (m *AdminLoginHistoryMutation) SetCity(s string) {
+ m.city = &s
+}
+
+// City returns the value of the "city" field in the mutation.
+func (m *AdminLoginHistoryMutation) City() (r string, exists bool) {
+ v := m.city
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldCity returns the old "city" field's value of the AdminLoginHistory entity.
+// If the AdminLoginHistory 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 *AdminLoginHistoryMutation) OldCity(ctx context.Context) (v string, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldCity is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldCity requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldCity: %w", err)
+ }
+ return oldValue.City, nil
+}
+
+// ResetCity resets all changes to the "city" field.
+func (m *AdminLoginHistoryMutation) ResetCity() {
+ m.city = nil
+}
+
+// SetIsp sets the "isp" field.
+func (m *AdminLoginHistoryMutation) SetIsp(s string) {
+ m.isp = &s
+}
+
+// Isp returns the value of the "isp" field in the mutation.
+func (m *AdminLoginHistoryMutation) Isp() (r string, exists bool) {
+ v := m.isp
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldIsp returns the old "isp" field's value of the AdminLoginHistory entity.
+// If the AdminLoginHistory 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 *AdminLoginHistoryMutation) OldIsp(ctx context.Context) (v string, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldIsp is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldIsp requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldIsp: %w", err)
+ }
+ return oldValue.Isp, nil
+}
+
+// ResetIsp resets all changes to the "isp" field.
+func (m *AdminLoginHistoryMutation) ResetIsp() {
+ m.isp = nil
+}
+
+// SetAsn sets the "asn" field.
+func (m *AdminLoginHistoryMutation) SetAsn(s string) {
+ m.asn = &s
+}
+
+// Asn returns the value of the "asn" field in the mutation.
+func (m *AdminLoginHistoryMutation) Asn() (r string, exists bool) {
+ v := m.asn
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldAsn returns the old "asn" field's value of the AdminLoginHistory entity.
+// If the AdminLoginHistory 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 *AdminLoginHistoryMutation) OldAsn(ctx context.Context) (v string, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldAsn is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldAsn requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldAsn: %w", err)
+ }
+ return oldValue.Asn, nil
+}
+
+// ResetAsn resets all changes to the "asn" field.
+func (m *AdminLoginHistoryMutation) ResetAsn() {
+ m.asn = nil
+}
+
+// SetClientVersion sets the "client_version" field.
+func (m *AdminLoginHistoryMutation) SetClientVersion(s string) {
+ m.client_version = &s
+}
+
+// ClientVersion returns the value of the "client_version" field in the mutation.
+func (m *AdminLoginHistoryMutation) ClientVersion() (r string, exists bool) {
+ v := m.client_version
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldClientVersion returns the old "client_version" field's value of the AdminLoginHistory entity.
+// If the AdminLoginHistory 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 *AdminLoginHistoryMutation) OldClientVersion(ctx context.Context) (v string, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldClientVersion is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldClientVersion requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldClientVersion: %w", err)
+ }
+ return oldValue.ClientVersion, nil
+}
+
+// ResetClientVersion resets all changes to the "client_version" field.
+func (m *AdminLoginHistoryMutation) ResetClientVersion() {
+ m.client_version = nil
+}
+
+// SetDevice sets the "device" field.
+func (m *AdminLoginHistoryMutation) SetDevice(s string) {
+ m.device = &s
+}
+
+// Device returns the value of the "device" field in the mutation.
+func (m *AdminLoginHistoryMutation) Device() (r string, exists bool) {
+ v := m.device
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldDevice returns the old "device" field's value of the AdminLoginHistory entity.
+// If the AdminLoginHistory 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 *AdminLoginHistoryMutation) OldDevice(ctx context.Context) (v string, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldDevice is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldDevice requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldDevice: %w", err)
+ }
+ return oldValue.Device, nil
+}
+
+// ResetDevice resets all changes to the "device" field.
+func (m *AdminLoginHistoryMutation) ResetDevice() {
+ m.device = nil
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (m *AdminLoginHistoryMutation) SetCreatedAt(t time.Time) {
+ m.created_at = &t
+}
+
+// CreatedAt returns the value of the "created_at" field in the mutation.
+func (m *AdminLoginHistoryMutation) 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 AdminLoginHistory entity.
+// If the AdminLoginHistory 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 *AdminLoginHistoryMutation) 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 *AdminLoginHistoryMutation) ResetCreatedAt() {
+ m.created_at = nil
+}
+
+// SetOwnerID sets the "owner" edge to the Admin entity by id.
+func (m *AdminLoginHistoryMutation) SetOwnerID(id uuid.UUID) {
+ m.owner = &id
+}
+
+// ClearOwner clears the "owner" edge to the Admin entity.
+func (m *AdminLoginHistoryMutation) ClearOwner() {
+ m.clearedowner = true
+}
+
+// OwnerCleared reports if the "owner" edge to the Admin entity was cleared.
+func (m *AdminLoginHistoryMutation) OwnerCleared() bool {
+ return m.clearedowner
+}
+
+// OwnerID returns the "owner" edge ID in the mutation.
+func (m *AdminLoginHistoryMutation) OwnerID() (id uuid.UUID, exists bool) {
+ if m.owner != nil {
+ return *m.owner, true
+ }
+ return
+}
+
+// OwnerIDs returns the "owner" edge IDs in the mutation.
+// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use
+// OwnerID instead. It exists only for internal usage by the builders.
+func (m *AdminLoginHistoryMutation) OwnerIDs() (ids []uuid.UUID) {
+ if id := m.owner; id != nil {
+ ids = append(ids, *id)
+ }
+ return
+}
+
+// ResetOwner resets all changes to the "owner" edge.
+func (m *AdminLoginHistoryMutation) ResetOwner() {
+ m.owner = nil
+ m.clearedowner = false
+}
+
+// Where appends a list predicates to the AdminLoginHistoryMutation builder.
+func (m *AdminLoginHistoryMutation) Where(ps ...predicate.AdminLoginHistory) {
+ m.predicates = append(m.predicates, ps...)
+}
+
+// WhereP appends storage-level predicates to the AdminLoginHistoryMutation builder. Using this method,
+// users can use type-assertion to append predicates that do not depend on any generated package.
+func (m *AdminLoginHistoryMutation) WhereP(ps ...func(*sql.Selector)) {
+ p := make([]predicate.AdminLoginHistory, len(ps))
+ for i := range ps {
+ p[i] = ps[i]
+ }
+ m.Where(p...)
+}
+
+// Op returns the operation name.
+func (m *AdminLoginHistoryMutation) Op() Op {
+ return m.op
+}
+
+// SetOp allows setting the mutation operation.
+func (m *AdminLoginHistoryMutation) SetOp(op Op) {
+ m.op = op
+}
+
+// Type returns the node type of this mutation (AdminLoginHistory).
+func (m *AdminLoginHistoryMutation) 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 *AdminLoginHistoryMutation) Fields() []string {
+ fields := make([]string, 0, 10)
+ if m.admin_id != nil {
+ fields = append(fields, adminloginhistory.FieldAdminID)
+ }
+ if m.ip != nil {
+ fields = append(fields, adminloginhistory.FieldIP)
+ }
+ if m.country != nil {
+ fields = append(fields, adminloginhistory.FieldCountry)
+ }
+ if m.province != nil {
+ fields = append(fields, adminloginhistory.FieldProvince)
+ }
+ if m.city != nil {
+ fields = append(fields, adminloginhistory.FieldCity)
+ }
+ if m.isp != nil {
+ fields = append(fields, adminloginhistory.FieldIsp)
+ }
+ if m.asn != nil {
+ fields = append(fields, adminloginhistory.FieldAsn)
+ }
+ if m.client_version != nil {
+ fields = append(fields, adminloginhistory.FieldClientVersion)
+ }
+ if m.device != nil {
+ fields = append(fields, adminloginhistory.FieldDevice)
+ }
+ if m.created_at != nil {
+ fields = append(fields, adminloginhistory.FieldCreatedAt)
+ }
+ 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 *AdminLoginHistoryMutation) Field(name string) (ent.Value, bool) {
+ switch name {
+ case adminloginhistory.FieldAdminID:
+ return m.AdminID()
+ case adminloginhistory.FieldIP:
+ return m.IP()
+ case adminloginhistory.FieldCountry:
+ return m.Country()
+ case adminloginhistory.FieldProvince:
+ return m.Province()
+ case adminloginhistory.FieldCity:
+ return m.City()
+ case adminloginhistory.FieldIsp:
+ return m.Isp()
+ case adminloginhistory.FieldAsn:
+ return m.Asn()
+ case adminloginhistory.FieldClientVersion:
+ return m.ClientVersion()
+ case adminloginhistory.FieldDevice:
+ return m.Device()
+ case adminloginhistory.FieldCreatedAt:
+ return m.CreatedAt()
+ }
+ 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 *AdminLoginHistoryMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
+ switch name {
+ case adminloginhistory.FieldAdminID:
+ return m.OldAdminID(ctx)
+ case adminloginhistory.FieldIP:
+ return m.OldIP(ctx)
+ case adminloginhistory.FieldCountry:
+ return m.OldCountry(ctx)
+ case adminloginhistory.FieldProvince:
+ return m.OldProvince(ctx)
+ case adminloginhistory.FieldCity:
+ return m.OldCity(ctx)
+ case adminloginhistory.FieldIsp:
+ return m.OldIsp(ctx)
+ case adminloginhistory.FieldAsn:
+ return m.OldAsn(ctx)
+ case adminloginhistory.FieldClientVersion:
+ return m.OldClientVersion(ctx)
+ case adminloginhistory.FieldDevice:
+ return m.OldDevice(ctx)
+ case adminloginhistory.FieldCreatedAt:
+ return m.OldCreatedAt(ctx)
+ }
+ return nil, fmt.Errorf("unknown AdminLoginHistory 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 *AdminLoginHistoryMutation) SetField(name string, value ent.Value) error {
+ switch name {
+ case adminloginhistory.FieldAdminID:
+ v, ok := value.(uuid.UUID)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetAdminID(v)
+ return nil
+ case adminloginhistory.FieldIP:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetIP(v)
+ return nil
+ case adminloginhistory.FieldCountry:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetCountry(v)
+ return nil
+ case adminloginhistory.FieldProvince:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetProvince(v)
+ return nil
+ case adminloginhistory.FieldCity:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetCity(v)
+ return nil
+ case adminloginhistory.FieldIsp:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetIsp(v)
+ return nil
+ case adminloginhistory.FieldAsn:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetAsn(v)
+ return nil
+ case adminloginhistory.FieldClientVersion:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetClientVersion(v)
+ return nil
+ case adminloginhistory.FieldDevice:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetDevice(v)
+ return nil
+ case adminloginhistory.FieldCreatedAt:
+ v, ok := value.(time.Time)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetCreatedAt(v)
+ return nil
+ }
+ return fmt.Errorf("unknown AdminLoginHistory field %s", name)
+}
+
+// AddedFields returns all numeric fields that were incremented/decremented during
+// this mutation.
+func (m *AdminLoginHistoryMutation) AddedFields() []string {
+ return nil
+}
+
+// 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 *AdminLoginHistoryMutation) AddedField(name string) (ent.Value, bool) {
+ 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 *AdminLoginHistoryMutation) AddField(name string, value ent.Value) error {
+ switch name {
+ }
+ return fmt.Errorf("unknown AdminLoginHistory numeric field %s", name)
+}
+
+// ClearedFields returns all nullable fields that were cleared during this
+// mutation.
+func (m *AdminLoginHistoryMutation) ClearedFields() []string {
+ return nil
+}
+
+// FieldCleared returns a boolean indicating if a field with the given name was
+// cleared in this mutation.
+func (m *AdminLoginHistoryMutation) 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 *AdminLoginHistoryMutation) ClearField(name string) error {
+ return fmt.Errorf("unknown AdminLoginHistory 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 *AdminLoginHistoryMutation) ResetField(name string) error {
+ switch name {
+ case adminloginhistory.FieldAdminID:
+ m.ResetAdminID()
+ return nil
+ case adminloginhistory.FieldIP:
+ m.ResetIP()
+ return nil
+ case adminloginhistory.FieldCountry:
+ m.ResetCountry()
+ return nil
+ case adminloginhistory.FieldProvince:
+ m.ResetProvince()
+ return nil
+ case adminloginhistory.FieldCity:
+ m.ResetCity()
+ return nil
+ case adminloginhistory.FieldIsp:
+ m.ResetIsp()
+ return nil
+ case adminloginhistory.FieldAsn:
+ m.ResetAsn()
+ return nil
+ case adminloginhistory.FieldClientVersion:
+ m.ResetClientVersion()
+ return nil
+ case adminloginhistory.FieldDevice:
+ m.ResetDevice()
+ return nil
+ case adminloginhistory.FieldCreatedAt:
+ m.ResetCreatedAt()
+ return nil
+ }
+ return fmt.Errorf("unknown AdminLoginHistory field %s", name)
+}
+
+// AddedEdges returns all edge names that were set/added in this mutation.
+func (m *AdminLoginHistoryMutation) AddedEdges() []string {
+ edges := make([]string, 0, 1)
+ if m.owner != nil {
+ edges = append(edges, adminloginhistory.EdgeOwner)
+ }
+ return edges
+}
+
+// AddedIDs returns all IDs (to other nodes) that were added for the given edge
+// name in this mutation.
+func (m *AdminLoginHistoryMutation) AddedIDs(name string) []ent.Value {
+ switch name {
+ case adminloginhistory.EdgeOwner:
+ if id := m.owner; id != nil {
+ return []ent.Value{*id}
+ }
+ }
+ return nil
+}
+
+// RemovedEdges returns all edge names that were removed in this mutation.
+func (m *AdminLoginHistoryMutation) RemovedEdges() []string {
+ edges := make([]string, 0, 1)
+ return edges
+}
+
+// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with
+// the given name in this mutation.
+func (m *AdminLoginHistoryMutation) RemovedIDs(name string) []ent.Value {
+ return nil
+}
+
+// ClearedEdges returns all edge names that were cleared in this mutation.
+func (m *AdminLoginHistoryMutation) ClearedEdges() []string {
+ edges := make([]string, 0, 1)
+ if m.clearedowner {
+ edges = append(edges, adminloginhistory.EdgeOwner)
+ }
+ return edges
+}
+
+// EdgeCleared returns a boolean which indicates if the edge with the given name
+// was cleared in this mutation.
+func (m *AdminLoginHistoryMutation) EdgeCleared(name string) bool {
+ switch name {
+ case adminloginhistory.EdgeOwner:
+ return m.clearedowner
+ }
+ 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 *AdminLoginHistoryMutation) ClearEdge(name string) error {
+ switch name {
+ case adminloginhistory.EdgeOwner:
+ m.ClearOwner()
+ return nil
+ }
+ return fmt.Errorf("unknown AdminLoginHistory 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 *AdminLoginHistoryMutation) ResetEdge(name string) error {
+ switch name {
+ case adminloginhistory.EdgeOwner:
+ m.ResetOwner()
+ return nil
+ }
+ return fmt.Errorf("unknown AdminLoginHistory edge %s", name)
+}
+
+// ApiKeyMutation represents an operation that mutates the ApiKey nodes in the graph.
+type ApiKeyMutation struct {
+ config
+ op Op
+ typ string
+ id *uuid.UUID
+ user_id *uuid.UUID
+ key *string
+ name *string
+ status *consts.ApiKeyStatus
+ last_used *time.Time
+ created_at *time.Time
+ updated_at *time.Time
+ clearedFields map[string]struct{}
+ done bool
+ oldValue func(context.Context) (*ApiKey, error)
+ predicates []predicate.ApiKey
+}
+
+var _ ent.Mutation = (*ApiKeyMutation)(nil)
+
+// apikeyOption allows management of the mutation configuration using functional options.
+type apikeyOption func(*ApiKeyMutation)
+
+// newApiKeyMutation creates new mutation for the ApiKey entity.
+func newApiKeyMutation(c config, op Op, opts ...apikeyOption) *ApiKeyMutation {
+ m := &ApiKeyMutation{
+ config: c,
+ op: op,
+ typ: TypeApiKey,
+ clearedFields: make(map[string]struct{}),
+ }
+ for _, opt := range opts {
+ opt(m)
+ }
+ return m
+}
+
+// withApiKeyID sets the ID field of the mutation.
+func withApiKeyID(id uuid.UUID) apikeyOption {
+ return func(m *ApiKeyMutation) {
+ var (
+ err error
+ once sync.Once
+ value *ApiKey
+ )
+ m.oldValue = func(ctx context.Context) (*ApiKey, error) {
+ once.Do(func() {
+ if m.done {
+ err = errors.New("querying old values post mutation is not allowed")
+ } else {
+ value, err = m.Client().ApiKey.Get(ctx, id)
+ }
+ })
+ return value, err
+ }
+ m.id = &id
+ }
+}
+
+// withApiKey sets the old ApiKey of the mutation.
+func withApiKey(node *ApiKey) apikeyOption {
+ return func(m *ApiKeyMutation) {
+ m.oldValue = func(context.Context) (*ApiKey, 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 ApiKeyMutation) 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 ApiKeyMutation) Tx() (*Tx, error) {
+ if _, ok := m.driver.(*txDriver); !ok {
+ return nil, errors.New("db: mutation is not running in a transaction")
+ }
+ tx := &Tx{config: m.config}
+ tx.init()
+ return tx, nil
+}
+
+// SetID sets the value of the id field. Note that this
+// operation is only accepted on creation of ApiKey entities.
+func (m *ApiKeyMutation) SetID(id uuid.UUID) {
+ m.id = &id
+}
+
+// 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 *ApiKeyMutation) ID() (id uuid.UUID, 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 *ApiKeyMutation) IDs(ctx context.Context) ([]uuid.UUID, error) {
+ switch {
+ case m.op.Is(OpUpdateOne | OpDeleteOne):
+ id, exists := m.ID()
+ if exists {
+ return []uuid.UUID{id}, nil
+ }
+ fallthrough
+ case m.op.Is(OpUpdate | OpDelete):
+ return m.Client().ApiKey.Query().Where(m.predicates...).IDs(ctx)
+ default:
+ return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op)
+ }
+}
+
+// SetUserID sets the "user_id" field.
+func (m *ApiKeyMutation) SetUserID(u uuid.UUID) {
+ m.user_id = &u
+}
+
+// UserID returns the value of the "user_id" field in the mutation.
+func (m *ApiKeyMutation) UserID() (r uuid.UUID, exists bool) {
+ v := m.user_id
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldUserID returns the old "user_id" field's value of the ApiKey entity.
+// If the ApiKey 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 *ApiKeyMutation) OldUserID(ctx context.Context) (v uuid.UUID, 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 *ApiKeyMutation) ResetUserID() {
+ m.user_id = nil
+}
+
+// SetKey sets the "key" field.
+func (m *ApiKeyMutation) SetKey(s string) {
+ m.key = &s
+}
+
+// Key returns the value of the "key" field in the mutation.
+func (m *ApiKeyMutation) 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 ApiKey entity.
+// If the ApiKey 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 *ApiKeyMutation) 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 *ApiKeyMutation) ResetKey() {
+ m.key = nil
+}
+
+// SetName sets the "name" field.
+func (m *ApiKeyMutation) SetName(s string) {
+ m.name = &s
+}
+
+// Name returns the value of the "name" field in the mutation.
+func (m *ApiKeyMutation) 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 ApiKey entity.
+// If the ApiKey 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 *ApiKeyMutation) 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 *ApiKeyMutation) ResetName() {
+ m.name = nil
+}
+
+// SetStatus sets the "status" field.
+func (m *ApiKeyMutation) SetStatus(cks consts.ApiKeyStatus) {
+ m.status = &cks
+}
+
+// Status returns the value of the "status" field in the mutation.
+func (m *ApiKeyMutation) Status() (r consts.ApiKeyStatus, exists bool) {
+ v := m.status
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldStatus returns the old "status" field's value of the ApiKey entity.
+// If the ApiKey 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 *ApiKeyMutation) OldStatus(ctx context.Context) (v consts.ApiKeyStatus, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldStatus is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldStatus requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldStatus: %w", err)
+ }
+ return oldValue.Status, nil
+}
+
+// ResetStatus resets all changes to the "status" field.
+func (m *ApiKeyMutation) ResetStatus() {
+ m.status = nil
+}
+
+// SetLastUsed sets the "last_used" field.
+func (m *ApiKeyMutation) SetLastUsed(t time.Time) {
+ m.last_used = &t
+}
+
+// LastUsed returns the value of the "last_used" field in the mutation.
+func (m *ApiKeyMutation) LastUsed() (r time.Time, exists bool) {
+ v := m.last_used
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldLastUsed returns the old "last_used" field's value of the ApiKey entity.
+// If the ApiKey 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 *ApiKeyMutation) OldLastUsed(ctx context.Context) (v time.Time, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldLastUsed is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldLastUsed requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldLastUsed: %w", err)
+ }
+ return oldValue.LastUsed, nil
+}
+
+// ClearLastUsed clears the value of the "last_used" field.
+func (m *ApiKeyMutation) ClearLastUsed() {
+ m.last_used = nil
+ m.clearedFields[apikey.FieldLastUsed] = struct{}{}
+}
+
+// LastUsedCleared returns if the "last_used" field was cleared in this mutation.
+func (m *ApiKeyMutation) LastUsedCleared() bool {
+ _, ok := m.clearedFields[apikey.FieldLastUsed]
+ return ok
+}
+
+// ResetLastUsed resets all changes to the "last_used" field.
+func (m *ApiKeyMutation) ResetLastUsed() {
+ m.last_used = nil
+ delete(m.clearedFields, apikey.FieldLastUsed)
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (m *ApiKeyMutation) SetCreatedAt(t time.Time) {
+ m.created_at = &t
+}
+
+// CreatedAt returns the value of the "created_at" field in the mutation.
+func (m *ApiKeyMutation) 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 ApiKey entity.
+// If the ApiKey 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 *ApiKeyMutation) 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 *ApiKeyMutation) ResetCreatedAt() {
+ m.created_at = nil
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (m *ApiKeyMutation) SetUpdatedAt(t time.Time) {
+ m.updated_at = &t
+}
+
+// UpdatedAt returns the value of the "updated_at" field in the mutation.
+func (m *ApiKeyMutation) 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 ApiKey entity.
+// If the ApiKey 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 *ApiKeyMutation) 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 *ApiKeyMutation) ResetUpdatedAt() {
+ m.updated_at = nil
+}
+
+// Where appends a list predicates to the ApiKeyMutation builder.
+func (m *ApiKeyMutation) Where(ps ...predicate.ApiKey) {
+ m.predicates = append(m.predicates, ps...)
+}
+
+// WhereP appends storage-level predicates to the ApiKeyMutation builder. Using this method,
+// users can use type-assertion to append predicates that do not depend on any generated package.
+func (m *ApiKeyMutation) WhereP(ps ...func(*sql.Selector)) {
+ p := make([]predicate.ApiKey, len(ps))
+ for i := range ps {
+ p[i] = ps[i]
+ }
+ m.Where(p...)
+}
+
+// Op returns the operation name.
+func (m *ApiKeyMutation) Op() Op {
+ return m.op
+}
+
+// SetOp allows setting the mutation operation.
+func (m *ApiKeyMutation) SetOp(op Op) {
+ m.op = op
+}
+
+// Type returns the node type of this mutation (ApiKey).
+func (m *ApiKeyMutation) 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 *ApiKeyMutation) Fields() []string {
+ fields := make([]string, 0, 7)
+ if m.user_id != nil {
+ fields = append(fields, apikey.FieldUserID)
+ }
+ if m.key != nil {
+ fields = append(fields, apikey.FieldKey)
+ }
+ if m.name != nil {
+ fields = append(fields, apikey.FieldName)
+ }
+ if m.status != nil {
+ fields = append(fields, apikey.FieldStatus)
+ }
+ if m.last_used != nil {
+ fields = append(fields, apikey.FieldLastUsed)
+ }
+ if m.created_at != nil {
+ fields = append(fields, apikey.FieldCreatedAt)
+ }
+ if m.updated_at != nil {
+ fields = append(fields, apikey.FieldUpdatedAt)
+ }
+ 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 *ApiKeyMutation) Field(name string) (ent.Value, bool) {
+ switch name {
+ case apikey.FieldUserID:
+ return m.UserID()
+ case apikey.FieldKey:
+ return m.Key()
+ case apikey.FieldName:
+ return m.Name()
+ case apikey.FieldStatus:
+ return m.Status()
+ case apikey.FieldLastUsed:
+ return m.LastUsed()
+ case apikey.FieldCreatedAt:
+ return m.CreatedAt()
+ case apikey.FieldUpdatedAt:
+ return m.UpdatedAt()
+ }
+ 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 *ApiKeyMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
+ switch name {
+ case apikey.FieldUserID:
+ return m.OldUserID(ctx)
+ case apikey.FieldKey:
+ return m.OldKey(ctx)
+ case apikey.FieldName:
+ return m.OldName(ctx)
+ case apikey.FieldStatus:
+ return m.OldStatus(ctx)
+ case apikey.FieldLastUsed:
+ return m.OldLastUsed(ctx)
+ case apikey.FieldCreatedAt:
+ return m.OldCreatedAt(ctx)
+ case apikey.FieldUpdatedAt:
+ return m.OldUpdatedAt(ctx)
+ }
+ return nil, fmt.Errorf("unknown ApiKey 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 *ApiKeyMutation) SetField(name string, value ent.Value) error {
+ switch name {
+ case apikey.FieldUserID:
+ v, ok := value.(uuid.UUID)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetUserID(v)
+ return nil
+ case apikey.FieldKey:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetKey(v)
+ return nil
+ case apikey.FieldName:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetName(v)
+ return nil
+ case apikey.FieldStatus:
+ v, ok := value.(consts.ApiKeyStatus)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetStatus(v)
+ return nil
+ case apikey.FieldLastUsed:
+ v, ok := value.(time.Time)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetLastUsed(v)
+ return nil
+ case apikey.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 apikey.FieldUpdatedAt:
+ v, ok := value.(time.Time)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetUpdatedAt(v)
+ return nil
+ }
+ return fmt.Errorf("unknown ApiKey field %s", name)
+}
+
+// AddedFields returns all numeric fields that were incremented/decremented during
+// this mutation.
+func (m *ApiKeyMutation) AddedFields() []string {
+ return nil
+}
+
+// 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 *ApiKeyMutation) AddedField(name string) (ent.Value, bool) {
+ 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 *ApiKeyMutation) AddField(name string, value ent.Value) error {
+ switch name {
+ }
+ return fmt.Errorf("unknown ApiKey numeric field %s", name)
+}
+
+// ClearedFields returns all nullable fields that were cleared during this
+// mutation.
+func (m *ApiKeyMutation) ClearedFields() []string {
+ var fields []string
+ if m.FieldCleared(apikey.FieldLastUsed) {
+ fields = append(fields, apikey.FieldLastUsed)
+ }
+ return fields
+}
+
+// FieldCleared returns a boolean indicating if a field with the given name was
+// cleared in this mutation.
+func (m *ApiKeyMutation) 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 *ApiKeyMutation) ClearField(name string) error {
+ switch name {
+ case apikey.FieldLastUsed:
+ m.ClearLastUsed()
+ return nil
+ }
+ return fmt.Errorf("unknown ApiKey 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 *ApiKeyMutation) ResetField(name string) error {
+ switch name {
+ case apikey.FieldUserID:
+ m.ResetUserID()
+ return nil
+ case apikey.FieldKey:
+ m.ResetKey()
+ return nil
+ case apikey.FieldName:
+ m.ResetName()
+ return nil
+ case apikey.FieldStatus:
+ m.ResetStatus()
+ return nil
+ case apikey.FieldLastUsed:
+ m.ResetLastUsed()
+ return nil
+ case apikey.FieldCreatedAt:
+ m.ResetCreatedAt()
+ return nil
+ case apikey.FieldUpdatedAt:
+ m.ResetUpdatedAt()
+ return nil
+ }
+ return fmt.Errorf("unknown ApiKey field %s", name)
+}
+
+// AddedEdges returns all edge names that were set/added in this mutation.
+func (m *ApiKeyMutation) AddedEdges() []string {
+ edges := make([]string, 0, 0)
+ return edges
+}
+
+// AddedIDs returns all IDs (to other nodes) that were added for the given edge
+// name in this mutation.
+func (m *ApiKeyMutation) AddedIDs(name string) []ent.Value {
+ return nil
+}
+
+// RemovedEdges returns all edge names that were removed in this mutation.
+func (m *ApiKeyMutation) RemovedEdges() []string {
+ edges := make([]string, 0, 0)
+ return edges
+}
+
+// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with
+// the given name in this mutation.
+func (m *ApiKeyMutation) RemovedIDs(name string) []ent.Value {
+ return nil
+}
+
+// ClearedEdges returns all edge names that were cleared in this mutation.
+func (m *ApiKeyMutation) ClearedEdges() []string {
+ edges := make([]string, 0, 0)
+ return edges
+}
+
+// EdgeCleared returns a boolean which indicates if the edge with the given name
+// was cleared in this mutation.
+func (m *ApiKeyMutation) EdgeCleared(name string) bool {
+ return false
+}
+
+// ClearEdge clears the value of the edge with the given name. It returns an error
+// if that edge is not defined in the schema.
+func (m *ApiKeyMutation) ClearEdge(name string) error {
+ return fmt.Errorf("unknown ApiKey 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 *ApiKeyMutation) ResetEdge(name string) error {
+ return fmt.Errorf("unknown ApiKey edge %s", name)
+}
+
+// BillingPlanMutation represents an operation that mutates the BillingPlan nodes in the graph.
+type BillingPlanMutation struct {
+ config
+ op Op
+ typ string
+ id *string
+ name *string
+ description *string
+ rules *map[string]interface{}
+ created_at *time.Time
+ updated_at *time.Time
+ clearedFields map[string]struct{}
+ done bool
+ oldValue func(context.Context) (*BillingPlan, error)
+ predicates []predicate.BillingPlan
+}
+
+var _ ent.Mutation = (*BillingPlanMutation)(nil)
+
+// billingplanOption allows management of the mutation configuration using functional options.
+type billingplanOption func(*BillingPlanMutation)
+
+// newBillingPlanMutation creates new mutation for the BillingPlan entity.
+func newBillingPlanMutation(c config, op Op, opts ...billingplanOption) *BillingPlanMutation {
+ m := &BillingPlanMutation{
+ config: c,
+ op: op,
+ typ: TypeBillingPlan,
+ clearedFields: make(map[string]struct{}),
+ }
+ for _, opt := range opts {
+ opt(m)
+ }
+ return m
+}
+
+// withBillingPlanID sets the ID field of the mutation.
+func withBillingPlanID(id string) billingplanOption {
+ return func(m *BillingPlanMutation) {
+ var (
+ err error
+ once sync.Once
+ value *BillingPlan
+ )
+ m.oldValue = func(ctx context.Context) (*BillingPlan, error) {
+ once.Do(func() {
+ if m.done {
+ err = errors.New("querying old values post mutation is not allowed")
+ } else {
+ value, err = m.Client().BillingPlan.Get(ctx, id)
+ }
+ })
+ return value, err
+ }
+ m.id = &id
+ }
+}
+
+// withBillingPlan sets the old BillingPlan of the mutation.
+func withBillingPlan(node *BillingPlan) billingplanOption {
+ return func(m *BillingPlanMutation) {
+ m.oldValue = func(context.Context) (*BillingPlan, 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 BillingPlanMutation) 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 BillingPlanMutation) Tx() (*Tx, error) {
+ if _, ok := m.driver.(*txDriver); !ok {
+ return nil, errors.New("db: mutation is not running in a transaction")
+ }
+ tx := &Tx{config: m.config}
+ tx.init()
+ return tx, nil
+}
+
+// SetID sets the value of the id field. Note that this
+// operation is only accepted on creation of BillingPlan entities.
+func (m *BillingPlanMutation) SetID(id string) {
+ m.id = &id
+}
+
+// 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 *BillingPlanMutation) ID() (id string, 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 *BillingPlanMutation) IDs(ctx context.Context) ([]string, error) {
+ switch {
+ case m.op.Is(OpUpdateOne | OpDeleteOne):
+ id, exists := m.ID()
+ if exists {
+ return []string{id}, nil
+ }
+ fallthrough
+ case m.op.Is(OpUpdate | OpDelete):
+ return m.Client().BillingPlan.Query().Where(m.predicates...).IDs(ctx)
+ default:
+ return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op)
+ }
+}
+
+// SetName sets the "name" field.
+func (m *BillingPlanMutation) SetName(s string) {
+ m.name = &s
+}
+
+// Name returns the value of the "name" field in the mutation.
+func (m *BillingPlanMutation) 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 BillingPlan entity.
+// If the BillingPlan 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 *BillingPlanMutation) 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 *BillingPlanMutation) ResetName() {
+ m.name = nil
+}
+
+// SetDescription sets the "description" field.
+func (m *BillingPlanMutation) SetDescription(s string) {
+ m.description = &s
+}
+
+// Description returns the value of the "description" field in the mutation.
+func (m *BillingPlanMutation) 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 BillingPlan entity.
+// If the BillingPlan 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 *BillingPlanMutation) 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 *BillingPlanMutation) ResetDescription() {
+ m.description = nil
+}
+
+// SetRules sets the "rules" field.
+func (m *BillingPlanMutation) SetRules(value map[string]interface{}) {
+ m.rules = &value
+}
+
+// Rules returns the value of the "rules" field in the mutation.
+func (m *BillingPlanMutation) Rules() (r map[string]interface{}, exists bool) {
+ v := m.rules
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldRules returns the old "rules" field's value of the BillingPlan entity.
+// If the BillingPlan 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 *BillingPlanMutation) OldRules(ctx context.Context) (v map[string]interface{}, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldRules is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldRules requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldRules: %w", err)
+ }
+ return oldValue.Rules, nil
+}
+
+// ResetRules resets all changes to the "rules" field.
+func (m *BillingPlanMutation) ResetRules() {
+ m.rules = nil
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (m *BillingPlanMutation) SetCreatedAt(t time.Time) {
+ m.created_at = &t
+}
+
+// CreatedAt returns the value of the "created_at" field in the mutation.
+func (m *BillingPlanMutation) 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 BillingPlan entity.
+// If the BillingPlan 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 *BillingPlanMutation) 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 *BillingPlanMutation) ResetCreatedAt() {
+ m.created_at = nil
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (m *BillingPlanMutation) SetUpdatedAt(t time.Time) {
+ m.updated_at = &t
+}
+
+// UpdatedAt returns the value of the "updated_at" field in the mutation.
+func (m *BillingPlanMutation) 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 BillingPlan entity.
+// If the BillingPlan 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 *BillingPlanMutation) 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 *BillingPlanMutation) ResetUpdatedAt() {
+ m.updated_at = nil
+}
+
+// Where appends a list predicates to the BillingPlanMutation builder.
+func (m *BillingPlanMutation) Where(ps ...predicate.BillingPlan) {
+ m.predicates = append(m.predicates, ps...)
+}
+
+// WhereP appends storage-level predicates to the BillingPlanMutation builder. Using this method,
+// users can use type-assertion to append predicates that do not depend on any generated package.
+func (m *BillingPlanMutation) WhereP(ps ...func(*sql.Selector)) {
+ p := make([]predicate.BillingPlan, len(ps))
+ for i := range ps {
+ p[i] = ps[i]
+ }
+ m.Where(p...)
+}
+
+// Op returns the operation name.
+func (m *BillingPlanMutation) Op() Op {
+ return m.op
+}
+
+// SetOp allows setting the mutation operation.
+func (m *BillingPlanMutation) SetOp(op Op) {
+ m.op = op
+}
+
+// Type returns the node type of this mutation (BillingPlan).
+func (m *BillingPlanMutation) 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 *BillingPlanMutation) Fields() []string {
+ fields := make([]string, 0, 5)
+ if m.name != nil {
+ fields = append(fields, billingplan.FieldName)
+ }
+ if m.description != nil {
+ fields = append(fields, billingplan.FieldDescription)
+ }
+ if m.rules != nil {
+ fields = append(fields, billingplan.FieldRules)
+ }
+ if m.created_at != nil {
+ fields = append(fields, billingplan.FieldCreatedAt)
+ }
+ if m.updated_at != nil {
+ fields = append(fields, billingplan.FieldUpdatedAt)
+ }
+ 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 *BillingPlanMutation) Field(name string) (ent.Value, bool) {
+ switch name {
+ case billingplan.FieldName:
+ return m.Name()
+ case billingplan.FieldDescription:
+ return m.Description()
+ case billingplan.FieldRules:
+ return m.Rules()
+ case billingplan.FieldCreatedAt:
+ return m.CreatedAt()
+ case billingplan.FieldUpdatedAt:
+ return m.UpdatedAt()
+ }
+ 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 *BillingPlanMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
+ switch name {
+ case billingplan.FieldName:
+ return m.OldName(ctx)
+ case billingplan.FieldDescription:
+ return m.OldDescription(ctx)
+ case billingplan.FieldRules:
+ return m.OldRules(ctx)
+ case billingplan.FieldCreatedAt:
+ return m.OldCreatedAt(ctx)
+ case billingplan.FieldUpdatedAt:
+ return m.OldUpdatedAt(ctx)
+ }
+ return nil, fmt.Errorf("unknown BillingPlan 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 *BillingPlanMutation) SetField(name string, value ent.Value) error {
+ switch name {
+ case billingplan.FieldName:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetName(v)
+ return nil
+ case billingplan.FieldDescription:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetDescription(v)
+ return nil
+ case billingplan.FieldRules:
+ v, ok := value.(map[string]interface{})
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetRules(v)
+ return nil
+ case billingplan.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 billingplan.FieldUpdatedAt:
+ v, ok := value.(time.Time)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetUpdatedAt(v)
+ return nil
+ }
+ return fmt.Errorf("unknown BillingPlan field %s", name)
+}
+
+// AddedFields returns all numeric fields that were incremented/decremented during
+// this mutation.
+func (m *BillingPlanMutation) AddedFields() []string {
+ return nil
+}
+
+// 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 *BillingPlanMutation) AddedField(name string) (ent.Value, bool) {
+ 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 *BillingPlanMutation) AddField(name string, value ent.Value) error {
+ switch name {
+ }
+ return fmt.Errorf("unknown BillingPlan numeric field %s", name)
+}
+
+// ClearedFields returns all nullable fields that were cleared during this
+// mutation.
+func (m *BillingPlanMutation) ClearedFields() []string {
+ return nil
+}
+
+// FieldCleared returns a boolean indicating if a field with the given name was
+// cleared in this mutation.
+func (m *BillingPlanMutation) 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 *BillingPlanMutation) ClearField(name string) error {
+ return fmt.Errorf("unknown BillingPlan 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 *BillingPlanMutation) ResetField(name string) error {
+ switch name {
+ case billingplan.FieldName:
+ m.ResetName()
+ return nil
+ case billingplan.FieldDescription:
+ m.ResetDescription()
+ return nil
+ case billingplan.FieldRules:
+ m.ResetRules()
+ return nil
+ case billingplan.FieldCreatedAt:
+ m.ResetCreatedAt()
+ return nil
+ case billingplan.FieldUpdatedAt:
+ m.ResetUpdatedAt()
+ return nil
+ }
+ return fmt.Errorf("unknown BillingPlan field %s", name)
+}
+
+// AddedEdges returns all edge names that were set/added in this mutation.
+func (m *BillingPlanMutation) AddedEdges() []string {
+ edges := make([]string, 0, 0)
+ return edges
+}
+
+// AddedIDs returns all IDs (to other nodes) that were added for the given edge
+// name in this mutation.
+func (m *BillingPlanMutation) AddedIDs(name string) []ent.Value {
+ return nil
+}
+
+// RemovedEdges returns all edge names that were removed in this mutation.
+func (m *BillingPlanMutation) RemovedEdges() []string {
+ edges := make([]string, 0, 0)
+ return edges
+}
+
+// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with
+// the given name in this mutation.
+func (m *BillingPlanMutation) RemovedIDs(name string) []ent.Value {
+ return nil
+}
+
+// ClearedEdges returns all edge names that were cleared in this mutation.
+func (m *BillingPlanMutation) ClearedEdges() []string {
+ edges := make([]string, 0, 0)
+ return edges
+}
+
+// EdgeCleared returns a boolean which indicates if the edge with the given name
+// was cleared in this mutation.
+func (m *BillingPlanMutation) EdgeCleared(name string) bool {
+ return false
+}
+
+// ClearEdge clears the value of the edge with the given name. It returns an error
+// if that edge is not defined in the schema.
+func (m *BillingPlanMutation) ClearEdge(name string) error {
+ return fmt.Errorf("unknown BillingPlan 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 *BillingPlanMutation) ResetEdge(name string) error {
+ return fmt.Errorf("unknown BillingPlan edge %s", name)
+}
+
+// BillingQuotaMutation represents an operation that mutates the BillingQuota nodes in the graph.
+type BillingQuotaMutation struct {
+ config
+ op Op
+ typ string
+ id *string
+ deleted_at *time.Time
+ user_id *string
+ total *int64
+ addtotal *int64
+ used *int64
+ addused *int64
+ remain *int64
+ addremain *int64
+ created_at *time.Time
+ updated_at *time.Time
+ clearedFields map[string]struct{}
+ done bool
+ oldValue func(context.Context) (*BillingQuota, error)
+ predicates []predicate.BillingQuota
+}
+
+var _ ent.Mutation = (*BillingQuotaMutation)(nil)
+
+// billingquotaOption allows management of the mutation configuration using functional options.
+type billingquotaOption func(*BillingQuotaMutation)
+
+// newBillingQuotaMutation creates new mutation for the BillingQuota entity.
+func newBillingQuotaMutation(c config, op Op, opts ...billingquotaOption) *BillingQuotaMutation {
+ m := &BillingQuotaMutation{
+ config: c,
+ op: op,
+ typ: TypeBillingQuota,
+ clearedFields: make(map[string]struct{}),
+ }
+ for _, opt := range opts {
+ opt(m)
+ }
+ return m
+}
+
+// withBillingQuotaID sets the ID field of the mutation.
+func withBillingQuotaID(id string) billingquotaOption {
+ return func(m *BillingQuotaMutation) {
+ var (
+ err error
+ once sync.Once
+ value *BillingQuota
+ )
+ m.oldValue = func(ctx context.Context) (*BillingQuota, error) {
+ once.Do(func() {
+ if m.done {
+ err = errors.New("querying old values post mutation is not allowed")
+ } else {
+ value, err = m.Client().BillingQuota.Get(ctx, id)
+ }
+ })
+ return value, err
+ }
+ m.id = &id
+ }
+}
+
+// withBillingQuota sets the old BillingQuota of the mutation.
+func withBillingQuota(node *BillingQuota) billingquotaOption {
+ return func(m *BillingQuotaMutation) {
+ m.oldValue = func(context.Context) (*BillingQuota, 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 BillingQuotaMutation) 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 BillingQuotaMutation) Tx() (*Tx, error) {
+ if _, ok := m.driver.(*txDriver); !ok {
+ return nil, errors.New("db: mutation is not running in a transaction")
+ }
+ tx := &Tx{config: m.config}
+ tx.init()
+ return tx, nil
+}
+
+// SetID sets the value of the id field. Note that this
+// operation is only accepted on creation of BillingQuota entities.
+func (m *BillingQuotaMutation) SetID(id string) {
+ m.id = &id
+}
+
+// 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 *BillingQuotaMutation) ID() (id string, 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 *BillingQuotaMutation) IDs(ctx context.Context) ([]string, error) {
+ switch {
+ case m.op.Is(OpUpdateOne | OpDeleteOne):
+ id, exists := m.ID()
+ if exists {
+ return []string{id}, nil
+ }
+ fallthrough
+ case m.op.Is(OpUpdate | OpDelete):
+ return m.Client().BillingQuota.Query().Where(m.predicates...).IDs(ctx)
+ default:
+ return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op)
+ }
+}
+
+// SetDeletedAt sets the "deleted_at" field.
+func (m *BillingQuotaMutation) SetDeletedAt(t time.Time) {
+ m.deleted_at = &t
+}
+
+// DeletedAt returns the value of the "deleted_at" field in the mutation.
+func (m *BillingQuotaMutation) 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 BillingQuota entity.
+// If the BillingQuota 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 *BillingQuotaMutation) 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 *BillingQuotaMutation) ClearDeletedAt() {
+ m.deleted_at = nil
+ m.clearedFields[billingquota.FieldDeletedAt] = struct{}{}
+}
+
+// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation.
+func (m *BillingQuotaMutation) DeletedAtCleared() bool {
+ _, ok := m.clearedFields[billingquota.FieldDeletedAt]
+ return ok
+}
+
+// ResetDeletedAt resets all changes to the "deleted_at" field.
+func (m *BillingQuotaMutation) ResetDeletedAt() {
+ m.deleted_at = nil
+ delete(m.clearedFields, billingquota.FieldDeletedAt)
+}
+
+// SetUserID sets the "user_id" field.
+func (m *BillingQuotaMutation) SetUserID(s string) {
+ m.user_id = &s
+}
+
+// UserID returns the value of the "user_id" field in the mutation.
+func (m *BillingQuotaMutation) UserID() (r string, exists bool) {
+ v := m.user_id
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldUserID returns the old "user_id" field's value of the BillingQuota entity.
+// If the BillingQuota 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 *BillingQuotaMutation) OldUserID(ctx context.Context) (v string, 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 *BillingQuotaMutation) ResetUserID() {
+ m.user_id = nil
+}
+
+// SetTotal sets the "total" field.
+func (m *BillingQuotaMutation) SetTotal(i int64) {
+ m.total = &i
+ m.addtotal = nil
+}
+
+// Total returns the value of the "total" field in the mutation.
+func (m *BillingQuotaMutation) Total() (r int64, exists bool) {
+ v := m.total
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldTotal returns the old "total" field's value of the BillingQuota entity.
+// If the BillingQuota 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 *BillingQuotaMutation) OldTotal(ctx context.Context) (v int64, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldTotal is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldTotal requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldTotal: %w", err)
+ }
+ return oldValue.Total, nil
+}
+
+// AddTotal adds i to the "total" field.
+func (m *BillingQuotaMutation) AddTotal(i int64) {
+ if m.addtotal != nil {
+ *m.addtotal += i
+ } else {
+ m.addtotal = &i
+ }
+}
+
+// AddedTotal returns the value that was added to the "total" field in this mutation.
+func (m *BillingQuotaMutation) AddedTotal() (r int64, exists bool) {
+ v := m.addtotal
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// ResetTotal resets all changes to the "total" field.
+func (m *BillingQuotaMutation) ResetTotal() {
+ m.total = nil
+ m.addtotal = nil
+}
+
+// SetUsed sets the "used" field.
+func (m *BillingQuotaMutation) SetUsed(i int64) {
+ m.used = &i
+ m.addused = nil
+}
+
+// Used returns the value of the "used" field in the mutation.
+func (m *BillingQuotaMutation) Used() (r int64, exists bool) {
+ v := m.used
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldUsed returns the old "used" field's value of the BillingQuota entity.
+// If the BillingQuota 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 *BillingQuotaMutation) OldUsed(ctx context.Context) (v int64, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldUsed is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldUsed requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldUsed: %w", err)
+ }
+ return oldValue.Used, nil
+}
+
+// AddUsed adds i to the "used" field.
+func (m *BillingQuotaMutation) AddUsed(i int64) {
+ if m.addused != nil {
+ *m.addused += i
+ } else {
+ m.addused = &i
+ }
+}
+
+// AddedUsed returns the value that was added to the "used" field in this mutation.
+func (m *BillingQuotaMutation) AddedUsed() (r int64, exists bool) {
+ v := m.addused
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// ResetUsed resets all changes to the "used" field.
+func (m *BillingQuotaMutation) ResetUsed() {
+ m.used = nil
+ m.addused = nil
+}
+
+// SetRemain sets the "remain" field.
+func (m *BillingQuotaMutation) SetRemain(i int64) {
+ m.remain = &i
+ m.addremain = nil
+}
+
+// Remain returns the value of the "remain" field in the mutation.
+func (m *BillingQuotaMutation) Remain() (r int64, exists bool) {
+ v := m.remain
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldRemain returns the old "remain" field's value of the BillingQuota entity.
+// If the BillingQuota 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 *BillingQuotaMutation) OldRemain(ctx context.Context) (v int64, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldRemain is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldRemain requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldRemain: %w", err)
+ }
+ return oldValue.Remain, nil
+}
+
+// AddRemain adds i to the "remain" field.
+func (m *BillingQuotaMutation) AddRemain(i int64) {
+ if m.addremain != nil {
+ *m.addremain += i
+ } else {
+ m.addremain = &i
+ }
+}
+
+// AddedRemain returns the value that was added to the "remain" field in this mutation.
+func (m *BillingQuotaMutation) AddedRemain() (r int64, exists bool) {
+ v := m.addremain
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// ResetRemain resets all changes to the "remain" field.
+func (m *BillingQuotaMutation) ResetRemain() {
+ m.remain = nil
+ m.addremain = nil
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (m *BillingQuotaMutation) SetCreatedAt(t time.Time) {
+ m.created_at = &t
+}
+
+// CreatedAt returns the value of the "created_at" field in the mutation.
+func (m *BillingQuotaMutation) 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 BillingQuota entity.
+// If the BillingQuota 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 *BillingQuotaMutation) 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 *BillingQuotaMutation) ResetCreatedAt() {
+ m.created_at = nil
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (m *BillingQuotaMutation) SetUpdatedAt(t time.Time) {
+ m.updated_at = &t
+}
+
+// UpdatedAt returns the value of the "updated_at" field in the mutation.
+func (m *BillingQuotaMutation) 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 BillingQuota entity.
+// If the BillingQuota 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 *BillingQuotaMutation) 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 *BillingQuotaMutation) ResetUpdatedAt() {
+ m.updated_at = nil
+}
+
+// Where appends a list predicates to the BillingQuotaMutation builder.
+func (m *BillingQuotaMutation) Where(ps ...predicate.BillingQuota) {
+ m.predicates = append(m.predicates, ps...)
+}
+
+// WhereP appends storage-level predicates to the BillingQuotaMutation builder. Using this method,
+// users can use type-assertion to append predicates that do not depend on any generated package.
+func (m *BillingQuotaMutation) WhereP(ps ...func(*sql.Selector)) {
+ p := make([]predicate.BillingQuota, len(ps))
+ for i := range ps {
+ p[i] = ps[i]
+ }
+ m.Where(p...)
+}
+
+// Op returns the operation name.
+func (m *BillingQuotaMutation) Op() Op {
+ return m.op
+}
+
+// SetOp allows setting the mutation operation.
+func (m *BillingQuotaMutation) SetOp(op Op) {
+ m.op = op
+}
+
+// Type returns the node type of this mutation (BillingQuota).
+func (m *BillingQuotaMutation) 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 *BillingQuotaMutation) Fields() []string {
+ fields := make([]string, 0, 7)
+ if m.deleted_at != nil {
+ fields = append(fields, billingquota.FieldDeletedAt)
+ }
+ if m.user_id != nil {
+ fields = append(fields, billingquota.FieldUserID)
+ }
+ if m.total != nil {
+ fields = append(fields, billingquota.FieldTotal)
+ }
+ if m.used != nil {
+ fields = append(fields, billingquota.FieldUsed)
+ }
+ if m.remain != nil {
+ fields = append(fields, billingquota.FieldRemain)
+ }
+ if m.created_at != nil {
+ fields = append(fields, billingquota.FieldCreatedAt)
+ }
+ if m.updated_at != nil {
+ fields = append(fields, billingquota.FieldUpdatedAt)
+ }
+ 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 *BillingQuotaMutation) Field(name string) (ent.Value, bool) {
+ switch name {
+ case billingquota.FieldDeletedAt:
+ return m.DeletedAt()
+ case billingquota.FieldUserID:
+ return m.UserID()
+ case billingquota.FieldTotal:
+ return m.Total()
+ case billingquota.FieldUsed:
+ return m.Used()
+ case billingquota.FieldRemain:
+ return m.Remain()
+ case billingquota.FieldCreatedAt:
+ return m.CreatedAt()
+ case billingquota.FieldUpdatedAt:
+ return m.UpdatedAt()
+ }
+ 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 *BillingQuotaMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
+ switch name {
+ case billingquota.FieldDeletedAt:
+ return m.OldDeletedAt(ctx)
+ case billingquota.FieldUserID:
+ return m.OldUserID(ctx)
+ case billingquota.FieldTotal:
+ return m.OldTotal(ctx)
+ case billingquota.FieldUsed:
+ return m.OldUsed(ctx)
+ case billingquota.FieldRemain:
+ return m.OldRemain(ctx)
+ case billingquota.FieldCreatedAt:
+ return m.OldCreatedAt(ctx)
+ case billingquota.FieldUpdatedAt:
+ return m.OldUpdatedAt(ctx)
+ }
+ return nil, fmt.Errorf("unknown BillingQuota 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 *BillingQuotaMutation) SetField(name string, value ent.Value) error {
+ switch name {
+ case billingquota.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 billingquota.FieldUserID:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetUserID(v)
+ return nil
+ case billingquota.FieldTotal:
+ v, ok := value.(int64)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetTotal(v)
+ return nil
+ case billingquota.FieldUsed:
+ v, ok := value.(int64)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetUsed(v)
+ return nil
+ case billingquota.FieldRemain:
+ v, ok := value.(int64)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetRemain(v)
+ return nil
+ case billingquota.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 billingquota.FieldUpdatedAt:
+ v, ok := value.(time.Time)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetUpdatedAt(v)
+ return nil
+ }
+ return fmt.Errorf("unknown BillingQuota field %s", name)
+}
+
+// AddedFields returns all numeric fields that were incremented/decremented during
+// this mutation.
+func (m *BillingQuotaMutation) AddedFields() []string {
+ var fields []string
+ if m.addtotal != nil {
+ fields = append(fields, billingquota.FieldTotal)
+ }
+ if m.addused != nil {
+ fields = append(fields, billingquota.FieldUsed)
+ }
+ if m.addremain != nil {
+ fields = append(fields, billingquota.FieldRemain)
+ }
+ 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 *BillingQuotaMutation) AddedField(name string) (ent.Value, bool) {
+ switch name {
+ case billingquota.FieldTotal:
+ return m.AddedTotal()
+ case billingquota.FieldUsed:
+ return m.AddedUsed()
+ case billingquota.FieldRemain:
+ return m.AddedRemain()
+ }
+ 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 *BillingQuotaMutation) AddField(name string, value ent.Value) error {
+ switch name {
+ case billingquota.FieldTotal:
+ v, ok := value.(int64)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.AddTotal(v)
+ return nil
+ case billingquota.FieldUsed:
+ v, ok := value.(int64)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.AddUsed(v)
+ return nil
+ case billingquota.FieldRemain:
+ v, ok := value.(int64)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.AddRemain(v)
+ return nil
+ }
+ return fmt.Errorf("unknown BillingQuota numeric field %s", name)
+}
+
+// ClearedFields returns all nullable fields that were cleared during this
+// mutation.
+func (m *BillingQuotaMutation) ClearedFields() []string {
+ var fields []string
+ if m.FieldCleared(billingquota.FieldDeletedAt) {
+ fields = append(fields, billingquota.FieldDeletedAt)
+ }
+ return fields
+}
+
+// FieldCleared returns a boolean indicating if a field with the given name was
+// cleared in this mutation.
+func (m *BillingQuotaMutation) 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 *BillingQuotaMutation) ClearField(name string) error {
+ switch name {
+ case billingquota.FieldDeletedAt:
+ m.ClearDeletedAt()
+ return nil
+ }
+ return fmt.Errorf("unknown BillingQuota 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 *BillingQuotaMutation) ResetField(name string) error {
+ switch name {
+ case billingquota.FieldDeletedAt:
+ m.ResetDeletedAt()
+ return nil
+ case billingquota.FieldUserID:
+ m.ResetUserID()
+ return nil
+ case billingquota.FieldTotal:
+ m.ResetTotal()
+ return nil
+ case billingquota.FieldUsed:
+ m.ResetUsed()
+ return nil
+ case billingquota.FieldRemain:
+ m.ResetRemain()
+ return nil
+ case billingquota.FieldCreatedAt:
+ m.ResetCreatedAt()
+ return nil
+ case billingquota.FieldUpdatedAt:
+ m.ResetUpdatedAt()
+ return nil
+ }
+ return fmt.Errorf("unknown BillingQuota field %s", name)
+}
+
+// AddedEdges returns all edge names that were set/added in this mutation.
+func (m *BillingQuotaMutation) AddedEdges() []string {
+ edges := make([]string, 0, 0)
+ return edges
+}
+
+// AddedIDs returns all IDs (to other nodes) that were added for the given edge
+// name in this mutation.
+func (m *BillingQuotaMutation) AddedIDs(name string) []ent.Value {
+ return nil
+}
+
+// RemovedEdges returns all edge names that were removed in this mutation.
+func (m *BillingQuotaMutation) RemovedEdges() []string {
+ edges := make([]string, 0, 0)
+ return edges
+}
+
+// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with
+// the given name in this mutation.
+func (m *BillingQuotaMutation) RemovedIDs(name string) []ent.Value {
+ return nil
+}
+
+// ClearedEdges returns all edge names that were cleared in this mutation.
+func (m *BillingQuotaMutation) ClearedEdges() []string {
+ edges := make([]string, 0, 0)
+ return edges
+}
+
+// EdgeCleared returns a boolean which indicates if the edge with the given name
+// was cleared in this mutation.
+func (m *BillingQuotaMutation) EdgeCleared(name string) bool {
+ return false
+}
+
+// ClearEdge clears the value of the edge with the given name. It returns an error
+// if that edge is not defined in the schema.
+func (m *BillingQuotaMutation) ClearEdge(name string) error {
+ return fmt.Errorf("unknown BillingQuota 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 *BillingQuotaMutation) ResetEdge(name string) error {
+ return fmt.Errorf("unknown BillingQuota edge %s", name)
+}
+
+// BillingRecordMutation represents an operation that mutates the BillingRecord nodes in the graph.
+type BillingRecordMutation struct {
+ config
+ op Op
+ typ string
+ id *string
+ tenant_id *string
+ user_id *string
+ model *string
+ operation *string
+ input_tokens *int64
+ addinput_tokens *int64
+ output_tokens *int64
+ addoutput_tokens *int64
+ cost *int64
+ addcost *int64
+ request_time *time.Time
+ metadata *map[string]interface{}
+ created_at *time.Time
+ updated_at *time.Time
+ clearedFields map[string]struct{}
+ done bool
+ oldValue func(context.Context) (*BillingRecord, error)
+ predicates []predicate.BillingRecord
+}
+
+var _ ent.Mutation = (*BillingRecordMutation)(nil)
+
+// billingrecordOption allows management of the mutation configuration using functional options.
+type billingrecordOption func(*BillingRecordMutation)
+
+// newBillingRecordMutation creates new mutation for the BillingRecord entity.
+func newBillingRecordMutation(c config, op Op, opts ...billingrecordOption) *BillingRecordMutation {
+ m := &BillingRecordMutation{
+ config: c,
+ op: op,
+ typ: TypeBillingRecord,
+ clearedFields: make(map[string]struct{}),
+ }
+ for _, opt := range opts {
+ opt(m)
+ }
+ return m
+}
+
+// withBillingRecordID sets the ID field of the mutation.
+func withBillingRecordID(id string) billingrecordOption {
+ return func(m *BillingRecordMutation) {
+ var (
+ err error
+ once sync.Once
+ value *BillingRecord
+ )
+ m.oldValue = func(ctx context.Context) (*BillingRecord, error) {
+ once.Do(func() {
+ if m.done {
+ err = errors.New("querying old values post mutation is not allowed")
+ } else {
+ value, err = m.Client().BillingRecord.Get(ctx, id)
+ }
+ })
+ return value, err
+ }
+ m.id = &id
+ }
+}
+
+// withBillingRecord sets the old BillingRecord of the mutation.
+func withBillingRecord(node *BillingRecord) billingrecordOption {
+ return func(m *BillingRecordMutation) {
+ m.oldValue = func(context.Context) (*BillingRecord, 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 BillingRecordMutation) 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 BillingRecordMutation) Tx() (*Tx, error) {
+ if _, ok := m.driver.(*txDriver); !ok {
+ return nil, errors.New("db: mutation is not running in a transaction")
+ }
+ tx := &Tx{config: m.config}
+ tx.init()
+ return tx, nil
+}
+
+// SetID sets the value of the id field. Note that this
+// operation is only accepted on creation of BillingRecord entities.
+func (m *BillingRecordMutation) SetID(id string) {
+ m.id = &id
+}
+
+// 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 *BillingRecordMutation) ID() (id string, 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 *BillingRecordMutation) IDs(ctx context.Context) ([]string, error) {
+ switch {
+ case m.op.Is(OpUpdateOne | OpDeleteOne):
+ id, exists := m.ID()
+ if exists {
+ return []string{id}, nil
+ }
+ fallthrough
+ case m.op.Is(OpUpdate | OpDelete):
+ return m.Client().BillingRecord.Query().Where(m.predicates...).IDs(ctx)
+ default:
+ return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op)
+ }
+}
+
+// SetTenantID sets the "tenant_id" field.
+func (m *BillingRecordMutation) SetTenantID(s string) {
+ m.tenant_id = &s
+}
+
+// TenantID returns the value of the "tenant_id" field in the mutation.
+func (m *BillingRecordMutation) TenantID() (r string, exists bool) {
+ v := m.tenant_id
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldTenantID returns the old "tenant_id" field's value of the BillingRecord entity.
+// If the BillingRecord 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 *BillingRecordMutation) OldTenantID(ctx context.Context) (v string, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldTenantID is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldTenantID requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldTenantID: %w", err)
+ }
+ return oldValue.TenantID, nil
+}
+
+// ResetTenantID resets all changes to the "tenant_id" field.
+func (m *BillingRecordMutation) ResetTenantID() {
+ m.tenant_id = nil
+}
+
+// SetUserID sets the "user_id" field.
+func (m *BillingRecordMutation) SetUserID(s string) {
+ m.user_id = &s
+}
+
+// UserID returns the value of the "user_id" field in the mutation.
+func (m *BillingRecordMutation) UserID() (r string, exists bool) {
+ v := m.user_id
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldUserID returns the old "user_id" field's value of the BillingRecord entity.
+// If the BillingRecord 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 *BillingRecordMutation) OldUserID(ctx context.Context) (v string, 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 *BillingRecordMutation) ResetUserID() {
+ m.user_id = nil
+}
+
+// SetModel sets the "model" field.
+func (m *BillingRecordMutation) SetModel(s string) {
+ m.model = &s
+}
+
+// Model returns the value of the "model" field in the mutation.
+func (m *BillingRecordMutation) Model() (r string, exists bool) {
+ v := m.model
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldModel returns the old "model" field's value of the BillingRecord entity.
+// If the BillingRecord 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 *BillingRecordMutation) OldModel(ctx context.Context) (v string, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldModel is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldModel requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldModel: %w", err)
+ }
+ return oldValue.Model, nil
+}
+
+// ResetModel resets all changes to the "model" field.
+func (m *BillingRecordMutation) ResetModel() {
+ m.model = nil
+}
+
+// SetOperation sets the "operation" field.
+func (m *BillingRecordMutation) SetOperation(s string) {
+ m.operation = &s
+}
+
+// Operation returns the value of the "operation" field in the mutation.
+func (m *BillingRecordMutation) Operation() (r string, exists bool) {
+ v := m.operation
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldOperation returns the old "operation" field's value of the BillingRecord entity.
+// If the BillingRecord 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 *BillingRecordMutation) OldOperation(ctx context.Context) (v string, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldOperation is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldOperation requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldOperation: %w", err)
+ }
+ return oldValue.Operation, nil
+}
+
+// ResetOperation resets all changes to the "operation" field.
+func (m *BillingRecordMutation) ResetOperation() {
+ m.operation = nil
+}
+
+// SetInputTokens sets the "input_tokens" field.
+func (m *BillingRecordMutation) SetInputTokens(i int64) {
+ m.input_tokens = &i
+ m.addinput_tokens = nil
+}
+
+// InputTokens returns the value of the "input_tokens" field in the mutation.
+func (m *BillingRecordMutation) InputTokens() (r int64, exists bool) {
+ v := m.input_tokens
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldInputTokens returns the old "input_tokens" field's value of the BillingRecord entity.
+// If the BillingRecord 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 *BillingRecordMutation) OldInputTokens(ctx context.Context) (v int64, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldInputTokens is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldInputTokens requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldInputTokens: %w", err)
+ }
+ return oldValue.InputTokens, nil
+}
+
+// AddInputTokens adds i to the "input_tokens" field.
+func (m *BillingRecordMutation) AddInputTokens(i int64) {
+ if m.addinput_tokens != nil {
+ *m.addinput_tokens += i
+ } else {
+ m.addinput_tokens = &i
+ }
+}
+
+// AddedInputTokens returns the value that was added to the "input_tokens" field in this mutation.
+func (m *BillingRecordMutation) AddedInputTokens() (r int64, exists bool) {
+ v := m.addinput_tokens
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// ResetInputTokens resets all changes to the "input_tokens" field.
+func (m *BillingRecordMutation) ResetInputTokens() {
+ m.input_tokens = nil
+ m.addinput_tokens = nil
+}
+
+// SetOutputTokens sets the "output_tokens" field.
+func (m *BillingRecordMutation) SetOutputTokens(i int64) {
+ m.output_tokens = &i
+ m.addoutput_tokens = nil
+}
+
+// OutputTokens returns the value of the "output_tokens" field in the mutation.
+func (m *BillingRecordMutation) OutputTokens() (r int64, exists bool) {
+ v := m.output_tokens
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldOutputTokens returns the old "output_tokens" field's value of the BillingRecord entity.
+// If the BillingRecord 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 *BillingRecordMutation) OldOutputTokens(ctx context.Context) (v int64, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldOutputTokens is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldOutputTokens requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldOutputTokens: %w", err)
+ }
+ return oldValue.OutputTokens, nil
+}
+
+// AddOutputTokens adds i to the "output_tokens" field.
+func (m *BillingRecordMutation) AddOutputTokens(i int64) {
+ if m.addoutput_tokens != nil {
+ *m.addoutput_tokens += i
+ } else {
+ m.addoutput_tokens = &i
+ }
+}
+
+// AddedOutputTokens returns the value that was added to the "output_tokens" field in this mutation.
+func (m *BillingRecordMutation) AddedOutputTokens() (r int64, exists bool) {
+ v := m.addoutput_tokens
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// ResetOutputTokens resets all changes to the "output_tokens" field.
+func (m *BillingRecordMutation) ResetOutputTokens() {
+ m.output_tokens = nil
+ m.addoutput_tokens = nil
+}
+
+// SetCost sets the "cost" field.
+func (m *BillingRecordMutation) SetCost(i int64) {
+ m.cost = &i
+ m.addcost = nil
+}
+
+// Cost returns the value of the "cost" field in the mutation.
+func (m *BillingRecordMutation) Cost() (r int64, exists bool) {
+ v := m.cost
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldCost returns the old "cost" field's value of the BillingRecord entity.
+// If the BillingRecord 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 *BillingRecordMutation) OldCost(ctx context.Context) (v int64, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldCost is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldCost requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldCost: %w", err)
+ }
+ return oldValue.Cost, nil
+}
+
+// AddCost adds i to the "cost" field.
+func (m *BillingRecordMutation) AddCost(i int64) {
+ if m.addcost != nil {
+ *m.addcost += i
+ } else {
+ m.addcost = &i
+ }
+}
+
+// AddedCost returns the value that was added to the "cost" field in this mutation.
+func (m *BillingRecordMutation) AddedCost() (r int64, exists bool) {
+ v := m.addcost
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// ResetCost resets all changes to the "cost" field.
+func (m *BillingRecordMutation) ResetCost() {
+ m.cost = nil
+ m.addcost = nil
+}
+
+// SetRequestTime sets the "request_time" field.
+func (m *BillingRecordMutation) SetRequestTime(t time.Time) {
+ m.request_time = &t
+}
+
+// RequestTime returns the value of the "request_time" field in the mutation.
+func (m *BillingRecordMutation) RequestTime() (r time.Time, exists bool) {
+ v := m.request_time
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldRequestTime returns the old "request_time" field's value of the BillingRecord entity.
+// If the BillingRecord 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 *BillingRecordMutation) OldRequestTime(ctx context.Context) (v time.Time, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldRequestTime is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldRequestTime requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldRequestTime: %w", err)
+ }
+ return oldValue.RequestTime, nil
+}
+
+// ResetRequestTime resets all changes to the "request_time" field.
+func (m *BillingRecordMutation) ResetRequestTime() {
+ m.request_time = nil
+}
+
+// SetMetadata sets the "metadata" field.
+func (m *BillingRecordMutation) SetMetadata(value map[string]interface{}) {
+ m.metadata = &value
+}
+
+// Metadata returns the value of the "metadata" field in the mutation.
+func (m *BillingRecordMutation) Metadata() (r map[string]interface{}, exists bool) {
+ v := m.metadata
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldMetadata returns the old "metadata" field's value of the BillingRecord entity.
+// If the BillingRecord 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 *BillingRecordMutation) OldMetadata(ctx context.Context) (v map[string]interface{}, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldMetadata is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldMetadata requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldMetadata: %w", err)
+ }
+ return oldValue.Metadata, nil
+}
+
+// ResetMetadata resets all changes to the "metadata" field.
+func (m *BillingRecordMutation) ResetMetadata() {
+ m.metadata = nil
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (m *BillingRecordMutation) SetCreatedAt(t time.Time) {
+ m.created_at = &t
+}
+
+// CreatedAt returns the value of the "created_at" field in the mutation.
+func (m *BillingRecordMutation) 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 BillingRecord entity.
+// If the BillingRecord 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 *BillingRecordMutation) 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 *BillingRecordMutation) ResetCreatedAt() {
+ m.created_at = nil
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (m *BillingRecordMutation) SetUpdatedAt(t time.Time) {
+ m.updated_at = &t
+}
+
+// UpdatedAt returns the value of the "updated_at" field in the mutation.
+func (m *BillingRecordMutation) 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 BillingRecord entity.
+// If the BillingRecord 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 *BillingRecordMutation) 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 *BillingRecordMutation) ResetUpdatedAt() {
+ m.updated_at = nil
+}
+
+// Where appends a list predicates to the BillingRecordMutation builder.
+func (m *BillingRecordMutation) Where(ps ...predicate.BillingRecord) {
+ m.predicates = append(m.predicates, ps...)
+}
+
+// WhereP appends storage-level predicates to the BillingRecordMutation builder. Using this method,
+// users can use type-assertion to append predicates that do not depend on any generated package.
+func (m *BillingRecordMutation) WhereP(ps ...func(*sql.Selector)) {
+ p := make([]predicate.BillingRecord, len(ps))
+ for i := range ps {
+ p[i] = ps[i]
+ }
+ m.Where(p...)
+}
+
+// Op returns the operation name.
+func (m *BillingRecordMutation) Op() Op {
+ return m.op
+}
+
+// SetOp allows setting the mutation operation.
+func (m *BillingRecordMutation) SetOp(op Op) {
+ m.op = op
+}
+
+// Type returns the node type of this mutation (BillingRecord).
+func (m *BillingRecordMutation) 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 *BillingRecordMutation) Fields() []string {
+ fields := make([]string, 0, 11)
+ if m.tenant_id != nil {
+ fields = append(fields, billingrecord.FieldTenantID)
+ }
+ if m.user_id != nil {
+ fields = append(fields, billingrecord.FieldUserID)
+ }
+ if m.model != nil {
+ fields = append(fields, billingrecord.FieldModel)
+ }
+ if m.operation != nil {
+ fields = append(fields, billingrecord.FieldOperation)
+ }
+ if m.input_tokens != nil {
+ fields = append(fields, billingrecord.FieldInputTokens)
+ }
+ if m.output_tokens != nil {
+ fields = append(fields, billingrecord.FieldOutputTokens)
+ }
+ if m.cost != nil {
+ fields = append(fields, billingrecord.FieldCost)
+ }
+ if m.request_time != nil {
+ fields = append(fields, billingrecord.FieldRequestTime)
+ }
+ if m.metadata != nil {
+ fields = append(fields, billingrecord.FieldMetadata)
+ }
+ if m.created_at != nil {
+ fields = append(fields, billingrecord.FieldCreatedAt)
+ }
+ if m.updated_at != nil {
+ fields = append(fields, billingrecord.FieldUpdatedAt)
+ }
+ 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 *BillingRecordMutation) Field(name string) (ent.Value, bool) {
+ switch name {
+ case billingrecord.FieldTenantID:
+ return m.TenantID()
+ case billingrecord.FieldUserID:
+ return m.UserID()
+ case billingrecord.FieldModel:
+ return m.Model()
+ case billingrecord.FieldOperation:
+ return m.Operation()
+ case billingrecord.FieldInputTokens:
+ return m.InputTokens()
+ case billingrecord.FieldOutputTokens:
+ return m.OutputTokens()
+ case billingrecord.FieldCost:
+ return m.Cost()
+ case billingrecord.FieldRequestTime:
+ return m.RequestTime()
+ case billingrecord.FieldMetadata:
+ return m.Metadata()
+ case billingrecord.FieldCreatedAt:
+ return m.CreatedAt()
+ case billingrecord.FieldUpdatedAt:
+ return m.UpdatedAt()
+ }
+ 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 *BillingRecordMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
+ switch name {
+ case billingrecord.FieldTenantID:
+ return m.OldTenantID(ctx)
+ case billingrecord.FieldUserID:
+ return m.OldUserID(ctx)
+ case billingrecord.FieldModel:
+ return m.OldModel(ctx)
+ case billingrecord.FieldOperation:
+ return m.OldOperation(ctx)
+ case billingrecord.FieldInputTokens:
+ return m.OldInputTokens(ctx)
+ case billingrecord.FieldOutputTokens:
+ return m.OldOutputTokens(ctx)
+ case billingrecord.FieldCost:
+ return m.OldCost(ctx)
+ case billingrecord.FieldRequestTime:
+ return m.OldRequestTime(ctx)
+ case billingrecord.FieldMetadata:
+ return m.OldMetadata(ctx)
+ case billingrecord.FieldCreatedAt:
+ return m.OldCreatedAt(ctx)
+ case billingrecord.FieldUpdatedAt:
+ return m.OldUpdatedAt(ctx)
+ }
+ return nil, fmt.Errorf("unknown BillingRecord 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 *BillingRecordMutation) SetField(name string, value ent.Value) error {
+ switch name {
+ case billingrecord.FieldTenantID:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetTenantID(v)
+ return nil
+ case billingrecord.FieldUserID:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetUserID(v)
+ return nil
+ case billingrecord.FieldModel:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetModel(v)
+ return nil
+ case billingrecord.FieldOperation:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetOperation(v)
+ return nil
+ case billingrecord.FieldInputTokens:
+ v, ok := value.(int64)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetInputTokens(v)
+ return nil
+ case billingrecord.FieldOutputTokens:
+ v, ok := value.(int64)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetOutputTokens(v)
+ return nil
+ case billingrecord.FieldCost:
+ v, ok := value.(int64)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetCost(v)
+ return nil
+ case billingrecord.FieldRequestTime:
+ v, ok := value.(time.Time)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetRequestTime(v)
+ return nil
+ case billingrecord.FieldMetadata:
+ v, ok := value.(map[string]interface{})
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetMetadata(v)
+ return nil
+ case billingrecord.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 billingrecord.FieldUpdatedAt:
+ v, ok := value.(time.Time)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetUpdatedAt(v)
+ return nil
+ }
+ return fmt.Errorf("unknown BillingRecord field %s", name)
+}
+
+// AddedFields returns all numeric fields that were incremented/decremented during
+// this mutation.
+func (m *BillingRecordMutation) AddedFields() []string {
+ var fields []string
+ if m.addinput_tokens != nil {
+ fields = append(fields, billingrecord.FieldInputTokens)
+ }
+ if m.addoutput_tokens != nil {
+ fields = append(fields, billingrecord.FieldOutputTokens)
+ }
+ if m.addcost != nil {
+ fields = append(fields, billingrecord.FieldCost)
+ }
+ 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 *BillingRecordMutation) AddedField(name string) (ent.Value, bool) {
+ switch name {
+ case billingrecord.FieldInputTokens:
+ return m.AddedInputTokens()
+ case billingrecord.FieldOutputTokens:
+ return m.AddedOutputTokens()
+ case billingrecord.FieldCost:
+ return m.AddedCost()
+ }
+ 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 *BillingRecordMutation) AddField(name string, value ent.Value) error {
+ switch name {
+ case billingrecord.FieldInputTokens:
+ v, ok := value.(int64)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.AddInputTokens(v)
+ return nil
+ case billingrecord.FieldOutputTokens:
+ v, ok := value.(int64)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.AddOutputTokens(v)
+ return nil
+ case billingrecord.FieldCost:
+ v, ok := value.(int64)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.AddCost(v)
+ return nil
+ }
+ return fmt.Errorf("unknown BillingRecord numeric field %s", name)
+}
+
+// ClearedFields returns all nullable fields that were cleared during this
+// mutation.
+func (m *BillingRecordMutation) ClearedFields() []string {
+ return nil
+}
+
+// FieldCleared returns a boolean indicating if a field with the given name was
+// cleared in this mutation.
+func (m *BillingRecordMutation) 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 *BillingRecordMutation) ClearField(name string) error {
+ return fmt.Errorf("unknown BillingRecord 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 *BillingRecordMutation) ResetField(name string) error {
+ switch name {
+ case billingrecord.FieldTenantID:
+ m.ResetTenantID()
+ return nil
+ case billingrecord.FieldUserID:
+ m.ResetUserID()
+ return nil
+ case billingrecord.FieldModel:
+ m.ResetModel()
+ return nil
+ case billingrecord.FieldOperation:
+ m.ResetOperation()
+ return nil
+ case billingrecord.FieldInputTokens:
+ m.ResetInputTokens()
+ return nil
+ case billingrecord.FieldOutputTokens:
+ m.ResetOutputTokens()
+ return nil
+ case billingrecord.FieldCost:
+ m.ResetCost()
+ return nil
+ case billingrecord.FieldRequestTime:
+ m.ResetRequestTime()
+ return nil
+ case billingrecord.FieldMetadata:
+ m.ResetMetadata()
+ return nil
+ case billingrecord.FieldCreatedAt:
+ m.ResetCreatedAt()
+ return nil
+ case billingrecord.FieldUpdatedAt:
+ m.ResetUpdatedAt()
+ return nil
+ }
+ return fmt.Errorf("unknown BillingRecord field %s", name)
+}
+
+// AddedEdges returns all edge names that were set/added in this mutation.
+func (m *BillingRecordMutation) AddedEdges() []string {
+ edges := make([]string, 0, 0)
+ return edges
+}
+
+// AddedIDs returns all IDs (to other nodes) that were added for the given edge
+// name in this mutation.
+func (m *BillingRecordMutation) AddedIDs(name string) []ent.Value {
+ return nil
+}
+
+// RemovedEdges returns all edge names that were removed in this mutation.
+func (m *BillingRecordMutation) RemovedEdges() []string {
+ edges := make([]string, 0, 0)
+ return edges
+}
+
+// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with
+// the given name in this mutation.
+func (m *BillingRecordMutation) RemovedIDs(name string) []ent.Value {
+ return nil
+}
+
+// ClearedEdges returns all edge names that were cleared in this mutation.
+func (m *BillingRecordMutation) ClearedEdges() []string {
+ edges := make([]string, 0, 0)
+ return edges
+}
+
+// EdgeCleared returns a boolean which indicates if the edge with the given name
+// was cleared in this mutation.
+func (m *BillingRecordMutation) EdgeCleared(name string) bool {
+ return false
+}
+
+// ClearEdge clears the value of the edge with the given name. It returns an error
+// if that edge is not defined in the schema.
+func (m *BillingRecordMutation) ClearEdge(name string) error {
+ return fmt.Errorf("unknown BillingRecord 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 *BillingRecordMutation) ResetEdge(name string) error {
+ return fmt.Errorf("unknown BillingRecord edge %s", name)
+}
+
+// BillingUsageMutation represents an operation that mutates the BillingUsage nodes in the graph.
+type BillingUsageMutation struct {
+ config
+ op Op
+ typ string
+ id *string
+ deleted_at *time.Time
+ user_id *string
+ model_name *string
+ tokens *int64
+ addtokens *int64
+ operation *string
+ created_at *time.Time
+ updated_at *time.Time
+ clearedFields map[string]struct{}
+ done bool
+ oldValue func(context.Context) (*BillingUsage, error)
+ predicates []predicate.BillingUsage
+}
+
+var _ ent.Mutation = (*BillingUsageMutation)(nil)
+
+// billingusageOption allows management of the mutation configuration using functional options.
+type billingusageOption func(*BillingUsageMutation)
+
+// newBillingUsageMutation creates new mutation for the BillingUsage entity.
+func newBillingUsageMutation(c config, op Op, opts ...billingusageOption) *BillingUsageMutation {
+ m := &BillingUsageMutation{
+ config: c,
+ op: op,
+ typ: TypeBillingUsage,
+ clearedFields: make(map[string]struct{}),
+ }
+ for _, opt := range opts {
+ opt(m)
+ }
+ return m
+}
+
+// withBillingUsageID sets the ID field of the mutation.
+func withBillingUsageID(id string) billingusageOption {
+ return func(m *BillingUsageMutation) {
+ var (
+ err error
+ once sync.Once
+ value *BillingUsage
+ )
+ m.oldValue = func(ctx context.Context) (*BillingUsage, error) {
+ once.Do(func() {
+ if m.done {
+ err = errors.New("querying old values post mutation is not allowed")
+ } else {
+ value, err = m.Client().BillingUsage.Get(ctx, id)
+ }
+ })
+ return value, err
+ }
+ m.id = &id
+ }
+}
+
+// withBillingUsage sets the old BillingUsage of the mutation.
+func withBillingUsage(node *BillingUsage) billingusageOption {
+ return func(m *BillingUsageMutation) {
+ m.oldValue = func(context.Context) (*BillingUsage, 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 BillingUsageMutation) 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 BillingUsageMutation) Tx() (*Tx, error) {
+ if _, ok := m.driver.(*txDriver); !ok {
+ return nil, errors.New("db: mutation is not running in a transaction")
+ }
+ tx := &Tx{config: m.config}
+ tx.init()
+ return tx, nil
+}
+
+// SetID sets the value of the id field. Note that this
+// operation is only accepted on creation of BillingUsage entities.
+func (m *BillingUsageMutation) SetID(id string) {
+ m.id = &id
+}
+
+// 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 *BillingUsageMutation) ID() (id string, 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 *BillingUsageMutation) IDs(ctx context.Context) ([]string, error) {
+ switch {
+ case m.op.Is(OpUpdateOne | OpDeleteOne):
+ id, exists := m.ID()
+ if exists {
+ return []string{id}, nil
+ }
+ fallthrough
+ case m.op.Is(OpUpdate | OpDelete):
+ return m.Client().BillingUsage.Query().Where(m.predicates...).IDs(ctx)
+ default:
+ return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op)
+ }
+}
+
+// SetDeletedAt sets the "deleted_at" field.
+func (m *BillingUsageMutation) SetDeletedAt(t time.Time) {
+ m.deleted_at = &t
+}
+
+// DeletedAt returns the value of the "deleted_at" field in the mutation.
+func (m *BillingUsageMutation) 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 BillingUsage entity.
+// If the BillingUsage 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 *BillingUsageMutation) 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 *BillingUsageMutation) ClearDeletedAt() {
+ m.deleted_at = nil
+ m.clearedFields[billingusage.FieldDeletedAt] = struct{}{}
+}
+
+// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation.
+func (m *BillingUsageMutation) DeletedAtCleared() bool {
+ _, ok := m.clearedFields[billingusage.FieldDeletedAt]
+ return ok
+}
+
+// ResetDeletedAt resets all changes to the "deleted_at" field.
+func (m *BillingUsageMutation) ResetDeletedAt() {
+ m.deleted_at = nil
+ delete(m.clearedFields, billingusage.FieldDeletedAt)
+}
+
+// SetUserID sets the "user_id" field.
+func (m *BillingUsageMutation) SetUserID(s string) {
+ m.user_id = &s
+}
+
+// UserID returns the value of the "user_id" field in the mutation.
+func (m *BillingUsageMutation) UserID() (r string, exists bool) {
+ v := m.user_id
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldUserID returns the old "user_id" field's value of the BillingUsage entity.
+// If the BillingUsage 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 *BillingUsageMutation) OldUserID(ctx context.Context) (v string, 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 *BillingUsageMutation) ResetUserID() {
+ m.user_id = nil
+}
+
+// SetModelName sets the "model_name" field.
+func (m *BillingUsageMutation) SetModelName(s string) {
+ m.model_name = &s
+}
+
+// ModelName returns the value of the "model_name" field in the mutation.
+func (m *BillingUsageMutation) ModelName() (r string, exists bool) {
+ v := m.model_name
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldModelName returns the old "model_name" field's value of the BillingUsage entity.
+// If the BillingUsage 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 *BillingUsageMutation) OldModelName(ctx context.Context) (v string, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldModelName is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldModelName requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldModelName: %w", err)
+ }
+ return oldValue.ModelName, nil
+}
+
+// ResetModelName resets all changes to the "model_name" field.
+func (m *BillingUsageMutation) ResetModelName() {
+ m.model_name = nil
+}
+
+// SetTokens sets the "tokens" field.
+func (m *BillingUsageMutation) SetTokens(i int64) {
+ m.tokens = &i
+ m.addtokens = nil
+}
+
+// Tokens returns the value of the "tokens" field in the mutation.
+func (m *BillingUsageMutation) Tokens() (r int64, exists bool) {
+ v := m.tokens
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldTokens returns the old "tokens" field's value of the BillingUsage entity.
+// If the BillingUsage 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 *BillingUsageMutation) OldTokens(ctx context.Context) (v int64, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldTokens is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldTokens requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldTokens: %w", err)
+ }
+ return oldValue.Tokens, nil
+}
+
+// AddTokens adds i to the "tokens" field.
+func (m *BillingUsageMutation) AddTokens(i int64) {
+ if m.addtokens != nil {
+ *m.addtokens += i
+ } else {
+ m.addtokens = &i
+ }
+}
+
+// AddedTokens returns the value that was added to the "tokens" field in this mutation.
+func (m *BillingUsageMutation) AddedTokens() (r int64, exists bool) {
+ v := m.addtokens
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// ResetTokens resets all changes to the "tokens" field.
+func (m *BillingUsageMutation) ResetTokens() {
+ m.tokens = nil
+ m.addtokens = nil
+}
+
+// SetOperation sets the "operation" field.
+func (m *BillingUsageMutation) SetOperation(s string) {
+ m.operation = &s
+}
+
+// Operation returns the value of the "operation" field in the mutation.
+func (m *BillingUsageMutation) Operation() (r string, exists bool) {
+ v := m.operation
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldOperation returns the old "operation" field's value of the BillingUsage entity.
+// If the BillingUsage 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 *BillingUsageMutation) OldOperation(ctx context.Context) (v string, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldOperation is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldOperation requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldOperation: %w", err)
+ }
+ return oldValue.Operation, nil
+}
+
+// ResetOperation resets all changes to the "operation" field.
+func (m *BillingUsageMutation) ResetOperation() {
+ m.operation = nil
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (m *BillingUsageMutation) SetCreatedAt(t time.Time) {
+ m.created_at = &t
+}
+
+// CreatedAt returns the value of the "created_at" field in the mutation.
+func (m *BillingUsageMutation) 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 BillingUsage entity.
+// If the BillingUsage 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 *BillingUsageMutation) 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 *BillingUsageMutation) ResetCreatedAt() {
+ m.created_at = nil
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (m *BillingUsageMutation) SetUpdatedAt(t time.Time) {
+ m.updated_at = &t
+}
+
+// UpdatedAt returns the value of the "updated_at" field in the mutation.
+func (m *BillingUsageMutation) 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 BillingUsage entity.
+// If the BillingUsage 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 *BillingUsageMutation) 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 *BillingUsageMutation) ResetUpdatedAt() {
+ m.updated_at = nil
+}
+
+// Where appends a list predicates to the BillingUsageMutation builder.
+func (m *BillingUsageMutation) Where(ps ...predicate.BillingUsage) {
+ m.predicates = append(m.predicates, ps...)
+}
+
+// WhereP appends storage-level predicates to the BillingUsageMutation builder. Using this method,
+// users can use type-assertion to append predicates that do not depend on any generated package.
+func (m *BillingUsageMutation) WhereP(ps ...func(*sql.Selector)) {
+ p := make([]predicate.BillingUsage, len(ps))
+ for i := range ps {
+ p[i] = ps[i]
+ }
+ m.Where(p...)
+}
+
+// Op returns the operation name.
+func (m *BillingUsageMutation) Op() Op {
+ return m.op
+}
+
+// SetOp allows setting the mutation operation.
+func (m *BillingUsageMutation) SetOp(op Op) {
+ m.op = op
+}
+
+// Type returns the node type of this mutation (BillingUsage).
+func (m *BillingUsageMutation) 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 *BillingUsageMutation) Fields() []string {
+ fields := make([]string, 0, 7)
+ if m.deleted_at != nil {
+ fields = append(fields, billingusage.FieldDeletedAt)
+ }
+ if m.user_id != nil {
+ fields = append(fields, billingusage.FieldUserID)
+ }
+ if m.model_name != nil {
+ fields = append(fields, billingusage.FieldModelName)
+ }
+ if m.tokens != nil {
+ fields = append(fields, billingusage.FieldTokens)
+ }
+ if m.operation != nil {
+ fields = append(fields, billingusage.FieldOperation)
+ }
+ if m.created_at != nil {
+ fields = append(fields, billingusage.FieldCreatedAt)
+ }
+ if m.updated_at != nil {
+ fields = append(fields, billingusage.FieldUpdatedAt)
+ }
+ 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 *BillingUsageMutation) Field(name string) (ent.Value, bool) {
+ switch name {
+ case billingusage.FieldDeletedAt:
+ return m.DeletedAt()
+ case billingusage.FieldUserID:
+ return m.UserID()
+ case billingusage.FieldModelName:
+ return m.ModelName()
+ case billingusage.FieldTokens:
+ return m.Tokens()
+ case billingusage.FieldOperation:
+ return m.Operation()
+ case billingusage.FieldCreatedAt:
+ return m.CreatedAt()
+ case billingusage.FieldUpdatedAt:
+ return m.UpdatedAt()
+ }
+ 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 *BillingUsageMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
+ switch name {
+ case billingusage.FieldDeletedAt:
+ return m.OldDeletedAt(ctx)
+ case billingusage.FieldUserID:
+ return m.OldUserID(ctx)
+ case billingusage.FieldModelName:
+ return m.OldModelName(ctx)
+ case billingusage.FieldTokens:
+ return m.OldTokens(ctx)
+ case billingusage.FieldOperation:
+ return m.OldOperation(ctx)
+ case billingusage.FieldCreatedAt:
+ return m.OldCreatedAt(ctx)
+ case billingusage.FieldUpdatedAt:
+ return m.OldUpdatedAt(ctx)
+ }
+ return nil, fmt.Errorf("unknown BillingUsage 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 *BillingUsageMutation) SetField(name string, value ent.Value) error {
+ switch name {
+ case billingusage.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 billingusage.FieldUserID:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetUserID(v)
+ return nil
+ case billingusage.FieldModelName:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetModelName(v)
+ return nil
+ case billingusage.FieldTokens:
+ v, ok := value.(int64)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetTokens(v)
+ return nil
+ case billingusage.FieldOperation:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetOperation(v)
+ return nil
+ case billingusage.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 billingusage.FieldUpdatedAt:
+ v, ok := value.(time.Time)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetUpdatedAt(v)
+ return nil
+ }
+ return fmt.Errorf("unknown BillingUsage field %s", name)
+}
+
+// AddedFields returns all numeric fields that were incremented/decremented during
+// this mutation.
+func (m *BillingUsageMutation) AddedFields() []string {
+ var fields []string
+ if m.addtokens != nil {
+ fields = append(fields, billingusage.FieldTokens)
+ }
+ 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 *BillingUsageMutation) AddedField(name string) (ent.Value, bool) {
+ switch name {
+ case billingusage.FieldTokens:
+ return m.AddedTokens()
+ }
+ 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 *BillingUsageMutation) AddField(name string, value ent.Value) error {
+ switch name {
+ case billingusage.FieldTokens:
+ v, ok := value.(int64)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.AddTokens(v)
+ return nil
+ }
+ return fmt.Errorf("unknown BillingUsage numeric field %s", name)
+}
+
+// ClearedFields returns all nullable fields that were cleared during this
+// mutation.
+func (m *BillingUsageMutation) ClearedFields() []string {
+ var fields []string
+ if m.FieldCleared(billingusage.FieldDeletedAt) {
+ fields = append(fields, billingusage.FieldDeletedAt)
+ }
+ return fields
+}
+
+// FieldCleared returns a boolean indicating if a field with the given name was
+// cleared in this mutation.
+func (m *BillingUsageMutation) 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 *BillingUsageMutation) ClearField(name string) error {
+ switch name {
+ case billingusage.FieldDeletedAt:
+ m.ClearDeletedAt()
+ return nil
+ }
+ return fmt.Errorf("unknown BillingUsage 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 *BillingUsageMutation) ResetField(name string) error {
+ switch name {
+ case billingusage.FieldDeletedAt:
+ m.ResetDeletedAt()
+ return nil
+ case billingusage.FieldUserID:
+ m.ResetUserID()
+ return nil
+ case billingusage.FieldModelName:
+ m.ResetModelName()
+ return nil
+ case billingusage.FieldTokens:
+ m.ResetTokens()
+ return nil
+ case billingusage.FieldOperation:
+ m.ResetOperation()
+ return nil
+ case billingusage.FieldCreatedAt:
+ m.ResetCreatedAt()
+ return nil
+ case billingusage.FieldUpdatedAt:
+ m.ResetUpdatedAt()
+ return nil
+ }
+ return fmt.Errorf("unknown BillingUsage field %s", name)
+}
+
+// AddedEdges returns all edge names that were set/added in this mutation.
+func (m *BillingUsageMutation) AddedEdges() []string {
+ edges := make([]string, 0, 0)
+ return edges
+}
+
+// AddedIDs returns all IDs (to other nodes) that were added for the given edge
+// name in this mutation.
+func (m *BillingUsageMutation) AddedIDs(name string) []ent.Value {
+ return nil
+}
+
+// RemovedEdges returns all edge names that were removed in this mutation.
+func (m *BillingUsageMutation) RemovedEdges() []string {
+ edges := make([]string, 0, 0)
+ return edges
+}
+
+// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with
+// the given name in this mutation.
+func (m *BillingUsageMutation) RemovedIDs(name string) []ent.Value {
+ return nil
+}
+
+// ClearedEdges returns all edge names that were cleared in this mutation.
+func (m *BillingUsageMutation) ClearedEdges() []string {
+ edges := make([]string, 0, 0)
+ return edges
+}
+
+// EdgeCleared returns a boolean which indicates if the edge with the given name
+// was cleared in this mutation.
+func (m *BillingUsageMutation) EdgeCleared(name string) bool {
+ return false
+}
+
+// ClearEdge clears the value of the edge with the given name. It returns an error
+// if that edge is not defined in the schema.
+func (m *BillingUsageMutation) ClearEdge(name string) error {
+ return fmt.Errorf("unknown BillingUsage 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 *BillingUsageMutation) ResetEdge(name string) error {
+ return fmt.Errorf("unknown BillingUsage edge %s", name)
+}
+
+// InviteCodeMutation represents an operation that mutates the InviteCode nodes in the graph.
+type InviteCodeMutation struct {
+ config
+ op Op
+ typ string
+ id *uuid.UUID
+ admin_id *uuid.UUID
+ code *string
+ created_at *time.Time
+ updated_at *time.Time
+ clearedFields map[string]struct{}
+ done bool
+ oldValue func(context.Context) (*InviteCode, error)
+ predicates []predicate.InviteCode
+}
+
+var _ ent.Mutation = (*InviteCodeMutation)(nil)
+
+// invitecodeOption allows management of the mutation configuration using functional options.
+type invitecodeOption func(*InviteCodeMutation)
+
+// newInviteCodeMutation creates new mutation for the InviteCode entity.
+func newInviteCodeMutation(c config, op Op, opts ...invitecodeOption) *InviteCodeMutation {
+ m := &InviteCodeMutation{
+ config: c,
+ op: op,
+ typ: TypeInviteCode,
+ clearedFields: make(map[string]struct{}),
+ }
+ for _, opt := range opts {
+ opt(m)
+ }
+ return m
+}
+
+// withInviteCodeID sets the ID field of the mutation.
+func withInviteCodeID(id uuid.UUID) invitecodeOption {
+ return func(m *InviteCodeMutation) {
+ var (
+ err error
+ once sync.Once
+ value *InviteCode
+ )
+ m.oldValue = func(ctx context.Context) (*InviteCode, error) {
+ once.Do(func() {
+ if m.done {
+ err = errors.New("querying old values post mutation is not allowed")
+ } else {
+ value, err = m.Client().InviteCode.Get(ctx, id)
+ }
+ })
+ return value, err
+ }
+ m.id = &id
+ }
+}
+
+// withInviteCode sets the old InviteCode of the mutation.
+func withInviteCode(node *InviteCode) invitecodeOption {
+ return func(m *InviteCodeMutation) {
+ m.oldValue = func(context.Context) (*InviteCode, 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 InviteCodeMutation) 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 InviteCodeMutation) Tx() (*Tx, error) {
+ if _, ok := m.driver.(*txDriver); !ok {
+ return nil, errors.New("db: mutation is not running in a transaction")
+ }
+ tx := &Tx{config: m.config}
+ tx.init()
+ return tx, nil
+}
+
+// SetID sets the value of the id field. Note that this
+// operation is only accepted on creation of InviteCode entities.
+func (m *InviteCodeMutation) SetID(id uuid.UUID) {
+ m.id = &id
+}
+
+// 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 *InviteCodeMutation) ID() (id uuid.UUID, 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 *InviteCodeMutation) IDs(ctx context.Context) ([]uuid.UUID, error) {
+ switch {
+ case m.op.Is(OpUpdateOne | OpDeleteOne):
+ id, exists := m.ID()
+ if exists {
+ return []uuid.UUID{id}, nil
+ }
+ fallthrough
+ case m.op.Is(OpUpdate | OpDelete):
+ return m.Client().InviteCode.Query().Where(m.predicates...).IDs(ctx)
+ default:
+ return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op)
+ }
+}
+
+// SetAdminID sets the "admin_id" field.
+func (m *InviteCodeMutation) SetAdminID(u uuid.UUID) {
+ m.admin_id = &u
+}
+
+// AdminID returns the value of the "admin_id" field in the mutation.
+func (m *InviteCodeMutation) AdminID() (r uuid.UUID, exists bool) {
+ v := m.admin_id
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldAdminID returns the old "admin_id" field's value of the InviteCode entity.
+// If the InviteCode 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 *InviteCodeMutation) OldAdminID(ctx context.Context) (v uuid.UUID, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldAdminID is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldAdminID requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldAdminID: %w", err)
+ }
+ return oldValue.AdminID, nil
+}
+
+// ResetAdminID resets all changes to the "admin_id" field.
+func (m *InviteCodeMutation) ResetAdminID() {
+ m.admin_id = nil
+}
+
+// SetCode sets the "code" field.
+func (m *InviteCodeMutation) SetCode(s string) {
+ m.code = &s
+}
+
+// Code returns the value of the "code" field in the mutation.
+func (m *InviteCodeMutation) Code() (r string, exists bool) {
+ v := m.code
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldCode returns the old "code" field's value of the InviteCode entity.
+// If the InviteCode 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 *InviteCodeMutation) OldCode(ctx context.Context) (v string, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldCode is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldCode requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldCode: %w", err)
+ }
+ return oldValue.Code, nil
+}
+
+// ResetCode resets all changes to the "code" field.
+func (m *InviteCodeMutation) ResetCode() {
+ m.code = nil
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (m *InviteCodeMutation) SetCreatedAt(t time.Time) {
+ m.created_at = &t
+}
+
+// CreatedAt returns the value of the "created_at" field in the mutation.
+func (m *InviteCodeMutation) 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 InviteCode entity.
+// If the InviteCode 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 *InviteCodeMutation) 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 *InviteCodeMutation) ResetCreatedAt() {
+ m.created_at = nil
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (m *InviteCodeMutation) SetUpdatedAt(t time.Time) {
+ m.updated_at = &t
+}
+
+// UpdatedAt returns the value of the "updated_at" field in the mutation.
+func (m *InviteCodeMutation) 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 InviteCode entity.
+// If the InviteCode 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 *InviteCodeMutation) 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 *InviteCodeMutation) ResetUpdatedAt() {
+ m.updated_at = nil
+}
+
+// Where appends a list predicates to the InviteCodeMutation builder.
+func (m *InviteCodeMutation) Where(ps ...predicate.InviteCode) {
+ m.predicates = append(m.predicates, ps...)
+}
+
+// WhereP appends storage-level predicates to the InviteCodeMutation builder. Using this method,
+// users can use type-assertion to append predicates that do not depend on any generated package.
+func (m *InviteCodeMutation) WhereP(ps ...func(*sql.Selector)) {
+ p := make([]predicate.InviteCode, len(ps))
+ for i := range ps {
+ p[i] = ps[i]
+ }
+ m.Where(p...)
+}
+
+// Op returns the operation name.
+func (m *InviteCodeMutation) Op() Op {
+ return m.op
+}
+
+// SetOp allows setting the mutation operation.
+func (m *InviteCodeMutation) SetOp(op Op) {
+ m.op = op
+}
+
+// Type returns the node type of this mutation (InviteCode).
+func (m *InviteCodeMutation) 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 *InviteCodeMutation) Fields() []string {
+ fields := make([]string, 0, 4)
+ if m.admin_id != nil {
+ fields = append(fields, invitecode.FieldAdminID)
+ }
+ if m.code != nil {
+ fields = append(fields, invitecode.FieldCode)
+ }
+ if m.created_at != nil {
+ fields = append(fields, invitecode.FieldCreatedAt)
+ }
+ if m.updated_at != nil {
+ fields = append(fields, invitecode.FieldUpdatedAt)
+ }
+ 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 *InviteCodeMutation) Field(name string) (ent.Value, bool) {
+ switch name {
+ case invitecode.FieldAdminID:
+ return m.AdminID()
+ case invitecode.FieldCode:
+ return m.Code()
+ case invitecode.FieldCreatedAt:
+ return m.CreatedAt()
+ case invitecode.FieldUpdatedAt:
+ return m.UpdatedAt()
+ }
+ 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 *InviteCodeMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
+ switch name {
+ case invitecode.FieldAdminID:
+ return m.OldAdminID(ctx)
+ case invitecode.FieldCode:
+ return m.OldCode(ctx)
+ case invitecode.FieldCreatedAt:
+ return m.OldCreatedAt(ctx)
+ case invitecode.FieldUpdatedAt:
+ return m.OldUpdatedAt(ctx)
+ }
+ return nil, fmt.Errorf("unknown InviteCode 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 *InviteCodeMutation) SetField(name string, value ent.Value) error {
+ switch name {
+ case invitecode.FieldAdminID:
+ v, ok := value.(uuid.UUID)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetAdminID(v)
+ return nil
+ case invitecode.FieldCode:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetCode(v)
+ return nil
+ case invitecode.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 invitecode.FieldUpdatedAt:
+ v, ok := value.(time.Time)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetUpdatedAt(v)
+ return nil
+ }
+ return fmt.Errorf("unknown InviteCode field %s", name)
+}
+
+// AddedFields returns all numeric fields that were incremented/decremented during
+// this mutation.
+func (m *InviteCodeMutation) AddedFields() []string {
+ return nil
+}
+
+// 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 *InviteCodeMutation) AddedField(name string) (ent.Value, bool) {
+ 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 *InviteCodeMutation) AddField(name string, value ent.Value) error {
+ switch name {
+ }
+ return fmt.Errorf("unknown InviteCode numeric field %s", name)
+}
+
+// ClearedFields returns all nullable fields that were cleared during this
+// mutation.
+func (m *InviteCodeMutation) ClearedFields() []string {
+ return nil
+}
+
+// FieldCleared returns a boolean indicating if a field with the given name was
+// cleared in this mutation.
+func (m *InviteCodeMutation) 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 *InviteCodeMutation) ClearField(name string) error {
+ return fmt.Errorf("unknown InviteCode 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 *InviteCodeMutation) ResetField(name string) error {
+ switch name {
+ case invitecode.FieldAdminID:
+ m.ResetAdminID()
+ return nil
+ case invitecode.FieldCode:
+ m.ResetCode()
+ return nil
+ case invitecode.FieldCreatedAt:
+ m.ResetCreatedAt()
+ return nil
+ case invitecode.FieldUpdatedAt:
+ m.ResetUpdatedAt()
+ return nil
+ }
+ return fmt.Errorf("unknown InviteCode field %s", name)
+}
+
+// AddedEdges returns all edge names that were set/added in this mutation.
+func (m *InviteCodeMutation) AddedEdges() []string {
+ edges := make([]string, 0, 0)
+ return edges
+}
+
+// AddedIDs returns all IDs (to other nodes) that were added for the given edge
+// name in this mutation.
+func (m *InviteCodeMutation) AddedIDs(name string) []ent.Value {
+ return nil
+}
+
+// RemovedEdges returns all edge names that were removed in this mutation.
+func (m *InviteCodeMutation) RemovedEdges() []string {
+ edges := make([]string, 0, 0)
+ return edges
+}
+
+// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with
+// the given name in this mutation.
+func (m *InviteCodeMutation) RemovedIDs(name string) []ent.Value {
+ return nil
+}
+
+// ClearedEdges returns all edge names that were cleared in this mutation.
+func (m *InviteCodeMutation) ClearedEdges() []string {
+ edges := make([]string, 0, 0)
+ return edges
+}
+
+// EdgeCleared returns a boolean which indicates if the edge with the given name
+// was cleared in this mutation.
+func (m *InviteCodeMutation) EdgeCleared(name string) bool {
+ return false
+}
+
+// ClearEdge clears the value of the edge with the given name. It returns an error
+// if that edge is not defined in the schema.
+func (m *InviteCodeMutation) ClearEdge(name string) error {
+ return fmt.Errorf("unknown InviteCode 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 *InviteCodeMutation) ResetEdge(name string) error {
+ return fmt.Errorf("unknown InviteCode edge %s", name)
+}
+
+// ModelMutation represents an operation that mutates the Model nodes in the graph.
+type ModelMutation struct {
+ config
+ op Op
+ typ string
+ id *uuid.UUID
+ model_name *string
+ model_type *consts.ModelType
+ api_base *string
+ api_key *string
+ api_version *string
+ description *string
+ provider *string
+ status *consts.ModelStatus
+ context_length *int
+ addcontext_length *int
+ created_at *time.Time
+ updated_at *time.Time
+ clearedFields map[string]struct{}
+ records map[uuid.UUID]struct{}
+ removedrecords map[uuid.UUID]struct{}
+ clearedrecords bool
+ user *uuid.UUID
+ cleareduser bool
+ done bool
+ oldValue func(context.Context) (*Model, error)
+ predicates []predicate.Model
+}
+
+var _ ent.Mutation = (*ModelMutation)(nil)
+
+// modelOption allows management of the mutation configuration using functional options.
+type modelOption func(*ModelMutation)
+
+// newModelMutation creates new mutation for the Model entity.
+func newModelMutation(c config, op Op, opts ...modelOption) *ModelMutation {
+ m := &ModelMutation{
+ config: c,
+ op: op,
+ typ: TypeModel,
+ clearedFields: make(map[string]struct{}),
+ }
+ for _, opt := range opts {
+ opt(m)
+ }
+ return m
+}
+
+// withModelID sets the ID field of the mutation.
+func withModelID(id uuid.UUID) modelOption {
+ return func(m *ModelMutation) {
+ var (
+ err error
+ once sync.Once
+ value *Model
+ )
+ m.oldValue = func(ctx context.Context) (*Model, error) {
+ once.Do(func() {
+ if m.done {
+ err = errors.New("querying old values post mutation is not allowed")
+ } else {
+ value, err = m.Client().Model.Get(ctx, id)
+ }
+ })
+ return value, err
+ }
+ m.id = &id
+ }
+}
+
+// withModel sets the old Model of the mutation.
+func withModel(node *Model) modelOption {
+ return func(m *ModelMutation) {
+ m.oldValue = func(context.Context) (*Model, 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 ModelMutation) 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 ModelMutation) Tx() (*Tx, error) {
+ if _, ok := m.driver.(*txDriver); !ok {
+ return nil, errors.New("db: mutation is not running in a transaction")
+ }
+ tx := &Tx{config: m.config}
+ tx.init()
+ return tx, nil
+}
+
+// SetID sets the value of the id field. Note that this
+// operation is only accepted on creation of Model entities.
+func (m *ModelMutation) SetID(id uuid.UUID) {
+ m.id = &id
+}
+
+// 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 *ModelMutation) ID() (id uuid.UUID, 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 *ModelMutation) IDs(ctx context.Context) ([]uuid.UUID, error) {
+ switch {
+ case m.op.Is(OpUpdateOne | OpDeleteOne):
+ id, exists := m.ID()
+ if exists {
+ return []uuid.UUID{id}, nil
+ }
+ fallthrough
+ case m.op.Is(OpUpdate | OpDelete):
+ return m.Client().Model.Query().Where(m.predicates...).IDs(ctx)
+ default:
+ return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op)
+ }
+}
+
+// SetUserID sets the "user_id" field.
+func (m *ModelMutation) SetUserID(u uuid.UUID) {
+ m.user = &u
+}
+
+// UserID returns the value of the "user_id" field in the mutation.
+func (m *ModelMutation) UserID() (r uuid.UUID, exists bool) {
+ v := m.user
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldUserID returns the old "user_id" field's value of the Model entity.
+// If the Model 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 *ModelMutation) OldUserID(ctx context.Context) (v uuid.UUID, 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
+}
+
+// ClearUserID clears the value of the "user_id" field.
+func (m *ModelMutation) ClearUserID() {
+ m.user = nil
+ m.clearedFields[model.FieldUserID] = struct{}{}
+}
+
+// UserIDCleared returns if the "user_id" field was cleared in this mutation.
+func (m *ModelMutation) UserIDCleared() bool {
+ _, ok := m.clearedFields[model.FieldUserID]
+ return ok
+}
+
+// ResetUserID resets all changes to the "user_id" field.
+func (m *ModelMutation) ResetUserID() {
+ m.user = nil
+ delete(m.clearedFields, model.FieldUserID)
+}
+
+// SetModelName sets the "model_name" field.
+func (m *ModelMutation) SetModelName(s string) {
+ m.model_name = &s
+}
+
+// ModelName returns the value of the "model_name" field in the mutation.
+func (m *ModelMutation) ModelName() (r string, exists bool) {
+ v := m.model_name
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldModelName returns the old "model_name" field's value of the Model entity.
+// If the Model 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 *ModelMutation) OldModelName(ctx context.Context) (v string, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldModelName is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldModelName requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldModelName: %w", err)
+ }
+ return oldValue.ModelName, nil
+}
+
+// ResetModelName resets all changes to the "model_name" field.
+func (m *ModelMutation) ResetModelName() {
+ m.model_name = nil
+}
+
+// SetModelType sets the "model_type" field.
+func (m *ModelMutation) SetModelType(ct consts.ModelType) {
+ m.model_type = &ct
+}
+
+// ModelType returns the value of the "model_type" field in the mutation.
+func (m *ModelMutation) ModelType() (r consts.ModelType, exists bool) {
+ v := m.model_type
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldModelType returns the old "model_type" field's value of the Model entity.
+// If the Model 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 *ModelMutation) OldModelType(ctx context.Context) (v consts.ModelType, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldModelType is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldModelType requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldModelType: %w", err)
+ }
+ return oldValue.ModelType, nil
+}
+
+// ResetModelType resets all changes to the "model_type" field.
+func (m *ModelMutation) ResetModelType() {
+ m.model_type = nil
+}
+
+// SetAPIBase sets the "api_base" field.
+func (m *ModelMutation) SetAPIBase(s string) {
+ m.api_base = &s
+}
+
+// APIBase returns the value of the "api_base" field in the mutation.
+func (m *ModelMutation) APIBase() (r string, exists bool) {
+ v := m.api_base
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldAPIBase returns the old "api_base" field's value of the Model entity.
+// If the Model 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 *ModelMutation) OldAPIBase(ctx context.Context) (v string, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldAPIBase is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldAPIBase requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldAPIBase: %w", err)
+ }
+ return oldValue.APIBase, nil
+}
+
+// ResetAPIBase resets all changes to the "api_base" field.
+func (m *ModelMutation) ResetAPIBase() {
+ m.api_base = nil
+}
+
+// SetAPIKey sets the "api_key" field.
+func (m *ModelMutation) SetAPIKey(s string) {
+ m.api_key = &s
+}
+
+// APIKey returns the value of the "api_key" field in the mutation.
+func (m *ModelMutation) APIKey() (r string, exists bool) {
+ v := m.api_key
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldAPIKey returns the old "api_key" field's value of the Model entity.
+// If the Model 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 *ModelMutation) OldAPIKey(ctx context.Context) (v string, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldAPIKey is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldAPIKey requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldAPIKey: %w", err)
+ }
+ return oldValue.APIKey, nil
+}
+
+// ResetAPIKey resets all changes to the "api_key" field.
+func (m *ModelMutation) ResetAPIKey() {
+ m.api_key = nil
+}
+
+// SetAPIVersion sets the "api_version" field.
+func (m *ModelMutation) SetAPIVersion(s string) {
+ m.api_version = &s
+}
+
+// APIVersion returns the value of the "api_version" field in the mutation.
+func (m *ModelMutation) APIVersion() (r string, exists bool) {
+ v := m.api_version
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldAPIVersion returns the old "api_version" field's value of the Model entity.
+// If the Model 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 *ModelMutation) OldAPIVersion(ctx context.Context) (v string, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldAPIVersion is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldAPIVersion requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldAPIVersion: %w", err)
+ }
+ return oldValue.APIVersion, nil
+}
+
+// ClearAPIVersion clears the value of the "api_version" field.
+func (m *ModelMutation) ClearAPIVersion() {
+ m.api_version = nil
+ m.clearedFields[model.FieldAPIVersion] = struct{}{}
+}
+
+// APIVersionCleared returns if the "api_version" field was cleared in this mutation.
+func (m *ModelMutation) APIVersionCleared() bool {
+ _, ok := m.clearedFields[model.FieldAPIVersion]
+ return ok
+}
+
+// ResetAPIVersion resets all changes to the "api_version" field.
+func (m *ModelMutation) ResetAPIVersion() {
+ m.api_version = nil
+ delete(m.clearedFields, model.FieldAPIVersion)
+}
+
+// SetDescription sets the "description" field.
+func (m *ModelMutation) SetDescription(s string) {
+ m.description = &s
+}
+
+// Description returns the value of the "description" field in the mutation.
+func (m *ModelMutation) 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 Model entity.
+// If the Model 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 *ModelMutation) 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
+}
+
+// ClearDescription clears the value of the "description" field.
+func (m *ModelMutation) ClearDescription() {
+ m.description = nil
+ m.clearedFields[model.FieldDescription] = struct{}{}
+}
+
+// DescriptionCleared returns if the "description" field was cleared in this mutation.
+func (m *ModelMutation) DescriptionCleared() bool {
+ _, ok := m.clearedFields[model.FieldDescription]
+ return ok
+}
+
+// ResetDescription resets all changes to the "description" field.
+func (m *ModelMutation) ResetDescription() {
+ m.description = nil
+ delete(m.clearedFields, model.FieldDescription)
+}
+
+// SetProvider sets the "provider" field.
+func (m *ModelMutation) SetProvider(s string) {
+ m.provider = &s
+}
+
+// Provider returns the value of the "provider" field in the mutation.
+func (m *ModelMutation) Provider() (r string, exists bool) {
+ v := m.provider
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldProvider returns the old "provider" field's value of the Model entity.
+// If the Model 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 *ModelMutation) OldProvider(ctx context.Context) (v string, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldProvider is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldProvider requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldProvider: %w", err)
+ }
+ return oldValue.Provider, nil
+}
+
+// ResetProvider resets all changes to the "provider" field.
+func (m *ModelMutation) ResetProvider() {
+ m.provider = nil
+}
+
+// SetStatus sets the "status" field.
+func (m *ModelMutation) SetStatus(cs consts.ModelStatus) {
+ m.status = &cs
+}
+
+// Status returns the value of the "status" field in the mutation.
+func (m *ModelMutation) Status() (r consts.ModelStatus, exists bool) {
+ v := m.status
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldStatus returns the old "status" field's value of the Model entity.
+// If the Model 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 *ModelMutation) OldStatus(ctx context.Context) (v consts.ModelStatus, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldStatus is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldStatus requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldStatus: %w", err)
+ }
+ return oldValue.Status, nil
+}
+
+// ResetStatus resets all changes to the "status" field.
+func (m *ModelMutation) ResetStatus() {
+ m.status = nil
+}
+
+// SetContextLength sets the "context_length" field.
+func (m *ModelMutation) SetContextLength(i int) {
+ m.context_length = &i
+ m.addcontext_length = nil
+}
+
+// ContextLength returns the value of the "context_length" field in the mutation.
+func (m *ModelMutation) ContextLength() (r int, exists bool) {
+ v := m.context_length
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldContextLength returns the old "context_length" field's value of the Model entity.
+// If the Model 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 *ModelMutation) OldContextLength(ctx context.Context) (v int, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldContextLength is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldContextLength requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldContextLength: %w", err)
+ }
+ return oldValue.ContextLength, nil
+}
+
+// AddContextLength adds i to the "context_length" field.
+func (m *ModelMutation) AddContextLength(i int) {
+ if m.addcontext_length != nil {
+ *m.addcontext_length += i
+ } else {
+ m.addcontext_length = &i
+ }
+}
+
+// AddedContextLength returns the value that was added to the "context_length" field in this mutation.
+func (m *ModelMutation) AddedContextLength() (r int, exists bool) {
+ v := m.addcontext_length
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// ClearContextLength clears the value of the "context_length" field.
+func (m *ModelMutation) ClearContextLength() {
+ m.context_length = nil
+ m.addcontext_length = nil
+ m.clearedFields[model.FieldContextLength] = struct{}{}
+}
+
+// ContextLengthCleared returns if the "context_length" field was cleared in this mutation.
+func (m *ModelMutation) ContextLengthCleared() bool {
+ _, ok := m.clearedFields[model.FieldContextLength]
+ return ok
+}
+
+// ResetContextLength resets all changes to the "context_length" field.
+func (m *ModelMutation) ResetContextLength() {
+ m.context_length = nil
+ m.addcontext_length = nil
+ delete(m.clearedFields, model.FieldContextLength)
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (m *ModelMutation) SetCreatedAt(t time.Time) {
+ m.created_at = &t
+}
+
+// CreatedAt returns the value of the "created_at" field in the mutation.
+func (m *ModelMutation) 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 Model entity.
+// If the Model 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 *ModelMutation) 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 *ModelMutation) ResetCreatedAt() {
+ m.created_at = nil
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (m *ModelMutation) SetUpdatedAt(t time.Time) {
+ m.updated_at = &t
+}
+
+// UpdatedAt returns the value of the "updated_at" field in the mutation.
+func (m *ModelMutation) 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 Model entity.
+// If the Model 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 *ModelMutation) 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 *ModelMutation) ResetUpdatedAt() {
+ m.updated_at = nil
+}
+
+// AddRecordIDs adds the "records" edge to the Record entity by ids.
+func (m *ModelMutation) AddRecordIDs(ids ...uuid.UUID) {
+ if m.records == nil {
+ m.records = make(map[uuid.UUID]struct{})
+ }
+ for i := range ids {
+ m.records[ids[i]] = struct{}{}
+ }
+}
+
+// ClearRecords clears the "records" edge to the Record entity.
+func (m *ModelMutation) ClearRecords() {
+ m.clearedrecords = true
+}
+
+// RecordsCleared reports if the "records" edge to the Record entity was cleared.
+func (m *ModelMutation) RecordsCleared() bool {
+ return m.clearedrecords
+}
+
+// RemoveRecordIDs removes the "records" edge to the Record entity by IDs.
+func (m *ModelMutation) RemoveRecordIDs(ids ...uuid.UUID) {
+ if m.removedrecords == nil {
+ m.removedrecords = make(map[uuid.UUID]struct{})
+ }
+ for i := range ids {
+ delete(m.records, ids[i])
+ m.removedrecords[ids[i]] = struct{}{}
+ }
+}
+
+// RemovedRecords returns the removed IDs of the "records" edge to the Record entity.
+func (m *ModelMutation) RemovedRecordsIDs() (ids []uuid.UUID) {
+ for id := range m.removedrecords {
+ ids = append(ids, id)
+ }
+ return
+}
+
+// RecordsIDs returns the "records" edge IDs in the mutation.
+func (m *ModelMutation) RecordsIDs() (ids []uuid.UUID) {
+ for id := range m.records {
+ ids = append(ids, id)
+ }
+ return
+}
+
+// ResetRecords resets all changes to the "records" edge.
+func (m *ModelMutation) ResetRecords() {
+ m.records = nil
+ m.clearedrecords = false
+ m.removedrecords = nil
+}
+
+// ClearUser clears the "user" edge to the User entity.
+func (m *ModelMutation) ClearUser() {
+ m.cleareduser = true
+ m.clearedFields[model.FieldUserID] = struct{}{}
+}
+
+// UserCleared reports if the "user" edge to the User entity was cleared.
+func (m *ModelMutation) UserCleared() bool {
+ return m.UserIDCleared() || 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 *ModelMutation) UserIDs() (ids []uuid.UUID) {
+ if id := m.user; id != nil {
+ ids = append(ids, *id)
+ }
+ return
+}
+
+// ResetUser resets all changes to the "user" edge.
+func (m *ModelMutation) ResetUser() {
+ m.user = nil
+ m.cleareduser = false
+}
+
+// Where appends a list predicates to the ModelMutation builder.
+func (m *ModelMutation) Where(ps ...predicate.Model) {
+ m.predicates = append(m.predicates, ps...)
+}
+
+// WhereP appends storage-level predicates to the ModelMutation builder. Using this method,
+// users can use type-assertion to append predicates that do not depend on any generated package.
+func (m *ModelMutation) WhereP(ps ...func(*sql.Selector)) {
+ p := make([]predicate.Model, len(ps))
+ for i := range ps {
+ p[i] = ps[i]
+ }
+ m.Where(p...)
+}
+
+// Op returns the operation name.
+func (m *ModelMutation) Op() Op {
+ return m.op
+}
+
+// SetOp allows setting the mutation operation.
+func (m *ModelMutation) SetOp(op Op) {
+ m.op = op
+}
+
+// Type returns the node type of this mutation (Model).
+func (m *ModelMutation) 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 *ModelMutation) Fields() []string {
+ fields := make([]string, 0, 12)
+ if m.user != nil {
+ fields = append(fields, model.FieldUserID)
+ }
+ if m.model_name != nil {
+ fields = append(fields, model.FieldModelName)
+ }
+ if m.model_type != nil {
+ fields = append(fields, model.FieldModelType)
+ }
+ if m.api_base != nil {
+ fields = append(fields, model.FieldAPIBase)
+ }
+ if m.api_key != nil {
+ fields = append(fields, model.FieldAPIKey)
+ }
+ if m.api_version != nil {
+ fields = append(fields, model.FieldAPIVersion)
+ }
+ if m.description != nil {
+ fields = append(fields, model.FieldDescription)
+ }
+ if m.provider != nil {
+ fields = append(fields, model.FieldProvider)
+ }
+ if m.status != nil {
+ fields = append(fields, model.FieldStatus)
+ }
+ if m.context_length != nil {
+ fields = append(fields, model.FieldContextLength)
+ }
+ if m.created_at != nil {
+ fields = append(fields, model.FieldCreatedAt)
+ }
+ if m.updated_at != nil {
+ fields = append(fields, model.FieldUpdatedAt)
+ }
+ 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 *ModelMutation) Field(name string) (ent.Value, bool) {
+ switch name {
+ case model.FieldUserID:
+ return m.UserID()
+ case model.FieldModelName:
+ return m.ModelName()
+ case model.FieldModelType:
+ return m.ModelType()
+ case model.FieldAPIBase:
+ return m.APIBase()
+ case model.FieldAPIKey:
+ return m.APIKey()
+ case model.FieldAPIVersion:
+ return m.APIVersion()
+ case model.FieldDescription:
+ return m.Description()
+ case model.FieldProvider:
+ return m.Provider()
+ case model.FieldStatus:
+ return m.Status()
+ case model.FieldContextLength:
+ return m.ContextLength()
+ case model.FieldCreatedAt:
+ return m.CreatedAt()
+ case model.FieldUpdatedAt:
+ return m.UpdatedAt()
+ }
+ 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 *ModelMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
+ switch name {
+ case model.FieldUserID:
+ return m.OldUserID(ctx)
+ case model.FieldModelName:
+ return m.OldModelName(ctx)
+ case model.FieldModelType:
+ return m.OldModelType(ctx)
+ case model.FieldAPIBase:
+ return m.OldAPIBase(ctx)
+ case model.FieldAPIKey:
+ return m.OldAPIKey(ctx)
+ case model.FieldAPIVersion:
+ return m.OldAPIVersion(ctx)
+ case model.FieldDescription:
+ return m.OldDescription(ctx)
+ case model.FieldProvider:
+ return m.OldProvider(ctx)
+ case model.FieldStatus:
+ return m.OldStatus(ctx)
+ case model.FieldContextLength:
+ return m.OldContextLength(ctx)
+ case model.FieldCreatedAt:
+ return m.OldCreatedAt(ctx)
+ case model.FieldUpdatedAt:
+ return m.OldUpdatedAt(ctx)
+ }
+ return nil, fmt.Errorf("unknown Model 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 *ModelMutation) SetField(name string, value ent.Value) error {
+ switch name {
+ case model.FieldUserID:
+ v, ok := value.(uuid.UUID)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetUserID(v)
+ return nil
+ case model.FieldModelName:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetModelName(v)
+ return nil
+ case model.FieldModelType:
+ v, ok := value.(consts.ModelType)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetModelType(v)
+ return nil
+ case model.FieldAPIBase:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetAPIBase(v)
+ return nil
+ case model.FieldAPIKey:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetAPIKey(v)
+ return nil
+ case model.FieldAPIVersion:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetAPIVersion(v)
+ return nil
+ case model.FieldDescription:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetDescription(v)
+ return nil
+ case model.FieldProvider:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetProvider(v)
+ return nil
+ case model.FieldStatus:
+ v, ok := value.(consts.ModelStatus)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetStatus(v)
+ return nil
+ case model.FieldContextLength:
+ v, ok := value.(int)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetContextLength(v)
+ return nil
+ case model.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 model.FieldUpdatedAt:
+ v, ok := value.(time.Time)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetUpdatedAt(v)
+ return nil
+ }
+ return fmt.Errorf("unknown Model field %s", name)
+}
+
+// AddedFields returns all numeric fields that were incremented/decremented during
+// this mutation.
+func (m *ModelMutation) AddedFields() []string {
+ var fields []string
+ if m.addcontext_length != nil {
+ fields = append(fields, model.FieldContextLength)
+ }
+ 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 *ModelMutation) AddedField(name string) (ent.Value, bool) {
+ switch name {
+ case model.FieldContextLength:
+ return m.AddedContextLength()
+ }
+ 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 *ModelMutation) AddField(name string, value ent.Value) error {
+ switch name {
+ case model.FieldContextLength:
+ v, ok := value.(int)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.AddContextLength(v)
+ return nil
+ }
+ return fmt.Errorf("unknown Model numeric field %s", name)
+}
+
+// ClearedFields returns all nullable fields that were cleared during this
+// mutation.
+func (m *ModelMutation) ClearedFields() []string {
+ var fields []string
+ if m.FieldCleared(model.FieldUserID) {
+ fields = append(fields, model.FieldUserID)
+ }
+ if m.FieldCleared(model.FieldAPIVersion) {
+ fields = append(fields, model.FieldAPIVersion)
+ }
+ if m.FieldCleared(model.FieldDescription) {
+ fields = append(fields, model.FieldDescription)
+ }
+ if m.FieldCleared(model.FieldContextLength) {
+ fields = append(fields, model.FieldContextLength)
+ }
+ return fields
+}
+
+// FieldCleared returns a boolean indicating if a field with the given name was
+// cleared in this mutation.
+func (m *ModelMutation) 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 *ModelMutation) ClearField(name string) error {
+ switch name {
+ case model.FieldUserID:
+ m.ClearUserID()
+ return nil
+ case model.FieldAPIVersion:
+ m.ClearAPIVersion()
+ return nil
+ case model.FieldDescription:
+ m.ClearDescription()
+ return nil
+ case model.FieldContextLength:
+ m.ClearContextLength()
+ return nil
+ }
+ return fmt.Errorf("unknown Model 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 *ModelMutation) ResetField(name string) error {
+ switch name {
+ case model.FieldUserID:
+ m.ResetUserID()
+ return nil
+ case model.FieldModelName:
+ m.ResetModelName()
+ return nil
+ case model.FieldModelType:
+ m.ResetModelType()
+ return nil
+ case model.FieldAPIBase:
+ m.ResetAPIBase()
+ return nil
+ case model.FieldAPIKey:
+ m.ResetAPIKey()
+ return nil
+ case model.FieldAPIVersion:
+ m.ResetAPIVersion()
+ return nil
+ case model.FieldDescription:
+ m.ResetDescription()
+ return nil
+ case model.FieldProvider:
+ m.ResetProvider()
+ return nil
+ case model.FieldStatus:
+ m.ResetStatus()
+ return nil
+ case model.FieldContextLength:
+ m.ResetContextLength()
+ return nil
+ case model.FieldCreatedAt:
+ m.ResetCreatedAt()
+ return nil
+ case model.FieldUpdatedAt:
+ m.ResetUpdatedAt()
+ return nil
+ }
+ return fmt.Errorf("unknown Model field %s", name)
+}
+
+// AddedEdges returns all edge names that were set/added in this mutation.
+func (m *ModelMutation) AddedEdges() []string {
+ edges := make([]string, 0, 2)
+ if m.records != nil {
+ edges = append(edges, model.EdgeRecords)
+ }
+ if m.user != nil {
+ edges = append(edges, model.EdgeUser)
+ }
+ return edges
+}
+
+// AddedIDs returns all IDs (to other nodes) that were added for the given edge
+// name in this mutation.
+func (m *ModelMutation) AddedIDs(name string) []ent.Value {
+ switch name {
+ case model.EdgeRecords:
+ ids := make([]ent.Value, 0, len(m.records))
+ for id := range m.records {
+ ids = append(ids, id)
+ }
+ return ids
+ case model.EdgeUser:
+ if id := m.user; id != nil {
+ return []ent.Value{*id}
+ }
+ }
+ return nil
+}
+
+// RemovedEdges returns all edge names that were removed in this mutation.
+func (m *ModelMutation) RemovedEdges() []string {
+ edges := make([]string, 0, 2)
+ if m.removedrecords != nil {
+ edges = append(edges, model.EdgeRecords)
+ }
+ return edges
+}
+
+// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with
+// the given name in this mutation.
+func (m *ModelMutation) RemovedIDs(name string) []ent.Value {
+ switch name {
+ case model.EdgeRecords:
+ ids := make([]ent.Value, 0, len(m.removedrecords))
+ for id := range m.removedrecords {
+ ids = append(ids, id)
+ }
+ return ids
+ }
+ return nil
+}
+
+// ClearedEdges returns all edge names that were cleared in this mutation.
+func (m *ModelMutation) ClearedEdges() []string {
+ edges := make([]string, 0, 2)
+ if m.clearedrecords {
+ edges = append(edges, model.EdgeRecords)
+ }
+ if m.cleareduser {
+ edges = append(edges, model.EdgeUser)
+ }
+ return edges
+}
+
+// EdgeCleared returns a boolean which indicates if the edge with the given name
+// was cleared in this mutation.
+func (m *ModelMutation) EdgeCleared(name string) bool {
+ switch name {
+ case model.EdgeRecords:
+ return m.clearedrecords
+ case model.EdgeUser:
+ return m.cleareduser
+ }
+ 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 *ModelMutation) ClearEdge(name string) error {
+ switch name {
+ case model.EdgeUser:
+ m.ClearUser()
+ return nil
+ }
+ return fmt.Errorf("unknown Model 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 *ModelMutation) ResetEdge(name string) error {
+ switch name {
+ case model.EdgeRecords:
+ m.ResetRecords()
+ return nil
+ case model.EdgeUser:
+ m.ResetUser()
+ return nil
+ }
+ return fmt.Errorf("unknown Model edge %s", name)
+}
+
+// RecordMutation represents an operation that mutates the Record nodes in the graph.
+type RecordMutation struct {
+ config
+ op Op
+ typ string
+ id *uuid.UUID
+ task_id *string
+ model_type *consts.ModelType
+ prompt *string
+ completion *string
+ is_accept *bool
+ program_language *string
+ work_mode *string
+ code_lines *int64
+ addcode_lines *int64
+ input_tokens *int64
+ addinput_tokens *int64
+ output_tokens *int64
+ addoutput_tokens *int64
+ created_at *time.Time
+ updated_at *time.Time
+ clearedFields map[string]struct{}
+ user *uuid.UUID
+ cleareduser bool
+ model *uuid.UUID
+ clearedmodel bool
+ done bool
+ oldValue func(context.Context) (*Record, error)
+ predicates []predicate.Record
+}
+
+var _ ent.Mutation = (*RecordMutation)(nil)
+
+// recordOption allows management of the mutation configuration using functional options.
+type recordOption func(*RecordMutation)
+
+// newRecordMutation creates new mutation for the Record entity.
+func newRecordMutation(c config, op Op, opts ...recordOption) *RecordMutation {
+ m := &RecordMutation{
+ config: c,
+ op: op,
+ typ: TypeRecord,
+ clearedFields: make(map[string]struct{}),
+ }
+ for _, opt := range opts {
+ opt(m)
+ }
+ return m
+}
+
+// withRecordID sets the ID field of the mutation.
+func withRecordID(id uuid.UUID) recordOption {
+ return func(m *RecordMutation) {
+ var (
+ err error
+ once sync.Once
+ value *Record
+ )
+ m.oldValue = func(ctx context.Context) (*Record, error) {
+ once.Do(func() {
+ if m.done {
+ err = errors.New("querying old values post mutation is not allowed")
+ } else {
+ value, err = m.Client().Record.Get(ctx, id)
+ }
+ })
+ return value, err
+ }
+ m.id = &id
+ }
+}
+
+// withRecord sets the old Record of the mutation.
+func withRecord(node *Record) recordOption {
+ return func(m *RecordMutation) {
+ m.oldValue = func(context.Context) (*Record, 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 RecordMutation) 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 RecordMutation) Tx() (*Tx, error) {
+ if _, ok := m.driver.(*txDriver); !ok {
+ return nil, errors.New("db: mutation is not running in a transaction")
+ }
+ tx := &Tx{config: m.config}
+ tx.init()
+ return tx, nil
+}
+
+// SetID sets the value of the id field. Note that this
+// operation is only accepted on creation of Record entities.
+func (m *RecordMutation) SetID(id uuid.UUID) {
+ m.id = &id
+}
+
+// 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 *RecordMutation) ID() (id uuid.UUID, 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 *RecordMutation) IDs(ctx context.Context) ([]uuid.UUID, error) {
+ switch {
+ case m.op.Is(OpUpdateOne | OpDeleteOne):
+ id, exists := m.ID()
+ if exists {
+ return []uuid.UUID{id}, nil
+ }
+ fallthrough
+ case m.op.Is(OpUpdate | OpDelete):
+ return m.Client().Record.Query().Where(m.predicates...).IDs(ctx)
+ default:
+ return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op)
+ }
+}
+
+// SetUserID sets the "user_id" field.
+func (m *RecordMutation) SetUserID(u uuid.UUID) {
+ m.user = &u
+}
+
+// UserID returns the value of the "user_id" field in the mutation.
+func (m *RecordMutation) UserID() (r uuid.UUID, exists bool) {
+ v := m.user
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldUserID returns the old "user_id" field's value of the Record entity.
+// If the Record 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 *RecordMutation) OldUserID(ctx context.Context) (v uuid.UUID, 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
+}
+
+// ClearUserID clears the value of the "user_id" field.
+func (m *RecordMutation) ClearUserID() {
+ m.user = nil
+ m.clearedFields[record.FieldUserID] = struct{}{}
+}
+
+// UserIDCleared returns if the "user_id" field was cleared in this mutation.
+func (m *RecordMutation) UserIDCleared() bool {
+ _, ok := m.clearedFields[record.FieldUserID]
+ return ok
+}
+
+// ResetUserID resets all changes to the "user_id" field.
+func (m *RecordMutation) ResetUserID() {
+ m.user = nil
+ delete(m.clearedFields, record.FieldUserID)
+}
+
+// SetModelID sets the "model_id" field.
+func (m *RecordMutation) SetModelID(u uuid.UUID) {
+ m.model = &u
+}
+
+// ModelID returns the value of the "model_id" field in the mutation.
+func (m *RecordMutation) ModelID() (r uuid.UUID, exists bool) {
+ v := m.model
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldModelID returns the old "model_id" field's value of the Record entity.
+// If the Record 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 *RecordMutation) OldModelID(ctx context.Context) (v uuid.UUID, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldModelID is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldModelID requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldModelID: %w", err)
+ }
+ return oldValue.ModelID, nil
+}
+
+// ClearModelID clears the value of the "model_id" field.
+func (m *RecordMutation) ClearModelID() {
+ m.model = nil
+ m.clearedFields[record.FieldModelID] = struct{}{}
+}
+
+// ModelIDCleared returns if the "model_id" field was cleared in this mutation.
+func (m *RecordMutation) ModelIDCleared() bool {
+ _, ok := m.clearedFields[record.FieldModelID]
+ return ok
+}
+
+// ResetModelID resets all changes to the "model_id" field.
+func (m *RecordMutation) ResetModelID() {
+ m.model = nil
+ delete(m.clearedFields, record.FieldModelID)
+}
+
+// SetTaskID sets the "task_id" field.
+func (m *RecordMutation) SetTaskID(s string) {
+ m.task_id = &s
+}
+
+// TaskID returns the value of the "task_id" field in the mutation.
+func (m *RecordMutation) TaskID() (r string, exists bool) {
+ v := m.task_id
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldTaskID returns the old "task_id" field's value of the Record entity.
+// If the Record 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 *RecordMutation) OldTaskID(ctx context.Context) (v string, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldTaskID is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldTaskID requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldTaskID: %w", err)
+ }
+ return oldValue.TaskID, nil
+}
+
+// ResetTaskID resets all changes to the "task_id" field.
+func (m *RecordMutation) ResetTaskID() {
+ m.task_id = nil
+}
+
+// SetModelType sets the "model_type" field.
+func (m *RecordMutation) SetModelType(ct consts.ModelType) {
+ m.model_type = &ct
+}
+
+// ModelType returns the value of the "model_type" field in the mutation.
+func (m *RecordMutation) ModelType() (r consts.ModelType, exists bool) {
+ v := m.model_type
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldModelType returns the old "model_type" field's value of the Record entity.
+// If the Record 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 *RecordMutation) OldModelType(ctx context.Context) (v consts.ModelType, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldModelType is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldModelType requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldModelType: %w", err)
+ }
+ return oldValue.ModelType, nil
+}
+
+// ClearModelType clears the value of the "model_type" field.
+func (m *RecordMutation) ClearModelType() {
+ m.model_type = nil
+ m.clearedFields[record.FieldModelType] = struct{}{}
+}
+
+// ModelTypeCleared returns if the "model_type" field was cleared in this mutation.
+func (m *RecordMutation) ModelTypeCleared() bool {
+ _, ok := m.clearedFields[record.FieldModelType]
+ return ok
+}
+
+// ResetModelType resets all changes to the "model_type" field.
+func (m *RecordMutation) ResetModelType() {
+ m.model_type = nil
+ delete(m.clearedFields, record.FieldModelType)
+}
+
+// SetPrompt sets the "prompt" field.
+func (m *RecordMutation) SetPrompt(s string) {
+ m.prompt = &s
+}
+
+// Prompt returns the value of the "prompt" field in the mutation.
+func (m *RecordMutation) Prompt() (r string, exists bool) {
+ v := m.prompt
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldPrompt returns the old "prompt" field's value of the Record entity.
+// If the Record 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 *RecordMutation) OldPrompt(ctx context.Context) (v string, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldPrompt is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldPrompt requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldPrompt: %w", err)
+ }
+ return oldValue.Prompt, nil
+}
+
+// ClearPrompt clears the value of the "prompt" field.
+func (m *RecordMutation) ClearPrompt() {
+ m.prompt = nil
+ m.clearedFields[record.FieldPrompt] = struct{}{}
+}
+
+// PromptCleared returns if the "prompt" field was cleared in this mutation.
+func (m *RecordMutation) PromptCleared() bool {
+ _, ok := m.clearedFields[record.FieldPrompt]
+ return ok
+}
+
+// ResetPrompt resets all changes to the "prompt" field.
+func (m *RecordMutation) ResetPrompt() {
+ m.prompt = nil
+ delete(m.clearedFields, record.FieldPrompt)
+}
+
+// SetCompletion sets the "completion" field.
+func (m *RecordMutation) SetCompletion(s string) {
+ m.completion = &s
+}
+
+// Completion returns the value of the "completion" field in the mutation.
+func (m *RecordMutation) Completion() (r string, exists bool) {
+ v := m.completion
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldCompletion returns the old "completion" field's value of the Record entity.
+// If the Record 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 *RecordMutation) OldCompletion(ctx context.Context) (v string, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldCompletion is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldCompletion requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldCompletion: %w", err)
+ }
+ return oldValue.Completion, nil
+}
+
+// ClearCompletion clears the value of the "completion" field.
+func (m *RecordMutation) ClearCompletion() {
+ m.completion = nil
+ m.clearedFields[record.FieldCompletion] = struct{}{}
+}
+
+// CompletionCleared returns if the "completion" field was cleared in this mutation.
+func (m *RecordMutation) CompletionCleared() bool {
+ _, ok := m.clearedFields[record.FieldCompletion]
+ return ok
+}
+
+// ResetCompletion resets all changes to the "completion" field.
+func (m *RecordMutation) ResetCompletion() {
+ m.completion = nil
+ delete(m.clearedFields, record.FieldCompletion)
+}
+
+// SetIsAccept sets the "is_accept" field.
+func (m *RecordMutation) SetIsAccept(b bool) {
+ m.is_accept = &b
+}
+
+// IsAccept returns the value of the "is_accept" field in the mutation.
+func (m *RecordMutation) IsAccept() (r bool, exists bool) {
+ v := m.is_accept
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldIsAccept returns the old "is_accept" field's value of the Record entity.
+// If the Record 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 *RecordMutation) OldIsAccept(ctx context.Context) (v bool, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldIsAccept is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldIsAccept requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldIsAccept: %w", err)
+ }
+ return oldValue.IsAccept, nil
+}
+
+// ResetIsAccept resets all changes to the "is_accept" field.
+func (m *RecordMutation) ResetIsAccept() {
+ m.is_accept = nil
+}
+
+// SetProgramLanguage sets the "program_language" field.
+func (m *RecordMutation) SetProgramLanguage(s string) {
+ m.program_language = &s
+}
+
+// ProgramLanguage returns the value of the "program_language" field in the mutation.
+func (m *RecordMutation) ProgramLanguage() (r string, exists bool) {
+ v := m.program_language
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldProgramLanguage returns the old "program_language" field's value of the Record entity.
+// If the Record 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 *RecordMutation) OldProgramLanguage(ctx context.Context) (v string, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldProgramLanguage is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldProgramLanguage requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldProgramLanguage: %w", err)
+ }
+ return oldValue.ProgramLanguage, nil
+}
+
+// ClearProgramLanguage clears the value of the "program_language" field.
+func (m *RecordMutation) ClearProgramLanguage() {
+ m.program_language = nil
+ m.clearedFields[record.FieldProgramLanguage] = struct{}{}
+}
+
+// ProgramLanguageCleared returns if the "program_language" field was cleared in this mutation.
+func (m *RecordMutation) ProgramLanguageCleared() bool {
+ _, ok := m.clearedFields[record.FieldProgramLanguage]
+ return ok
+}
+
+// ResetProgramLanguage resets all changes to the "program_language" field.
+func (m *RecordMutation) ResetProgramLanguage() {
+ m.program_language = nil
+ delete(m.clearedFields, record.FieldProgramLanguage)
+}
+
+// SetWorkMode sets the "work_mode" field.
+func (m *RecordMutation) SetWorkMode(s string) {
+ m.work_mode = &s
+}
+
+// WorkMode returns the value of the "work_mode" field in the mutation.
+func (m *RecordMutation) WorkMode() (r string, exists bool) {
+ v := m.work_mode
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldWorkMode returns the old "work_mode" field's value of the Record entity.
+// If the Record 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 *RecordMutation) OldWorkMode(ctx context.Context) (v string, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldWorkMode is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldWorkMode requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldWorkMode: %w", err)
+ }
+ return oldValue.WorkMode, nil
+}
+
+// ClearWorkMode clears the value of the "work_mode" field.
+func (m *RecordMutation) ClearWorkMode() {
+ m.work_mode = nil
+ m.clearedFields[record.FieldWorkMode] = struct{}{}
+}
+
+// WorkModeCleared returns if the "work_mode" field was cleared in this mutation.
+func (m *RecordMutation) WorkModeCleared() bool {
+ _, ok := m.clearedFields[record.FieldWorkMode]
+ return ok
+}
+
+// ResetWorkMode resets all changes to the "work_mode" field.
+func (m *RecordMutation) ResetWorkMode() {
+ m.work_mode = nil
+ delete(m.clearedFields, record.FieldWorkMode)
+}
+
+// SetCodeLines sets the "code_lines" field.
+func (m *RecordMutation) SetCodeLines(i int64) {
+ m.code_lines = &i
+ m.addcode_lines = nil
+}
+
+// CodeLines returns the value of the "code_lines" field in the mutation.
+func (m *RecordMutation) CodeLines() (r int64, exists bool) {
+ v := m.code_lines
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldCodeLines returns the old "code_lines" field's value of the Record entity.
+// If the Record 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 *RecordMutation) OldCodeLines(ctx context.Context) (v int64, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldCodeLines is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldCodeLines requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldCodeLines: %w", err)
+ }
+ return oldValue.CodeLines, nil
+}
+
+// AddCodeLines adds i to the "code_lines" field.
+func (m *RecordMutation) AddCodeLines(i int64) {
+ if m.addcode_lines != nil {
+ *m.addcode_lines += i
+ } else {
+ m.addcode_lines = &i
+ }
+}
+
+// AddedCodeLines returns the value that was added to the "code_lines" field in this mutation.
+func (m *RecordMutation) AddedCodeLines() (r int64, exists bool) {
+ v := m.addcode_lines
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// ClearCodeLines clears the value of the "code_lines" field.
+func (m *RecordMutation) ClearCodeLines() {
+ m.code_lines = nil
+ m.addcode_lines = nil
+ m.clearedFields[record.FieldCodeLines] = struct{}{}
+}
+
+// CodeLinesCleared returns if the "code_lines" field was cleared in this mutation.
+func (m *RecordMutation) CodeLinesCleared() bool {
+ _, ok := m.clearedFields[record.FieldCodeLines]
+ return ok
+}
+
+// ResetCodeLines resets all changes to the "code_lines" field.
+func (m *RecordMutation) ResetCodeLines() {
+ m.code_lines = nil
+ m.addcode_lines = nil
+ delete(m.clearedFields, record.FieldCodeLines)
+}
+
+// SetInputTokens sets the "input_tokens" field.
+func (m *RecordMutation) SetInputTokens(i int64) {
+ m.input_tokens = &i
+ m.addinput_tokens = nil
+}
+
+// InputTokens returns the value of the "input_tokens" field in the mutation.
+func (m *RecordMutation) InputTokens() (r int64, exists bool) {
+ v := m.input_tokens
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldInputTokens returns the old "input_tokens" field's value of the Record entity.
+// If the Record 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 *RecordMutation) OldInputTokens(ctx context.Context) (v int64, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldInputTokens is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldInputTokens requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldInputTokens: %w", err)
+ }
+ return oldValue.InputTokens, nil
+}
+
+// AddInputTokens adds i to the "input_tokens" field.
+func (m *RecordMutation) AddInputTokens(i int64) {
+ if m.addinput_tokens != nil {
+ *m.addinput_tokens += i
+ } else {
+ m.addinput_tokens = &i
+ }
+}
+
+// AddedInputTokens returns the value that was added to the "input_tokens" field in this mutation.
+func (m *RecordMutation) AddedInputTokens() (r int64, exists bool) {
+ v := m.addinput_tokens
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// ResetInputTokens resets all changes to the "input_tokens" field.
+func (m *RecordMutation) ResetInputTokens() {
+ m.input_tokens = nil
+ m.addinput_tokens = nil
+}
+
+// SetOutputTokens sets the "output_tokens" field.
+func (m *RecordMutation) SetOutputTokens(i int64) {
+ m.output_tokens = &i
+ m.addoutput_tokens = nil
+}
+
+// OutputTokens returns the value of the "output_tokens" field in the mutation.
+func (m *RecordMutation) OutputTokens() (r int64, exists bool) {
+ v := m.output_tokens
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldOutputTokens returns the old "output_tokens" field's value of the Record entity.
+// If the Record 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 *RecordMutation) OldOutputTokens(ctx context.Context) (v int64, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldOutputTokens is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldOutputTokens requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldOutputTokens: %w", err)
+ }
+ return oldValue.OutputTokens, nil
+}
+
+// AddOutputTokens adds i to the "output_tokens" field.
+func (m *RecordMutation) AddOutputTokens(i int64) {
+ if m.addoutput_tokens != nil {
+ *m.addoutput_tokens += i
+ } else {
+ m.addoutput_tokens = &i
+ }
+}
+
+// AddedOutputTokens returns the value that was added to the "output_tokens" field in this mutation.
+func (m *RecordMutation) AddedOutputTokens() (r int64, exists bool) {
+ v := m.addoutput_tokens
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// ResetOutputTokens resets all changes to the "output_tokens" field.
+func (m *RecordMutation) ResetOutputTokens() {
+ m.output_tokens = nil
+ m.addoutput_tokens = nil
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (m *RecordMutation) SetCreatedAt(t time.Time) {
+ m.created_at = &t
+}
+
+// CreatedAt returns the value of the "created_at" field in the mutation.
+func (m *RecordMutation) 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 Record entity.
+// If the Record 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 *RecordMutation) 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 *RecordMutation) ResetCreatedAt() {
+ m.created_at = nil
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (m *RecordMutation) SetUpdatedAt(t time.Time) {
+ m.updated_at = &t
+}
+
+// UpdatedAt returns the value of the "updated_at" field in the mutation.
+func (m *RecordMutation) 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 Record entity.
+// If the Record 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 *RecordMutation) 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 *RecordMutation) ResetUpdatedAt() {
+ m.updated_at = nil
+}
+
+// ClearUser clears the "user" edge to the User entity.
+func (m *RecordMutation) ClearUser() {
+ m.cleareduser = true
+ m.clearedFields[record.FieldUserID] = struct{}{}
+}
+
+// UserCleared reports if the "user" edge to the User entity was cleared.
+func (m *RecordMutation) UserCleared() bool {
+ return m.UserIDCleared() || 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 *RecordMutation) UserIDs() (ids []uuid.UUID) {
+ if id := m.user; id != nil {
+ ids = append(ids, *id)
+ }
+ return
+}
+
+// ResetUser resets all changes to the "user" edge.
+func (m *RecordMutation) ResetUser() {
+ m.user = nil
+ m.cleareduser = false
+}
+
+// ClearModel clears the "model" edge to the Model entity.
+func (m *RecordMutation) ClearModel() {
+ m.clearedmodel = true
+ m.clearedFields[record.FieldModelID] = struct{}{}
+}
+
+// ModelCleared reports if the "model" edge to the Model entity was cleared.
+func (m *RecordMutation) ModelCleared() bool {
+ return m.ModelIDCleared() || m.clearedmodel
+}
+
+// ModelIDs returns the "model" edge IDs in the mutation.
+// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use
+// ModelID instead. It exists only for internal usage by the builders.
+func (m *RecordMutation) ModelIDs() (ids []uuid.UUID) {
+ if id := m.model; id != nil {
+ ids = append(ids, *id)
+ }
+ return
+}
+
+// ResetModel resets all changes to the "model" edge.
+func (m *RecordMutation) ResetModel() {
+ m.model = nil
+ m.clearedmodel = false
+}
+
+// Where appends a list predicates to the RecordMutation builder.
+func (m *RecordMutation) Where(ps ...predicate.Record) {
+ m.predicates = append(m.predicates, ps...)
+}
+
+// WhereP appends storage-level predicates to the RecordMutation builder. Using this method,
+// users can use type-assertion to append predicates that do not depend on any generated package.
+func (m *RecordMutation) WhereP(ps ...func(*sql.Selector)) {
+ p := make([]predicate.Record, len(ps))
+ for i := range ps {
+ p[i] = ps[i]
+ }
+ m.Where(p...)
+}
+
+// Op returns the operation name.
+func (m *RecordMutation) Op() Op {
+ return m.op
+}
+
+// SetOp allows setting the mutation operation.
+func (m *RecordMutation) SetOp(op Op) {
+ m.op = op
+}
+
+// Type returns the node type of this mutation (Record).
+func (m *RecordMutation) 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 *RecordMutation) Fields() []string {
+ fields := make([]string, 0, 14)
+ if m.user != nil {
+ fields = append(fields, record.FieldUserID)
+ }
+ if m.model != nil {
+ fields = append(fields, record.FieldModelID)
+ }
+ if m.task_id != nil {
+ fields = append(fields, record.FieldTaskID)
+ }
+ if m.model_type != nil {
+ fields = append(fields, record.FieldModelType)
+ }
+ if m.prompt != nil {
+ fields = append(fields, record.FieldPrompt)
+ }
+ if m.completion != nil {
+ fields = append(fields, record.FieldCompletion)
+ }
+ if m.is_accept != nil {
+ fields = append(fields, record.FieldIsAccept)
+ }
+ if m.program_language != nil {
+ fields = append(fields, record.FieldProgramLanguage)
+ }
+ if m.work_mode != nil {
+ fields = append(fields, record.FieldWorkMode)
+ }
+ if m.code_lines != nil {
+ fields = append(fields, record.FieldCodeLines)
+ }
+ if m.input_tokens != nil {
+ fields = append(fields, record.FieldInputTokens)
+ }
+ if m.output_tokens != nil {
+ fields = append(fields, record.FieldOutputTokens)
+ }
+ if m.created_at != nil {
+ fields = append(fields, record.FieldCreatedAt)
+ }
+ if m.updated_at != nil {
+ fields = append(fields, record.FieldUpdatedAt)
+ }
+ 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 *RecordMutation) Field(name string) (ent.Value, bool) {
+ switch name {
+ case record.FieldUserID:
+ return m.UserID()
+ case record.FieldModelID:
+ return m.ModelID()
+ case record.FieldTaskID:
+ return m.TaskID()
+ case record.FieldModelType:
+ return m.ModelType()
+ case record.FieldPrompt:
+ return m.Prompt()
+ case record.FieldCompletion:
+ return m.Completion()
+ case record.FieldIsAccept:
+ return m.IsAccept()
+ case record.FieldProgramLanguage:
+ return m.ProgramLanguage()
+ case record.FieldWorkMode:
+ return m.WorkMode()
+ case record.FieldCodeLines:
+ return m.CodeLines()
+ case record.FieldInputTokens:
+ return m.InputTokens()
+ case record.FieldOutputTokens:
+ return m.OutputTokens()
+ case record.FieldCreatedAt:
+ return m.CreatedAt()
+ case record.FieldUpdatedAt:
+ return m.UpdatedAt()
+ }
+ 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 *RecordMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
+ switch name {
+ case record.FieldUserID:
+ return m.OldUserID(ctx)
+ case record.FieldModelID:
+ return m.OldModelID(ctx)
+ case record.FieldTaskID:
+ return m.OldTaskID(ctx)
+ case record.FieldModelType:
+ return m.OldModelType(ctx)
+ case record.FieldPrompt:
+ return m.OldPrompt(ctx)
+ case record.FieldCompletion:
+ return m.OldCompletion(ctx)
+ case record.FieldIsAccept:
+ return m.OldIsAccept(ctx)
+ case record.FieldProgramLanguage:
+ return m.OldProgramLanguage(ctx)
+ case record.FieldWorkMode:
+ return m.OldWorkMode(ctx)
+ case record.FieldCodeLines:
+ return m.OldCodeLines(ctx)
+ case record.FieldInputTokens:
+ return m.OldInputTokens(ctx)
+ case record.FieldOutputTokens:
+ return m.OldOutputTokens(ctx)
+ case record.FieldCreatedAt:
+ return m.OldCreatedAt(ctx)
+ case record.FieldUpdatedAt:
+ return m.OldUpdatedAt(ctx)
+ }
+ return nil, fmt.Errorf("unknown Record 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 *RecordMutation) SetField(name string, value ent.Value) error {
+ switch name {
+ case record.FieldUserID:
+ v, ok := value.(uuid.UUID)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetUserID(v)
+ return nil
+ case record.FieldModelID:
+ v, ok := value.(uuid.UUID)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetModelID(v)
+ return nil
+ case record.FieldTaskID:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetTaskID(v)
+ return nil
+ case record.FieldModelType:
+ v, ok := value.(consts.ModelType)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetModelType(v)
+ return nil
+ case record.FieldPrompt:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetPrompt(v)
+ return nil
+ case record.FieldCompletion:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetCompletion(v)
+ return nil
+ case record.FieldIsAccept:
+ v, ok := value.(bool)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetIsAccept(v)
+ return nil
+ case record.FieldProgramLanguage:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetProgramLanguage(v)
+ return nil
+ case record.FieldWorkMode:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetWorkMode(v)
+ return nil
+ case record.FieldCodeLines:
+ v, ok := value.(int64)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetCodeLines(v)
+ return nil
+ case record.FieldInputTokens:
+ v, ok := value.(int64)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetInputTokens(v)
+ return nil
+ case record.FieldOutputTokens:
+ v, ok := value.(int64)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetOutputTokens(v)
+ return nil
+ case record.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 record.FieldUpdatedAt:
+ v, ok := value.(time.Time)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetUpdatedAt(v)
+ return nil
+ }
+ return fmt.Errorf("unknown Record field %s", name)
+}
+
+// AddedFields returns all numeric fields that were incremented/decremented during
+// this mutation.
+func (m *RecordMutation) AddedFields() []string {
+ var fields []string
+ if m.addcode_lines != nil {
+ fields = append(fields, record.FieldCodeLines)
+ }
+ if m.addinput_tokens != nil {
+ fields = append(fields, record.FieldInputTokens)
+ }
+ if m.addoutput_tokens != nil {
+ fields = append(fields, record.FieldOutputTokens)
+ }
+ 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 *RecordMutation) AddedField(name string) (ent.Value, bool) {
+ switch name {
+ case record.FieldCodeLines:
+ return m.AddedCodeLines()
+ case record.FieldInputTokens:
+ return m.AddedInputTokens()
+ case record.FieldOutputTokens:
+ return m.AddedOutputTokens()
+ }
+ 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 *RecordMutation) AddField(name string, value ent.Value) error {
+ switch name {
+ case record.FieldCodeLines:
+ v, ok := value.(int64)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.AddCodeLines(v)
+ return nil
+ case record.FieldInputTokens:
+ v, ok := value.(int64)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.AddInputTokens(v)
+ return nil
+ case record.FieldOutputTokens:
+ v, ok := value.(int64)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.AddOutputTokens(v)
+ return nil
+ }
+ return fmt.Errorf("unknown Record numeric field %s", name)
+}
+
+// ClearedFields returns all nullable fields that were cleared during this
+// mutation.
+func (m *RecordMutation) ClearedFields() []string {
+ var fields []string
+ if m.FieldCleared(record.FieldUserID) {
+ fields = append(fields, record.FieldUserID)
+ }
+ if m.FieldCleared(record.FieldModelID) {
+ fields = append(fields, record.FieldModelID)
+ }
+ if m.FieldCleared(record.FieldModelType) {
+ fields = append(fields, record.FieldModelType)
+ }
+ if m.FieldCleared(record.FieldPrompt) {
+ fields = append(fields, record.FieldPrompt)
+ }
+ if m.FieldCleared(record.FieldCompletion) {
+ fields = append(fields, record.FieldCompletion)
+ }
+ if m.FieldCleared(record.FieldProgramLanguage) {
+ fields = append(fields, record.FieldProgramLanguage)
+ }
+ if m.FieldCleared(record.FieldWorkMode) {
+ fields = append(fields, record.FieldWorkMode)
+ }
+ if m.FieldCleared(record.FieldCodeLines) {
+ fields = append(fields, record.FieldCodeLines)
+ }
+ return fields
+}
+
+// FieldCleared returns a boolean indicating if a field with the given name was
+// cleared in this mutation.
+func (m *RecordMutation) 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 *RecordMutation) ClearField(name string) error {
+ switch name {
+ case record.FieldUserID:
+ m.ClearUserID()
+ return nil
+ case record.FieldModelID:
+ m.ClearModelID()
+ return nil
+ case record.FieldModelType:
+ m.ClearModelType()
+ return nil
+ case record.FieldPrompt:
+ m.ClearPrompt()
+ return nil
+ case record.FieldCompletion:
+ m.ClearCompletion()
+ return nil
+ case record.FieldProgramLanguage:
+ m.ClearProgramLanguage()
+ return nil
+ case record.FieldWorkMode:
+ m.ClearWorkMode()
+ return nil
+ case record.FieldCodeLines:
+ m.ClearCodeLines()
+ return nil
+ }
+ return fmt.Errorf("unknown Record 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 *RecordMutation) ResetField(name string) error {
+ switch name {
+ case record.FieldUserID:
+ m.ResetUserID()
+ return nil
+ case record.FieldModelID:
+ m.ResetModelID()
+ return nil
+ case record.FieldTaskID:
+ m.ResetTaskID()
+ return nil
+ case record.FieldModelType:
+ m.ResetModelType()
+ return nil
+ case record.FieldPrompt:
+ m.ResetPrompt()
+ return nil
+ case record.FieldCompletion:
+ m.ResetCompletion()
+ return nil
+ case record.FieldIsAccept:
+ m.ResetIsAccept()
+ return nil
+ case record.FieldProgramLanguage:
+ m.ResetProgramLanguage()
+ return nil
+ case record.FieldWorkMode:
+ m.ResetWorkMode()
+ return nil
+ case record.FieldCodeLines:
+ m.ResetCodeLines()
+ return nil
+ case record.FieldInputTokens:
+ m.ResetInputTokens()
+ return nil
+ case record.FieldOutputTokens:
+ m.ResetOutputTokens()
+ return nil
+ case record.FieldCreatedAt:
+ m.ResetCreatedAt()
+ return nil
+ case record.FieldUpdatedAt:
+ m.ResetUpdatedAt()
+ return nil
+ }
+ return fmt.Errorf("unknown Record field %s", name)
+}
+
+// AddedEdges returns all edge names that were set/added in this mutation.
+func (m *RecordMutation) AddedEdges() []string {
+ edges := make([]string, 0, 2)
+ if m.user != nil {
+ edges = append(edges, record.EdgeUser)
+ }
+ if m.model != nil {
+ edges = append(edges, record.EdgeModel)
+ }
+ return edges
+}
+
+// AddedIDs returns all IDs (to other nodes) that were added for the given edge
+// name in this mutation.
+func (m *RecordMutation) AddedIDs(name string) []ent.Value {
+ switch name {
+ case record.EdgeUser:
+ if id := m.user; id != nil {
+ return []ent.Value{*id}
+ }
+ case record.EdgeModel:
+ if id := m.model; id != nil {
+ return []ent.Value{*id}
+ }
+ }
+ return nil
+}
+
+// RemovedEdges returns all edge names that were removed in this mutation.
+func (m *RecordMutation) 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 *RecordMutation) RemovedIDs(name string) []ent.Value {
+ return nil
+}
+
+// ClearedEdges returns all edge names that were cleared in this mutation.
+func (m *RecordMutation) ClearedEdges() []string {
+ edges := make([]string, 0, 2)
+ if m.cleareduser {
+ edges = append(edges, record.EdgeUser)
+ }
+ if m.clearedmodel {
+ edges = append(edges, record.EdgeModel)
+ }
+ return edges
+}
+
+// EdgeCleared returns a boolean which indicates if the edge with the given name
+// was cleared in this mutation.
+func (m *RecordMutation) EdgeCleared(name string) bool {
+ switch name {
+ case record.EdgeUser:
+ return m.cleareduser
+ case record.EdgeModel:
+ return m.clearedmodel
+ }
+ 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 *RecordMutation) ClearEdge(name string) error {
+ switch name {
+ case record.EdgeUser:
+ m.ClearUser()
+ return nil
+ case record.EdgeModel:
+ m.ClearModel()
+ return nil
+ }
+ return fmt.Errorf("unknown Record 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 *RecordMutation) ResetEdge(name string) error {
+ switch name {
+ case record.EdgeUser:
+ m.ResetUser()
+ return nil
+ case record.EdgeModel:
+ m.ResetModel()
+ return nil
+ }
+ return fmt.Errorf("unknown Record edge %s", name)
+}
+
+// SettingMutation represents an operation that mutates the Setting nodes in the graph.
+type SettingMutation struct {
+ config
+ op Op
+ typ string
+ id *uuid.UUID
+ enable_sso *bool
+ force_two_factor_auth *bool
+ disable_password_login *bool
+ created_at *time.Time
+ updated_at *time.Time
+ clearedFields map[string]struct{}
+ done bool
+ oldValue func(context.Context) (*Setting, error)
+ predicates []predicate.Setting
+}
+
+var _ ent.Mutation = (*SettingMutation)(nil)
+
+// settingOption allows management of the mutation configuration using functional options.
+type settingOption func(*SettingMutation)
+
+// newSettingMutation creates new mutation for the Setting entity.
+func newSettingMutation(c config, op Op, opts ...settingOption) *SettingMutation {
+ m := &SettingMutation{
+ config: c,
+ op: op,
+ typ: TypeSetting,
+ clearedFields: make(map[string]struct{}),
+ }
+ for _, opt := range opts {
+ opt(m)
+ }
+ return m
+}
+
+// withSettingID sets the ID field of the mutation.
+func withSettingID(id uuid.UUID) settingOption {
+ return func(m *SettingMutation) {
+ var (
+ err error
+ once sync.Once
+ value *Setting
+ )
+ m.oldValue = func(ctx context.Context) (*Setting, error) {
+ once.Do(func() {
+ if m.done {
+ err = errors.New("querying old values post mutation is not allowed")
+ } else {
+ value, err = m.Client().Setting.Get(ctx, id)
+ }
+ })
+ return value, err
+ }
+ m.id = &id
+ }
+}
+
+// withSetting sets the old Setting of the mutation.
+func withSetting(node *Setting) settingOption {
+ return func(m *SettingMutation) {
+ m.oldValue = func(context.Context) (*Setting, 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 SettingMutation) 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 SettingMutation) Tx() (*Tx, error) {
+ if _, ok := m.driver.(*txDriver); !ok {
+ return nil, errors.New("db: mutation is not running in a transaction")
+ }
+ tx := &Tx{config: m.config}
+ tx.init()
+ return tx, nil
+}
+
+// SetID sets the value of the id field. Note that this
+// operation is only accepted on creation of Setting entities.
+func (m *SettingMutation) SetID(id uuid.UUID) {
+ m.id = &id
+}
+
+// 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 *SettingMutation) ID() (id uuid.UUID, 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 *SettingMutation) IDs(ctx context.Context) ([]uuid.UUID, error) {
+ switch {
+ case m.op.Is(OpUpdateOne | OpDeleteOne):
+ id, exists := m.ID()
+ if exists {
+ return []uuid.UUID{id}, nil
+ }
+ fallthrough
+ case m.op.Is(OpUpdate | OpDelete):
+ return m.Client().Setting.Query().Where(m.predicates...).IDs(ctx)
+ default:
+ return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op)
+ }
+}
+
+// SetEnableSSO sets the "enable_sso" field.
+func (m *SettingMutation) SetEnableSSO(b bool) {
+ m.enable_sso = &b
+}
+
+// EnableSSO returns the value of the "enable_sso" field in the mutation.
+func (m *SettingMutation) EnableSSO() (r bool, exists bool) {
+ v := m.enable_sso
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldEnableSSO returns the old "enable_sso" field's value of the Setting entity.
+// If the Setting 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 *SettingMutation) OldEnableSSO(ctx context.Context) (v bool, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldEnableSSO is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldEnableSSO requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldEnableSSO: %w", err)
+ }
+ return oldValue.EnableSSO, nil
+}
+
+// ResetEnableSSO resets all changes to the "enable_sso" field.
+func (m *SettingMutation) ResetEnableSSO() {
+ m.enable_sso = nil
+}
+
+// SetForceTwoFactorAuth sets the "force_two_factor_auth" field.
+func (m *SettingMutation) SetForceTwoFactorAuth(b bool) {
+ m.force_two_factor_auth = &b
+}
+
+// ForceTwoFactorAuth returns the value of the "force_two_factor_auth" field in the mutation.
+func (m *SettingMutation) ForceTwoFactorAuth() (r bool, exists bool) {
+ v := m.force_two_factor_auth
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldForceTwoFactorAuth returns the old "force_two_factor_auth" field's value of the Setting entity.
+// If the Setting 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 *SettingMutation) OldForceTwoFactorAuth(ctx context.Context) (v bool, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldForceTwoFactorAuth is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldForceTwoFactorAuth requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldForceTwoFactorAuth: %w", err)
+ }
+ return oldValue.ForceTwoFactorAuth, nil
+}
+
+// ResetForceTwoFactorAuth resets all changes to the "force_two_factor_auth" field.
+func (m *SettingMutation) ResetForceTwoFactorAuth() {
+ m.force_two_factor_auth = nil
+}
+
+// SetDisablePasswordLogin sets the "disable_password_login" field.
+func (m *SettingMutation) SetDisablePasswordLogin(b bool) {
+ m.disable_password_login = &b
+}
+
+// DisablePasswordLogin returns the value of the "disable_password_login" field in the mutation.
+func (m *SettingMutation) DisablePasswordLogin() (r bool, exists bool) {
+ v := m.disable_password_login
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldDisablePasswordLogin returns the old "disable_password_login" field's value of the Setting entity.
+// If the Setting 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 *SettingMutation) OldDisablePasswordLogin(ctx context.Context) (v bool, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldDisablePasswordLogin is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldDisablePasswordLogin requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldDisablePasswordLogin: %w", err)
+ }
+ return oldValue.DisablePasswordLogin, nil
+}
+
+// ResetDisablePasswordLogin resets all changes to the "disable_password_login" field.
+func (m *SettingMutation) ResetDisablePasswordLogin() {
+ m.disable_password_login = nil
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (m *SettingMutation) SetCreatedAt(t time.Time) {
+ m.created_at = &t
+}
+
+// CreatedAt returns the value of the "created_at" field in the mutation.
+func (m *SettingMutation) 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 Setting entity.
+// If the Setting 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 *SettingMutation) 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 *SettingMutation) ResetCreatedAt() {
+ m.created_at = nil
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (m *SettingMutation) SetUpdatedAt(t time.Time) {
+ m.updated_at = &t
+}
+
+// UpdatedAt returns the value of the "updated_at" field in the mutation.
+func (m *SettingMutation) 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 Setting entity.
+// If the Setting 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 *SettingMutation) 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 *SettingMutation) ResetUpdatedAt() {
+ m.updated_at = nil
+}
+
+// Where appends a list predicates to the SettingMutation builder.
+func (m *SettingMutation) Where(ps ...predicate.Setting) {
+ m.predicates = append(m.predicates, ps...)
+}
+
+// WhereP appends storage-level predicates to the SettingMutation builder. Using this method,
+// users can use type-assertion to append predicates that do not depend on any generated package.
+func (m *SettingMutation) WhereP(ps ...func(*sql.Selector)) {
+ p := make([]predicate.Setting, len(ps))
+ for i := range ps {
+ p[i] = ps[i]
+ }
+ m.Where(p...)
+}
+
+// Op returns the operation name.
+func (m *SettingMutation) Op() Op {
+ return m.op
+}
+
+// SetOp allows setting the mutation operation.
+func (m *SettingMutation) SetOp(op Op) {
+ m.op = op
+}
+
+// Type returns the node type of this mutation (Setting).
+func (m *SettingMutation) 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 *SettingMutation) Fields() []string {
+ fields := make([]string, 0, 5)
+ if m.enable_sso != nil {
+ fields = append(fields, setting.FieldEnableSSO)
+ }
+ if m.force_two_factor_auth != nil {
+ fields = append(fields, setting.FieldForceTwoFactorAuth)
+ }
+ if m.disable_password_login != nil {
+ fields = append(fields, setting.FieldDisablePasswordLogin)
+ }
+ if m.created_at != nil {
+ fields = append(fields, setting.FieldCreatedAt)
+ }
+ if m.updated_at != nil {
+ fields = append(fields, setting.FieldUpdatedAt)
+ }
+ 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 *SettingMutation) Field(name string) (ent.Value, bool) {
+ switch name {
+ case setting.FieldEnableSSO:
+ return m.EnableSSO()
+ case setting.FieldForceTwoFactorAuth:
+ return m.ForceTwoFactorAuth()
+ case setting.FieldDisablePasswordLogin:
+ return m.DisablePasswordLogin()
+ case setting.FieldCreatedAt:
+ return m.CreatedAt()
+ case setting.FieldUpdatedAt:
+ return m.UpdatedAt()
+ }
+ 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 *SettingMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
+ switch name {
+ case setting.FieldEnableSSO:
+ return m.OldEnableSSO(ctx)
+ case setting.FieldForceTwoFactorAuth:
+ return m.OldForceTwoFactorAuth(ctx)
+ case setting.FieldDisablePasswordLogin:
+ return m.OldDisablePasswordLogin(ctx)
+ case setting.FieldCreatedAt:
+ return m.OldCreatedAt(ctx)
+ case setting.FieldUpdatedAt:
+ return m.OldUpdatedAt(ctx)
+ }
+ return nil, fmt.Errorf("unknown Setting 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 *SettingMutation) SetField(name string, value ent.Value) error {
+ switch name {
+ case setting.FieldEnableSSO:
+ v, ok := value.(bool)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetEnableSSO(v)
+ return nil
+ case setting.FieldForceTwoFactorAuth:
+ v, ok := value.(bool)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetForceTwoFactorAuth(v)
+ return nil
+ case setting.FieldDisablePasswordLogin:
+ v, ok := value.(bool)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetDisablePasswordLogin(v)
+ return nil
+ case setting.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 setting.FieldUpdatedAt:
+ v, ok := value.(time.Time)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetUpdatedAt(v)
+ return nil
+ }
+ return fmt.Errorf("unknown Setting field %s", name)
+}
+
+// AddedFields returns all numeric fields that were incremented/decremented during
+// this mutation.
+func (m *SettingMutation) AddedFields() []string {
+ return nil
+}
+
+// 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 *SettingMutation) AddedField(name string) (ent.Value, bool) {
+ 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 *SettingMutation) AddField(name string, value ent.Value) error {
+ switch name {
+ }
+ return fmt.Errorf("unknown Setting numeric field %s", name)
+}
+
+// ClearedFields returns all nullable fields that were cleared during this
+// mutation.
+func (m *SettingMutation) ClearedFields() []string {
+ return nil
+}
+
+// FieldCleared returns a boolean indicating if a field with the given name was
+// cleared in this mutation.
+func (m *SettingMutation) 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 *SettingMutation) ClearField(name string) error {
+ return fmt.Errorf("unknown Setting 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 *SettingMutation) ResetField(name string) error {
+ switch name {
+ case setting.FieldEnableSSO:
+ m.ResetEnableSSO()
+ return nil
+ case setting.FieldForceTwoFactorAuth:
+ m.ResetForceTwoFactorAuth()
+ return nil
+ case setting.FieldDisablePasswordLogin:
+ m.ResetDisablePasswordLogin()
+ return nil
+ case setting.FieldCreatedAt:
+ m.ResetCreatedAt()
+ return nil
+ case setting.FieldUpdatedAt:
+ m.ResetUpdatedAt()
+ return nil
+ }
+ return fmt.Errorf("unknown Setting field %s", name)
+}
+
+// AddedEdges returns all edge names that were set/added in this mutation.
+func (m *SettingMutation) AddedEdges() []string {
+ edges := make([]string, 0, 0)
+ return edges
+}
+
+// AddedIDs returns all IDs (to other nodes) that were added for the given edge
+// name in this mutation.
+func (m *SettingMutation) AddedIDs(name string) []ent.Value {
+ return nil
+}
+
+// RemovedEdges returns all edge names that were removed in this mutation.
+func (m *SettingMutation) RemovedEdges() []string {
+ edges := make([]string, 0, 0)
+ return edges
+}
+
+// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with
+// the given name in this mutation.
+func (m *SettingMutation) RemovedIDs(name string) []ent.Value {
+ return nil
+}
+
+// ClearedEdges returns all edge names that were cleared in this mutation.
+func (m *SettingMutation) ClearedEdges() []string {
+ edges := make([]string, 0, 0)
+ return edges
+}
+
+// EdgeCleared returns a boolean which indicates if the edge with the given name
+// was cleared in this mutation.
+func (m *SettingMutation) EdgeCleared(name string) bool {
+ return false
+}
+
+// ClearEdge clears the value of the edge with the given name. It returns an error
+// if that edge is not defined in the schema.
+func (m *SettingMutation) ClearEdge(name string) error {
+ return fmt.Errorf("unknown Setting 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 *SettingMutation) ResetEdge(name string) error {
+ return fmt.Errorf("unknown Setting edge %s", name)
+}
+
+// UserMutation represents an operation that mutates the User nodes in the graph.
+type UserMutation struct {
+ config
+ op Op
+ typ string
+ id *uuid.UUID
+ username *string
+ password *string
+ email *string
+ status *consts.UserStatus
+ created_at *time.Time
+ updated_at *time.Time
+ clearedFields map[string]struct{}
+ records map[uuid.UUID]struct{}
+ removedrecords map[uuid.UUID]struct{}
+ clearedrecords bool
+ login_histories map[uuid.UUID]struct{}
+ removedlogin_histories map[uuid.UUID]struct{}
+ clearedlogin_histories bool
+ models map[uuid.UUID]struct{}
+ removedmodels map[uuid.UUID]struct{}
+ clearedmodels bool
+ done bool
+ oldValue func(context.Context) (*User, error)
+ predicates []predicate.User
+}
+
+var _ ent.Mutation = (*UserMutation)(nil)
+
+// userOption allows management of the mutation configuration using functional options.
+type userOption func(*UserMutation)
+
+// newUserMutation creates new mutation for the User entity.
+func newUserMutation(c config, op Op, opts ...userOption) *UserMutation {
+ m := &UserMutation{
+ config: c,
+ op: op,
+ typ: TypeUser,
+ clearedFields: make(map[string]struct{}),
+ }
+ for _, opt := range opts {
+ opt(m)
+ }
+ return m
+}
+
+// withUserID sets the ID field of the mutation.
+func withUserID(id uuid.UUID) userOption {
+ return func(m *UserMutation) {
+ var (
+ err error
+ once sync.Once
+ value *User
+ )
+ m.oldValue = func(ctx context.Context) (*User, error) {
+ once.Do(func() {
+ if m.done {
+ err = errors.New("querying old values post mutation is not allowed")
+ } else {
+ value, err = m.Client().User.Get(ctx, id)
+ }
+ })
+ return value, err
+ }
+ m.id = &id
+ }
+}
+
+// withUser sets the old User of the mutation.
+func withUser(node *User) userOption {
+ return func(m *UserMutation) {
+ m.oldValue = func(context.Context) (*User, 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 UserMutation) 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 UserMutation) Tx() (*Tx, error) {
+ if _, ok := m.driver.(*txDriver); !ok {
+ return nil, errors.New("db: mutation is not running in a transaction")
+ }
+ tx := &Tx{config: m.config}
+ tx.init()
+ return tx, nil
+}
+
+// SetID sets the value of the id field. Note that this
+// operation is only accepted on creation of User entities.
+func (m *UserMutation) SetID(id uuid.UUID) {
+ m.id = &id
+}
+
+// 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 *UserMutation) ID() (id uuid.UUID, 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 *UserMutation) IDs(ctx context.Context) ([]uuid.UUID, error) {
+ switch {
+ case m.op.Is(OpUpdateOne | OpDeleteOne):
+ id, exists := m.ID()
+ if exists {
+ return []uuid.UUID{id}, nil
+ }
+ fallthrough
+ case m.op.Is(OpUpdate | OpDelete):
+ return m.Client().User.Query().Where(m.predicates...).IDs(ctx)
+ default:
+ return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op)
+ }
+}
+
+// SetUsername sets the "username" field.
+func (m *UserMutation) SetUsername(s string) {
+ m.username = &s
+}
+
+// Username returns the value of the "username" field in the mutation.
+func (m *UserMutation) Username() (r string, exists bool) {
+ v := m.username
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldUsername returns the old "username" 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) OldUsername(ctx context.Context) (v string, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldUsername is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldUsername requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldUsername: %w", err)
+ }
+ return oldValue.Username, nil
+}
+
+// ResetUsername resets all changes to the "username" field.
+func (m *UserMutation) ResetUsername() {
+ m.username = nil
+}
+
+// SetPassword sets the "password" field.
+func (m *UserMutation) SetPassword(s string) {
+ m.password = &s
+}
+
+// Password returns the value of the "password" field in the mutation.
+func (m *UserMutation) Password() (r string, exists bool) {
+ v := m.password
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldPassword returns the old "password" 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) OldPassword(ctx context.Context) (v string, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldPassword is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldPassword requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldPassword: %w", err)
+ }
+ return oldValue.Password, nil
+}
+
+// ResetPassword resets all changes to the "password" field.
+func (m *UserMutation) ResetPassword() {
+ m.password = nil
+}
+
+// SetEmail sets the "email" field.
+func (m *UserMutation) SetEmail(s string) {
+ m.email = &s
+}
+
+// Email returns the value of the "email" field in the mutation.
+func (m *UserMutation) Email() (r string, exists bool) {
+ v := m.email
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldEmail returns the old "email" 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) OldEmail(ctx context.Context) (v string, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldEmail is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldEmail requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldEmail: %w", err)
+ }
+ return oldValue.Email, nil
+}
+
+// ResetEmail resets all changes to the "email" field.
+func (m *UserMutation) ResetEmail() {
+ m.email = nil
+}
+
+// SetStatus sets the "status" field.
+func (m *UserMutation) SetStatus(cs consts.UserStatus) {
+ m.status = &cs
+}
+
+// Status returns the value of the "status" field in the mutation.
+func (m *UserMutation) Status() (r consts.UserStatus, exists bool) {
+ v := m.status
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldStatus returns the old "status" 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) OldStatus(ctx context.Context) (v consts.UserStatus, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldStatus is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldStatus requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldStatus: %w", err)
+ }
+ return oldValue.Status, nil
+}
+
+// ResetStatus resets all changes to the "status" field.
+func (m *UserMutation) ResetStatus() {
+ m.status = nil
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (m *UserMutation) SetCreatedAt(t time.Time) {
+ m.created_at = &t
+}
+
+// CreatedAt returns the value of the "created_at" field in the mutation.
+func (m *UserMutation) 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 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) 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 *UserMutation) ResetCreatedAt() {
+ m.created_at = nil
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (m *UserMutation) SetUpdatedAt(t time.Time) {
+ m.updated_at = &t
+}
+
+// UpdatedAt returns the value of the "updated_at" field in the mutation.
+func (m *UserMutation) 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 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) 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 *UserMutation) ResetUpdatedAt() {
+ m.updated_at = nil
+}
+
+// AddRecordIDs adds the "records" edge to the Record entity by ids.
+func (m *UserMutation) AddRecordIDs(ids ...uuid.UUID) {
+ if m.records == nil {
+ m.records = make(map[uuid.UUID]struct{})
+ }
+ for i := range ids {
+ m.records[ids[i]] = struct{}{}
+ }
+}
+
+// ClearRecords clears the "records" edge to the Record entity.
+func (m *UserMutation) ClearRecords() {
+ m.clearedrecords = true
+}
+
+// RecordsCleared reports if the "records" edge to the Record entity was cleared.
+func (m *UserMutation) RecordsCleared() bool {
+ return m.clearedrecords
+}
+
+// RemoveRecordIDs removes the "records" edge to the Record entity by IDs.
+func (m *UserMutation) RemoveRecordIDs(ids ...uuid.UUID) {
+ if m.removedrecords == nil {
+ m.removedrecords = make(map[uuid.UUID]struct{})
+ }
+ for i := range ids {
+ delete(m.records, ids[i])
+ m.removedrecords[ids[i]] = struct{}{}
+ }
+}
+
+// RemovedRecords returns the removed IDs of the "records" edge to the Record entity.
+func (m *UserMutation) RemovedRecordsIDs() (ids []uuid.UUID) {
+ for id := range m.removedrecords {
+ ids = append(ids, id)
+ }
+ return
+}
+
+// RecordsIDs returns the "records" edge IDs in the mutation.
+func (m *UserMutation) RecordsIDs() (ids []uuid.UUID) {
+ for id := range m.records {
+ ids = append(ids, id)
+ }
+ return
+}
+
+// ResetRecords resets all changes to the "records" edge.
+func (m *UserMutation) ResetRecords() {
+ m.records = nil
+ m.clearedrecords = false
+ m.removedrecords = nil
+}
+
+// AddLoginHistoryIDs adds the "login_histories" edge to the UserLoginHistory entity by ids.
+func (m *UserMutation) AddLoginHistoryIDs(ids ...uuid.UUID) {
+ if m.login_histories == nil {
+ m.login_histories = make(map[uuid.UUID]struct{})
+ }
+ for i := range ids {
+ m.login_histories[ids[i]] = struct{}{}
+ }
+}
+
+// ClearLoginHistories clears the "login_histories" edge to the UserLoginHistory entity.
+func (m *UserMutation) ClearLoginHistories() {
+ m.clearedlogin_histories = true
+}
+
+// LoginHistoriesCleared reports if the "login_histories" edge to the UserLoginHistory entity was cleared.
+func (m *UserMutation) LoginHistoriesCleared() bool {
+ return m.clearedlogin_histories
+}
+
+// RemoveLoginHistoryIDs removes the "login_histories" edge to the UserLoginHistory entity by IDs.
+func (m *UserMutation) RemoveLoginHistoryIDs(ids ...uuid.UUID) {
+ if m.removedlogin_histories == nil {
+ m.removedlogin_histories = make(map[uuid.UUID]struct{})
+ }
+ for i := range ids {
+ delete(m.login_histories, ids[i])
+ m.removedlogin_histories[ids[i]] = struct{}{}
+ }
+}
+
+// RemovedLoginHistories returns the removed IDs of the "login_histories" edge to the UserLoginHistory entity.
+func (m *UserMutation) RemovedLoginHistoriesIDs() (ids []uuid.UUID) {
+ for id := range m.removedlogin_histories {
+ ids = append(ids, id)
+ }
+ return
+}
+
+// LoginHistoriesIDs returns the "login_histories" edge IDs in the mutation.
+func (m *UserMutation) LoginHistoriesIDs() (ids []uuid.UUID) {
+ for id := range m.login_histories {
+ ids = append(ids, id)
+ }
+ return
+}
+
+// ResetLoginHistories resets all changes to the "login_histories" edge.
+func (m *UserMutation) ResetLoginHistories() {
+ m.login_histories = nil
+ m.clearedlogin_histories = false
+ m.removedlogin_histories = nil
+}
+
+// AddModelIDs adds the "models" edge to the Model entity by ids.
+func (m *UserMutation) AddModelIDs(ids ...uuid.UUID) {
+ if m.models == nil {
+ m.models = make(map[uuid.UUID]struct{})
+ }
+ for i := range ids {
+ m.models[ids[i]] = struct{}{}
+ }
+}
+
+// ClearModels clears the "models" edge to the Model entity.
+func (m *UserMutation) ClearModels() {
+ m.clearedmodels = true
+}
+
+// ModelsCleared reports if the "models" edge to the Model entity was cleared.
+func (m *UserMutation) ModelsCleared() bool {
+ return m.clearedmodels
+}
+
+// RemoveModelIDs removes the "models" edge to the Model entity by IDs.
+func (m *UserMutation) RemoveModelIDs(ids ...uuid.UUID) {
+ if m.removedmodels == nil {
+ m.removedmodels = make(map[uuid.UUID]struct{})
+ }
+ for i := range ids {
+ delete(m.models, ids[i])
+ m.removedmodels[ids[i]] = struct{}{}
+ }
+}
+
+// RemovedModels returns the removed IDs of the "models" edge to the Model entity.
+func (m *UserMutation) RemovedModelsIDs() (ids []uuid.UUID) {
+ for id := range m.removedmodels {
+ ids = append(ids, id)
+ }
+ return
+}
+
+// ModelsIDs returns the "models" edge IDs in the mutation.
+func (m *UserMutation) ModelsIDs() (ids []uuid.UUID) {
+ for id := range m.models {
+ ids = append(ids, id)
+ }
+ return
+}
+
+// ResetModels resets all changes to the "models" edge.
+func (m *UserMutation) ResetModels() {
+ m.models = nil
+ m.clearedmodels = false
+ m.removedmodels = nil
+}
+
+// Where appends a list predicates to the UserMutation builder.
+func (m *UserMutation) Where(ps ...predicate.User) {
+ m.predicates = append(m.predicates, ps...)
+}
+
+// WhereP appends storage-level predicates to the UserMutation builder. Using this method,
+// users can use type-assertion to append predicates that do not depend on any generated package.
+func (m *UserMutation) WhereP(ps ...func(*sql.Selector)) {
+ p := make([]predicate.User, len(ps))
+ for i := range ps {
+ p[i] = ps[i]
+ }
+ m.Where(p...)
+}
+
+// Op returns the operation name.
+func (m *UserMutation) Op() Op {
+ return m.op
+}
+
+// SetOp allows setting the mutation operation.
+func (m *UserMutation) SetOp(op Op) {
+ m.op = op
+}
+
+// Type returns the node type of this mutation (User).
+func (m *UserMutation) 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 *UserMutation) Fields() []string {
+ fields := make([]string, 0, 6)
+ if m.username != nil {
+ fields = append(fields, user.FieldUsername)
+ }
+ if m.password != nil {
+ fields = append(fields, user.FieldPassword)
+ }
+ if m.email != nil {
+ fields = append(fields, user.FieldEmail)
+ }
+ if m.status != nil {
+ fields = append(fields, user.FieldStatus)
+ }
+ if m.created_at != nil {
+ fields = append(fields, user.FieldCreatedAt)
+ }
+ if m.updated_at != nil {
+ fields = append(fields, user.FieldUpdatedAt)
+ }
+ 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 *UserMutation) Field(name string) (ent.Value, bool) {
+ switch name {
+ case user.FieldUsername:
+ return m.Username()
+ case user.FieldPassword:
+ return m.Password()
+ case user.FieldEmail:
+ return m.Email()
+ case user.FieldStatus:
+ return m.Status()
+ case user.FieldCreatedAt:
+ return m.CreatedAt()
+ case user.FieldUpdatedAt:
+ return m.UpdatedAt()
+ }
+ 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 *UserMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
+ switch name {
+ case user.FieldUsername:
+ return m.OldUsername(ctx)
+ case user.FieldPassword:
+ return m.OldPassword(ctx)
+ case user.FieldEmail:
+ return m.OldEmail(ctx)
+ case user.FieldStatus:
+ return m.OldStatus(ctx)
+ case user.FieldCreatedAt:
+ return m.OldCreatedAt(ctx)
+ case user.FieldUpdatedAt:
+ return m.OldUpdatedAt(ctx)
+ }
+ return nil, fmt.Errorf("unknown User 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 *UserMutation) SetField(name string, value ent.Value) error {
+ switch name {
+ case user.FieldUsername:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetUsername(v)
+ return nil
+ case user.FieldPassword:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetPassword(v)
+ return nil
+ case user.FieldEmail:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetEmail(v)
+ return nil
+ case user.FieldStatus:
+ v, ok := value.(consts.UserStatus)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetStatus(v)
+ return nil
+ case user.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 user.FieldUpdatedAt:
+ v, ok := value.(time.Time)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetUpdatedAt(v)
+ return nil
+ }
+ return fmt.Errorf("unknown User field %s", name)
+}
+
+// AddedFields returns all numeric fields that were incremented/decremented during
+// this mutation.
+func (m *UserMutation) AddedFields() []string {
+ return nil
+}
+
+// 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 *UserMutation) AddedField(name string) (ent.Value, bool) {
+ 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 *UserMutation) AddField(name string, value ent.Value) error {
+ switch name {
+ }
+ return fmt.Errorf("unknown User numeric field %s", name)
+}
+
+// ClearedFields returns all nullable fields that were cleared during this
+// mutation.
+func (m *UserMutation) ClearedFields() []string {
+ return nil
+}
+
+// FieldCleared returns a boolean indicating if a field with the given name was
+// cleared in this mutation.
+func (m *UserMutation) 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 *UserMutation) ClearField(name string) error {
+ return fmt.Errorf("unknown User 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 *UserMutation) ResetField(name string) error {
+ switch name {
+ case user.FieldUsername:
+ m.ResetUsername()
+ return nil
+ case user.FieldPassword:
+ m.ResetPassword()
+ return nil
+ case user.FieldEmail:
+ m.ResetEmail()
+ return nil
+ case user.FieldStatus:
+ m.ResetStatus()
+ return nil
+ case user.FieldCreatedAt:
+ m.ResetCreatedAt()
+ return nil
+ case user.FieldUpdatedAt:
+ m.ResetUpdatedAt()
+ return nil
+ }
+ return fmt.Errorf("unknown User field %s", name)
+}
+
+// AddedEdges returns all edge names that were set/added in this mutation.
+func (m *UserMutation) AddedEdges() []string {
+ edges := make([]string, 0, 3)
+ if m.records != nil {
+ edges = append(edges, user.EdgeRecords)
+ }
+ if m.login_histories != nil {
+ edges = append(edges, user.EdgeLoginHistories)
+ }
+ if m.models != nil {
+ edges = append(edges, user.EdgeModels)
+ }
+ return edges
+}
+
+// AddedIDs returns all IDs (to other nodes) that were added for the given edge
+// name in this mutation.
+func (m *UserMutation) AddedIDs(name string) []ent.Value {
+ switch name {
+ case user.EdgeRecords:
+ ids := make([]ent.Value, 0, len(m.records))
+ for id := range m.records {
+ ids = append(ids, id)
+ }
+ return ids
+ case user.EdgeLoginHistories:
+ ids := make([]ent.Value, 0, len(m.login_histories))
+ for id := range m.login_histories {
+ ids = append(ids, id)
+ }
+ return ids
+ case user.EdgeModels:
+ ids := make([]ent.Value, 0, len(m.models))
+ for id := range m.models {
+ ids = append(ids, id)
+ }
+ return ids
+ }
+ return nil
+}
+
+// RemovedEdges returns all edge names that were removed in this mutation.
+func (m *UserMutation) RemovedEdges() []string {
+ edges := make([]string, 0, 3)
+ if m.removedrecords != nil {
+ edges = append(edges, user.EdgeRecords)
+ }
+ if m.removedlogin_histories != nil {
+ edges = append(edges, user.EdgeLoginHistories)
+ }
+ if m.removedmodels != nil {
+ edges = append(edges, user.EdgeModels)
+ }
+ return edges
+}
+
+// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with
+// the given name in this mutation.
+func (m *UserMutation) RemovedIDs(name string) []ent.Value {
+ switch name {
+ case user.EdgeRecords:
+ ids := make([]ent.Value, 0, len(m.removedrecords))
+ for id := range m.removedrecords {
+ ids = append(ids, id)
+ }
+ return ids
+ case user.EdgeLoginHistories:
+ ids := make([]ent.Value, 0, len(m.removedlogin_histories))
+ for id := range m.removedlogin_histories {
+ ids = append(ids, id)
+ }
+ return ids
+ case user.EdgeModels:
+ ids := make([]ent.Value, 0, len(m.removedmodels))
+ for id := range m.removedmodels {
+ ids = append(ids, id)
+ }
+ return ids
+ }
+ return nil
+}
+
+// ClearedEdges returns all edge names that were cleared in this mutation.
+func (m *UserMutation) ClearedEdges() []string {
+ edges := make([]string, 0, 3)
+ if m.clearedrecords {
+ edges = append(edges, user.EdgeRecords)
+ }
+ if m.clearedlogin_histories {
+ edges = append(edges, user.EdgeLoginHistories)
+ }
+ if m.clearedmodels {
+ edges = append(edges, user.EdgeModels)
+ }
+ return edges
+}
+
+// EdgeCleared returns a boolean which indicates if the edge with the given name
+// was cleared in this mutation.
+func (m *UserMutation) EdgeCleared(name string) bool {
+ switch name {
+ case user.EdgeRecords:
+ return m.clearedrecords
+ case user.EdgeLoginHistories:
+ return m.clearedlogin_histories
+ case user.EdgeModels:
+ return m.clearedmodels
+ }
+ 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 *UserMutation) ClearEdge(name string) error {
+ switch name {
+ }
+ return fmt.Errorf("unknown User 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 *UserMutation) ResetEdge(name string) error {
+ switch name {
+ case user.EdgeRecords:
+ m.ResetRecords()
+ return nil
+ case user.EdgeLoginHistories:
+ m.ResetLoginHistories()
+ return nil
+ case user.EdgeModels:
+ m.ResetModels()
+ return nil
+ }
+ return fmt.Errorf("unknown User edge %s", name)
+}
+
+// UserLoginHistoryMutation represents an operation that mutates the UserLoginHistory nodes in the graph.
+type UserLoginHistoryMutation struct {
+ config
+ op Op
+ typ string
+ id *uuid.UUID
+ user_id *uuid.UUID
+ ip *string
+ country *string
+ province *string
+ city *string
+ isp *string
+ asn *string
+ client_version *string
+ device *string
+ created_at *time.Time
+ clearedFields map[string]struct{}
+ owner *uuid.UUID
+ clearedowner bool
+ done bool
+ oldValue func(context.Context) (*UserLoginHistory, error)
+ predicates []predicate.UserLoginHistory
+}
+
+var _ ent.Mutation = (*UserLoginHistoryMutation)(nil)
+
+// userloginhistoryOption allows management of the mutation configuration using functional options.
+type userloginhistoryOption func(*UserLoginHistoryMutation)
+
+// newUserLoginHistoryMutation creates new mutation for the UserLoginHistory entity.
+func newUserLoginHistoryMutation(c config, op Op, opts ...userloginhistoryOption) *UserLoginHistoryMutation {
+ m := &UserLoginHistoryMutation{
+ config: c,
+ op: op,
+ typ: TypeUserLoginHistory,
+ clearedFields: make(map[string]struct{}),
+ }
+ for _, opt := range opts {
+ opt(m)
+ }
+ return m
+}
+
+// withUserLoginHistoryID sets the ID field of the mutation.
+func withUserLoginHistoryID(id uuid.UUID) userloginhistoryOption {
+ return func(m *UserLoginHistoryMutation) {
+ var (
+ err error
+ once sync.Once
+ value *UserLoginHistory
+ )
+ m.oldValue = func(ctx context.Context) (*UserLoginHistory, error) {
+ once.Do(func() {
+ if m.done {
+ err = errors.New("querying old values post mutation is not allowed")
+ } else {
+ value, err = m.Client().UserLoginHistory.Get(ctx, id)
+ }
+ })
+ return value, err
+ }
+ m.id = &id
+ }
+}
+
+// withUserLoginHistory sets the old UserLoginHistory of the mutation.
+func withUserLoginHistory(node *UserLoginHistory) userloginhistoryOption {
+ return func(m *UserLoginHistoryMutation) {
+ m.oldValue = func(context.Context) (*UserLoginHistory, 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 UserLoginHistoryMutation) 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 UserLoginHistoryMutation) Tx() (*Tx, error) {
+ if _, ok := m.driver.(*txDriver); !ok {
+ return nil, errors.New("db: mutation is not running in a transaction")
+ }
+ tx := &Tx{config: m.config}
+ tx.init()
+ return tx, nil
+}
+
+// SetID sets the value of the id field. Note that this
+// operation is only accepted on creation of UserLoginHistory entities.
+func (m *UserLoginHistoryMutation) SetID(id uuid.UUID) {
+ m.id = &id
+}
+
+// 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 *UserLoginHistoryMutation) ID() (id uuid.UUID, 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 *UserLoginHistoryMutation) IDs(ctx context.Context) ([]uuid.UUID, error) {
+ switch {
+ case m.op.Is(OpUpdateOne | OpDeleteOne):
+ id, exists := m.ID()
+ if exists {
+ return []uuid.UUID{id}, nil
+ }
+ fallthrough
+ case m.op.Is(OpUpdate | OpDelete):
+ return m.Client().UserLoginHistory.Query().Where(m.predicates...).IDs(ctx)
+ default:
+ return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op)
+ }
+}
+
+// SetUserID sets the "user_id" field.
+func (m *UserLoginHistoryMutation) SetUserID(u uuid.UUID) {
+ m.user_id = &u
+}
+
+// UserID returns the value of the "user_id" field in the mutation.
+func (m *UserLoginHistoryMutation) UserID() (r uuid.UUID, exists bool) {
+ v := m.user_id
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldUserID returns the old "user_id" field's value of the UserLoginHistory entity.
+// If the UserLoginHistory 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 *UserLoginHistoryMutation) OldUserID(ctx context.Context) (v uuid.UUID, 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 *UserLoginHistoryMutation) ResetUserID() {
+ m.user_id = nil
+}
+
+// SetIP sets the "ip" field.
+func (m *UserLoginHistoryMutation) SetIP(s string) {
+ m.ip = &s
+}
+
+// IP returns the value of the "ip" field in the mutation.
+func (m *UserLoginHistoryMutation) IP() (r string, exists bool) {
+ v := m.ip
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldIP returns the old "ip" field's value of the UserLoginHistory entity.
+// If the UserLoginHistory 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 *UserLoginHistoryMutation) OldIP(ctx context.Context) (v string, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldIP is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldIP requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldIP: %w", err)
+ }
+ return oldValue.IP, nil
+}
+
+// ResetIP resets all changes to the "ip" field.
+func (m *UserLoginHistoryMutation) ResetIP() {
+ m.ip = nil
+}
+
+// SetCountry sets the "country" field.
+func (m *UserLoginHistoryMutation) SetCountry(s string) {
+ m.country = &s
+}
+
+// Country returns the value of the "country" field in the mutation.
+func (m *UserLoginHistoryMutation) Country() (r string, exists bool) {
+ v := m.country
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldCountry returns the old "country" field's value of the UserLoginHistory entity.
+// If the UserLoginHistory 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 *UserLoginHistoryMutation) OldCountry(ctx context.Context) (v string, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldCountry is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldCountry requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldCountry: %w", err)
+ }
+ return oldValue.Country, nil
+}
+
+// ResetCountry resets all changes to the "country" field.
+func (m *UserLoginHistoryMutation) ResetCountry() {
+ m.country = nil
+}
+
+// SetProvince sets the "province" field.
+func (m *UserLoginHistoryMutation) SetProvince(s string) {
+ m.province = &s
+}
+
+// Province returns the value of the "province" field in the mutation.
+func (m *UserLoginHistoryMutation) Province() (r string, exists bool) {
+ v := m.province
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldProvince returns the old "province" field's value of the UserLoginHistory entity.
+// If the UserLoginHistory 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 *UserLoginHistoryMutation) OldProvince(ctx context.Context) (v string, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldProvince is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldProvince requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldProvince: %w", err)
+ }
+ return oldValue.Province, nil
+}
+
+// ResetProvince resets all changes to the "province" field.
+func (m *UserLoginHistoryMutation) ResetProvince() {
+ m.province = nil
+}
+
+// SetCity sets the "city" field.
+func (m *UserLoginHistoryMutation) SetCity(s string) {
+ m.city = &s
+}
+
+// City returns the value of the "city" field in the mutation.
+func (m *UserLoginHistoryMutation) City() (r string, exists bool) {
+ v := m.city
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldCity returns the old "city" field's value of the UserLoginHistory entity.
+// If the UserLoginHistory 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 *UserLoginHistoryMutation) OldCity(ctx context.Context) (v string, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldCity is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldCity requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldCity: %w", err)
+ }
+ return oldValue.City, nil
+}
+
+// ResetCity resets all changes to the "city" field.
+func (m *UserLoginHistoryMutation) ResetCity() {
+ m.city = nil
+}
+
+// SetIsp sets the "isp" field.
+func (m *UserLoginHistoryMutation) SetIsp(s string) {
+ m.isp = &s
+}
+
+// Isp returns the value of the "isp" field in the mutation.
+func (m *UserLoginHistoryMutation) Isp() (r string, exists bool) {
+ v := m.isp
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldIsp returns the old "isp" field's value of the UserLoginHistory entity.
+// If the UserLoginHistory 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 *UserLoginHistoryMutation) OldIsp(ctx context.Context) (v string, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldIsp is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldIsp requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldIsp: %w", err)
+ }
+ return oldValue.Isp, nil
+}
+
+// ResetIsp resets all changes to the "isp" field.
+func (m *UserLoginHistoryMutation) ResetIsp() {
+ m.isp = nil
+}
+
+// SetAsn sets the "asn" field.
+func (m *UserLoginHistoryMutation) SetAsn(s string) {
+ m.asn = &s
+}
+
+// Asn returns the value of the "asn" field in the mutation.
+func (m *UserLoginHistoryMutation) Asn() (r string, exists bool) {
+ v := m.asn
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldAsn returns the old "asn" field's value of the UserLoginHistory entity.
+// If the UserLoginHistory 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 *UserLoginHistoryMutation) OldAsn(ctx context.Context) (v string, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldAsn is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldAsn requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldAsn: %w", err)
+ }
+ return oldValue.Asn, nil
+}
+
+// ResetAsn resets all changes to the "asn" field.
+func (m *UserLoginHistoryMutation) ResetAsn() {
+ m.asn = nil
+}
+
+// SetClientVersion sets the "client_version" field.
+func (m *UserLoginHistoryMutation) SetClientVersion(s string) {
+ m.client_version = &s
+}
+
+// ClientVersion returns the value of the "client_version" field in the mutation.
+func (m *UserLoginHistoryMutation) ClientVersion() (r string, exists bool) {
+ v := m.client_version
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldClientVersion returns the old "client_version" field's value of the UserLoginHistory entity.
+// If the UserLoginHistory 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 *UserLoginHistoryMutation) OldClientVersion(ctx context.Context) (v string, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldClientVersion is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldClientVersion requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldClientVersion: %w", err)
+ }
+ return oldValue.ClientVersion, nil
+}
+
+// ResetClientVersion resets all changes to the "client_version" field.
+func (m *UserLoginHistoryMutation) ResetClientVersion() {
+ m.client_version = nil
+}
+
+// SetDevice sets the "device" field.
+func (m *UserLoginHistoryMutation) SetDevice(s string) {
+ m.device = &s
+}
+
+// Device returns the value of the "device" field in the mutation.
+func (m *UserLoginHistoryMutation) Device() (r string, exists bool) {
+ v := m.device
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldDevice returns the old "device" field's value of the UserLoginHistory entity.
+// If the UserLoginHistory 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 *UserLoginHistoryMutation) OldDevice(ctx context.Context) (v string, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldDevice is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldDevice requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldDevice: %w", err)
+ }
+ return oldValue.Device, nil
+}
+
+// ResetDevice resets all changes to the "device" field.
+func (m *UserLoginHistoryMutation) ResetDevice() {
+ m.device = nil
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (m *UserLoginHistoryMutation) SetCreatedAt(t time.Time) {
+ m.created_at = &t
+}
+
+// CreatedAt returns the value of the "created_at" field in the mutation.
+func (m *UserLoginHistoryMutation) 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 UserLoginHistory entity.
+// If the UserLoginHistory 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 *UserLoginHistoryMutation) 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 *UserLoginHistoryMutation) ResetCreatedAt() {
+ m.created_at = nil
+}
+
+// SetOwnerID sets the "owner" edge to the User entity by id.
+func (m *UserLoginHistoryMutation) SetOwnerID(id uuid.UUID) {
+ m.owner = &id
+}
+
+// ClearOwner clears the "owner" edge to the User entity.
+func (m *UserLoginHistoryMutation) ClearOwner() {
+ m.clearedowner = true
+}
+
+// OwnerCleared reports if the "owner" edge to the User entity was cleared.
+func (m *UserLoginHistoryMutation) OwnerCleared() bool {
+ return m.clearedowner
+}
+
+// OwnerID returns the "owner" edge ID in the mutation.
+func (m *UserLoginHistoryMutation) OwnerID() (id uuid.UUID, exists bool) {
+ if m.owner != nil {
+ return *m.owner, true
+ }
+ return
+}
+
+// OwnerIDs returns the "owner" edge IDs in the mutation.
+// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use
+// OwnerID instead. It exists only for internal usage by the builders.
+func (m *UserLoginHistoryMutation) OwnerIDs() (ids []uuid.UUID) {
+ if id := m.owner; id != nil {
+ ids = append(ids, *id)
+ }
+ return
+}
+
+// ResetOwner resets all changes to the "owner" edge.
+func (m *UserLoginHistoryMutation) ResetOwner() {
+ m.owner = nil
+ m.clearedowner = false
+}
+
+// Where appends a list predicates to the UserLoginHistoryMutation builder.
+func (m *UserLoginHistoryMutation) Where(ps ...predicate.UserLoginHistory) {
+ m.predicates = append(m.predicates, ps...)
+}
+
+// WhereP appends storage-level predicates to the UserLoginHistoryMutation builder. Using this method,
+// users can use type-assertion to append predicates that do not depend on any generated package.
+func (m *UserLoginHistoryMutation) WhereP(ps ...func(*sql.Selector)) {
+ p := make([]predicate.UserLoginHistory, len(ps))
+ for i := range ps {
+ p[i] = ps[i]
+ }
+ m.Where(p...)
+}
+
+// Op returns the operation name.
+func (m *UserLoginHistoryMutation) Op() Op {
+ return m.op
+}
+
+// SetOp allows setting the mutation operation.
+func (m *UserLoginHistoryMutation) SetOp(op Op) {
+ m.op = op
+}
+
+// Type returns the node type of this mutation (UserLoginHistory).
+func (m *UserLoginHistoryMutation) 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 *UserLoginHistoryMutation) Fields() []string {
+ fields := make([]string, 0, 10)
+ if m.user_id != nil {
+ fields = append(fields, userloginhistory.FieldUserID)
+ }
+ if m.ip != nil {
+ fields = append(fields, userloginhistory.FieldIP)
+ }
+ if m.country != nil {
+ fields = append(fields, userloginhistory.FieldCountry)
+ }
+ if m.province != nil {
+ fields = append(fields, userloginhistory.FieldProvince)
+ }
+ if m.city != nil {
+ fields = append(fields, userloginhistory.FieldCity)
+ }
+ if m.isp != nil {
+ fields = append(fields, userloginhistory.FieldIsp)
+ }
+ if m.asn != nil {
+ fields = append(fields, userloginhistory.FieldAsn)
+ }
+ if m.client_version != nil {
+ fields = append(fields, userloginhistory.FieldClientVersion)
+ }
+ if m.device != nil {
+ fields = append(fields, userloginhistory.FieldDevice)
+ }
+ if m.created_at != nil {
+ fields = append(fields, userloginhistory.FieldCreatedAt)
+ }
+ 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 *UserLoginHistoryMutation) Field(name string) (ent.Value, bool) {
+ switch name {
+ case userloginhistory.FieldUserID:
+ return m.UserID()
+ case userloginhistory.FieldIP:
+ return m.IP()
+ case userloginhistory.FieldCountry:
+ return m.Country()
+ case userloginhistory.FieldProvince:
+ return m.Province()
+ case userloginhistory.FieldCity:
+ return m.City()
+ case userloginhistory.FieldIsp:
+ return m.Isp()
+ case userloginhistory.FieldAsn:
+ return m.Asn()
+ case userloginhistory.FieldClientVersion:
+ return m.ClientVersion()
+ case userloginhistory.FieldDevice:
+ return m.Device()
+ case userloginhistory.FieldCreatedAt:
+ return m.CreatedAt()
+ }
+ 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 *UserLoginHistoryMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
+ switch name {
+ case userloginhistory.FieldUserID:
+ return m.OldUserID(ctx)
+ case userloginhistory.FieldIP:
+ return m.OldIP(ctx)
+ case userloginhistory.FieldCountry:
+ return m.OldCountry(ctx)
+ case userloginhistory.FieldProvince:
+ return m.OldProvince(ctx)
+ case userloginhistory.FieldCity:
+ return m.OldCity(ctx)
+ case userloginhistory.FieldIsp:
+ return m.OldIsp(ctx)
+ case userloginhistory.FieldAsn:
+ return m.OldAsn(ctx)
+ case userloginhistory.FieldClientVersion:
+ return m.OldClientVersion(ctx)
+ case userloginhistory.FieldDevice:
+ return m.OldDevice(ctx)
+ case userloginhistory.FieldCreatedAt:
+ return m.OldCreatedAt(ctx)
+ }
+ return nil, fmt.Errorf("unknown UserLoginHistory 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 *UserLoginHistoryMutation) SetField(name string, value ent.Value) error {
+ switch name {
+ case userloginhistory.FieldUserID:
+ v, ok := value.(uuid.UUID)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetUserID(v)
+ return nil
+ case userloginhistory.FieldIP:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetIP(v)
+ return nil
+ case userloginhistory.FieldCountry:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetCountry(v)
+ return nil
+ case userloginhistory.FieldProvince:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetProvince(v)
+ return nil
+ case userloginhistory.FieldCity:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetCity(v)
+ return nil
+ case userloginhistory.FieldIsp:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetIsp(v)
+ return nil
+ case userloginhistory.FieldAsn:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetAsn(v)
+ return nil
+ case userloginhistory.FieldClientVersion:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetClientVersion(v)
+ return nil
+ case userloginhistory.FieldDevice:
+ v, ok := value.(string)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetDevice(v)
+ return nil
+ case userloginhistory.FieldCreatedAt:
+ v, ok := value.(time.Time)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetCreatedAt(v)
+ return nil
+ }
+ return fmt.Errorf("unknown UserLoginHistory field %s", name)
+}
+
+// AddedFields returns all numeric fields that were incremented/decremented during
+// this mutation.
+func (m *UserLoginHistoryMutation) AddedFields() []string {
+ return nil
+}
+
+// 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 *UserLoginHistoryMutation) AddedField(name string) (ent.Value, bool) {
+ 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 *UserLoginHistoryMutation) AddField(name string, value ent.Value) error {
+ switch name {
+ }
+ return fmt.Errorf("unknown UserLoginHistory numeric field %s", name)
+}
+
+// ClearedFields returns all nullable fields that were cleared during this
+// mutation.
+func (m *UserLoginHistoryMutation) ClearedFields() []string {
+ return nil
+}
+
+// FieldCleared returns a boolean indicating if a field with the given name was
+// cleared in this mutation.
+func (m *UserLoginHistoryMutation) 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 *UserLoginHistoryMutation) ClearField(name string) error {
+ return fmt.Errorf("unknown UserLoginHistory 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 *UserLoginHistoryMutation) ResetField(name string) error {
+ switch name {
+ case userloginhistory.FieldUserID:
+ m.ResetUserID()
+ return nil
+ case userloginhistory.FieldIP:
+ m.ResetIP()
+ return nil
+ case userloginhistory.FieldCountry:
+ m.ResetCountry()
+ return nil
+ case userloginhistory.FieldProvince:
+ m.ResetProvince()
+ return nil
+ case userloginhistory.FieldCity:
+ m.ResetCity()
+ return nil
+ case userloginhistory.FieldIsp:
+ m.ResetIsp()
+ return nil
+ case userloginhistory.FieldAsn:
+ m.ResetAsn()
+ return nil
+ case userloginhistory.FieldClientVersion:
+ m.ResetClientVersion()
+ return nil
+ case userloginhistory.FieldDevice:
+ m.ResetDevice()
+ return nil
+ case userloginhistory.FieldCreatedAt:
+ m.ResetCreatedAt()
+ return nil
+ }
+ return fmt.Errorf("unknown UserLoginHistory field %s", name)
+}
+
+// AddedEdges returns all edge names that were set/added in this mutation.
+func (m *UserLoginHistoryMutation) AddedEdges() []string {
+ edges := make([]string, 0, 1)
+ if m.owner != nil {
+ edges = append(edges, userloginhistory.EdgeOwner)
+ }
+ return edges
+}
+
+// AddedIDs returns all IDs (to other nodes) that were added for the given edge
+// name in this mutation.
+func (m *UserLoginHistoryMutation) AddedIDs(name string) []ent.Value {
+ switch name {
+ case userloginhistory.EdgeOwner:
+ if id := m.owner; id != nil {
+ return []ent.Value{*id}
+ }
+ }
+ return nil
+}
+
+// RemovedEdges returns all edge names that were removed in this mutation.
+func (m *UserLoginHistoryMutation) RemovedEdges() []string {
+ edges := make([]string, 0, 1)
+ return edges
+}
+
+// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with
+// the given name in this mutation.
+func (m *UserLoginHistoryMutation) RemovedIDs(name string) []ent.Value {
+ return nil
+}
+
+// ClearedEdges returns all edge names that were cleared in this mutation.
+func (m *UserLoginHistoryMutation) ClearedEdges() []string {
+ edges := make([]string, 0, 1)
+ if m.clearedowner {
+ edges = append(edges, userloginhistory.EdgeOwner)
+ }
+ return edges
+}
+
+// EdgeCleared returns a boolean which indicates if the edge with the given name
+// was cleared in this mutation.
+func (m *UserLoginHistoryMutation) EdgeCleared(name string) bool {
+ switch name {
+ case userloginhistory.EdgeOwner:
+ return m.clearedowner
+ }
+ 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 *UserLoginHistoryMutation) ClearEdge(name string) error {
+ switch name {
+ case userloginhistory.EdgeOwner:
+ m.ClearOwner()
+ return nil
+ }
+ return fmt.Errorf("unknown UserLoginHistory 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 *UserLoginHistoryMutation) ResetEdge(name string) error {
+ switch name {
+ case userloginhistory.EdgeOwner:
+ m.ResetOwner()
+ return nil
+ }
+ return fmt.Errorf("unknown UserLoginHistory edge %s", name)
+}
diff --git a/backend/db/page.go b/backend/db/page.go
new file mode 100644
index 0000000..345a744
--- /dev/null
+++ b/backend/db/page.go
@@ -0,0 +1,194 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import "context"
+
+// PageInfo 分页信息
+type PageInfo struct {
+ NextToken string `json:"next_token,omitempty"`
+ HasNextPage bool `json:"has_next_page"`
+ TotalCount int64 `json:"total_count"`
+}
+
+func (a *AdminQuery) Page(ctx context.Context, page, size int) ([]*Admin, *PageInfo, error) {
+ cnt, err := a.Count(ctx)
+ if err != nil {
+ return nil, nil, err
+ }
+ offset := size * (page - 1)
+ rs, err := a.Offset(offset).Limit(size).All(ctx)
+ if err != nil {
+ return nil, nil, err
+ }
+ has := (page * size) < cnt
+ return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil
+}
+
+func (alh *AdminLoginHistoryQuery) Page(ctx context.Context, page, size int) ([]*AdminLoginHistory, *PageInfo, error) {
+ cnt, err := alh.Count(ctx)
+ if err != nil {
+ return nil, nil, err
+ }
+ offset := size * (page - 1)
+ rs, err := alh.Offset(offset).Limit(size).All(ctx)
+ if err != nil {
+ return nil, nil, err
+ }
+ has := (page * size) < cnt
+ return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil
+}
+
+func (ak *ApiKeyQuery) Page(ctx context.Context, page, size int) ([]*ApiKey, *PageInfo, error) {
+ cnt, err := ak.Count(ctx)
+ if err != nil {
+ return nil, nil, err
+ }
+ offset := size * (page - 1)
+ rs, err := ak.Offset(offset).Limit(size).All(ctx)
+ if err != nil {
+ return nil, nil, err
+ }
+ has := (page * size) < cnt
+ return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil
+}
+
+func (bp *BillingPlanQuery) Page(ctx context.Context, page, size int) ([]*BillingPlan, *PageInfo, error) {
+ cnt, err := bp.Count(ctx)
+ if err != nil {
+ return nil, nil, err
+ }
+ offset := size * (page - 1)
+ rs, err := bp.Offset(offset).Limit(size).All(ctx)
+ if err != nil {
+ return nil, nil, err
+ }
+ has := (page * size) < cnt
+ return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil
+}
+
+func (bq *BillingQuotaQuery) Page(ctx context.Context, page, size int) ([]*BillingQuota, *PageInfo, error) {
+ cnt, err := bq.Count(ctx)
+ if err != nil {
+ return nil, nil, err
+ }
+ offset := size * (page - 1)
+ rs, err := bq.Offset(offset).Limit(size).All(ctx)
+ if err != nil {
+ return nil, nil, err
+ }
+ has := (page * size) < cnt
+ return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil
+}
+
+func (br *BillingRecordQuery) Page(ctx context.Context, page, size int) ([]*BillingRecord, *PageInfo, error) {
+ cnt, err := br.Count(ctx)
+ if err != nil {
+ return nil, nil, err
+ }
+ offset := size * (page - 1)
+ rs, err := br.Offset(offset).Limit(size).All(ctx)
+ if err != nil {
+ return nil, nil, err
+ }
+ has := (page * size) < cnt
+ return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil
+}
+
+func (bu *BillingUsageQuery) Page(ctx context.Context, page, size int) ([]*BillingUsage, *PageInfo, error) {
+ cnt, err := bu.Count(ctx)
+ if err != nil {
+ return nil, nil, err
+ }
+ offset := size * (page - 1)
+ rs, err := bu.Offset(offset).Limit(size).All(ctx)
+ if err != nil {
+ return nil, nil, err
+ }
+ has := (page * size) < cnt
+ return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil
+}
+
+func (ic *InviteCodeQuery) Page(ctx context.Context, page, size int) ([]*InviteCode, *PageInfo, error) {
+ cnt, err := ic.Count(ctx)
+ if err != nil {
+ return nil, nil, err
+ }
+ offset := size * (page - 1)
+ rs, err := ic.Offset(offset).Limit(size).All(ctx)
+ if err != nil {
+ return nil, nil, err
+ }
+ has := (page * size) < cnt
+ return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil
+}
+
+func (m *ModelQuery) Page(ctx context.Context, page, size int) ([]*Model, *PageInfo, error) {
+ cnt, err := m.Count(ctx)
+ if err != nil {
+ return nil, nil, err
+ }
+ offset := size * (page - 1)
+ rs, err := m.Offset(offset).Limit(size).All(ctx)
+ if err != nil {
+ return nil, nil, err
+ }
+ has := (page * size) < cnt
+ return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil
+}
+
+func (r *RecordQuery) Page(ctx context.Context, page, size int) ([]*Record, *PageInfo, error) {
+ cnt, err := r.Count(ctx)
+ if err != nil {
+ return nil, nil, err
+ }
+ offset := size * (page - 1)
+ rs, err := r.Offset(offset).Limit(size).All(ctx)
+ if err != nil {
+ return nil, nil, err
+ }
+ has := (page * size) < cnt
+ return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil
+}
+
+func (s *SettingQuery) Page(ctx context.Context, page, size int) ([]*Setting, *PageInfo, error) {
+ cnt, err := s.Count(ctx)
+ if err != nil {
+ return nil, nil, err
+ }
+ offset := size * (page - 1)
+ rs, err := s.Offset(offset).Limit(size).All(ctx)
+ if err != nil {
+ return nil, nil, err
+ }
+ has := (page * size) < cnt
+ return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil
+}
+
+func (u *UserQuery) Page(ctx context.Context, page, size int) ([]*User, *PageInfo, error) {
+ cnt, err := u.Count(ctx)
+ if err != nil {
+ return nil, nil, err
+ }
+ offset := size * (page - 1)
+ rs, err := u.Offset(offset).Limit(size).All(ctx)
+ if err != nil {
+ return nil, nil, err
+ }
+ has := (page * size) < cnt
+ return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil
+}
+
+func (ulh *UserLoginHistoryQuery) Page(ctx context.Context, page, size int) ([]*UserLoginHistory, *PageInfo, error) {
+ cnt, err := ulh.Count(ctx)
+ if err != nil {
+ return nil, nil, err
+ }
+ offset := size * (page - 1)
+ rs, err := ulh.Offset(offset).Limit(size).All(ctx)
+ if err != nil {
+ return nil, nil, err
+ }
+ has := (page * size) < cnt
+ return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil
+}
diff --git a/backend/db/predicate/predicate.go b/backend/db/predicate/predicate.go
new file mode 100644
index 0000000..82b46a8
--- /dev/null
+++ b/backend/db/predicate/predicate.go
@@ -0,0 +1,46 @@
+// Code generated by ent, DO NOT EDIT.
+
+package predicate
+
+import (
+ "entgo.io/ent/dialect/sql"
+)
+
+// Admin is the predicate function for admin builders.
+type Admin func(*sql.Selector)
+
+// AdminLoginHistory is the predicate function for adminloginhistory builders.
+type AdminLoginHistory func(*sql.Selector)
+
+// ApiKey is the predicate function for apikey builders.
+type ApiKey func(*sql.Selector)
+
+// BillingPlan is the predicate function for billingplan builders.
+type BillingPlan func(*sql.Selector)
+
+// BillingQuota is the predicate function for billingquota builders.
+type BillingQuota func(*sql.Selector)
+
+// BillingRecord is the predicate function for billingrecord builders.
+type BillingRecord func(*sql.Selector)
+
+// BillingUsage is the predicate function for billingusage builders.
+type BillingUsage func(*sql.Selector)
+
+// InviteCode is the predicate function for invitecode builders.
+type InviteCode func(*sql.Selector)
+
+// Model is the predicate function for model builders.
+type Model func(*sql.Selector)
+
+// Record is the predicate function for record builders.
+type Record func(*sql.Selector)
+
+// Setting is the predicate function for setting builders.
+type Setting func(*sql.Selector)
+
+// User is the predicate function for user builders.
+type User func(*sql.Selector)
+
+// UserLoginHistory is the predicate function for userloginhistory builders.
+type UserLoginHistory func(*sql.Selector)
diff --git a/backend/db/record.go b/backend/db/record.go
new file mode 100644
index 0000000..b296370
--- /dev/null
+++ b/backend/db/record.go
@@ -0,0 +1,303 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "fmt"
+ "strings"
+ "time"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect/sql"
+ "github.com/chaitin/MonkeyCode/backend/consts"
+ "github.com/chaitin/MonkeyCode/backend/db/model"
+ "github.com/chaitin/MonkeyCode/backend/db/record"
+ "github.com/chaitin/MonkeyCode/backend/db/user"
+ "github.com/google/uuid"
+)
+
+// Record is the model entity for the Record schema.
+type Record struct {
+ config `json:"-"`
+ // ID of the ent.
+ ID uuid.UUID `json:"id,omitempty"`
+ // UserID holds the value of the "user_id" field.
+ UserID uuid.UUID `json:"user_id,omitempty"`
+ // ModelID holds the value of the "model_id" field.
+ ModelID uuid.UUID `json:"model_id,omitempty"`
+ // TaskID holds the value of the "task_id" field.
+ TaskID string `json:"task_id,omitempty"`
+ // ModelType holds the value of the "model_type" field.
+ ModelType consts.ModelType `json:"model_type,omitempty"`
+ // Prompt holds the value of the "prompt" field.
+ Prompt string `json:"prompt,omitempty"`
+ // Completion holds the value of the "completion" field.
+ Completion string `json:"completion,omitempty"`
+ // IsAccept holds the value of the "is_accept" field.
+ IsAccept bool `json:"is_accept,omitempty"`
+ // ProgramLanguage holds the value of the "program_language" field.
+ ProgramLanguage string `json:"program_language,omitempty"`
+ // WorkMode holds the value of the "work_mode" field.
+ WorkMode string `json:"work_mode,omitempty"`
+ // CodeLines holds the value of the "code_lines" field.
+ CodeLines int64 `json:"code_lines,omitempty"`
+ // InputTokens holds the value of the "input_tokens" field.
+ InputTokens int64 `json:"input_tokens,omitempty"`
+ // OutputTokens holds the value of the "output_tokens" field.
+ OutputTokens int64 `json:"output_tokens,omitempty"`
+ // CreatedAt holds the value of the "created_at" field.
+ CreatedAt time.Time `json:"created_at,omitempty"`
+ // UpdatedAt holds the value of the "updated_at" field.
+ UpdatedAt time.Time `json:"updated_at,omitempty"`
+ // Edges holds the relations/edges for other nodes in the graph.
+ // The values are being populated by the RecordQuery when eager-loading is set.
+ Edges RecordEdges `json:"edges"`
+ selectValues sql.SelectValues
+}
+
+// RecordEdges holds the relations/edges for other nodes in the graph.
+type RecordEdges struct {
+ // User holds the value of the user edge.
+ User *User `json:"user,omitempty"`
+ // Model holds the value of the model edge.
+ Model *Model `json:"model,omitempty"`
+ // loadedTypes holds the information for reporting if a
+ // type was loaded (or requested) in eager-loading or not.
+ loadedTypes [2]bool
+}
+
+// UserOrErr returns the User value or an error if the edge
+// was not loaded in eager-loading, or loaded but was not found.
+func (e RecordEdges) UserOrErr() (*User, error) {
+ if e.User != nil {
+ return e.User, nil
+ } else if e.loadedTypes[0] {
+ return nil, &NotFoundError{label: user.Label}
+ }
+ return nil, &NotLoadedError{edge: "user"}
+}
+
+// ModelOrErr returns the Model value or an error if the edge
+// was not loaded in eager-loading, or loaded but was not found.
+func (e RecordEdges) ModelOrErr() (*Model, error) {
+ if e.Model != nil {
+ return e.Model, nil
+ } else if e.loadedTypes[1] {
+ return nil, &NotFoundError{label: model.Label}
+ }
+ return nil, &NotLoadedError{edge: "model"}
+}
+
+// scanValues returns the types for scanning values from sql.Rows.
+func (*Record) scanValues(columns []string) ([]any, error) {
+ values := make([]any, len(columns))
+ for i := range columns {
+ switch columns[i] {
+ case record.FieldIsAccept:
+ values[i] = new(sql.NullBool)
+ case record.FieldCodeLines, record.FieldInputTokens, record.FieldOutputTokens:
+ values[i] = new(sql.NullInt64)
+ case record.FieldTaskID, record.FieldModelType, record.FieldPrompt, record.FieldCompletion, record.FieldProgramLanguage, record.FieldWorkMode:
+ values[i] = new(sql.NullString)
+ case record.FieldCreatedAt, record.FieldUpdatedAt:
+ values[i] = new(sql.NullTime)
+ case record.FieldID, record.FieldUserID, record.FieldModelID:
+ values[i] = new(uuid.UUID)
+ default:
+ values[i] = new(sql.UnknownType)
+ }
+ }
+ return values, nil
+}
+
+// assignValues assigns the values that were returned from sql.Rows (after scanning)
+// to the Record fields.
+func (r *Record) assignValues(columns []string, values []any) error {
+ if m, n := len(values), len(columns); m < n {
+ return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
+ }
+ for i := range columns {
+ switch columns[i] {
+ case record.FieldID:
+ if value, ok := values[i].(*uuid.UUID); !ok {
+ return fmt.Errorf("unexpected type %T for field id", values[i])
+ } else if value != nil {
+ r.ID = *value
+ }
+ case record.FieldUserID:
+ if value, ok := values[i].(*uuid.UUID); !ok {
+ return fmt.Errorf("unexpected type %T for field user_id", values[i])
+ } else if value != nil {
+ r.UserID = *value
+ }
+ case record.FieldModelID:
+ if value, ok := values[i].(*uuid.UUID); !ok {
+ return fmt.Errorf("unexpected type %T for field model_id", values[i])
+ } else if value != nil {
+ r.ModelID = *value
+ }
+ case record.FieldTaskID:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field task_id", values[i])
+ } else if value.Valid {
+ r.TaskID = value.String
+ }
+ case record.FieldModelType:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field model_type", values[i])
+ } else if value.Valid {
+ r.ModelType = consts.ModelType(value.String)
+ }
+ case record.FieldPrompt:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field prompt", values[i])
+ } else if value.Valid {
+ r.Prompt = value.String
+ }
+ case record.FieldCompletion:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field completion", values[i])
+ } else if value.Valid {
+ r.Completion = value.String
+ }
+ case record.FieldIsAccept:
+ if value, ok := values[i].(*sql.NullBool); !ok {
+ return fmt.Errorf("unexpected type %T for field is_accept", values[i])
+ } else if value.Valid {
+ r.IsAccept = value.Bool
+ }
+ case record.FieldProgramLanguage:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field program_language", values[i])
+ } else if value.Valid {
+ r.ProgramLanguage = value.String
+ }
+ case record.FieldWorkMode:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field work_mode", values[i])
+ } else if value.Valid {
+ r.WorkMode = value.String
+ }
+ case record.FieldCodeLines:
+ if value, ok := values[i].(*sql.NullInt64); !ok {
+ return fmt.Errorf("unexpected type %T for field code_lines", values[i])
+ } else if value.Valid {
+ r.CodeLines = value.Int64
+ }
+ case record.FieldInputTokens:
+ if value, ok := values[i].(*sql.NullInt64); !ok {
+ return fmt.Errorf("unexpected type %T for field input_tokens", values[i])
+ } else if value.Valid {
+ r.InputTokens = value.Int64
+ }
+ case record.FieldOutputTokens:
+ if value, ok := values[i].(*sql.NullInt64); !ok {
+ return fmt.Errorf("unexpected type %T for field output_tokens", values[i])
+ } else if value.Valid {
+ r.OutputTokens = value.Int64
+ }
+ case record.FieldCreatedAt:
+ if value, ok := values[i].(*sql.NullTime); !ok {
+ return fmt.Errorf("unexpected type %T for field created_at", values[i])
+ } else if value.Valid {
+ r.CreatedAt = value.Time
+ }
+ case record.FieldUpdatedAt:
+ if value, ok := values[i].(*sql.NullTime); !ok {
+ return fmt.Errorf("unexpected type %T for field updated_at", values[i])
+ } else if value.Valid {
+ r.UpdatedAt = value.Time
+ }
+ default:
+ r.selectValues.Set(columns[i], values[i])
+ }
+ }
+ return nil
+}
+
+// Value returns the ent.Value that was dynamically selected and assigned to the Record.
+// This includes values selected through modifiers, order, etc.
+func (r *Record) Value(name string) (ent.Value, error) {
+ return r.selectValues.Get(name)
+}
+
+// QueryUser queries the "user" edge of the Record entity.
+func (r *Record) QueryUser() *UserQuery {
+ return NewRecordClient(r.config).QueryUser(r)
+}
+
+// QueryModel queries the "model" edge of the Record entity.
+func (r *Record) QueryModel() *ModelQuery {
+ return NewRecordClient(r.config).QueryModel(r)
+}
+
+// Update returns a builder for updating this Record.
+// Note that you need to call Record.Unwrap() before calling this method if this Record
+// was returned from a transaction, and the transaction was committed or rolled back.
+func (r *Record) Update() *RecordUpdateOne {
+ return NewRecordClient(r.config).UpdateOne(r)
+}
+
+// Unwrap unwraps the Record entity that was returned from a transaction after it was closed,
+// so that all future queries will be executed through the driver which created the transaction.
+func (r *Record) Unwrap() *Record {
+ _tx, ok := r.config.driver.(*txDriver)
+ if !ok {
+ panic("db: Record is not a transactional entity")
+ }
+ r.config.driver = _tx.drv
+ return r
+}
+
+// String implements the fmt.Stringer.
+func (r *Record) String() string {
+ var builder strings.Builder
+ builder.WriteString("Record(")
+ builder.WriteString(fmt.Sprintf("id=%v, ", r.ID))
+ builder.WriteString("user_id=")
+ builder.WriteString(fmt.Sprintf("%v", r.UserID))
+ builder.WriteString(", ")
+ builder.WriteString("model_id=")
+ builder.WriteString(fmt.Sprintf("%v", r.ModelID))
+ builder.WriteString(", ")
+ builder.WriteString("task_id=")
+ builder.WriteString(r.TaskID)
+ builder.WriteString(", ")
+ builder.WriteString("model_type=")
+ builder.WriteString(fmt.Sprintf("%v", r.ModelType))
+ builder.WriteString(", ")
+ builder.WriteString("prompt=")
+ builder.WriteString(r.Prompt)
+ builder.WriteString(", ")
+ builder.WriteString("completion=")
+ builder.WriteString(r.Completion)
+ builder.WriteString(", ")
+ builder.WriteString("is_accept=")
+ builder.WriteString(fmt.Sprintf("%v", r.IsAccept))
+ builder.WriteString(", ")
+ builder.WriteString("program_language=")
+ builder.WriteString(r.ProgramLanguage)
+ builder.WriteString(", ")
+ builder.WriteString("work_mode=")
+ builder.WriteString(r.WorkMode)
+ builder.WriteString(", ")
+ builder.WriteString("code_lines=")
+ builder.WriteString(fmt.Sprintf("%v", r.CodeLines))
+ builder.WriteString(", ")
+ builder.WriteString("input_tokens=")
+ builder.WriteString(fmt.Sprintf("%v", r.InputTokens))
+ builder.WriteString(", ")
+ builder.WriteString("output_tokens=")
+ builder.WriteString(fmt.Sprintf("%v", r.OutputTokens))
+ builder.WriteString(", ")
+ builder.WriteString("created_at=")
+ builder.WriteString(r.CreatedAt.Format(time.ANSIC))
+ builder.WriteString(", ")
+ builder.WriteString("updated_at=")
+ builder.WriteString(r.UpdatedAt.Format(time.ANSIC))
+ builder.WriteByte(')')
+ return builder.String()
+}
+
+// Records is a parsable slice of Record.
+type Records []*Record
diff --git a/backend/db/record/record.go b/backend/db/record/record.go
new file mode 100644
index 0000000..4797926
--- /dev/null
+++ b/backend/db/record/record.go
@@ -0,0 +1,211 @@
+// Code generated by ent, DO NOT EDIT.
+
+package record
+
+import (
+ "time"
+
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+)
+
+const (
+ // Label holds the string label denoting the record type in the database.
+ Label = "record"
+ // FieldID holds the string denoting the id field in the database.
+ FieldID = "id"
+ // FieldUserID holds the string denoting the user_id field in the database.
+ FieldUserID = "user_id"
+ // FieldModelID holds the string denoting the model_id field in the database.
+ FieldModelID = "model_id"
+ // FieldTaskID holds the string denoting the task_id field in the database.
+ FieldTaskID = "task_id"
+ // FieldModelType holds the string denoting the model_type field in the database.
+ FieldModelType = "model_type"
+ // FieldPrompt holds the string denoting the prompt field in the database.
+ FieldPrompt = "prompt"
+ // FieldCompletion holds the string denoting the completion field in the database.
+ FieldCompletion = "completion"
+ // FieldIsAccept holds the string denoting the is_accept field in the database.
+ FieldIsAccept = "is_accept"
+ // FieldProgramLanguage holds the string denoting the program_language field in the database.
+ FieldProgramLanguage = "program_language"
+ // FieldWorkMode holds the string denoting the work_mode field in the database.
+ FieldWorkMode = "work_mode"
+ // FieldCodeLines holds the string denoting the code_lines field in the database.
+ FieldCodeLines = "code_lines"
+ // FieldInputTokens holds the string denoting the input_tokens field in the database.
+ FieldInputTokens = "input_tokens"
+ // FieldOutputTokens holds the string denoting the output_tokens field in the database.
+ FieldOutputTokens = "output_tokens"
+ // FieldCreatedAt holds the string denoting the created_at field in the database.
+ FieldCreatedAt = "created_at"
+ // FieldUpdatedAt holds the string denoting the updated_at field in the database.
+ FieldUpdatedAt = "updated_at"
+ // EdgeUser holds the string denoting the user edge name in mutations.
+ EdgeUser = "user"
+ // EdgeModel holds the string denoting the model edge name in mutations.
+ EdgeModel = "model"
+ // Table holds the table name of the record in the database.
+ Table = "records"
+ // UserTable is the table that holds the user relation/edge.
+ UserTable = "records"
+ // UserInverseTable is the table name for the User entity.
+ // It exists in this package in order to avoid circular dependency with the "user" package.
+ UserInverseTable = "users"
+ // UserColumn is the table column denoting the user relation/edge.
+ UserColumn = "user_id"
+ // ModelTable is the table that holds the model relation/edge.
+ ModelTable = "records"
+ // ModelInverseTable is the table name for the Model entity.
+ // It exists in this package in order to avoid circular dependency with the "model" package.
+ ModelInverseTable = "models"
+ // ModelColumn is the table column denoting the model relation/edge.
+ ModelColumn = "model_id"
+)
+
+// Columns holds all SQL columns for record fields.
+var Columns = []string{
+ FieldID,
+ FieldUserID,
+ FieldModelID,
+ FieldTaskID,
+ FieldModelType,
+ FieldPrompt,
+ FieldCompletion,
+ FieldIsAccept,
+ FieldProgramLanguage,
+ FieldWorkMode,
+ FieldCodeLines,
+ FieldInputTokens,
+ FieldOutputTokens,
+ FieldCreatedAt,
+ FieldUpdatedAt,
+}
+
+// ValidColumn reports if the column name is valid (part of the table columns).
+func ValidColumn(column string) bool {
+ for i := range Columns {
+ if column == Columns[i] {
+ return true
+ }
+ }
+ return false
+}
+
+var (
+ // DefaultIsAccept holds the default value on creation for the "is_accept" field.
+ DefaultIsAccept bool
+ // DefaultCreatedAt holds the default value on creation for the "created_at" field.
+ DefaultCreatedAt func() time.Time
+ // DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
+ DefaultUpdatedAt func() time.Time
+ // UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field.
+ UpdateDefaultUpdatedAt func() time.Time
+)
+
+// OrderOption defines the ordering options for the Record queries.
+type OrderOption func(*sql.Selector)
+
+// ByID orders the results by the id field.
+func ByID(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldID, opts...).ToFunc()
+}
+
+// ByUserID orders the results by the user_id field.
+func ByUserID(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldUserID, opts...).ToFunc()
+}
+
+// ByModelID orders the results by the model_id field.
+func ByModelID(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldModelID, opts...).ToFunc()
+}
+
+// ByTaskID orders the results by the task_id field.
+func ByTaskID(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldTaskID, opts...).ToFunc()
+}
+
+// ByModelType orders the results by the model_type field.
+func ByModelType(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldModelType, opts...).ToFunc()
+}
+
+// ByPrompt orders the results by the prompt field.
+func ByPrompt(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldPrompt, opts...).ToFunc()
+}
+
+// ByCompletion orders the results by the completion field.
+func ByCompletion(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldCompletion, opts...).ToFunc()
+}
+
+// ByIsAccept orders the results by the is_accept field.
+func ByIsAccept(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldIsAccept, opts...).ToFunc()
+}
+
+// ByProgramLanguage orders the results by the program_language field.
+func ByProgramLanguage(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldProgramLanguage, opts...).ToFunc()
+}
+
+// ByWorkMode orders the results by the work_mode field.
+func ByWorkMode(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldWorkMode, opts...).ToFunc()
+}
+
+// ByCodeLines orders the results by the code_lines field.
+func ByCodeLines(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldCodeLines, opts...).ToFunc()
+}
+
+// ByInputTokens orders the results by the input_tokens field.
+func ByInputTokens(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldInputTokens, opts...).ToFunc()
+}
+
+// ByOutputTokens orders the results by the output_tokens field.
+func ByOutputTokens(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldOutputTokens, opts...).ToFunc()
+}
+
+// ByCreatedAt orders the results by the created_at field.
+func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
+}
+
+// ByUpdatedAt orders the results by the updated_at field.
+func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc()
+}
+
+// ByUserField orders the results by user field.
+func ByUserField(field string, opts ...sql.OrderTermOption) OrderOption {
+ return func(s *sql.Selector) {
+ sqlgraph.OrderByNeighborTerms(s, newUserStep(), sql.OrderByField(field, opts...))
+ }
+}
+
+// ByModelField orders the results by model field.
+func ByModelField(field string, opts ...sql.OrderTermOption) OrderOption {
+ return func(s *sql.Selector) {
+ sqlgraph.OrderByNeighborTerms(s, newModelStep(), sql.OrderByField(field, opts...))
+ }
+}
+func newUserStep() *sqlgraph.Step {
+ return sqlgraph.NewStep(
+ sqlgraph.From(Table, FieldID),
+ sqlgraph.To(UserInverseTable, FieldID),
+ sqlgraph.Edge(sqlgraph.M2O, true, UserTable, UserColumn),
+ )
+}
+func newModelStep() *sqlgraph.Step {
+ return sqlgraph.NewStep(
+ sqlgraph.From(Table, FieldID),
+ sqlgraph.To(ModelInverseTable, FieldID),
+ sqlgraph.Edge(sqlgraph.M2O, true, ModelTable, ModelColumn),
+ )
+}
diff --git a/backend/db/record/where.go b/backend/db/record/where.go
new file mode 100644
index 0000000..0ee915e
--- /dev/null
+++ b/backend/db/record/where.go
@@ -0,0 +1,929 @@
+// Code generated by ent, DO NOT EDIT.
+
+package record
+
+import (
+ "time"
+
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "github.com/chaitin/MonkeyCode/backend/consts"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+ "github.com/google/uuid"
+)
+
+// ID filters vertices based on their ID field.
+func ID(id uuid.UUID) predicate.Record {
+ return predicate.Record(sql.FieldEQ(FieldID, id))
+}
+
+// IDEQ applies the EQ predicate on the ID field.
+func IDEQ(id uuid.UUID) predicate.Record {
+ return predicate.Record(sql.FieldEQ(FieldID, id))
+}
+
+// IDNEQ applies the NEQ predicate on the ID field.
+func IDNEQ(id uuid.UUID) predicate.Record {
+ return predicate.Record(sql.FieldNEQ(FieldID, id))
+}
+
+// IDIn applies the In predicate on the ID field.
+func IDIn(ids ...uuid.UUID) predicate.Record {
+ return predicate.Record(sql.FieldIn(FieldID, ids...))
+}
+
+// IDNotIn applies the NotIn predicate on the ID field.
+func IDNotIn(ids ...uuid.UUID) predicate.Record {
+ return predicate.Record(sql.FieldNotIn(FieldID, ids...))
+}
+
+// IDGT applies the GT predicate on the ID field.
+func IDGT(id uuid.UUID) predicate.Record {
+ return predicate.Record(sql.FieldGT(FieldID, id))
+}
+
+// IDGTE applies the GTE predicate on the ID field.
+func IDGTE(id uuid.UUID) predicate.Record {
+ return predicate.Record(sql.FieldGTE(FieldID, id))
+}
+
+// IDLT applies the LT predicate on the ID field.
+func IDLT(id uuid.UUID) predicate.Record {
+ return predicate.Record(sql.FieldLT(FieldID, id))
+}
+
+// IDLTE applies the LTE predicate on the ID field.
+func IDLTE(id uuid.UUID) predicate.Record {
+ return predicate.Record(sql.FieldLTE(FieldID, id))
+}
+
+// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ.
+func UserID(v uuid.UUID) predicate.Record {
+ return predicate.Record(sql.FieldEQ(FieldUserID, v))
+}
+
+// ModelID applies equality check predicate on the "model_id" field. It's identical to ModelIDEQ.
+func ModelID(v uuid.UUID) predicate.Record {
+ return predicate.Record(sql.FieldEQ(FieldModelID, v))
+}
+
+// TaskID applies equality check predicate on the "task_id" field. It's identical to TaskIDEQ.
+func TaskID(v string) predicate.Record {
+ return predicate.Record(sql.FieldEQ(FieldTaskID, v))
+}
+
+// ModelType applies equality check predicate on the "model_type" field. It's identical to ModelTypeEQ.
+func ModelType(v consts.ModelType) predicate.Record {
+ vc := string(v)
+ return predicate.Record(sql.FieldEQ(FieldModelType, vc))
+}
+
+// Prompt applies equality check predicate on the "prompt" field. It's identical to PromptEQ.
+func Prompt(v string) predicate.Record {
+ return predicate.Record(sql.FieldEQ(FieldPrompt, v))
+}
+
+// Completion applies equality check predicate on the "completion" field. It's identical to CompletionEQ.
+func Completion(v string) predicate.Record {
+ return predicate.Record(sql.FieldEQ(FieldCompletion, v))
+}
+
+// IsAccept applies equality check predicate on the "is_accept" field. It's identical to IsAcceptEQ.
+func IsAccept(v bool) predicate.Record {
+ return predicate.Record(sql.FieldEQ(FieldIsAccept, v))
+}
+
+// ProgramLanguage applies equality check predicate on the "program_language" field. It's identical to ProgramLanguageEQ.
+func ProgramLanguage(v string) predicate.Record {
+ return predicate.Record(sql.FieldEQ(FieldProgramLanguage, v))
+}
+
+// WorkMode applies equality check predicate on the "work_mode" field. It's identical to WorkModeEQ.
+func WorkMode(v string) predicate.Record {
+ return predicate.Record(sql.FieldEQ(FieldWorkMode, v))
+}
+
+// CodeLines applies equality check predicate on the "code_lines" field. It's identical to CodeLinesEQ.
+func CodeLines(v int64) predicate.Record {
+ return predicate.Record(sql.FieldEQ(FieldCodeLines, v))
+}
+
+// InputTokens applies equality check predicate on the "input_tokens" field. It's identical to InputTokensEQ.
+func InputTokens(v int64) predicate.Record {
+ return predicate.Record(sql.FieldEQ(FieldInputTokens, v))
+}
+
+// OutputTokens applies equality check predicate on the "output_tokens" field. It's identical to OutputTokensEQ.
+func OutputTokens(v int64) predicate.Record {
+ return predicate.Record(sql.FieldEQ(FieldOutputTokens, v))
+}
+
+// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
+func CreatedAt(v time.Time) predicate.Record {
+ return predicate.Record(sql.FieldEQ(FieldCreatedAt, v))
+}
+
+// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
+func UpdatedAt(v time.Time) predicate.Record {
+ return predicate.Record(sql.FieldEQ(FieldUpdatedAt, v))
+}
+
+// UserIDEQ applies the EQ predicate on the "user_id" field.
+func UserIDEQ(v uuid.UUID) predicate.Record {
+ return predicate.Record(sql.FieldEQ(FieldUserID, v))
+}
+
+// UserIDNEQ applies the NEQ predicate on the "user_id" field.
+func UserIDNEQ(v uuid.UUID) predicate.Record {
+ return predicate.Record(sql.FieldNEQ(FieldUserID, v))
+}
+
+// UserIDIn applies the In predicate on the "user_id" field.
+func UserIDIn(vs ...uuid.UUID) predicate.Record {
+ return predicate.Record(sql.FieldIn(FieldUserID, vs...))
+}
+
+// UserIDNotIn applies the NotIn predicate on the "user_id" field.
+func UserIDNotIn(vs ...uuid.UUID) predicate.Record {
+ return predicate.Record(sql.FieldNotIn(FieldUserID, vs...))
+}
+
+// UserIDIsNil applies the IsNil predicate on the "user_id" field.
+func UserIDIsNil() predicate.Record {
+ return predicate.Record(sql.FieldIsNull(FieldUserID))
+}
+
+// UserIDNotNil applies the NotNil predicate on the "user_id" field.
+func UserIDNotNil() predicate.Record {
+ return predicate.Record(sql.FieldNotNull(FieldUserID))
+}
+
+// ModelIDEQ applies the EQ predicate on the "model_id" field.
+func ModelIDEQ(v uuid.UUID) predicate.Record {
+ return predicate.Record(sql.FieldEQ(FieldModelID, v))
+}
+
+// ModelIDNEQ applies the NEQ predicate on the "model_id" field.
+func ModelIDNEQ(v uuid.UUID) predicate.Record {
+ return predicate.Record(sql.FieldNEQ(FieldModelID, v))
+}
+
+// ModelIDIn applies the In predicate on the "model_id" field.
+func ModelIDIn(vs ...uuid.UUID) predicate.Record {
+ return predicate.Record(sql.FieldIn(FieldModelID, vs...))
+}
+
+// ModelIDNotIn applies the NotIn predicate on the "model_id" field.
+func ModelIDNotIn(vs ...uuid.UUID) predicate.Record {
+ return predicate.Record(sql.FieldNotIn(FieldModelID, vs...))
+}
+
+// ModelIDIsNil applies the IsNil predicate on the "model_id" field.
+func ModelIDIsNil() predicate.Record {
+ return predicate.Record(sql.FieldIsNull(FieldModelID))
+}
+
+// ModelIDNotNil applies the NotNil predicate on the "model_id" field.
+func ModelIDNotNil() predicate.Record {
+ return predicate.Record(sql.FieldNotNull(FieldModelID))
+}
+
+// TaskIDEQ applies the EQ predicate on the "task_id" field.
+func TaskIDEQ(v string) predicate.Record {
+ return predicate.Record(sql.FieldEQ(FieldTaskID, v))
+}
+
+// TaskIDNEQ applies the NEQ predicate on the "task_id" field.
+func TaskIDNEQ(v string) predicate.Record {
+ return predicate.Record(sql.FieldNEQ(FieldTaskID, v))
+}
+
+// TaskIDIn applies the In predicate on the "task_id" field.
+func TaskIDIn(vs ...string) predicate.Record {
+ return predicate.Record(sql.FieldIn(FieldTaskID, vs...))
+}
+
+// TaskIDNotIn applies the NotIn predicate on the "task_id" field.
+func TaskIDNotIn(vs ...string) predicate.Record {
+ return predicate.Record(sql.FieldNotIn(FieldTaskID, vs...))
+}
+
+// TaskIDGT applies the GT predicate on the "task_id" field.
+func TaskIDGT(v string) predicate.Record {
+ return predicate.Record(sql.FieldGT(FieldTaskID, v))
+}
+
+// TaskIDGTE applies the GTE predicate on the "task_id" field.
+func TaskIDGTE(v string) predicate.Record {
+ return predicate.Record(sql.FieldGTE(FieldTaskID, v))
+}
+
+// TaskIDLT applies the LT predicate on the "task_id" field.
+func TaskIDLT(v string) predicate.Record {
+ return predicate.Record(sql.FieldLT(FieldTaskID, v))
+}
+
+// TaskIDLTE applies the LTE predicate on the "task_id" field.
+func TaskIDLTE(v string) predicate.Record {
+ return predicate.Record(sql.FieldLTE(FieldTaskID, v))
+}
+
+// TaskIDContains applies the Contains predicate on the "task_id" field.
+func TaskIDContains(v string) predicate.Record {
+ return predicate.Record(sql.FieldContains(FieldTaskID, v))
+}
+
+// TaskIDHasPrefix applies the HasPrefix predicate on the "task_id" field.
+func TaskIDHasPrefix(v string) predicate.Record {
+ return predicate.Record(sql.FieldHasPrefix(FieldTaskID, v))
+}
+
+// TaskIDHasSuffix applies the HasSuffix predicate on the "task_id" field.
+func TaskIDHasSuffix(v string) predicate.Record {
+ return predicate.Record(sql.FieldHasSuffix(FieldTaskID, v))
+}
+
+// TaskIDEqualFold applies the EqualFold predicate on the "task_id" field.
+func TaskIDEqualFold(v string) predicate.Record {
+ return predicate.Record(sql.FieldEqualFold(FieldTaskID, v))
+}
+
+// TaskIDContainsFold applies the ContainsFold predicate on the "task_id" field.
+func TaskIDContainsFold(v string) predicate.Record {
+ return predicate.Record(sql.FieldContainsFold(FieldTaskID, v))
+}
+
+// ModelTypeEQ applies the EQ predicate on the "model_type" field.
+func ModelTypeEQ(v consts.ModelType) predicate.Record {
+ vc := string(v)
+ return predicate.Record(sql.FieldEQ(FieldModelType, vc))
+}
+
+// ModelTypeNEQ applies the NEQ predicate on the "model_type" field.
+func ModelTypeNEQ(v consts.ModelType) predicate.Record {
+ vc := string(v)
+ return predicate.Record(sql.FieldNEQ(FieldModelType, vc))
+}
+
+// ModelTypeIn applies the In predicate on the "model_type" field.
+func ModelTypeIn(vs ...consts.ModelType) predicate.Record {
+ v := make([]any, len(vs))
+ for i := range v {
+ v[i] = string(vs[i])
+ }
+ return predicate.Record(sql.FieldIn(FieldModelType, v...))
+}
+
+// ModelTypeNotIn applies the NotIn predicate on the "model_type" field.
+func ModelTypeNotIn(vs ...consts.ModelType) predicate.Record {
+ v := make([]any, len(vs))
+ for i := range v {
+ v[i] = string(vs[i])
+ }
+ return predicate.Record(sql.FieldNotIn(FieldModelType, v...))
+}
+
+// ModelTypeGT applies the GT predicate on the "model_type" field.
+func ModelTypeGT(v consts.ModelType) predicate.Record {
+ vc := string(v)
+ return predicate.Record(sql.FieldGT(FieldModelType, vc))
+}
+
+// ModelTypeGTE applies the GTE predicate on the "model_type" field.
+func ModelTypeGTE(v consts.ModelType) predicate.Record {
+ vc := string(v)
+ return predicate.Record(sql.FieldGTE(FieldModelType, vc))
+}
+
+// ModelTypeLT applies the LT predicate on the "model_type" field.
+func ModelTypeLT(v consts.ModelType) predicate.Record {
+ vc := string(v)
+ return predicate.Record(sql.FieldLT(FieldModelType, vc))
+}
+
+// ModelTypeLTE applies the LTE predicate on the "model_type" field.
+func ModelTypeLTE(v consts.ModelType) predicate.Record {
+ vc := string(v)
+ return predicate.Record(sql.FieldLTE(FieldModelType, vc))
+}
+
+// ModelTypeContains applies the Contains predicate on the "model_type" field.
+func ModelTypeContains(v consts.ModelType) predicate.Record {
+ vc := string(v)
+ return predicate.Record(sql.FieldContains(FieldModelType, vc))
+}
+
+// ModelTypeHasPrefix applies the HasPrefix predicate on the "model_type" field.
+func ModelTypeHasPrefix(v consts.ModelType) predicate.Record {
+ vc := string(v)
+ return predicate.Record(sql.FieldHasPrefix(FieldModelType, vc))
+}
+
+// ModelTypeHasSuffix applies the HasSuffix predicate on the "model_type" field.
+func ModelTypeHasSuffix(v consts.ModelType) predicate.Record {
+ vc := string(v)
+ return predicate.Record(sql.FieldHasSuffix(FieldModelType, vc))
+}
+
+// ModelTypeIsNil applies the IsNil predicate on the "model_type" field.
+func ModelTypeIsNil() predicate.Record {
+ return predicate.Record(sql.FieldIsNull(FieldModelType))
+}
+
+// ModelTypeNotNil applies the NotNil predicate on the "model_type" field.
+func ModelTypeNotNil() predicate.Record {
+ return predicate.Record(sql.FieldNotNull(FieldModelType))
+}
+
+// ModelTypeEqualFold applies the EqualFold predicate on the "model_type" field.
+func ModelTypeEqualFold(v consts.ModelType) predicate.Record {
+ vc := string(v)
+ return predicate.Record(sql.FieldEqualFold(FieldModelType, vc))
+}
+
+// ModelTypeContainsFold applies the ContainsFold predicate on the "model_type" field.
+func ModelTypeContainsFold(v consts.ModelType) predicate.Record {
+ vc := string(v)
+ return predicate.Record(sql.FieldContainsFold(FieldModelType, vc))
+}
+
+// PromptEQ applies the EQ predicate on the "prompt" field.
+func PromptEQ(v string) predicate.Record {
+ return predicate.Record(sql.FieldEQ(FieldPrompt, v))
+}
+
+// PromptNEQ applies the NEQ predicate on the "prompt" field.
+func PromptNEQ(v string) predicate.Record {
+ return predicate.Record(sql.FieldNEQ(FieldPrompt, v))
+}
+
+// PromptIn applies the In predicate on the "prompt" field.
+func PromptIn(vs ...string) predicate.Record {
+ return predicate.Record(sql.FieldIn(FieldPrompt, vs...))
+}
+
+// PromptNotIn applies the NotIn predicate on the "prompt" field.
+func PromptNotIn(vs ...string) predicate.Record {
+ return predicate.Record(sql.FieldNotIn(FieldPrompt, vs...))
+}
+
+// PromptGT applies the GT predicate on the "prompt" field.
+func PromptGT(v string) predicate.Record {
+ return predicate.Record(sql.FieldGT(FieldPrompt, v))
+}
+
+// PromptGTE applies the GTE predicate on the "prompt" field.
+func PromptGTE(v string) predicate.Record {
+ return predicate.Record(sql.FieldGTE(FieldPrompt, v))
+}
+
+// PromptLT applies the LT predicate on the "prompt" field.
+func PromptLT(v string) predicate.Record {
+ return predicate.Record(sql.FieldLT(FieldPrompt, v))
+}
+
+// PromptLTE applies the LTE predicate on the "prompt" field.
+func PromptLTE(v string) predicate.Record {
+ return predicate.Record(sql.FieldLTE(FieldPrompt, v))
+}
+
+// PromptContains applies the Contains predicate on the "prompt" field.
+func PromptContains(v string) predicate.Record {
+ return predicate.Record(sql.FieldContains(FieldPrompt, v))
+}
+
+// PromptHasPrefix applies the HasPrefix predicate on the "prompt" field.
+func PromptHasPrefix(v string) predicate.Record {
+ return predicate.Record(sql.FieldHasPrefix(FieldPrompt, v))
+}
+
+// PromptHasSuffix applies the HasSuffix predicate on the "prompt" field.
+func PromptHasSuffix(v string) predicate.Record {
+ return predicate.Record(sql.FieldHasSuffix(FieldPrompt, v))
+}
+
+// PromptIsNil applies the IsNil predicate on the "prompt" field.
+func PromptIsNil() predicate.Record {
+ return predicate.Record(sql.FieldIsNull(FieldPrompt))
+}
+
+// PromptNotNil applies the NotNil predicate on the "prompt" field.
+func PromptNotNil() predicate.Record {
+ return predicate.Record(sql.FieldNotNull(FieldPrompt))
+}
+
+// PromptEqualFold applies the EqualFold predicate on the "prompt" field.
+func PromptEqualFold(v string) predicate.Record {
+ return predicate.Record(sql.FieldEqualFold(FieldPrompt, v))
+}
+
+// PromptContainsFold applies the ContainsFold predicate on the "prompt" field.
+func PromptContainsFold(v string) predicate.Record {
+ return predicate.Record(sql.FieldContainsFold(FieldPrompt, v))
+}
+
+// CompletionEQ applies the EQ predicate on the "completion" field.
+func CompletionEQ(v string) predicate.Record {
+ return predicate.Record(sql.FieldEQ(FieldCompletion, v))
+}
+
+// CompletionNEQ applies the NEQ predicate on the "completion" field.
+func CompletionNEQ(v string) predicate.Record {
+ return predicate.Record(sql.FieldNEQ(FieldCompletion, v))
+}
+
+// CompletionIn applies the In predicate on the "completion" field.
+func CompletionIn(vs ...string) predicate.Record {
+ return predicate.Record(sql.FieldIn(FieldCompletion, vs...))
+}
+
+// CompletionNotIn applies the NotIn predicate on the "completion" field.
+func CompletionNotIn(vs ...string) predicate.Record {
+ return predicate.Record(sql.FieldNotIn(FieldCompletion, vs...))
+}
+
+// CompletionGT applies the GT predicate on the "completion" field.
+func CompletionGT(v string) predicate.Record {
+ return predicate.Record(sql.FieldGT(FieldCompletion, v))
+}
+
+// CompletionGTE applies the GTE predicate on the "completion" field.
+func CompletionGTE(v string) predicate.Record {
+ return predicate.Record(sql.FieldGTE(FieldCompletion, v))
+}
+
+// CompletionLT applies the LT predicate on the "completion" field.
+func CompletionLT(v string) predicate.Record {
+ return predicate.Record(sql.FieldLT(FieldCompletion, v))
+}
+
+// CompletionLTE applies the LTE predicate on the "completion" field.
+func CompletionLTE(v string) predicate.Record {
+ return predicate.Record(sql.FieldLTE(FieldCompletion, v))
+}
+
+// CompletionContains applies the Contains predicate on the "completion" field.
+func CompletionContains(v string) predicate.Record {
+ return predicate.Record(sql.FieldContains(FieldCompletion, v))
+}
+
+// CompletionHasPrefix applies the HasPrefix predicate on the "completion" field.
+func CompletionHasPrefix(v string) predicate.Record {
+ return predicate.Record(sql.FieldHasPrefix(FieldCompletion, v))
+}
+
+// CompletionHasSuffix applies the HasSuffix predicate on the "completion" field.
+func CompletionHasSuffix(v string) predicate.Record {
+ return predicate.Record(sql.FieldHasSuffix(FieldCompletion, v))
+}
+
+// CompletionIsNil applies the IsNil predicate on the "completion" field.
+func CompletionIsNil() predicate.Record {
+ return predicate.Record(sql.FieldIsNull(FieldCompletion))
+}
+
+// CompletionNotNil applies the NotNil predicate on the "completion" field.
+func CompletionNotNil() predicate.Record {
+ return predicate.Record(sql.FieldNotNull(FieldCompletion))
+}
+
+// CompletionEqualFold applies the EqualFold predicate on the "completion" field.
+func CompletionEqualFold(v string) predicate.Record {
+ return predicate.Record(sql.FieldEqualFold(FieldCompletion, v))
+}
+
+// CompletionContainsFold applies the ContainsFold predicate on the "completion" field.
+func CompletionContainsFold(v string) predicate.Record {
+ return predicate.Record(sql.FieldContainsFold(FieldCompletion, v))
+}
+
+// IsAcceptEQ applies the EQ predicate on the "is_accept" field.
+func IsAcceptEQ(v bool) predicate.Record {
+ return predicate.Record(sql.FieldEQ(FieldIsAccept, v))
+}
+
+// IsAcceptNEQ applies the NEQ predicate on the "is_accept" field.
+func IsAcceptNEQ(v bool) predicate.Record {
+ return predicate.Record(sql.FieldNEQ(FieldIsAccept, v))
+}
+
+// ProgramLanguageEQ applies the EQ predicate on the "program_language" field.
+func ProgramLanguageEQ(v string) predicate.Record {
+ return predicate.Record(sql.FieldEQ(FieldProgramLanguage, v))
+}
+
+// ProgramLanguageNEQ applies the NEQ predicate on the "program_language" field.
+func ProgramLanguageNEQ(v string) predicate.Record {
+ return predicate.Record(sql.FieldNEQ(FieldProgramLanguage, v))
+}
+
+// ProgramLanguageIn applies the In predicate on the "program_language" field.
+func ProgramLanguageIn(vs ...string) predicate.Record {
+ return predicate.Record(sql.FieldIn(FieldProgramLanguage, vs...))
+}
+
+// ProgramLanguageNotIn applies the NotIn predicate on the "program_language" field.
+func ProgramLanguageNotIn(vs ...string) predicate.Record {
+ return predicate.Record(sql.FieldNotIn(FieldProgramLanguage, vs...))
+}
+
+// ProgramLanguageGT applies the GT predicate on the "program_language" field.
+func ProgramLanguageGT(v string) predicate.Record {
+ return predicate.Record(sql.FieldGT(FieldProgramLanguage, v))
+}
+
+// ProgramLanguageGTE applies the GTE predicate on the "program_language" field.
+func ProgramLanguageGTE(v string) predicate.Record {
+ return predicate.Record(sql.FieldGTE(FieldProgramLanguage, v))
+}
+
+// ProgramLanguageLT applies the LT predicate on the "program_language" field.
+func ProgramLanguageLT(v string) predicate.Record {
+ return predicate.Record(sql.FieldLT(FieldProgramLanguage, v))
+}
+
+// ProgramLanguageLTE applies the LTE predicate on the "program_language" field.
+func ProgramLanguageLTE(v string) predicate.Record {
+ return predicate.Record(sql.FieldLTE(FieldProgramLanguage, v))
+}
+
+// ProgramLanguageContains applies the Contains predicate on the "program_language" field.
+func ProgramLanguageContains(v string) predicate.Record {
+ return predicate.Record(sql.FieldContains(FieldProgramLanguage, v))
+}
+
+// ProgramLanguageHasPrefix applies the HasPrefix predicate on the "program_language" field.
+func ProgramLanguageHasPrefix(v string) predicate.Record {
+ return predicate.Record(sql.FieldHasPrefix(FieldProgramLanguage, v))
+}
+
+// ProgramLanguageHasSuffix applies the HasSuffix predicate on the "program_language" field.
+func ProgramLanguageHasSuffix(v string) predicate.Record {
+ return predicate.Record(sql.FieldHasSuffix(FieldProgramLanguage, v))
+}
+
+// ProgramLanguageIsNil applies the IsNil predicate on the "program_language" field.
+func ProgramLanguageIsNil() predicate.Record {
+ return predicate.Record(sql.FieldIsNull(FieldProgramLanguage))
+}
+
+// ProgramLanguageNotNil applies the NotNil predicate on the "program_language" field.
+func ProgramLanguageNotNil() predicate.Record {
+ return predicate.Record(sql.FieldNotNull(FieldProgramLanguage))
+}
+
+// ProgramLanguageEqualFold applies the EqualFold predicate on the "program_language" field.
+func ProgramLanguageEqualFold(v string) predicate.Record {
+ return predicate.Record(sql.FieldEqualFold(FieldProgramLanguage, v))
+}
+
+// ProgramLanguageContainsFold applies the ContainsFold predicate on the "program_language" field.
+func ProgramLanguageContainsFold(v string) predicate.Record {
+ return predicate.Record(sql.FieldContainsFold(FieldProgramLanguage, v))
+}
+
+// WorkModeEQ applies the EQ predicate on the "work_mode" field.
+func WorkModeEQ(v string) predicate.Record {
+ return predicate.Record(sql.FieldEQ(FieldWorkMode, v))
+}
+
+// WorkModeNEQ applies the NEQ predicate on the "work_mode" field.
+func WorkModeNEQ(v string) predicate.Record {
+ return predicate.Record(sql.FieldNEQ(FieldWorkMode, v))
+}
+
+// WorkModeIn applies the In predicate on the "work_mode" field.
+func WorkModeIn(vs ...string) predicate.Record {
+ return predicate.Record(sql.FieldIn(FieldWorkMode, vs...))
+}
+
+// WorkModeNotIn applies the NotIn predicate on the "work_mode" field.
+func WorkModeNotIn(vs ...string) predicate.Record {
+ return predicate.Record(sql.FieldNotIn(FieldWorkMode, vs...))
+}
+
+// WorkModeGT applies the GT predicate on the "work_mode" field.
+func WorkModeGT(v string) predicate.Record {
+ return predicate.Record(sql.FieldGT(FieldWorkMode, v))
+}
+
+// WorkModeGTE applies the GTE predicate on the "work_mode" field.
+func WorkModeGTE(v string) predicate.Record {
+ return predicate.Record(sql.FieldGTE(FieldWorkMode, v))
+}
+
+// WorkModeLT applies the LT predicate on the "work_mode" field.
+func WorkModeLT(v string) predicate.Record {
+ return predicate.Record(sql.FieldLT(FieldWorkMode, v))
+}
+
+// WorkModeLTE applies the LTE predicate on the "work_mode" field.
+func WorkModeLTE(v string) predicate.Record {
+ return predicate.Record(sql.FieldLTE(FieldWorkMode, v))
+}
+
+// WorkModeContains applies the Contains predicate on the "work_mode" field.
+func WorkModeContains(v string) predicate.Record {
+ return predicate.Record(sql.FieldContains(FieldWorkMode, v))
+}
+
+// WorkModeHasPrefix applies the HasPrefix predicate on the "work_mode" field.
+func WorkModeHasPrefix(v string) predicate.Record {
+ return predicate.Record(sql.FieldHasPrefix(FieldWorkMode, v))
+}
+
+// WorkModeHasSuffix applies the HasSuffix predicate on the "work_mode" field.
+func WorkModeHasSuffix(v string) predicate.Record {
+ return predicate.Record(sql.FieldHasSuffix(FieldWorkMode, v))
+}
+
+// WorkModeIsNil applies the IsNil predicate on the "work_mode" field.
+func WorkModeIsNil() predicate.Record {
+ return predicate.Record(sql.FieldIsNull(FieldWorkMode))
+}
+
+// WorkModeNotNil applies the NotNil predicate on the "work_mode" field.
+func WorkModeNotNil() predicate.Record {
+ return predicate.Record(sql.FieldNotNull(FieldWorkMode))
+}
+
+// WorkModeEqualFold applies the EqualFold predicate on the "work_mode" field.
+func WorkModeEqualFold(v string) predicate.Record {
+ return predicate.Record(sql.FieldEqualFold(FieldWorkMode, v))
+}
+
+// WorkModeContainsFold applies the ContainsFold predicate on the "work_mode" field.
+func WorkModeContainsFold(v string) predicate.Record {
+ return predicate.Record(sql.FieldContainsFold(FieldWorkMode, v))
+}
+
+// CodeLinesEQ applies the EQ predicate on the "code_lines" field.
+func CodeLinesEQ(v int64) predicate.Record {
+ return predicate.Record(sql.FieldEQ(FieldCodeLines, v))
+}
+
+// CodeLinesNEQ applies the NEQ predicate on the "code_lines" field.
+func CodeLinesNEQ(v int64) predicate.Record {
+ return predicate.Record(sql.FieldNEQ(FieldCodeLines, v))
+}
+
+// CodeLinesIn applies the In predicate on the "code_lines" field.
+func CodeLinesIn(vs ...int64) predicate.Record {
+ return predicate.Record(sql.FieldIn(FieldCodeLines, vs...))
+}
+
+// CodeLinesNotIn applies the NotIn predicate on the "code_lines" field.
+func CodeLinesNotIn(vs ...int64) predicate.Record {
+ return predicate.Record(sql.FieldNotIn(FieldCodeLines, vs...))
+}
+
+// CodeLinesGT applies the GT predicate on the "code_lines" field.
+func CodeLinesGT(v int64) predicate.Record {
+ return predicate.Record(sql.FieldGT(FieldCodeLines, v))
+}
+
+// CodeLinesGTE applies the GTE predicate on the "code_lines" field.
+func CodeLinesGTE(v int64) predicate.Record {
+ return predicate.Record(sql.FieldGTE(FieldCodeLines, v))
+}
+
+// CodeLinesLT applies the LT predicate on the "code_lines" field.
+func CodeLinesLT(v int64) predicate.Record {
+ return predicate.Record(sql.FieldLT(FieldCodeLines, v))
+}
+
+// CodeLinesLTE applies the LTE predicate on the "code_lines" field.
+func CodeLinesLTE(v int64) predicate.Record {
+ return predicate.Record(sql.FieldLTE(FieldCodeLines, v))
+}
+
+// CodeLinesIsNil applies the IsNil predicate on the "code_lines" field.
+func CodeLinesIsNil() predicate.Record {
+ return predicate.Record(sql.FieldIsNull(FieldCodeLines))
+}
+
+// CodeLinesNotNil applies the NotNil predicate on the "code_lines" field.
+func CodeLinesNotNil() predicate.Record {
+ return predicate.Record(sql.FieldNotNull(FieldCodeLines))
+}
+
+// InputTokensEQ applies the EQ predicate on the "input_tokens" field.
+func InputTokensEQ(v int64) predicate.Record {
+ return predicate.Record(sql.FieldEQ(FieldInputTokens, v))
+}
+
+// InputTokensNEQ applies the NEQ predicate on the "input_tokens" field.
+func InputTokensNEQ(v int64) predicate.Record {
+ return predicate.Record(sql.FieldNEQ(FieldInputTokens, v))
+}
+
+// InputTokensIn applies the In predicate on the "input_tokens" field.
+func InputTokensIn(vs ...int64) predicate.Record {
+ return predicate.Record(sql.FieldIn(FieldInputTokens, vs...))
+}
+
+// InputTokensNotIn applies the NotIn predicate on the "input_tokens" field.
+func InputTokensNotIn(vs ...int64) predicate.Record {
+ return predicate.Record(sql.FieldNotIn(FieldInputTokens, vs...))
+}
+
+// InputTokensGT applies the GT predicate on the "input_tokens" field.
+func InputTokensGT(v int64) predicate.Record {
+ return predicate.Record(sql.FieldGT(FieldInputTokens, v))
+}
+
+// InputTokensGTE applies the GTE predicate on the "input_tokens" field.
+func InputTokensGTE(v int64) predicate.Record {
+ return predicate.Record(sql.FieldGTE(FieldInputTokens, v))
+}
+
+// InputTokensLT applies the LT predicate on the "input_tokens" field.
+func InputTokensLT(v int64) predicate.Record {
+ return predicate.Record(sql.FieldLT(FieldInputTokens, v))
+}
+
+// InputTokensLTE applies the LTE predicate on the "input_tokens" field.
+func InputTokensLTE(v int64) predicate.Record {
+ return predicate.Record(sql.FieldLTE(FieldInputTokens, v))
+}
+
+// OutputTokensEQ applies the EQ predicate on the "output_tokens" field.
+func OutputTokensEQ(v int64) predicate.Record {
+ return predicate.Record(sql.FieldEQ(FieldOutputTokens, v))
+}
+
+// OutputTokensNEQ applies the NEQ predicate on the "output_tokens" field.
+func OutputTokensNEQ(v int64) predicate.Record {
+ return predicate.Record(sql.FieldNEQ(FieldOutputTokens, v))
+}
+
+// OutputTokensIn applies the In predicate on the "output_tokens" field.
+func OutputTokensIn(vs ...int64) predicate.Record {
+ return predicate.Record(sql.FieldIn(FieldOutputTokens, vs...))
+}
+
+// OutputTokensNotIn applies the NotIn predicate on the "output_tokens" field.
+func OutputTokensNotIn(vs ...int64) predicate.Record {
+ return predicate.Record(sql.FieldNotIn(FieldOutputTokens, vs...))
+}
+
+// OutputTokensGT applies the GT predicate on the "output_tokens" field.
+func OutputTokensGT(v int64) predicate.Record {
+ return predicate.Record(sql.FieldGT(FieldOutputTokens, v))
+}
+
+// OutputTokensGTE applies the GTE predicate on the "output_tokens" field.
+func OutputTokensGTE(v int64) predicate.Record {
+ return predicate.Record(sql.FieldGTE(FieldOutputTokens, v))
+}
+
+// OutputTokensLT applies the LT predicate on the "output_tokens" field.
+func OutputTokensLT(v int64) predicate.Record {
+ return predicate.Record(sql.FieldLT(FieldOutputTokens, v))
+}
+
+// OutputTokensLTE applies the LTE predicate on the "output_tokens" field.
+func OutputTokensLTE(v int64) predicate.Record {
+ return predicate.Record(sql.FieldLTE(FieldOutputTokens, v))
+}
+
+// CreatedAtEQ applies the EQ predicate on the "created_at" field.
+func CreatedAtEQ(v time.Time) predicate.Record {
+ return predicate.Record(sql.FieldEQ(FieldCreatedAt, v))
+}
+
+// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
+func CreatedAtNEQ(v time.Time) predicate.Record {
+ return predicate.Record(sql.FieldNEQ(FieldCreatedAt, v))
+}
+
+// CreatedAtIn applies the In predicate on the "created_at" field.
+func CreatedAtIn(vs ...time.Time) predicate.Record {
+ return predicate.Record(sql.FieldIn(FieldCreatedAt, vs...))
+}
+
+// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
+func CreatedAtNotIn(vs ...time.Time) predicate.Record {
+ return predicate.Record(sql.FieldNotIn(FieldCreatedAt, vs...))
+}
+
+// CreatedAtGT applies the GT predicate on the "created_at" field.
+func CreatedAtGT(v time.Time) predicate.Record {
+ return predicate.Record(sql.FieldGT(FieldCreatedAt, v))
+}
+
+// CreatedAtGTE applies the GTE predicate on the "created_at" field.
+func CreatedAtGTE(v time.Time) predicate.Record {
+ return predicate.Record(sql.FieldGTE(FieldCreatedAt, v))
+}
+
+// CreatedAtLT applies the LT predicate on the "created_at" field.
+func CreatedAtLT(v time.Time) predicate.Record {
+ return predicate.Record(sql.FieldLT(FieldCreatedAt, v))
+}
+
+// CreatedAtLTE applies the LTE predicate on the "created_at" field.
+func CreatedAtLTE(v time.Time) predicate.Record {
+ return predicate.Record(sql.FieldLTE(FieldCreatedAt, v))
+}
+
+// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
+func UpdatedAtEQ(v time.Time) predicate.Record {
+ return predicate.Record(sql.FieldEQ(FieldUpdatedAt, v))
+}
+
+// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
+func UpdatedAtNEQ(v time.Time) predicate.Record {
+ return predicate.Record(sql.FieldNEQ(FieldUpdatedAt, v))
+}
+
+// UpdatedAtIn applies the In predicate on the "updated_at" field.
+func UpdatedAtIn(vs ...time.Time) predicate.Record {
+ return predicate.Record(sql.FieldIn(FieldUpdatedAt, vs...))
+}
+
+// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
+func UpdatedAtNotIn(vs ...time.Time) predicate.Record {
+ return predicate.Record(sql.FieldNotIn(FieldUpdatedAt, vs...))
+}
+
+// UpdatedAtGT applies the GT predicate on the "updated_at" field.
+func UpdatedAtGT(v time.Time) predicate.Record {
+ return predicate.Record(sql.FieldGT(FieldUpdatedAt, v))
+}
+
+// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
+func UpdatedAtGTE(v time.Time) predicate.Record {
+ return predicate.Record(sql.FieldGTE(FieldUpdatedAt, v))
+}
+
+// UpdatedAtLT applies the LT predicate on the "updated_at" field.
+func UpdatedAtLT(v time.Time) predicate.Record {
+ return predicate.Record(sql.FieldLT(FieldUpdatedAt, v))
+}
+
+// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
+func UpdatedAtLTE(v time.Time) predicate.Record {
+ return predicate.Record(sql.FieldLTE(FieldUpdatedAt, v))
+}
+
+// HasUser applies the HasEdge predicate on the "user" edge.
+func HasUser() predicate.Record {
+ return predicate.Record(func(s *sql.Selector) {
+ step := sqlgraph.NewStep(
+ sqlgraph.From(Table, FieldID),
+ sqlgraph.Edge(sqlgraph.M2O, true, UserTable, UserColumn),
+ )
+ sqlgraph.HasNeighbors(s, step)
+ })
+}
+
+// HasUserWith applies the HasEdge predicate on the "user" edge with a given conditions (other predicates).
+func HasUserWith(preds ...predicate.User) predicate.Record {
+ return predicate.Record(func(s *sql.Selector) {
+ step := newUserStep()
+ sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
+ for _, p := range preds {
+ p(s)
+ }
+ })
+ })
+}
+
+// HasModel applies the HasEdge predicate on the "model" edge.
+func HasModel() predicate.Record {
+ return predicate.Record(func(s *sql.Selector) {
+ step := sqlgraph.NewStep(
+ sqlgraph.From(Table, FieldID),
+ sqlgraph.Edge(sqlgraph.M2O, true, ModelTable, ModelColumn),
+ )
+ sqlgraph.HasNeighbors(s, step)
+ })
+}
+
+// HasModelWith applies the HasEdge predicate on the "model" edge with a given conditions (other predicates).
+func HasModelWith(preds ...predicate.Model) predicate.Record {
+ return predicate.Record(func(s *sql.Selector) {
+ step := newModelStep()
+ sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
+ for _, p := range preds {
+ p(s)
+ }
+ })
+ })
+}
+
+// And groups predicates with the AND operator between them.
+func And(predicates ...predicate.Record) predicate.Record {
+ return predicate.Record(sql.AndPredicates(predicates...))
+}
+
+// Or groups predicates with the OR operator between them.
+func Or(predicates ...predicate.Record) predicate.Record {
+ return predicate.Record(sql.OrPredicates(predicates...))
+}
+
+// Not applies the not operator on the given predicate.
+func Not(p predicate.Record) predicate.Record {
+ return predicate.Record(sql.NotPredicates(p))
+}
diff --git a/backend/db/record_create.go b/backend/db/record_create.go
new file mode 100644
index 0000000..cbb8421
--- /dev/null
+++ b/backend/db/record_create.go
@@ -0,0 +1,1521 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "time"
+
+ "entgo.io/ent/dialect"
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/consts"
+ "github.com/chaitin/MonkeyCode/backend/db/model"
+ "github.com/chaitin/MonkeyCode/backend/db/record"
+ "github.com/chaitin/MonkeyCode/backend/db/user"
+ "github.com/google/uuid"
+)
+
+// RecordCreate is the builder for creating a Record entity.
+type RecordCreate struct {
+ config
+ mutation *RecordMutation
+ hooks []Hook
+ conflict []sql.ConflictOption
+}
+
+// SetUserID sets the "user_id" field.
+func (rc *RecordCreate) SetUserID(u uuid.UUID) *RecordCreate {
+ rc.mutation.SetUserID(u)
+ return rc
+}
+
+// SetNillableUserID sets the "user_id" field if the given value is not nil.
+func (rc *RecordCreate) SetNillableUserID(u *uuid.UUID) *RecordCreate {
+ if u != nil {
+ rc.SetUserID(*u)
+ }
+ return rc
+}
+
+// SetModelID sets the "model_id" field.
+func (rc *RecordCreate) SetModelID(u uuid.UUID) *RecordCreate {
+ rc.mutation.SetModelID(u)
+ return rc
+}
+
+// SetNillableModelID sets the "model_id" field if the given value is not nil.
+func (rc *RecordCreate) SetNillableModelID(u *uuid.UUID) *RecordCreate {
+ if u != nil {
+ rc.SetModelID(*u)
+ }
+ return rc
+}
+
+// SetTaskID sets the "task_id" field.
+func (rc *RecordCreate) SetTaskID(s string) *RecordCreate {
+ rc.mutation.SetTaskID(s)
+ return rc
+}
+
+// SetModelType sets the "model_type" field.
+func (rc *RecordCreate) SetModelType(ct consts.ModelType) *RecordCreate {
+ rc.mutation.SetModelType(ct)
+ return rc
+}
+
+// SetNillableModelType sets the "model_type" field if the given value is not nil.
+func (rc *RecordCreate) SetNillableModelType(ct *consts.ModelType) *RecordCreate {
+ if ct != nil {
+ rc.SetModelType(*ct)
+ }
+ return rc
+}
+
+// SetPrompt sets the "prompt" field.
+func (rc *RecordCreate) SetPrompt(s string) *RecordCreate {
+ rc.mutation.SetPrompt(s)
+ return rc
+}
+
+// SetNillablePrompt sets the "prompt" field if the given value is not nil.
+func (rc *RecordCreate) SetNillablePrompt(s *string) *RecordCreate {
+ if s != nil {
+ rc.SetPrompt(*s)
+ }
+ return rc
+}
+
+// SetCompletion sets the "completion" field.
+func (rc *RecordCreate) SetCompletion(s string) *RecordCreate {
+ rc.mutation.SetCompletion(s)
+ return rc
+}
+
+// SetNillableCompletion sets the "completion" field if the given value is not nil.
+func (rc *RecordCreate) SetNillableCompletion(s *string) *RecordCreate {
+ if s != nil {
+ rc.SetCompletion(*s)
+ }
+ return rc
+}
+
+// SetIsAccept sets the "is_accept" field.
+func (rc *RecordCreate) SetIsAccept(b bool) *RecordCreate {
+ rc.mutation.SetIsAccept(b)
+ return rc
+}
+
+// SetNillableIsAccept sets the "is_accept" field if the given value is not nil.
+func (rc *RecordCreate) SetNillableIsAccept(b *bool) *RecordCreate {
+ if b != nil {
+ rc.SetIsAccept(*b)
+ }
+ return rc
+}
+
+// SetProgramLanguage sets the "program_language" field.
+func (rc *RecordCreate) SetProgramLanguage(s string) *RecordCreate {
+ rc.mutation.SetProgramLanguage(s)
+ return rc
+}
+
+// SetNillableProgramLanguage sets the "program_language" field if the given value is not nil.
+func (rc *RecordCreate) SetNillableProgramLanguage(s *string) *RecordCreate {
+ if s != nil {
+ rc.SetProgramLanguage(*s)
+ }
+ return rc
+}
+
+// SetWorkMode sets the "work_mode" field.
+func (rc *RecordCreate) SetWorkMode(s string) *RecordCreate {
+ rc.mutation.SetWorkMode(s)
+ return rc
+}
+
+// SetNillableWorkMode sets the "work_mode" field if the given value is not nil.
+func (rc *RecordCreate) SetNillableWorkMode(s *string) *RecordCreate {
+ if s != nil {
+ rc.SetWorkMode(*s)
+ }
+ return rc
+}
+
+// SetCodeLines sets the "code_lines" field.
+func (rc *RecordCreate) SetCodeLines(i int64) *RecordCreate {
+ rc.mutation.SetCodeLines(i)
+ return rc
+}
+
+// SetNillableCodeLines sets the "code_lines" field if the given value is not nil.
+func (rc *RecordCreate) SetNillableCodeLines(i *int64) *RecordCreate {
+ if i != nil {
+ rc.SetCodeLines(*i)
+ }
+ return rc
+}
+
+// SetInputTokens sets the "input_tokens" field.
+func (rc *RecordCreate) SetInputTokens(i int64) *RecordCreate {
+ rc.mutation.SetInputTokens(i)
+ return rc
+}
+
+// SetOutputTokens sets the "output_tokens" field.
+func (rc *RecordCreate) SetOutputTokens(i int64) *RecordCreate {
+ rc.mutation.SetOutputTokens(i)
+ return rc
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (rc *RecordCreate) SetCreatedAt(t time.Time) *RecordCreate {
+ rc.mutation.SetCreatedAt(t)
+ return rc
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (rc *RecordCreate) SetNillableCreatedAt(t *time.Time) *RecordCreate {
+ if t != nil {
+ rc.SetCreatedAt(*t)
+ }
+ return rc
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (rc *RecordCreate) SetUpdatedAt(t time.Time) *RecordCreate {
+ rc.mutation.SetUpdatedAt(t)
+ return rc
+}
+
+// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
+func (rc *RecordCreate) SetNillableUpdatedAt(t *time.Time) *RecordCreate {
+ if t != nil {
+ rc.SetUpdatedAt(*t)
+ }
+ return rc
+}
+
+// SetID sets the "id" field.
+func (rc *RecordCreate) SetID(u uuid.UUID) *RecordCreate {
+ rc.mutation.SetID(u)
+ return rc
+}
+
+// SetUser sets the "user" edge to the User entity.
+func (rc *RecordCreate) SetUser(u *User) *RecordCreate {
+ return rc.SetUserID(u.ID)
+}
+
+// SetModel sets the "model" edge to the Model entity.
+func (rc *RecordCreate) SetModel(m *Model) *RecordCreate {
+ return rc.SetModelID(m.ID)
+}
+
+// Mutation returns the RecordMutation object of the builder.
+func (rc *RecordCreate) Mutation() *RecordMutation {
+ return rc.mutation
+}
+
+// Save creates the Record in the database.
+func (rc *RecordCreate) Save(ctx context.Context) (*Record, error) {
+ rc.defaults()
+ return withHooks(ctx, rc.sqlSave, rc.mutation, rc.hooks)
+}
+
+// SaveX calls Save and panics if Save returns an error.
+func (rc *RecordCreate) SaveX(ctx context.Context) *Record {
+ v, err := rc.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return v
+}
+
+// Exec executes the query.
+func (rc *RecordCreate) Exec(ctx context.Context) error {
+ _, err := rc.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (rc *RecordCreate) ExecX(ctx context.Context) {
+ if err := rc.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// defaults sets the default values of the builder before save.
+func (rc *RecordCreate) defaults() {
+ if _, ok := rc.mutation.IsAccept(); !ok {
+ v := record.DefaultIsAccept
+ rc.mutation.SetIsAccept(v)
+ }
+ if _, ok := rc.mutation.CreatedAt(); !ok {
+ v := record.DefaultCreatedAt()
+ rc.mutation.SetCreatedAt(v)
+ }
+ if _, ok := rc.mutation.UpdatedAt(); !ok {
+ v := record.DefaultUpdatedAt()
+ rc.mutation.SetUpdatedAt(v)
+ }
+}
+
+// check runs all checks and user-defined validators on the builder.
+func (rc *RecordCreate) check() error {
+ if _, ok := rc.mutation.TaskID(); !ok {
+ return &ValidationError{Name: "task_id", err: errors.New(`db: missing required field "Record.task_id"`)}
+ }
+ if _, ok := rc.mutation.IsAccept(); !ok {
+ return &ValidationError{Name: "is_accept", err: errors.New(`db: missing required field "Record.is_accept"`)}
+ }
+ if _, ok := rc.mutation.InputTokens(); !ok {
+ return &ValidationError{Name: "input_tokens", err: errors.New(`db: missing required field "Record.input_tokens"`)}
+ }
+ if _, ok := rc.mutation.OutputTokens(); !ok {
+ return &ValidationError{Name: "output_tokens", err: errors.New(`db: missing required field "Record.output_tokens"`)}
+ }
+ if _, ok := rc.mutation.CreatedAt(); !ok {
+ return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "Record.created_at"`)}
+ }
+ if _, ok := rc.mutation.UpdatedAt(); !ok {
+ return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "Record.updated_at"`)}
+ }
+ return nil
+}
+
+func (rc *RecordCreate) sqlSave(ctx context.Context) (*Record, error) {
+ if err := rc.check(); err != nil {
+ return nil, err
+ }
+ _node, _spec := rc.createSpec()
+ if err := sqlgraph.CreateNode(ctx, rc.driver, _spec); err != nil {
+ if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return nil, err
+ }
+ if _spec.ID.Value != nil {
+ if id, ok := _spec.ID.Value.(*uuid.UUID); ok {
+ _node.ID = *id
+ } else if err := _node.ID.Scan(_spec.ID.Value); err != nil {
+ return nil, err
+ }
+ }
+ rc.mutation.id = &_node.ID
+ rc.mutation.done = true
+ return _node, nil
+}
+
+func (rc *RecordCreate) createSpec() (*Record, *sqlgraph.CreateSpec) {
+ var (
+ _node = &Record{config: rc.config}
+ _spec = sqlgraph.NewCreateSpec(record.Table, sqlgraph.NewFieldSpec(record.FieldID, field.TypeUUID))
+ )
+ _spec.OnConflict = rc.conflict
+ if id, ok := rc.mutation.ID(); ok {
+ _node.ID = id
+ _spec.ID.Value = &id
+ }
+ if value, ok := rc.mutation.TaskID(); ok {
+ _spec.SetField(record.FieldTaskID, field.TypeString, value)
+ _node.TaskID = value
+ }
+ if value, ok := rc.mutation.ModelType(); ok {
+ _spec.SetField(record.FieldModelType, field.TypeString, value)
+ _node.ModelType = value
+ }
+ if value, ok := rc.mutation.Prompt(); ok {
+ _spec.SetField(record.FieldPrompt, field.TypeString, value)
+ _node.Prompt = value
+ }
+ if value, ok := rc.mutation.Completion(); ok {
+ _spec.SetField(record.FieldCompletion, field.TypeString, value)
+ _node.Completion = value
+ }
+ if value, ok := rc.mutation.IsAccept(); ok {
+ _spec.SetField(record.FieldIsAccept, field.TypeBool, value)
+ _node.IsAccept = value
+ }
+ if value, ok := rc.mutation.ProgramLanguage(); ok {
+ _spec.SetField(record.FieldProgramLanguage, field.TypeString, value)
+ _node.ProgramLanguage = value
+ }
+ if value, ok := rc.mutation.WorkMode(); ok {
+ _spec.SetField(record.FieldWorkMode, field.TypeString, value)
+ _node.WorkMode = value
+ }
+ if value, ok := rc.mutation.CodeLines(); ok {
+ _spec.SetField(record.FieldCodeLines, field.TypeInt64, value)
+ _node.CodeLines = value
+ }
+ if value, ok := rc.mutation.InputTokens(); ok {
+ _spec.SetField(record.FieldInputTokens, field.TypeInt64, value)
+ _node.InputTokens = value
+ }
+ if value, ok := rc.mutation.OutputTokens(); ok {
+ _spec.SetField(record.FieldOutputTokens, field.TypeInt64, value)
+ _node.OutputTokens = value
+ }
+ if value, ok := rc.mutation.CreatedAt(); ok {
+ _spec.SetField(record.FieldCreatedAt, field.TypeTime, value)
+ _node.CreatedAt = value
+ }
+ if value, ok := rc.mutation.UpdatedAt(); ok {
+ _spec.SetField(record.FieldUpdatedAt, field.TypeTime, value)
+ _node.UpdatedAt = value
+ }
+ if nodes := rc.mutation.UserIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: true,
+ Table: record.UserTable,
+ Columns: []string{record.UserColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _node.UserID = nodes[0]
+ _spec.Edges = append(_spec.Edges, edge)
+ }
+ if nodes := rc.mutation.ModelIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: true,
+ Table: record.ModelTable,
+ Columns: []string{record.ModelColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(model.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _node.ModelID = nodes[0]
+ _spec.Edges = append(_spec.Edges, edge)
+ }
+ return _node, _spec
+}
+
+// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
+// of the `INSERT` statement. For example:
+//
+// client.Record.Create().
+// SetUserID(v).
+// OnConflict(
+// // Update the row with the new values
+// // the was proposed for insertion.
+// sql.ResolveWithNewValues(),
+// ).
+// // Override some of the fields with custom
+// // update values.
+// Update(func(u *ent.RecordUpsert) {
+// SetUserID(v+v).
+// }).
+// Exec(ctx)
+func (rc *RecordCreate) OnConflict(opts ...sql.ConflictOption) *RecordUpsertOne {
+ rc.conflict = opts
+ return &RecordUpsertOne{
+ create: rc,
+ }
+}
+
+// OnConflictColumns calls `OnConflict` and configures the columns
+// as conflict target. Using this option is equivalent to using:
+//
+// client.Record.Create().
+// OnConflict(sql.ConflictColumns(columns...)).
+// Exec(ctx)
+func (rc *RecordCreate) OnConflictColumns(columns ...string) *RecordUpsertOne {
+ rc.conflict = append(rc.conflict, sql.ConflictColumns(columns...))
+ return &RecordUpsertOne{
+ create: rc,
+ }
+}
+
+type (
+ // RecordUpsertOne is the builder for "upsert"-ing
+ // one Record node.
+ RecordUpsertOne struct {
+ create *RecordCreate
+ }
+
+ // RecordUpsert is the "OnConflict" setter.
+ RecordUpsert struct {
+ *sql.UpdateSet
+ }
+)
+
+// SetUserID sets the "user_id" field.
+func (u *RecordUpsert) SetUserID(v uuid.UUID) *RecordUpsert {
+ u.Set(record.FieldUserID, v)
+ return u
+}
+
+// UpdateUserID sets the "user_id" field to the value that was provided on create.
+func (u *RecordUpsert) UpdateUserID() *RecordUpsert {
+ u.SetExcluded(record.FieldUserID)
+ return u
+}
+
+// ClearUserID clears the value of the "user_id" field.
+func (u *RecordUpsert) ClearUserID() *RecordUpsert {
+ u.SetNull(record.FieldUserID)
+ return u
+}
+
+// SetModelID sets the "model_id" field.
+func (u *RecordUpsert) SetModelID(v uuid.UUID) *RecordUpsert {
+ u.Set(record.FieldModelID, v)
+ return u
+}
+
+// UpdateModelID sets the "model_id" field to the value that was provided on create.
+func (u *RecordUpsert) UpdateModelID() *RecordUpsert {
+ u.SetExcluded(record.FieldModelID)
+ return u
+}
+
+// ClearModelID clears the value of the "model_id" field.
+func (u *RecordUpsert) ClearModelID() *RecordUpsert {
+ u.SetNull(record.FieldModelID)
+ return u
+}
+
+// SetTaskID sets the "task_id" field.
+func (u *RecordUpsert) SetTaskID(v string) *RecordUpsert {
+ u.Set(record.FieldTaskID, v)
+ return u
+}
+
+// UpdateTaskID sets the "task_id" field to the value that was provided on create.
+func (u *RecordUpsert) UpdateTaskID() *RecordUpsert {
+ u.SetExcluded(record.FieldTaskID)
+ return u
+}
+
+// SetModelType sets the "model_type" field.
+func (u *RecordUpsert) SetModelType(v consts.ModelType) *RecordUpsert {
+ u.Set(record.FieldModelType, v)
+ return u
+}
+
+// UpdateModelType sets the "model_type" field to the value that was provided on create.
+func (u *RecordUpsert) UpdateModelType() *RecordUpsert {
+ u.SetExcluded(record.FieldModelType)
+ return u
+}
+
+// ClearModelType clears the value of the "model_type" field.
+func (u *RecordUpsert) ClearModelType() *RecordUpsert {
+ u.SetNull(record.FieldModelType)
+ return u
+}
+
+// SetPrompt sets the "prompt" field.
+func (u *RecordUpsert) SetPrompt(v string) *RecordUpsert {
+ u.Set(record.FieldPrompt, v)
+ return u
+}
+
+// UpdatePrompt sets the "prompt" field to the value that was provided on create.
+func (u *RecordUpsert) UpdatePrompt() *RecordUpsert {
+ u.SetExcluded(record.FieldPrompt)
+ return u
+}
+
+// ClearPrompt clears the value of the "prompt" field.
+func (u *RecordUpsert) ClearPrompt() *RecordUpsert {
+ u.SetNull(record.FieldPrompt)
+ return u
+}
+
+// SetCompletion sets the "completion" field.
+func (u *RecordUpsert) SetCompletion(v string) *RecordUpsert {
+ u.Set(record.FieldCompletion, v)
+ return u
+}
+
+// UpdateCompletion sets the "completion" field to the value that was provided on create.
+func (u *RecordUpsert) UpdateCompletion() *RecordUpsert {
+ u.SetExcluded(record.FieldCompletion)
+ return u
+}
+
+// ClearCompletion clears the value of the "completion" field.
+func (u *RecordUpsert) ClearCompletion() *RecordUpsert {
+ u.SetNull(record.FieldCompletion)
+ return u
+}
+
+// SetIsAccept sets the "is_accept" field.
+func (u *RecordUpsert) SetIsAccept(v bool) *RecordUpsert {
+ u.Set(record.FieldIsAccept, v)
+ return u
+}
+
+// UpdateIsAccept sets the "is_accept" field to the value that was provided on create.
+func (u *RecordUpsert) UpdateIsAccept() *RecordUpsert {
+ u.SetExcluded(record.FieldIsAccept)
+ return u
+}
+
+// SetProgramLanguage sets the "program_language" field.
+func (u *RecordUpsert) SetProgramLanguage(v string) *RecordUpsert {
+ u.Set(record.FieldProgramLanguage, v)
+ return u
+}
+
+// UpdateProgramLanguage sets the "program_language" field to the value that was provided on create.
+func (u *RecordUpsert) UpdateProgramLanguage() *RecordUpsert {
+ u.SetExcluded(record.FieldProgramLanguage)
+ return u
+}
+
+// ClearProgramLanguage clears the value of the "program_language" field.
+func (u *RecordUpsert) ClearProgramLanguage() *RecordUpsert {
+ u.SetNull(record.FieldProgramLanguage)
+ return u
+}
+
+// SetWorkMode sets the "work_mode" field.
+func (u *RecordUpsert) SetWorkMode(v string) *RecordUpsert {
+ u.Set(record.FieldWorkMode, v)
+ return u
+}
+
+// UpdateWorkMode sets the "work_mode" field to the value that was provided on create.
+func (u *RecordUpsert) UpdateWorkMode() *RecordUpsert {
+ u.SetExcluded(record.FieldWorkMode)
+ return u
+}
+
+// ClearWorkMode clears the value of the "work_mode" field.
+func (u *RecordUpsert) ClearWorkMode() *RecordUpsert {
+ u.SetNull(record.FieldWorkMode)
+ return u
+}
+
+// SetCodeLines sets the "code_lines" field.
+func (u *RecordUpsert) SetCodeLines(v int64) *RecordUpsert {
+ u.Set(record.FieldCodeLines, v)
+ return u
+}
+
+// UpdateCodeLines sets the "code_lines" field to the value that was provided on create.
+func (u *RecordUpsert) UpdateCodeLines() *RecordUpsert {
+ u.SetExcluded(record.FieldCodeLines)
+ return u
+}
+
+// AddCodeLines adds v to the "code_lines" field.
+func (u *RecordUpsert) AddCodeLines(v int64) *RecordUpsert {
+ u.Add(record.FieldCodeLines, v)
+ return u
+}
+
+// ClearCodeLines clears the value of the "code_lines" field.
+func (u *RecordUpsert) ClearCodeLines() *RecordUpsert {
+ u.SetNull(record.FieldCodeLines)
+ return u
+}
+
+// SetInputTokens sets the "input_tokens" field.
+func (u *RecordUpsert) SetInputTokens(v int64) *RecordUpsert {
+ u.Set(record.FieldInputTokens, v)
+ return u
+}
+
+// UpdateInputTokens sets the "input_tokens" field to the value that was provided on create.
+func (u *RecordUpsert) UpdateInputTokens() *RecordUpsert {
+ u.SetExcluded(record.FieldInputTokens)
+ return u
+}
+
+// AddInputTokens adds v to the "input_tokens" field.
+func (u *RecordUpsert) AddInputTokens(v int64) *RecordUpsert {
+ u.Add(record.FieldInputTokens, v)
+ return u
+}
+
+// SetOutputTokens sets the "output_tokens" field.
+func (u *RecordUpsert) SetOutputTokens(v int64) *RecordUpsert {
+ u.Set(record.FieldOutputTokens, v)
+ return u
+}
+
+// UpdateOutputTokens sets the "output_tokens" field to the value that was provided on create.
+func (u *RecordUpsert) UpdateOutputTokens() *RecordUpsert {
+ u.SetExcluded(record.FieldOutputTokens)
+ return u
+}
+
+// AddOutputTokens adds v to the "output_tokens" field.
+func (u *RecordUpsert) AddOutputTokens(v int64) *RecordUpsert {
+ u.Add(record.FieldOutputTokens, v)
+ return u
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (u *RecordUpsert) SetCreatedAt(v time.Time) *RecordUpsert {
+ u.Set(record.FieldCreatedAt, v)
+ return u
+}
+
+// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
+func (u *RecordUpsert) UpdateCreatedAt() *RecordUpsert {
+ u.SetExcluded(record.FieldCreatedAt)
+ return u
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (u *RecordUpsert) SetUpdatedAt(v time.Time) *RecordUpsert {
+ u.Set(record.FieldUpdatedAt, v)
+ return u
+}
+
+// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
+func (u *RecordUpsert) UpdateUpdatedAt() *RecordUpsert {
+ u.SetExcluded(record.FieldUpdatedAt)
+ return u
+}
+
+// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field.
+// Using this option is equivalent to using:
+//
+// client.Record.Create().
+// OnConflict(
+// sql.ResolveWithNewValues(),
+// sql.ResolveWith(func(u *sql.UpdateSet) {
+// u.SetIgnore(record.FieldID)
+// }),
+// ).
+// Exec(ctx)
+func (u *RecordUpsertOne) UpdateNewValues() *RecordUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
+ if _, exists := u.create.mutation.ID(); exists {
+ s.SetIgnore(record.FieldID)
+ }
+ }))
+ return u
+}
+
+// Ignore sets each column to itself in case of conflict.
+// Using this option is equivalent to using:
+//
+// client.Record.Create().
+// OnConflict(sql.ResolveWithIgnore()).
+// Exec(ctx)
+func (u *RecordUpsertOne) Ignore() *RecordUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
+ return u
+}
+
+// DoNothing configures the conflict_action to `DO NOTHING`.
+// Supported only by SQLite and PostgreSQL.
+func (u *RecordUpsertOne) DoNothing() *RecordUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.DoNothing())
+ return u
+}
+
+// Update allows overriding fields `UPDATE` values. See the RecordCreate.OnConflict
+// documentation for more info.
+func (u *RecordUpsertOne) Update(set func(*RecordUpsert)) *RecordUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
+ set(&RecordUpsert{UpdateSet: update})
+ }))
+ return u
+}
+
+// SetUserID sets the "user_id" field.
+func (u *RecordUpsertOne) SetUserID(v uuid.UUID) *RecordUpsertOne {
+ return u.Update(func(s *RecordUpsert) {
+ s.SetUserID(v)
+ })
+}
+
+// UpdateUserID sets the "user_id" field to the value that was provided on create.
+func (u *RecordUpsertOne) UpdateUserID() *RecordUpsertOne {
+ return u.Update(func(s *RecordUpsert) {
+ s.UpdateUserID()
+ })
+}
+
+// ClearUserID clears the value of the "user_id" field.
+func (u *RecordUpsertOne) ClearUserID() *RecordUpsertOne {
+ return u.Update(func(s *RecordUpsert) {
+ s.ClearUserID()
+ })
+}
+
+// SetModelID sets the "model_id" field.
+func (u *RecordUpsertOne) SetModelID(v uuid.UUID) *RecordUpsertOne {
+ return u.Update(func(s *RecordUpsert) {
+ s.SetModelID(v)
+ })
+}
+
+// UpdateModelID sets the "model_id" field to the value that was provided on create.
+func (u *RecordUpsertOne) UpdateModelID() *RecordUpsertOne {
+ return u.Update(func(s *RecordUpsert) {
+ s.UpdateModelID()
+ })
+}
+
+// ClearModelID clears the value of the "model_id" field.
+func (u *RecordUpsertOne) ClearModelID() *RecordUpsertOne {
+ return u.Update(func(s *RecordUpsert) {
+ s.ClearModelID()
+ })
+}
+
+// SetTaskID sets the "task_id" field.
+func (u *RecordUpsertOne) SetTaskID(v string) *RecordUpsertOne {
+ return u.Update(func(s *RecordUpsert) {
+ s.SetTaskID(v)
+ })
+}
+
+// UpdateTaskID sets the "task_id" field to the value that was provided on create.
+func (u *RecordUpsertOne) UpdateTaskID() *RecordUpsertOne {
+ return u.Update(func(s *RecordUpsert) {
+ s.UpdateTaskID()
+ })
+}
+
+// SetModelType sets the "model_type" field.
+func (u *RecordUpsertOne) SetModelType(v consts.ModelType) *RecordUpsertOne {
+ return u.Update(func(s *RecordUpsert) {
+ s.SetModelType(v)
+ })
+}
+
+// UpdateModelType sets the "model_type" field to the value that was provided on create.
+func (u *RecordUpsertOne) UpdateModelType() *RecordUpsertOne {
+ return u.Update(func(s *RecordUpsert) {
+ s.UpdateModelType()
+ })
+}
+
+// ClearModelType clears the value of the "model_type" field.
+func (u *RecordUpsertOne) ClearModelType() *RecordUpsertOne {
+ return u.Update(func(s *RecordUpsert) {
+ s.ClearModelType()
+ })
+}
+
+// SetPrompt sets the "prompt" field.
+func (u *RecordUpsertOne) SetPrompt(v string) *RecordUpsertOne {
+ return u.Update(func(s *RecordUpsert) {
+ s.SetPrompt(v)
+ })
+}
+
+// UpdatePrompt sets the "prompt" field to the value that was provided on create.
+func (u *RecordUpsertOne) UpdatePrompt() *RecordUpsertOne {
+ return u.Update(func(s *RecordUpsert) {
+ s.UpdatePrompt()
+ })
+}
+
+// ClearPrompt clears the value of the "prompt" field.
+func (u *RecordUpsertOne) ClearPrompt() *RecordUpsertOne {
+ return u.Update(func(s *RecordUpsert) {
+ s.ClearPrompt()
+ })
+}
+
+// SetCompletion sets the "completion" field.
+func (u *RecordUpsertOne) SetCompletion(v string) *RecordUpsertOne {
+ return u.Update(func(s *RecordUpsert) {
+ s.SetCompletion(v)
+ })
+}
+
+// UpdateCompletion sets the "completion" field to the value that was provided on create.
+func (u *RecordUpsertOne) UpdateCompletion() *RecordUpsertOne {
+ return u.Update(func(s *RecordUpsert) {
+ s.UpdateCompletion()
+ })
+}
+
+// ClearCompletion clears the value of the "completion" field.
+func (u *RecordUpsertOne) ClearCompletion() *RecordUpsertOne {
+ return u.Update(func(s *RecordUpsert) {
+ s.ClearCompletion()
+ })
+}
+
+// SetIsAccept sets the "is_accept" field.
+func (u *RecordUpsertOne) SetIsAccept(v bool) *RecordUpsertOne {
+ return u.Update(func(s *RecordUpsert) {
+ s.SetIsAccept(v)
+ })
+}
+
+// UpdateIsAccept sets the "is_accept" field to the value that was provided on create.
+func (u *RecordUpsertOne) UpdateIsAccept() *RecordUpsertOne {
+ return u.Update(func(s *RecordUpsert) {
+ s.UpdateIsAccept()
+ })
+}
+
+// SetProgramLanguage sets the "program_language" field.
+func (u *RecordUpsertOne) SetProgramLanguage(v string) *RecordUpsertOne {
+ return u.Update(func(s *RecordUpsert) {
+ s.SetProgramLanguage(v)
+ })
+}
+
+// UpdateProgramLanguage sets the "program_language" field to the value that was provided on create.
+func (u *RecordUpsertOne) UpdateProgramLanguage() *RecordUpsertOne {
+ return u.Update(func(s *RecordUpsert) {
+ s.UpdateProgramLanguage()
+ })
+}
+
+// ClearProgramLanguage clears the value of the "program_language" field.
+func (u *RecordUpsertOne) ClearProgramLanguage() *RecordUpsertOne {
+ return u.Update(func(s *RecordUpsert) {
+ s.ClearProgramLanguage()
+ })
+}
+
+// SetWorkMode sets the "work_mode" field.
+func (u *RecordUpsertOne) SetWorkMode(v string) *RecordUpsertOne {
+ return u.Update(func(s *RecordUpsert) {
+ s.SetWorkMode(v)
+ })
+}
+
+// UpdateWorkMode sets the "work_mode" field to the value that was provided on create.
+func (u *RecordUpsertOne) UpdateWorkMode() *RecordUpsertOne {
+ return u.Update(func(s *RecordUpsert) {
+ s.UpdateWorkMode()
+ })
+}
+
+// ClearWorkMode clears the value of the "work_mode" field.
+func (u *RecordUpsertOne) ClearWorkMode() *RecordUpsertOne {
+ return u.Update(func(s *RecordUpsert) {
+ s.ClearWorkMode()
+ })
+}
+
+// SetCodeLines sets the "code_lines" field.
+func (u *RecordUpsertOne) SetCodeLines(v int64) *RecordUpsertOne {
+ return u.Update(func(s *RecordUpsert) {
+ s.SetCodeLines(v)
+ })
+}
+
+// AddCodeLines adds v to the "code_lines" field.
+func (u *RecordUpsertOne) AddCodeLines(v int64) *RecordUpsertOne {
+ return u.Update(func(s *RecordUpsert) {
+ s.AddCodeLines(v)
+ })
+}
+
+// UpdateCodeLines sets the "code_lines" field to the value that was provided on create.
+func (u *RecordUpsertOne) UpdateCodeLines() *RecordUpsertOne {
+ return u.Update(func(s *RecordUpsert) {
+ s.UpdateCodeLines()
+ })
+}
+
+// ClearCodeLines clears the value of the "code_lines" field.
+func (u *RecordUpsertOne) ClearCodeLines() *RecordUpsertOne {
+ return u.Update(func(s *RecordUpsert) {
+ s.ClearCodeLines()
+ })
+}
+
+// SetInputTokens sets the "input_tokens" field.
+func (u *RecordUpsertOne) SetInputTokens(v int64) *RecordUpsertOne {
+ return u.Update(func(s *RecordUpsert) {
+ s.SetInputTokens(v)
+ })
+}
+
+// AddInputTokens adds v to the "input_tokens" field.
+func (u *RecordUpsertOne) AddInputTokens(v int64) *RecordUpsertOne {
+ return u.Update(func(s *RecordUpsert) {
+ s.AddInputTokens(v)
+ })
+}
+
+// UpdateInputTokens sets the "input_tokens" field to the value that was provided on create.
+func (u *RecordUpsertOne) UpdateInputTokens() *RecordUpsertOne {
+ return u.Update(func(s *RecordUpsert) {
+ s.UpdateInputTokens()
+ })
+}
+
+// SetOutputTokens sets the "output_tokens" field.
+func (u *RecordUpsertOne) SetOutputTokens(v int64) *RecordUpsertOne {
+ return u.Update(func(s *RecordUpsert) {
+ s.SetOutputTokens(v)
+ })
+}
+
+// AddOutputTokens adds v to the "output_tokens" field.
+func (u *RecordUpsertOne) AddOutputTokens(v int64) *RecordUpsertOne {
+ return u.Update(func(s *RecordUpsert) {
+ s.AddOutputTokens(v)
+ })
+}
+
+// UpdateOutputTokens sets the "output_tokens" field to the value that was provided on create.
+func (u *RecordUpsertOne) UpdateOutputTokens() *RecordUpsertOne {
+ return u.Update(func(s *RecordUpsert) {
+ s.UpdateOutputTokens()
+ })
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (u *RecordUpsertOne) SetCreatedAt(v time.Time) *RecordUpsertOne {
+ return u.Update(func(s *RecordUpsert) {
+ s.SetCreatedAt(v)
+ })
+}
+
+// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
+func (u *RecordUpsertOne) UpdateCreatedAt() *RecordUpsertOne {
+ return u.Update(func(s *RecordUpsert) {
+ s.UpdateCreatedAt()
+ })
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (u *RecordUpsertOne) SetUpdatedAt(v time.Time) *RecordUpsertOne {
+ return u.Update(func(s *RecordUpsert) {
+ s.SetUpdatedAt(v)
+ })
+}
+
+// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
+func (u *RecordUpsertOne) UpdateUpdatedAt() *RecordUpsertOne {
+ return u.Update(func(s *RecordUpsert) {
+ s.UpdateUpdatedAt()
+ })
+}
+
+// Exec executes the query.
+func (u *RecordUpsertOne) Exec(ctx context.Context) error {
+ if len(u.create.conflict) == 0 {
+ return errors.New("db: missing options for RecordCreate.OnConflict")
+ }
+ return u.create.Exec(ctx)
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (u *RecordUpsertOne) ExecX(ctx context.Context) {
+ if err := u.create.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// Exec executes the UPSERT query and returns the inserted/updated ID.
+func (u *RecordUpsertOne) ID(ctx context.Context) (id uuid.UUID, err error) {
+ if u.create.driver.Dialect() == dialect.MySQL {
+ // In case of "ON CONFLICT", there is no way to get back non-numeric ID
+ // fields from the database since MySQL does not support the RETURNING clause.
+ return id, errors.New("db: RecordUpsertOne.ID is not supported by MySQL driver. Use RecordUpsertOne.Exec instead")
+ }
+ node, err := u.create.Save(ctx)
+ if err != nil {
+ return id, err
+ }
+ return node.ID, nil
+}
+
+// IDX is like ID, but panics if an error occurs.
+func (u *RecordUpsertOne) IDX(ctx context.Context) uuid.UUID {
+ id, err := u.ID(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return id
+}
+
+// RecordCreateBulk is the builder for creating many Record entities in bulk.
+type RecordCreateBulk struct {
+ config
+ err error
+ builders []*RecordCreate
+ conflict []sql.ConflictOption
+}
+
+// Save creates the Record entities in the database.
+func (rcb *RecordCreateBulk) Save(ctx context.Context) ([]*Record, error) {
+ if rcb.err != nil {
+ return nil, rcb.err
+ }
+ specs := make([]*sqlgraph.CreateSpec, len(rcb.builders))
+ nodes := make([]*Record, len(rcb.builders))
+ mutators := make([]Mutator, len(rcb.builders))
+ for i := range rcb.builders {
+ func(i int, root context.Context) {
+ builder := rcb.builders[i]
+ builder.defaults()
+ var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
+ mutation, ok := m.(*RecordMutation)
+ if !ok {
+ return nil, fmt.Errorf("unexpected mutation type %T", m)
+ }
+ if err := builder.check(); err != nil {
+ return nil, err
+ }
+ builder.mutation = mutation
+ var err error
+ nodes[i], specs[i] = builder.createSpec()
+ if i < len(mutators)-1 {
+ _, err = mutators[i+1].Mutate(root, rcb.builders[i+1].mutation)
+ } else {
+ spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
+ spec.OnConflict = rcb.conflict
+ // Invoke the actual operation on the latest mutation in the chain.
+ if err = sqlgraph.BatchCreate(ctx, rcb.driver, spec); err != nil {
+ if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ }
+ }
+ if err != nil {
+ return nil, err
+ }
+ mutation.id = &nodes[i].ID
+ mutation.done = true
+ return nodes[i], nil
+ })
+ for i := len(builder.hooks) - 1; i >= 0; i-- {
+ mut = builder.hooks[i](mut)
+ }
+ mutators[i] = mut
+ }(i, ctx)
+ }
+ if len(mutators) > 0 {
+ if _, err := mutators[0].Mutate(ctx, rcb.builders[0].mutation); err != nil {
+ return nil, err
+ }
+ }
+ return nodes, nil
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (rcb *RecordCreateBulk) SaveX(ctx context.Context) []*Record {
+ v, err := rcb.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return v
+}
+
+// Exec executes the query.
+func (rcb *RecordCreateBulk) Exec(ctx context.Context) error {
+ _, err := rcb.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (rcb *RecordCreateBulk) ExecX(ctx context.Context) {
+ if err := rcb.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
+// of the `INSERT` statement. For example:
+//
+// client.Record.CreateBulk(builders...).
+// OnConflict(
+// // Update the row with the new values
+// // the was proposed for insertion.
+// sql.ResolveWithNewValues(),
+// ).
+// // Override some of the fields with custom
+// // update values.
+// Update(func(u *ent.RecordUpsert) {
+// SetUserID(v+v).
+// }).
+// Exec(ctx)
+func (rcb *RecordCreateBulk) OnConflict(opts ...sql.ConflictOption) *RecordUpsertBulk {
+ rcb.conflict = opts
+ return &RecordUpsertBulk{
+ create: rcb,
+ }
+}
+
+// OnConflictColumns calls `OnConflict` and configures the columns
+// as conflict target. Using this option is equivalent to using:
+//
+// client.Record.Create().
+// OnConflict(sql.ConflictColumns(columns...)).
+// Exec(ctx)
+func (rcb *RecordCreateBulk) OnConflictColumns(columns ...string) *RecordUpsertBulk {
+ rcb.conflict = append(rcb.conflict, sql.ConflictColumns(columns...))
+ return &RecordUpsertBulk{
+ create: rcb,
+ }
+}
+
+// RecordUpsertBulk is the builder for "upsert"-ing
+// a bulk of Record nodes.
+type RecordUpsertBulk struct {
+ create *RecordCreateBulk
+}
+
+// UpdateNewValues updates the mutable fields using the new values that
+// were set on create. Using this option is equivalent to using:
+//
+// client.Record.Create().
+// OnConflict(
+// sql.ResolveWithNewValues(),
+// sql.ResolveWith(func(u *sql.UpdateSet) {
+// u.SetIgnore(record.FieldID)
+// }),
+// ).
+// Exec(ctx)
+func (u *RecordUpsertBulk) UpdateNewValues() *RecordUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
+ for _, b := range u.create.builders {
+ if _, exists := b.mutation.ID(); exists {
+ s.SetIgnore(record.FieldID)
+ }
+ }
+ }))
+ return u
+}
+
+// Ignore sets each column to itself in case of conflict.
+// Using this option is equivalent to using:
+//
+// client.Record.Create().
+// OnConflict(sql.ResolveWithIgnore()).
+// Exec(ctx)
+func (u *RecordUpsertBulk) Ignore() *RecordUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
+ return u
+}
+
+// DoNothing configures the conflict_action to `DO NOTHING`.
+// Supported only by SQLite and PostgreSQL.
+func (u *RecordUpsertBulk) DoNothing() *RecordUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.DoNothing())
+ return u
+}
+
+// Update allows overriding fields `UPDATE` values. See the RecordCreateBulk.OnConflict
+// documentation for more info.
+func (u *RecordUpsertBulk) Update(set func(*RecordUpsert)) *RecordUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
+ set(&RecordUpsert{UpdateSet: update})
+ }))
+ return u
+}
+
+// SetUserID sets the "user_id" field.
+func (u *RecordUpsertBulk) SetUserID(v uuid.UUID) *RecordUpsertBulk {
+ return u.Update(func(s *RecordUpsert) {
+ s.SetUserID(v)
+ })
+}
+
+// UpdateUserID sets the "user_id" field to the value that was provided on create.
+func (u *RecordUpsertBulk) UpdateUserID() *RecordUpsertBulk {
+ return u.Update(func(s *RecordUpsert) {
+ s.UpdateUserID()
+ })
+}
+
+// ClearUserID clears the value of the "user_id" field.
+func (u *RecordUpsertBulk) ClearUserID() *RecordUpsertBulk {
+ return u.Update(func(s *RecordUpsert) {
+ s.ClearUserID()
+ })
+}
+
+// SetModelID sets the "model_id" field.
+func (u *RecordUpsertBulk) SetModelID(v uuid.UUID) *RecordUpsertBulk {
+ return u.Update(func(s *RecordUpsert) {
+ s.SetModelID(v)
+ })
+}
+
+// UpdateModelID sets the "model_id" field to the value that was provided on create.
+func (u *RecordUpsertBulk) UpdateModelID() *RecordUpsertBulk {
+ return u.Update(func(s *RecordUpsert) {
+ s.UpdateModelID()
+ })
+}
+
+// ClearModelID clears the value of the "model_id" field.
+func (u *RecordUpsertBulk) ClearModelID() *RecordUpsertBulk {
+ return u.Update(func(s *RecordUpsert) {
+ s.ClearModelID()
+ })
+}
+
+// SetTaskID sets the "task_id" field.
+func (u *RecordUpsertBulk) SetTaskID(v string) *RecordUpsertBulk {
+ return u.Update(func(s *RecordUpsert) {
+ s.SetTaskID(v)
+ })
+}
+
+// UpdateTaskID sets the "task_id" field to the value that was provided on create.
+func (u *RecordUpsertBulk) UpdateTaskID() *RecordUpsertBulk {
+ return u.Update(func(s *RecordUpsert) {
+ s.UpdateTaskID()
+ })
+}
+
+// SetModelType sets the "model_type" field.
+func (u *RecordUpsertBulk) SetModelType(v consts.ModelType) *RecordUpsertBulk {
+ return u.Update(func(s *RecordUpsert) {
+ s.SetModelType(v)
+ })
+}
+
+// UpdateModelType sets the "model_type" field to the value that was provided on create.
+func (u *RecordUpsertBulk) UpdateModelType() *RecordUpsertBulk {
+ return u.Update(func(s *RecordUpsert) {
+ s.UpdateModelType()
+ })
+}
+
+// ClearModelType clears the value of the "model_type" field.
+func (u *RecordUpsertBulk) ClearModelType() *RecordUpsertBulk {
+ return u.Update(func(s *RecordUpsert) {
+ s.ClearModelType()
+ })
+}
+
+// SetPrompt sets the "prompt" field.
+func (u *RecordUpsertBulk) SetPrompt(v string) *RecordUpsertBulk {
+ return u.Update(func(s *RecordUpsert) {
+ s.SetPrompt(v)
+ })
+}
+
+// UpdatePrompt sets the "prompt" field to the value that was provided on create.
+func (u *RecordUpsertBulk) UpdatePrompt() *RecordUpsertBulk {
+ return u.Update(func(s *RecordUpsert) {
+ s.UpdatePrompt()
+ })
+}
+
+// ClearPrompt clears the value of the "prompt" field.
+func (u *RecordUpsertBulk) ClearPrompt() *RecordUpsertBulk {
+ return u.Update(func(s *RecordUpsert) {
+ s.ClearPrompt()
+ })
+}
+
+// SetCompletion sets the "completion" field.
+func (u *RecordUpsertBulk) SetCompletion(v string) *RecordUpsertBulk {
+ return u.Update(func(s *RecordUpsert) {
+ s.SetCompletion(v)
+ })
+}
+
+// UpdateCompletion sets the "completion" field to the value that was provided on create.
+func (u *RecordUpsertBulk) UpdateCompletion() *RecordUpsertBulk {
+ return u.Update(func(s *RecordUpsert) {
+ s.UpdateCompletion()
+ })
+}
+
+// ClearCompletion clears the value of the "completion" field.
+func (u *RecordUpsertBulk) ClearCompletion() *RecordUpsertBulk {
+ return u.Update(func(s *RecordUpsert) {
+ s.ClearCompletion()
+ })
+}
+
+// SetIsAccept sets the "is_accept" field.
+func (u *RecordUpsertBulk) SetIsAccept(v bool) *RecordUpsertBulk {
+ return u.Update(func(s *RecordUpsert) {
+ s.SetIsAccept(v)
+ })
+}
+
+// UpdateIsAccept sets the "is_accept" field to the value that was provided on create.
+func (u *RecordUpsertBulk) UpdateIsAccept() *RecordUpsertBulk {
+ return u.Update(func(s *RecordUpsert) {
+ s.UpdateIsAccept()
+ })
+}
+
+// SetProgramLanguage sets the "program_language" field.
+func (u *RecordUpsertBulk) SetProgramLanguage(v string) *RecordUpsertBulk {
+ return u.Update(func(s *RecordUpsert) {
+ s.SetProgramLanguage(v)
+ })
+}
+
+// UpdateProgramLanguage sets the "program_language" field to the value that was provided on create.
+func (u *RecordUpsertBulk) UpdateProgramLanguage() *RecordUpsertBulk {
+ return u.Update(func(s *RecordUpsert) {
+ s.UpdateProgramLanguage()
+ })
+}
+
+// ClearProgramLanguage clears the value of the "program_language" field.
+func (u *RecordUpsertBulk) ClearProgramLanguage() *RecordUpsertBulk {
+ return u.Update(func(s *RecordUpsert) {
+ s.ClearProgramLanguage()
+ })
+}
+
+// SetWorkMode sets the "work_mode" field.
+func (u *RecordUpsertBulk) SetWorkMode(v string) *RecordUpsertBulk {
+ return u.Update(func(s *RecordUpsert) {
+ s.SetWorkMode(v)
+ })
+}
+
+// UpdateWorkMode sets the "work_mode" field to the value that was provided on create.
+func (u *RecordUpsertBulk) UpdateWorkMode() *RecordUpsertBulk {
+ return u.Update(func(s *RecordUpsert) {
+ s.UpdateWorkMode()
+ })
+}
+
+// ClearWorkMode clears the value of the "work_mode" field.
+func (u *RecordUpsertBulk) ClearWorkMode() *RecordUpsertBulk {
+ return u.Update(func(s *RecordUpsert) {
+ s.ClearWorkMode()
+ })
+}
+
+// SetCodeLines sets the "code_lines" field.
+func (u *RecordUpsertBulk) SetCodeLines(v int64) *RecordUpsertBulk {
+ return u.Update(func(s *RecordUpsert) {
+ s.SetCodeLines(v)
+ })
+}
+
+// AddCodeLines adds v to the "code_lines" field.
+func (u *RecordUpsertBulk) AddCodeLines(v int64) *RecordUpsertBulk {
+ return u.Update(func(s *RecordUpsert) {
+ s.AddCodeLines(v)
+ })
+}
+
+// UpdateCodeLines sets the "code_lines" field to the value that was provided on create.
+func (u *RecordUpsertBulk) UpdateCodeLines() *RecordUpsertBulk {
+ return u.Update(func(s *RecordUpsert) {
+ s.UpdateCodeLines()
+ })
+}
+
+// ClearCodeLines clears the value of the "code_lines" field.
+func (u *RecordUpsertBulk) ClearCodeLines() *RecordUpsertBulk {
+ return u.Update(func(s *RecordUpsert) {
+ s.ClearCodeLines()
+ })
+}
+
+// SetInputTokens sets the "input_tokens" field.
+func (u *RecordUpsertBulk) SetInputTokens(v int64) *RecordUpsertBulk {
+ return u.Update(func(s *RecordUpsert) {
+ s.SetInputTokens(v)
+ })
+}
+
+// AddInputTokens adds v to the "input_tokens" field.
+func (u *RecordUpsertBulk) AddInputTokens(v int64) *RecordUpsertBulk {
+ return u.Update(func(s *RecordUpsert) {
+ s.AddInputTokens(v)
+ })
+}
+
+// UpdateInputTokens sets the "input_tokens" field to the value that was provided on create.
+func (u *RecordUpsertBulk) UpdateInputTokens() *RecordUpsertBulk {
+ return u.Update(func(s *RecordUpsert) {
+ s.UpdateInputTokens()
+ })
+}
+
+// SetOutputTokens sets the "output_tokens" field.
+func (u *RecordUpsertBulk) SetOutputTokens(v int64) *RecordUpsertBulk {
+ return u.Update(func(s *RecordUpsert) {
+ s.SetOutputTokens(v)
+ })
+}
+
+// AddOutputTokens adds v to the "output_tokens" field.
+func (u *RecordUpsertBulk) AddOutputTokens(v int64) *RecordUpsertBulk {
+ return u.Update(func(s *RecordUpsert) {
+ s.AddOutputTokens(v)
+ })
+}
+
+// UpdateOutputTokens sets the "output_tokens" field to the value that was provided on create.
+func (u *RecordUpsertBulk) UpdateOutputTokens() *RecordUpsertBulk {
+ return u.Update(func(s *RecordUpsert) {
+ s.UpdateOutputTokens()
+ })
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (u *RecordUpsertBulk) SetCreatedAt(v time.Time) *RecordUpsertBulk {
+ return u.Update(func(s *RecordUpsert) {
+ s.SetCreatedAt(v)
+ })
+}
+
+// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
+func (u *RecordUpsertBulk) UpdateCreatedAt() *RecordUpsertBulk {
+ return u.Update(func(s *RecordUpsert) {
+ s.UpdateCreatedAt()
+ })
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (u *RecordUpsertBulk) SetUpdatedAt(v time.Time) *RecordUpsertBulk {
+ return u.Update(func(s *RecordUpsert) {
+ s.SetUpdatedAt(v)
+ })
+}
+
+// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
+func (u *RecordUpsertBulk) UpdateUpdatedAt() *RecordUpsertBulk {
+ return u.Update(func(s *RecordUpsert) {
+ s.UpdateUpdatedAt()
+ })
+}
+
+// Exec executes the query.
+func (u *RecordUpsertBulk) Exec(ctx context.Context) error {
+ if u.create.err != nil {
+ return u.create.err
+ }
+ for i, b := range u.create.builders {
+ if len(b.conflict) != 0 {
+ return fmt.Errorf("db: OnConflict was set for builder %d. Set it on the RecordCreateBulk instead", i)
+ }
+ }
+ if len(u.create.conflict) == 0 {
+ return errors.New("db: missing options for RecordCreateBulk.OnConflict")
+ }
+ return u.create.Exec(ctx)
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (u *RecordUpsertBulk) ExecX(ctx context.Context) {
+ if err := u.create.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
diff --git a/backend/db/record_delete.go b/backend/db/record_delete.go
new file mode 100644
index 0000000..06aa28b
--- /dev/null
+++ b/backend/db/record_delete.go
@@ -0,0 +1,88 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+ "github.com/chaitin/MonkeyCode/backend/db/record"
+)
+
+// RecordDelete is the builder for deleting a Record entity.
+type RecordDelete struct {
+ config
+ hooks []Hook
+ mutation *RecordMutation
+}
+
+// Where appends a list predicates to the RecordDelete builder.
+func (rd *RecordDelete) Where(ps ...predicate.Record) *RecordDelete {
+ rd.mutation.Where(ps...)
+ return rd
+}
+
+// Exec executes the deletion query and returns how many vertices were deleted.
+func (rd *RecordDelete) Exec(ctx context.Context) (int, error) {
+ return withHooks(ctx, rd.sqlExec, rd.mutation, rd.hooks)
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (rd *RecordDelete) ExecX(ctx context.Context) int {
+ n, err := rd.Exec(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return n
+}
+
+func (rd *RecordDelete) sqlExec(ctx context.Context) (int, error) {
+ _spec := sqlgraph.NewDeleteSpec(record.Table, sqlgraph.NewFieldSpec(record.FieldID, field.TypeUUID))
+ if ps := rd.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ affected, err := sqlgraph.DeleteNodes(ctx, rd.driver, _spec)
+ if err != nil && sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ rd.mutation.done = true
+ return affected, err
+}
+
+// RecordDeleteOne is the builder for deleting a single Record entity.
+type RecordDeleteOne struct {
+ rd *RecordDelete
+}
+
+// Where appends a list predicates to the RecordDelete builder.
+func (rdo *RecordDeleteOne) Where(ps ...predicate.Record) *RecordDeleteOne {
+ rdo.rd.mutation.Where(ps...)
+ return rdo
+}
+
+// Exec executes the deletion query.
+func (rdo *RecordDeleteOne) Exec(ctx context.Context) error {
+ n, err := rdo.rd.Exec(ctx)
+ switch {
+ case err != nil:
+ return err
+ case n == 0:
+ return &NotFoundError{record.Label}
+ default:
+ return nil
+ }
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (rdo *RecordDeleteOne) ExecX(ctx context.Context) {
+ if err := rdo.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
diff --git a/backend/db/record_query.go b/backend/db/record_query.go
new file mode 100644
index 0000000..efb8284
--- /dev/null
+++ b/backend/db/record_query.go
@@ -0,0 +1,732 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "fmt"
+ "math"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect"
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/model"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+ "github.com/chaitin/MonkeyCode/backend/db/record"
+ "github.com/chaitin/MonkeyCode/backend/db/user"
+ "github.com/google/uuid"
+)
+
+// RecordQuery is the builder for querying Record entities.
+type RecordQuery struct {
+ config
+ ctx *QueryContext
+ order []record.OrderOption
+ inters []Interceptor
+ predicates []predicate.Record
+ withUser *UserQuery
+ withModel *ModelQuery
+ modifiers []func(*sql.Selector)
+ // intermediate query (i.e. traversal path).
+ sql *sql.Selector
+ path func(context.Context) (*sql.Selector, error)
+}
+
+// Where adds a new predicate for the RecordQuery builder.
+func (rq *RecordQuery) Where(ps ...predicate.Record) *RecordQuery {
+ rq.predicates = append(rq.predicates, ps...)
+ return rq
+}
+
+// Limit the number of records to be returned by this query.
+func (rq *RecordQuery) Limit(limit int) *RecordQuery {
+ rq.ctx.Limit = &limit
+ return rq
+}
+
+// Offset to start from.
+func (rq *RecordQuery) Offset(offset int) *RecordQuery {
+ rq.ctx.Offset = &offset
+ return rq
+}
+
+// Unique configures the query builder to filter duplicate records on query.
+// By default, unique is set to true, and can be disabled using this method.
+func (rq *RecordQuery) Unique(unique bool) *RecordQuery {
+ rq.ctx.Unique = &unique
+ return rq
+}
+
+// Order specifies how the records should be ordered.
+func (rq *RecordQuery) Order(o ...record.OrderOption) *RecordQuery {
+ rq.order = append(rq.order, o...)
+ return rq
+}
+
+// QueryUser chains the current query on the "user" edge.
+func (rq *RecordQuery) QueryUser() *UserQuery {
+ query := (&UserClient{config: rq.config}).Query()
+ query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
+ if err := rq.prepareQuery(ctx); err != nil {
+ return nil, err
+ }
+ selector := rq.sqlQuery(ctx)
+ if err := selector.Err(); err != nil {
+ return nil, err
+ }
+ step := sqlgraph.NewStep(
+ sqlgraph.From(record.Table, record.FieldID, selector),
+ sqlgraph.To(user.Table, user.FieldID),
+ sqlgraph.Edge(sqlgraph.M2O, true, record.UserTable, record.UserColumn),
+ )
+ fromU = sqlgraph.SetNeighbors(rq.driver.Dialect(), step)
+ return fromU, nil
+ }
+ return query
+}
+
+// QueryModel chains the current query on the "model" edge.
+func (rq *RecordQuery) QueryModel() *ModelQuery {
+ query := (&ModelClient{config: rq.config}).Query()
+ query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
+ if err := rq.prepareQuery(ctx); err != nil {
+ return nil, err
+ }
+ selector := rq.sqlQuery(ctx)
+ if err := selector.Err(); err != nil {
+ return nil, err
+ }
+ step := sqlgraph.NewStep(
+ sqlgraph.From(record.Table, record.FieldID, selector),
+ sqlgraph.To(model.Table, model.FieldID),
+ sqlgraph.Edge(sqlgraph.M2O, true, record.ModelTable, record.ModelColumn),
+ )
+ fromU = sqlgraph.SetNeighbors(rq.driver.Dialect(), step)
+ return fromU, nil
+ }
+ return query
+}
+
+// First returns the first Record entity from the query.
+// Returns a *NotFoundError when no Record was found.
+func (rq *RecordQuery) First(ctx context.Context) (*Record, error) {
+ nodes, err := rq.Limit(1).All(setContextOp(ctx, rq.ctx, ent.OpQueryFirst))
+ if err != nil {
+ return nil, err
+ }
+ if len(nodes) == 0 {
+ return nil, &NotFoundError{record.Label}
+ }
+ return nodes[0], nil
+}
+
+// FirstX is like First, but panics if an error occurs.
+func (rq *RecordQuery) FirstX(ctx context.Context) *Record {
+ node, err := rq.First(ctx)
+ if err != nil && !IsNotFound(err) {
+ panic(err)
+ }
+ return node
+}
+
+// FirstID returns the first Record ID from the query.
+// Returns a *NotFoundError when no Record ID was found.
+func (rq *RecordQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
+ var ids []uuid.UUID
+ if ids, err = rq.Limit(1).IDs(setContextOp(ctx, rq.ctx, ent.OpQueryFirstID)); err != nil {
+ return
+ }
+ if len(ids) == 0 {
+ err = &NotFoundError{record.Label}
+ return
+ }
+ return ids[0], nil
+}
+
+// FirstIDX is like FirstID, but panics if an error occurs.
+func (rq *RecordQuery) FirstIDX(ctx context.Context) uuid.UUID {
+ id, err := rq.FirstID(ctx)
+ if err != nil && !IsNotFound(err) {
+ panic(err)
+ }
+ return id
+}
+
+// Only returns a single Record entity found by the query, ensuring it only returns one.
+// Returns a *NotSingularError when more than one Record entity is found.
+// Returns a *NotFoundError when no Record entities are found.
+func (rq *RecordQuery) Only(ctx context.Context) (*Record, error) {
+ nodes, err := rq.Limit(2).All(setContextOp(ctx, rq.ctx, ent.OpQueryOnly))
+ if err != nil {
+ return nil, err
+ }
+ switch len(nodes) {
+ case 1:
+ return nodes[0], nil
+ case 0:
+ return nil, &NotFoundError{record.Label}
+ default:
+ return nil, &NotSingularError{record.Label}
+ }
+}
+
+// OnlyX is like Only, but panics if an error occurs.
+func (rq *RecordQuery) OnlyX(ctx context.Context) *Record {
+ node, err := rq.Only(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return node
+}
+
+// OnlyID is like Only, but returns the only Record ID in the query.
+// Returns a *NotSingularError when more than one Record ID is found.
+// Returns a *NotFoundError when no entities are found.
+func (rq *RecordQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
+ var ids []uuid.UUID
+ if ids, err = rq.Limit(2).IDs(setContextOp(ctx, rq.ctx, ent.OpQueryOnlyID)); err != nil {
+ return
+ }
+ switch len(ids) {
+ case 1:
+ id = ids[0]
+ case 0:
+ err = &NotFoundError{record.Label}
+ default:
+ err = &NotSingularError{record.Label}
+ }
+ return
+}
+
+// OnlyIDX is like OnlyID, but panics if an error occurs.
+func (rq *RecordQuery) OnlyIDX(ctx context.Context) uuid.UUID {
+ id, err := rq.OnlyID(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return id
+}
+
+// All executes the query and returns a list of Records.
+func (rq *RecordQuery) All(ctx context.Context) ([]*Record, error) {
+ ctx = setContextOp(ctx, rq.ctx, ent.OpQueryAll)
+ if err := rq.prepareQuery(ctx); err != nil {
+ return nil, err
+ }
+ qr := querierAll[[]*Record, *RecordQuery]()
+ return withInterceptors[[]*Record](ctx, rq, qr, rq.inters)
+}
+
+// AllX is like All, but panics if an error occurs.
+func (rq *RecordQuery) AllX(ctx context.Context) []*Record {
+ nodes, err := rq.All(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return nodes
+}
+
+// IDs executes the query and returns a list of Record IDs.
+func (rq *RecordQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) {
+ if rq.ctx.Unique == nil && rq.path != nil {
+ rq.Unique(true)
+ }
+ ctx = setContextOp(ctx, rq.ctx, ent.OpQueryIDs)
+ if err = rq.Select(record.FieldID).Scan(ctx, &ids); err != nil {
+ return nil, err
+ }
+ return ids, nil
+}
+
+// IDsX is like IDs, but panics if an error occurs.
+func (rq *RecordQuery) IDsX(ctx context.Context) []uuid.UUID {
+ ids, err := rq.IDs(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return ids
+}
+
+// Count returns the count of the given query.
+func (rq *RecordQuery) Count(ctx context.Context) (int, error) {
+ ctx = setContextOp(ctx, rq.ctx, ent.OpQueryCount)
+ if err := rq.prepareQuery(ctx); err != nil {
+ return 0, err
+ }
+ return withInterceptors[int](ctx, rq, querierCount[*RecordQuery](), rq.inters)
+}
+
+// CountX is like Count, but panics if an error occurs.
+func (rq *RecordQuery) CountX(ctx context.Context) int {
+ count, err := rq.Count(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return count
+}
+
+// Exist returns true if the query has elements in the graph.
+func (rq *RecordQuery) Exist(ctx context.Context) (bool, error) {
+ ctx = setContextOp(ctx, rq.ctx, ent.OpQueryExist)
+ switch _, err := rq.FirstID(ctx); {
+ case IsNotFound(err):
+ return false, nil
+ case err != nil:
+ return false, fmt.Errorf("db: check existence: %w", err)
+ default:
+ return true, nil
+ }
+}
+
+// ExistX is like Exist, but panics if an error occurs.
+func (rq *RecordQuery) ExistX(ctx context.Context) bool {
+ exist, err := rq.Exist(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return exist
+}
+
+// Clone returns a duplicate of the RecordQuery builder, including all associated steps. It can be
+// used to prepare common query builders and use them differently after the clone is made.
+func (rq *RecordQuery) Clone() *RecordQuery {
+ if rq == nil {
+ return nil
+ }
+ return &RecordQuery{
+ config: rq.config,
+ ctx: rq.ctx.Clone(),
+ order: append([]record.OrderOption{}, rq.order...),
+ inters: append([]Interceptor{}, rq.inters...),
+ predicates: append([]predicate.Record{}, rq.predicates...),
+ withUser: rq.withUser.Clone(),
+ withModel: rq.withModel.Clone(),
+ // clone intermediate query.
+ sql: rq.sql.Clone(),
+ path: rq.path,
+ modifiers: append([]func(*sql.Selector){}, rq.modifiers...),
+ }
+}
+
+// WithUser tells the query-builder to eager-load the nodes that are connected to
+// the "user" edge. The optional arguments are used to configure the query builder of the edge.
+func (rq *RecordQuery) WithUser(opts ...func(*UserQuery)) *RecordQuery {
+ query := (&UserClient{config: rq.config}).Query()
+ for _, opt := range opts {
+ opt(query)
+ }
+ rq.withUser = query
+ return rq
+}
+
+// WithModel tells the query-builder to eager-load the nodes that are connected to
+// the "model" edge. The optional arguments are used to configure the query builder of the edge.
+func (rq *RecordQuery) WithModel(opts ...func(*ModelQuery)) *RecordQuery {
+ query := (&ModelClient{config: rq.config}).Query()
+ for _, opt := range opts {
+ opt(query)
+ }
+ rq.withModel = query
+ return rq
+}
+
+// GroupBy is used to group vertices by one or more fields/columns.
+// It is often used with aggregate functions, like: count, max, mean, min, sum.
+//
+// Example:
+//
+// var v []struct {
+// UserID uuid.UUID `json:"user_id,omitempty"`
+// Count int `json:"count,omitempty"`
+// }
+//
+// client.Record.Query().
+// GroupBy(record.FieldUserID).
+// Aggregate(db.Count()).
+// Scan(ctx, &v)
+func (rq *RecordQuery) GroupBy(field string, fields ...string) *RecordGroupBy {
+ rq.ctx.Fields = append([]string{field}, fields...)
+ grbuild := &RecordGroupBy{build: rq}
+ grbuild.flds = &rq.ctx.Fields
+ grbuild.label = record.Label
+ grbuild.scan = grbuild.Scan
+ return grbuild
+}
+
+// Select allows the selection one or more fields/columns for the given query,
+// instead of selecting all fields in the entity.
+//
+// Example:
+//
+// var v []struct {
+// UserID uuid.UUID `json:"user_id,omitempty"`
+// }
+//
+// client.Record.Query().
+// Select(record.FieldUserID).
+// Scan(ctx, &v)
+func (rq *RecordQuery) Select(fields ...string) *RecordSelect {
+ rq.ctx.Fields = append(rq.ctx.Fields, fields...)
+ sbuild := &RecordSelect{RecordQuery: rq}
+ sbuild.label = record.Label
+ sbuild.flds, sbuild.scan = &rq.ctx.Fields, sbuild.Scan
+ return sbuild
+}
+
+// Aggregate returns a RecordSelect configured with the given aggregations.
+func (rq *RecordQuery) Aggregate(fns ...AggregateFunc) *RecordSelect {
+ return rq.Select().Aggregate(fns...)
+}
+
+func (rq *RecordQuery) prepareQuery(ctx context.Context) error {
+ for _, inter := range rq.inters {
+ if inter == nil {
+ return fmt.Errorf("db: uninitialized interceptor (forgotten import db/runtime?)")
+ }
+ if trv, ok := inter.(Traverser); ok {
+ if err := trv.Traverse(ctx, rq); err != nil {
+ return err
+ }
+ }
+ }
+ for _, f := range rq.ctx.Fields {
+ if !record.ValidColumn(f) {
+ return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
+ }
+ }
+ if rq.path != nil {
+ prev, err := rq.path(ctx)
+ if err != nil {
+ return err
+ }
+ rq.sql = prev
+ }
+ return nil
+}
+
+func (rq *RecordQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Record, error) {
+ var (
+ nodes = []*Record{}
+ _spec = rq.querySpec()
+ loadedTypes = [2]bool{
+ rq.withUser != nil,
+ rq.withModel != nil,
+ }
+ )
+ _spec.ScanValues = func(columns []string) ([]any, error) {
+ return (*Record).scanValues(nil, columns)
+ }
+ _spec.Assign = func(columns []string, values []any) error {
+ node := &Record{config: rq.config}
+ nodes = append(nodes, node)
+ node.Edges.loadedTypes = loadedTypes
+ return node.assignValues(columns, values)
+ }
+ if len(rq.modifiers) > 0 {
+ _spec.Modifiers = rq.modifiers
+ }
+ for i := range hooks {
+ hooks[i](ctx, _spec)
+ }
+ if err := sqlgraph.QueryNodes(ctx, rq.driver, _spec); err != nil {
+ return nil, err
+ }
+ if len(nodes) == 0 {
+ return nodes, nil
+ }
+ if query := rq.withUser; query != nil {
+ if err := rq.loadUser(ctx, query, nodes, nil,
+ func(n *Record, e *User) { n.Edges.User = e }); err != nil {
+ return nil, err
+ }
+ }
+ if query := rq.withModel; query != nil {
+ if err := rq.loadModel(ctx, query, nodes, nil,
+ func(n *Record, e *Model) { n.Edges.Model = e }); err != nil {
+ return nil, err
+ }
+ }
+ return nodes, nil
+}
+
+func (rq *RecordQuery) loadUser(ctx context.Context, query *UserQuery, nodes []*Record, init func(*Record), assign func(*Record, *User)) error {
+ ids := make([]uuid.UUID, 0, len(nodes))
+ nodeids := make(map[uuid.UUID][]*Record)
+ for i := range nodes {
+ fk := nodes[i].UserID
+ if _, ok := nodeids[fk]; !ok {
+ ids = append(ids, fk)
+ }
+ nodeids[fk] = append(nodeids[fk], nodes[i])
+ }
+ if len(ids) == 0 {
+ return nil
+ }
+ query.Where(user.IDIn(ids...))
+ neighbors, err := query.All(ctx)
+ if err != nil {
+ return err
+ }
+ for _, n := range neighbors {
+ nodes, ok := nodeids[n.ID]
+ if !ok {
+ return fmt.Errorf(`unexpected foreign-key "user_id" returned %v`, n.ID)
+ }
+ for i := range nodes {
+ assign(nodes[i], n)
+ }
+ }
+ return nil
+}
+func (rq *RecordQuery) loadModel(ctx context.Context, query *ModelQuery, nodes []*Record, init func(*Record), assign func(*Record, *Model)) error {
+ ids := make([]uuid.UUID, 0, len(nodes))
+ nodeids := make(map[uuid.UUID][]*Record)
+ for i := range nodes {
+ fk := nodes[i].ModelID
+ if _, ok := nodeids[fk]; !ok {
+ ids = append(ids, fk)
+ }
+ nodeids[fk] = append(nodeids[fk], nodes[i])
+ }
+ if len(ids) == 0 {
+ return nil
+ }
+ query.Where(model.IDIn(ids...))
+ neighbors, err := query.All(ctx)
+ if err != nil {
+ return err
+ }
+ for _, n := range neighbors {
+ nodes, ok := nodeids[n.ID]
+ if !ok {
+ return fmt.Errorf(`unexpected foreign-key "model_id" returned %v`, n.ID)
+ }
+ for i := range nodes {
+ assign(nodes[i], n)
+ }
+ }
+ return nil
+}
+
+func (rq *RecordQuery) sqlCount(ctx context.Context) (int, error) {
+ _spec := rq.querySpec()
+ if len(rq.modifiers) > 0 {
+ _spec.Modifiers = rq.modifiers
+ }
+ _spec.Node.Columns = rq.ctx.Fields
+ if len(rq.ctx.Fields) > 0 {
+ _spec.Unique = rq.ctx.Unique != nil && *rq.ctx.Unique
+ }
+ return sqlgraph.CountNodes(ctx, rq.driver, _spec)
+}
+
+func (rq *RecordQuery) querySpec() *sqlgraph.QuerySpec {
+ _spec := sqlgraph.NewQuerySpec(record.Table, record.Columns, sqlgraph.NewFieldSpec(record.FieldID, field.TypeUUID))
+ _spec.From = rq.sql
+ if unique := rq.ctx.Unique; unique != nil {
+ _spec.Unique = *unique
+ } else if rq.path != nil {
+ _spec.Unique = true
+ }
+ if fields := rq.ctx.Fields; len(fields) > 0 {
+ _spec.Node.Columns = make([]string, 0, len(fields))
+ _spec.Node.Columns = append(_spec.Node.Columns, record.FieldID)
+ for i := range fields {
+ if fields[i] != record.FieldID {
+ _spec.Node.Columns = append(_spec.Node.Columns, fields[i])
+ }
+ }
+ if rq.withUser != nil {
+ _spec.Node.AddColumnOnce(record.FieldUserID)
+ }
+ if rq.withModel != nil {
+ _spec.Node.AddColumnOnce(record.FieldModelID)
+ }
+ }
+ if ps := rq.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if limit := rq.ctx.Limit; limit != nil {
+ _spec.Limit = *limit
+ }
+ if offset := rq.ctx.Offset; offset != nil {
+ _spec.Offset = *offset
+ }
+ if ps := rq.order; len(ps) > 0 {
+ _spec.Order = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ return _spec
+}
+
+func (rq *RecordQuery) sqlQuery(ctx context.Context) *sql.Selector {
+ builder := sql.Dialect(rq.driver.Dialect())
+ t1 := builder.Table(record.Table)
+ columns := rq.ctx.Fields
+ if len(columns) == 0 {
+ columns = record.Columns
+ }
+ selector := builder.Select(t1.Columns(columns...)...).From(t1)
+ if rq.sql != nil {
+ selector = rq.sql
+ selector.Select(selector.Columns(columns...)...)
+ }
+ if rq.ctx.Unique != nil && *rq.ctx.Unique {
+ selector.Distinct()
+ }
+ for _, m := range rq.modifiers {
+ m(selector)
+ }
+ for _, p := range rq.predicates {
+ p(selector)
+ }
+ for _, p := range rq.order {
+ p(selector)
+ }
+ if offset := rq.ctx.Offset; offset != nil {
+ // limit is mandatory for offset clause. We start
+ // with default value, and override it below if needed.
+ selector.Offset(*offset).Limit(math.MaxInt32)
+ }
+ if limit := rq.ctx.Limit; limit != nil {
+ selector.Limit(*limit)
+ }
+ return selector
+}
+
+// ForUpdate locks the selected rows against concurrent updates, and prevent them from being
+// updated, deleted or "selected ... for update" by other sessions, until the transaction is
+// either committed or rolled-back.
+func (rq *RecordQuery) ForUpdate(opts ...sql.LockOption) *RecordQuery {
+ if rq.driver.Dialect() == dialect.Postgres {
+ rq.Unique(false)
+ }
+ rq.modifiers = append(rq.modifiers, func(s *sql.Selector) {
+ s.ForUpdate(opts...)
+ })
+ return rq
+}
+
+// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock
+// on any rows that are read. Other sessions can read the rows, but cannot modify them
+// until your transaction commits.
+func (rq *RecordQuery) ForShare(opts ...sql.LockOption) *RecordQuery {
+ if rq.driver.Dialect() == dialect.Postgres {
+ rq.Unique(false)
+ }
+ rq.modifiers = append(rq.modifiers, func(s *sql.Selector) {
+ s.ForShare(opts...)
+ })
+ return rq
+}
+
+// Modify adds a query modifier for attaching custom logic to queries.
+func (rq *RecordQuery) Modify(modifiers ...func(s *sql.Selector)) *RecordSelect {
+ rq.modifiers = append(rq.modifiers, modifiers...)
+ return rq.Select()
+}
+
+// RecordGroupBy is the group-by builder for Record entities.
+type RecordGroupBy struct {
+ selector
+ build *RecordQuery
+}
+
+// Aggregate adds the given aggregation functions to the group-by query.
+func (rgb *RecordGroupBy) Aggregate(fns ...AggregateFunc) *RecordGroupBy {
+ rgb.fns = append(rgb.fns, fns...)
+ return rgb
+}
+
+// Scan applies the selector query and scans the result into the given value.
+func (rgb *RecordGroupBy) Scan(ctx context.Context, v any) error {
+ ctx = setContextOp(ctx, rgb.build.ctx, ent.OpQueryGroupBy)
+ if err := rgb.build.prepareQuery(ctx); err != nil {
+ return err
+ }
+ return scanWithInterceptors[*RecordQuery, *RecordGroupBy](ctx, rgb.build, rgb, rgb.build.inters, v)
+}
+
+func (rgb *RecordGroupBy) sqlScan(ctx context.Context, root *RecordQuery, v any) error {
+ selector := root.sqlQuery(ctx).Select()
+ aggregation := make([]string, 0, len(rgb.fns))
+ for _, fn := range rgb.fns {
+ aggregation = append(aggregation, fn(selector))
+ }
+ if len(selector.SelectedColumns()) == 0 {
+ columns := make([]string, 0, len(*rgb.flds)+len(rgb.fns))
+ for _, f := range *rgb.flds {
+ columns = append(columns, selector.C(f))
+ }
+ columns = append(columns, aggregation...)
+ selector.Select(columns...)
+ }
+ selector.GroupBy(selector.Columns(*rgb.flds...)...)
+ if err := selector.Err(); err != nil {
+ return err
+ }
+ rows := &sql.Rows{}
+ query, args := selector.Query()
+ if err := rgb.build.driver.Query(ctx, query, args, rows); err != nil {
+ return err
+ }
+ defer rows.Close()
+ return sql.ScanSlice(rows, v)
+}
+
+// RecordSelect is the builder for selecting fields of Record entities.
+type RecordSelect struct {
+ *RecordQuery
+ selector
+}
+
+// Aggregate adds the given aggregation functions to the selector query.
+func (rs *RecordSelect) Aggregate(fns ...AggregateFunc) *RecordSelect {
+ rs.fns = append(rs.fns, fns...)
+ return rs
+}
+
+// Scan applies the selector query and scans the result into the given value.
+func (rs *RecordSelect) Scan(ctx context.Context, v any) error {
+ ctx = setContextOp(ctx, rs.ctx, ent.OpQuerySelect)
+ if err := rs.prepareQuery(ctx); err != nil {
+ return err
+ }
+ return scanWithInterceptors[*RecordQuery, *RecordSelect](ctx, rs.RecordQuery, rs, rs.inters, v)
+}
+
+func (rs *RecordSelect) sqlScan(ctx context.Context, root *RecordQuery, v any) error {
+ selector := root.sqlQuery(ctx)
+ aggregation := make([]string, 0, len(rs.fns))
+ for _, fn := range rs.fns {
+ aggregation = append(aggregation, fn(selector))
+ }
+ switch n := len(*rs.selector.flds); {
+ case n == 0 && len(aggregation) > 0:
+ selector.Select(aggregation...)
+ case n != 0 && len(aggregation) > 0:
+ selector.AppendSelect(aggregation...)
+ }
+ rows := &sql.Rows{}
+ query, args := selector.Query()
+ if err := rs.driver.Query(ctx, query, args, rows); err != nil {
+ return err
+ }
+ defer rows.Close()
+ return sql.ScanSlice(rows, v)
+}
+
+// Modify adds a query modifier for attaching custom logic to queries.
+func (rs *RecordSelect) Modify(modifiers ...func(s *sql.Selector)) *RecordSelect {
+ rs.modifiers = append(rs.modifiers, modifiers...)
+ return rs
+}
diff --git a/backend/db/record_update.go b/backend/db/record_update.go
new file mode 100644
index 0000000..edbbbf1
--- /dev/null
+++ b/backend/db/record_update.go
@@ -0,0 +1,1014 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "time"
+
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/consts"
+ "github.com/chaitin/MonkeyCode/backend/db/model"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+ "github.com/chaitin/MonkeyCode/backend/db/record"
+ "github.com/chaitin/MonkeyCode/backend/db/user"
+ "github.com/google/uuid"
+)
+
+// RecordUpdate is the builder for updating Record entities.
+type RecordUpdate struct {
+ config
+ hooks []Hook
+ mutation *RecordMutation
+ modifiers []func(*sql.UpdateBuilder)
+}
+
+// Where appends a list predicates to the RecordUpdate builder.
+func (ru *RecordUpdate) Where(ps ...predicate.Record) *RecordUpdate {
+ ru.mutation.Where(ps...)
+ return ru
+}
+
+// SetUserID sets the "user_id" field.
+func (ru *RecordUpdate) SetUserID(u uuid.UUID) *RecordUpdate {
+ ru.mutation.SetUserID(u)
+ return ru
+}
+
+// SetNillableUserID sets the "user_id" field if the given value is not nil.
+func (ru *RecordUpdate) SetNillableUserID(u *uuid.UUID) *RecordUpdate {
+ if u != nil {
+ ru.SetUserID(*u)
+ }
+ return ru
+}
+
+// ClearUserID clears the value of the "user_id" field.
+func (ru *RecordUpdate) ClearUserID() *RecordUpdate {
+ ru.mutation.ClearUserID()
+ return ru
+}
+
+// SetModelID sets the "model_id" field.
+func (ru *RecordUpdate) SetModelID(u uuid.UUID) *RecordUpdate {
+ ru.mutation.SetModelID(u)
+ return ru
+}
+
+// SetNillableModelID sets the "model_id" field if the given value is not nil.
+func (ru *RecordUpdate) SetNillableModelID(u *uuid.UUID) *RecordUpdate {
+ if u != nil {
+ ru.SetModelID(*u)
+ }
+ return ru
+}
+
+// ClearModelID clears the value of the "model_id" field.
+func (ru *RecordUpdate) ClearModelID() *RecordUpdate {
+ ru.mutation.ClearModelID()
+ return ru
+}
+
+// SetTaskID sets the "task_id" field.
+func (ru *RecordUpdate) SetTaskID(s string) *RecordUpdate {
+ ru.mutation.SetTaskID(s)
+ return ru
+}
+
+// SetNillableTaskID sets the "task_id" field if the given value is not nil.
+func (ru *RecordUpdate) SetNillableTaskID(s *string) *RecordUpdate {
+ if s != nil {
+ ru.SetTaskID(*s)
+ }
+ return ru
+}
+
+// SetModelType sets the "model_type" field.
+func (ru *RecordUpdate) SetModelType(ct consts.ModelType) *RecordUpdate {
+ ru.mutation.SetModelType(ct)
+ return ru
+}
+
+// SetNillableModelType sets the "model_type" field if the given value is not nil.
+func (ru *RecordUpdate) SetNillableModelType(ct *consts.ModelType) *RecordUpdate {
+ if ct != nil {
+ ru.SetModelType(*ct)
+ }
+ return ru
+}
+
+// ClearModelType clears the value of the "model_type" field.
+func (ru *RecordUpdate) ClearModelType() *RecordUpdate {
+ ru.mutation.ClearModelType()
+ return ru
+}
+
+// SetPrompt sets the "prompt" field.
+func (ru *RecordUpdate) SetPrompt(s string) *RecordUpdate {
+ ru.mutation.SetPrompt(s)
+ return ru
+}
+
+// SetNillablePrompt sets the "prompt" field if the given value is not nil.
+func (ru *RecordUpdate) SetNillablePrompt(s *string) *RecordUpdate {
+ if s != nil {
+ ru.SetPrompt(*s)
+ }
+ return ru
+}
+
+// ClearPrompt clears the value of the "prompt" field.
+func (ru *RecordUpdate) ClearPrompt() *RecordUpdate {
+ ru.mutation.ClearPrompt()
+ return ru
+}
+
+// SetCompletion sets the "completion" field.
+func (ru *RecordUpdate) SetCompletion(s string) *RecordUpdate {
+ ru.mutation.SetCompletion(s)
+ return ru
+}
+
+// SetNillableCompletion sets the "completion" field if the given value is not nil.
+func (ru *RecordUpdate) SetNillableCompletion(s *string) *RecordUpdate {
+ if s != nil {
+ ru.SetCompletion(*s)
+ }
+ return ru
+}
+
+// ClearCompletion clears the value of the "completion" field.
+func (ru *RecordUpdate) ClearCompletion() *RecordUpdate {
+ ru.mutation.ClearCompletion()
+ return ru
+}
+
+// SetIsAccept sets the "is_accept" field.
+func (ru *RecordUpdate) SetIsAccept(b bool) *RecordUpdate {
+ ru.mutation.SetIsAccept(b)
+ return ru
+}
+
+// SetNillableIsAccept sets the "is_accept" field if the given value is not nil.
+func (ru *RecordUpdate) SetNillableIsAccept(b *bool) *RecordUpdate {
+ if b != nil {
+ ru.SetIsAccept(*b)
+ }
+ return ru
+}
+
+// SetProgramLanguage sets the "program_language" field.
+func (ru *RecordUpdate) SetProgramLanguage(s string) *RecordUpdate {
+ ru.mutation.SetProgramLanguage(s)
+ return ru
+}
+
+// SetNillableProgramLanguage sets the "program_language" field if the given value is not nil.
+func (ru *RecordUpdate) SetNillableProgramLanguage(s *string) *RecordUpdate {
+ if s != nil {
+ ru.SetProgramLanguage(*s)
+ }
+ return ru
+}
+
+// ClearProgramLanguage clears the value of the "program_language" field.
+func (ru *RecordUpdate) ClearProgramLanguage() *RecordUpdate {
+ ru.mutation.ClearProgramLanguage()
+ return ru
+}
+
+// SetWorkMode sets the "work_mode" field.
+func (ru *RecordUpdate) SetWorkMode(s string) *RecordUpdate {
+ ru.mutation.SetWorkMode(s)
+ return ru
+}
+
+// SetNillableWorkMode sets the "work_mode" field if the given value is not nil.
+func (ru *RecordUpdate) SetNillableWorkMode(s *string) *RecordUpdate {
+ if s != nil {
+ ru.SetWorkMode(*s)
+ }
+ return ru
+}
+
+// ClearWorkMode clears the value of the "work_mode" field.
+func (ru *RecordUpdate) ClearWorkMode() *RecordUpdate {
+ ru.mutation.ClearWorkMode()
+ return ru
+}
+
+// SetCodeLines sets the "code_lines" field.
+func (ru *RecordUpdate) SetCodeLines(i int64) *RecordUpdate {
+ ru.mutation.ResetCodeLines()
+ ru.mutation.SetCodeLines(i)
+ return ru
+}
+
+// SetNillableCodeLines sets the "code_lines" field if the given value is not nil.
+func (ru *RecordUpdate) SetNillableCodeLines(i *int64) *RecordUpdate {
+ if i != nil {
+ ru.SetCodeLines(*i)
+ }
+ return ru
+}
+
+// AddCodeLines adds i to the "code_lines" field.
+func (ru *RecordUpdate) AddCodeLines(i int64) *RecordUpdate {
+ ru.mutation.AddCodeLines(i)
+ return ru
+}
+
+// ClearCodeLines clears the value of the "code_lines" field.
+func (ru *RecordUpdate) ClearCodeLines() *RecordUpdate {
+ ru.mutation.ClearCodeLines()
+ return ru
+}
+
+// SetInputTokens sets the "input_tokens" field.
+func (ru *RecordUpdate) SetInputTokens(i int64) *RecordUpdate {
+ ru.mutation.ResetInputTokens()
+ ru.mutation.SetInputTokens(i)
+ return ru
+}
+
+// SetNillableInputTokens sets the "input_tokens" field if the given value is not nil.
+func (ru *RecordUpdate) SetNillableInputTokens(i *int64) *RecordUpdate {
+ if i != nil {
+ ru.SetInputTokens(*i)
+ }
+ return ru
+}
+
+// AddInputTokens adds i to the "input_tokens" field.
+func (ru *RecordUpdate) AddInputTokens(i int64) *RecordUpdate {
+ ru.mutation.AddInputTokens(i)
+ return ru
+}
+
+// SetOutputTokens sets the "output_tokens" field.
+func (ru *RecordUpdate) SetOutputTokens(i int64) *RecordUpdate {
+ ru.mutation.ResetOutputTokens()
+ ru.mutation.SetOutputTokens(i)
+ return ru
+}
+
+// SetNillableOutputTokens sets the "output_tokens" field if the given value is not nil.
+func (ru *RecordUpdate) SetNillableOutputTokens(i *int64) *RecordUpdate {
+ if i != nil {
+ ru.SetOutputTokens(*i)
+ }
+ return ru
+}
+
+// AddOutputTokens adds i to the "output_tokens" field.
+func (ru *RecordUpdate) AddOutputTokens(i int64) *RecordUpdate {
+ ru.mutation.AddOutputTokens(i)
+ return ru
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (ru *RecordUpdate) SetCreatedAt(t time.Time) *RecordUpdate {
+ ru.mutation.SetCreatedAt(t)
+ return ru
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (ru *RecordUpdate) SetNillableCreatedAt(t *time.Time) *RecordUpdate {
+ if t != nil {
+ ru.SetCreatedAt(*t)
+ }
+ return ru
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (ru *RecordUpdate) SetUpdatedAt(t time.Time) *RecordUpdate {
+ ru.mutation.SetUpdatedAt(t)
+ return ru
+}
+
+// SetUser sets the "user" edge to the User entity.
+func (ru *RecordUpdate) SetUser(u *User) *RecordUpdate {
+ return ru.SetUserID(u.ID)
+}
+
+// SetModel sets the "model" edge to the Model entity.
+func (ru *RecordUpdate) SetModel(m *Model) *RecordUpdate {
+ return ru.SetModelID(m.ID)
+}
+
+// Mutation returns the RecordMutation object of the builder.
+func (ru *RecordUpdate) Mutation() *RecordMutation {
+ return ru.mutation
+}
+
+// ClearUser clears the "user" edge to the User entity.
+func (ru *RecordUpdate) ClearUser() *RecordUpdate {
+ ru.mutation.ClearUser()
+ return ru
+}
+
+// ClearModel clears the "model" edge to the Model entity.
+func (ru *RecordUpdate) ClearModel() *RecordUpdate {
+ ru.mutation.ClearModel()
+ return ru
+}
+
+// Save executes the query and returns the number of nodes affected by the update operation.
+func (ru *RecordUpdate) Save(ctx context.Context) (int, error) {
+ ru.defaults()
+ return withHooks(ctx, ru.sqlSave, ru.mutation, ru.hooks)
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (ru *RecordUpdate) SaveX(ctx context.Context) int {
+ affected, err := ru.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return affected
+}
+
+// Exec executes the query.
+func (ru *RecordUpdate) Exec(ctx context.Context) error {
+ _, err := ru.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (ru *RecordUpdate) ExecX(ctx context.Context) {
+ if err := ru.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// defaults sets the default values of the builder before save.
+func (ru *RecordUpdate) defaults() {
+ if _, ok := ru.mutation.UpdatedAt(); !ok {
+ v := record.UpdateDefaultUpdatedAt()
+ ru.mutation.SetUpdatedAt(v)
+ }
+}
+
+// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
+func (ru *RecordUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *RecordUpdate {
+ ru.modifiers = append(ru.modifiers, modifiers...)
+ return ru
+}
+
+func (ru *RecordUpdate) sqlSave(ctx context.Context) (n int, err error) {
+ _spec := sqlgraph.NewUpdateSpec(record.Table, record.Columns, sqlgraph.NewFieldSpec(record.FieldID, field.TypeUUID))
+ if ps := ru.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if value, ok := ru.mutation.TaskID(); ok {
+ _spec.SetField(record.FieldTaskID, field.TypeString, value)
+ }
+ if value, ok := ru.mutation.ModelType(); ok {
+ _spec.SetField(record.FieldModelType, field.TypeString, value)
+ }
+ if ru.mutation.ModelTypeCleared() {
+ _spec.ClearField(record.FieldModelType, field.TypeString)
+ }
+ if value, ok := ru.mutation.Prompt(); ok {
+ _spec.SetField(record.FieldPrompt, field.TypeString, value)
+ }
+ if ru.mutation.PromptCleared() {
+ _spec.ClearField(record.FieldPrompt, field.TypeString)
+ }
+ if value, ok := ru.mutation.Completion(); ok {
+ _spec.SetField(record.FieldCompletion, field.TypeString, value)
+ }
+ if ru.mutation.CompletionCleared() {
+ _spec.ClearField(record.FieldCompletion, field.TypeString)
+ }
+ if value, ok := ru.mutation.IsAccept(); ok {
+ _spec.SetField(record.FieldIsAccept, field.TypeBool, value)
+ }
+ if value, ok := ru.mutation.ProgramLanguage(); ok {
+ _spec.SetField(record.FieldProgramLanguage, field.TypeString, value)
+ }
+ if ru.mutation.ProgramLanguageCleared() {
+ _spec.ClearField(record.FieldProgramLanguage, field.TypeString)
+ }
+ if value, ok := ru.mutation.WorkMode(); ok {
+ _spec.SetField(record.FieldWorkMode, field.TypeString, value)
+ }
+ if ru.mutation.WorkModeCleared() {
+ _spec.ClearField(record.FieldWorkMode, field.TypeString)
+ }
+ if value, ok := ru.mutation.CodeLines(); ok {
+ _spec.SetField(record.FieldCodeLines, field.TypeInt64, value)
+ }
+ if value, ok := ru.mutation.AddedCodeLines(); ok {
+ _spec.AddField(record.FieldCodeLines, field.TypeInt64, value)
+ }
+ if ru.mutation.CodeLinesCleared() {
+ _spec.ClearField(record.FieldCodeLines, field.TypeInt64)
+ }
+ if value, ok := ru.mutation.InputTokens(); ok {
+ _spec.SetField(record.FieldInputTokens, field.TypeInt64, value)
+ }
+ if value, ok := ru.mutation.AddedInputTokens(); ok {
+ _spec.AddField(record.FieldInputTokens, field.TypeInt64, value)
+ }
+ if value, ok := ru.mutation.OutputTokens(); ok {
+ _spec.SetField(record.FieldOutputTokens, field.TypeInt64, value)
+ }
+ if value, ok := ru.mutation.AddedOutputTokens(); ok {
+ _spec.AddField(record.FieldOutputTokens, field.TypeInt64, value)
+ }
+ if value, ok := ru.mutation.CreatedAt(); ok {
+ _spec.SetField(record.FieldCreatedAt, field.TypeTime, value)
+ }
+ if value, ok := ru.mutation.UpdatedAt(); ok {
+ _spec.SetField(record.FieldUpdatedAt, field.TypeTime, value)
+ }
+ if ru.mutation.UserCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: true,
+ Table: record.UserTable,
+ Columns: []string{record.UserColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID),
+ },
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := ru.mutation.UserIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: true,
+ Table: record.UserTable,
+ Columns: []string{record.UserColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Add = append(_spec.Edges.Add, edge)
+ }
+ if ru.mutation.ModelCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: true,
+ Table: record.ModelTable,
+ Columns: []string{record.ModelColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(model.FieldID, field.TypeUUID),
+ },
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := ru.mutation.ModelIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: true,
+ Table: record.ModelTable,
+ Columns: []string{record.ModelColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(model.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Add = append(_spec.Edges.Add, edge)
+ }
+ _spec.AddModifiers(ru.modifiers...)
+ if n, err = sqlgraph.UpdateNodes(ctx, ru.driver, _spec); err != nil {
+ if _, ok := err.(*sqlgraph.NotFoundError); ok {
+ err = &NotFoundError{record.Label}
+ } else if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return 0, err
+ }
+ ru.mutation.done = true
+ return n, nil
+}
+
+// RecordUpdateOne is the builder for updating a single Record entity.
+type RecordUpdateOne struct {
+ config
+ fields []string
+ hooks []Hook
+ mutation *RecordMutation
+ modifiers []func(*sql.UpdateBuilder)
+}
+
+// SetUserID sets the "user_id" field.
+func (ruo *RecordUpdateOne) SetUserID(u uuid.UUID) *RecordUpdateOne {
+ ruo.mutation.SetUserID(u)
+ return ruo
+}
+
+// SetNillableUserID sets the "user_id" field if the given value is not nil.
+func (ruo *RecordUpdateOne) SetNillableUserID(u *uuid.UUID) *RecordUpdateOne {
+ if u != nil {
+ ruo.SetUserID(*u)
+ }
+ return ruo
+}
+
+// ClearUserID clears the value of the "user_id" field.
+func (ruo *RecordUpdateOne) ClearUserID() *RecordUpdateOne {
+ ruo.mutation.ClearUserID()
+ return ruo
+}
+
+// SetModelID sets the "model_id" field.
+func (ruo *RecordUpdateOne) SetModelID(u uuid.UUID) *RecordUpdateOne {
+ ruo.mutation.SetModelID(u)
+ return ruo
+}
+
+// SetNillableModelID sets the "model_id" field if the given value is not nil.
+func (ruo *RecordUpdateOne) SetNillableModelID(u *uuid.UUID) *RecordUpdateOne {
+ if u != nil {
+ ruo.SetModelID(*u)
+ }
+ return ruo
+}
+
+// ClearModelID clears the value of the "model_id" field.
+func (ruo *RecordUpdateOne) ClearModelID() *RecordUpdateOne {
+ ruo.mutation.ClearModelID()
+ return ruo
+}
+
+// SetTaskID sets the "task_id" field.
+func (ruo *RecordUpdateOne) SetTaskID(s string) *RecordUpdateOne {
+ ruo.mutation.SetTaskID(s)
+ return ruo
+}
+
+// SetNillableTaskID sets the "task_id" field if the given value is not nil.
+func (ruo *RecordUpdateOne) SetNillableTaskID(s *string) *RecordUpdateOne {
+ if s != nil {
+ ruo.SetTaskID(*s)
+ }
+ return ruo
+}
+
+// SetModelType sets the "model_type" field.
+func (ruo *RecordUpdateOne) SetModelType(ct consts.ModelType) *RecordUpdateOne {
+ ruo.mutation.SetModelType(ct)
+ return ruo
+}
+
+// SetNillableModelType sets the "model_type" field if the given value is not nil.
+func (ruo *RecordUpdateOne) SetNillableModelType(ct *consts.ModelType) *RecordUpdateOne {
+ if ct != nil {
+ ruo.SetModelType(*ct)
+ }
+ return ruo
+}
+
+// ClearModelType clears the value of the "model_type" field.
+func (ruo *RecordUpdateOne) ClearModelType() *RecordUpdateOne {
+ ruo.mutation.ClearModelType()
+ return ruo
+}
+
+// SetPrompt sets the "prompt" field.
+func (ruo *RecordUpdateOne) SetPrompt(s string) *RecordUpdateOne {
+ ruo.mutation.SetPrompt(s)
+ return ruo
+}
+
+// SetNillablePrompt sets the "prompt" field if the given value is not nil.
+func (ruo *RecordUpdateOne) SetNillablePrompt(s *string) *RecordUpdateOne {
+ if s != nil {
+ ruo.SetPrompt(*s)
+ }
+ return ruo
+}
+
+// ClearPrompt clears the value of the "prompt" field.
+func (ruo *RecordUpdateOne) ClearPrompt() *RecordUpdateOne {
+ ruo.mutation.ClearPrompt()
+ return ruo
+}
+
+// SetCompletion sets the "completion" field.
+func (ruo *RecordUpdateOne) SetCompletion(s string) *RecordUpdateOne {
+ ruo.mutation.SetCompletion(s)
+ return ruo
+}
+
+// SetNillableCompletion sets the "completion" field if the given value is not nil.
+func (ruo *RecordUpdateOne) SetNillableCompletion(s *string) *RecordUpdateOne {
+ if s != nil {
+ ruo.SetCompletion(*s)
+ }
+ return ruo
+}
+
+// ClearCompletion clears the value of the "completion" field.
+func (ruo *RecordUpdateOne) ClearCompletion() *RecordUpdateOne {
+ ruo.mutation.ClearCompletion()
+ return ruo
+}
+
+// SetIsAccept sets the "is_accept" field.
+func (ruo *RecordUpdateOne) SetIsAccept(b bool) *RecordUpdateOne {
+ ruo.mutation.SetIsAccept(b)
+ return ruo
+}
+
+// SetNillableIsAccept sets the "is_accept" field if the given value is not nil.
+func (ruo *RecordUpdateOne) SetNillableIsAccept(b *bool) *RecordUpdateOne {
+ if b != nil {
+ ruo.SetIsAccept(*b)
+ }
+ return ruo
+}
+
+// SetProgramLanguage sets the "program_language" field.
+func (ruo *RecordUpdateOne) SetProgramLanguage(s string) *RecordUpdateOne {
+ ruo.mutation.SetProgramLanguage(s)
+ return ruo
+}
+
+// SetNillableProgramLanguage sets the "program_language" field if the given value is not nil.
+func (ruo *RecordUpdateOne) SetNillableProgramLanguage(s *string) *RecordUpdateOne {
+ if s != nil {
+ ruo.SetProgramLanguage(*s)
+ }
+ return ruo
+}
+
+// ClearProgramLanguage clears the value of the "program_language" field.
+func (ruo *RecordUpdateOne) ClearProgramLanguage() *RecordUpdateOne {
+ ruo.mutation.ClearProgramLanguage()
+ return ruo
+}
+
+// SetWorkMode sets the "work_mode" field.
+func (ruo *RecordUpdateOne) SetWorkMode(s string) *RecordUpdateOne {
+ ruo.mutation.SetWorkMode(s)
+ return ruo
+}
+
+// SetNillableWorkMode sets the "work_mode" field if the given value is not nil.
+func (ruo *RecordUpdateOne) SetNillableWorkMode(s *string) *RecordUpdateOne {
+ if s != nil {
+ ruo.SetWorkMode(*s)
+ }
+ return ruo
+}
+
+// ClearWorkMode clears the value of the "work_mode" field.
+func (ruo *RecordUpdateOne) ClearWorkMode() *RecordUpdateOne {
+ ruo.mutation.ClearWorkMode()
+ return ruo
+}
+
+// SetCodeLines sets the "code_lines" field.
+func (ruo *RecordUpdateOne) SetCodeLines(i int64) *RecordUpdateOne {
+ ruo.mutation.ResetCodeLines()
+ ruo.mutation.SetCodeLines(i)
+ return ruo
+}
+
+// SetNillableCodeLines sets the "code_lines" field if the given value is not nil.
+func (ruo *RecordUpdateOne) SetNillableCodeLines(i *int64) *RecordUpdateOne {
+ if i != nil {
+ ruo.SetCodeLines(*i)
+ }
+ return ruo
+}
+
+// AddCodeLines adds i to the "code_lines" field.
+func (ruo *RecordUpdateOne) AddCodeLines(i int64) *RecordUpdateOne {
+ ruo.mutation.AddCodeLines(i)
+ return ruo
+}
+
+// ClearCodeLines clears the value of the "code_lines" field.
+func (ruo *RecordUpdateOne) ClearCodeLines() *RecordUpdateOne {
+ ruo.mutation.ClearCodeLines()
+ return ruo
+}
+
+// SetInputTokens sets the "input_tokens" field.
+func (ruo *RecordUpdateOne) SetInputTokens(i int64) *RecordUpdateOne {
+ ruo.mutation.ResetInputTokens()
+ ruo.mutation.SetInputTokens(i)
+ return ruo
+}
+
+// SetNillableInputTokens sets the "input_tokens" field if the given value is not nil.
+func (ruo *RecordUpdateOne) SetNillableInputTokens(i *int64) *RecordUpdateOne {
+ if i != nil {
+ ruo.SetInputTokens(*i)
+ }
+ return ruo
+}
+
+// AddInputTokens adds i to the "input_tokens" field.
+func (ruo *RecordUpdateOne) AddInputTokens(i int64) *RecordUpdateOne {
+ ruo.mutation.AddInputTokens(i)
+ return ruo
+}
+
+// SetOutputTokens sets the "output_tokens" field.
+func (ruo *RecordUpdateOne) SetOutputTokens(i int64) *RecordUpdateOne {
+ ruo.mutation.ResetOutputTokens()
+ ruo.mutation.SetOutputTokens(i)
+ return ruo
+}
+
+// SetNillableOutputTokens sets the "output_tokens" field if the given value is not nil.
+func (ruo *RecordUpdateOne) SetNillableOutputTokens(i *int64) *RecordUpdateOne {
+ if i != nil {
+ ruo.SetOutputTokens(*i)
+ }
+ return ruo
+}
+
+// AddOutputTokens adds i to the "output_tokens" field.
+func (ruo *RecordUpdateOne) AddOutputTokens(i int64) *RecordUpdateOne {
+ ruo.mutation.AddOutputTokens(i)
+ return ruo
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (ruo *RecordUpdateOne) SetCreatedAt(t time.Time) *RecordUpdateOne {
+ ruo.mutation.SetCreatedAt(t)
+ return ruo
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (ruo *RecordUpdateOne) SetNillableCreatedAt(t *time.Time) *RecordUpdateOne {
+ if t != nil {
+ ruo.SetCreatedAt(*t)
+ }
+ return ruo
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (ruo *RecordUpdateOne) SetUpdatedAt(t time.Time) *RecordUpdateOne {
+ ruo.mutation.SetUpdatedAt(t)
+ return ruo
+}
+
+// SetUser sets the "user" edge to the User entity.
+func (ruo *RecordUpdateOne) SetUser(u *User) *RecordUpdateOne {
+ return ruo.SetUserID(u.ID)
+}
+
+// SetModel sets the "model" edge to the Model entity.
+func (ruo *RecordUpdateOne) SetModel(m *Model) *RecordUpdateOne {
+ return ruo.SetModelID(m.ID)
+}
+
+// Mutation returns the RecordMutation object of the builder.
+func (ruo *RecordUpdateOne) Mutation() *RecordMutation {
+ return ruo.mutation
+}
+
+// ClearUser clears the "user" edge to the User entity.
+func (ruo *RecordUpdateOne) ClearUser() *RecordUpdateOne {
+ ruo.mutation.ClearUser()
+ return ruo
+}
+
+// ClearModel clears the "model" edge to the Model entity.
+func (ruo *RecordUpdateOne) ClearModel() *RecordUpdateOne {
+ ruo.mutation.ClearModel()
+ return ruo
+}
+
+// Where appends a list predicates to the RecordUpdate builder.
+func (ruo *RecordUpdateOne) Where(ps ...predicate.Record) *RecordUpdateOne {
+ ruo.mutation.Where(ps...)
+ return ruo
+}
+
+// Select allows selecting one or more fields (columns) of the returned entity.
+// The default is selecting all fields defined in the entity schema.
+func (ruo *RecordUpdateOne) Select(field string, fields ...string) *RecordUpdateOne {
+ ruo.fields = append([]string{field}, fields...)
+ return ruo
+}
+
+// Save executes the query and returns the updated Record entity.
+func (ruo *RecordUpdateOne) Save(ctx context.Context) (*Record, error) {
+ ruo.defaults()
+ return withHooks(ctx, ruo.sqlSave, ruo.mutation, ruo.hooks)
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (ruo *RecordUpdateOne) SaveX(ctx context.Context) *Record {
+ node, err := ruo.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return node
+}
+
+// Exec executes the query on the entity.
+func (ruo *RecordUpdateOne) Exec(ctx context.Context) error {
+ _, err := ruo.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (ruo *RecordUpdateOne) ExecX(ctx context.Context) {
+ if err := ruo.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// defaults sets the default values of the builder before save.
+func (ruo *RecordUpdateOne) defaults() {
+ if _, ok := ruo.mutation.UpdatedAt(); !ok {
+ v := record.UpdateDefaultUpdatedAt()
+ ruo.mutation.SetUpdatedAt(v)
+ }
+}
+
+// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
+func (ruo *RecordUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *RecordUpdateOne {
+ ruo.modifiers = append(ruo.modifiers, modifiers...)
+ return ruo
+}
+
+func (ruo *RecordUpdateOne) sqlSave(ctx context.Context) (_node *Record, err error) {
+ _spec := sqlgraph.NewUpdateSpec(record.Table, record.Columns, sqlgraph.NewFieldSpec(record.FieldID, field.TypeUUID))
+ id, ok := ruo.mutation.ID()
+ if !ok {
+ return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "Record.id" for update`)}
+ }
+ _spec.Node.ID.Value = id
+ if fields := ruo.fields; len(fields) > 0 {
+ _spec.Node.Columns = make([]string, 0, len(fields))
+ _spec.Node.Columns = append(_spec.Node.Columns, record.FieldID)
+ for _, f := range fields {
+ if !record.ValidColumn(f) {
+ return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
+ }
+ if f != record.FieldID {
+ _spec.Node.Columns = append(_spec.Node.Columns, f)
+ }
+ }
+ }
+ if ps := ruo.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if value, ok := ruo.mutation.TaskID(); ok {
+ _spec.SetField(record.FieldTaskID, field.TypeString, value)
+ }
+ if value, ok := ruo.mutation.ModelType(); ok {
+ _spec.SetField(record.FieldModelType, field.TypeString, value)
+ }
+ if ruo.mutation.ModelTypeCleared() {
+ _spec.ClearField(record.FieldModelType, field.TypeString)
+ }
+ if value, ok := ruo.mutation.Prompt(); ok {
+ _spec.SetField(record.FieldPrompt, field.TypeString, value)
+ }
+ if ruo.mutation.PromptCleared() {
+ _spec.ClearField(record.FieldPrompt, field.TypeString)
+ }
+ if value, ok := ruo.mutation.Completion(); ok {
+ _spec.SetField(record.FieldCompletion, field.TypeString, value)
+ }
+ if ruo.mutation.CompletionCleared() {
+ _spec.ClearField(record.FieldCompletion, field.TypeString)
+ }
+ if value, ok := ruo.mutation.IsAccept(); ok {
+ _spec.SetField(record.FieldIsAccept, field.TypeBool, value)
+ }
+ if value, ok := ruo.mutation.ProgramLanguage(); ok {
+ _spec.SetField(record.FieldProgramLanguage, field.TypeString, value)
+ }
+ if ruo.mutation.ProgramLanguageCleared() {
+ _spec.ClearField(record.FieldProgramLanguage, field.TypeString)
+ }
+ if value, ok := ruo.mutation.WorkMode(); ok {
+ _spec.SetField(record.FieldWorkMode, field.TypeString, value)
+ }
+ if ruo.mutation.WorkModeCleared() {
+ _spec.ClearField(record.FieldWorkMode, field.TypeString)
+ }
+ if value, ok := ruo.mutation.CodeLines(); ok {
+ _spec.SetField(record.FieldCodeLines, field.TypeInt64, value)
+ }
+ if value, ok := ruo.mutation.AddedCodeLines(); ok {
+ _spec.AddField(record.FieldCodeLines, field.TypeInt64, value)
+ }
+ if ruo.mutation.CodeLinesCleared() {
+ _spec.ClearField(record.FieldCodeLines, field.TypeInt64)
+ }
+ if value, ok := ruo.mutation.InputTokens(); ok {
+ _spec.SetField(record.FieldInputTokens, field.TypeInt64, value)
+ }
+ if value, ok := ruo.mutation.AddedInputTokens(); ok {
+ _spec.AddField(record.FieldInputTokens, field.TypeInt64, value)
+ }
+ if value, ok := ruo.mutation.OutputTokens(); ok {
+ _spec.SetField(record.FieldOutputTokens, field.TypeInt64, value)
+ }
+ if value, ok := ruo.mutation.AddedOutputTokens(); ok {
+ _spec.AddField(record.FieldOutputTokens, field.TypeInt64, value)
+ }
+ if value, ok := ruo.mutation.CreatedAt(); ok {
+ _spec.SetField(record.FieldCreatedAt, field.TypeTime, value)
+ }
+ if value, ok := ruo.mutation.UpdatedAt(); ok {
+ _spec.SetField(record.FieldUpdatedAt, field.TypeTime, value)
+ }
+ if ruo.mutation.UserCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: true,
+ Table: record.UserTable,
+ Columns: []string{record.UserColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID),
+ },
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := ruo.mutation.UserIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: true,
+ Table: record.UserTable,
+ Columns: []string{record.UserColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Add = append(_spec.Edges.Add, edge)
+ }
+ if ruo.mutation.ModelCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: true,
+ Table: record.ModelTable,
+ Columns: []string{record.ModelColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(model.FieldID, field.TypeUUID),
+ },
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := ruo.mutation.ModelIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: true,
+ Table: record.ModelTable,
+ Columns: []string{record.ModelColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(model.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Add = append(_spec.Edges.Add, edge)
+ }
+ _spec.AddModifiers(ruo.modifiers...)
+ _node = &Record{config: ruo.config}
+ _spec.Assign = _node.assignValues
+ _spec.ScanValues = _node.scanValues
+ if err = sqlgraph.UpdateNode(ctx, ruo.driver, _spec); err != nil {
+ if _, ok := err.(*sqlgraph.NotFoundError); ok {
+ err = &NotFoundError{record.Label}
+ } else if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return nil, err
+ }
+ ruo.mutation.done = true
+ return _node, nil
+}
diff --git a/backend/db/runtime.go b/backend/db/runtime.go
new file mode 100644
index 0000000..2693c25
--- /dev/null
+++ b/backend/db/runtime.go
@@ -0,0 +1,5 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+// The schema-stitching logic is generated in github.com/chaitin/MonkeyCode/backend/db/runtime/runtime.go
diff --git a/backend/db/runtime/runtime.go b/backend/db/runtime/runtime.go
new file mode 100644
index 0000000..9d628bc
--- /dev/null
+++ b/backend/db/runtime/runtime.go
@@ -0,0 +1,222 @@
+// Code generated by ent, DO NOT EDIT.
+
+package runtime
+
+import (
+ "time"
+
+ "github.com/chaitin/MonkeyCode/backend/consts"
+ "github.com/chaitin/MonkeyCode/backend/db/admin"
+ "github.com/chaitin/MonkeyCode/backend/db/adminloginhistory"
+ "github.com/chaitin/MonkeyCode/backend/db/apikey"
+ "github.com/chaitin/MonkeyCode/backend/db/billingplan"
+ "github.com/chaitin/MonkeyCode/backend/db/billingquota"
+ "github.com/chaitin/MonkeyCode/backend/db/billingrecord"
+ "github.com/chaitin/MonkeyCode/backend/db/billingusage"
+ "github.com/chaitin/MonkeyCode/backend/db/invitecode"
+ "github.com/chaitin/MonkeyCode/backend/db/model"
+ "github.com/chaitin/MonkeyCode/backend/db/record"
+ "github.com/chaitin/MonkeyCode/backend/db/setting"
+ "github.com/chaitin/MonkeyCode/backend/db/user"
+ "github.com/chaitin/MonkeyCode/backend/db/userloginhistory"
+ "github.com/chaitin/MonkeyCode/backend/ent/schema"
+)
+
+// The init function reads all schema descriptors with runtime code
+// (default values, validators, hooks and policies) and stitches it
+// to their package variables.
+func init() {
+ adminFields := schema.Admin{}.Fields()
+ _ = adminFields
+ // adminDescLastActiveAt is the schema descriptor for last_active_at field.
+ adminDescLastActiveAt := adminFields[4].Descriptor()
+ // admin.DefaultLastActiveAt holds the default value on creation for the last_active_at field.
+ admin.DefaultLastActiveAt = adminDescLastActiveAt.Default.(func() time.Time)
+ // adminDescCreatedAt is the schema descriptor for created_at field.
+ adminDescCreatedAt := adminFields[5].Descriptor()
+ // admin.DefaultCreatedAt holds the default value on creation for the created_at field.
+ admin.DefaultCreatedAt = adminDescCreatedAt.Default.(func() time.Time)
+ // adminDescUpdatedAt is the schema descriptor for updated_at field.
+ adminDescUpdatedAt := adminFields[6].Descriptor()
+ // admin.DefaultUpdatedAt holds the default value on creation for the updated_at field.
+ admin.DefaultUpdatedAt = adminDescUpdatedAt.Default.(func() time.Time)
+ // admin.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
+ admin.UpdateDefaultUpdatedAt = adminDescUpdatedAt.UpdateDefault.(func() time.Time)
+ adminloginhistoryFields := schema.AdminLoginHistory{}.Fields()
+ _ = adminloginhistoryFields
+ // adminloginhistoryDescCreatedAt is the schema descriptor for created_at field.
+ adminloginhistoryDescCreatedAt := adminloginhistoryFields[10].Descriptor()
+ // adminloginhistory.DefaultCreatedAt holds the default value on creation for the created_at field.
+ adminloginhistory.DefaultCreatedAt = adminloginhistoryDescCreatedAt.Default.(func() time.Time)
+ apikeyFields := schema.ApiKey{}.Fields()
+ _ = apikeyFields
+ // apikeyDescStatus is the schema descriptor for status field.
+ apikeyDescStatus := apikeyFields[4].Descriptor()
+ // apikey.DefaultStatus holds the default value on creation for the status field.
+ apikey.DefaultStatus = consts.ApiKeyStatus(apikeyDescStatus.Default.(string))
+ // apikeyDescCreatedAt is the schema descriptor for created_at field.
+ apikeyDescCreatedAt := apikeyFields[6].Descriptor()
+ // apikey.DefaultCreatedAt holds the default value on creation for the created_at field.
+ apikey.DefaultCreatedAt = apikeyDescCreatedAt.Default.(func() time.Time)
+ // apikeyDescUpdatedAt is the schema descriptor for updated_at field.
+ apikeyDescUpdatedAt := apikeyFields[7].Descriptor()
+ // apikey.DefaultUpdatedAt holds the default value on creation for the updated_at field.
+ apikey.DefaultUpdatedAt = apikeyDescUpdatedAt.Default.(func() time.Time)
+ // apikey.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
+ apikey.UpdateDefaultUpdatedAt = apikeyDescUpdatedAt.UpdateDefault.(func() time.Time)
+ billingplanFields := schema.BillingPlan{}.Fields()
+ _ = billingplanFields
+ // billingplanDescCreatedAt is the schema descriptor for created_at field.
+ billingplanDescCreatedAt := billingplanFields[4].Descriptor()
+ // billingplan.DefaultCreatedAt holds the default value on creation for the created_at field.
+ billingplan.DefaultCreatedAt = billingplanDescCreatedAt.Default.(func() time.Time)
+ // billingplanDescUpdatedAt is the schema descriptor for updated_at field.
+ billingplanDescUpdatedAt := billingplanFields[5].Descriptor()
+ // billingplan.DefaultUpdatedAt holds the default value on creation for the updated_at field.
+ billingplan.DefaultUpdatedAt = billingplanDescUpdatedAt.Default.(func() time.Time)
+ // billingplan.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
+ billingplan.UpdateDefaultUpdatedAt = billingplanDescUpdatedAt.UpdateDefault.(func() time.Time)
+ billingquotaMixin := schema.BillingQuota{}.Mixin()
+ billingquotaMixinHooks0 := billingquotaMixin[0].Hooks()
+ billingquota.Hooks[0] = billingquotaMixinHooks0[0]
+ billingquotaMixinInters0 := billingquotaMixin[0].Interceptors()
+ billingquota.Interceptors[0] = billingquotaMixinInters0[0]
+ billingquotaFields := schema.BillingQuota{}.Fields()
+ _ = billingquotaFields
+ // billingquotaDescCreatedAt is the schema descriptor for created_at field.
+ billingquotaDescCreatedAt := billingquotaFields[5].Descriptor()
+ // billingquota.DefaultCreatedAt holds the default value on creation for the created_at field.
+ billingquota.DefaultCreatedAt = billingquotaDescCreatedAt.Default.(func() time.Time)
+ // billingquotaDescUpdatedAt is the schema descriptor for updated_at field.
+ billingquotaDescUpdatedAt := billingquotaFields[6].Descriptor()
+ // billingquota.DefaultUpdatedAt holds the default value on creation for the updated_at field.
+ billingquota.DefaultUpdatedAt = billingquotaDescUpdatedAt.Default.(func() time.Time)
+ // billingquota.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
+ billingquota.UpdateDefaultUpdatedAt = billingquotaDescUpdatedAt.UpdateDefault.(func() time.Time)
+ billingrecordFields := schema.BillingRecord{}.Fields()
+ _ = billingrecordFields
+ // billingrecordDescRequestTime is the schema descriptor for request_time field.
+ billingrecordDescRequestTime := billingrecordFields[8].Descriptor()
+ // billingrecord.DefaultRequestTime holds the default value on creation for the request_time field.
+ billingrecord.DefaultRequestTime = billingrecordDescRequestTime.Default.(func() time.Time)
+ // billingrecordDescCreatedAt is the schema descriptor for created_at field.
+ billingrecordDescCreatedAt := billingrecordFields[10].Descriptor()
+ // billingrecord.DefaultCreatedAt holds the default value on creation for the created_at field.
+ billingrecord.DefaultCreatedAt = billingrecordDescCreatedAt.Default.(func() time.Time)
+ // billingrecordDescUpdatedAt is the schema descriptor for updated_at field.
+ billingrecordDescUpdatedAt := billingrecordFields[11].Descriptor()
+ // billingrecord.DefaultUpdatedAt holds the default value on creation for the updated_at field.
+ billingrecord.DefaultUpdatedAt = billingrecordDescUpdatedAt.Default.(func() time.Time)
+ // billingrecord.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
+ billingrecord.UpdateDefaultUpdatedAt = billingrecordDescUpdatedAt.UpdateDefault.(func() time.Time)
+ billingusageMixin := schema.BillingUsage{}.Mixin()
+ billingusageMixinHooks0 := billingusageMixin[0].Hooks()
+ billingusage.Hooks[0] = billingusageMixinHooks0[0]
+ billingusageMixinInters0 := billingusageMixin[0].Interceptors()
+ billingusage.Interceptors[0] = billingusageMixinInters0[0]
+ billingusageFields := schema.BillingUsage{}.Fields()
+ _ = billingusageFields
+ // billingusageDescCreatedAt is the schema descriptor for created_at field.
+ billingusageDescCreatedAt := billingusageFields[5].Descriptor()
+ // billingusage.DefaultCreatedAt holds the default value on creation for the created_at field.
+ billingusage.DefaultCreatedAt = billingusageDescCreatedAt.Default.(func() time.Time)
+ // billingusageDescUpdatedAt is the schema descriptor for updated_at field.
+ billingusageDescUpdatedAt := billingusageFields[6].Descriptor()
+ // billingusage.DefaultUpdatedAt holds the default value on creation for the updated_at field.
+ billingusage.DefaultUpdatedAt = billingusageDescUpdatedAt.Default.(func() time.Time)
+ // billingusage.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
+ billingusage.UpdateDefaultUpdatedAt = billingusageDescUpdatedAt.UpdateDefault.(func() time.Time)
+ invitecodeFields := schema.InviteCode{}.Fields()
+ _ = invitecodeFields
+ // invitecodeDescCreatedAt is the schema descriptor for created_at field.
+ invitecodeDescCreatedAt := invitecodeFields[3].Descriptor()
+ // invitecode.DefaultCreatedAt holds the default value on creation for the created_at field.
+ invitecode.DefaultCreatedAt = invitecodeDescCreatedAt.Default.(func() time.Time)
+ // invitecodeDescUpdatedAt is the schema descriptor for updated_at field.
+ invitecodeDescUpdatedAt := invitecodeFields[4].Descriptor()
+ // invitecode.DefaultUpdatedAt holds the default value on creation for the updated_at field.
+ invitecode.DefaultUpdatedAt = invitecodeDescUpdatedAt.Default.(func() time.Time)
+ // invitecode.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
+ invitecode.UpdateDefaultUpdatedAt = invitecodeDescUpdatedAt.UpdateDefault.(func() time.Time)
+ modelFields := schema.Model{}.Fields()
+ _ = modelFields
+ // modelDescStatus is the schema descriptor for status field.
+ modelDescStatus := modelFields[9].Descriptor()
+ // model.DefaultStatus holds the default value on creation for the status field.
+ model.DefaultStatus = consts.ModelStatus(modelDescStatus.Default.(string))
+ // modelDescCreatedAt is the schema descriptor for created_at field.
+ modelDescCreatedAt := modelFields[11].Descriptor()
+ // model.DefaultCreatedAt holds the default value on creation for the created_at field.
+ model.DefaultCreatedAt = modelDescCreatedAt.Default.(func() time.Time)
+ // modelDescUpdatedAt is the schema descriptor for updated_at field.
+ modelDescUpdatedAt := modelFields[12].Descriptor()
+ // model.DefaultUpdatedAt holds the default value on creation for the updated_at field.
+ model.DefaultUpdatedAt = modelDescUpdatedAt.Default.(func() time.Time)
+ // model.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
+ model.UpdateDefaultUpdatedAt = modelDescUpdatedAt.UpdateDefault.(func() time.Time)
+ recordFields := schema.Record{}.Fields()
+ _ = recordFields
+ // recordDescIsAccept is the schema descriptor for is_accept field.
+ recordDescIsAccept := recordFields[7].Descriptor()
+ // record.DefaultIsAccept holds the default value on creation for the is_accept field.
+ record.DefaultIsAccept = recordDescIsAccept.Default.(bool)
+ // recordDescCreatedAt is the schema descriptor for created_at field.
+ recordDescCreatedAt := recordFields[13].Descriptor()
+ // record.DefaultCreatedAt holds the default value on creation for the created_at field.
+ record.DefaultCreatedAt = recordDescCreatedAt.Default.(func() time.Time)
+ // recordDescUpdatedAt is the schema descriptor for updated_at field.
+ recordDescUpdatedAt := recordFields[14].Descriptor()
+ // record.DefaultUpdatedAt holds the default value on creation for the updated_at field.
+ record.DefaultUpdatedAt = recordDescUpdatedAt.Default.(func() time.Time)
+ // record.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
+ record.UpdateDefaultUpdatedAt = recordDescUpdatedAt.UpdateDefault.(func() time.Time)
+ settingFields := schema.Setting{}.Fields()
+ _ = settingFields
+ // settingDescEnableSSO is the schema descriptor for enable_sso field.
+ settingDescEnableSSO := settingFields[1].Descriptor()
+ // setting.DefaultEnableSSO holds the default value on creation for the enable_sso field.
+ setting.DefaultEnableSSO = settingDescEnableSSO.Default.(bool)
+ // settingDescForceTwoFactorAuth is the schema descriptor for force_two_factor_auth field.
+ settingDescForceTwoFactorAuth := settingFields[2].Descriptor()
+ // setting.DefaultForceTwoFactorAuth holds the default value on creation for the force_two_factor_auth field.
+ setting.DefaultForceTwoFactorAuth = settingDescForceTwoFactorAuth.Default.(bool)
+ // settingDescDisablePasswordLogin is the schema descriptor for disable_password_login field.
+ settingDescDisablePasswordLogin := settingFields[3].Descriptor()
+ // setting.DefaultDisablePasswordLogin holds the default value on creation for the disable_password_login field.
+ setting.DefaultDisablePasswordLogin = settingDescDisablePasswordLogin.Default.(bool)
+ // settingDescCreatedAt is the schema descriptor for created_at field.
+ settingDescCreatedAt := settingFields[4].Descriptor()
+ // setting.DefaultCreatedAt holds the default value on creation for the created_at field.
+ setting.DefaultCreatedAt = settingDescCreatedAt.Default.(func() time.Time)
+ // settingDescUpdatedAt is the schema descriptor for updated_at field.
+ settingDescUpdatedAt := settingFields[5].Descriptor()
+ // setting.DefaultUpdatedAt holds the default value on creation for the updated_at field.
+ setting.DefaultUpdatedAt = settingDescUpdatedAt.Default.(func() time.Time)
+ // setting.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
+ setting.UpdateDefaultUpdatedAt = settingDescUpdatedAt.UpdateDefault.(func() time.Time)
+ userFields := schema.User{}.Fields()
+ _ = userFields
+ // userDescStatus is the schema descriptor for status field.
+ userDescStatus := userFields[4].Descriptor()
+ // user.DefaultStatus holds the default value on creation for the status field.
+ user.DefaultStatus = consts.UserStatus(userDescStatus.Default.(string))
+ // userDescCreatedAt is the schema descriptor for created_at field.
+ userDescCreatedAt := userFields[5].Descriptor()
+ // user.DefaultCreatedAt holds the default value on creation for the created_at field.
+ user.DefaultCreatedAt = userDescCreatedAt.Default.(func() time.Time)
+ // userDescUpdatedAt is the schema descriptor for updated_at field.
+ userDescUpdatedAt := userFields[6].Descriptor()
+ // user.DefaultUpdatedAt holds the default value on creation for the updated_at field.
+ user.DefaultUpdatedAt = userDescUpdatedAt.Default.(func() time.Time)
+ userloginhistoryFields := schema.UserLoginHistory{}.Fields()
+ _ = userloginhistoryFields
+ // userloginhistoryDescCreatedAt is the schema descriptor for created_at field.
+ userloginhistoryDescCreatedAt := userloginhistoryFields[10].Descriptor()
+ // userloginhistory.DefaultCreatedAt holds the default value on creation for the created_at field.
+ userloginhistory.DefaultCreatedAt = userloginhistoryDescCreatedAt.Default.(func() time.Time)
+}
+
+const (
+ Version = "v0.14.4" // Version of ent codegen.
+ Sum = "h1:/DhDraSLXIkBhyiVoJeSshr4ZYi7femzhj6/TckzZuI=" // Sum of ent codegen.
+)
diff --git a/backend/db/setting.go b/backend/db/setting.go
new file mode 100644
index 0000000..5f845cb
--- /dev/null
+++ b/backend/db/setting.go
@@ -0,0 +1,151 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "fmt"
+ "strings"
+ "time"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect/sql"
+ "github.com/chaitin/MonkeyCode/backend/db/setting"
+ "github.com/google/uuid"
+)
+
+// Setting is the model entity for the Setting schema.
+type Setting struct {
+ config `json:"-"`
+ // ID of the ent.
+ ID uuid.UUID `json:"id,omitempty"`
+ // EnableSSO holds the value of the "enable_sso" field.
+ EnableSSO bool `json:"enable_sso,omitempty"`
+ // ForceTwoFactorAuth holds the value of the "force_two_factor_auth" field.
+ ForceTwoFactorAuth bool `json:"force_two_factor_auth,omitempty"`
+ // DisablePasswordLogin holds the value of the "disable_password_login" field.
+ DisablePasswordLogin bool `json:"disable_password_login,omitempty"`
+ // CreatedAt holds the value of the "created_at" field.
+ CreatedAt time.Time `json:"created_at,omitempty"`
+ // UpdatedAt holds the value of the "updated_at" field.
+ UpdatedAt time.Time `json:"updated_at,omitempty"`
+ selectValues sql.SelectValues
+}
+
+// scanValues returns the types for scanning values from sql.Rows.
+func (*Setting) scanValues(columns []string) ([]any, error) {
+ values := make([]any, len(columns))
+ for i := range columns {
+ switch columns[i] {
+ case setting.FieldEnableSSO, setting.FieldForceTwoFactorAuth, setting.FieldDisablePasswordLogin:
+ values[i] = new(sql.NullBool)
+ case setting.FieldCreatedAt, setting.FieldUpdatedAt:
+ values[i] = new(sql.NullTime)
+ case setting.FieldID:
+ values[i] = new(uuid.UUID)
+ default:
+ values[i] = new(sql.UnknownType)
+ }
+ }
+ return values, nil
+}
+
+// assignValues assigns the values that were returned from sql.Rows (after scanning)
+// to the Setting fields.
+func (s *Setting) assignValues(columns []string, values []any) error {
+ if m, n := len(values), len(columns); m < n {
+ return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
+ }
+ for i := range columns {
+ switch columns[i] {
+ case setting.FieldID:
+ if value, ok := values[i].(*uuid.UUID); !ok {
+ return fmt.Errorf("unexpected type %T for field id", values[i])
+ } else if value != nil {
+ s.ID = *value
+ }
+ case setting.FieldEnableSSO:
+ if value, ok := values[i].(*sql.NullBool); !ok {
+ return fmt.Errorf("unexpected type %T for field enable_sso", values[i])
+ } else if value.Valid {
+ s.EnableSSO = value.Bool
+ }
+ case setting.FieldForceTwoFactorAuth:
+ if value, ok := values[i].(*sql.NullBool); !ok {
+ return fmt.Errorf("unexpected type %T for field force_two_factor_auth", values[i])
+ } else if value.Valid {
+ s.ForceTwoFactorAuth = value.Bool
+ }
+ case setting.FieldDisablePasswordLogin:
+ if value, ok := values[i].(*sql.NullBool); !ok {
+ return fmt.Errorf("unexpected type %T for field disable_password_login", values[i])
+ } else if value.Valid {
+ s.DisablePasswordLogin = value.Bool
+ }
+ case setting.FieldCreatedAt:
+ if value, ok := values[i].(*sql.NullTime); !ok {
+ return fmt.Errorf("unexpected type %T for field created_at", values[i])
+ } else if value.Valid {
+ s.CreatedAt = value.Time
+ }
+ case setting.FieldUpdatedAt:
+ if value, ok := values[i].(*sql.NullTime); !ok {
+ return fmt.Errorf("unexpected type %T for field updated_at", values[i])
+ } else if value.Valid {
+ s.UpdatedAt = value.Time
+ }
+ default:
+ s.selectValues.Set(columns[i], values[i])
+ }
+ }
+ return nil
+}
+
+// Value returns the ent.Value that was dynamically selected and assigned to the Setting.
+// This includes values selected through modifiers, order, etc.
+func (s *Setting) Value(name string) (ent.Value, error) {
+ return s.selectValues.Get(name)
+}
+
+// Update returns a builder for updating this Setting.
+// Note that you need to call Setting.Unwrap() before calling this method if this Setting
+// was returned from a transaction, and the transaction was committed or rolled back.
+func (s *Setting) Update() *SettingUpdateOne {
+ return NewSettingClient(s.config).UpdateOne(s)
+}
+
+// Unwrap unwraps the Setting entity that was returned from a transaction after it was closed,
+// so that all future queries will be executed through the driver which created the transaction.
+func (s *Setting) Unwrap() *Setting {
+ _tx, ok := s.config.driver.(*txDriver)
+ if !ok {
+ panic("db: Setting is not a transactional entity")
+ }
+ s.config.driver = _tx.drv
+ return s
+}
+
+// String implements the fmt.Stringer.
+func (s *Setting) String() string {
+ var builder strings.Builder
+ builder.WriteString("Setting(")
+ builder.WriteString(fmt.Sprintf("id=%v, ", s.ID))
+ builder.WriteString("enable_sso=")
+ builder.WriteString(fmt.Sprintf("%v", s.EnableSSO))
+ builder.WriteString(", ")
+ builder.WriteString("force_two_factor_auth=")
+ builder.WriteString(fmt.Sprintf("%v", s.ForceTwoFactorAuth))
+ builder.WriteString(", ")
+ builder.WriteString("disable_password_login=")
+ builder.WriteString(fmt.Sprintf("%v", s.DisablePasswordLogin))
+ builder.WriteString(", ")
+ builder.WriteString("created_at=")
+ builder.WriteString(s.CreatedAt.Format(time.ANSIC))
+ builder.WriteString(", ")
+ builder.WriteString("updated_at=")
+ builder.WriteString(s.UpdatedAt.Format(time.ANSIC))
+ builder.WriteByte(')')
+ return builder.String()
+}
+
+// Settings is a parsable slice of Setting.
+type Settings []*Setting
diff --git a/backend/db/setting/setting.go b/backend/db/setting/setting.go
new file mode 100644
index 0000000..3f036a2
--- /dev/null
+++ b/backend/db/setting/setting.go
@@ -0,0 +1,96 @@
+// Code generated by ent, DO NOT EDIT.
+
+package setting
+
+import (
+ "time"
+
+ "entgo.io/ent/dialect/sql"
+)
+
+const (
+ // Label holds the string label denoting the setting type in the database.
+ Label = "setting"
+ // FieldID holds the string denoting the id field in the database.
+ FieldID = "id"
+ // FieldEnableSSO holds the string denoting the enable_sso field in the database.
+ FieldEnableSSO = "enable_sso"
+ // FieldForceTwoFactorAuth holds the string denoting the force_two_factor_auth field in the database.
+ FieldForceTwoFactorAuth = "force_two_factor_auth"
+ // FieldDisablePasswordLogin holds the string denoting the disable_password_login field in the database.
+ FieldDisablePasswordLogin = "disable_password_login"
+ // FieldCreatedAt holds the string denoting the created_at field in the database.
+ FieldCreatedAt = "created_at"
+ // FieldUpdatedAt holds the string denoting the updated_at field in the database.
+ FieldUpdatedAt = "updated_at"
+ // Table holds the table name of the setting in the database.
+ Table = "settings"
+)
+
+// Columns holds all SQL columns for setting fields.
+var Columns = []string{
+ FieldID,
+ FieldEnableSSO,
+ FieldForceTwoFactorAuth,
+ FieldDisablePasswordLogin,
+ FieldCreatedAt,
+ FieldUpdatedAt,
+}
+
+// ValidColumn reports if the column name is valid (part of the table columns).
+func ValidColumn(column string) bool {
+ for i := range Columns {
+ if column == Columns[i] {
+ return true
+ }
+ }
+ return false
+}
+
+var (
+ // DefaultEnableSSO holds the default value on creation for the "enable_sso" field.
+ DefaultEnableSSO bool
+ // DefaultForceTwoFactorAuth holds the default value on creation for the "force_two_factor_auth" field.
+ DefaultForceTwoFactorAuth bool
+ // DefaultDisablePasswordLogin holds the default value on creation for the "disable_password_login" field.
+ DefaultDisablePasswordLogin bool
+ // DefaultCreatedAt holds the default value on creation for the "created_at" field.
+ DefaultCreatedAt func() time.Time
+ // DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
+ DefaultUpdatedAt func() time.Time
+ // UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field.
+ UpdateDefaultUpdatedAt func() time.Time
+)
+
+// OrderOption defines the ordering options for the Setting queries.
+type OrderOption func(*sql.Selector)
+
+// ByID orders the results by the id field.
+func ByID(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldID, opts...).ToFunc()
+}
+
+// ByEnableSSO orders the results by the enable_sso field.
+func ByEnableSSO(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldEnableSSO, opts...).ToFunc()
+}
+
+// ByForceTwoFactorAuth orders the results by the force_two_factor_auth field.
+func ByForceTwoFactorAuth(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldForceTwoFactorAuth, opts...).ToFunc()
+}
+
+// ByDisablePasswordLogin orders the results by the disable_password_login field.
+func ByDisablePasswordLogin(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldDisablePasswordLogin, opts...).ToFunc()
+}
+
+// ByCreatedAt orders the results by the created_at field.
+func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
+}
+
+// ByUpdatedAt orders the results by the updated_at field.
+func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc()
+}
diff --git a/backend/db/setting/where.go b/backend/db/setting/where.go
new file mode 100644
index 0000000..90e9461
--- /dev/null
+++ b/backend/db/setting/where.go
@@ -0,0 +1,206 @@
+// Code generated by ent, DO NOT EDIT.
+
+package setting
+
+import (
+ "time"
+
+ "entgo.io/ent/dialect/sql"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+ "github.com/google/uuid"
+)
+
+// ID filters vertices based on their ID field.
+func ID(id uuid.UUID) predicate.Setting {
+ return predicate.Setting(sql.FieldEQ(FieldID, id))
+}
+
+// IDEQ applies the EQ predicate on the ID field.
+func IDEQ(id uuid.UUID) predicate.Setting {
+ return predicate.Setting(sql.FieldEQ(FieldID, id))
+}
+
+// IDNEQ applies the NEQ predicate on the ID field.
+func IDNEQ(id uuid.UUID) predicate.Setting {
+ return predicate.Setting(sql.FieldNEQ(FieldID, id))
+}
+
+// IDIn applies the In predicate on the ID field.
+func IDIn(ids ...uuid.UUID) predicate.Setting {
+ return predicate.Setting(sql.FieldIn(FieldID, ids...))
+}
+
+// IDNotIn applies the NotIn predicate on the ID field.
+func IDNotIn(ids ...uuid.UUID) predicate.Setting {
+ return predicate.Setting(sql.FieldNotIn(FieldID, ids...))
+}
+
+// IDGT applies the GT predicate on the ID field.
+func IDGT(id uuid.UUID) predicate.Setting {
+ return predicate.Setting(sql.FieldGT(FieldID, id))
+}
+
+// IDGTE applies the GTE predicate on the ID field.
+func IDGTE(id uuid.UUID) predicate.Setting {
+ return predicate.Setting(sql.FieldGTE(FieldID, id))
+}
+
+// IDLT applies the LT predicate on the ID field.
+func IDLT(id uuid.UUID) predicate.Setting {
+ return predicate.Setting(sql.FieldLT(FieldID, id))
+}
+
+// IDLTE applies the LTE predicate on the ID field.
+func IDLTE(id uuid.UUID) predicate.Setting {
+ return predicate.Setting(sql.FieldLTE(FieldID, id))
+}
+
+// EnableSSO applies equality check predicate on the "enable_sso" field. It's identical to EnableSSOEQ.
+func EnableSSO(v bool) predicate.Setting {
+ return predicate.Setting(sql.FieldEQ(FieldEnableSSO, v))
+}
+
+// ForceTwoFactorAuth applies equality check predicate on the "force_two_factor_auth" field. It's identical to ForceTwoFactorAuthEQ.
+func ForceTwoFactorAuth(v bool) predicate.Setting {
+ return predicate.Setting(sql.FieldEQ(FieldForceTwoFactorAuth, v))
+}
+
+// DisablePasswordLogin applies equality check predicate on the "disable_password_login" field. It's identical to DisablePasswordLoginEQ.
+func DisablePasswordLogin(v bool) predicate.Setting {
+ return predicate.Setting(sql.FieldEQ(FieldDisablePasswordLogin, v))
+}
+
+// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
+func CreatedAt(v time.Time) predicate.Setting {
+ return predicate.Setting(sql.FieldEQ(FieldCreatedAt, v))
+}
+
+// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
+func UpdatedAt(v time.Time) predicate.Setting {
+ return predicate.Setting(sql.FieldEQ(FieldUpdatedAt, v))
+}
+
+// EnableSSOEQ applies the EQ predicate on the "enable_sso" field.
+func EnableSSOEQ(v bool) predicate.Setting {
+ return predicate.Setting(sql.FieldEQ(FieldEnableSSO, v))
+}
+
+// EnableSSONEQ applies the NEQ predicate on the "enable_sso" field.
+func EnableSSONEQ(v bool) predicate.Setting {
+ return predicate.Setting(sql.FieldNEQ(FieldEnableSSO, v))
+}
+
+// ForceTwoFactorAuthEQ applies the EQ predicate on the "force_two_factor_auth" field.
+func ForceTwoFactorAuthEQ(v bool) predicate.Setting {
+ return predicate.Setting(sql.FieldEQ(FieldForceTwoFactorAuth, v))
+}
+
+// ForceTwoFactorAuthNEQ applies the NEQ predicate on the "force_two_factor_auth" field.
+func ForceTwoFactorAuthNEQ(v bool) predicate.Setting {
+ return predicate.Setting(sql.FieldNEQ(FieldForceTwoFactorAuth, v))
+}
+
+// DisablePasswordLoginEQ applies the EQ predicate on the "disable_password_login" field.
+func DisablePasswordLoginEQ(v bool) predicate.Setting {
+ return predicate.Setting(sql.FieldEQ(FieldDisablePasswordLogin, v))
+}
+
+// DisablePasswordLoginNEQ applies the NEQ predicate on the "disable_password_login" field.
+func DisablePasswordLoginNEQ(v bool) predicate.Setting {
+ return predicate.Setting(sql.FieldNEQ(FieldDisablePasswordLogin, v))
+}
+
+// CreatedAtEQ applies the EQ predicate on the "created_at" field.
+func CreatedAtEQ(v time.Time) predicate.Setting {
+ return predicate.Setting(sql.FieldEQ(FieldCreatedAt, v))
+}
+
+// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
+func CreatedAtNEQ(v time.Time) predicate.Setting {
+ return predicate.Setting(sql.FieldNEQ(FieldCreatedAt, v))
+}
+
+// CreatedAtIn applies the In predicate on the "created_at" field.
+func CreatedAtIn(vs ...time.Time) predicate.Setting {
+ return predicate.Setting(sql.FieldIn(FieldCreatedAt, vs...))
+}
+
+// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
+func CreatedAtNotIn(vs ...time.Time) predicate.Setting {
+ return predicate.Setting(sql.FieldNotIn(FieldCreatedAt, vs...))
+}
+
+// CreatedAtGT applies the GT predicate on the "created_at" field.
+func CreatedAtGT(v time.Time) predicate.Setting {
+ return predicate.Setting(sql.FieldGT(FieldCreatedAt, v))
+}
+
+// CreatedAtGTE applies the GTE predicate on the "created_at" field.
+func CreatedAtGTE(v time.Time) predicate.Setting {
+ return predicate.Setting(sql.FieldGTE(FieldCreatedAt, v))
+}
+
+// CreatedAtLT applies the LT predicate on the "created_at" field.
+func CreatedAtLT(v time.Time) predicate.Setting {
+ return predicate.Setting(sql.FieldLT(FieldCreatedAt, v))
+}
+
+// CreatedAtLTE applies the LTE predicate on the "created_at" field.
+func CreatedAtLTE(v time.Time) predicate.Setting {
+ return predicate.Setting(sql.FieldLTE(FieldCreatedAt, v))
+}
+
+// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
+func UpdatedAtEQ(v time.Time) predicate.Setting {
+ return predicate.Setting(sql.FieldEQ(FieldUpdatedAt, v))
+}
+
+// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
+func UpdatedAtNEQ(v time.Time) predicate.Setting {
+ return predicate.Setting(sql.FieldNEQ(FieldUpdatedAt, v))
+}
+
+// UpdatedAtIn applies the In predicate on the "updated_at" field.
+func UpdatedAtIn(vs ...time.Time) predicate.Setting {
+ return predicate.Setting(sql.FieldIn(FieldUpdatedAt, vs...))
+}
+
+// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
+func UpdatedAtNotIn(vs ...time.Time) predicate.Setting {
+ return predicate.Setting(sql.FieldNotIn(FieldUpdatedAt, vs...))
+}
+
+// UpdatedAtGT applies the GT predicate on the "updated_at" field.
+func UpdatedAtGT(v time.Time) predicate.Setting {
+ return predicate.Setting(sql.FieldGT(FieldUpdatedAt, v))
+}
+
+// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
+func UpdatedAtGTE(v time.Time) predicate.Setting {
+ return predicate.Setting(sql.FieldGTE(FieldUpdatedAt, v))
+}
+
+// UpdatedAtLT applies the LT predicate on the "updated_at" field.
+func UpdatedAtLT(v time.Time) predicate.Setting {
+ return predicate.Setting(sql.FieldLT(FieldUpdatedAt, v))
+}
+
+// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
+func UpdatedAtLTE(v time.Time) predicate.Setting {
+ return predicate.Setting(sql.FieldLTE(FieldUpdatedAt, v))
+}
+
+// And groups predicates with the AND operator between them.
+func And(predicates ...predicate.Setting) predicate.Setting {
+ return predicate.Setting(sql.AndPredicates(predicates...))
+}
+
+// Or groups predicates with the OR operator between them.
+func Or(predicates ...predicate.Setting) predicate.Setting {
+ return predicate.Setting(sql.OrPredicates(predicates...))
+}
+
+// Not applies the not operator on the given predicate.
+func Not(p predicate.Setting) predicate.Setting {
+ return predicate.Setting(sql.NotPredicates(p))
+}
diff --git a/backend/db/setting_create.go b/backend/db/setting_create.go
new file mode 100644
index 0000000..6f2c293
--- /dev/null
+++ b/backend/db/setting_create.go
@@ -0,0 +1,769 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "time"
+
+ "entgo.io/ent/dialect"
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/setting"
+ "github.com/google/uuid"
+)
+
+// SettingCreate is the builder for creating a Setting entity.
+type SettingCreate struct {
+ config
+ mutation *SettingMutation
+ hooks []Hook
+ conflict []sql.ConflictOption
+}
+
+// SetEnableSSO sets the "enable_sso" field.
+func (sc *SettingCreate) SetEnableSSO(b bool) *SettingCreate {
+ sc.mutation.SetEnableSSO(b)
+ return sc
+}
+
+// SetNillableEnableSSO sets the "enable_sso" field if the given value is not nil.
+func (sc *SettingCreate) SetNillableEnableSSO(b *bool) *SettingCreate {
+ if b != nil {
+ sc.SetEnableSSO(*b)
+ }
+ return sc
+}
+
+// SetForceTwoFactorAuth sets the "force_two_factor_auth" field.
+func (sc *SettingCreate) SetForceTwoFactorAuth(b bool) *SettingCreate {
+ sc.mutation.SetForceTwoFactorAuth(b)
+ return sc
+}
+
+// SetNillableForceTwoFactorAuth sets the "force_two_factor_auth" field if the given value is not nil.
+func (sc *SettingCreate) SetNillableForceTwoFactorAuth(b *bool) *SettingCreate {
+ if b != nil {
+ sc.SetForceTwoFactorAuth(*b)
+ }
+ return sc
+}
+
+// SetDisablePasswordLogin sets the "disable_password_login" field.
+func (sc *SettingCreate) SetDisablePasswordLogin(b bool) *SettingCreate {
+ sc.mutation.SetDisablePasswordLogin(b)
+ return sc
+}
+
+// SetNillableDisablePasswordLogin sets the "disable_password_login" field if the given value is not nil.
+func (sc *SettingCreate) SetNillableDisablePasswordLogin(b *bool) *SettingCreate {
+ if b != nil {
+ sc.SetDisablePasswordLogin(*b)
+ }
+ return sc
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (sc *SettingCreate) SetCreatedAt(t time.Time) *SettingCreate {
+ sc.mutation.SetCreatedAt(t)
+ return sc
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (sc *SettingCreate) SetNillableCreatedAt(t *time.Time) *SettingCreate {
+ if t != nil {
+ sc.SetCreatedAt(*t)
+ }
+ return sc
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (sc *SettingCreate) SetUpdatedAt(t time.Time) *SettingCreate {
+ sc.mutation.SetUpdatedAt(t)
+ return sc
+}
+
+// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
+func (sc *SettingCreate) SetNillableUpdatedAt(t *time.Time) *SettingCreate {
+ if t != nil {
+ sc.SetUpdatedAt(*t)
+ }
+ return sc
+}
+
+// SetID sets the "id" field.
+func (sc *SettingCreate) SetID(u uuid.UUID) *SettingCreate {
+ sc.mutation.SetID(u)
+ return sc
+}
+
+// Mutation returns the SettingMutation object of the builder.
+func (sc *SettingCreate) Mutation() *SettingMutation {
+ return sc.mutation
+}
+
+// Save creates the Setting in the database.
+func (sc *SettingCreate) Save(ctx context.Context) (*Setting, error) {
+ sc.defaults()
+ return withHooks(ctx, sc.sqlSave, sc.mutation, sc.hooks)
+}
+
+// SaveX calls Save and panics if Save returns an error.
+func (sc *SettingCreate) SaveX(ctx context.Context) *Setting {
+ v, err := sc.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return v
+}
+
+// Exec executes the query.
+func (sc *SettingCreate) Exec(ctx context.Context) error {
+ _, err := sc.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (sc *SettingCreate) ExecX(ctx context.Context) {
+ if err := sc.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// defaults sets the default values of the builder before save.
+func (sc *SettingCreate) defaults() {
+ if _, ok := sc.mutation.EnableSSO(); !ok {
+ v := setting.DefaultEnableSSO
+ sc.mutation.SetEnableSSO(v)
+ }
+ if _, ok := sc.mutation.ForceTwoFactorAuth(); !ok {
+ v := setting.DefaultForceTwoFactorAuth
+ sc.mutation.SetForceTwoFactorAuth(v)
+ }
+ if _, ok := sc.mutation.DisablePasswordLogin(); !ok {
+ v := setting.DefaultDisablePasswordLogin
+ sc.mutation.SetDisablePasswordLogin(v)
+ }
+ if _, ok := sc.mutation.CreatedAt(); !ok {
+ v := setting.DefaultCreatedAt()
+ sc.mutation.SetCreatedAt(v)
+ }
+ if _, ok := sc.mutation.UpdatedAt(); !ok {
+ v := setting.DefaultUpdatedAt()
+ sc.mutation.SetUpdatedAt(v)
+ }
+}
+
+// check runs all checks and user-defined validators on the builder.
+func (sc *SettingCreate) check() error {
+ if _, ok := sc.mutation.EnableSSO(); !ok {
+ return &ValidationError{Name: "enable_sso", err: errors.New(`db: missing required field "Setting.enable_sso"`)}
+ }
+ if _, ok := sc.mutation.ForceTwoFactorAuth(); !ok {
+ return &ValidationError{Name: "force_two_factor_auth", err: errors.New(`db: missing required field "Setting.force_two_factor_auth"`)}
+ }
+ if _, ok := sc.mutation.DisablePasswordLogin(); !ok {
+ return &ValidationError{Name: "disable_password_login", err: errors.New(`db: missing required field "Setting.disable_password_login"`)}
+ }
+ if _, ok := sc.mutation.CreatedAt(); !ok {
+ return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "Setting.created_at"`)}
+ }
+ if _, ok := sc.mutation.UpdatedAt(); !ok {
+ return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "Setting.updated_at"`)}
+ }
+ return nil
+}
+
+func (sc *SettingCreate) sqlSave(ctx context.Context) (*Setting, error) {
+ if err := sc.check(); err != nil {
+ return nil, err
+ }
+ _node, _spec := sc.createSpec()
+ if err := sqlgraph.CreateNode(ctx, sc.driver, _spec); err != nil {
+ if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return nil, err
+ }
+ if _spec.ID.Value != nil {
+ if id, ok := _spec.ID.Value.(*uuid.UUID); ok {
+ _node.ID = *id
+ } else if err := _node.ID.Scan(_spec.ID.Value); err != nil {
+ return nil, err
+ }
+ }
+ sc.mutation.id = &_node.ID
+ sc.mutation.done = true
+ return _node, nil
+}
+
+func (sc *SettingCreate) createSpec() (*Setting, *sqlgraph.CreateSpec) {
+ var (
+ _node = &Setting{config: sc.config}
+ _spec = sqlgraph.NewCreateSpec(setting.Table, sqlgraph.NewFieldSpec(setting.FieldID, field.TypeUUID))
+ )
+ _spec.OnConflict = sc.conflict
+ if id, ok := sc.mutation.ID(); ok {
+ _node.ID = id
+ _spec.ID.Value = &id
+ }
+ if value, ok := sc.mutation.EnableSSO(); ok {
+ _spec.SetField(setting.FieldEnableSSO, field.TypeBool, value)
+ _node.EnableSSO = value
+ }
+ if value, ok := sc.mutation.ForceTwoFactorAuth(); ok {
+ _spec.SetField(setting.FieldForceTwoFactorAuth, field.TypeBool, value)
+ _node.ForceTwoFactorAuth = value
+ }
+ if value, ok := sc.mutation.DisablePasswordLogin(); ok {
+ _spec.SetField(setting.FieldDisablePasswordLogin, field.TypeBool, value)
+ _node.DisablePasswordLogin = value
+ }
+ if value, ok := sc.mutation.CreatedAt(); ok {
+ _spec.SetField(setting.FieldCreatedAt, field.TypeTime, value)
+ _node.CreatedAt = value
+ }
+ if value, ok := sc.mutation.UpdatedAt(); ok {
+ _spec.SetField(setting.FieldUpdatedAt, field.TypeTime, value)
+ _node.UpdatedAt = value
+ }
+ return _node, _spec
+}
+
+// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
+// of the `INSERT` statement. For example:
+//
+// client.Setting.Create().
+// SetEnableSSO(v).
+// OnConflict(
+// // Update the row with the new values
+// // the was proposed for insertion.
+// sql.ResolveWithNewValues(),
+// ).
+// // Override some of the fields with custom
+// // update values.
+// Update(func(u *ent.SettingUpsert) {
+// SetEnableSSO(v+v).
+// }).
+// Exec(ctx)
+func (sc *SettingCreate) OnConflict(opts ...sql.ConflictOption) *SettingUpsertOne {
+ sc.conflict = opts
+ return &SettingUpsertOne{
+ create: sc,
+ }
+}
+
+// OnConflictColumns calls `OnConflict` and configures the columns
+// as conflict target. Using this option is equivalent to using:
+//
+// client.Setting.Create().
+// OnConflict(sql.ConflictColumns(columns...)).
+// Exec(ctx)
+func (sc *SettingCreate) OnConflictColumns(columns ...string) *SettingUpsertOne {
+ sc.conflict = append(sc.conflict, sql.ConflictColumns(columns...))
+ return &SettingUpsertOne{
+ create: sc,
+ }
+}
+
+type (
+ // SettingUpsertOne is the builder for "upsert"-ing
+ // one Setting node.
+ SettingUpsertOne struct {
+ create *SettingCreate
+ }
+
+ // SettingUpsert is the "OnConflict" setter.
+ SettingUpsert struct {
+ *sql.UpdateSet
+ }
+)
+
+// SetEnableSSO sets the "enable_sso" field.
+func (u *SettingUpsert) SetEnableSSO(v bool) *SettingUpsert {
+ u.Set(setting.FieldEnableSSO, v)
+ return u
+}
+
+// UpdateEnableSSO sets the "enable_sso" field to the value that was provided on create.
+func (u *SettingUpsert) UpdateEnableSSO() *SettingUpsert {
+ u.SetExcluded(setting.FieldEnableSSO)
+ return u
+}
+
+// SetForceTwoFactorAuth sets the "force_two_factor_auth" field.
+func (u *SettingUpsert) SetForceTwoFactorAuth(v bool) *SettingUpsert {
+ u.Set(setting.FieldForceTwoFactorAuth, v)
+ return u
+}
+
+// UpdateForceTwoFactorAuth sets the "force_two_factor_auth" field to the value that was provided on create.
+func (u *SettingUpsert) UpdateForceTwoFactorAuth() *SettingUpsert {
+ u.SetExcluded(setting.FieldForceTwoFactorAuth)
+ return u
+}
+
+// SetDisablePasswordLogin sets the "disable_password_login" field.
+func (u *SettingUpsert) SetDisablePasswordLogin(v bool) *SettingUpsert {
+ u.Set(setting.FieldDisablePasswordLogin, v)
+ return u
+}
+
+// UpdateDisablePasswordLogin sets the "disable_password_login" field to the value that was provided on create.
+func (u *SettingUpsert) UpdateDisablePasswordLogin() *SettingUpsert {
+ u.SetExcluded(setting.FieldDisablePasswordLogin)
+ return u
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (u *SettingUpsert) SetCreatedAt(v time.Time) *SettingUpsert {
+ u.Set(setting.FieldCreatedAt, v)
+ return u
+}
+
+// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
+func (u *SettingUpsert) UpdateCreatedAt() *SettingUpsert {
+ u.SetExcluded(setting.FieldCreatedAt)
+ return u
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (u *SettingUpsert) SetUpdatedAt(v time.Time) *SettingUpsert {
+ u.Set(setting.FieldUpdatedAt, v)
+ return u
+}
+
+// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
+func (u *SettingUpsert) UpdateUpdatedAt() *SettingUpsert {
+ u.SetExcluded(setting.FieldUpdatedAt)
+ return u
+}
+
+// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field.
+// Using this option is equivalent to using:
+//
+// client.Setting.Create().
+// OnConflict(
+// sql.ResolveWithNewValues(),
+// sql.ResolveWith(func(u *sql.UpdateSet) {
+// u.SetIgnore(setting.FieldID)
+// }),
+// ).
+// Exec(ctx)
+func (u *SettingUpsertOne) UpdateNewValues() *SettingUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
+ if _, exists := u.create.mutation.ID(); exists {
+ s.SetIgnore(setting.FieldID)
+ }
+ }))
+ return u
+}
+
+// Ignore sets each column to itself in case of conflict.
+// Using this option is equivalent to using:
+//
+// client.Setting.Create().
+// OnConflict(sql.ResolveWithIgnore()).
+// Exec(ctx)
+func (u *SettingUpsertOne) Ignore() *SettingUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
+ return u
+}
+
+// DoNothing configures the conflict_action to `DO NOTHING`.
+// Supported only by SQLite and PostgreSQL.
+func (u *SettingUpsertOne) DoNothing() *SettingUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.DoNothing())
+ return u
+}
+
+// Update allows overriding fields `UPDATE` values. See the SettingCreate.OnConflict
+// documentation for more info.
+func (u *SettingUpsertOne) Update(set func(*SettingUpsert)) *SettingUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
+ set(&SettingUpsert{UpdateSet: update})
+ }))
+ return u
+}
+
+// SetEnableSSO sets the "enable_sso" field.
+func (u *SettingUpsertOne) SetEnableSSO(v bool) *SettingUpsertOne {
+ return u.Update(func(s *SettingUpsert) {
+ s.SetEnableSSO(v)
+ })
+}
+
+// UpdateEnableSSO sets the "enable_sso" field to the value that was provided on create.
+func (u *SettingUpsertOne) UpdateEnableSSO() *SettingUpsertOne {
+ return u.Update(func(s *SettingUpsert) {
+ s.UpdateEnableSSO()
+ })
+}
+
+// SetForceTwoFactorAuth sets the "force_two_factor_auth" field.
+func (u *SettingUpsertOne) SetForceTwoFactorAuth(v bool) *SettingUpsertOne {
+ return u.Update(func(s *SettingUpsert) {
+ s.SetForceTwoFactorAuth(v)
+ })
+}
+
+// UpdateForceTwoFactorAuth sets the "force_two_factor_auth" field to the value that was provided on create.
+func (u *SettingUpsertOne) UpdateForceTwoFactorAuth() *SettingUpsertOne {
+ return u.Update(func(s *SettingUpsert) {
+ s.UpdateForceTwoFactorAuth()
+ })
+}
+
+// SetDisablePasswordLogin sets the "disable_password_login" field.
+func (u *SettingUpsertOne) SetDisablePasswordLogin(v bool) *SettingUpsertOne {
+ return u.Update(func(s *SettingUpsert) {
+ s.SetDisablePasswordLogin(v)
+ })
+}
+
+// UpdateDisablePasswordLogin sets the "disable_password_login" field to the value that was provided on create.
+func (u *SettingUpsertOne) UpdateDisablePasswordLogin() *SettingUpsertOne {
+ return u.Update(func(s *SettingUpsert) {
+ s.UpdateDisablePasswordLogin()
+ })
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (u *SettingUpsertOne) SetCreatedAt(v time.Time) *SettingUpsertOne {
+ return u.Update(func(s *SettingUpsert) {
+ s.SetCreatedAt(v)
+ })
+}
+
+// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
+func (u *SettingUpsertOne) UpdateCreatedAt() *SettingUpsertOne {
+ return u.Update(func(s *SettingUpsert) {
+ s.UpdateCreatedAt()
+ })
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (u *SettingUpsertOne) SetUpdatedAt(v time.Time) *SettingUpsertOne {
+ return u.Update(func(s *SettingUpsert) {
+ s.SetUpdatedAt(v)
+ })
+}
+
+// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
+func (u *SettingUpsertOne) UpdateUpdatedAt() *SettingUpsertOne {
+ return u.Update(func(s *SettingUpsert) {
+ s.UpdateUpdatedAt()
+ })
+}
+
+// Exec executes the query.
+func (u *SettingUpsertOne) Exec(ctx context.Context) error {
+ if len(u.create.conflict) == 0 {
+ return errors.New("db: missing options for SettingCreate.OnConflict")
+ }
+ return u.create.Exec(ctx)
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (u *SettingUpsertOne) ExecX(ctx context.Context) {
+ if err := u.create.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// Exec executes the UPSERT query and returns the inserted/updated ID.
+func (u *SettingUpsertOne) ID(ctx context.Context) (id uuid.UUID, err error) {
+ if u.create.driver.Dialect() == dialect.MySQL {
+ // In case of "ON CONFLICT", there is no way to get back non-numeric ID
+ // fields from the database since MySQL does not support the RETURNING clause.
+ return id, errors.New("db: SettingUpsertOne.ID is not supported by MySQL driver. Use SettingUpsertOne.Exec instead")
+ }
+ node, err := u.create.Save(ctx)
+ if err != nil {
+ return id, err
+ }
+ return node.ID, nil
+}
+
+// IDX is like ID, but panics if an error occurs.
+func (u *SettingUpsertOne) IDX(ctx context.Context) uuid.UUID {
+ id, err := u.ID(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return id
+}
+
+// SettingCreateBulk is the builder for creating many Setting entities in bulk.
+type SettingCreateBulk struct {
+ config
+ err error
+ builders []*SettingCreate
+ conflict []sql.ConflictOption
+}
+
+// Save creates the Setting entities in the database.
+func (scb *SettingCreateBulk) Save(ctx context.Context) ([]*Setting, error) {
+ if scb.err != nil {
+ return nil, scb.err
+ }
+ specs := make([]*sqlgraph.CreateSpec, len(scb.builders))
+ nodes := make([]*Setting, len(scb.builders))
+ mutators := make([]Mutator, len(scb.builders))
+ for i := range scb.builders {
+ func(i int, root context.Context) {
+ builder := scb.builders[i]
+ builder.defaults()
+ var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
+ mutation, ok := m.(*SettingMutation)
+ if !ok {
+ return nil, fmt.Errorf("unexpected mutation type %T", m)
+ }
+ if err := builder.check(); err != nil {
+ return nil, err
+ }
+ builder.mutation = mutation
+ var err error
+ nodes[i], specs[i] = builder.createSpec()
+ if i < len(mutators)-1 {
+ _, err = mutators[i+1].Mutate(root, scb.builders[i+1].mutation)
+ } else {
+ spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
+ spec.OnConflict = scb.conflict
+ // Invoke the actual operation on the latest mutation in the chain.
+ if err = sqlgraph.BatchCreate(ctx, scb.driver, spec); err != nil {
+ if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ }
+ }
+ if err != nil {
+ return nil, err
+ }
+ mutation.id = &nodes[i].ID
+ mutation.done = true
+ return nodes[i], nil
+ })
+ for i := len(builder.hooks) - 1; i >= 0; i-- {
+ mut = builder.hooks[i](mut)
+ }
+ mutators[i] = mut
+ }(i, ctx)
+ }
+ if len(mutators) > 0 {
+ if _, err := mutators[0].Mutate(ctx, scb.builders[0].mutation); err != nil {
+ return nil, err
+ }
+ }
+ return nodes, nil
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (scb *SettingCreateBulk) SaveX(ctx context.Context) []*Setting {
+ v, err := scb.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return v
+}
+
+// Exec executes the query.
+func (scb *SettingCreateBulk) Exec(ctx context.Context) error {
+ _, err := scb.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (scb *SettingCreateBulk) ExecX(ctx context.Context) {
+ if err := scb.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
+// of the `INSERT` statement. For example:
+//
+// client.Setting.CreateBulk(builders...).
+// OnConflict(
+// // Update the row with the new values
+// // the was proposed for insertion.
+// sql.ResolveWithNewValues(),
+// ).
+// // Override some of the fields with custom
+// // update values.
+// Update(func(u *ent.SettingUpsert) {
+// SetEnableSSO(v+v).
+// }).
+// Exec(ctx)
+func (scb *SettingCreateBulk) OnConflict(opts ...sql.ConflictOption) *SettingUpsertBulk {
+ scb.conflict = opts
+ return &SettingUpsertBulk{
+ create: scb,
+ }
+}
+
+// OnConflictColumns calls `OnConflict` and configures the columns
+// as conflict target. Using this option is equivalent to using:
+//
+// client.Setting.Create().
+// OnConflict(sql.ConflictColumns(columns...)).
+// Exec(ctx)
+func (scb *SettingCreateBulk) OnConflictColumns(columns ...string) *SettingUpsertBulk {
+ scb.conflict = append(scb.conflict, sql.ConflictColumns(columns...))
+ return &SettingUpsertBulk{
+ create: scb,
+ }
+}
+
+// SettingUpsertBulk is the builder for "upsert"-ing
+// a bulk of Setting nodes.
+type SettingUpsertBulk struct {
+ create *SettingCreateBulk
+}
+
+// UpdateNewValues updates the mutable fields using the new values that
+// were set on create. Using this option is equivalent to using:
+//
+// client.Setting.Create().
+// OnConflict(
+// sql.ResolveWithNewValues(),
+// sql.ResolveWith(func(u *sql.UpdateSet) {
+// u.SetIgnore(setting.FieldID)
+// }),
+// ).
+// Exec(ctx)
+func (u *SettingUpsertBulk) UpdateNewValues() *SettingUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
+ for _, b := range u.create.builders {
+ if _, exists := b.mutation.ID(); exists {
+ s.SetIgnore(setting.FieldID)
+ }
+ }
+ }))
+ return u
+}
+
+// Ignore sets each column to itself in case of conflict.
+// Using this option is equivalent to using:
+//
+// client.Setting.Create().
+// OnConflict(sql.ResolveWithIgnore()).
+// Exec(ctx)
+func (u *SettingUpsertBulk) Ignore() *SettingUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
+ return u
+}
+
+// DoNothing configures the conflict_action to `DO NOTHING`.
+// Supported only by SQLite and PostgreSQL.
+func (u *SettingUpsertBulk) DoNothing() *SettingUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.DoNothing())
+ return u
+}
+
+// Update allows overriding fields `UPDATE` values. See the SettingCreateBulk.OnConflict
+// documentation for more info.
+func (u *SettingUpsertBulk) Update(set func(*SettingUpsert)) *SettingUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
+ set(&SettingUpsert{UpdateSet: update})
+ }))
+ return u
+}
+
+// SetEnableSSO sets the "enable_sso" field.
+func (u *SettingUpsertBulk) SetEnableSSO(v bool) *SettingUpsertBulk {
+ return u.Update(func(s *SettingUpsert) {
+ s.SetEnableSSO(v)
+ })
+}
+
+// UpdateEnableSSO sets the "enable_sso" field to the value that was provided on create.
+func (u *SettingUpsertBulk) UpdateEnableSSO() *SettingUpsertBulk {
+ return u.Update(func(s *SettingUpsert) {
+ s.UpdateEnableSSO()
+ })
+}
+
+// SetForceTwoFactorAuth sets the "force_two_factor_auth" field.
+func (u *SettingUpsertBulk) SetForceTwoFactorAuth(v bool) *SettingUpsertBulk {
+ return u.Update(func(s *SettingUpsert) {
+ s.SetForceTwoFactorAuth(v)
+ })
+}
+
+// UpdateForceTwoFactorAuth sets the "force_two_factor_auth" field to the value that was provided on create.
+func (u *SettingUpsertBulk) UpdateForceTwoFactorAuth() *SettingUpsertBulk {
+ return u.Update(func(s *SettingUpsert) {
+ s.UpdateForceTwoFactorAuth()
+ })
+}
+
+// SetDisablePasswordLogin sets the "disable_password_login" field.
+func (u *SettingUpsertBulk) SetDisablePasswordLogin(v bool) *SettingUpsertBulk {
+ return u.Update(func(s *SettingUpsert) {
+ s.SetDisablePasswordLogin(v)
+ })
+}
+
+// UpdateDisablePasswordLogin sets the "disable_password_login" field to the value that was provided on create.
+func (u *SettingUpsertBulk) UpdateDisablePasswordLogin() *SettingUpsertBulk {
+ return u.Update(func(s *SettingUpsert) {
+ s.UpdateDisablePasswordLogin()
+ })
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (u *SettingUpsertBulk) SetCreatedAt(v time.Time) *SettingUpsertBulk {
+ return u.Update(func(s *SettingUpsert) {
+ s.SetCreatedAt(v)
+ })
+}
+
+// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
+func (u *SettingUpsertBulk) UpdateCreatedAt() *SettingUpsertBulk {
+ return u.Update(func(s *SettingUpsert) {
+ s.UpdateCreatedAt()
+ })
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (u *SettingUpsertBulk) SetUpdatedAt(v time.Time) *SettingUpsertBulk {
+ return u.Update(func(s *SettingUpsert) {
+ s.SetUpdatedAt(v)
+ })
+}
+
+// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
+func (u *SettingUpsertBulk) UpdateUpdatedAt() *SettingUpsertBulk {
+ return u.Update(func(s *SettingUpsert) {
+ s.UpdateUpdatedAt()
+ })
+}
+
+// Exec executes the query.
+func (u *SettingUpsertBulk) Exec(ctx context.Context) error {
+ if u.create.err != nil {
+ return u.create.err
+ }
+ for i, b := range u.create.builders {
+ if len(b.conflict) != 0 {
+ return fmt.Errorf("db: OnConflict was set for builder %d. Set it on the SettingCreateBulk instead", i)
+ }
+ }
+ if len(u.create.conflict) == 0 {
+ return errors.New("db: missing options for SettingCreateBulk.OnConflict")
+ }
+ return u.create.Exec(ctx)
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (u *SettingUpsertBulk) ExecX(ctx context.Context) {
+ if err := u.create.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
diff --git a/backend/db/setting_delete.go b/backend/db/setting_delete.go
new file mode 100644
index 0000000..6a18a0a
--- /dev/null
+++ b/backend/db/setting_delete.go
@@ -0,0 +1,88 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+ "github.com/chaitin/MonkeyCode/backend/db/setting"
+)
+
+// SettingDelete is the builder for deleting a Setting entity.
+type SettingDelete struct {
+ config
+ hooks []Hook
+ mutation *SettingMutation
+}
+
+// Where appends a list predicates to the SettingDelete builder.
+func (sd *SettingDelete) Where(ps ...predicate.Setting) *SettingDelete {
+ sd.mutation.Where(ps...)
+ return sd
+}
+
+// Exec executes the deletion query and returns how many vertices were deleted.
+func (sd *SettingDelete) Exec(ctx context.Context) (int, error) {
+ return withHooks(ctx, sd.sqlExec, sd.mutation, sd.hooks)
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (sd *SettingDelete) ExecX(ctx context.Context) int {
+ n, err := sd.Exec(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return n
+}
+
+func (sd *SettingDelete) sqlExec(ctx context.Context) (int, error) {
+ _spec := sqlgraph.NewDeleteSpec(setting.Table, sqlgraph.NewFieldSpec(setting.FieldID, field.TypeUUID))
+ if ps := sd.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ affected, err := sqlgraph.DeleteNodes(ctx, sd.driver, _spec)
+ if err != nil && sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ sd.mutation.done = true
+ return affected, err
+}
+
+// SettingDeleteOne is the builder for deleting a single Setting entity.
+type SettingDeleteOne struct {
+ sd *SettingDelete
+}
+
+// Where appends a list predicates to the SettingDelete builder.
+func (sdo *SettingDeleteOne) Where(ps ...predicate.Setting) *SettingDeleteOne {
+ sdo.sd.mutation.Where(ps...)
+ return sdo
+}
+
+// Exec executes the deletion query.
+func (sdo *SettingDeleteOne) Exec(ctx context.Context) error {
+ n, err := sdo.sd.Exec(ctx)
+ switch {
+ case err != nil:
+ return err
+ case n == 0:
+ return &NotFoundError{setting.Label}
+ default:
+ return nil
+ }
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (sdo *SettingDeleteOne) ExecX(ctx context.Context) {
+ if err := sdo.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
diff --git a/backend/db/setting_query.go b/backend/db/setting_query.go
new file mode 100644
index 0000000..ef84b70
--- /dev/null
+++ b/backend/db/setting_query.go
@@ -0,0 +1,578 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "fmt"
+ "math"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect"
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+ "github.com/chaitin/MonkeyCode/backend/db/setting"
+ "github.com/google/uuid"
+)
+
+// SettingQuery is the builder for querying Setting entities.
+type SettingQuery struct {
+ config
+ ctx *QueryContext
+ order []setting.OrderOption
+ inters []Interceptor
+ predicates []predicate.Setting
+ modifiers []func(*sql.Selector)
+ // intermediate query (i.e. traversal path).
+ sql *sql.Selector
+ path func(context.Context) (*sql.Selector, error)
+}
+
+// Where adds a new predicate for the SettingQuery builder.
+func (sq *SettingQuery) Where(ps ...predicate.Setting) *SettingQuery {
+ sq.predicates = append(sq.predicates, ps...)
+ return sq
+}
+
+// Limit the number of records to be returned by this query.
+func (sq *SettingQuery) Limit(limit int) *SettingQuery {
+ sq.ctx.Limit = &limit
+ return sq
+}
+
+// Offset to start from.
+func (sq *SettingQuery) Offset(offset int) *SettingQuery {
+ sq.ctx.Offset = &offset
+ return sq
+}
+
+// Unique configures the query builder to filter duplicate records on query.
+// By default, unique is set to true, and can be disabled using this method.
+func (sq *SettingQuery) Unique(unique bool) *SettingQuery {
+ sq.ctx.Unique = &unique
+ return sq
+}
+
+// Order specifies how the records should be ordered.
+func (sq *SettingQuery) Order(o ...setting.OrderOption) *SettingQuery {
+ sq.order = append(sq.order, o...)
+ return sq
+}
+
+// First returns the first Setting entity from the query.
+// Returns a *NotFoundError when no Setting was found.
+func (sq *SettingQuery) First(ctx context.Context) (*Setting, error) {
+ nodes, err := sq.Limit(1).All(setContextOp(ctx, sq.ctx, ent.OpQueryFirst))
+ if err != nil {
+ return nil, err
+ }
+ if len(nodes) == 0 {
+ return nil, &NotFoundError{setting.Label}
+ }
+ return nodes[0], nil
+}
+
+// FirstX is like First, but panics if an error occurs.
+func (sq *SettingQuery) FirstX(ctx context.Context) *Setting {
+ node, err := sq.First(ctx)
+ if err != nil && !IsNotFound(err) {
+ panic(err)
+ }
+ return node
+}
+
+// FirstID returns the first Setting ID from the query.
+// Returns a *NotFoundError when no Setting ID was found.
+func (sq *SettingQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
+ var ids []uuid.UUID
+ if ids, err = sq.Limit(1).IDs(setContextOp(ctx, sq.ctx, ent.OpQueryFirstID)); err != nil {
+ return
+ }
+ if len(ids) == 0 {
+ err = &NotFoundError{setting.Label}
+ return
+ }
+ return ids[0], nil
+}
+
+// FirstIDX is like FirstID, but panics if an error occurs.
+func (sq *SettingQuery) FirstIDX(ctx context.Context) uuid.UUID {
+ id, err := sq.FirstID(ctx)
+ if err != nil && !IsNotFound(err) {
+ panic(err)
+ }
+ return id
+}
+
+// Only returns a single Setting entity found by the query, ensuring it only returns one.
+// Returns a *NotSingularError when more than one Setting entity is found.
+// Returns a *NotFoundError when no Setting entities are found.
+func (sq *SettingQuery) Only(ctx context.Context) (*Setting, error) {
+ nodes, err := sq.Limit(2).All(setContextOp(ctx, sq.ctx, ent.OpQueryOnly))
+ if err != nil {
+ return nil, err
+ }
+ switch len(nodes) {
+ case 1:
+ return nodes[0], nil
+ case 0:
+ return nil, &NotFoundError{setting.Label}
+ default:
+ return nil, &NotSingularError{setting.Label}
+ }
+}
+
+// OnlyX is like Only, but panics if an error occurs.
+func (sq *SettingQuery) OnlyX(ctx context.Context) *Setting {
+ node, err := sq.Only(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return node
+}
+
+// OnlyID is like Only, but returns the only Setting ID in the query.
+// Returns a *NotSingularError when more than one Setting ID is found.
+// Returns a *NotFoundError when no entities are found.
+func (sq *SettingQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
+ var ids []uuid.UUID
+ if ids, err = sq.Limit(2).IDs(setContextOp(ctx, sq.ctx, ent.OpQueryOnlyID)); err != nil {
+ return
+ }
+ switch len(ids) {
+ case 1:
+ id = ids[0]
+ case 0:
+ err = &NotFoundError{setting.Label}
+ default:
+ err = &NotSingularError{setting.Label}
+ }
+ return
+}
+
+// OnlyIDX is like OnlyID, but panics if an error occurs.
+func (sq *SettingQuery) OnlyIDX(ctx context.Context) uuid.UUID {
+ id, err := sq.OnlyID(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return id
+}
+
+// All executes the query and returns a list of Settings.
+func (sq *SettingQuery) All(ctx context.Context) ([]*Setting, error) {
+ ctx = setContextOp(ctx, sq.ctx, ent.OpQueryAll)
+ if err := sq.prepareQuery(ctx); err != nil {
+ return nil, err
+ }
+ qr := querierAll[[]*Setting, *SettingQuery]()
+ return withInterceptors[[]*Setting](ctx, sq, qr, sq.inters)
+}
+
+// AllX is like All, but panics if an error occurs.
+func (sq *SettingQuery) AllX(ctx context.Context) []*Setting {
+ nodes, err := sq.All(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return nodes
+}
+
+// IDs executes the query and returns a list of Setting IDs.
+func (sq *SettingQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) {
+ if sq.ctx.Unique == nil && sq.path != nil {
+ sq.Unique(true)
+ }
+ ctx = setContextOp(ctx, sq.ctx, ent.OpQueryIDs)
+ if err = sq.Select(setting.FieldID).Scan(ctx, &ids); err != nil {
+ return nil, err
+ }
+ return ids, nil
+}
+
+// IDsX is like IDs, but panics if an error occurs.
+func (sq *SettingQuery) IDsX(ctx context.Context) []uuid.UUID {
+ ids, err := sq.IDs(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return ids
+}
+
+// Count returns the count of the given query.
+func (sq *SettingQuery) Count(ctx context.Context) (int, error) {
+ ctx = setContextOp(ctx, sq.ctx, ent.OpQueryCount)
+ if err := sq.prepareQuery(ctx); err != nil {
+ return 0, err
+ }
+ return withInterceptors[int](ctx, sq, querierCount[*SettingQuery](), sq.inters)
+}
+
+// CountX is like Count, but panics if an error occurs.
+func (sq *SettingQuery) CountX(ctx context.Context) int {
+ count, err := sq.Count(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return count
+}
+
+// Exist returns true if the query has elements in the graph.
+func (sq *SettingQuery) Exist(ctx context.Context) (bool, error) {
+ ctx = setContextOp(ctx, sq.ctx, ent.OpQueryExist)
+ switch _, err := sq.FirstID(ctx); {
+ case IsNotFound(err):
+ return false, nil
+ case err != nil:
+ return false, fmt.Errorf("db: check existence: %w", err)
+ default:
+ return true, nil
+ }
+}
+
+// ExistX is like Exist, but panics if an error occurs.
+func (sq *SettingQuery) ExistX(ctx context.Context) bool {
+ exist, err := sq.Exist(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return exist
+}
+
+// Clone returns a duplicate of the SettingQuery builder, including all associated steps. It can be
+// used to prepare common query builders and use them differently after the clone is made.
+func (sq *SettingQuery) Clone() *SettingQuery {
+ if sq == nil {
+ return nil
+ }
+ return &SettingQuery{
+ config: sq.config,
+ ctx: sq.ctx.Clone(),
+ order: append([]setting.OrderOption{}, sq.order...),
+ inters: append([]Interceptor{}, sq.inters...),
+ predicates: append([]predicate.Setting{}, sq.predicates...),
+ // clone intermediate query.
+ sql: sq.sql.Clone(),
+ path: sq.path,
+ modifiers: append([]func(*sql.Selector){}, sq.modifiers...),
+ }
+}
+
+// GroupBy is used to group vertices by one or more fields/columns.
+// It is often used with aggregate functions, like: count, max, mean, min, sum.
+//
+// Example:
+//
+// var v []struct {
+// EnableSSO bool `json:"enable_sso,omitempty"`
+// Count int `json:"count,omitempty"`
+// }
+//
+// client.Setting.Query().
+// GroupBy(setting.FieldEnableSSO).
+// Aggregate(db.Count()).
+// Scan(ctx, &v)
+func (sq *SettingQuery) GroupBy(field string, fields ...string) *SettingGroupBy {
+ sq.ctx.Fields = append([]string{field}, fields...)
+ grbuild := &SettingGroupBy{build: sq}
+ grbuild.flds = &sq.ctx.Fields
+ grbuild.label = setting.Label
+ grbuild.scan = grbuild.Scan
+ return grbuild
+}
+
+// Select allows the selection one or more fields/columns for the given query,
+// instead of selecting all fields in the entity.
+//
+// Example:
+//
+// var v []struct {
+// EnableSSO bool `json:"enable_sso,omitempty"`
+// }
+//
+// client.Setting.Query().
+// Select(setting.FieldEnableSSO).
+// Scan(ctx, &v)
+func (sq *SettingQuery) Select(fields ...string) *SettingSelect {
+ sq.ctx.Fields = append(sq.ctx.Fields, fields...)
+ sbuild := &SettingSelect{SettingQuery: sq}
+ sbuild.label = setting.Label
+ sbuild.flds, sbuild.scan = &sq.ctx.Fields, sbuild.Scan
+ return sbuild
+}
+
+// Aggregate returns a SettingSelect configured with the given aggregations.
+func (sq *SettingQuery) Aggregate(fns ...AggregateFunc) *SettingSelect {
+ return sq.Select().Aggregate(fns...)
+}
+
+func (sq *SettingQuery) prepareQuery(ctx context.Context) error {
+ for _, inter := range sq.inters {
+ if inter == nil {
+ return fmt.Errorf("db: uninitialized interceptor (forgotten import db/runtime?)")
+ }
+ if trv, ok := inter.(Traverser); ok {
+ if err := trv.Traverse(ctx, sq); err != nil {
+ return err
+ }
+ }
+ }
+ for _, f := range sq.ctx.Fields {
+ if !setting.ValidColumn(f) {
+ return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
+ }
+ }
+ if sq.path != nil {
+ prev, err := sq.path(ctx)
+ if err != nil {
+ return err
+ }
+ sq.sql = prev
+ }
+ return nil
+}
+
+func (sq *SettingQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Setting, error) {
+ var (
+ nodes = []*Setting{}
+ _spec = sq.querySpec()
+ )
+ _spec.ScanValues = func(columns []string) ([]any, error) {
+ return (*Setting).scanValues(nil, columns)
+ }
+ _spec.Assign = func(columns []string, values []any) error {
+ node := &Setting{config: sq.config}
+ nodes = append(nodes, node)
+ return node.assignValues(columns, values)
+ }
+ if len(sq.modifiers) > 0 {
+ _spec.Modifiers = sq.modifiers
+ }
+ for i := range hooks {
+ hooks[i](ctx, _spec)
+ }
+ if err := sqlgraph.QueryNodes(ctx, sq.driver, _spec); err != nil {
+ return nil, err
+ }
+ if len(nodes) == 0 {
+ return nodes, nil
+ }
+ return nodes, nil
+}
+
+func (sq *SettingQuery) sqlCount(ctx context.Context) (int, error) {
+ _spec := sq.querySpec()
+ if len(sq.modifiers) > 0 {
+ _spec.Modifiers = sq.modifiers
+ }
+ _spec.Node.Columns = sq.ctx.Fields
+ if len(sq.ctx.Fields) > 0 {
+ _spec.Unique = sq.ctx.Unique != nil && *sq.ctx.Unique
+ }
+ return sqlgraph.CountNodes(ctx, sq.driver, _spec)
+}
+
+func (sq *SettingQuery) querySpec() *sqlgraph.QuerySpec {
+ _spec := sqlgraph.NewQuerySpec(setting.Table, setting.Columns, sqlgraph.NewFieldSpec(setting.FieldID, field.TypeUUID))
+ _spec.From = sq.sql
+ if unique := sq.ctx.Unique; unique != nil {
+ _spec.Unique = *unique
+ } else if sq.path != nil {
+ _spec.Unique = true
+ }
+ if fields := sq.ctx.Fields; len(fields) > 0 {
+ _spec.Node.Columns = make([]string, 0, len(fields))
+ _spec.Node.Columns = append(_spec.Node.Columns, setting.FieldID)
+ for i := range fields {
+ if fields[i] != setting.FieldID {
+ _spec.Node.Columns = append(_spec.Node.Columns, fields[i])
+ }
+ }
+ }
+ if ps := sq.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if limit := sq.ctx.Limit; limit != nil {
+ _spec.Limit = *limit
+ }
+ if offset := sq.ctx.Offset; offset != nil {
+ _spec.Offset = *offset
+ }
+ if ps := sq.order; len(ps) > 0 {
+ _spec.Order = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ return _spec
+}
+
+func (sq *SettingQuery) sqlQuery(ctx context.Context) *sql.Selector {
+ builder := sql.Dialect(sq.driver.Dialect())
+ t1 := builder.Table(setting.Table)
+ columns := sq.ctx.Fields
+ if len(columns) == 0 {
+ columns = setting.Columns
+ }
+ selector := builder.Select(t1.Columns(columns...)...).From(t1)
+ if sq.sql != nil {
+ selector = sq.sql
+ selector.Select(selector.Columns(columns...)...)
+ }
+ if sq.ctx.Unique != nil && *sq.ctx.Unique {
+ selector.Distinct()
+ }
+ for _, m := range sq.modifiers {
+ m(selector)
+ }
+ for _, p := range sq.predicates {
+ p(selector)
+ }
+ for _, p := range sq.order {
+ p(selector)
+ }
+ if offset := sq.ctx.Offset; offset != nil {
+ // limit is mandatory for offset clause. We start
+ // with default value, and override it below if needed.
+ selector.Offset(*offset).Limit(math.MaxInt32)
+ }
+ if limit := sq.ctx.Limit; limit != nil {
+ selector.Limit(*limit)
+ }
+ return selector
+}
+
+// ForUpdate locks the selected rows against concurrent updates, and prevent them from being
+// updated, deleted or "selected ... for update" by other sessions, until the transaction is
+// either committed or rolled-back.
+func (sq *SettingQuery) ForUpdate(opts ...sql.LockOption) *SettingQuery {
+ if sq.driver.Dialect() == dialect.Postgres {
+ sq.Unique(false)
+ }
+ sq.modifiers = append(sq.modifiers, func(s *sql.Selector) {
+ s.ForUpdate(opts...)
+ })
+ return sq
+}
+
+// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock
+// on any rows that are read. Other sessions can read the rows, but cannot modify them
+// until your transaction commits.
+func (sq *SettingQuery) ForShare(opts ...sql.LockOption) *SettingQuery {
+ if sq.driver.Dialect() == dialect.Postgres {
+ sq.Unique(false)
+ }
+ sq.modifiers = append(sq.modifiers, func(s *sql.Selector) {
+ s.ForShare(opts...)
+ })
+ return sq
+}
+
+// Modify adds a query modifier for attaching custom logic to queries.
+func (sq *SettingQuery) Modify(modifiers ...func(s *sql.Selector)) *SettingSelect {
+ sq.modifiers = append(sq.modifiers, modifiers...)
+ return sq.Select()
+}
+
+// SettingGroupBy is the group-by builder for Setting entities.
+type SettingGroupBy struct {
+ selector
+ build *SettingQuery
+}
+
+// Aggregate adds the given aggregation functions to the group-by query.
+func (sgb *SettingGroupBy) Aggregate(fns ...AggregateFunc) *SettingGroupBy {
+ sgb.fns = append(sgb.fns, fns...)
+ return sgb
+}
+
+// Scan applies the selector query and scans the result into the given value.
+func (sgb *SettingGroupBy) Scan(ctx context.Context, v any) error {
+ ctx = setContextOp(ctx, sgb.build.ctx, ent.OpQueryGroupBy)
+ if err := sgb.build.prepareQuery(ctx); err != nil {
+ return err
+ }
+ return scanWithInterceptors[*SettingQuery, *SettingGroupBy](ctx, sgb.build, sgb, sgb.build.inters, v)
+}
+
+func (sgb *SettingGroupBy) sqlScan(ctx context.Context, root *SettingQuery, v any) error {
+ selector := root.sqlQuery(ctx).Select()
+ aggregation := make([]string, 0, len(sgb.fns))
+ for _, fn := range sgb.fns {
+ aggregation = append(aggregation, fn(selector))
+ }
+ if len(selector.SelectedColumns()) == 0 {
+ columns := make([]string, 0, len(*sgb.flds)+len(sgb.fns))
+ for _, f := range *sgb.flds {
+ columns = append(columns, selector.C(f))
+ }
+ columns = append(columns, aggregation...)
+ selector.Select(columns...)
+ }
+ selector.GroupBy(selector.Columns(*sgb.flds...)...)
+ if err := selector.Err(); err != nil {
+ return err
+ }
+ rows := &sql.Rows{}
+ query, args := selector.Query()
+ if err := sgb.build.driver.Query(ctx, query, args, rows); err != nil {
+ return err
+ }
+ defer rows.Close()
+ return sql.ScanSlice(rows, v)
+}
+
+// SettingSelect is the builder for selecting fields of Setting entities.
+type SettingSelect struct {
+ *SettingQuery
+ selector
+}
+
+// Aggregate adds the given aggregation functions to the selector query.
+func (ss *SettingSelect) Aggregate(fns ...AggregateFunc) *SettingSelect {
+ ss.fns = append(ss.fns, fns...)
+ return ss
+}
+
+// Scan applies the selector query and scans the result into the given value.
+func (ss *SettingSelect) Scan(ctx context.Context, v any) error {
+ ctx = setContextOp(ctx, ss.ctx, ent.OpQuerySelect)
+ if err := ss.prepareQuery(ctx); err != nil {
+ return err
+ }
+ return scanWithInterceptors[*SettingQuery, *SettingSelect](ctx, ss.SettingQuery, ss, ss.inters, v)
+}
+
+func (ss *SettingSelect) sqlScan(ctx context.Context, root *SettingQuery, v any) error {
+ selector := root.sqlQuery(ctx)
+ aggregation := make([]string, 0, len(ss.fns))
+ for _, fn := range ss.fns {
+ aggregation = append(aggregation, fn(selector))
+ }
+ switch n := len(*ss.selector.flds); {
+ case n == 0 && len(aggregation) > 0:
+ selector.Select(aggregation...)
+ case n != 0 && len(aggregation) > 0:
+ selector.AppendSelect(aggregation...)
+ }
+ rows := &sql.Rows{}
+ query, args := selector.Query()
+ if err := ss.driver.Query(ctx, query, args, rows); err != nil {
+ return err
+ }
+ defer rows.Close()
+ return sql.ScanSlice(rows, v)
+}
+
+// Modify adds a query modifier for attaching custom logic to queries.
+func (ss *SettingSelect) Modify(modifiers ...func(s *sql.Selector)) *SettingSelect {
+ ss.modifiers = append(ss.modifiers, modifiers...)
+ return ss
+}
diff --git a/backend/db/setting_update.go b/backend/db/setting_update.go
new file mode 100644
index 0000000..5028777
--- /dev/null
+++ b/backend/db/setting_update.go
@@ -0,0 +1,364 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "time"
+
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+ "github.com/chaitin/MonkeyCode/backend/db/setting"
+)
+
+// SettingUpdate is the builder for updating Setting entities.
+type SettingUpdate struct {
+ config
+ hooks []Hook
+ mutation *SettingMutation
+ modifiers []func(*sql.UpdateBuilder)
+}
+
+// Where appends a list predicates to the SettingUpdate builder.
+func (su *SettingUpdate) Where(ps ...predicate.Setting) *SettingUpdate {
+ su.mutation.Where(ps...)
+ return su
+}
+
+// SetEnableSSO sets the "enable_sso" field.
+func (su *SettingUpdate) SetEnableSSO(b bool) *SettingUpdate {
+ su.mutation.SetEnableSSO(b)
+ return su
+}
+
+// SetNillableEnableSSO sets the "enable_sso" field if the given value is not nil.
+func (su *SettingUpdate) SetNillableEnableSSO(b *bool) *SettingUpdate {
+ if b != nil {
+ su.SetEnableSSO(*b)
+ }
+ return su
+}
+
+// SetForceTwoFactorAuth sets the "force_two_factor_auth" field.
+func (su *SettingUpdate) SetForceTwoFactorAuth(b bool) *SettingUpdate {
+ su.mutation.SetForceTwoFactorAuth(b)
+ return su
+}
+
+// SetNillableForceTwoFactorAuth sets the "force_two_factor_auth" field if the given value is not nil.
+func (su *SettingUpdate) SetNillableForceTwoFactorAuth(b *bool) *SettingUpdate {
+ if b != nil {
+ su.SetForceTwoFactorAuth(*b)
+ }
+ return su
+}
+
+// SetDisablePasswordLogin sets the "disable_password_login" field.
+func (su *SettingUpdate) SetDisablePasswordLogin(b bool) *SettingUpdate {
+ su.mutation.SetDisablePasswordLogin(b)
+ return su
+}
+
+// SetNillableDisablePasswordLogin sets the "disable_password_login" field if the given value is not nil.
+func (su *SettingUpdate) SetNillableDisablePasswordLogin(b *bool) *SettingUpdate {
+ if b != nil {
+ su.SetDisablePasswordLogin(*b)
+ }
+ return su
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (su *SettingUpdate) SetCreatedAt(t time.Time) *SettingUpdate {
+ su.mutation.SetCreatedAt(t)
+ return su
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (su *SettingUpdate) SetNillableCreatedAt(t *time.Time) *SettingUpdate {
+ if t != nil {
+ su.SetCreatedAt(*t)
+ }
+ return su
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (su *SettingUpdate) SetUpdatedAt(t time.Time) *SettingUpdate {
+ su.mutation.SetUpdatedAt(t)
+ return su
+}
+
+// Mutation returns the SettingMutation object of the builder.
+func (su *SettingUpdate) Mutation() *SettingMutation {
+ return su.mutation
+}
+
+// Save executes the query and returns the number of nodes affected by the update operation.
+func (su *SettingUpdate) Save(ctx context.Context) (int, error) {
+ su.defaults()
+ return withHooks(ctx, su.sqlSave, su.mutation, su.hooks)
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (su *SettingUpdate) SaveX(ctx context.Context) int {
+ affected, err := su.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return affected
+}
+
+// Exec executes the query.
+func (su *SettingUpdate) Exec(ctx context.Context) error {
+ _, err := su.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (su *SettingUpdate) ExecX(ctx context.Context) {
+ if err := su.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// defaults sets the default values of the builder before save.
+func (su *SettingUpdate) defaults() {
+ if _, ok := su.mutation.UpdatedAt(); !ok {
+ v := setting.UpdateDefaultUpdatedAt()
+ su.mutation.SetUpdatedAt(v)
+ }
+}
+
+// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
+func (su *SettingUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *SettingUpdate {
+ su.modifiers = append(su.modifiers, modifiers...)
+ return su
+}
+
+func (su *SettingUpdate) sqlSave(ctx context.Context) (n int, err error) {
+ _spec := sqlgraph.NewUpdateSpec(setting.Table, setting.Columns, sqlgraph.NewFieldSpec(setting.FieldID, field.TypeUUID))
+ if ps := su.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if value, ok := su.mutation.EnableSSO(); ok {
+ _spec.SetField(setting.FieldEnableSSO, field.TypeBool, value)
+ }
+ if value, ok := su.mutation.ForceTwoFactorAuth(); ok {
+ _spec.SetField(setting.FieldForceTwoFactorAuth, field.TypeBool, value)
+ }
+ if value, ok := su.mutation.DisablePasswordLogin(); ok {
+ _spec.SetField(setting.FieldDisablePasswordLogin, field.TypeBool, value)
+ }
+ if value, ok := su.mutation.CreatedAt(); ok {
+ _spec.SetField(setting.FieldCreatedAt, field.TypeTime, value)
+ }
+ if value, ok := su.mutation.UpdatedAt(); ok {
+ _spec.SetField(setting.FieldUpdatedAt, field.TypeTime, value)
+ }
+ _spec.AddModifiers(su.modifiers...)
+ if n, err = sqlgraph.UpdateNodes(ctx, su.driver, _spec); err != nil {
+ if _, ok := err.(*sqlgraph.NotFoundError); ok {
+ err = &NotFoundError{setting.Label}
+ } else if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return 0, err
+ }
+ su.mutation.done = true
+ return n, nil
+}
+
+// SettingUpdateOne is the builder for updating a single Setting entity.
+type SettingUpdateOne struct {
+ config
+ fields []string
+ hooks []Hook
+ mutation *SettingMutation
+ modifiers []func(*sql.UpdateBuilder)
+}
+
+// SetEnableSSO sets the "enable_sso" field.
+func (suo *SettingUpdateOne) SetEnableSSO(b bool) *SettingUpdateOne {
+ suo.mutation.SetEnableSSO(b)
+ return suo
+}
+
+// SetNillableEnableSSO sets the "enable_sso" field if the given value is not nil.
+func (suo *SettingUpdateOne) SetNillableEnableSSO(b *bool) *SettingUpdateOne {
+ if b != nil {
+ suo.SetEnableSSO(*b)
+ }
+ return suo
+}
+
+// SetForceTwoFactorAuth sets the "force_two_factor_auth" field.
+func (suo *SettingUpdateOne) SetForceTwoFactorAuth(b bool) *SettingUpdateOne {
+ suo.mutation.SetForceTwoFactorAuth(b)
+ return suo
+}
+
+// SetNillableForceTwoFactorAuth sets the "force_two_factor_auth" field if the given value is not nil.
+func (suo *SettingUpdateOne) SetNillableForceTwoFactorAuth(b *bool) *SettingUpdateOne {
+ if b != nil {
+ suo.SetForceTwoFactorAuth(*b)
+ }
+ return suo
+}
+
+// SetDisablePasswordLogin sets the "disable_password_login" field.
+func (suo *SettingUpdateOne) SetDisablePasswordLogin(b bool) *SettingUpdateOne {
+ suo.mutation.SetDisablePasswordLogin(b)
+ return suo
+}
+
+// SetNillableDisablePasswordLogin sets the "disable_password_login" field if the given value is not nil.
+func (suo *SettingUpdateOne) SetNillableDisablePasswordLogin(b *bool) *SettingUpdateOne {
+ if b != nil {
+ suo.SetDisablePasswordLogin(*b)
+ }
+ return suo
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (suo *SettingUpdateOne) SetCreatedAt(t time.Time) *SettingUpdateOne {
+ suo.mutation.SetCreatedAt(t)
+ return suo
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (suo *SettingUpdateOne) SetNillableCreatedAt(t *time.Time) *SettingUpdateOne {
+ if t != nil {
+ suo.SetCreatedAt(*t)
+ }
+ return suo
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (suo *SettingUpdateOne) SetUpdatedAt(t time.Time) *SettingUpdateOne {
+ suo.mutation.SetUpdatedAt(t)
+ return suo
+}
+
+// Mutation returns the SettingMutation object of the builder.
+func (suo *SettingUpdateOne) Mutation() *SettingMutation {
+ return suo.mutation
+}
+
+// Where appends a list predicates to the SettingUpdate builder.
+func (suo *SettingUpdateOne) Where(ps ...predicate.Setting) *SettingUpdateOne {
+ suo.mutation.Where(ps...)
+ return suo
+}
+
+// Select allows selecting one or more fields (columns) of the returned entity.
+// The default is selecting all fields defined in the entity schema.
+func (suo *SettingUpdateOne) Select(field string, fields ...string) *SettingUpdateOne {
+ suo.fields = append([]string{field}, fields...)
+ return suo
+}
+
+// Save executes the query and returns the updated Setting entity.
+func (suo *SettingUpdateOne) Save(ctx context.Context) (*Setting, error) {
+ suo.defaults()
+ return withHooks(ctx, suo.sqlSave, suo.mutation, suo.hooks)
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (suo *SettingUpdateOne) SaveX(ctx context.Context) *Setting {
+ node, err := suo.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return node
+}
+
+// Exec executes the query on the entity.
+func (suo *SettingUpdateOne) Exec(ctx context.Context) error {
+ _, err := suo.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (suo *SettingUpdateOne) ExecX(ctx context.Context) {
+ if err := suo.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// defaults sets the default values of the builder before save.
+func (suo *SettingUpdateOne) defaults() {
+ if _, ok := suo.mutation.UpdatedAt(); !ok {
+ v := setting.UpdateDefaultUpdatedAt()
+ suo.mutation.SetUpdatedAt(v)
+ }
+}
+
+// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
+func (suo *SettingUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *SettingUpdateOne {
+ suo.modifiers = append(suo.modifiers, modifiers...)
+ return suo
+}
+
+func (suo *SettingUpdateOne) sqlSave(ctx context.Context) (_node *Setting, err error) {
+ _spec := sqlgraph.NewUpdateSpec(setting.Table, setting.Columns, sqlgraph.NewFieldSpec(setting.FieldID, field.TypeUUID))
+ id, ok := suo.mutation.ID()
+ if !ok {
+ return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "Setting.id" for update`)}
+ }
+ _spec.Node.ID.Value = id
+ if fields := suo.fields; len(fields) > 0 {
+ _spec.Node.Columns = make([]string, 0, len(fields))
+ _spec.Node.Columns = append(_spec.Node.Columns, setting.FieldID)
+ for _, f := range fields {
+ if !setting.ValidColumn(f) {
+ return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
+ }
+ if f != setting.FieldID {
+ _spec.Node.Columns = append(_spec.Node.Columns, f)
+ }
+ }
+ }
+ if ps := suo.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if value, ok := suo.mutation.EnableSSO(); ok {
+ _spec.SetField(setting.FieldEnableSSO, field.TypeBool, value)
+ }
+ if value, ok := suo.mutation.ForceTwoFactorAuth(); ok {
+ _spec.SetField(setting.FieldForceTwoFactorAuth, field.TypeBool, value)
+ }
+ if value, ok := suo.mutation.DisablePasswordLogin(); ok {
+ _spec.SetField(setting.FieldDisablePasswordLogin, field.TypeBool, value)
+ }
+ if value, ok := suo.mutation.CreatedAt(); ok {
+ _spec.SetField(setting.FieldCreatedAt, field.TypeTime, value)
+ }
+ if value, ok := suo.mutation.UpdatedAt(); ok {
+ _spec.SetField(setting.FieldUpdatedAt, field.TypeTime, value)
+ }
+ _spec.AddModifiers(suo.modifiers...)
+ _node = &Setting{config: suo.config}
+ _spec.Assign = _node.assignValues
+ _spec.ScanValues = _node.scanValues
+ if err = sqlgraph.UpdateNode(ctx, suo.driver, _spec); err != nil {
+ if _, ok := err.(*sqlgraph.NotFoundError); ok {
+ err = &NotFoundError{setting.Label}
+ } else if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return nil, err
+ }
+ suo.mutation.done = true
+ return _node, nil
+}
diff --git a/backend/db/tx.go b/backend/db/tx.go
new file mode 100644
index 0000000..7d53b1f
--- /dev/null
+++ b/backend/db/tx.go
@@ -0,0 +1,272 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ stdsql "database/sql"
+ "fmt"
+ "sync"
+
+ "entgo.io/ent/dialect"
+)
+
+// Tx is a transactional client that is created by calling Client.Tx().
+type Tx struct {
+ config
+ // Admin is the client for interacting with the Admin builders.
+ Admin *AdminClient
+ // AdminLoginHistory is the client for interacting with the AdminLoginHistory builders.
+ AdminLoginHistory *AdminLoginHistoryClient
+ // ApiKey is the client for interacting with the ApiKey builders.
+ ApiKey *ApiKeyClient
+ // BillingPlan is the client for interacting with the BillingPlan builders.
+ BillingPlan *BillingPlanClient
+ // BillingQuota is the client for interacting with the BillingQuota builders.
+ BillingQuota *BillingQuotaClient
+ // BillingRecord is the client for interacting with the BillingRecord builders.
+ BillingRecord *BillingRecordClient
+ // BillingUsage is the client for interacting with the BillingUsage builders.
+ BillingUsage *BillingUsageClient
+ // InviteCode is the client for interacting with the InviteCode builders.
+ InviteCode *InviteCodeClient
+ // Model is the client for interacting with the Model builders.
+ Model *ModelClient
+ // Record is the client for interacting with the Record builders.
+ Record *RecordClient
+ // Setting is the client for interacting with the Setting builders.
+ Setting *SettingClient
+ // User is the client for interacting with the User builders.
+ User *UserClient
+ // UserLoginHistory is the client for interacting with the UserLoginHistory builders.
+ UserLoginHistory *UserLoginHistoryClient
+
+ // lazily loaded.
+ client *Client
+ clientOnce sync.Once
+ // ctx lives for the life of the transaction. It is
+ // the same context used by the underlying connection.
+ ctx context.Context
+}
+
+type (
+ // Committer is the interface that wraps the Commit method.
+ Committer interface {
+ Commit(context.Context, *Tx) error
+ }
+
+ // The CommitFunc type is an adapter to allow the use of ordinary
+ // function as a Committer. If f is a function with the appropriate
+ // signature, CommitFunc(f) is a Committer that calls f.
+ CommitFunc func(context.Context, *Tx) error
+
+ // CommitHook defines the "commit middleware". A function that gets a Committer
+ // and returns a Committer. For example:
+ //
+ // hook := func(next ent.Committer) ent.Committer {
+ // return ent.CommitFunc(func(ctx context.Context, tx *ent.Tx) error {
+ // // Do some stuff before.
+ // if err := next.Commit(ctx, tx); err != nil {
+ // return err
+ // }
+ // // Do some stuff after.
+ // return nil
+ // })
+ // }
+ //
+ CommitHook func(Committer) Committer
+)
+
+// Commit calls f(ctx, m).
+func (f CommitFunc) Commit(ctx context.Context, tx *Tx) error {
+ return f(ctx, tx)
+}
+
+// Commit commits the transaction.
+func (tx *Tx) Commit() error {
+ txDriver := tx.config.driver.(*txDriver)
+ var fn Committer = CommitFunc(func(context.Context, *Tx) error {
+ return txDriver.tx.Commit()
+ })
+ txDriver.mu.Lock()
+ hooks := append([]CommitHook(nil), txDriver.onCommit...)
+ txDriver.mu.Unlock()
+ for i := len(hooks) - 1; i >= 0; i-- {
+ fn = hooks[i](fn)
+ }
+ return fn.Commit(tx.ctx, tx)
+}
+
+// OnCommit adds a hook to call on commit.
+func (tx *Tx) OnCommit(f CommitHook) {
+ txDriver := tx.config.driver.(*txDriver)
+ txDriver.mu.Lock()
+ txDriver.onCommit = append(txDriver.onCommit, f)
+ txDriver.mu.Unlock()
+}
+
+type (
+ // Rollbacker is the interface that wraps the Rollback method.
+ Rollbacker interface {
+ Rollback(context.Context, *Tx) error
+ }
+
+ // The RollbackFunc type is an adapter to allow the use of ordinary
+ // function as a Rollbacker. If f is a function with the appropriate
+ // signature, RollbackFunc(f) is a Rollbacker that calls f.
+ RollbackFunc func(context.Context, *Tx) error
+
+ // RollbackHook defines the "rollback middleware". A function that gets a Rollbacker
+ // and returns a Rollbacker. For example:
+ //
+ // hook := func(next ent.Rollbacker) ent.Rollbacker {
+ // return ent.RollbackFunc(func(ctx context.Context, tx *ent.Tx) error {
+ // // Do some stuff before.
+ // if err := next.Rollback(ctx, tx); err != nil {
+ // return err
+ // }
+ // // Do some stuff after.
+ // return nil
+ // })
+ // }
+ //
+ RollbackHook func(Rollbacker) Rollbacker
+)
+
+// Rollback calls f(ctx, m).
+func (f RollbackFunc) Rollback(ctx context.Context, tx *Tx) error {
+ return f(ctx, tx)
+}
+
+// Rollback rollbacks the transaction.
+func (tx *Tx) Rollback() error {
+ txDriver := tx.config.driver.(*txDriver)
+ var fn Rollbacker = RollbackFunc(func(context.Context, *Tx) error {
+ return txDriver.tx.Rollback()
+ })
+ txDriver.mu.Lock()
+ hooks := append([]RollbackHook(nil), txDriver.onRollback...)
+ txDriver.mu.Unlock()
+ for i := len(hooks) - 1; i >= 0; i-- {
+ fn = hooks[i](fn)
+ }
+ return fn.Rollback(tx.ctx, tx)
+}
+
+// OnRollback adds a hook to call on rollback.
+func (tx *Tx) OnRollback(f RollbackHook) {
+ txDriver := tx.config.driver.(*txDriver)
+ txDriver.mu.Lock()
+ txDriver.onRollback = append(txDriver.onRollback, f)
+ txDriver.mu.Unlock()
+}
+
+// Client returns a Client that binds to current transaction.
+func (tx *Tx) Client() *Client {
+ tx.clientOnce.Do(func() {
+ tx.client = &Client{config: tx.config}
+ tx.client.init()
+ })
+ return tx.client
+}
+
+func (tx *Tx) init() {
+ tx.Admin = NewAdminClient(tx.config)
+ tx.AdminLoginHistory = NewAdminLoginHistoryClient(tx.config)
+ tx.ApiKey = NewApiKeyClient(tx.config)
+ tx.BillingPlan = NewBillingPlanClient(tx.config)
+ tx.BillingQuota = NewBillingQuotaClient(tx.config)
+ tx.BillingRecord = NewBillingRecordClient(tx.config)
+ tx.BillingUsage = NewBillingUsageClient(tx.config)
+ tx.InviteCode = NewInviteCodeClient(tx.config)
+ tx.Model = NewModelClient(tx.config)
+ tx.Record = NewRecordClient(tx.config)
+ tx.Setting = NewSettingClient(tx.config)
+ tx.User = NewUserClient(tx.config)
+ tx.UserLoginHistory = NewUserLoginHistoryClient(tx.config)
+}
+
+// txDriver wraps the given dialect.Tx with a nop dialect.Driver implementation.
+// The idea is to support transactions without adding any extra code to the builders.
+// When a builder calls to driver.Tx(), it gets the same dialect.Tx instance.
+// Commit and Rollback are nop for the internal builders and the user must call one
+// of them in order to commit or rollback the transaction.
+//
+// If a closed transaction is embedded in one of the generated entities, and the entity
+// applies a query, for example: Admin.QueryXXX(), the query will be executed
+// through the driver which created this transaction.
+//
+// Note that txDriver is not goroutine safe.
+type txDriver struct {
+ // the driver we started the transaction from.
+ drv dialect.Driver
+ // tx is the underlying transaction.
+ tx dialect.Tx
+ // completion hooks.
+ mu sync.Mutex
+ onCommit []CommitHook
+ onRollback []RollbackHook
+}
+
+// newTx creates a new transactional driver.
+func newTx(ctx context.Context, drv dialect.Driver) (*txDriver, error) {
+ tx, err := drv.Tx(ctx)
+ if err != nil {
+ return nil, err
+ }
+ return &txDriver{tx: tx, drv: drv}, nil
+}
+
+// Tx returns the transaction wrapper (txDriver) to avoid Commit or Rollback calls
+// from the internal builders. Should be called only by the internal builders.
+func (tx *txDriver) Tx(context.Context) (dialect.Tx, error) { return tx, nil }
+
+// Dialect returns the dialect of the driver we started the transaction from.
+func (tx *txDriver) Dialect() string { return tx.drv.Dialect() }
+
+// Close is a nop close.
+func (*txDriver) Close() error { return nil }
+
+// Commit is a nop commit for the internal builders.
+// User must call `Tx.Commit` in order to commit the transaction.
+func (*txDriver) Commit() error { return nil }
+
+// Rollback is a nop rollback for the internal builders.
+// User must call `Tx.Rollback` in order to rollback the transaction.
+func (*txDriver) Rollback() error { return nil }
+
+// Exec calls tx.Exec.
+func (tx *txDriver) Exec(ctx context.Context, query string, args, v any) error {
+ return tx.tx.Exec(ctx, query, args, v)
+}
+
+// Query calls tx.Query.
+func (tx *txDriver) Query(ctx context.Context, query string, args, v any) error {
+ return tx.tx.Query(ctx, query, args, v)
+}
+
+var _ dialect.Driver = (*txDriver)(nil)
+
+// ExecContext allows calling the underlying ExecContext method of the transaction if it is supported by it.
+// See, database/sql#Tx.ExecContext for more information.
+func (tx *txDriver) ExecContext(ctx context.Context, query string, args ...any) (stdsql.Result, error) {
+ ex, ok := tx.tx.(interface {
+ ExecContext(context.Context, string, ...any) (stdsql.Result, error)
+ })
+ if !ok {
+ return nil, fmt.Errorf("Tx.ExecContext is not supported")
+ }
+ return ex.ExecContext(ctx, query, args...)
+}
+
+// QueryContext allows calling the underlying QueryContext method of the transaction if it is supported by it.
+// See, database/sql#Tx.QueryContext for more information.
+func (tx *txDriver) QueryContext(ctx context.Context, query string, args ...any) (*stdsql.Rows, error) {
+ q, ok := tx.tx.(interface {
+ QueryContext(context.Context, string, ...any) (*stdsql.Rows, error)
+ })
+ if !ok {
+ return nil, fmt.Errorf("Tx.QueryContext is not supported")
+ }
+ return q.QueryContext(ctx, query, args...)
+}
diff --git a/backend/db/user.go b/backend/db/user.go
new file mode 100644
index 0000000..17c1c2a
--- /dev/null
+++ b/backend/db/user.go
@@ -0,0 +1,221 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "fmt"
+ "strings"
+ "time"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect/sql"
+ "github.com/chaitin/MonkeyCode/backend/consts"
+ "github.com/chaitin/MonkeyCode/backend/db/user"
+ "github.com/google/uuid"
+)
+
+// User is the model entity for the User schema.
+type User struct {
+ config `json:"-"`
+ // ID of the ent.
+ ID uuid.UUID `json:"id,omitempty"`
+ // Username holds the value of the "username" field.
+ Username string `json:"username,omitempty"`
+ // Password holds the value of the "password" field.
+ Password string `json:"password,omitempty"`
+ // Email holds the value of the "email" field.
+ Email string `json:"email,omitempty"`
+ // Status holds the value of the "status" field.
+ Status consts.UserStatus `json:"status,omitempty"`
+ // CreatedAt holds the value of the "created_at" field.
+ CreatedAt time.Time `json:"created_at,omitempty"`
+ // UpdatedAt holds the value of the "updated_at" field.
+ UpdatedAt time.Time `json:"updated_at,omitempty"`
+ // Edges holds the relations/edges for other nodes in the graph.
+ // The values are being populated by the UserQuery when eager-loading is set.
+ Edges UserEdges `json:"edges"`
+ selectValues sql.SelectValues
+}
+
+// UserEdges holds the relations/edges for other nodes in the graph.
+type UserEdges struct {
+ // Records holds the value of the records edge.
+ Records []*Record `json:"records,omitempty"`
+ // LoginHistories holds the value of the login_histories edge.
+ LoginHistories []*UserLoginHistory `json:"login_histories,omitempty"`
+ // Models holds the value of the models edge.
+ Models []*Model `json:"models,omitempty"`
+ // loadedTypes holds the information for reporting if a
+ // type was loaded (or requested) in eager-loading or not.
+ loadedTypes [3]bool
+}
+
+// RecordsOrErr returns the Records value or an error if the edge
+// was not loaded in eager-loading.
+func (e UserEdges) RecordsOrErr() ([]*Record, error) {
+ if e.loadedTypes[0] {
+ return e.Records, nil
+ }
+ return nil, &NotLoadedError{edge: "records"}
+}
+
+// LoginHistoriesOrErr returns the LoginHistories value or an error if the edge
+// was not loaded in eager-loading.
+func (e UserEdges) LoginHistoriesOrErr() ([]*UserLoginHistory, error) {
+ if e.loadedTypes[1] {
+ return e.LoginHistories, nil
+ }
+ return nil, &NotLoadedError{edge: "login_histories"}
+}
+
+// ModelsOrErr returns the Models value or an error if the edge
+// was not loaded in eager-loading.
+func (e UserEdges) ModelsOrErr() ([]*Model, error) {
+ if e.loadedTypes[2] {
+ return e.Models, nil
+ }
+ return nil, &NotLoadedError{edge: "models"}
+}
+
+// scanValues returns the types for scanning values from sql.Rows.
+func (*User) scanValues(columns []string) ([]any, error) {
+ values := make([]any, len(columns))
+ for i := range columns {
+ switch columns[i] {
+ case user.FieldUsername, user.FieldPassword, user.FieldEmail, user.FieldStatus:
+ values[i] = new(sql.NullString)
+ case user.FieldCreatedAt, user.FieldUpdatedAt:
+ values[i] = new(sql.NullTime)
+ case user.FieldID:
+ values[i] = new(uuid.UUID)
+ default:
+ values[i] = new(sql.UnknownType)
+ }
+ }
+ return values, nil
+}
+
+// assignValues assigns the values that were returned from sql.Rows (after scanning)
+// to the User fields.
+func (u *User) assignValues(columns []string, values []any) error {
+ if m, n := len(values), len(columns); m < n {
+ return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
+ }
+ for i := range columns {
+ switch columns[i] {
+ case user.FieldID:
+ if value, ok := values[i].(*uuid.UUID); !ok {
+ return fmt.Errorf("unexpected type %T for field id", values[i])
+ } else if value != nil {
+ u.ID = *value
+ }
+ case user.FieldUsername:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field username", values[i])
+ } else if value.Valid {
+ u.Username = value.String
+ }
+ case user.FieldPassword:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field password", values[i])
+ } else if value.Valid {
+ u.Password = value.String
+ }
+ case user.FieldEmail:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field email", values[i])
+ } else if value.Valid {
+ u.Email = value.String
+ }
+ case user.FieldStatus:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field status", values[i])
+ } else if value.Valid {
+ u.Status = consts.UserStatus(value.String)
+ }
+ case user.FieldCreatedAt:
+ if value, ok := values[i].(*sql.NullTime); !ok {
+ return fmt.Errorf("unexpected type %T for field created_at", values[i])
+ } else if value.Valid {
+ u.CreatedAt = value.Time
+ }
+ case user.FieldUpdatedAt:
+ if value, ok := values[i].(*sql.NullTime); !ok {
+ return fmt.Errorf("unexpected type %T for field updated_at", values[i])
+ } else if value.Valid {
+ u.UpdatedAt = value.Time
+ }
+ default:
+ u.selectValues.Set(columns[i], values[i])
+ }
+ }
+ return nil
+}
+
+// Value returns the ent.Value that was dynamically selected and assigned to the User.
+// This includes values selected through modifiers, order, etc.
+func (u *User) Value(name string) (ent.Value, error) {
+ return u.selectValues.Get(name)
+}
+
+// QueryRecords queries the "records" edge of the User entity.
+func (u *User) QueryRecords() *RecordQuery {
+ return NewUserClient(u.config).QueryRecords(u)
+}
+
+// QueryLoginHistories queries the "login_histories" edge of the User entity.
+func (u *User) QueryLoginHistories() *UserLoginHistoryQuery {
+ return NewUserClient(u.config).QueryLoginHistories(u)
+}
+
+// QueryModels queries the "models" edge of the User entity.
+func (u *User) QueryModels() *ModelQuery {
+ return NewUserClient(u.config).QueryModels(u)
+}
+
+// Update returns a builder for updating this User.
+// Note that you need to call User.Unwrap() before calling this method if this User
+// was returned from a transaction, and the transaction was committed or rolled back.
+func (u *User) Update() *UserUpdateOne {
+ return NewUserClient(u.config).UpdateOne(u)
+}
+
+// Unwrap unwraps the User entity that was returned from a transaction after it was closed,
+// so that all future queries will be executed through the driver which created the transaction.
+func (u *User) Unwrap() *User {
+ _tx, ok := u.config.driver.(*txDriver)
+ if !ok {
+ panic("db: User is not a transactional entity")
+ }
+ u.config.driver = _tx.drv
+ return u
+}
+
+// String implements the fmt.Stringer.
+func (u *User) String() string {
+ var builder strings.Builder
+ builder.WriteString("User(")
+ builder.WriteString(fmt.Sprintf("id=%v, ", u.ID))
+ builder.WriteString("username=")
+ builder.WriteString(u.Username)
+ builder.WriteString(", ")
+ builder.WriteString("password=")
+ builder.WriteString(u.Password)
+ builder.WriteString(", ")
+ builder.WriteString("email=")
+ builder.WriteString(u.Email)
+ builder.WriteString(", ")
+ builder.WriteString("status=")
+ builder.WriteString(fmt.Sprintf("%v", u.Status))
+ builder.WriteString(", ")
+ builder.WriteString("created_at=")
+ builder.WriteString(u.CreatedAt.Format(time.ANSIC))
+ builder.WriteString(", ")
+ builder.WriteString("updated_at=")
+ builder.WriteString(u.UpdatedAt.Format(time.ANSIC))
+ builder.WriteByte(')')
+ return builder.String()
+}
+
+// Users is a parsable slice of User.
+type Users []*User
diff --git a/backend/db/user/user.go b/backend/db/user/user.go
new file mode 100644
index 0000000..794ea11
--- /dev/null
+++ b/backend/db/user/user.go
@@ -0,0 +1,190 @@
+// Code generated by ent, DO NOT EDIT.
+
+package user
+
+import (
+ "time"
+
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "github.com/chaitin/MonkeyCode/backend/consts"
+)
+
+const (
+ // Label holds the string label denoting the user type in the database.
+ Label = "user"
+ // FieldID holds the string denoting the id field in the database.
+ FieldID = "id"
+ // FieldUsername holds the string denoting the username field in the database.
+ FieldUsername = "username"
+ // FieldPassword holds the string denoting the password field in the database.
+ FieldPassword = "password"
+ // FieldEmail holds the string denoting the email field in the database.
+ FieldEmail = "email"
+ // FieldStatus holds the string denoting the status field in the database.
+ FieldStatus = "status"
+ // FieldCreatedAt holds the string denoting the created_at field in the database.
+ FieldCreatedAt = "created_at"
+ // FieldUpdatedAt holds the string denoting the updated_at field in the database.
+ FieldUpdatedAt = "updated_at"
+ // EdgeRecords holds the string denoting the records edge name in mutations.
+ EdgeRecords = "records"
+ // EdgeLoginHistories holds the string denoting the login_histories edge name in mutations.
+ EdgeLoginHistories = "login_histories"
+ // EdgeModels holds the string denoting the models edge name in mutations.
+ EdgeModels = "models"
+ // Table holds the table name of the user in the database.
+ Table = "users"
+ // RecordsTable is the table that holds the records relation/edge.
+ RecordsTable = "records"
+ // RecordsInverseTable is the table name for the Record entity.
+ // It exists in this package in order to avoid circular dependency with the "record" package.
+ RecordsInverseTable = "records"
+ // RecordsColumn is the table column denoting the records relation/edge.
+ RecordsColumn = "user_id"
+ // LoginHistoriesTable is the table that holds the login_histories relation/edge.
+ LoginHistoriesTable = "user_login_histories"
+ // LoginHistoriesInverseTable is the table name for the UserLoginHistory entity.
+ // It exists in this package in order to avoid circular dependency with the "userloginhistory" package.
+ LoginHistoriesInverseTable = "user_login_histories"
+ // LoginHistoriesColumn is the table column denoting the login_histories relation/edge.
+ LoginHistoriesColumn = "user_login_histories"
+ // ModelsTable is the table that holds the models relation/edge.
+ ModelsTable = "models"
+ // ModelsInverseTable is the table name for the Model entity.
+ // It exists in this package in order to avoid circular dependency with the "model" package.
+ ModelsInverseTable = "models"
+ // ModelsColumn is the table column denoting the models relation/edge.
+ ModelsColumn = "user_id"
+)
+
+// Columns holds all SQL columns for user fields.
+var Columns = []string{
+ FieldID,
+ FieldUsername,
+ FieldPassword,
+ FieldEmail,
+ FieldStatus,
+ FieldCreatedAt,
+ FieldUpdatedAt,
+}
+
+// ValidColumn reports if the column name is valid (part of the table columns).
+func ValidColumn(column string) bool {
+ for i := range Columns {
+ if column == Columns[i] {
+ return true
+ }
+ }
+ return false
+}
+
+var (
+ // DefaultStatus holds the default value on creation for the "status" field.
+ DefaultStatus consts.UserStatus
+ // DefaultCreatedAt holds the default value on creation for the "created_at" field.
+ DefaultCreatedAt func() time.Time
+ // DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
+ DefaultUpdatedAt func() time.Time
+)
+
+// OrderOption defines the ordering options for the User queries.
+type OrderOption func(*sql.Selector)
+
+// ByID orders the results by the id field.
+func ByID(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldID, opts...).ToFunc()
+}
+
+// ByUsername orders the results by the username field.
+func ByUsername(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldUsername, opts...).ToFunc()
+}
+
+// ByPassword orders the results by the password field.
+func ByPassword(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldPassword, opts...).ToFunc()
+}
+
+// ByEmail orders the results by the email field.
+func ByEmail(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldEmail, opts...).ToFunc()
+}
+
+// ByStatus orders the results by the status field.
+func ByStatus(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldStatus, opts...).ToFunc()
+}
+
+// ByCreatedAt orders the results by the created_at field.
+func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
+}
+
+// ByUpdatedAt orders the results by the updated_at field.
+func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc()
+}
+
+// ByRecordsCount orders the results by records count.
+func ByRecordsCount(opts ...sql.OrderTermOption) OrderOption {
+ return func(s *sql.Selector) {
+ sqlgraph.OrderByNeighborsCount(s, newRecordsStep(), opts...)
+ }
+}
+
+// ByRecords orders the results by records terms.
+func ByRecords(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
+ return func(s *sql.Selector) {
+ sqlgraph.OrderByNeighborTerms(s, newRecordsStep(), append([]sql.OrderTerm{term}, terms...)...)
+ }
+}
+
+// ByLoginHistoriesCount orders the results by login_histories count.
+func ByLoginHistoriesCount(opts ...sql.OrderTermOption) OrderOption {
+ return func(s *sql.Selector) {
+ sqlgraph.OrderByNeighborsCount(s, newLoginHistoriesStep(), opts...)
+ }
+}
+
+// ByLoginHistories orders the results by login_histories terms.
+func ByLoginHistories(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
+ return func(s *sql.Selector) {
+ sqlgraph.OrderByNeighborTerms(s, newLoginHistoriesStep(), append([]sql.OrderTerm{term}, terms...)...)
+ }
+}
+
+// ByModelsCount orders the results by models count.
+func ByModelsCount(opts ...sql.OrderTermOption) OrderOption {
+ return func(s *sql.Selector) {
+ sqlgraph.OrderByNeighborsCount(s, newModelsStep(), opts...)
+ }
+}
+
+// ByModels orders the results by models terms.
+func ByModels(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
+ return func(s *sql.Selector) {
+ sqlgraph.OrderByNeighborTerms(s, newModelsStep(), append([]sql.OrderTerm{term}, terms...)...)
+ }
+}
+func newRecordsStep() *sqlgraph.Step {
+ return sqlgraph.NewStep(
+ sqlgraph.From(Table, FieldID),
+ sqlgraph.To(RecordsInverseTable, FieldID),
+ sqlgraph.Edge(sqlgraph.O2M, false, RecordsTable, RecordsColumn),
+ )
+}
+func newLoginHistoriesStep() *sqlgraph.Step {
+ return sqlgraph.NewStep(
+ sqlgraph.From(Table, FieldID),
+ sqlgraph.To(LoginHistoriesInverseTable, FieldID),
+ sqlgraph.Edge(sqlgraph.O2M, false, LoginHistoriesTable, LoginHistoriesColumn),
+ )
+}
+func newModelsStep() *sqlgraph.Step {
+ return sqlgraph.NewStep(
+ sqlgraph.From(Table, FieldID),
+ sqlgraph.To(ModelsInverseTable, FieldID),
+ sqlgraph.Edge(sqlgraph.O2M, false, ModelsTable, ModelsColumn),
+ )
+}
diff --git a/backend/db/user/where.go b/backend/db/user/where.go
new file mode 100644
index 0000000..792403f
--- /dev/null
+++ b/backend/db/user/where.go
@@ -0,0 +1,532 @@
+// Code generated by ent, DO NOT EDIT.
+
+package user
+
+import (
+ "time"
+
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "github.com/chaitin/MonkeyCode/backend/consts"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+ "github.com/google/uuid"
+)
+
+// ID filters vertices based on their ID field.
+func ID(id uuid.UUID) predicate.User {
+ return predicate.User(sql.FieldEQ(FieldID, id))
+}
+
+// IDEQ applies the EQ predicate on the ID field.
+func IDEQ(id uuid.UUID) predicate.User {
+ return predicate.User(sql.FieldEQ(FieldID, id))
+}
+
+// IDNEQ applies the NEQ predicate on the ID field.
+func IDNEQ(id uuid.UUID) predicate.User {
+ return predicate.User(sql.FieldNEQ(FieldID, id))
+}
+
+// IDIn applies the In predicate on the ID field.
+func IDIn(ids ...uuid.UUID) predicate.User {
+ return predicate.User(sql.FieldIn(FieldID, ids...))
+}
+
+// IDNotIn applies the NotIn predicate on the ID field.
+func IDNotIn(ids ...uuid.UUID) predicate.User {
+ return predicate.User(sql.FieldNotIn(FieldID, ids...))
+}
+
+// IDGT applies the GT predicate on the ID field.
+func IDGT(id uuid.UUID) predicate.User {
+ return predicate.User(sql.FieldGT(FieldID, id))
+}
+
+// IDGTE applies the GTE predicate on the ID field.
+func IDGTE(id uuid.UUID) predicate.User {
+ return predicate.User(sql.FieldGTE(FieldID, id))
+}
+
+// IDLT applies the LT predicate on the ID field.
+func IDLT(id uuid.UUID) predicate.User {
+ return predicate.User(sql.FieldLT(FieldID, id))
+}
+
+// IDLTE applies the LTE predicate on the ID field.
+func IDLTE(id uuid.UUID) predicate.User {
+ return predicate.User(sql.FieldLTE(FieldID, id))
+}
+
+// Username applies equality check predicate on the "username" field. It's identical to UsernameEQ.
+func Username(v string) predicate.User {
+ return predicate.User(sql.FieldEQ(FieldUsername, v))
+}
+
+// Password applies equality check predicate on the "password" field. It's identical to PasswordEQ.
+func Password(v string) predicate.User {
+ return predicate.User(sql.FieldEQ(FieldPassword, v))
+}
+
+// Email applies equality check predicate on the "email" field. It's identical to EmailEQ.
+func Email(v string) predicate.User {
+ return predicate.User(sql.FieldEQ(FieldEmail, v))
+}
+
+// Status applies equality check predicate on the "status" field. It's identical to StatusEQ.
+func Status(v consts.UserStatus) predicate.User {
+ vc := string(v)
+ return predicate.User(sql.FieldEQ(FieldStatus, vc))
+}
+
+// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
+func CreatedAt(v time.Time) predicate.User {
+ return predicate.User(sql.FieldEQ(FieldCreatedAt, v))
+}
+
+// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
+func UpdatedAt(v time.Time) predicate.User {
+ return predicate.User(sql.FieldEQ(FieldUpdatedAt, v))
+}
+
+// UsernameEQ applies the EQ predicate on the "username" field.
+func UsernameEQ(v string) predicate.User {
+ return predicate.User(sql.FieldEQ(FieldUsername, v))
+}
+
+// UsernameNEQ applies the NEQ predicate on the "username" field.
+func UsernameNEQ(v string) predicate.User {
+ return predicate.User(sql.FieldNEQ(FieldUsername, v))
+}
+
+// UsernameIn applies the In predicate on the "username" field.
+func UsernameIn(vs ...string) predicate.User {
+ return predicate.User(sql.FieldIn(FieldUsername, vs...))
+}
+
+// UsernameNotIn applies the NotIn predicate on the "username" field.
+func UsernameNotIn(vs ...string) predicate.User {
+ return predicate.User(sql.FieldNotIn(FieldUsername, vs...))
+}
+
+// UsernameGT applies the GT predicate on the "username" field.
+func UsernameGT(v string) predicate.User {
+ return predicate.User(sql.FieldGT(FieldUsername, v))
+}
+
+// UsernameGTE applies the GTE predicate on the "username" field.
+func UsernameGTE(v string) predicate.User {
+ return predicate.User(sql.FieldGTE(FieldUsername, v))
+}
+
+// UsernameLT applies the LT predicate on the "username" field.
+func UsernameLT(v string) predicate.User {
+ return predicate.User(sql.FieldLT(FieldUsername, v))
+}
+
+// UsernameLTE applies the LTE predicate on the "username" field.
+func UsernameLTE(v string) predicate.User {
+ return predicate.User(sql.FieldLTE(FieldUsername, v))
+}
+
+// UsernameContains applies the Contains predicate on the "username" field.
+func UsernameContains(v string) predicate.User {
+ return predicate.User(sql.FieldContains(FieldUsername, v))
+}
+
+// UsernameHasPrefix applies the HasPrefix predicate on the "username" field.
+func UsernameHasPrefix(v string) predicate.User {
+ return predicate.User(sql.FieldHasPrefix(FieldUsername, v))
+}
+
+// UsernameHasSuffix applies the HasSuffix predicate on the "username" field.
+func UsernameHasSuffix(v string) predicate.User {
+ return predicate.User(sql.FieldHasSuffix(FieldUsername, v))
+}
+
+// UsernameEqualFold applies the EqualFold predicate on the "username" field.
+func UsernameEqualFold(v string) predicate.User {
+ return predicate.User(sql.FieldEqualFold(FieldUsername, v))
+}
+
+// UsernameContainsFold applies the ContainsFold predicate on the "username" field.
+func UsernameContainsFold(v string) predicate.User {
+ return predicate.User(sql.FieldContainsFold(FieldUsername, v))
+}
+
+// PasswordEQ applies the EQ predicate on the "password" field.
+func PasswordEQ(v string) predicate.User {
+ return predicate.User(sql.FieldEQ(FieldPassword, v))
+}
+
+// PasswordNEQ applies the NEQ predicate on the "password" field.
+func PasswordNEQ(v string) predicate.User {
+ return predicate.User(sql.FieldNEQ(FieldPassword, v))
+}
+
+// PasswordIn applies the In predicate on the "password" field.
+func PasswordIn(vs ...string) predicate.User {
+ return predicate.User(sql.FieldIn(FieldPassword, vs...))
+}
+
+// PasswordNotIn applies the NotIn predicate on the "password" field.
+func PasswordNotIn(vs ...string) predicate.User {
+ return predicate.User(sql.FieldNotIn(FieldPassword, vs...))
+}
+
+// PasswordGT applies the GT predicate on the "password" field.
+func PasswordGT(v string) predicate.User {
+ return predicate.User(sql.FieldGT(FieldPassword, v))
+}
+
+// PasswordGTE applies the GTE predicate on the "password" field.
+func PasswordGTE(v string) predicate.User {
+ return predicate.User(sql.FieldGTE(FieldPassword, v))
+}
+
+// PasswordLT applies the LT predicate on the "password" field.
+func PasswordLT(v string) predicate.User {
+ return predicate.User(sql.FieldLT(FieldPassword, v))
+}
+
+// PasswordLTE applies the LTE predicate on the "password" field.
+func PasswordLTE(v string) predicate.User {
+ return predicate.User(sql.FieldLTE(FieldPassword, v))
+}
+
+// PasswordContains applies the Contains predicate on the "password" field.
+func PasswordContains(v string) predicate.User {
+ return predicate.User(sql.FieldContains(FieldPassword, v))
+}
+
+// PasswordHasPrefix applies the HasPrefix predicate on the "password" field.
+func PasswordHasPrefix(v string) predicate.User {
+ return predicate.User(sql.FieldHasPrefix(FieldPassword, v))
+}
+
+// PasswordHasSuffix applies the HasSuffix predicate on the "password" field.
+func PasswordHasSuffix(v string) predicate.User {
+ return predicate.User(sql.FieldHasSuffix(FieldPassword, v))
+}
+
+// PasswordEqualFold applies the EqualFold predicate on the "password" field.
+func PasswordEqualFold(v string) predicate.User {
+ return predicate.User(sql.FieldEqualFold(FieldPassword, v))
+}
+
+// PasswordContainsFold applies the ContainsFold predicate on the "password" field.
+func PasswordContainsFold(v string) predicate.User {
+ return predicate.User(sql.FieldContainsFold(FieldPassword, v))
+}
+
+// EmailEQ applies the EQ predicate on the "email" field.
+func EmailEQ(v string) predicate.User {
+ return predicate.User(sql.FieldEQ(FieldEmail, v))
+}
+
+// EmailNEQ applies the NEQ predicate on the "email" field.
+func EmailNEQ(v string) predicate.User {
+ return predicate.User(sql.FieldNEQ(FieldEmail, v))
+}
+
+// EmailIn applies the In predicate on the "email" field.
+func EmailIn(vs ...string) predicate.User {
+ return predicate.User(sql.FieldIn(FieldEmail, vs...))
+}
+
+// EmailNotIn applies the NotIn predicate on the "email" field.
+func EmailNotIn(vs ...string) predicate.User {
+ return predicate.User(sql.FieldNotIn(FieldEmail, vs...))
+}
+
+// EmailGT applies the GT predicate on the "email" field.
+func EmailGT(v string) predicate.User {
+ return predicate.User(sql.FieldGT(FieldEmail, v))
+}
+
+// EmailGTE applies the GTE predicate on the "email" field.
+func EmailGTE(v string) predicate.User {
+ return predicate.User(sql.FieldGTE(FieldEmail, v))
+}
+
+// EmailLT applies the LT predicate on the "email" field.
+func EmailLT(v string) predicate.User {
+ return predicate.User(sql.FieldLT(FieldEmail, v))
+}
+
+// EmailLTE applies the LTE predicate on the "email" field.
+func EmailLTE(v string) predicate.User {
+ return predicate.User(sql.FieldLTE(FieldEmail, v))
+}
+
+// EmailContains applies the Contains predicate on the "email" field.
+func EmailContains(v string) predicate.User {
+ return predicate.User(sql.FieldContains(FieldEmail, v))
+}
+
+// EmailHasPrefix applies the HasPrefix predicate on the "email" field.
+func EmailHasPrefix(v string) predicate.User {
+ return predicate.User(sql.FieldHasPrefix(FieldEmail, v))
+}
+
+// EmailHasSuffix applies the HasSuffix predicate on the "email" field.
+func EmailHasSuffix(v string) predicate.User {
+ return predicate.User(sql.FieldHasSuffix(FieldEmail, v))
+}
+
+// EmailEqualFold applies the EqualFold predicate on the "email" field.
+func EmailEqualFold(v string) predicate.User {
+ return predicate.User(sql.FieldEqualFold(FieldEmail, v))
+}
+
+// EmailContainsFold applies the ContainsFold predicate on the "email" field.
+func EmailContainsFold(v string) predicate.User {
+ return predicate.User(sql.FieldContainsFold(FieldEmail, v))
+}
+
+// StatusEQ applies the EQ predicate on the "status" field.
+func StatusEQ(v consts.UserStatus) predicate.User {
+ vc := string(v)
+ return predicate.User(sql.FieldEQ(FieldStatus, vc))
+}
+
+// StatusNEQ applies the NEQ predicate on the "status" field.
+func StatusNEQ(v consts.UserStatus) predicate.User {
+ vc := string(v)
+ return predicate.User(sql.FieldNEQ(FieldStatus, vc))
+}
+
+// StatusIn applies the In predicate on the "status" field.
+func StatusIn(vs ...consts.UserStatus) predicate.User {
+ v := make([]any, len(vs))
+ for i := range v {
+ v[i] = string(vs[i])
+ }
+ return predicate.User(sql.FieldIn(FieldStatus, v...))
+}
+
+// StatusNotIn applies the NotIn predicate on the "status" field.
+func StatusNotIn(vs ...consts.UserStatus) predicate.User {
+ v := make([]any, len(vs))
+ for i := range v {
+ v[i] = string(vs[i])
+ }
+ return predicate.User(sql.FieldNotIn(FieldStatus, v...))
+}
+
+// StatusGT applies the GT predicate on the "status" field.
+func StatusGT(v consts.UserStatus) predicate.User {
+ vc := string(v)
+ return predicate.User(sql.FieldGT(FieldStatus, vc))
+}
+
+// StatusGTE applies the GTE predicate on the "status" field.
+func StatusGTE(v consts.UserStatus) predicate.User {
+ vc := string(v)
+ return predicate.User(sql.FieldGTE(FieldStatus, vc))
+}
+
+// StatusLT applies the LT predicate on the "status" field.
+func StatusLT(v consts.UserStatus) predicate.User {
+ vc := string(v)
+ return predicate.User(sql.FieldLT(FieldStatus, vc))
+}
+
+// StatusLTE applies the LTE predicate on the "status" field.
+func StatusLTE(v consts.UserStatus) predicate.User {
+ vc := string(v)
+ return predicate.User(sql.FieldLTE(FieldStatus, vc))
+}
+
+// StatusContains applies the Contains predicate on the "status" field.
+func StatusContains(v consts.UserStatus) predicate.User {
+ vc := string(v)
+ return predicate.User(sql.FieldContains(FieldStatus, vc))
+}
+
+// StatusHasPrefix applies the HasPrefix predicate on the "status" field.
+func StatusHasPrefix(v consts.UserStatus) predicate.User {
+ vc := string(v)
+ return predicate.User(sql.FieldHasPrefix(FieldStatus, vc))
+}
+
+// StatusHasSuffix applies the HasSuffix predicate on the "status" field.
+func StatusHasSuffix(v consts.UserStatus) predicate.User {
+ vc := string(v)
+ return predicate.User(sql.FieldHasSuffix(FieldStatus, vc))
+}
+
+// StatusEqualFold applies the EqualFold predicate on the "status" field.
+func StatusEqualFold(v consts.UserStatus) predicate.User {
+ vc := string(v)
+ return predicate.User(sql.FieldEqualFold(FieldStatus, vc))
+}
+
+// StatusContainsFold applies the ContainsFold predicate on the "status" field.
+func StatusContainsFold(v consts.UserStatus) predicate.User {
+ vc := string(v)
+ return predicate.User(sql.FieldContainsFold(FieldStatus, vc))
+}
+
+// CreatedAtEQ applies the EQ predicate on the "created_at" field.
+func CreatedAtEQ(v time.Time) predicate.User {
+ return predicate.User(sql.FieldEQ(FieldCreatedAt, v))
+}
+
+// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
+func CreatedAtNEQ(v time.Time) predicate.User {
+ return predicate.User(sql.FieldNEQ(FieldCreatedAt, v))
+}
+
+// CreatedAtIn applies the In predicate on the "created_at" field.
+func CreatedAtIn(vs ...time.Time) predicate.User {
+ return predicate.User(sql.FieldIn(FieldCreatedAt, vs...))
+}
+
+// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
+func CreatedAtNotIn(vs ...time.Time) predicate.User {
+ return predicate.User(sql.FieldNotIn(FieldCreatedAt, vs...))
+}
+
+// CreatedAtGT applies the GT predicate on the "created_at" field.
+func CreatedAtGT(v time.Time) predicate.User {
+ return predicate.User(sql.FieldGT(FieldCreatedAt, v))
+}
+
+// CreatedAtGTE applies the GTE predicate on the "created_at" field.
+func CreatedAtGTE(v time.Time) predicate.User {
+ return predicate.User(sql.FieldGTE(FieldCreatedAt, v))
+}
+
+// CreatedAtLT applies the LT predicate on the "created_at" field.
+func CreatedAtLT(v time.Time) predicate.User {
+ return predicate.User(sql.FieldLT(FieldCreatedAt, v))
+}
+
+// CreatedAtLTE applies the LTE predicate on the "created_at" field.
+func CreatedAtLTE(v time.Time) predicate.User {
+ return predicate.User(sql.FieldLTE(FieldCreatedAt, v))
+}
+
+// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
+func UpdatedAtEQ(v time.Time) predicate.User {
+ return predicate.User(sql.FieldEQ(FieldUpdatedAt, v))
+}
+
+// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
+func UpdatedAtNEQ(v time.Time) predicate.User {
+ return predicate.User(sql.FieldNEQ(FieldUpdatedAt, v))
+}
+
+// UpdatedAtIn applies the In predicate on the "updated_at" field.
+func UpdatedAtIn(vs ...time.Time) predicate.User {
+ return predicate.User(sql.FieldIn(FieldUpdatedAt, vs...))
+}
+
+// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
+func UpdatedAtNotIn(vs ...time.Time) predicate.User {
+ return predicate.User(sql.FieldNotIn(FieldUpdatedAt, vs...))
+}
+
+// UpdatedAtGT applies the GT predicate on the "updated_at" field.
+func UpdatedAtGT(v time.Time) predicate.User {
+ return predicate.User(sql.FieldGT(FieldUpdatedAt, v))
+}
+
+// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
+func UpdatedAtGTE(v time.Time) predicate.User {
+ return predicate.User(sql.FieldGTE(FieldUpdatedAt, v))
+}
+
+// UpdatedAtLT applies the LT predicate on the "updated_at" field.
+func UpdatedAtLT(v time.Time) predicate.User {
+ return predicate.User(sql.FieldLT(FieldUpdatedAt, v))
+}
+
+// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
+func UpdatedAtLTE(v time.Time) predicate.User {
+ return predicate.User(sql.FieldLTE(FieldUpdatedAt, v))
+}
+
+// HasRecords applies the HasEdge predicate on the "records" edge.
+func HasRecords() predicate.User {
+ return predicate.User(func(s *sql.Selector) {
+ step := sqlgraph.NewStep(
+ sqlgraph.From(Table, FieldID),
+ sqlgraph.Edge(sqlgraph.O2M, false, RecordsTable, RecordsColumn),
+ )
+ sqlgraph.HasNeighbors(s, step)
+ })
+}
+
+// HasRecordsWith applies the HasEdge predicate on the "records" edge with a given conditions (other predicates).
+func HasRecordsWith(preds ...predicate.Record) predicate.User {
+ return predicate.User(func(s *sql.Selector) {
+ step := newRecordsStep()
+ sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
+ for _, p := range preds {
+ p(s)
+ }
+ })
+ })
+}
+
+// HasLoginHistories applies the HasEdge predicate on the "login_histories" edge.
+func HasLoginHistories() predicate.User {
+ return predicate.User(func(s *sql.Selector) {
+ step := sqlgraph.NewStep(
+ sqlgraph.From(Table, FieldID),
+ sqlgraph.Edge(sqlgraph.O2M, false, LoginHistoriesTable, LoginHistoriesColumn),
+ )
+ sqlgraph.HasNeighbors(s, step)
+ })
+}
+
+// HasLoginHistoriesWith applies the HasEdge predicate on the "login_histories" edge with a given conditions (other predicates).
+func HasLoginHistoriesWith(preds ...predicate.UserLoginHistory) predicate.User {
+ return predicate.User(func(s *sql.Selector) {
+ step := newLoginHistoriesStep()
+ sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
+ for _, p := range preds {
+ p(s)
+ }
+ })
+ })
+}
+
+// HasModels applies the HasEdge predicate on the "models" edge.
+func HasModels() predicate.User {
+ return predicate.User(func(s *sql.Selector) {
+ step := sqlgraph.NewStep(
+ sqlgraph.From(Table, FieldID),
+ sqlgraph.Edge(sqlgraph.O2M, false, ModelsTable, ModelsColumn),
+ )
+ sqlgraph.HasNeighbors(s, step)
+ })
+}
+
+// HasModelsWith applies the HasEdge predicate on the "models" edge with a given conditions (other predicates).
+func HasModelsWith(preds ...predicate.Model) predicate.User {
+ return predicate.User(func(s *sql.Selector) {
+ step := newModelsStep()
+ sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
+ for _, p := range preds {
+ p(s)
+ }
+ })
+ })
+}
+
+// And groups predicates with the AND operator between them.
+func And(predicates ...predicate.User) predicate.User {
+ return predicate.User(sql.AndPredicates(predicates...))
+}
+
+// Or groups predicates with the OR operator between them.
+func Or(predicates ...predicate.User) predicate.User {
+ return predicate.User(sql.OrPredicates(predicates...))
+}
+
+// Not applies the not operator on the given predicate.
+func Not(p predicate.User) predicate.User {
+ return predicate.User(sql.NotPredicates(p))
+}
diff --git a/backend/db/user_create.go b/backend/db/user_create.go
new file mode 100644
index 0000000..eeee021
--- /dev/null
+++ b/backend/db/user_create.go
@@ -0,0 +1,895 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "time"
+
+ "entgo.io/ent/dialect"
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/consts"
+ "github.com/chaitin/MonkeyCode/backend/db/model"
+ "github.com/chaitin/MonkeyCode/backend/db/record"
+ "github.com/chaitin/MonkeyCode/backend/db/user"
+ "github.com/chaitin/MonkeyCode/backend/db/userloginhistory"
+ "github.com/google/uuid"
+)
+
+// UserCreate is the builder for creating a User entity.
+type UserCreate struct {
+ config
+ mutation *UserMutation
+ hooks []Hook
+ conflict []sql.ConflictOption
+}
+
+// SetUsername sets the "username" field.
+func (uc *UserCreate) SetUsername(s string) *UserCreate {
+ uc.mutation.SetUsername(s)
+ return uc
+}
+
+// SetPassword sets the "password" field.
+func (uc *UserCreate) SetPassword(s string) *UserCreate {
+ uc.mutation.SetPassword(s)
+ return uc
+}
+
+// SetEmail sets the "email" field.
+func (uc *UserCreate) SetEmail(s string) *UserCreate {
+ uc.mutation.SetEmail(s)
+ return uc
+}
+
+// SetStatus sets the "status" field.
+func (uc *UserCreate) SetStatus(cs consts.UserStatus) *UserCreate {
+ uc.mutation.SetStatus(cs)
+ return uc
+}
+
+// SetNillableStatus sets the "status" field if the given value is not nil.
+func (uc *UserCreate) SetNillableStatus(cs *consts.UserStatus) *UserCreate {
+ if cs != nil {
+ uc.SetStatus(*cs)
+ }
+ return uc
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (uc *UserCreate) SetCreatedAt(t time.Time) *UserCreate {
+ uc.mutation.SetCreatedAt(t)
+ return uc
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (uc *UserCreate) SetNillableCreatedAt(t *time.Time) *UserCreate {
+ if t != nil {
+ uc.SetCreatedAt(*t)
+ }
+ return uc
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (uc *UserCreate) SetUpdatedAt(t time.Time) *UserCreate {
+ uc.mutation.SetUpdatedAt(t)
+ return uc
+}
+
+// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
+func (uc *UserCreate) SetNillableUpdatedAt(t *time.Time) *UserCreate {
+ if t != nil {
+ uc.SetUpdatedAt(*t)
+ }
+ return uc
+}
+
+// SetID sets the "id" field.
+func (uc *UserCreate) SetID(u uuid.UUID) *UserCreate {
+ uc.mutation.SetID(u)
+ return uc
+}
+
+// AddRecordIDs adds the "records" edge to the Record entity by IDs.
+func (uc *UserCreate) AddRecordIDs(ids ...uuid.UUID) *UserCreate {
+ uc.mutation.AddRecordIDs(ids...)
+ return uc
+}
+
+// AddRecords adds the "records" edges to the Record entity.
+func (uc *UserCreate) AddRecords(r ...*Record) *UserCreate {
+ ids := make([]uuid.UUID, len(r))
+ for i := range r {
+ ids[i] = r[i].ID
+ }
+ return uc.AddRecordIDs(ids...)
+}
+
+// AddLoginHistoryIDs adds the "login_histories" edge to the UserLoginHistory entity by IDs.
+func (uc *UserCreate) AddLoginHistoryIDs(ids ...uuid.UUID) *UserCreate {
+ uc.mutation.AddLoginHistoryIDs(ids...)
+ return uc
+}
+
+// AddLoginHistories adds the "login_histories" edges to the UserLoginHistory entity.
+func (uc *UserCreate) AddLoginHistories(u ...*UserLoginHistory) *UserCreate {
+ ids := make([]uuid.UUID, len(u))
+ for i := range u {
+ ids[i] = u[i].ID
+ }
+ return uc.AddLoginHistoryIDs(ids...)
+}
+
+// AddModelIDs adds the "models" edge to the Model entity by IDs.
+func (uc *UserCreate) AddModelIDs(ids ...uuid.UUID) *UserCreate {
+ uc.mutation.AddModelIDs(ids...)
+ return uc
+}
+
+// AddModels adds the "models" edges to the Model entity.
+func (uc *UserCreate) AddModels(m ...*Model) *UserCreate {
+ ids := make([]uuid.UUID, len(m))
+ for i := range m {
+ ids[i] = m[i].ID
+ }
+ return uc.AddModelIDs(ids...)
+}
+
+// Mutation returns the UserMutation object of the builder.
+func (uc *UserCreate) Mutation() *UserMutation {
+ return uc.mutation
+}
+
+// Save creates the User in the database.
+func (uc *UserCreate) Save(ctx context.Context) (*User, error) {
+ uc.defaults()
+ return withHooks(ctx, uc.sqlSave, uc.mutation, uc.hooks)
+}
+
+// SaveX calls Save and panics if Save returns an error.
+func (uc *UserCreate) SaveX(ctx context.Context) *User {
+ v, err := uc.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return v
+}
+
+// Exec executes the query.
+func (uc *UserCreate) Exec(ctx context.Context) error {
+ _, err := uc.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (uc *UserCreate) ExecX(ctx context.Context) {
+ if err := uc.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// defaults sets the default values of the builder before save.
+func (uc *UserCreate) defaults() {
+ if _, ok := uc.mutation.Status(); !ok {
+ v := user.DefaultStatus
+ uc.mutation.SetStatus(v)
+ }
+ if _, ok := uc.mutation.CreatedAt(); !ok {
+ v := user.DefaultCreatedAt()
+ uc.mutation.SetCreatedAt(v)
+ }
+ if _, ok := uc.mutation.UpdatedAt(); !ok {
+ v := user.DefaultUpdatedAt()
+ uc.mutation.SetUpdatedAt(v)
+ }
+}
+
+// check runs all checks and user-defined validators on the builder.
+func (uc *UserCreate) check() error {
+ if _, ok := uc.mutation.Username(); !ok {
+ return &ValidationError{Name: "username", err: errors.New(`db: missing required field "User.username"`)}
+ }
+ if _, ok := uc.mutation.Password(); !ok {
+ return &ValidationError{Name: "password", err: errors.New(`db: missing required field "User.password"`)}
+ }
+ if _, ok := uc.mutation.Email(); !ok {
+ return &ValidationError{Name: "email", err: errors.New(`db: missing required field "User.email"`)}
+ }
+ if _, ok := uc.mutation.Status(); !ok {
+ return &ValidationError{Name: "status", err: errors.New(`db: missing required field "User.status"`)}
+ }
+ if _, ok := uc.mutation.CreatedAt(); !ok {
+ return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "User.created_at"`)}
+ }
+ if _, ok := uc.mutation.UpdatedAt(); !ok {
+ return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "User.updated_at"`)}
+ }
+ return nil
+}
+
+func (uc *UserCreate) sqlSave(ctx context.Context) (*User, error) {
+ if err := uc.check(); err != nil {
+ return nil, err
+ }
+ _node, _spec := uc.createSpec()
+ if err := sqlgraph.CreateNode(ctx, uc.driver, _spec); err != nil {
+ if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return nil, err
+ }
+ if _spec.ID.Value != nil {
+ if id, ok := _spec.ID.Value.(*uuid.UUID); ok {
+ _node.ID = *id
+ } else if err := _node.ID.Scan(_spec.ID.Value); err != nil {
+ return nil, err
+ }
+ }
+ uc.mutation.id = &_node.ID
+ uc.mutation.done = true
+ return _node, nil
+}
+
+func (uc *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) {
+ var (
+ _node = &User{config: uc.config}
+ _spec = sqlgraph.NewCreateSpec(user.Table, sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID))
+ )
+ _spec.OnConflict = uc.conflict
+ if id, ok := uc.mutation.ID(); ok {
+ _node.ID = id
+ _spec.ID.Value = &id
+ }
+ if value, ok := uc.mutation.Username(); ok {
+ _spec.SetField(user.FieldUsername, field.TypeString, value)
+ _node.Username = value
+ }
+ if value, ok := uc.mutation.Password(); ok {
+ _spec.SetField(user.FieldPassword, field.TypeString, value)
+ _node.Password = value
+ }
+ if value, ok := uc.mutation.Email(); ok {
+ _spec.SetField(user.FieldEmail, field.TypeString, value)
+ _node.Email = value
+ }
+ if value, ok := uc.mutation.Status(); ok {
+ _spec.SetField(user.FieldStatus, field.TypeString, value)
+ _node.Status = value
+ }
+ if value, ok := uc.mutation.CreatedAt(); ok {
+ _spec.SetField(user.FieldCreatedAt, field.TypeTime, value)
+ _node.CreatedAt = value
+ }
+ if value, ok := uc.mutation.UpdatedAt(); ok {
+ _spec.SetField(user.FieldUpdatedAt, field.TypeTime, value)
+ _node.UpdatedAt = value
+ }
+ if nodes := uc.mutation.RecordsIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: user.RecordsTable,
+ Columns: []string{user.RecordsColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(record.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges = append(_spec.Edges, edge)
+ }
+ if nodes := uc.mutation.LoginHistoriesIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: user.LoginHistoriesTable,
+ Columns: []string{user.LoginHistoriesColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(userloginhistory.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges = append(_spec.Edges, edge)
+ }
+ if nodes := uc.mutation.ModelsIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: user.ModelsTable,
+ Columns: []string{user.ModelsColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(model.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges = append(_spec.Edges, edge)
+ }
+ return _node, _spec
+}
+
+// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
+// of the `INSERT` statement. For example:
+//
+// client.User.Create().
+// SetUsername(v).
+// OnConflict(
+// // Update the row with the new values
+// // the was proposed for insertion.
+// sql.ResolveWithNewValues(),
+// ).
+// // Override some of the fields with custom
+// // update values.
+// Update(func(u *ent.UserUpsert) {
+// SetUsername(v+v).
+// }).
+// Exec(ctx)
+func (uc *UserCreate) OnConflict(opts ...sql.ConflictOption) *UserUpsertOne {
+ uc.conflict = opts
+ return &UserUpsertOne{
+ create: uc,
+ }
+}
+
+// OnConflictColumns calls `OnConflict` and configures the columns
+// as conflict target. Using this option is equivalent to using:
+//
+// client.User.Create().
+// OnConflict(sql.ConflictColumns(columns...)).
+// Exec(ctx)
+func (uc *UserCreate) OnConflictColumns(columns ...string) *UserUpsertOne {
+ uc.conflict = append(uc.conflict, sql.ConflictColumns(columns...))
+ return &UserUpsertOne{
+ create: uc,
+ }
+}
+
+type (
+ // UserUpsertOne is the builder for "upsert"-ing
+ // one User node.
+ UserUpsertOne struct {
+ create *UserCreate
+ }
+
+ // UserUpsert is the "OnConflict" setter.
+ UserUpsert struct {
+ *sql.UpdateSet
+ }
+)
+
+// SetUsername sets the "username" field.
+func (u *UserUpsert) SetUsername(v string) *UserUpsert {
+ u.Set(user.FieldUsername, v)
+ return u
+}
+
+// UpdateUsername sets the "username" field to the value that was provided on create.
+func (u *UserUpsert) UpdateUsername() *UserUpsert {
+ u.SetExcluded(user.FieldUsername)
+ return u
+}
+
+// SetPassword sets the "password" field.
+func (u *UserUpsert) SetPassword(v string) *UserUpsert {
+ u.Set(user.FieldPassword, v)
+ return u
+}
+
+// UpdatePassword sets the "password" field to the value that was provided on create.
+func (u *UserUpsert) UpdatePassword() *UserUpsert {
+ u.SetExcluded(user.FieldPassword)
+ return u
+}
+
+// SetEmail sets the "email" field.
+func (u *UserUpsert) SetEmail(v string) *UserUpsert {
+ u.Set(user.FieldEmail, v)
+ return u
+}
+
+// UpdateEmail sets the "email" field to the value that was provided on create.
+func (u *UserUpsert) UpdateEmail() *UserUpsert {
+ u.SetExcluded(user.FieldEmail)
+ return u
+}
+
+// SetStatus sets the "status" field.
+func (u *UserUpsert) SetStatus(v consts.UserStatus) *UserUpsert {
+ u.Set(user.FieldStatus, v)
+ return u
+}
+
+// UpdateStatus sets the "status" field to the value that was provided on create.
+func (u *UserUpsert) UpdateStatus() *UserUpsert {
+ u.SetExcluded(user.FieldStatus)
+ return u
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (u *UserUpsert) SetCreatedAt(v time.Time) *UserUpsert {
+ u.Set(user.FieldCreatedAt, v)
+ return u
+}
+
+// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
+func (u *UserUpsert) UpdateCreatedAt() *UserUpsert {
+ u.SetExcluded(user.FieldCreatedAt)
+ return u
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (u *UserUpsert) SetUpdatedAt(v time.Time) *UserUpsert {
+ u.Set(user.FieldUpdatedAt, v)
+ return u
+}
+
+// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
+func (u *UserUpsert) UpdateUpdatedAt() *UserUpsert {
+ u.SetExcluded(user.FieldUpdatedAt)
+ return u
+}
+
+// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field.
+// Using this option is equivalent to using:
+//
+// client.User.Create().
+// OnConflict(
+// sql.ResolveWithNewValues(),
+// sql.ResolveWith(func(u *sql.UpdateSet) {
+// u.SetIgnore(user.FieldID)
+// }),
+// ).
+// Exec(ctx)
+func (u *UserUpsertOne) UpdateNewValues() *UserUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
+ if _, exists := u.create.mutation.ID(); exists {
+ s.SetIgnore(user.FieldID)
+ }
+ }))
+ return u
+}
+
+// Ignore sets each column to itself in case of conflict.
+// Using this option is equivalent to using:
+//
+// client.User.Create().
+// OnConflict(sql.ResolveWithIgnore()).
+// Exec(ctx)
+func (u *UserUpsertOne) Ignore() *UserUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
+ return u
+}
+
+// DoNothing configures the conflict_action to `DO NOTHING`.
+// Supported only by SQLite and PostgreSQL.
+func (u *UserUpsertOne) DoNothing() *UserUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.DoNothing())
+ return u
+}
+
+// Update allows overriding fields `UPDATE` values. See the UserCreate.OnConflict
+// documentation for more info.
+func (u *UserUpsertOne) Update(set func(*UserUpsert)) *UserUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
+ set(&UserUpsert{UpdateSet: update})
+ }))
+ return u
+}
+
+// SetUsername sets the "username" field.
+func (u *UserUpsertOne) SetUsername(v string) *UserUpsertOne {
+ return u.Update(func(s *UserUpsert) {
+ s.SetUsername(v)
+ })
+}
+
+// UpdateUsername sets the "username" field to the value that was provided on create.
+func (u *UserUpsertOne) UpdateUsername() *UserUpsertOne {
+ return u.Update(func(s *UserUpsert) {
+ s.UpdateUsername()
+ })
+}
+
+// SetPassword sets the "password" field.
+func (u *UserUpsertOne) SetPassword(v string) *UserUpsertOne {
+ return u.Update(func(s *UserUpsert) {
+ s.SetPassword(v)
+ })
+}
+
+// UpdatePassword sets the "password" field to the value that was provided on create.
+func (u *UserUpsertOne) UpdatePassword() *UserUpsertOne {
+ return u.Update(func(s *UserUpsert) {
+ s.UpdatePassword()
+ })
+}
+
+// SetEmail sets the "email" field.
+func (u *UserUpsertOne) SetEmail(v string) *UserUpsertOne {
+ return u.Update(func(s *UserUpsert) {
+ s.SetEmail(v)
+ })
+}
+
+// UpdateEmail sets the "email" field to the value that was provided on create.
+func (u *UserUpsertOne) UpdateEmail() *UserUpsertOne {
+ return u.Update(func(s *UserUpsert) {
+ s.UpdateEmail()
+ })
+}
+
+// SetStatus sets the "status" field.
+func (u *UserUpsertOne) SetStatus(v consts.UserStatus) *UserUpsertOne {
+ return u.Update(func(s *UserUpsert) {
+ s.SetStatus(v)
+ })
+}
+
+// UpdateStatus sets the "status" field to the value that was provided on create.
+func (u *UserUpsertOne) UpdateStatus() *UserUpsertOne {
+ return u.Update(func(s *UserUpsert) {
+ s.UpdateStatus()
+ })
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (u *UserUpsertOne) SetCreatedAt(v time.Time) *UserUpsertOne {
+ return u.Update(func(s *UserUpsert) {
+ s.SetCreatedAt(v)
+ })
+}
+
+// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
+func (u *UserUpsertOne) UpdateCreatedAt() *UserUpsertOne {
+ return u.Update(func(s *UserUpsert) {
+ s.UpdateCreatedAt()
+ })
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (u *UserUpsertOne) SetUpdatedAt(v time.Time) *UserUpsertOne {
+ return u.Update(func(s *UserUpsert) {
+ s.SetUpdatedAt(v)
+ })
+}
+
+// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
+func (u *UserUpsertOne) UpdateUpdatedAt() *UserUpsertOne {
+ return u.Update(func(s *UserUpsert) {
+ s.UpdateUpdatedAt()
+ })
+}
+
+// Exec executes the query.
+func (u *UserUpsertOne) Exec(ctx context.Context) error {
+ if len(u.create.conflict) == 0 {
+ return errors.New("db: missing options for UserCreate.OnConflict")
+ }
+ return u.create.Exec(ctx)
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (u *UserUpsertOne) ExecX(ctx context.Context) {
+ if err := u.create.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// Exec executes the UPSERT query and returns the inserted/updated ID.
+func (u *UserUpsertOne) ID(ctx context.Context) (id uuid.UUID, err error) {
+ if u.create.driver.Dialect() == dialect.MySQL {
+ // In case of "ON CONFLICT", there is no way to get back non-numeric ID
+ // fields from the database since MySQL does not support the RETURNING clause.
+ return id, errors.New("db: UserUpsertOne.ID is not supported by MySQL driver. Use UserUpsertOne.Exec instead")
+ }
+ node, err := u.create.Save(ctx)
+ if err != nil {
+ return id, err
+ }
+ return node.ID, nil
+}
+
+// IDX is like ID, but panics if an error occurs.
+func (u *UserUpsertOne) IDX(ctx context.Context) uuid.UUID {
+ id, err := u.ID(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return id
+}
+
+// UserCreateBulk is the builder for creating many User entities in bulk.
+type UserCreateBulk struct {
+ config
+ err error
+ builders []*UserCreate
+ conflict []sql.ConflictOption
+}
+
+// Save creates the User entities in the database.
+func (ucb *UserCreateBulk) Save(ctx context.Context) ([]*User, error) {
+ if ucb.err != nil {
+ return nil, ucb.err
+ }
+ specs := make([]*sqlgraph.CreateSpec, len(ucb.builders))
+ nodes := make([]*User, len(ucb.builders))
+ mutators := make([]Mutator, len(ucb.builders))
+ for i := range ucb.builders {
+ func(i int, root context.Context) {
+ builder := ucb.builders[i]
+ builder.defaults()
+ var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
+ mutation, ok := m.(*UserMutation)
+ if !ok {
+ return nil, fmt.Errorf("unexpected mutation type %T", m)
+ }
+ if err := builder.check(); err != nil {
+ return nil, err
+ }
+ builder.mutation = mutation
+ var err error
+ nodes[i], specs[i] = builder.createSpec()
+ if i < len(mutators)-1 {
+ _, err = mutators[i+1].Mutate(root, ucb.builders[i+1].mutation)
+ } else {
+ spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
+ spec.OnConflict = ucb.conflict
+ // Invoke the actual operation on the latest mutation in the chain.
+ if err = sqlgraph.BatchCreate(ctx, ucb.driver, spec); err != nil {
+ if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ }
+ }
+ if err != nil {
+ return nil, err
+ }
+ mutation.id = &nodes[i].ID
+ mutation.done = true
+ return nodes[i], nil
+ })
+ for i := len(builder.hooks) - 1; i >= 0; i-- {
+ mut = builder.hooks[i](mut)
+ }
+ mutators[i] = mut
+ }(i, ctx)
+ }
+ if len(mutators) > 0 {
+ if _, err := mutators[0].Mutate(ctx, ucb.builders[0].mutation); err != nil {
+ return nil, err
+ }
+ }
+ return nodes, nil
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (ucb *UserCreateBulk) SaveX(ctx context.Context) []*User {
+ v, err := ucb.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return v
+}
+
+// Exec executes the query.
+func (ucb *UserCreateBulk) Exec(ctx context.Context) error {
+ _, err := ucb.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (ucb *UserCreateBulk) ExecX(ctx context.Context) {
+ if err := ucb.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
+// of the `INSERT` statement. For example:
+//
+// client.User.CreateBulk(builders...).
+// OnConflict(
+// // Update the row with the new values
+// // the was proposed for insertion.
+// sql.ResolveWithNewValues(),
+// ).
+// // Override some of the fields with custom
+// // update values.
+// Update(func(u *ent.UserUpsert) {
+// SetUsername(v+v).
+// }).
+// Exec(ctx)
+func (ucb *UserCreateBulk) OnConflict(opts ...sql.ConflictOption) *UserUpsertBulk {
+ ucb.conflict = opts
+ return &UserUpsertBulk{
+ create: ucb,
+ }
+}
+
+// OnConflictColumns calls `OnConflict` and configures the columns
+// as conflict target. Using this option is equivalent to using:
+//
+// client.User.Create().
+// OnConflict(sql.ConflictColumns(columns...)).
+// Exec(ctx)
+func (ucb *UserCreateBulk) OnConflictColumns(columns ...string) *UserUpsertBulk {
+ ucb.conflict = append(ucb.conflict, sql.ConflictColumns(columns...))
+ return &UserUpsertBulk{
+ create: ucb,
+ }
+}
+
+// UserUpsertBulk is the builder for "upsert"-ing
+// a bulk of User nodes.
+type UserUpsertBulk struct {
+ create *UserCreateBulk
+}
+
+// UpdateNewValues updates the mutable fields using the new values that
+// were set on create. Using this option is equivalent to using:
+//
+// client.User.Create().
+// OnConflict(
+// sql.ResolveWithNewValues(),
+// sql.ResolveWith(func(u *sql.UpdateSet) {
+// u.SetIgnore(user.FieldID)
+// }),
+// ).
+// Exec(ctx)
+func (u *UserUpsertBulk) UpdateNewValues() *UserUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
+ for _, b := range u.create.builders {
+ if _, exists := b.mutation.ID(); exists {
+ s.SetIgnore(user.FieldID)
+ }
+ }
+ }))
+ return u
+}
+
+// Ignore sets each column to itself in case of conflict.
+// Using this option is equivalent to using:
+//
+// client.User.Create().
+// OnConflict(sql.ResolveWithIgnore()).
+// Exec(ctx)
+func (u *UserUpsertBulk) Ignore() *UserUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
+ return u
+}
+
+// DoNothing configures the conflict_action to `DO NOTHING`.
+// Supported only by SQLite and PostgreSQL.
+func (u *UserUpsertBulk) DoNothing() *UserUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.DoNothing())
+ return u
+}
+
+// Update allows overriding fields `UPDATE` values. See the UserCreateBulk.OnConflict
+// documentation for more info.
+func (u *UserUpsertBulk) Update(set func(*UserUpsert)) *UserUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
+ set(&UserUpsert{UpdateSet: update})
+ }))
+ return u
+}
+
+// SetUsername sets the "username" field.
+func (u *UserUpsertBulk) SetUsername(v string) *UserUpsertBulk {
+ return u.Update(func(s *UserUpsert) {
+ s.SetUsername(v)
+ })
+}
+
+// UpdateUsername sets the "username" field to the value that was provided on create.
+func (u *UserUpsertBulk) UpdateUsername() *UserUpsertBulk {
+ return u.Update(func(s *UserUpsert) {
+ s.UpdateUsername()
+ })
+}
+
+// SetPassword sets the "password" field.
+func (u *UserUpsertBulk) SetPassword(v string) *UserUpsertBulk {
+ return u.Update(func(s *UserUpsert) {
+ s.SetPassword(v)
+ })
+}
+
+// UpdatePassword sets the "password" field to the value that was provided on create.
+func (u *UserUpsertBulk) UpdatePassword() *UserUpsertBulk {
+ return u.Update(func(s *UserUpsert) {
+ s.UpdatePassword()
+ })
+}
+
+// SetEmail sets the "email" field.
+func (u *UserUpsertBulk) SetEmail(v string) *UserUpsertBulk {
+ return u.Update(func(s *UserUpsert) {
+ s.SetEmail(v)
+ })
+}
+
+// UpdateEmail sets the "email" field to the value that was provided on create.
+func (u *UserUpsertBulk) UpdateEmail() *UserUpsertBulk {
+ return u.Update(func(s *UserUpsert) {
+ s.UpdateEmail()
+ })
+}
+
+// SetStatus sets the "status" field.
+func (u *UserUpsertBulk) SetStatus(v consts.UserStatus) *UserUpsertBulk {
+ return u.Update(func(s *UserUpsert) {
+ s.SetStatus(v)
+ })
+}
+
+// UpdateStatus sets the "status" field to the value that was provided on create.
+func (u *UserUpsertBulk) UpdateStatus() *UserUpsertBulk {
+ return u.Update(func(s *UserUpsert) {
+ s.UpdateStatus()
+ })
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (u *UserUpsertBulk) SetCreatedAt(v time.Time) *UserUpsertBulk {
+ return u.Update(func(s *UserUpsert) {
+ s.SetCreatedAt(v)
+ })
+}
+
+// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
+func (u *UserUpsertBulk) UpdateCreatedAt() *UserUpsertBulk {
+ return u.Update(func(s *UserUpsert) {
+ s.UpdateCreatedAt()
+ })
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (u *UserUpsertBulk) SetUpdatedAt(v time.Time) *UserUpsertBulk {
+ return u.Update(func(s *UserUpsert) {
+ s.SetUpdatedAt(v)
+ })
+}
+
+// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
+func (u *UserUpsertBulk) UpdateUpdatedAt() *UserUpsertBulk {
+ return u.Update(func(s *UserUpsert) {
+ s.UpdateUpdatedAt()
+ })
+}
+
+// Exec executes the query.
+func (u *UserUpsertBulk) Exec(ctx context.Context) error {
+ if u.create.err != nil {
+ return u.create.err
+ }
+ for i, b := range u.create.builders {
+ if len(b.conflict) != 0 {
+ return fmt.Errorf("db: OnConflict was set for builder %d. Set it on the UserCreateBulk instead", i)
+ }
+ }
+ if len(u.create.conflict) == 0 {
+ return errors.New("db: missing options for UserCreateBulk.OnConflict")
+ }
+ return u.create.Exec(ctx)
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (u *UserUpsertBulk) ExecX(ctx context.Context) {
+ if err := u.create.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
diff --git a/backend/db/user_delete.go b/backend/db/user_delete.go
new file mode 100644
index 0000000..eef7703
--- /dev/null
+++ b/backend/db/user_delete.go
@@ -0,0 +1,88 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+ "github.com/chaitin/MonkeyCode/backend/db/user"
+)
+
+// UserDelete is the builder for deleting a User entity.
+type UserDelete struct {
+ config
+ hooks []Hook
+ mutation *UserMutation
+}
+
+// Where appends a list predicates to the UserDelete builder.
+func (ud *UserDelete) Where(ps ...predicate.User) *UserDelete {
+ ud.mutation.Where(ps...)
+ return ud
+}
+
+// Exec executes the deletion query and returns how many vertices were deleted.
+func (ud *UserDelete) Exec(ctx context.Context) (int, error) {
+ return withHooks(ctx, ud.sqlExec, ud.mutation, ud.hooks)
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (ud *UserDelete) ExecX(ctx context.Context) int {
+ n, err := ud.Exec(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return n
+}
+
+func (ud *UserDelete) sqlExec(ctx context.Context) (int, error) {
+ _spec := sqlgraph.NewDeleteSpec(user.Table, sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID))
+ if ps := ud.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ affected, err := sqlgraph.DeleteNodes(ctx, ud.driver, _spec)
+ if err != nil && sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ ud.mutation.done = true
+ return affected, err
+}
+
+// UserDeleteOne is the builder for deleting a single User entity.
+type UserDeleteOne struct {
+ ud *UserDelete
+}
+
+// Where appends a list predicates to the UserDelete builder.
+func (udo *UserDeleteOne) Where(ps ...predicate.User) *UserDeleteOne {
+ udo.ud.mutation.Where(ps...)
+ return udo
+}
+
+// Exec executes the deletion query.
+func (udo *UserDeleteOne) Exec(ctx context.Context) error {
+ n, err := udo.ud.Exec(ctx)
+ switch {
+ case err != nil:
+ return err
+ case n == 0:
+ return &NotFoundError{user.Label}
+ default:
+ return nil
+ }
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (udo *UserDeleteOne) ExecX(ctx context.Context) {
+ if err := udo.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
diff --git a/backend/db/user_query.go b/backend/db/user_query.go
new file mode 100644
index 0000000..170b753
--- /dev/null
+++ b/backend/db/user_query.go
@@ -0,0 +1,806 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "database/sql/driver"
+ "fmt"
+ "math"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect"
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/model"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+ "github.com/chaitin/MonkeyCode/backend/db/record"
+ "github.com/chaitin/MonkeyCode/backend/db/user"
+ "github.com/chaitin/MonkeyCode/backend/db/userloginhistory"
+ "github.com/google/uuid"
+)
+
+// UserQuery is the builder for querying User entities.
+type UserQuery struct {
+ config
+ ctx *QueryContext
+ order []user.OrderOption
+ inters []Interceptor
+ predicates []predicate.User
+ withRecords *RecordQuery
+ withLoginHistories *UserLoginHistoryQuery
+ withModels *ModelQuery
+ modifiers []func(*sql.Selector)
+ // intermediate query (i.e. traversal path).
+ sql *sql.Selector
+ path func(context.Context) (*sql.Selector, error)
+}
+
+// Where adds a new predicate for the UserQuery builder.
+func (uq *UserQuery) Where(ps ...predicate.User) *UserQuery {
+ uq.predicates = append(uq.predicates, ps...)
+ return uq
+}
+
+// Limit the number of records to be returned by this query.
+func (uq *UserQuery) Limit(limit int) *UserQuery {
+ uq.ctx.Limit = &limit
+ return uq
+}
+
+// Offset to start from.
+func (uq *UserQuery) Offset(offset int) *UserQuery {
+ uq.ctx.Offset = &offset
+ return uq
+}
+
+// Unique configures the query builder to filter duplicate records on query.
+// By default, unique is set to true, and can be disabled using this method.
+func (uq *UserQuery) Unique(unique bool) *UserQuery {
+ uq.ctx.Unique = &unique
+ return uq
+}
+
+// Order specifies how the records should be ordered.
+func (uq *UserQuery) Order(o ...user.OrderOption) *UserQuery {
+ uq.order = append(uq.order, o...)
+ return uq
+}
+
+// QueryRecords chains the current query on the "records" edge.
+func (uq *UserQuery) QueryRecords() *RecordQuery {
+ query := (&RecordClient{config: uq.config}).Query()
+ query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
+ if err := uq.prepareQuery(ctx); err != nil {
+ return nil, err
+ }
+ selector := uq.sqlQuery(ctx)
+ if err := selector.Err(); err != nil {
+ return nil, err
+ }
+ step := sqlgraph.NewStep(
+ sqlgraph.From(user.Table, user.FieldID, selector),
+ sqlgraph.To(record.Table, record.FieldID),
+ sqlgraph.Edge(sqlgraph.O2M, false, user.RecordsTable, user.RecordsColumn),
+ )
+ fromU = sqlgraph.SetNeighbors(uq.driver.Dialect(), step)
+ return fromU, nil
+ }
+ return query
+}
+
+// QueryLoginHistories chains the current query on the "login_histories" edge.
+func (uq *UserQuery) QueryLoginHistories() *UserLoginHistoryQuery {
+ query := (&UserLoginHistoryClient{config: uq.config}).Query()
+ query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
+ if err := uq.prepareQuery(ctx); err != nil {
+ return nil, err
+ }
+ selector := uq.sqlQuery(ctx)
+ if err := selector.Err(); err != nil {
+ return nil, err
+ }
+ step := sqlgraph.NewStep(
+ sqlgraph.From(user.Table, user.FieldID, selector),
+ sqlgraph.To(userloginhistory.Table, userloginhistory.FieldID),
+ sqlgraph.Edge(sqlgraph.O2M, false, user.LoginHistoriesTable, user.LoginHistoriesColumn),
+ )
+ fromU = sqlgraph.SetNeighbors(uq.driver.Dialect(), step)
+ return fromU, nil
+ }
+ return query
+}
+
+// QueryModels chains the current query on the "models" edge.
+func (uq *UserQuery) QueryModels() *ModelQuery {
+ query := (&ModelClient{config: uq.config}).Query()
+ query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
+ if err := uq.prepareQuery(ctx); err != nil {
+ return nil, err
+ }
+ selector := uq.sqlQuery(ctx)
+ if err := selector.Err(); err != nil {
+ return nil, err
+ }
+ step := sqlgraph.NewStep(
+ sqlgraph.From(user.Table, user.FieldID, selector),
+ sqlgraph.To(model.Table, model.FieldID),
+ sqlgraph.Edge(sqlgraph.O2M, false, user.ModelsTable, user.ModelsColumn),
+ )
+ fromU = sqlgraph.SetNeighbors(uq.driver.Dialect(), step)
+ return fromU, nil
+ }
+ return query
+}
+
+// First returns the first User entity from the query.
+// Returns a *NotFoundError when no User was found.
+func (uq *UserQuery) First(ctx context.Context) (*User, error) {
+ nodes, err := uq.Limit(1).All(setContextOp(ctx, uq.ctx, ent.OpQueryFirst))
+ if err != nil {
+ return nil, err
+ }
+ if len(nodes) == 0 {
+ return nil, &NotFoundError{user.Label}
+ }
+ return nodes[0], nil
+}
+
+// FirstX is like First, but panics if an error occurs.
+func (uq *UserQuery) FirstX(ctx context.Context) *User {
+ node, err := uq.First(ctx)
+ if err != nil && !IsNotFound(err) {
+ panic(err)
+ }
+ return node
+}
+
+// FirstID returns the first User ID from the query.
+// Returns a *NotFoundError when no User ID was found.
+func (uq *UserQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
+ var ids []uuid.UUID
+ if ids, err = uq.Limit(1).IDs(setContextOp(ctx, uq.ctx, ent.OpQueryFirstID)); err != nil {
+ return
+ }
+ if len(ids) == 0 {
+ err = &NotFoundError{user.Label}
+ return
+ }
+ return ids[0], nil
+}
+
+// FirstIDX is like FirstID, but panics if an error occurs.
+func (uq *UserQuery) FirstIDX(ctx context.Context) uuid.UUID {
+ id, err := uq.FirstID(ctx)
+ if err != nil && !IsNotFound(err) {
+ panic(err)
+ }
+ return id
+}
+
+// Only returns a single User entity found by the query, ensuring it only returns one.
+// Returns a *NotSingularError when more than one User entity is found.
+// Returns a *NotFoundError when no User entities are found.
+func (uq *UserQuery) Only(ctx context.Context) (*User, error) {
+ nodes, err := uq.Limit(2).All(setContextOp(ctx, uq.ctx, ent.OpQueryOnly))
+ if err != nil {
+ return nil, err
+ }
+ switch len(nodes) {
+ case 1:
+ return nodes[0], nil
+ case 0:
+ return nil, &NotFoundError{user.Label}
+ default:
+ return nil, &NotSingularError{user.Label}
+ }
+}
+
+// OnlyX is like Only, but panics if an error occurs.
+func (uq *UserQuery) OnlyX(ctx context.Context) *User {
+ node, err := uq.Only(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return node
+}
+
+// OnlyID is like Only, but returns the only User ID in the query.
+// Returns a *NotSingularError when more than one User ID is found.
+// Returns a *NotFoundError when no entities are found.
+func (uq *UserQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
+ var ids []uuid.UUID
+ if ids, err = uq.Limit(2).IDs(setContextOp(ctx, uq.ctx, ent.OpQueryOnlyID)); err != nil {
+ return
+ }
+ switch len(ids) {
+ case 1:
+ id = ids[0]
+ case 0:
+ err = &NotFoundError{user.Label}
+ default:
+ err = &NotSingularError{user.Label}
+ }
+ return
+}
+
+// OnlyIDX is like OnlyID, but panics if an error occurs.
+func (uq *UserQuery) OnlyIDX(ctx context.Context) uuid.UUID {
+ id, err := uq.OnlyID(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return id
+}
+
+// All executes the query and returns a list of Users.
+func (uq *UserQuery) All(ctx context.Context) ([]*User, error) {
+ ctx = setContextOp(ctx, uq.ctx, ent.OpQueryAll)
+ if err := uq.prepareQuery(ctx); err != nil {
+ return nil, err
+ }
+ qr := querierAll[[]*User, *UserQuery]()
+ return withInterceptors[[]*User](ctx, uq, qr, uq.inters)
+}
+
+// AllX is like All, but panics if an error occurs.
+func (uq *UserQuery) AllX(ctx context.Context) []*User {
+ nodes, err := uq.All(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return nodes
+}
+
+// IDs executes the query and returns a list of User IDs.
+func (uq *UserQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) {
+ if uq.ctx.Unique == nil && uq.path != nil {
+ uq.Unique(true)
+ }
+ ctx = setContextOp(ctx, uq.ctx, ent.OpQueryIDs)
+ if err = uq.Select(user.FieldID).Scan(ctx, &ids); err != nil {
+ return nil, err
+ }
+ return ids, nil
+}
+
+// IDsX is like IDs, but panics if an error occurs.
+func (uq *UserQuery) IDsX(ctx context.Context) []uuid.UUID {
+ ids, err := uq.IDs(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return ids
+}
+
+// Count returns the count of the given query.
+func (uq *UserQuery) Count(ctx context.Context) (int, error) {
+ ctx = setContextOp(ctx, uq.ctx, ent.OpQueryCount)
+ if err := uq.prepareQuery(ctx); err != nil {
+ return 0, err
+ }
+ return withInterceptors[int](ctx, uq, querierCount[*UserQuery](), uq.inters)
+}
+
+// CountX is like Count, but panics if an error occurs.
+func (uq *UserQuery) CountX(ctx context.Context) int {
+ count, err := uq.Count(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return count
+}
+
+// Exist returns true if the query has elements in the graph.
+func (uq *UserQuery) Exist(ctx context.Context) (bool, error) {
+ ctx = setContextOp(ctx, uq.ctx, ent.OpQueryExist)
+ switch _, err := uq.FirstID(ctx); {
+ case IsNotFound(err):
+ return false, nil
+ case err != nil:
+ return false, fmt.Errorf("db: check existence: %w", err)
+ default:
+ return true, nil
+ }
+}
+
+// ExistX is like Exist, but panics if an error occurs.
+func (uq *UserQuery) ExistX(ctx context.Context) bool {
+ exist, err := uq.Exist(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return exist
+}
+
+// Clone returns a duplicate of the UserQuery builder, including all associated steps. It can be
+// used to prepare common query builders and use them differently after the clone is made.
+func (uq *UserQuery) Clone() *UserQuery {
+ if uq == nil {
+ return nil
+ }
+ return &UserQuery{
+ config: uq.config,
+ ctx: uq.ctx.Clone(),
+ order: append([]user.OrderOption{}, uq.order...),
+ inters: append([]Interceptor{}, uq.inters...),
+ predicates: append([]predicate.User{}, uq.predicates...),
+ withRecords: uq.withRecords.Clone(),
+ withLoginHistories: uq.withLoginHistories.Clone(),
+ withModels: uq.withModels.Clone(),
+ // clone intermediate query.
+ sql: uq.sql.Clone(),
+ path: uq.path,
+ modifiers: append([]func(*sql.Selector){}, uq.modifiers...),
+ }
+}
+
+// WithRecords tells the query-builder to eager-load the nodes that are connected to
+// the "records" edge. The optional arguments are used to configure the query builder of the edge.
+func (uq *UserQuery) WithRecords(opts ...func(*RecordQuery)) *UserQuery {
+ query := (&RecordClient{config: uq.config}).Query()
+ for _, opt := range opts {
+ opt(query)
+ }
+ uq.withRecords = query
+ return uq
+}
+
+// WithLoginHistories tells the query-builder to eager-load the nodes that are connected to
+// the "login_histories" edge. The optional arguments are used to configure the query builder of the edge.
+func (uq *UserQuery) WithLoginHistories(opts ...func(*UserLoginHistoryQuery)) *UserQuery {
+ query := (&UserLoginHistoryClient{config: uq.config}).Query()
+ for _, opt := range opts {
+ opt(query)
+ }
+ uq.withLoginHistories = query
+ return uq
+}
+
+// WithModels tells the query-builder to eager-load the nodes that are connected to
+// the "models" edge. The optional arguments are used to configure the query builder of the edge.
+func (uq *UserQuery) WithModels(opts ...func(*ModelQuery)) *UserQuery {
+ query := (&ModelClient{config: uq.config}).Query()
+ for _, opt := range opts {
+ opt(query)
+ }
+ uq.withModels = query
+ return uq
+}
+
+// GroupBy is used to group vertices by one or more fields/columns.
+// It is often used with aggregate functions, like: count, max, mean, min, sum.
+//
+// Example:
+//
+// var v []struct {
+// Username string `json:"username,omitempty"`
+// Count int `json:"count,omitempty"`
+// }
+//
+// client.User.Query().
+// GroupBy(user.FieldUsername).
+// Aggregate(db.Count()).
+// Scan(ctx, &v)
+func (uq *UserQuery) GroupBy(field string, fields ...string) *UserGroupBy {
+ uq.ctx.Fields = append([]string{field}, fields...)
+ grbuild := &UserGroupBy{build: uq}
+ grbuild.flds = &uq.ctx.Fields
+ grbuild.label = user.Label
+ grbuild.scan = grbuild.Scan
+ return grbuild
+}
+
+// Select allows the selection one or more fields/columns for the given query,
+// instead of selecting all fields in the entity.
+//
+// Example:
+//
+// var v []struct {
+// Username string `json:"username,omitempty"`
+// }
+//
+// client.User.Query().
+// Select(user.FieldUsername).
+// Scan(ctx, &v)
+func (uq *UserQuery) Select(fields ...string) *UserSelect {
+ uq.ctx.Fields = append(uq.ctx.Fields, fields...)
+ sbuild := &UserSelect{UserQuery: uq}
+ sbuild.label = user.Label
+ sbuild.flds, sbuild.scan = &uq.ctx.Fields, sbuild.Scan
+ return sbuild
+}
+
+// Aggregate returns a UserSelect configured with the given aggregations.
+func (uq *UserQuery) Aggregate(fns ...AggregateFunc) *UserSelect {
+ return uq.Select().Aggregate(fns...)
+}
+
+func (uq *UserQuery) prepareQuery(ctx context.Context) error {
+ for _, inter := range uq.inters {
+ if inter == nil {
+ return fmt.Errorf("db: uninitialized interceptor (forgotten import db/runtime?)")
+ }
+ if trv, ok := inter.(Traverser); ok {
+ if err := trv.Traverse(ctx, uq); err != nil {
+ return err
+ }
+ }
+ }
+ for _, f := range uq.ctx.Fields {
+ if !user.ValidColumn(f) {
+ return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
+ }
+ }
+ if uq.path != nil {
+ prev, err := uq.path(ctx)
+ if err != nil {
+ return err
+ }
+ uq.sql = prev
+ }
+ return nil
+}
+
+func (uq *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, error) {
+ var (
+ nodes = []*User{}
+ _spec = uq.querySpec()
+ loadedTypes = [3]bool{
+ uq.withRecords != nil,
+ uq.withLoginHistories != nil,
+ uq.withModels != nil,
+ }
+ )
+ _spec.ScanValues = func(columns []string) ([]any, error) {
+ return (*User).scanValues(nil, columns)
+ }
+ _spec.Assign = func(columns []string, values []any) error {
+ node := &User{config: uq.config}
+ nodes = append(nodes, node)
+ node.Edges.loadedTypes = loadedTypes
+ return node.assignValues(columns, values)
+ }
+ if len(uq.modifiers) > 0 {
+ _spec.Modifiers = uq.modifiers
+ }
+ for i := range hooks {
+ hooks[i](ctx, _spec)
+ }
+ if err := sqlgraph.QueryNodes(ctx, uq.driver, _spec); err != nil {
+ return nil, err
+ }
+ if len(nodes) == 0 {
+ return nodes, nil
+ }
+ if query := uq.withRecords; query != nil {
+ if err := uq.loadRecords(ctx, query, nodes,
+ func(n *User) { n.Edges.Records = []*Record{} },
+ func(n *User, e *Record) { n.Edges.Records = append(n.Edges.Records, e) }); err != nil {
+ return nil, err
+ }
+ }
+ if query := uq.withLoginHistories; query != nil {
+ if err := uq.loadLoginHistories(ctx, query, nodes,
+ func(n *User) { n.Edges.LoginHistories = []*UserLoginHistory{} },
+ func(n *User, e *UserLoginHistory) { n.Edges.LoginHistories = append(n.Edges.LoginHistories, e) }); err != nil {
+ return nil, err
+ }
+ }
+ if query := uq.withModels; query != nil {
+ if err := uq.loadModels(ctx, query, nodes,
+ func(n *User) { n.Edges.Models = []*Model{} },
+ func(n *User, e *Model) { n.Edges.Models = append(n.Edges.Models, e) }); err != nil {
+ return nil, err
+ }
+ }
+ return nodes, nil
+}
+
+func (uq *UserQuery) loadRecords(ctx context.Context, query *RecordQuery, nodes []*User, init func(*User), assign func(*User, *Record)) error {
+ fks := make([]driver.Value, 0, len(nodes))
+ nodeids := make(map[uuid.UUID]*User)
+ for i := range nodes {
+ fks = append(fks, nodes[i].ID)
+ nodeids[nodes[i].ID] = nodes[i]
+ if init != nil {
+ init(nodes[i])
+ }
+ }
+ if len(query.ctx.Fields) > 0 {
+ query.ctx.AppendFieldOnce(record.FieldUserID)
+ }
+ query.Where(predicate.Record(func(s *sql.Selector) {
+ s.Where(sql.InValues(s.C(user.RecordsColumn), fks...))
+ }))
+ neighbors, err := query.All(ctx)
+ if err != nil {
+ return err
+ }
+ for _, n := range neighbors {
+ fk := n.UserID
+ node, ok := nodeids[fk]
+ if !ok {
+ return fmt.Errorf(`unexpected referenced foreign-key "user_id" returned %v for node %v`, fk, n.ID)
+ }
+ assign(node, n)
+ }
+ return nil
+}
+func (uq *UserQuery) loadLoginHistories(ctx context.Context, query *UserLoginHistoryQuery, nodes []*User, init func(*User), assign func(*User, *UserLoginHistory)) error {
+ fks := make([]driver.Value, 0, len(nodes))
+ nodeids := make(map[uuid.UUID]*User)
+ for i := range nodes {
+ fks = append(fks, nodes[i].ID)
+ nodeids[nodes[i].ID] = nodes[i]
+ if init != nil {
+ init(nodes[i])
+ }
+ }
+ query.withFKs = true
+ query.Where(predicate.UserLoginHistory(func(s *sql.Selector) {
+ s.Where(sql.InValues(s.C(user.LoginHistoriesColumn), fks...))
+ }))
+ neighbors, err := query.All(ctx)
+ if err != nil {
+ return err
+ }
+ for _, n := range neighbors {
+ fk := n.user_login_histories
+ if fk == nil {
+ return fmt.Errorf(`foreign-key "user_login_histories" is nil for node %v`, n.ID)
+ }
+ node, ok := nodeids[*fk]
+ if !ok {
+ return fmt.Errorf(`unexpected referenced foreign-key "user_login_histories" returned %v for node %v`, *fk, n.ID)
+ }
+ assign(node, n)
+ }
+ return nil
+}
+func (uq *UserQuery) loadModels(ctx context.Context, query *ModelQuery, nodes []*User, init func(*User), assign func(*User, *Model)) error {
+ fks := make([]driver.Value, 0, len(nodes))
+ nodeids := make(map[uuid.UUID]*User)
+ for i := range nodes {
+ fks = append(fks, nodes[i].ID)
+ nodeids[nodes[i].ID] = nodes[i]
+ if init != nil {
+ init(nodes[i])
+ }
+ }
+ if len(query.ctx.Fields) > 0 {
+ query.ctx.AppendFieldOnce(model.FieldUserID)
+ }
+ query.Where(predicate.Model(func(s *sql.Selector) {
+ s.Where(sql.InValues(s.C(user.ModelsColumn), fks...))
+ }))
+ neighbors, err := query.All(ctx)
+ if err != nil {
+ return err
+ }
+ for _, n := range neighbors {
+ fk := n.UserID
+ node, ok := nodeids[fk]
+ if !ok {
+ return fmt.Errorf(`unexpected referenced foreign-key "user_id" returned %v for node %v`, fk, n.ID)
+ }
+ assign(node, n)
+ }
+ return nil
+}
+
+func (uq *UserQuery) sqlCount(ctx context.Context) (int, error) {
+ _spec := uq.querySpec()
+ if len(uq.modifiers) > 0 {
+ _spec.Modifiers = uq.modifiers
+ }
+ _spec.Node.Columns = uq.ctx.Fields
+ if len(uq.ctx.Fields) > 0 {
+ _spec.Unique = uq.ctx.Unique != nil && *uq.ctx.Unique
+ }
+ return sqlgraph.CountNodes(ctx, uq.driver, _spec)
+}
+
+func (uq *UserQuery) querySpec() *sqlgraph.QuerySpec {
+ _spec := sqlgraph.NewQuerySpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID))
+ _spec.From = uq.sql
+ if unique := uq.ctx.Unique; unique != nil {
+ _spec.Unique = *unique
+ } else if uq.path != nil {
+ _spec.Unique = true
+ }
+ if fields := uq.ctx.Fields; len(fields) > 0 {
+ _spec.Node.Columns = make([]string, 0, len(fields))
+ _spec.Node.Columns = append(_spec.Node.Columns, user.FieldID)
+ for i := range fields {
+ if fields[i] != user.FieldID {
+ _spec.Node.Columns = append(_spec.Node.Columns, fields[i])
+ }
+ }
+ }
+ if ps := uq.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if limit := uq.ctx.Limit; limit != nil {
+ _spec.Limit = *limit
+ }
+ if offset := uq.ctx.Offset; offset != nil {
+ _spec.Offset = *offset
+ }
+ if ps := uq.order; len(ps) > 0 {
+ _spec.Order = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ return _spec
+}
+
+func (uq *UserQuery) sqlQuery(ctx context.Context) *sql.Selector {
+ builder := sql.Dialect(uq.driver.Dialect())
+ t1 := builder.Table(user.Table)
+ columns := uq.ctx.Fields
+ if len(columns) == 0 {
+ columns = user.Columns
+ }
+ selector := builder.Select(t1.Columns(columns...)...).From(t1)
+ if uq.sql != nil {
+ selector = uq.sql
+ selector.Select(selector.Columns(columns...)...)
+ }
+ if uq.ctx.Unique != nil && *uq.ctx.Unique {
+ selector.Distinct()
+ }
+ for _, m := range uq.modifiers {
+ m(selector)
+ }
+ for _, p := range uq.predicates {
+ p(selector)
+ }
+ for _, p := range uq.order {
+ p(selector)
+ }
+ if offset := uq.ctx.Offset; offset != nil {
+ // limit is mandatory for offset clause. We start
+ // with default value, and override it below if needed.
+ selector.Offset(*offset).Limit(math.MaxInt32)
+ }
+ if limit := uq.ctx.Limit; limit != nil {
+ selector.Limit(*limit)
+ }
+ return selector
+}
+
+// ForUpdate locks the selected rows against concurrent updates, and prevent them from being
+// updated, deleted or "selected ... for update" by other sessions, until the transaction is
+// either committed or rolled-back.
+func (uq *UserQuery) ForUpdate(opts ...sql.LockOption) *UserQuery {
+ if uq.driver.Dialect() == dialect.Postgres {
+ uq.Unique(false)
+ }
+ uq.modifiers = append(uq.modifiers, func(s *sql.Selector) {
+ s.ForUpdate(opts...)
+ })
+ return uq
+}
+
+// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock
+// on any rows that are read. Other sessions can read the rows, but cannot modify them
+// until your transaction commits.
+func (uq *UserQuery) ForShare(opts ...sql.LockOption) *UserQuery {
+ if uq.driver.Dialect() == dialect.Postgres {
+ uq.Unique(false)
+ }
+ uq.modifiers = append(uq.modifiers, func(s *sql.Selector) {
+ s.ForShare(opts...)
+ })
+ return uq
+}
+
+// Modify adds a query modifier for attaching custom logic to queries.
+func (uq *UserQuery) Modify(modifiers ...func(s *sql.Selector)) *UserSelect {
+ uq.modifiers = append(uq.modifiers, modifiers...)
+ return uq.Select()
+}
+
+// UserGroupBy is the group-by builder for User entities.
+type UserGroupBy struct {
+ selector
+ build *UserQuery
+}
+
+// Aggregate adds the given aggregation functions to the group-by query.
+func (ugb *UserGroupBy) Aggregate(fns ...AggregateFunc) *UserGroupBy {
+ ugb.fns = append(ugb.fns, fns...)
+ return ugb
+}
+
+// Scan applies the selector query and scans the result into the given value.
+func (ugb *UserGroupBy) Scan(ctx context.Context, v any) error {
+ ctx = setContextOp(ctx, ugb.build.ctx, ent.OpQueryGroupBy)
+ if err := ugb.build.prepareQuery(ctx); err != nil {
+ return err
+ }
+ return scanWithInterceptors[*UserQuery, *UserGroupBy](ctx, ugb.build, ugb, ugb.build.inters, v)
+}
+
+func (ugb *UserGroupBy) sqlScan(ctx context.Context, root *UserQuery, v any) error {
+ selector := root.sqlQuery(ctx).Select()
+ aggregation := make([]string, 0, len(ugb.fns))
+ for _, fn := range ugb.fns {
+ aggregation = append(aggregation, fn(selector))
+ }
+ if len(selector.SelectedColumns()) == 0 {
+ columns := make([]string, 0, len(*ugb.flds)+len(ugb.fns))
+ for _, f := range *ugb.flds {
+ columns = append(columns, selector.C(f))
+ }
+ columns = append(columns, aggregation...)
+ selector.Select(columns...)
+ }
+ selector.GroupBy(selector.Columns(*ugb.flds...)...)
+ if err := selector.Err(); err != nil {
+ return err
+ }
+ rows := &sql.Rows{}
+ query, args := selector.Query()
+ if err := ugb.build.driver.Query(ctx, query, args, rows); err != nil {
+ return err
+ }
+ defer rows.Close()
+ return sql.ScanSlice(rows, v)
+}
+
+// UserSelect is the builder for selecting fields of User entities.
+type UserSelect struct {
+ *UserQuery
+ selector
+}
+
+// Aggregate adds the given aggregation functions to the selector query.
+func (us *UserSelect) Aggregate(fns ...AggregateFunc) *UserSelect {
+ us.fns = append(us.fns, fns...)
+ return us
+}
+
+// Scan applies the selector query and scans the result into the given value.
+func (us *UserSelect) Scan(ctx context.Context, v any) error {
+ ctx = setContextOp(ctx, us.ctx, ent.OpQuerySelect)
+ if err := us.prepareQuery(ctx); err != nil {
+ return err
+ }
+ return scanWithInterceptors[*UserQuery, *UserSelect](ctx, us.UserQuery, us, us.inters, v)
+}
+
+func (us *UserSelect) sqlScan(ctx context.Context, root *UserQuery, v any) error {
+ selector := root.sqlQuery(ctx)
+ aggregation := make([]string, 0, len(us.fns))
+ for _, fn := range us.fns {
+ aggregation = append(aggregation, fn(selector))
+ }
+ switch n := len(*us.selector.flds); {
+ case n == 0 && len(aggregation) > 0:
+ selector.Select(aggregation...)
+ case n != 0 && len(aggregation) > 0:
+ selector.AppendSelect(aggregation...)
+ }
+ rows := &sql.Rows{}
+ query, args := selector.Query()
+ if err := us.driver.Query(ctx, query, args, rows); err != nil {
+ return err
+ }
+ defer rows.Close()
+ return sql.ScanSlice(rows, v)
+}
+
+// Modify adds a query modifier for attaching custom logic to queries.
+func (us *UserSelect) Modify(modifiers ...func(s *sql.Selector)) *UserSelect {
+ us.modifiers = append(us.modifiers, modifiers...)
+ return us
+}
diff --git a/backend/db/user_update.go b/backend/db/user_update.go
new file mode 100644
index 0000000..f5d15d5
--- /dev/null
+++ b/backend/db/user_update.go
@@ -0,0 +1,887 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "time"
+
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/consts"
+ "github.com/chaitin/MonkeyCode/backend/db/model"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+ "github.com/chaitin/MonkeyCode/backend/db/record"
+ "github.com/chaitin/MonkeyCode/backend/db/user"
+ "github.com/chaitin/MonkeyCode/backend/db/userloginhistory"
+ "github.com/google/uuid"
+)
+
+// UserUpdate is the builder for updating User entities.
+type UserUpdate struct {
+ config
+ hooks []Hook
+ mutation *UserMutation
+ modifiers []func(*sql.UpdateBuilder)
+}
+
+// Where appends a list predicates to the UserUpdate builder.
+func (uu *UserUpdate) Where(ps ...predicate.User) *UserUpdate {
+ uu.mutation.Where(ps...)
+ return uu
+}
+
+// SetUsername sets the "username" field.
+func (uu *UserUpdate) SetUsername(s string) *UserUpdate {
+ uu.mutation.SetUsername(s)
+ return uu
+}
+
+// SetNillableUsername sets the "username" field if the given value is not nil.
+func (uu *UserUpdate) SetNillableUsername(s *string) *UserUpdate {
+ if s != nil {
+ uu.SetUsername(*s)
+ }
+ return uu
+}
+
+// SetPassword sets the "password" field.
+func (uu *UserUpdate) SetPassword(s string) *UserUpdate {
+ uu.mutation.SetPassword(s)
+ return uu
+}
+
+// SetNillablePassword sets the "password" field if the given value is not nil.
+func (uu *UserUpdate) SetNillablePassword(s *string) *UserUpdate {
+ if s != nil {
+ uu.SetPassword(*s)
+ }
+ return uu
+}
+
+// SetEmail sets the "email" field.
+func (uu *UserUpdate) SetEmail(s string) *UserUpdate {
+ uu.mutation.SetEmail(s)
+ return uu
+}
+
+// SetNillableEmail sets the "email" field if the given value is not nil.
+func (uu *UserUpdate) SetNillableEmail(s *string) *UserUpdate {
+ if s != nil {
+ uu.SetEmail(*s)
+ }
+ return uu
+}
+
+// SetStatus sets the "status" field.
+func (uu *UserUpdate) SetStatus(cs consts.UserStatus) *UserUpdate {
+ uu.mutation.SetStatus(cs)
+ return uu
+}
+
+// SetNillableStatus sets the "status" field if the given value is not nil.
+func (uu *UserUpdate) SetNillableStatus(cs *consts.UserStatus) *UserUpdate {
+ if cs != nil {
+ uu.SetStatus(*cs)
+ }
+ return uu
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (uu *UserUpdate) SetCreatedAt(t time.Time) *UserUpdate {
+ uu.mutation.SetCreatedAt(t)
+ return uu
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (uu *UserUpdate) SetNillableCreatedAt(t *time.Time) *UserUpdate {
+ if t != nil {
+ uu.SetCreatedAt(*t)
+ }
+ return uu
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (uu *UserUpdate) SetUpdatedAt(t time.Time) *UserUpdate {
+ uu.mutation.SetUpdatedAt(t)
+ return uu
+}
+
+// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
+func (uu *UserUpdate) SetNillableUpdatedAt(t *time.Time) *UserUpdate {
+ if t != nil {
+ uu.SetUpdatedAt(*t)
+ }
+ return uu
+}
+
+// AddRecordIDs adds the "records" edge to the Record entity by IDs.
+func (uu *UserUpdate) AddRecordIDs(ids ...uuid.UUID) *UserUpdate {
+ uu.mutation.AddRecordIDs(ids...)
+ return uu
+}
+
+// AddRecords adds the "records" edges to the Record entity.
+func (uu *UserUpdate) AddRecords(r ...*Record) *UserUpdate {
+ ids := make([]uuid.UUID, len(r))
+ for i := range r {
+ ids[i] = r[i].ID
+ }
+ return uu.AddRecordIDs(ids...)
+}
+
+// AddLoginHistoryIDs adds the "login_histories" edge to the UserLoginHistory entity by IDs.
+func (uu *UserUpdate) AddLoginHistoryIDs(ids ...uuid.UUID) *UserUpdate {
+ uu.mutation.AddLoginHistoryIDs(ids...)
+ return uu
+}
+
+// AddLoginHistories adds the "login_histories" edges to the UserLoginHistory entity.
+func (uu *UserUpdate) AddLoginHistories(u ...*UserLoginHistory) *UserUpdate {
+ ids := make([]uuid.UUID, len(u))
+ for i := range u {
+ ids[i] = u[i].ID
+ }
+ return uu.AddLoginHistoryIDs(ids...)
+}
+
+// AddModelIDs adds the "models" edge to the Model entity by IDs.
+func (uu *UserUpdate) AddModelIDs(ids ...uuid.UUID) *UserUpdate {
+ uu.mutation.AddModelIDs(ids...)
+ return uu
+}
+
+// AddModels adds the "models" edges to the Model entity.
+func (uu *UserUpdate) AddModels(m ...*Model) *UserUpdate {
+ ids := make([]uuid.UUID, len(m))
+ for i := range m {
+ ids[i] = m[i].ID
+ }
+ return uu.AddModelIDs(ids...)
+}
+
+// Mutation returns the UserMutation object of the builder.
+func (uu *UserUpdate) Mutation() *UserMutation {
+ return uu.mutation
+}
+
+// ClearRecords clears all "records" edges to the Record entity.
+func (uu *UserUpdate) ClearRecords() *UserUpdate {
+ uu.mutation.ClearRecords()
+ return uu
+}
+
+// RemoveRecordIDs removes the "records" edge to Record entities by IDs.
+func (uu *UserUpdate) RemoveRecordIDs(ids ...uuid.UUID) *UserUpdate {
+ uu.mutation.RemoveRecordIDs(ids...)
+ return uu
+}
+
+// RemoveRecords removes "records" edges to Record entities.
+func (uu *UserUpdate) RemoveRecords(r ...*Record) *UserUpdate {
+ ids := make([]uuid.UUID, len(r))
+ for i := range r {
+ ids[i] = r[i].ID
+ }
+ return uu.RemoveRecordIDs(ids...)
+}
+
+// ClearLoginHistories clears all "login_histories" edges to the UserLoginHistory entity.
+func (uu *UserUpdate) ClearLoginHistories() *UserUpdate {
+ uu.mutation.ClearLoginHistories()
+ return uu
+}
+
+// RemoveLoginHistoryIDs removes the "login_histories" edge to UserLoginHistory entities by IDs.
+func (uu *UserUpdate) RemoveLoginHistoryIDs(ids ...uuid.UUID) *UserUpdate {
+ uu.mutation.RemoveLoginHistoryIDs(ids...)
+ return uu
+}
+
+// RemoveLoginHistories removes "login_histories" edges to UserLoginHistory entities.
+func (uu *UserUpdate) RemoveLoginHistories(u ...*UserLoginHistory) *UserUpdate {
+ ids := make([]uuid.UUID, len(u))
+ for i := range u {
+ ids[i] = u[i].ID
+ }
+ return uu.RemoveLoginHistoryIDs(ids...)
+}
+
+// ClearModels clears all "models" edges to the Model entity.
+func (uu *UserUpdate) ClearModels() *UserUpdate {
+ uu.mutation.ClearModels()
+ return uu
+}
+
+// RemoveModelIDs removes the "models" edge to Model entities by IDs.
+func (uu *UserUpdate) RemoveModelIDs(ids ...uuid.UUID) *UserUpdate {
+ uu.mutation.RemoveModelIDs(ids...)
+ return uu
+}
+
+// RemoveModels removes "models" edges to Model entities.
+func (uu *UserUpdate) RemoveModels(m ...*Model) *UserUpdate {
+ ids := make([]uuid.UUID, len(m))
+ for i := range m {
+ ids[i] = m[i].ID
+ }
+ return uu.RemoveModelIDs(ids...)
+}
+
+// Save executes the query and returns the number of nodes affected by the update operation.
+func (uu *UserUpdate) Save(ctx context.Context) (int, error) {
+ return withHooks(ctx, uu.sqlSave, uu.mutation, uu.hooks)
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (uu *UserUpdate) SaveX(ctx context.Context) int {
+ affected, err := uu.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return affected
+}
+
+// Exec executes the query.
+func (uu *UserUpdate) Exec(ctx context.Context) error {
+ _, err := uu.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (uu *UserUpdate) ExecX(ctx context.Context) {
+ if err := uu.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
+func (uu *UserUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *UserUpdate {
+ uu.modifiers = append(uu.modifiers, modifiers...)
+ return uu
+}
+
+func (uu *UserUpdate) sqlSave(ctx context.Context) (n int, err error) {
+ _spec := sqlgraph.NewUpdateSpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID))
+ if ps := uu.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if value, ok := uu.mutation.Username(); ok {
+ _spec.SetField(user.FieldUsername, field.TypeString, value)
+ }
+ if value, ok := uu.mutation.Password(); ok {
+ _spec.SetField(user.FieldPassword, field.TypeString, value)
+ }
+ if value, ok := uu.mutation.Email(); ok {
+ _spec.SetField(user.FieldEmail, field.TypeString, value)
+ }
+ if value, ok := uu.mutation.Status(); ok {
+ _spec.SetField(user.FieldStatus, field.TypeString, value)
+ }
+ if value, ok := uu.mutation.CreatedAt(); ok {
+ _spec.SetField(user.FieldCreatedAt, field.TypeTime, value)
+ }
+ if value, ok := uu.mutation.UpdatedAt(); ok {
+ _spec.SetField(user.FieldUpdatedAt, field.TypeTime, value)
+ }
+ if uu.mutation.RecordsCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: user.RecordsTable,
+ Columns: []string{user.RecordsColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(record.FieldID, field.TypeUUID),
+ },
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := uu.mutation.RemovedRecordsIDs(); len(nodes) > 0 && !uu.mutation.RecordsCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: user.RecordsTable,
+ Columns: []string{user.RecordsColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(record.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := uu.mutation.RecordsIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: user.RecordsTable,
+ Columns: []string{user.RecordsColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(record.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Add = append(_spec.Edges.Add, edge)
+ }
+ if uu.mutation.LoginHistoriesCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: user.LoginHistoriesTable,
+ Columns: []string{user.LoginHistoriesColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(userloginhistory.FieldID, field.TypeUUID),
+ },
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := uu.mutation.RemovedLoginHistoriesIDs(); len(nodes) > 0 && !uu.mutation.LoginHistoriesCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: user.LoginHistoriesTable,
+ Columns: []string{user.LoginHistoriesColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(userloginhistory.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := uu.mutation.LoginHistoriesIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: user.LoginHistoriesTable,
+ Columns: []string{user.LoginHistoriesColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(userloginhistory.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Add = append(_spec.Edges.Add, edge)
+ }
+ if uu.mutation.ModelsCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: user.ModelsTable,
+ Columns: []string{user.ModelsColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(model.FieldID, field.TypeUUID),
+ },
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := uu.mutation.RemovedModelsIDs(); len(nodes) > 0 && !uu.mutation.ModelsCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: user.ModelsTable,
+ Columns: []string{user.ModelsColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(model.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := uu.mutation.ModelsIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: user.ModelsTable,
+ Columns: []string{user.ModelsColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(model.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Add = append(_spec.Edges.Add, edge)
+ }
+ _spec.AddModifiers(uu.modifiers...)
+ if n, err = sqlgraph.UpdateNodes(ctx, uu.driver, _spec); err != nil {
+ if _, ok := err.(*sqlgraph.NotFoundError); ok {
+ err = &NotFoundError{user.Label}
+ } else if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return 0, err
+ }
+ uu.mutation.done = true
+ return n, nil
+}
+
+// UserUpdateOne is the builder for updating a single User entity.
+type UserUpdateOne struct {
+ config
+ fields []string
+ hooks []Hook
+ mutation *UserMutation
+ modifiers []func(*sql.UpdateBuilder)
+}
+
+// SetUsername sets the "username" field.
+func (uuo *UserUpdateOne) SetUsername(s string) *UserUpdateOne {
+ uuo.mutation.SetUsername(s)
+ return uuo
+}
+
+// SetNillableUsername sets the "username" field if the given value is not nil.
+func (uuo *UserUpdateOne) SetNillableUsername(s *string) *UserUpdateOne {
+ if s != nil {
+ uuo.SetUsername(*s)
+ }
+ return uuo
+}
+
+// SetPassword sets the "password" field.
+func (uuo *UserUpdateOne) SetPassword(s string) *UserUpdateOne {
+ uuo.mutation.SetPassword(s)
+ return uuo
+}
+
+// SetNillablePassword sets the "password" field if the given value is not nil.
+func (uuo *UserUpdateOne) SetNillablePassword(s *string) *UserUpdateOne {
+ if s != nil {
+ uuo.SetPassword(*s)
+ }
+ return uuo
+}
+
+// SetEmail sets the "email" field.
+func (uuo *UserUpdateOne) SetEmail(s string) *UserUpdateOne {
+ uuo.mutation.SetEmail(s)
+ return uuo
+}
+
+// SetNillableEmail sets the "email" field if the given value is not nil.
+func (uuo *UserUpdateOne) SetNillableEmail(s *string) *UserUpdateOne {
+ if s != nil {
+ uuo.SetEmail(*s)
+ }
+ return uuo
+}
+
+// SetStatus sets the "status" field.
+func (uuo *UserUpdateOne) SetStatus(cs consts.UserStatus) *UserUpdateOne {
+ uuo.mutation.SetStatus(cs)
+ return uuo
+}
+
+// SetNillableStatus sets the "status" field if the given value is not nil.
+func (uuo *UserUpdateOne) SetNillableStatus(cs *consts.UserStatus) *UserUpdateOne {
+ if cs != nil {
+ uuo.SetStatus(*cs)
+ }
+ return uuo
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (uuo *UserUpdateOne) SetCreatedAt(t time.Time) *UserUpdateOne {
+ uuo.mutation.SetCreatedAt(t)
+ return uuo
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (uuo *UserUpdateOne) SetNillableCreatedAt(t *time.Time) *UserUpdateOne {
+ if t != nil {
+ uuo.SetCreatedAt(*t)
+ }
+ return uuo
+}
+
+// SetUpdatedAt sets the "updated_at" field.
+func (uuo *UserUpdateOne) SetUpdatedAt(t time.Time) *UserUpdateOne {
+ uuo.mutation.SetUpdatedAt(t)
+ return uuo
+}
+
+// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
+func (uuo *UserUpdateOne) SetNillableUpdatedAt(t *time.Time) *UserUpdateOne {
+ if t != nil {
+ uuo.SetUpdatedAt(*t)
+ }
+ return uuo
+}
+
+// AddRecordIDs adds the "records" edge to the Record entity by IDs.
+func (uuo *UserUpdateOne) AddRecordIDs(ids ...uuid.UUID) *UserUpdateOne {
+ uuo.mutation.AddRecordIDs(ids...)
+ return uuo
+}
+
+// AddRecords adds the "records" edges to the Record entity.
+func (uuo *UserUpdateOne) AddRecords(r ...*Record) *UserUpdateOne {
+ ids := make([]uuid.UUID, len(r))
+ for i := range r {
+ ids[i] = r[i].ID
+ }
+ return uuo.AddRecordIDs(ids...)
+}
+
+// AddLoginHistoryIDs adds the "login_histories" edge to the UserLoginHistory entity by IDs.
+func (uuo *UserUpdateOne) AddLoginHistoryIDs(ids ...uuid.UUID) *UserUpdateOne {
+ uuo.mutation.AddLoginHistoryIDs(ids...)
+ return uuo
+}
+
+// AddLoginHistories adds the "login_histories" edges to the UserLoginHistory entity.
+func (uuo *UserUpdateOne) AddLoginHistories(u ...*UserLoginHistory) *UserUpdateOne {
+ ids := make([]uuid.UUID, len(u))
+ for i := range u {
+ ids[i] = u[i].ID
+ }
+ return uuo.AddLoginHistoryIDs(ids...)
+}
+
+// AddModelIDs adds the "models" edge to the Model entity by IDs.
+func (uuo *UserUpdateOne) AddModelIDs(ids ...uuid.UUID) *UserUpdateOne {
+ uuo.mutation.AddModelIDs(ids...)
+ return uuo
+}
+
+// AddModels adds the "models" edges to the Model entity.
+func (uuo *UserUpdateOne) AddModels(m ...*Model) *UserUpdateOne {
+ ids := make([]uuid.UUID, len(m))
+ for i := range m {
+ ids[i] = m[i].ID
+ }
+ return uuo.AddModelIDs(ids...)
+}
+
+// Mutation returns the UserMutation object of the builder.
+func (uuo *UserUpdateOne) Mutation() *UserMutation {
+ return uuo.mutation
+}
+
+// ClearRecords clears all "records" edges to the Record entity.
+func (uuo *UserUpdateOne) ClearRecords() *UserUpdateOne {
+ uuo.mutation.ClearRecords()
+ return uuo
+}
+
+// RemoveRecordIDs removes the "records" edge to Record entities by IDs.
+func (uuo *UserUpdateOne) RemoveRecordIDs(ids ...uuid.UUID) *UserUpdateOne {
+ uuo.mutation.RemoveRecordIDs(ids...)
+ return uuo
+}
+
+// RemoveRecords removes "records" edges to Record entities.
+func (uuo *UserUpdateOne) RemoveRecords(r ...*Record) *UserUpdateOne {
+ ids := make([]uuid.UUID, len(r))
+ for i := range r {
+ ids[i] = r[i].ID
+ }
+ return uuo.RemoveRecordIDs(ids...)
+}
+
+// ClearLoginHistories clears all "login_histories" edges to the UserLoginHistory entity.
+func (uuo *UserUpdateOne) ClearLoginHistories() *UserUpdateOne {
+ uuo.mutation.ClearLoginHistories()
+ return uuo
+}
+
+// RemoveLoginHistoryIDs removes the "login_histories" edge to UserLoginHistory entities by IDs.
+func (uuo *UserUpdateOne) RemoveLoginHistoryIDs(ids ...uuid.UUID) *UserUpdateOne {
+ uuo.mutation.RemoveLoginHistoryIDs(ids...)
+ return uuo
+}
+
+// RemoveLoginHistories removes "login_histories" edges to UserLoginHistory entities.
+func (uuo *UserUpdateOne) RemoveLoginHistories(u ...*UserLoginHistory) *UserUpdateOne {
+ ids := make([]uuid.UUID, len(u))
+ for i := range u {
+ ids[i] = u[i].ID
+ }
+ return uuo.RemoveLoginHistoryIDs(ids...)
+}
+
+// ClearModels clears all "models" edges to the Model entity.
+func (uuo *UserUpdateOne) ClearModels() *UserUpdateOne {
+ uuo.mutation.ClearModels()
+ return uuo
+}
+
+// RemoveModelIDs removes the "models" edge to Model entities by IDs.
+func (uuo *UserUpdateOne) RemoveModelIDs(ids ...uuid.UUID) *UserUpdateOne {
+ uuo.mutation.RemoveModelIDs(ids...)
+ return uuo
+}
+
+// RemoveModels removes "models" edges to Model entities.
+func (uuo *UserUpdateOne) RemoveModels(m ...*Model) *UserUpdateOne {
+ ids := make([]uuid.UUID, len(m))
+ for i := range m {
+ ids[i] = m[i].ID
+ }
+ return uuo.RemoveModelIDs(ids...)
+}
+
+// Where appends a list predicates to the UserUpdate builder.
+func (uuo *UserUpdateOne) Where(ps ...predicate.User) *UserUpdateOne {
+ uuo.mutation.Where(ps...)
+ return uuo
+}
+
+// Select allows selecting one or more fields (columns) of the returned entity.
+// The default is selecting all fields defined in the entity schema.
+func (uuo *UserUpdateOne) Select(field string, fields ...string) *UserUpdateOne {
+ uuo.fields = append([]string{field}, fields...)
+ return uuo
+}
+
+// Save executes the query and returns the updated User entity.
+func (uuo *UserUpdateOne) Save(ctx context.Context) (*User, error) {
+ return withHooks(ctx, uuo.sqlSave, uuo.mutation, uuo.hooks)
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (uuo *UserUpdateOne) SaveX(ctx context.Context) *User {
+ node, err := uuo.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return node
+}
+
+// Exec executes the query on the entity.
+func (uuo *UserUpdateOne) Exec(ctx context.Context) error {
+ _, err := uuo.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (uuo *UserUpdateOne) ExecX(ctx context.Context) {
+ if err := uuo.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
+func (uuo *UserUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *UserUpdateOne {
+ uuo.modifiers = append(uuo.modifiers, modifiers...)
+ return uuo
+}
+
+func (uuo *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) {
+ _spec := sqlgraph.NewUpdateSpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID))
+ id, ok := uuo.mutation.ID()
+ if !ok {
+ return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "User.id" for update`)}
+ }
+ _spec.Node.ID.Value = id
+ if fields := uuo.fields; len(fields) > 0 {
+ _spec.Node.Columns = make([]string, 0, len(fields))
+ _spec.Node.Columns = append(_spec.Node.Columns, user.FieldID)
+ for _, f := range fields {
+ if !user.ValidColumn(f) {
+ return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
+ }
+ if f != user.FieldID {
+ _spec.Node.Columns = append(_spec.Node.Columns, f)
+ }
+ }
+ }
+ if ps := uuo.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if value, ok := uuo.mutation.Username(); ok {
+ _spec.SetField(user.FieldUsername, field.TypeString, value)
+ }
+ if value, ok := uuo.mutation.Password(); ok {
+ _spec.SetField(user.FieldPassword, field.TypeString, value)
+ }
+ if value, ok := uuo.mutation.Email(); ok {
+ _spec.SetField(user.FieldEmail, field.TypeString, value)
+ }
+ if value, ok := uuo.mutation.Status(); ok {
+ _spec.SetField(user.FieldStatus, field.TypeString, value)
+ }
+ if value, ok := uuo.mutation.CreatedAt(); ok {
+ _spec.SetField(user.FieldCreatedAt, field.TypeTime, value)
+ }
+ if value, ok := uuo.mutation.UpdatedAt(); ok {
+ _spec.SetField(user.FieldUpdatedAt, field.TypeTime, value)
+ }
+ if uuo.mutation.RecordsCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: user.RecordsTable,
+ Columns: []string{user.RecordsColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(record.FieldID, field.TypeUUID),
+ },
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := uuo.mutation.RemovedRecordsIDs(); len(nodes) > 0 && !uuo.mutation.RecordsCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: user.RecordsTable,
+ Columns: []string{user.RecordsColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(record.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := uuo.mutation.RecordsIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: user.RecordsTable,
+ Columns: []string{user.RecordsColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(record.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Add = append(_spec.Edges.Add, edge)
+ }
+ if uuo.mutation.LoginHistoriesCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: user.LoginHistoriesTable,
+ Columns: []string{user.LoginHistoriesColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(userloginhistory.FieldID, field.TypeUUID),
+ },
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := uuo.mutation.RemovedLoginHistoriesIDs(); len(nodes) > 0 && !uuo.mutation.LoginHistoriesCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: user.LoginHistoriesTable,
+ Columns: []string{user.LoginHistoriesColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(userloginhistory.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := uuo.mutation.LoginHistoriesIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: user.LoginHistoriesTable,
+ Columns: []string{user.LoginHistoriesColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(userloginhistory.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Add = append(_spec.Edges.Add, edge)
+ }
+ if uuo.mutation.ModelsCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: user.ModelsTable,
+ Columns: []string{user.ModelsColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(model.FieldID, field.TypeUUID),
+ },
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := uuo.mutation.RemovedModelsIDs(); len(nodes) > 0 && !uuo.mutation.ModelsCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: user.ModelsTable,
+ Columns: []string{user.ModelsColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(model.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := uuo.mutation.ModelsIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.O2M,
+ Inverse: false,
+ Table: user.ModelsTable,
+ Columns: []string{user.ModelsColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(model.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Add = append(_spec.Edges.Add, edge)
+ }
+ _spec.AddModifiers(uuo.modifiers...)
+ _node = &User{config: uuo.config}
+ _spec.Assign = _node.assignValues
+ _spec.ScanValues = _node.scanValues
+ if err = sqlgraph.UpdateNode(ctx, uuo.driver, _spec); err != nil {
+ if _, ok := err.(*sqlgraph.NotFoundError); ok {
+ err = &NotFoundError{user.Label}
+ } else if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return nil, err
+ }
+ uuo.mutation.done = true
+ return _node, nil
+}
diff --git a/backend/db/userloginhistory.go b/backend/db/userloginhistory.go
new file mode 100644
index 0000000..a183669
--- /dev/null
+++ b/backend/db/userloginhistory.go
@@ -0,0 +1,245 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "fmt"
+ "strings"
+ "time"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect/sql"
+ "github.com/chaitin/MonkeyCode/backend/db/user"
+ "github.com/chaitin/MonkeyCode/backend/db/userloginhistory"
+ "github.com/google/uuid"
+)
+
+// UserLoginHistory is the model entity for the UserLoginHistory schema.
+type UserLoginHistory struct {
+ config `json:"-"`
+ // ID of the ent.
+ ID uuid.UUID `json:"id,omitempty"`
+ // UserID holds the value of the "user_id" field.
+ UserID uuid.UUID `json:"user_id,omitempty"`
+ // IP holds the value of the "ip" field.
+ IP string `json:"ip,omitempty"`
+ // Country holds the value of the "country" field.
+ Country string `json:"country,omitempty"`
+ // Province holds the value of the "province" field.
+ Province string `json:"province,omitempty"`
+ // City holds the value of the "city" field.
+ City string `json:"city,omitempty"`
+ // Isp holds the value of the "isp" field.
+ Isp string `json:"isp,omitempty"`
+ // Asn holds the value of the "asn" field.
+ Asn string `json:"asn,omitempty"`
+ // ClientVersion holds the value of the "client_version" field.
+ ClientVersion string `json:"client_version,omitempty"`
+ // Device holds the value of the "device" field.
+ Device string `json:"device,omitempty"`
+ // CreatedAt holds the value of the "created_at" field.
+ CreatedAt time.Time `json:"created_at,omitempty"`
+ // Edges holds the relations/edges for other nodes in the graph.
+ // The values are being populated by the UserLoginHistoryQuery when eager-loading is set.
+ Edges UserLoginHistoryEdges `json:"edges"`
+ user_login_histories *uuid.UUID
+ selectValues sql.SelectValues
+}
+
+// UserLoginHistoryEdges holds the relations/edges for other nodes in the graph.
+type UserLoginHistoryEdges struct {
+ // Owner holds the value of the owner edge.
+ Owner *User `json:"owner,omitempty"`
+ // loadedTypes holds the information for reporting if a
+ // type was loaded (or requested) in eager-loading or not.
+ loadedTypes [1]bool
+}
+
+// OwnerOrErr returns the Owner value or an error if the edge
+// was not loaded in eager-loading, or loaded but was not found.
+func (e UserLoginHistoryEdges) OwnerOrErr() (*User, error) {
+ if e.Owner != nil {
+ return e.Owner, nil
+ } else if e.loadedTypes[0] {
+ return nil, &NotFoundError{label: user.Label}
+ }
+ return nil, &NotLoadedError{edge: "owner"}
+}
+
+// scanValues returns the types for scanning values from sql.Rows.
+func (*UserLoginHistory) scanValues(columns []string) ([]any, error) {
+ values := make([]any, len(columns))
+ for i := range columns {
+ switch columns[i] {
+ case userloginhistory.FieldIP, userloginhistory.FieldCountry, userloginhistory.FieldProvince, userloginhistory.FieldCity, userloginhistory.FieldIsp, userloginhistory.FieldAsn, userloginhistory.FieldClientVersion, userloginhistory.FieldDevice:
+ values[i] = new(sql.NullString)
+ case userloginhistory.FieldCreatedAt:
+ values[i] = new(sql.NullTime)
+ case userloginhistory.FieldID, userloginhistory.FieldUserID:
+ values[i] = new(uuid.UUID)
+ case userloginhistory.ForeignKeys[0]: // user_login_histories
+ values[i] = &sql.NullScanner{S: new(uuid.UUID)}
+ default:
+ values[i] = new(sql.UnknownType)
+ }
+ }
+ return values, nil
+}
+
+// assignValues assigns the values that were returned from sql.Rows (after scanning)
+// to the UserLoginHistory fields.
+func (ulh *UserLoginHistory) assignValues(columns []string, values []any) error {
+ if m, n := len(values), len(columns); m < n {
+ return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
+ }
+ for i := range columns {
+ switch columns[i] {
+ case userloginhistory.FieldID:
+ if value, ok := values[i].(*uuid.UUID); !ok {
+ return fmt.Errorf("unexpected type %T for field id", values[i])
+ } else if value != nil {
+ ulh.ID = *value
+ }
+ case userloginhistory.FieldUserID:
+ if value, ok := values[i].(*uuid.UUID); !ok {
+ return fmt.Errorf("unexpected type %T for field user_id", values[i])
+ } else if value != nil {
+ ulh.UserID = *value
+ }
+ case userloginhistory.FieldIP:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field ip", values[i])
+ } else if value.Valid {
+ ulh.IP = value.String
+ }
+ case userloginhistory.FieldCountry:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field country", values[i])
+ } else if value.Valid {
+ ulh.Country = value.String
+ }
+ case userloginhistory.FieldProvince:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field province", values[i])
+ } else if value.Valid {
+ ulh.Province = value.String
+ }
+ case userloginhistory.FieldCity:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field city", values[i])
+ } else if value.Valid {
+ ulh.City = value.String
+ }
+ case userloginhistory.FieldIsp:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field isp", values[i])
+ } else if value.Valid {
+ ulh.Isp = value.String
+ }
+ case userloginhistory.FieldAsn:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field asn", values[i])
+ } else if value.Valid {
+ ulh.Asn = value.String
+ }
+ case userloginhistory.FieldClientVersion:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field client_version", values[i])
+ } else if value.Valid {
+ ulh.ClientVersion = value.String
+ }
+ case userloginhistory.FieldDevice:
+ if value, ok := values[i].(*sql.NullString); !ok {
+ return fmt.Errorf("unexpected type %T for field device", values[i])
+ } else if value.Valid {
+ ulh.Device = value.String
+ }
+ case userloginhistory.FieldCreatedAt:
+ if value, ok := values[i].(*sql.NullTime); !ok {
+ return fmt.Errorf("unexpected type %T for field created_at", values[i])
+ } else if value.Valid {
+ ulh.CreatedAt = value.Time
+ }
+ case userloginhistory.ForeignKeys[0]:
+ if value, ok := values[i].(*sql.NullScanner); !ok {
+ return fmt.Errorf("unexpected type %T for field user_login_histories", values[i])
+ } else if value.Valid {
+ ulh.user_login_histories = new(uuid.UUID)
+ *ulh.user_login_histories = *value.S.(*uuid.UUID)
+ }
+ default:
+ ulh.selectValues.Set(columns[i], values[i])
+ }
+ }
+ return nil
+}
+
+// Value returns the ent.Value that was dynamically selected and assigned to the UserLoginHistory.
+// This includes values selected through modifiers, order, etc.
+func (ulh *UserLoginHistory) Value(name string) (ent.Value, error) {
+ return ulh.selectValues.Get(name)
+}
+
+// QueryOwner queries the "owner" edge of the UserLoginHistory entity.
+func (ulh *UserLoginHistory) QueryOwner() *UserQuery {
+ return NewUserLoginHistoryClient(ulh.config).QueryOwner(ulh)
+}
+
+// Update returns a builder for updating this UserLoginHistory.
+// Note that you need to call UserLoginHistory.Unwrap() before calling this method if this UserLoginHistory
+// was returned from a transaction, and the transaction was committed or rolled back.
+func (ulh *UserLoginHistory) Update() *UserLoginHistoryUpdateOne {
+ return NewUserLoginHistoryClient(ulh.config).UpdateOne(ulh)
+}
+
+// Unwrap unwraps the UserLoginHistory entity that was returned from a transaction after it was closed,
+// so that all future queries will be executed through the driver which created the transaction.
+func (ulh *UserLoginHistory) Unwrap() *UserLoginHistory {
+ _tx, ok := ulh.config.driver.(*txDriver)
+ if !ok {
+ panic("db: UserLoginHistory is not a transactional entity")
+ }
+ ulh.config.driver = _tx.drv
+ return ulh
+}
+
+// String implements the fmt.Stringer.
+func (ulh *UserLoginHistory) String() string {
+ var builder strings.Builder
+ builder.WriteString("UserLoginHistory(")
+ builder.WriteString(fmt.Sprintf("id=%v, ", ulh.ID))
+ builder.WriteString("user_id=")
+ builder.WriteString(fmt.Sprintf("%v", ulh.UserID))
+ builder.WriteString(", ")
+ builder.WriteString("ip=")
+ builder.WriteString(ulh.IP)
+ builder.WriteString(", ")
+ builder.WriteString("country=")
+ builder.WriteString(ulh.Country)
+ builder.WriteString(", ")
+ builder.WriteString("province=")
+ builder.WriteString(ulh.Province)
+ builder.WriteString(", ")
+ builder.WriteString("city=")
+ builder.WriteString(ulh.City)
+ builder.WriteString(", ")
+ builder.WriteString("isp=")
+ builder.WriteString(ulh.Isp)
+ builder.WriteString(", ")
+ builder.WriteString("asn=")
+ builder.WriteString(ulh.Asn)
+ builder.WriteString(", ")
+ builder.WriteString("client_version=")
+ builder.WriteString(ulh.ClientVersion)
+ builder.WriteString(", ")
+ builder.WriteString("device=")
+ builder.WriteString(ulh.Device)
+ builder.WriteString(", ")
+ builder.WriteString("created_at=")
+ builder.WriteString(ulh.CreatedAt.Format(time.ANSIC))
+ builder.WriteByte(')')
+ return builder.String()
+}
+
+// UserLoginHistories is a parsable slice of UserLoginHistory.
+type UserLoginHistories []*UserLoginHistory
diff --git a/backend/db/userloginhistory/userloginhistory.go b/backend/db/userloginhistory/userloginhistory.go
new file mode 100644
index 0000000..2694c85
--- /dev/null
+++ b/backend/db/userloginhistory/userloginhistory.go
@@ -0,0 +1,161 @@
+// Code generated by ent, DO NOT EDIT.
+
+package userloginhistory
+
+import (
+ "time"
+
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+)
+
+const (
+ // Label holds the string label denoting the userloginhistory type in the database.
+ Label = "user_login_history"
+ // FieldID holds the string denoting the id field in the database.
+ FieldID = "id"
+ // FieldUserID holds the string denoting the user_id field in the database.
+ FieldUserID = "user_id"
+ // FieldIP holds the string denoting the ip field in the database.
+ FieldIP = "ip"
+ // FieldCountry holds the string denoting the country field in the database.
+ FieldCountry = "country"
+ // FieldProvince holds the string denoting the province field in the database.
+ FieldProvince = "province"
+ // FieldCity holds the string denoting the city field in the database.
+ FieldCity = "city"
+ // FieldIsp holds the string denoting the isp field in the database.
+ FieldIsp = "isp"
+ // FieldAsn holds the string denoting the asn field in the database.
+ FieldAsn = "asn"
+ // FieldClientVersion holds the string denoting the client_version field in the database.
+ FieldClientVersion = "client_version"
+ // FieldDevice holds the string denoting the device field in the database.
+ FieldDevice = "device"
+ // FieldCreatedAt holds the string denoting the created_at field in the database.
+ FieldCreatedAt = "created_at"
+ // EdgeOwner holds the string denoting the owner edge name in mutations.
+ EdgeOwner = "owner"
+ // Table holds the table name of the userloginhistory in the database.
+ Table = "user_login_histories"
+ // OwnerTable is the table that holds the owner relation/edge.
+ OwnerTable = "user_login_histories"
+ // OwnerInverseTable is the table name for the User entity.
+ // It exists in this package in order to avoid circular dependency with the "user" package.
+ OwnerInverseTable = "users"
+ // OwnerColumn is the table column denoting the owner relation/edge.
+ OwnerColumn = "user_login_histories"
+)
+
+// Columns holds all SQL columns for userloginhistory fields.
+var Columns = []string{
+ FieldID,
+ FieldUserID,
+ FieldIP,
+ FieldCountry,
+ FieldProvince,
+ FieldCity,
+ FieldIsp,
+ FieldAsn,
+ FieldClientVersion,
+ FieldDevice,
+ FieldCreatedAt,
+}
+
+// ForeignKeys holds the SQL foreign-keys that are owned by the "user_login_histories"
+// table and are not defined as standalone fields in the schema.
+var ForeignKeys = []string{
+ "user_login_histories",
+}
+
+// ValidColumn reports if the column name is valid (part of the table columns).
+func ValidColumn(column string) bool {
+ for i := range Columns {
+ if column == Columns[i] {
+ return true
+ }
+ }
+ for i := range ForeignKeys {
+ if column == ForeignKeys[i] {
+ return true
+ }
+ }
+ return false
+}
+
+var (
+ // DefaultCreatedAt holds the default value on creation for the "created_at" field.
+ DefaultCreatedAt func() time.Time
+)
+
+// OrderOption defines the ordering options for the UserLoginHistory queries.
+type OrderOption func(*sql.Selector)
+
+// ByID orders the results by the id field.
+func ByID(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldID, opts...).ToFunc()
+}
+
+// ByUserID orders the results by the user_id field.
+func ByUserID(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldUserID, opts...).ToFunc()
+}
+
+// ByIP orders the results by the ip field.
+func ByIP(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldIP, opts...).ToFunc()
+}
+
+// ByCountry orders the results by the country field.
+func ByCountry(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldCountry, opts...).ToFunc()
+}
+
+// ByProvince orders the results by the province field.
+func ByProvince(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldProvince, opts...).ToFunc()
+}
+
+// ByCity orders the results by the city field.
+func ByCity(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldCity, opts...).ToFunc()
+}
+
+// ByIsp orders the results by the isp field.
+func ByIsp(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldIsp, opts...).ToFunc()
+}
+
+// ByAsn orders the results by the asn field.
+func ByAsn(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldAsn, opts...).ToFunc()
+}
+
+// ByClientVersion orders the results by the client_version field.
+func ByClientVersion(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldClientVersion, opts...).ToFunc()
+}
+
+// ByDevice orders the results by the device field.
+func ByDevice(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldDevice, opts...).ToFunc()
+}
+
+// ByCreatedAt orders the results by the created_at field.
+func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
+}
+
+// ByOwnerField orders the results by owner field.
+func ByOwnerField(field string, opts ...sql.OrderTermOption) OrderOption {
+ return func(s *sql.Selector) {
+ sqlgraph.OrderByNeighborTerms(s, newOwnerStep(), sql.OrderByField(field, opts...))
+ }
+}
+func newOwnerStep() *sqlgraph.Step {
+ return sqlgraph.NewStep(
+ sqlgraph.From(Table, FieldID),
+ sqlgraph.To(OwnerInverseTable, FieldID),
+ sqlgraph.Edge(sqlgraph.M2O, true, OwnerTable, OwnerColumn),
+ )
+}
diff --git a/backend/db/userloginhistory/where.go b/backend/db/userloginhistory/where.go
new file mode 100644
index 0000000..e603d6e
--- /dev/null
+++ b/backend/db/userloginhistory/where.go
@@ -0,0 +1,745 @@
+// Code generated by ent, DO NOT EDIT.
+
+package userloginhistory
+
+import (
+ "time"
+
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+ "github.com/google/uuid"
+)
+
+// ID filters vertices based on their ID field.
+func ID(id uuid.UUID) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldEQ(FieldID, id))
+}
+
+// IDEQ applies the EQ predicate on the ID field.
+func IDEQ(id uuid.UUID) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldEQ(FieldID, id))
+}
+
+// IDNEQ applies the NEQ predicate on the ID field.
+func IDNEQ(id uuid.UUID) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldNEQ(FieldID, id))
+}
+
+// IDIn applies the In predicate on the ID field.
+func IDIn(ids ...uuid.UUID) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldIn(FieldID, ids...))
+}
+
+// IDNotIn applies the NotIn predicate on the ID field.
+func IDNotIn(ids ...uuid.UUID) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldNotIn(FieldID, ids...))
+}
+
+// IDGT applies the GT predicate on the ID field.
+func IDGT(id uuid.UUID) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldGT(FieldID, id))
+}
+
+// IDGTE applies the GTE predicate on the ID field.
+func IDGTE(id uuid.UUID) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldGTE(FieldID, id))
+}
+
+// IDLT applies the LT predicate on the ID field.
+func IDLT(id uuid.UUID) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldLT(FieldID, id))
+}
+
+// IDLTE applies the LTE predicate on the ID field.
+func IDLTE(id uuid.UUID) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldLTE(FieldID, id))
+}
+
+// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ.
+func UserID(v uuid.UUID) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldEQ(FieldUserID, v))
+}
+
+// IP applies equality check predicate on the "ip" field. It's identical to IPEQ.
+func IP(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldEQ(FieldIP, v))
+}
+
+// Country applies equality check predicate on the "country" field. It's identical to CountryEQ.
+func Country(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldEQ(FieldCountry, v))
+}
+
+// Province applies equality check predicate on the "province" field. It's identical to ProvinceEQ.
+func Province(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldEQ(FieldProvince, v))
+}
+
+// City applies equality check predicate on the "city" field. It's identical to CityEQ.
+func City(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldEQ(FieldCity, v))
+}
+
+// Isp applies equality check predicate on the "isp" field. It's identical to IspEQ.
+func Isp(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldEQ(FieldIsp, v))
+}
+
+// Asn applies equality check predicate on the "asn" field. It's identical to AsnEQ.
+func Asn(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldEQ(FieldAsn, v))
+}
+
+// ClientVersion applies equality check predicate on the "client_version" field. It's identical to ClientVersionEQ.
+func ClientVersion(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldEQ(FieldClientVersion, v))
+}
+
+// Device applies equality check predicate on the "device" field. It's identical to DeviceEQ.
+func Device(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldEQ(FieldDevice, v))
+}
+
+// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
+func CreatedAt(v time.Time) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldEQ(FieldCreatedAt, v))
+}
+
+// UserIDEQ applies the EQ predicate on the "user_id" field.
+func UserIDEQ(v uuid.UUID) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldEQ(FieldUserID, v))
+}
+
+// UserIDNEQ applies the NEQ predicate on the "user_id" field.
+func UserIDNEQ(v uuid.UUID) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldNEQ(FieldUserID, v))
+}
+
+// UserIDIn applies the In predicate on the "user_id" field.
+func UserIDIn(vs ...uuid.UUID) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldIn(FieldUserID, vs...))
+}
+
+// UserIDNotIn applies the NotIn predicate on the "user_id" field.
+func UserIDNotIn(vs ...uuid.UUID) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldNotIn(FieldUserID, vs...))
+}
+
+// UserIDGT applies the GT predicate on the "user_id" field.
+func UserIDGT(v uuid.UUID) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldGT(FieldUserID, v))
+}
+
+// UserIDGTE applies the GTE predicate on the "user_id" field.
+func UserIDGTE(v uuid.UUID) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldGTE(FieldUserID, v))
+}
+
+// UserIDLT applies the LT predicate on the "user_id" field.
+func UserIDLT(v uuid.UUID) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldLT(FieldUserID, v))
+}
+
+// UserIDLTE applies the LTE predicate on the "user_id" field.
+func UserIDLTE(v uuid.UUID) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldLTE(FieldUserID, v))
+}
+
+// IPEQ applies the EQ predicate on the "ip" field.
+func IPEQ(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldEQ(FieldIP, v))
+}
+
+// IPNEQ applies the NEQ predicate on the "ip" field.
+func IPNEQ(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldNEQ(FieldIP, v))
+}
+
+// IPIn applies the In predicate on the "ip" field.
+func IPIn(vs ...string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldIn(FieldIP, vs...))
+}
+
+// IPNotIn applies the NotIn predicate on the "ip" field.
+func IPNotIn(vs ...string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldNotIn(FieldIP, vs...))
+}
+
+// IPGT applies the GT predicate on the "ip" field.
+func IPGT(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldGT(FieldIP, v))
+}
+
+// IPGTE applies the GTE predicate on the "ip" field.
+func IPGTE(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldGTE(FieldIP, v))
+}
+
+// IPLT applies the LT predicate on the "ip" field.
+func IPLT(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldLT(FieldIP, v))
+}
+
+// IPLTE applies the LTE predicate on the "ip" field.
+func IPLTE(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldLTE(FieldIP, v))
+}
+
+// IPContains applies the Contains predicate on the "ip" field.
+func IPContains(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldContains(FieldIP, v))
+}
+
+// IPHasPrefix applies the HasPrefix predicate on the "ip" field.
+func IPHasPrefix(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldHasPrefix(FieldIP, v))
+}
+
+// IPHasSuffix applies the HasSuffix predicate on the "ip" field.
+func IPHasSuffix(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldHasSuffix(FieldIP, v))
+}
+
+// IPEqualFold applies the EqualFold predicate on the "ip" field.
+func IPEqualFold(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldEqualFold(FieldIP, v))
+}
+
+// IPContainsFold applies the ContainsFold predicate on the "ip" field.
+func IPContainsFold(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldContainsFold(FieldIP, v))
+}
+
+// CountryEQ applies the EQ predicate on the "country" field.
+func CountryEQ(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldEQ(FieldCountry, v))
+}
+
+// CountryNEQ applies the NEQ predicate on the "country" field.
+func CountryNEQ(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldNEQ(FieldCountry, v))
+}
+
+// CountryIn applies the In predicate on the "country" field.
+func CountryIn(vs ...string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldIn(FieldCountry, vs...))
+}
+
+// CountryNotIn applies the NotIn predicate on the "country" field.
+func CountryNotIn(vs ...string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldNotIn(FieldCountry, vs...))
+}
+
+// CountryGT applies the GT predicate on the "country" field.
+func CountryGT(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldGT(FieldCountry, v))
+}
+
+// CountryGTE applies the GTE predicate on the "country" field.
+func CountryGTE(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldGTE(FieldCountry, v))
+}
+
+// CountryLT applies the LT predicate on the "country" field.
+func CountryLT(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldLT(FieldCountry, v))
+}
+
+// CountryLTE applies the LTE predicate on the "country" field.
+func CountryLTE(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldLTE(FieldCountry, v))
+}
+
+// CountryContains applies the Contains predicate on the "country" field.
+func CountryContains(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldContains(FieldCountry, v))
+}
+
+// CountryHasPrefix applies the HasPrefix predicate on the "country" field.
+func CountryHasPrefix(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldHasPrefix(FieldCountry, v))
+}
+
+// CountryHasSuffix applies the HasSuffix predicate on the "country" field.
+func CountryHasSuffix(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldHasSuffix(FieldCountry, v))
+}
+
+// CountryEqualFold applies the EqualFold predicate on the "country" field.
+func CountryEqualFold(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldEqualFold(FieldCountry, v))
+}
+
+// CountryContainsFold applies the ContainsFold predicate on the "country" field.
+func CountryContainsFold(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldContainsFold(FieldCountry, v))
+}
+
+// ProvinceEQ applies the EQ predicate on the "province" field.
+func ProvinceEQ(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldEQ(FieldProvince, v))
+}
+
+// ProvinceNEQ applies the NEQ predicate on the "province" field.
+func ProvinceNEQ(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldNEQ(FieldProvince, v))
+}
+
+// ProvinceIn applies the In predicate on the "province" field.
+func ProvinceIn(vs ...string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldIn(FieldProvince, vs...))
+}
+
+// ProvinceNotIn applies the NotIn predicate on the "province" field.
+func ProvinceNotIn(vs ...string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldNotIn(FieldProvince, vs...))
+}
+
+// ProvinceGT applies the GT predicate on the "province" field.
+func ProvinceGT(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldGT(FieldProvince, v))
+}
+
+// ProvinceGTE applies the GTE predicate on the "province" field.
+func ProvinceGTE(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldGTE(FieldProvince, v))
+}
+
+// ProvinceLT applies the LT predicate on the "province" field.
+func ProvinceLT(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldLT(FieldProvince, v))
+}
+
+// ProvinceLTE applies the LTE predicate on the "province" field.
+func ProvinceLTE(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldLTE(FieldProvince, v))
+}
+
+// ProvinceContains applies the Contains predicate on the "province" field.
+func ProvinceContains(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldContains(FieldProvince, v))
+}
+
+// ProvinceHasPrefix applies the HasPrefix predicate on the "province" field.
+func ProvinceHasPrefix(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldHasPrefix(FieldProvince, v))
+}
+
+// ProvinceHasSuffix applies the HasSuffix predicate on the "province" field.
+func ProvinceHasSuffix(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldHasSuffix(FieldProvince, v))
+}
+
+// ProvinceEqualFold applies the EqualFold predicate on the "province" field.
+func ProvinceEqualFold(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldEqualFold(FieldProvince, v))
+}
+
+// ProvinceContainsFold applies the ContainsFold predicate on the "province" field.
+func ProvinceContainsFold(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldContainsFold(FieldProvince, v))
+}
+
+// CityEQ applies the EQ predicate on the "city" field.
+func CityEQ(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldEQ(FieldCity, v))
+}
+
+// CityNEQ applies the NEQ predicate on the "city" field.
+func CityNEQ(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldNEQ(FieldCity, v))
+}
+
+// CityIn applies the In predicate on the "city" field.
+func CityIn(vs ...string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldIn(FieldCity, vs...))
+}
+
+// CityNotIn applies the NotIn predicate on the "city" field.
+func CityNotIn(vs ...string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldNotIn(FieldCity, vs...))
+}
+
+// CityGT applies the GT predicate on the "city" field.
+func CityGT(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldGT(FieldCity, v))
+}
+
+// CityGTE applies the GTE predicate on the "city" field.
+func CityGTE(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldGTE(FieldCity, v))
+}
+
+// CityLT applies the LT predicate on the "city" field.
+func CityLT(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldLT(FieldCity, v))
+}
+
+// CityLTE applies the LTE predicate on the "city" field.
+func CityLTE(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldLTE(FieldCity, v))
+}
+
+// CityContains applies the Contains predicate on the "city" field.
+func CityContains(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldContains(FieldCity, v))
+}
+
+// CityHasPrefix applies the HasPrefix predicate on the "city" field.
+func CityHasPrefix(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldHasPrefix(FieldCity, v))
+}
+
+// CityHasSuffix applies the HasSuffix predicate on the "city" field.
+func CityHasSuffix(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldHasSuffix(FieldCity, v))
+}
+
+// CityEqualFold applies the EqualFold predicate on the "city" field.
+func CityEqualFold(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldEqualFold(FieldCity, v))
+}
+
+// CityContainsFold applies the ContainsFold predicate on the "city" field.
+func CityContainsFold(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldContainsFold(FieldCity, v))
+}
+
+// IspEQ applies the EQ predicate on the "isp" field.
+func IspEQ(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldEQ(FieldIsp, v))
+}
+
+// IspNEQ applies the NEQ predicate on the "isp" field.
+func IspNEQ(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldNEQ(FieldIsp, v))
+}
+
+// IspIn applies the In predicate on the "isp" field.
+func IspIn(vs ...string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldIn(FieldIsp, vs...))
+}
+
+// IspNotIn applies the NotIn predicate on the "isp" field.
+func IspNotIn(vs ...string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldNotIn(FieldIsp, vs...))
+}
+
+// IspGT applies the GT predicate on the "isp" field.
+func IspGT(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldGT(FieldIsp, v))
+}
+
+// IspGTE applies the GTE predicate on the "isp" field.
+func IspGTE(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldGTE(FieldIsp, v))
+}
+
+// IspLT applies the LT predicate on the "isp" field.
+func IspLT(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldLT(FieldIsp, v))
+}
+
+// IspLTE applies the LTE predicate on the "isp" field.
+func IspLTE(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldLTE(FieldIsp, v))
+}
+
+// IspContains applies the Contains predicate on the "isp" field.
+func IspContains(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldContains(FieldIsp, v))
+}
+
+// IspHasPrefix applies the HasPrefix predicate on the "isp" field.
+func IspHasPrefix(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldHasPrefix(FieldIsp, v))
+}
+
+// IspHasSuffix applies the HasSuffix predicate on the "isp" field.
+func IspHasSuffix(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldHasSuffix(FieldIsp, v))
+}
+
+// IspEqualFold applies the EqualFold predicate on the "isp" field.
+func IspEqualFold(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldEqualFold(FieldIsp, v))
+}
+
+// IspContainsFold applies the ContainsFold predicate on the "isp" field.
+func IspContainsFold(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldContainsFold(FieldIsp, v))
+}
+
+// AsnEQ applies the EQ predicate on the "asn" field.
+func AsnEQ(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldEQ(FieldAsn, v))
+}
+
+// AsnNEQ applies the NEQ predicate on the "asn" field.
+func AsnNEQ(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldNEQ(FieldAsn, v))
+}
+
+// AsnIn applies the In predicate on the "asn" field.
+func AsnIn(vs ...string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldIn(FieldAsn, vs...))
+}
+
+// AsnNotIn applies the NotIn predicate on the "asn" field.
+func AsnNotIn(vs ...string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldNotIn(FieldAsn, vs...))
+}
+
+// AsnGT applies the GT predicate on the "asn" field.
+func AsnGT(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldGT(FieldAsn, v))
+}
+
+// AsnGTE applies the GTE predicate on the "asn" field.
+func AsnGTE(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldGTE(FieldAsn, v))
+}
+
+// AsnLT applies the LT predicate on the "asn" field.
+func AsnLT(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldLT(FieldAsn, v))
+}
+
+// AsnLTE applies the LTE predicate on the "asn" field.
+func AsnLTE(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldLTE(FieldAsn, v))
+}
+
+// AsnContains applies the Contains predicate on the "asn" field.
+func AsnContains(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldContains(FieldAsn, v))
+}
+
+// AsnHasPrefix applies the HasPrefix predicate on the "asn" field.
+func AsnHasPrefix(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldHasPrefix(FieldAsn, v))
+}
+
+// AsnHasSuffix applies the HasSuffix predicate on the "asn" field.
+func AsnHasSuffix(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldHasSuffix(FieldAsn, v))
+}
+
+// AsnEqualFold applies the EqualFold predicate on the "asn" field.
+func AsnEqualFold(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldEqualFold(FieldAsn, v))
+}
+
+// AsnContainsFold applies the ContainsFold predicate on the "asn" field.
+func AsnContainsFold(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldContainsFold(FieldAsn, v))
+}
+
+// ClientVersionEQ applies the EQ predicate on the "client_version" field.
+func ClientVersionEQ(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldEQ(FieldClientVersion, v))
+}
+
+// ClientVersionNEQ applies the NEQ predicate on the "client_version" field.
+func ClientVersionNEQ(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldNEQ(FieldClientVersion, v))
+}
+
+// ClientVersionIn applies the In predicate on the "client_version" field.
+func ClientVersionIn(vs ...string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldIn(FieldClientVersion, vs...))
+}
+
+// ClientVersionNotIn applies the NotIn predicate on the "client_version" field.
+func ClientVersionNotIn(vs ...string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldNotIn(FieldClientVersion, vs...))
+}
+
+// ClientVersionGT applies the GT predicate on the "client_version" field.
+func ClientVersionGT(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldGT(FieldClientVersion, v))
+}
+
+// ClientVersionGTE applies the GTE predicate on the "client_version" field.
+func ClientVersionGTE(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldGTE(FieldClientVersion, v))
+}
+
+// ClientVersionLT applies the LT predicate on the "client_version" field.
+func ClientVersionLT(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldLT(FieldClientVersion, v))
+}
+
+// ClientVersionLTE applies the LTE predicate on the "client_version" field.
+func ClientVersionLTE(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldLTE(FieldClientVersion, v))
+}
+
+// ClientVersionContains applies the Contains predicate on the "client_version" field.
+func ClientVersionContains(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldContains(FieldClientVersion, v))
+}
+
+// ClientVersionHasPrefix applies the HasPrefix predicate on the "client_version" field.
+func ClientVersionHasPrefix(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldHasPrefix(FieldClientVersion, v))
+}
+
+// ClientVersionHasSuffix applies the HasSuffix predicate on the "client_version" field.
+func ClientVersionHasSuffix(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldHasSuffix(FieldClientVersion, v))
+}
+
+// ClientVersionEqualFold applies the EqualFold predicate on the "client_version" field.
+func ClientVersionEqualFold(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldEqualFold(FieldClientVersion, v))
+}
+
+// ClientVersionContainsFold applies the ContainsFold predicate on the "client_version" field.
+func ClientVersionContainsFold(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldContainsFold(FieldClientVersion, v))
+}
+
+// DeviceEQ applies the EQ predicate on the "device" field.
+func DeviceEQ(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldEQ(FieldDevice, v))
+}
+
+// DeviceNEQ applies the NEQ predicate on the "device" field.
+func DeviceNEQ(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldNEQ(FieldDevice, v))
+}
+
+// DeviceIn applies the In predicate on the "device" field.
+func DeviceIn(vs ...string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldIn(FieldDevice, vs...))
+}
+
+// DeviceNotIn applies the NotIn predicate on the "device" field.
+func DeviceNotIn(vs ...string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldNotIn(FieldDevice, vs...))
+}
+
+// DeviceGT applies the GT predicate on the "device" field.
+func DeviceGT(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldGT(FieldDevice, v))
+}
+
+// DeviceGTE applies the GTE predicate on the "device" field.
+func DeviceGTE(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldGTE(FieldDevice, v))
+}
+
+// DeviceLT applies the LT predicate on the "device" field.
+func DeviceLT(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldLT(FieldDevice, v))
+}
+
+// DeviceLTE applies the LTE predicate on the "device" field.
+func DeviceLTE(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldLTE(FieldDevice, v))
+}
+
+// DeviceContains applies the Contains predicate on the "device" field.
+func DeviceContains(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldContains(FieldDevice, v))
+}
+
+// DeviceHasPrefix applies the HasPrefix predicate on the "device" field.
+func DeviceHasPrefix(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldHasPrefix(FieldDevice, v))
+}
+
+// DeviceHasSuffix applies the HasSuffix predicate on the "device" field.
+func DeviceHasSuffix(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldHasSuffix(FieldDevice, v))
+}
+
+// DeviceEqualFold applies the EqualFold predicate on the "device" field.
+func DeviceEqualFold(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldEqualFold(FieldDevice, v))
+}
+
+// DeviceContainsFold applies the ContainsFold predicate on the "device" field.
+func DeviceContainsFold(v string) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldContainsFold(FieldDevice, v))
+}
+
+// CreatedAtEQ applies the EQ predicate on the "created_at" field.
+func CreatedAtEQ(v time.Time) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldEQ(FieldCreatedAt, v))
+}
+
+// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
+func CreatedAtNEQ(v time.Time) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldNEQ(FieldCreatedAt, v))
+}
+
+// CreatedAtIn applies the In predicate on the "created_at" field.
+func CreatedAtIn(vs ...time.Time) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldIn(FieldCreatedAt, vs...))
+}
+
+// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
+func CreatedAtNotIn(vs ...time.Time) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldNotIn(FieldCreatedAt, vs...))
+}
+
+// CreatedAtGT applies the GT predicate on the "created_at" field.
+func CreatedAtGT(v time.Time) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldGT(FieldCreatedAt, v))
+}
+
+// CreatedAtGTE applies the GTE predicate on the "created_at" field.
+func CreatedAtGTE(v time.Time) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldGTE(FieldCreatedAt, v))
+}
+
+// CreatedAtLT applies the LT predicate on the "created_at" field.
+func CreatedAtLT(v time.Time) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldLT(FieldCreatedAt, v))
+}
+
+// CreatedAtLTE applies the LTE predicate on the "created_at" field.
+func CreatedAtLTE(v time.Time) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.FieldLTE(FieldCreatedAt, v))
+}
+
+// HasOwner applies the HasEdge predicate on the "owner" edge.
+func HasOwner() predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(func(s *sql.Selector) {
+ step := sqlgraph.NewStep(
+ sqlgraph.From(Table, FieldID),
+ sqlgraph.Edge(sqlgraph.M2O, true, OwnerTable, OwnerColumn),
+ )
+ sqlgraph.HasNeighbors(s, step)
+ })
+}
+
+// HasOwnerWith applies the HasEdge predicate on the "owner" edge with a given conditions (other predicates).
+func HasOwnerWith(preds ...predicate.User) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(func(s *sql.Selector) {
+ step := newOwnerStep()
+ sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
+ for _, p := range preds {
+ p(s)
+ }
+ })
+ })
+}
+
+// And groups predicates with the AND operator between them.
+func And(predicates ...predicate.UserLoginHistory) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.AndPredicates(predicates...))
+}
+
+// Or groups predicates with the OR operator between them.
+func Or(predicates ...predicate.UserLoginHistory) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.OrPredicates(predicates...))
+}
+
+// Not applies the not operator on the given predicate.
+func Not(p predicate.UserLoginHistory) predicate.UserLoginHistory {
+ return predicate.UserLoginHistory(sql.NotPredicates(p))
+}
diff --git a/backend/db/userloginhistory_create.go b/backend/db/userloginhistory_create.go
new file mode 100644
index 0000000..94b0022
--- /dev/null
+++ b/backend/db/userloginhistory_create.go
@@ -0,0 +1,1023 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "time"
+
+ "entgo.io/ent/dialect"
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/user"
+ "github.com/chaitin/MonkeyCode/backend/db/userloginhistory"
+ "github.com/google/uuid"
+)
+
+// UserLoginHistoryCreate is the builder for creating a UserLoginHistory entity.
+type UserLoginHistoryCreate struct {
+ config
+ mutation *UserLoginHistoryMutation
+ hooks []Hook
+ conflict []sql.ConflictOption
+}
+
+// SetUserID sets the "user_id" field.
+func (ulhc *UserLoginHistoryCreate) SetUserID(u uuid.UUID) *UserLoginHistoryCreate {
+ ulhc.mutation.SetUserID(u)
+ return ulhc
+}
+
+// SetIP sets the "ip" field.
+func (ulhc *UserLoginHistoryCreate) SetIP(s string) *UserLoginHistoryCreate {
+ ulhc.mutation.SetIP(s)
+ return ulhc
+}
+
+// SetCountry sets the "country" field.
+func (ulhc *UserLoginHistoryCreate) SetCountry(s string) *UserLoginHistoryCreate {
+ ulhc.mutation.SetCountry(s)
+ return ulhc
+}
+
+// SetProvince sets the "province" field.
+func (ulhc *UserLoginHistoryCreate) SetProvince(s string) *UserLoginHistoryCreate {
+ ulhc.mutation.SetProvince(s)
+ return ulhc
+}
+
+// SetCity sets the "city" field.
+func (ulhc *UserLoginHistoryCreate) SetCity(s string) *UserLoginHistoryCreate {
+ ulhc.mutation.SetCity(s)
+ return ulhc
+}
+
+// SetIsp sets the "isp" field.
+func (ulhc *UserLoginHistoryCreate) SetIsp(s string) *UserLoginHistoryCreate {
+ ulhc.mutation.SetIsp(s)
+ return ulhc
+}
+
+// SetAsn sets the "asn" field.
+func (ulhc *UserLoginHistoryCreate) SetAsn(s string) *UserLoginHistoryCreate {
+ ulhc.mutation.SetAsn(s)
+ return ulhc
+}
+
+// SetClientVersion sets the "client_version" field.
+func (ulhc *UserLoginHistoryCreate) SetClientVersion(s string) *UserLoginHistoryCreate {
+ ulhc.mutation.SetClientVersion(s)
+ return ulhc
+}
+
+// SetDevice sets the "device" field.
+func (ulhc *UserLoginHistoryCreate) SetDevice(s string) *UserLoginHistoryCreate {
+ ulhc.mutation.SetDevice(s)
+ return ulhc
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (ulhc *UserLoginHistoryCreate) SetCreatedAt(t time.Time) *UserLoginHistoryCreate {
+ ulhc.mutation.SetCreatedAt(t)
+ return ulhc
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (ulhc *UserLoginHistoryCreate) SetNillableCreatedAt(t *time.Time) *UserLoginHistoryCreate {
+ if t != nil {
+ ulhc.SetCreatedAt(*t)
+ }
+ return ulhc
+}
+
+// SetID sets the "id" field.
+func (ulhc *UserLoginHistoryCreate) SetID(u uuid.UUID) *UserLoginHistoryCreate {
+ ulhc.mutation.SetID(u)
+ return ulhc
+}
+
+// SetOwnerID sets the "owner" edge to the User entity by ID.
+func (ulhc *UserLoginHistoryCreate) SetOwnerID(id uuid.UUID) *UserLoginHistoryCreate {
+ ulhc.mutation.SetOwnerID(id)
+ return ulhc
+}
+
+// SetNillableOwnerID sets the "owner" edge to the User entity by ID if the given value is not nil.
+func (ulhc *UserLoginHistoryCreate) SetNillableOwnerID(id *uuid.UUID) *UserLoginHistoryCreate {
+ if id != nil {
+ ulhc = ulhc.SetOwnerID(*id)
+ }
+ return ulhc
+}
+
+// SetOwner sets the "owner" edge to the User entity.
+func (ulhc *UserLoginHistoryCreate) SetOwner(u *User) *UserLoginHistoryCreate {
+ return ulhc.SetOwnerID(u.ID)
+}
+
+// Mutation returns the UserLoginHistoryMutation object of the builder.
+func (ulhc *UserLoginHistoryCreate) Mutation() *UserLoginHistoryMutation {
+ return ulhc.mutation
+}
+
+// Save creates the UserLoginHistory in the database.
+func (ulhc *UserLoginHistoryCreate) Save(ctx context.Context) (*UserLoginHistory, error) {
+ ulhc.defaults()
+ return withHooks(ctx, ulhc.sqlSave, ulhc.mutation, ulhc.hooks)
+}
+
+// SaveX calls Save and panics if Save returns an error.
+func (ulhc *UserLoginHistoryCreate) SaveX(ctx context.Context) *UserLoginHistory {
+ v, err := ulhc.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return v
+}
+
+// Exec executes the query.
+func (ulhc *UserLoginHistoryCreate) Exec(ctx context.Context) error {
+ _, err := ulhc.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (ulhc *UserLoginHistoryCreate) ExecX(ctx context.Context) {
+ if err := ulhc.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// defaults sets the default values of the builder before save.
+func (ulhc *UserLoginHistoryCreate) defaults() {
+ if _, ok := ulhc.mutation.CreatedAt(); !ok {
+ v := userloginhistory.DefaultCreatedAt()
+ ulhc.mutation.SetCreatedAt(v)
+ }
+}
+
+// check runs all checks and user-defined validators on the builder.
+func (ulhc *UserLoginHistoryCreate) check() error {
+ if _, ok := ulhc.mutation.UserID(); !ok {
+ return &ValidationError{Name: "user_id", err: errors.New(`db: missing required field "UserLoginHistory.user_id"`)}
+ }
+ if _, ok := ulhc.mutation.IP(); !ok {
+ return &ValidationError{Name: "ip", err: errors.New(`db: missing required field "UserLoginHistory.ip"`)}
+ }
+ if _, ok := ulhc.mutation.Country(); !ok {
+ return &ValidationError{Name: "country", err: errors.New(`db: missing required field "UserLoginHistory.country"`)}
+ }
+ if _, ok := ulhc.mutation.Province(); !ok {
+ return &ValidationError{Name: "province", err: errors.New(`db: missing required field "UserLoginHistory.province"`)}
+ }
+ if _, ok := ulhc.mutation.City(); !ok {
+ return &ValidationError{Name: "city", err: errors.New(`db: missing required field "UserLoginHistory.city"`)}
+ }
+ if _, ok := ulhc.mutation.Isp(); !ok {
+ return &ValidationError{Name: "isp", err: errors.New(`db: missing required field "UserLoginHistory.isp"`)}
+ }
+ if _, ok := ulhc.mutation.Asn(); !ok {
+ return &ValidationError{Name: "asn", err: errors.New(`db: missing required field "UserLoginHistory.asn"`)}
+ }
+ if _, ok := ulhc.mutation.ClientVersion(); !ok {
+ return &ValidationError{Name: "client_version", err: errors.New(`db: missing required field "UserLoginHistory.client_version"`)}
+ }
+ if _, ok := ulhc.mutation.Device(); !ok {
+ return &ValidationError{Name: "device", err: errors.New(`db: missing required field "UserLoginHistory.device"`)}
+ }
+ if _, ok := ulhc.mutation.CreatedAt(); !ok {
+ return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "UserLoginHistory.created_at"`)}
+ }
+ return nil
+}
+
+func (ulhc *UserLoginHistoryCreate) sqlSave(ctx context.Context) (*UserLoginHistory, error) {
+ if err := ulhc.check(); err != nil {
+ return nil, err
+ }
+ _node, _spec := ulhc.createSpec()
+ if err := sqlgraph.CreateNode(ctx, ulhc.driver, _spec); err != nil {
+ if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return nil, err
+ }
+ if _spec.ID.Value != nil {
+ if id, ok := _spec.ID.Value.(*uuid.UUID); ok {
+ _node.ID = *id
+ } else if err := _node.ID.Scan(_spec.ID.Value); err != nil {
+ return nil, err
+ }
+ }
+ ulhc.mutation.id = &_node.ID
+ ulhc.mutation.done = true
+ return _node, nil
+}
+
+func (ulhc *UserLoginHistoryCreate) createSpec() (*UserLoginHistory, *sqlgraph.CreateSpec) {
+ var (
+ _node = &UserLoginHistory{config: ulhc.config}
+ _spec = sqlgraph.NewCreateSpec(userloginhistory.Table, sqlgraph.NewFieldSpec(userloginhistory.FieldID, field.TypeUUID))
+ )
+ _spec.OnConflict = ulhc.conflict
+ if id, ok := ulhc.mutation.ID(); ok {
+ _node.ID = id
+ _spec.ID.Value = &id
+ }
+ if value, ok := ulhc.mutation.UserID(); ok {
+ _spec.SetField(userloginhistory.FieldUserID, field.TypeUUID, value)
+ _node.UserID = value
+ }
+ if value, ok := ulhc.mutation.IP(); ok {
+ _spec.SetField(userloginhistory.FieldIP, field.TypeString, value)
+ _node.IP = value
+ }
+ if value, ok := ulhc.mutation.Country(); ok {
+ _spec.SetField(userloginhistory.FieldCountry, field.TypeString, value)
+ _node.Country = value
+ }
+ if value, ok := ulhc.mutation.Province(); ok {
+ _spec.SetField(userloginhistory.FieldProvince, field.TypeString, value)
+ _node.Province = value
+ }
+ if value, ok := ulhc.mutation.City(); ok {
+ _spec.SetField(userloginhistory.FieldCity, field.TypeString, value)
+ _node.City = value
+ }
+ if value, ok := ulhc.mutation.Isp(); ok {
+ _spec.SetField(userloginhistory.FieldIsp, field.TypeString, value)
+ _node.Isp = value
+ }
+ if value, ok := ulhc.mutation.Asn(); ok {
+ _spec.SetField(userloginhistory.FieldAsn, field.TypeString, value)
+ _node.Asn = value
+ }
+ if value, ok := ulhc.mutation.ClientVersion(); ok {
+ _spec.SetField(userloginhistory.FieldClientVersion, field.TypeString, value)
+ _node.ClientVersion = value
+ }
+ if value, ok := ulhc.mutation.Device(); ok {
+ _spec.SetField(userloginhistory.FieldDevice, field.TypeString, value)
+ _node.Device = value
+ }
+ if value, ok := ulhc.mutation.CreatedAt(); ok {
+ _spec.SetField(userloginhistory.FieldCreatedAt, field.TypeTime, value)
+ _node.CreatedAt = value
+ }
+ if nodes := ulhc.mutation.OwnerIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: true,
+ Table: userloginhistory.OwnerTable,
+ Columns: []string{userloginhistory.OwnerColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _node.user_login_histories = &nodes[0]
+ _spec.Edges = append(_spec.Edges, edge)
+ }
+ return _node, _spec
+}
+
+// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
+// of the `INSERT` statement. For example:
+//
+// client.UserLoginHistory.Create().
+// SetUserID(v).
+// OnConflict(
+// // Update the row with the new values
+// // the was proposed for insertion.
+// sql.ResolveWithNewValues(),
+// ).
+// // Override some of the fields with custom
+// // update values.
+// Update(func(u *ent.UserLoginHistoryUpsert) {
+// SetUserID(v+v).
+// }).
+// Exec(ctx)
+func (ulhc *UserLoginHistoryCreate) OnConflict(opts ...sql.ConflictOption) *UserLoginHistoryUpsertOne {
+ ulhc.conflict = opts
+ return &UserLoginHistoryUpsertOne{
+ create: ulhc,
+ }
+}
+
+// OnConflictColumns calls `OnConflict` and configures the columns
+// as conflict target. Using this option is equivalent to using:
+//
+// client.UserLoginHistory.Create().
+// OnConflict(sql.ConflictColumns(columns...)).
+// Exec(ctx)
+func (ulhc *UserLoginHistoryCreate) OnConflictColumns(columns ...string) *UserLoginHistoryUpsertOne {
+ ulhc.conflict = append(ulhc.conflict, sql.ConflictColumns(columns...))
+ return &UserLoginHistoryUpsertOne{
+ create: ulhc,
+ }
+}
+
+type (
+ // UserLoginHistoryUpsertOne is the builder for "upsert"-ing
+ // one UserLoginHistory node.
+ UserLoginHistoryUpsertOne struct {
+ create *UserLoginHistoryCreate
+ }
+
+ // UserLoginHistoryUpsert is the "OnConflict" setter.
+ UserLoginHistoryUpsert struct {
+ *sql.UpdateSet
+ }
+)
+
+// SetUserID sets the "user_id" field.
+func (u *UserLoginHistoryUpsert) SetUserID(v uuid.UUID) *UserLoginHistoryUpsert {
+ u.Set(userloginhistory.FieldUserID, v)
+ return u
+}
+
+// UpdateUserID sets the "user_id" field to the value that was provided on create.
+func (u *UserLoginHistoryUpsert) UpdateUserID() *UserLoginHistoryUpsert {
+ u.SetExcluded(userloginhistory.FieldUserID)
+ return u
+}
+
+// SetIP sets the "ip" field.
+func (u *UserLoginHistoryUpsert) SetIP(v string) *UserLoginHistoryUpsert {
+ u.Set(userloginhistory.FieldIP, v)
+ return u
+}
+
+// UpdateIP sets the "ip" field to the value that was provided on create.
+func (u *UserLoginHistoryUpsert) UpdateIP() *UserLoginHistoryUpsert {
+ u.SetExcluded(userloginhistory.FieldIP)
+ return u
+}
+
+// SetCountry sets the "country" field.
+func (u *UserLoginHistoryUpsert) SetCountry(v string) *UserLoginHistoryUpsert {
+ u.Set(userloginhistory.FieldCountry, v)
+ return u
+}
+
+// UpdateCountry sets the "country" field to the value that was provided on create.
+func (u *UserLoginHistoryUpsert) UpdateCountry() *UserLoginHistoryUpsert {
+ u.SetExcluded(userloginhistory.FieldCountry)
+ return u
+}
+
+// SetProvince sets the "province" field.
+func (u *UserLoginHistoryUpsert) SetProvince(v string) *UserLoginHistoryUpsert {
+ u.Set(userloginhistory.FieldProvince, v)
+ return u
+}
+
+// UpdateProvince sets the "province" field to the value that was provided on create.
+func (u *UserLoginHistoryUpsert) UpdateProvince() *UserLoginHistoryUpsert {
+ u.SetExcluded(userloginhistory.FieldProvince)
+ return u
+}
+
+// SetCity sets the "city" field.
+func (u *UserLoginHistoryUpsert) SetCity(v string) *UserLoginHistoryUpsert {
+ u.Set(userloginhistory.FieldCity, v)
+ return u
+}
+
+// UpdateCity sets the "city" field to the value that was provided on create.
+func (u *UserLoginHistoryUpsert) UpdateCity() *UserLoginHistoryUpsert {
+ u.SetExcluded(userloginhistory.FieldCity)
+ return u
+}
+
+// SetIsp sets the "isp" field.
+func (u *UserLoginHistoryUpsert) SetIsp(v string) *UserLoginHistoryUpsert {
+ u.Set(userloginhistory.FieldIsp, v)
+ return u
+}
+
+// UpdateIsp sets the "isp" field to the value that was provided on create.
+func (u *UserLoginHistoryUpsert) UpdateIsp() *UserLoginHistoryUpsert {
+ u.SetExcluded(userloginhistory.FieldIsp)
+ return u
+}
+
+// SetAsn sets the "asn" field.
+func (u *UserLoginHistoryUpsert) SetAsn(v string) *UserLoginHistoryUpsert {
+ u.Set(userloginhistory.FieldAsn, v)
+ return u
+}
+
+// UpdateAsn sets the "asn" field to the value that was provided on create.
+func (u *UserLoginHistoryUpsert) UpdateAsn() *UserLoginHistoryUpsert {
+ u.SetExcluded(userloginhistory.FieldAsn)
+ return u
+}
+
+// SetClientVersion sets the "client_version" field.
+func (u *UserLoginHistoryUpsert) SetClientVersion(v string) *UserLoginHistoryUpsert {
+ u.Set(userloginhistory.FieldClientVersion, v)
+ return u
+}
+
+// UpdateClientVersion sets the "client_version" field to the value that was provided on create.
+func (u *UserLoginHistoryUpsert) UpdateClientVersion() *UserLoginHistoryUpsert {
+ u.SetExcluded(userloginhistory.FieldClientVersion)
+ return u
+}
+
+// SetDevice sets the "device" field.
+func (u *UserLoginHistoryUpsert) SetDevice(v string) *UserLoginHistoryUpsert {
+ u.Set(userloginhistory.FieldDevice, v)
+ return u
+}
+
+// UpdateDevice sets the "device" field to the value that was provided on create.
+func (u *UserLoginHistoryUpsert) UpdateDevice() *UserLoginHistoryUpsert {
+ u.SetExcluded(userloginhistory.FieldDevice)
+ return u
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (u *UserLoginHistoryUpsert) SetCreatedAt(v time.Time) *UserLoginHistoryUpsert {
+ u.Set(userloginhistory.FieldCreatedAt, v)
+ return u
+}
+
+// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
+func (u *UserLoginHistoryUpsert) UpdateCreatedAt() *UserLoginHistoryUpsert {
+ u.SetExcluded(userloginhistory.FieldCreatedAt)
+ return u
+}
+
+// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field.
+// Using this option is equivalent to using:
+//
+// client.UserLoginHistory.Create().
+// OnConflict(
+// sql.ResolveWithNewValues(),
+// sql.ResolveWith(func(u *sql.UpdateSet) {
+// u.SetIgnore(userloginhistory.FieldID)
+// }),
+// ).
+// Exec(ctx)
+func (u *UserLoginHistoryUpsertOne) UpdateNewValues() *UserLoginHistoryUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
+ if _, exists := u.create.mutation.ID(); exists {
+ s.SetIgnore(userloginhistory.FieldID)
+ }
+ }))
+ return u
+}
+
+// Ignore sets each column to itself in case of conflict.
+// Using this option is equivalent to using:
+//
+// client.UserLoginHistory.Create().
+// OnConflict(sql.ResolveWithIgnore()).
+// Exec(ctx)
+func (u *UserLoginHistoryUpsertOne) Ignore() *UserLoginHistoryUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
+ return u
+}
+
+// DoNothing configures the conflict_action to `DO NOTHING`.
+// Supported only by SQLite and PostgreSQL.
+func (u *UserLoginHistoryUpsertOne) DoNothing() *UserLoginHistoryUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.DoNothing())
+ return u
+}
+
+// Update allows overriding fields `UPDATE` values. See the UserLoginHistoryCreate.OnConflict
+// documentation for more info.
+func (u *UserLoginHistoryUpsertOne) Update(set func(*UserLoginHistoryUpsert)) *UserLoginHistoryUpsertOne {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
+ set(&UserLoginHistoryUpsert{UpdateSet: update})
+ }))
+ return u
+}
+
+// SetUserID sets the "user_id" field.
+func (u *UserLoginHistoryUpsertOne) SetUserID(v uuid.UUID) *UserLoginHistoryUpsertOne {
+ return u.Update(func(s *UserLoginHistoryUpsert) {
+ s.SetUserID(v)
+ })
+}
+
+// UpdateUserID sets the "user_id" field to the value that was provided on create.
+func (u *UserLoginHistoryUpsertOne) UpdateUserID() *UserLoginHistoryUpsertOne {
+ return u.Update(func(s *UserLoginHistoryUpsert) {
+ s.UpdateUserID()
+ })
+}
+
+// SetIP sets the "ip" field.
+func (u *UserLoginHistoryUpsertOne) SetIP(v string) *UserLoginHistoryUpsertOne {
+ return u.Update(func(s *UserLoginHistoryUpsert) {
+ s.SetIP(v)
+ })
+}
+
+// UpdateIP sets the "ip" field to the value that was provided on create.
+func (u *UserLoginHistoryUpsertOne) UpdateIP() *UserLoginHistoryUpsertOne {
+ return u.Update(func(s *UserLoginHistoryUpsert) {
+ s.UpdateIP()
+ })
+}
+
+// SetCountry sets the "country" field.
+func (u *UserLoginHistoryUpsertOne) SetCountry(v string) *UserLoginHistoryUpsertOne {
+ return u.Update(func(s *UserLoginHistoryUpsert) {
+ s.SetCountry(v)
+ })
+}
+
+// UpdateCountry sets the "country" field to the value that was provided on create.
+func (u *UserLoginHistoryUpsertOne) UpdateCountry() *UserLoginHistoryUpsertOne {
+ return u.Update(func(s *UserLoginHistoryUpsert) {
+ s.UpdateCountry()
+ })
+}
+
+// SetProvince sets the "province" field.
+func (u *UserLoginHistoryUpsertOne) SetProvince(v string) *UserLoginHistoryUpsertOne {
+ return u.Update(func(s *UserLoginHistoryUpsert) {
+ s.SetProvince(v)
+ })
+}
+
+// UpdateProvince sets the "province" field to the value that was provided on create.
+func (u *UserLoginHistoryUpsertOne) UpdateProvince() *UserLoginHistoryUpsertOne {
+ return u.Update(func(s *UserLoginHistoryUpsert) {
+ s.UpdateProvince()
+ })
+}
+
+// SetCity sets the "city" field.
+func (u *UserLoginHistoryUpsertOne) SetCity(v string) *UserLoginHistoryUpsertOne {
+ return u.Update(func(s *UserLoginHistoryUpsert) {
+ s.SetCity(v)
+ })
+}
+
+// UpdateCity sets the "city" field to the value that was provided on create.
+func (u *UserLoginHistoryUpsertOne) UpdateCity() *UserLoginHistoryUpsertOne {
+ return u.Update(func(s *UserLoginHistoryUpsert) {
+ s.UpdateCity()
+ })
+}
+
+// SetIsp sets the "isp" field.
+func (u *UserLoginHistoryUpsertOne) SetIsp(v string) *UserLoginHistoryUpsertOne {
+ return u.Update(func(s *UserLoginHistoryUpsert) {
+ s.SetIsp(v)
+ })
+}
+
+// UpdateIsp sets the "isp" field to the value that was provided on create.
+func (u *UserLoginHistoryUpsertOne) UpdateIsp() *UserLoginHistoryUpsertOne {
+ return u.Update(func(s *UserLoginHistoryUpsert) {
+ s.UpdateIsp()
+ })
+}
+
+// SetAsn sets the "asn" field.
+func (u *UserLoginHistoryUpsertOne) SetAsn(v string) *UserLoginHistoryUpsertOne {
+ return u.Update(func(s *UserLoginHistoryUpsert) {
+ s.SetAsn(v)
+ })
+}
+
+// UpdateAsn sets the "asn" field to the value that was provided on create.
+func (u *UserLoginHistoryUpsertOne) UpdateAsn() *UserLoginHistoryUpsertOne {
+ return u.Update(func(s *UserLoginHistoryUpsert) {
+ s.UpdateAsn()
+ })
+}
+
+// SetClientVersion sets the "client_version" field.
+func (u *UserLoginHistoryUpsertOne) SetClientVersion(v string) *UserLoginHistoryUpsertOne {
+ return u.Update(func(s *UserLoginHistoryUpsert) {
+ s.SetClientVersion(v)
+ })
+}
+
+// UpdateClientVersion sets the "client_version" field to the value that was provided on create.
+func (u *UserLoginHistoryUpsertOne) UpdateClientVersion() *UserLoginHistoryUpsertOne {
+ return u.Update(func(s *UserLoginHistoryUpsert) {
+ s.UpdateClientVersion()
+ })
+}
+
+// SetDevice sets the "device" field.
+func (u *UserLoginHistoryUpsertOne) SetDevice(v string) *UserLoginHistoryUpsertOne {
+ return u.Update(func(s *UserLoginHistoryUpsert) {
+ s.SetDevice(v)
+ })
+}
+
+// UpdateDevice sets the "device" field to the value that was provided on create.
+func (u *UserLoginHistoryUpsertOne) UpdateDevice() *UserLoginHistoryUpsertOne {
+ return u.Update(func(s *UserLoginHistoryUpsert) {
+ s.UpdateDevice()
+ })
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (u *UserLoginHistoryUpsertOne) SetCreatedAt(v time.Time) *UserLoginHistoryUpsertOne {
+ return u.Update(func(s *UserLoginHistoryUpsert) {
+ s.SetCreatedAt(v)
+ })
+}
+
+// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
+func (u *UserLoginHistoryUpsertOne) UpdateCreatedAt() *UserLoginHistoryUpsertOne {
+ return u.Update(func(s *UserLoginHistoryUpsert) {
+ s.UpdateCreatedAt()
+ })
+}
+
+// Exec executes the query.
+func (u *UserLoginHistoryUpsertOne) Exec(ctx context.Context) error {
+ if len(u.create.conflict) == 0 {
+ return errors.New("db: missing options for UserLoginHistoryCreate.OnConflict")
+ }
+ return u.create.Exec(ctx)
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (u *UserLoginHistoryUpsertOne) ExecX(ctx context.Context) {
+ if err := u.create.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// Exec executes the UPSERT query and returns the inserted/updated ID.
+func (u *UserLoginHistoryUpsertOne) ID(ctx context.Context) (id uuid.UUID, err error) {
+ if u.create.driver.Dialect() == dialect.MySQL {
+ // In case of "ON CONFLICT", there is no way to get back non-numeric ID
+ // fields from the database since MySQL does not support the RETURNING clause.
+ return id, errors.New("db: UserLoginHistoryUpsertOne.ID is not supported by MySQL driver. Use UserLoginHistoryUpsertOne.Exec instead")
+ }
+ node, err := u.create.Save(ctx)
+ if err != nil {
+ return id, err
+ }
+ return node.ID, nil
+}
+
+// IDX is like ID, but panics if an error occurs.
+func (u *UserLoginHistoryUpsertOne) IDX(ctx context.Context) uuid.UUID {
+ id, err := u.ID(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return id
+}
+
+// UserLoginHistoryCreateBulk is the builder for creating many UserLoginHistory entities in bulk.
+type UserLoginHistoryCreateBulk struct {
+ config
+ err error
+ builders []*UserLoginHistoryCreate
+ conflict []sql.ConflictOption
+}
+
+// Save creates the UserLoginHistory entities in the database.
+func (ulhcb *UserLoginHistoryCreateBulk) Save(ctx context.Context) ([]*UserLoginHistory, error) {
+ if ulhcb.err != nil {
+ return nil, ulhcb.err
+ }
+ specs := make([]*sqlgraph.CreateSpec, len(ulhcb.builders))
+ nodes := make([]*UserLoginHistory, len(ulhcb.builders))
+ mutators := make([]Mutator, len(ulhcb.builders))
+ for i := range ulhcb.builders {
+ func(i int, root context.Context) {
+ builder := ulhcb.builders[i]
+ builder.defaults()
+ var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
+ mutation, ok := m.(*UserLoginHistoryMutation)
+ if !ok {
+ return nil, fmt.Errorf("unexpected mutation type %T", m)
+ }
+ if err := builder.check(); err != nil {
+ return nil, err
+ }
+ builder.mutation = mutation
+ var err error
+ nodes[i], specs[i] = builder.createSpec()
+ if i < len(mutators)-1 {
+ _, err = mutators[i+1].Mutate(root, ulhcb.builders[i+1].mutation)
+ } else {
+ spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
+ spec.OnConflict = ulhcb.conflict
+ // Invoke the actual operation on the latest mutation in the chain.
+ if err = sqlgraph.BatchCreate(ctx, ulhcb.driver, spec); err != nil {
+ if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ }
+ }
+ if err != nil {
+ return nil, err
+ }
+ mutation.id = &nodes[i].ID
+ mutation.done = true
+ return nodes[i], nil
+ })
+ for i := len(builder.hooks) - 1; i >= 0; i-- {
+ mut = builder.hooks[i](mut)
+ }
+ mutators[i] = mut
+ }(i, ctx)
+ }
+ if len(mutators) > 0 {
+ if _, err := mutators[0].Mutate(ctx, ulhcb.builders[0].mutation); err != nil {
+ return nil, err
+ }
+ }
+ return nodes, nil
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (ulhcb *UserLoginHistoryCreateBulk) SaveX(ctx context.Context) []*UserLoginHistory {
+ v, err := ulhcb.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return v
+}
+
+// Exec executes the query.
+func (ulhcb *UserLoginHistoryCreateBulk) Exec(ctx context.Context) error {
+ _, err := ulhcb.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (ulhcb *UserLoginHistoryCreateBulk) ExecX(ctx context.Context) {
+ if err := ulhcb.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
+// of the `INSERT` statement. For example:
+//
+// client.UserLoginHistory.CreateBulk(builders...).
+// OnConflict(
+// // Update the row with the new values
+// // the was proposed for insertion.
+// sql.ResolveWithNewValues(),
+// ).
+// // Override some of the fields with custom
+// // update values.
+// Update(func(u *ent.UserLoginHistoryUpsert) {
+// SetUserID(v+v).
+// }).
+// Exec(ctx)
+func (ulhcb *UserLoginHistoryCreateBulk) OnConflict(opts ...sql.ConflictOption) *UserLoginHistoryUpsertBulk {
+ ulhcb.conflict = opts
+ return &UserLoginHistoryUpsertBulk{
+ create: ulhcb,
+ }
+}
+
+// OnConflictColumns calls `OnConflict` and configures the columns
+// as conflict target. Using this option is equivalent to using:
+//
+// client.UserLoginHistory.Create().
+// OnConflict(sql.ConflictColumns(columns...)).
+// Exec(ctx)
+func (ulhcb *UserLoginHistoryCreateBulk) OnConflictColumns(columns ...string) *UserLoginHistoryUpsertBulk {
+ ulhcb.conflict = append(ulhcb.conflict, sql.ConflictColumns(columns...))
+ return &UserLoginHistoryUpsertBulk{
+ create: ulhcb,
+ }
+}
+
+// UserLoginHistoryUpsertBulk is the builder for "upsert"-ing
+// a bulk of UserLoginHistory nodes.
+type UserLoginHistoryUpsertBulk struct {
+ create *UserLoginHistoryCreateBulk
+}
+
+// UpdateNewValues updates the mutable fields using the new values that
+// were set on create. Using this option is equivalent to using:
+//
+// client.UserLoginHistory.Create().
+// OnConflict(
+// sql.ResolveWithNewValues(),
+// sql.ResolveWith(func(u *sql.UpdateSet) {
+// u.SetIgnore(userloginhistory.FieldID)
+// }),
+// ).
+// Exec(ctx)
+func (u *UserLoginHistoryUpsertBulk) UpdateNewValues() *UserLoginHistoryUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
+ for _, b := range u.create.builders {
+ if _, exists := b.mutation.ID(); exists {
+ s.SetIgnore(userloginhistory.FieldID)
+ }
+ }
+ }))
+ return u
+}
+
+// Ignore sets each column to itself in case of conflict.
+// Using this option is equivalent to using:
+//
+// client.UserLoginHistory.Create().
+// OnConflict(sql.ResolveWithIgnore()).
+// Exec(ctx)
+func (u *UserLoginHistoryUpsertBulk) Ignore() *UserLoginHistoryUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
+ return u
+}
+
+// DoNothing configures the conflict_action to `DO NOTHING`.
+// Supported only by SQLite and PostgreSQL.
+func (u *UserLoginHistoryUpsertBulk) DoNothing() *UserLoginHistoryUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.DoNothing())
+ return u
+}
+
+// Update allows overriding fields `UPDATE` values. See the UserLoginHistoryCreateBulk.OnConflict
+// documentation for more info.
+func (u *UserLoginHistoryUpsertBulk) Update(set func(*UserLoginHistoryUpsert)) *UserLoginHistoryUpsertBulk {
+ u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
+ set(&UserLoginHistoryUpsert{UpdateSet: update})
+ }))
+ return u
+}
+
+// SetUserID sets the "user_id" field.
+func (u *UserLoginHistoryUpsertBulk) SetUserID(v uuid.UUID) *UserLoginHistoryUpsertBulk {
+ return u.Update(func(s *UserLoginHistoryUpsert) {
+ s.SetUserID(v)
+ })
+}
+
+// UpdateUserID sets the "user_id" field to the value that was provided on create.
+func (u *UserLoginHistoryUpsertBulk) UpdateUserID() *UserLoginHistoryUpsertBulk {
+ return u.Update(func(s *UserLoginHistoryUpsert) {
+ s.UpdateUserID()
+ })
+}
+
+// SetIP sets the "ip" field.
+func (u *UserLoginHistoryUpsertBulk) SetIP(v string) *UserLoginHistoryUpsertBulk {
+ return u.Update(func(s *UserLoginHistoryUpsert) {
+ s.SetIP(v)
+ })
+}
+
+// UpdateIP sets the "ip" field to the value that was provided on create.
+func (u *UserLoginHistoryUpsertBulk) UpdateIP() *UserLoginHistoryUpsertBulk {
+ return u.Update(func(s *UserLoginHistoryUpsert) {
+ s.UpdateIP()
+ })
+}
+
+// SetCountry sets the "country" field.
+func (u *UserLoginHistoryUpsertBulk) SetCountry(v string) *UserLoginHistoryUpsertBulk {
+ return u.Update(func(s *UserLoginHistoryUpsert) {
+ s.SetCountry(v)
+ })
+}
+
+// UpdateCountry sets the "country" field to the value that was provided on create.
+func (u *UserLoginHistoryUpsertBulk) UpdateCountry() *UserLoginHistoryUpsertBulk {
+ return u.Update(func(s *UserLoginHistoryUpsert) {
+ s.UpdateCountry()
+ })
+}
+
+// SetProvince sets the "province" field.
+func (u *UserLoginHistoryUpsertBulk) SetProvince(v string) *UserLoginHistoryUpsertBulk {
+ return u.Update(func(s *UserLoginHistoryUpsert) {
+ s.SetProvince(v)
+ })
+}
+
+// UpdateProvince sets the "province" field to the value that was provided on create.
+func (u *UserLoginHistoryUpsertBulk) UpdateProvince() *UserLoginHistoryUpsertBulk {
+ return u.Update(func(s *UserLoginHistoryUpsert) {
+ s.UpdateProvince()
+ })
+}
+
+// SetCity sets the "city" field.
+func (u *UserLoginHistoryUpsertBulk) SetCity(v string) *UserLoginHistoryUpsertBulk {
+ return u.Update(func(s *UserLoginHistoryUpsert) {
+ s.SetCity(v)
+ })
+}
+
+// UpdateCity sets the "city" field to the value that was provided on create.
+func (u *UserLoginHistoryUpsertBulk) UpdateCity() *UserLoginHistoryUpsertBulk {
+ return u.Update(func(s *UserLoginHistoryUpsert) {
+ s.UpdateCity()
+ })
+}
+
+// SetIsp sets the "isp" field.
+func (u *UserLoginHistoryUpsertBulk) SetIsp(v string) *UserLoginHistoryUpsertBulk {
+ return u.Update(func(s *UserLoginHistoryUpsert) {
+ s.SetIsp(v)
+ })
+}
+
+// UpdateIsp sets the "isp" field to the value that was provided on create.
+func (u *UserLoginHistoryUpsertBulk) UpdateIsp() *UserLoginHistoryUpsertBulk {
+ return u.Update(func(s *UserLoginHistoryUpsert) {
+ s.UpdateIsp()
+ })
+}
+
+// SetAsn sets the "asn" field.
+func (u *UserLoginHistoryUpsertBulk) SetAsn(v string) *UserLoginHistoryUpsertBulk {
+ return u.Update(func(s *UserLoginHistoryUpsert) {
+ s.SetAsn(v)
+ })
+}
+
+// UpdateAsn sets the "asn" field to the value that was provided on create.
+func (u *UserLoginHistoryUpsertBulk) UpdateAsn() *UserLoginHistoryUpsertBulk {
+ return u.Update(func(s *UserLoginHistoryUpsert) {
+ s.UpdateAsn()
+ })
+}
+
+// SetClientVersion sets the "client_version" field.
+func (u *UserLoginHistoryUpsertBulk) SetClientVersion(v string) *UserLoginHistoryUpsertBulk {
+ return u.Update(func(s *UserLoginHistoryUpsert) {
+ s.SetClientVersion(v)
+ })
+}
+
+// UpdateClientVersion sets the "client_version" field to the value that was provided on create.
+func (u *UserLoginHistoryUpsertBulk) UpdateClientVersion() *UserLoginHistoryUpsertBulk {
+ return u.Update(func(s *UserLoginHistoryUpsert) {
+ s.UpdateClientVersion()
+ })
+}
+
+// SetDevice sets the "device" field.
+func (u *UserLoginHistoryUpsertBulk) SetDevice(v string) *UserLoginHistoryUpsertBulk {
+ return u.Update(func(s *UserLoginHistoryUpsert) {
+ s.SetDevice(v)
+ })
+}
+
+// UpdateDevice sets the "device" field to the value that was provided on create.
+func (u *UserLoginHistoryUpsertBulk) UpdateDevice() *UserLoginHistoryUpsertBulk {
+ return u.Update(func(s *UserLoginHistoryUpsert) {
+ s.UpdateDevice()
+ })
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (u *UserLoginHistoryUpsertBulk) SetCreatedAt(v time.Time) *UserLoginHistoryUpsertBulk {
+ return u.Update(func(s *UserLoginHistoryUpsert) {
+ s.SetCreatedAt(v)
+ })
+}
+
+// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
+func (u *UserLoginHistoryUpsertBulk) UpdateCreatedAt() *UserLoginHistoryUpsertBulk {
+ return u.Update(func(s *UserLoginHistoryUpsert) {
+ s.UpdateCreatedAt()
+ })
+}
+
+// Exec executes the query.
+func (u *UserLoginHistoryUpsertBulk) Exec(ctx context.Context) error {
+ if u.create.err != nil {
+ return u.create.err
+ }
+ for i, b := range u.create.builders {
+ if len(b.conflict) != 0 {
+ return fmt.Errorf("db: OnConflict was set for builder %d. Set it on the UserLoginHistoryCreateBulk instead", i)
+ }
+ }
+ if len(u.create.conflict) == 0 {
+ return errors.New("db: missing options for UserLoginHistoryCreateBulk.OnConflict")
+ }
+ return u.create.Exec(ctx)
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (u *UserLoginHistoryUpsertBulk) ExecX(ctx context.Context) {
+ if err := u.create.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
diff --git a/backend/db/userloginhistory_delete.go b/backend/db/userloginhistory_delete.go
new file mode 100644
index 0000000..c589a78
--- /dev/null
+++ b/backend/db/userloginhistory_delete.go
@@ -0,0 +1,88 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+ "github.com/chaitin/MonkeyCode/backend/db/userloginhistory"
+)
+
+// UserLoginHistoryDelete is the builder for deleting a UserLoginHistory entity.
+type UserLoginHistoryDelete struct {
+ config
+ hooks []Hook
+ mutation *UserLoginHistoryMutation
+}
+
+// Where appends a list predicates to the UserLoginHistoryDelete builder.
+func (ulhd *UserLoginHistoryDelete) Where(ps ...predicate.UserLoginHistory) *UserLoginHistoryDelete {
+ ulhd.mutation.Where(ps...)
+ return ulhd
+}
+
+// Exec executes the deletion query and returns how many vertices were deleted.
+func (ulhd *UserLoginHistoryDelete) Exec(ctx context.Context) (int, error) {
+ return withHooks(ctx, ulhd.sqlExec, ulhd.mutation, ulhd.hooks)
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (ulhd *UserLoginHistoryDelete) ExecX(ctx context.Context) int {
+ n, err := ulhd.Exec(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return n
+}
+
+func (ulhd *UserLoginHistoryDelete) sqlExec(ctx context.Context) (int, error) {
+ _spec := sqlgraph.NewDeleteSpec(userloginhistory.Table, sqlgraph.NewFieldSpec(userloginhistory.FieldID, field.TypeUUID))
+ if ps := ulhd.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ affected, err := sqlgraph.DeleteNodes(ctx, ulhd.driver, _spec)
+ if err != nil && sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ ulhd.mutation.done = true
+ return affected, err
+}
+
+// UserLoginHistoryDeleteOne is the builder for deleting a single UserLoginHistory entity.
+type UserLoginHistoryDeleteOne struct {
+ ulhd *UserLoginHistoryDelete
+}
+
+// Where appends a list predicates to the UserLoginHistoryDelete builder.
+func (ulhdo *UserLoginHistoryDeleteOne) Where(ps ...predicate.UserLoginHistory) *UserLoginHistoryDeleteOne {
+ ulhdo.ulhd.mutation.Where(ps...)
+ return ulhdo
+}
+
+// Exec executes the deletion query.
+func (ulhdo *UserLoginHistoryDeleteOne) Exec(ctx context.Context) error {
+ n, err := ulhdo.ulhd.Exec(ctx)
+ switch {
+ case err != nil:
+ return err
+ case n == 0:
+ return &NotFoundError{userloginhistory.Label}
+ default:
+ return nil
+ }
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (ulhdo *UserLoginHistoryDeleteOne) ExecX(ctx context.Context) {
+ if err := ulhdo.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
diff --git a/backend/db/userloginhistory_query.go b/backend/db/userloginhistory_query.go
new file mode 100644
index 0000000..5a1d192
--- /dev/null
+++ b/backend/db/userloginhistory_query.go
@@ -0,0 +1,665 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "fmt"
+ "math"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect"
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+ "github.com/chaitin/MonkeyCode/backend/db/user"
+ "github.com/chaitin/MonkeyCode/backend/db/userloginhistory"
+ "github.com/google/uuid"
+)
+
+// UserLoginHistoryQuery is the builder for querying UserLoginHistory entities.
+type UserLoginHistoryQuery struct {
+ config
+ ctx *QueryContext
+ order []userloginhistory.OrderOption
+ inters []Interceptor
+ predicates []predicate.UserLoginHistory
+ withOwner *UserQuery
+ withFKs bool
+ modifiers []func(*sql.Selector)
+ // intermediate query (i.e. traversal path).
+ sql *sql.Selector
+ path func(context.Context) (*sql.Selector, error)
+}
+
+// Where adds a new predicate for the UserLoginHistoryQuery builder.
+func (ulhq *UserLoginHistoryQuery) Where(ps ...predicate.UserLoginHistory) *UserLoginHistoryQuery {
+ ulhq.predicates = append(ulhq.predicates, ps...)
+ return ulhq
+}
+
+// Limit the number of records to be returned by this query.
+func (ulhq *UserLoginHistoryQuery) Limit(limit int) *UserLoginHistoryQuery {
+ ulhq.ctx.Limit = &limit
+ return ulhq
+}
+
+// Offset to start from.
+func (ulhq *UserLoginHistoryQuery) Offset(offset int) *UserLoginHistoryQuery {
+ ulhq.ctx.Offset = &offset
+ return ulhq
+}
+
+// Unique configures the query builder to filter duplicate records on query.
+// By default, unique is set to true, and can be disabled using this method.
+func (ulhq *UserLoginHistoryQuery) Unique(unique bool) *UserLoginHistoryQuery {
+ ulhq.ctx.Unique = &unique
+ return ulhq
+}
+
+// Order specifies how the records should be ordered.
+func (ulhq *UserLoginHistoryQuery) Order(o ...userloginhistory.OrderOption) *UserLoginHistoryQuery {
+ ulhq.order = append(ulhq.order, o...)
+ return ulhq
+}
+
+// QueryOwner chains the current query on the "owner" edge.
+func (ulhq *UserLoginHistoryQuery) QueryOwner() *UserQuery {
+ query := (&UserClient{config: ulhq.config}).Query()
+ query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
+ if err := ulhq.prepareQuery(ctx); err != nil {
+ return nil, err
+ }
+ selector := ulhq.sqlQuery(ctx)
+ if err := selector.Err(); err != nil {
+ return nil, err
+ }
+ step := sqlgraph.NewStep(
+ sqlgraph.From(userloginhistory.Table, userloginhistory.FieldID, selector),
+ sqlgraph.To(user.Table, user.FieldID),
+ sqlgraph.Edge(sqlgraph.M2O, true, userloginhistory.OwnerTable, userloginhistory.OwnerColumn),
+ )
+ fromU = sqlgraph.SetNeighbors(ulhq.driver.Dialect(), step)
+ return fromU, nil
+ }
+ return query
+}
+
+// First returns the first UserLoginHistory entity from the query.
+// Returns a *NotFoundError when no UserLoginHistory was found.
+func (ulhq *UserLoginHistoryQuery) First(ctx context.Context) (*UserLoginHistory, error) {
+ nodes, err := ulhq.Limit(1).All(setContextOp(ctx, ulhq.ctx, ent.OpQueryFirst))
+ if err != nil {
+ return nil, err
+ }
+ if len(nodes) == 0 {
+ return nil, &NotFoundError{userloginhistory.Label}
+ }
+ return nodes[0], nil
+}
+
+// FirstX is like First, but panics if an error occurs.
+func (ulhq *UserLoginHistoryQuery) FirstX(ctx context.Context) *UserLoginHistory {
+ node, err := ulhq.First(ctx)
+ if err != nil && !IsNotFound(err) {
+ panic(err)
+ }
+ return node
+}
+
+// FirstID returns the first UserLoginHistory ID from the query.
+// Returns a *NotFoundError when no UserLoginHistory ID was found.
+func (ulhq *UserLoginHistoryQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
+ var ids []uuid.UUID
+ if ids, err = ulhq.Limit(1).IDs(setContextOp(ctx, ulhq.ctx, ent.OpQueryFirstID)); err != nil {
+ return
+ }
+ if len(ids) == 0 {
+ err = &NotFoundError{userloginhistory.Label}
+ return
+ }
+ return ids[0], nil
+}
+
+// FirstIDX is like FirstID, but panics if an error occurs.
+func (ulhq *UserLoginHistoryQuery) FirstIDX(ctx context.Context) uuid.UUID {
+ id, err := ulhq.FirstID(ctx)
+ if err != nil && !IsNotFound(err) {
+ panic(err)
+ }
+ return id
+}
+
+// Only returns a single UserLoginHistory entity found by the query, ensuring it only returns one.
+// Returns a *NotSingularError when more than one UserLoginHistory entity is found.
+// Returns a *NotFoundError when no UserLoginHistory entities are found.
+func (ulhq *UserLoginHistoryQuery) Only(ctx context.Context) (*UserLoginHistory, error) {
+ nodes, err := ulhq.Limit(2).All(setContextOp(ctx, ulhq.ctx, ent.OpQueryOnly))
+ if err != nil {
+ return nil, err
+ }
+ switch len(nodes) {
+ case 1:
+ return nodes[0], nil
+ case 0:
+ return nil, &NotFoundError{userloginhistory.Label}
+ default:
+ return nil, &NotSingularError{userloginhistory.Label}
+ }
+}
+
+// OnlyX is like Only, but panics if an error occurs.
+func (ulhq *UserLoginHistoryQuery) OnlyX(ctx context.Context) *UserLoginHistory {
+ node, err := ulhq.Only(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return node
+}
+
+// OnlyID is like Only, but returns the only UserLoginHistory ID in the query.
+// Returns a *NotSingularError when more than one UserLoginHistory ID is found.
+// Returns a *NotFoundError when no entities are found.
+func (ulhq *UserLoginHistoryQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
+ var ids []uuid.UUID
+ if ids, err = ulhq.Limit(2).IDs(setContextOp(ctx, ulhq.ctx, ent.OpQueryOnlyID)); err != nil {
+ return
+ }
+ switch len(ids) {
+ case 1:
+ id = ids[0]
+ case 0:
+ err = &NotFoundError{userloginhistory.Label}
+ default:
+ err = &NotSingularError{userloginhistory.Label}
+ }
+ return
+}
+
+// OnlyIDX is like OnlyID, but panics if an error occurs.
+func (ulhq *UserLoginHistoryQuery) OnlyIDX(ctx context.Context) uuid.UUID {
+ id, err := ulhq.OnlyID(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return id
+}
+
+// All executes the query and returns a list of UserLoginHistories.
+func (ulhq *UserLoginHistoryQuery) All(ctx context.Context) ([]*UserLoginHistory, error) {
+ ctx = setContextOp(ctx, ulhq.ctx, ent.OpQueryAll)
+ if err := ulhq.prepareQuery(ctx); err != nil {
+ return nil, err
+ }
+ qr := querierAll[[]*UserLoginHistory, *UserLoginHistoryQuery]()
+ return withInterceptors[[]*UserLoginHistory](ctx, ulhq, qr, ulhq.inters)
+}
+
+// AllX is like All, but panics if an error occurs.
+func (ulhq *UserLoginHistoryQuery) AllX(ctx context.Context) []*UserLoginHistory {
+ nodes, err := ulhq.All(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return nodes
+}
+
+// IDs executes the query and returns a list of UserLoginHistory IDs.
+func (ulhq *UserLoginHistoryQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) {
+ if ulhq.ctx.Unique == nil && ulhq.path != nil {
+ ulhq.Unique(true)
+ }
+ ctx = setContextOp(ctx, ulhq.ctx, ent.OpQueryIDs)
+ if err = ulhq.Select(userloginhistory.FieldID).Scan(ctx, &ids); err != nil {
+ return nil, err
+ }
+ return ids, nil
+}
+
+// IDsX is like IDs, but panics if an error occurs.
+func (ulhq *UserLoginHistoryQuery) IDsX(ctx context.Context) []uuid.UUID {
+ ids, err := ulhq.IDs(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return ids
+}
+
+// Count returns the count of the given query.
+func (ulhq *UserLoginHistoryQuery) Count(ctx context.Context) (int, error) {
+ ctx = setContextOp(ctx, ulhq.ctx, ent.OpQueryCount)
+ if err := ulhq.prepareQuery(ctx); err != nil {
+ return 0, err
+ }
+ return withInterceptors[int](ctx, ulhq, querierCount[*UserLoginHistoryQuery](), ulhq.inters)
+}
+
+// CountX is like Count, but panics if an error occurs.
+func (ulhq *UserLoginHistoryQuery) CountX(ctx context.Context) int {
+ count, err := ulhq.Count(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return count
+}
+
+// Exist returns true if the query has elements in the graph.
+func (ulhq *UserLoginHistoryQuery) Exist(ctx context.Context) (bool, error) {
+ ctx = setContextOp(ctx, ulhq.ctx, ent.OpQueryExist)
+ switch _, err := ulhq.FirstID(ctx); {
+ case IsNotFound(err):
+ return false, nil
+ case err != nil:
+ return false, fmt.Errorf("db: check existence: %w", err)
+ default:
+ return true, nil
+ }
+}
+
+// ExistX is like Exist, but panics if an error occurs.
+func (ulhq *UserLoginHistoryQuery) ExistX(ctx context.Context) bool {
+ exist, err := ulhq.Exist(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return exist
+}
+
+// Clone returns a duplicate of the UserLoginHistoryQuery builder, including all associated steps. It can be
+// used to prepare common query builders and use them differently after the clone is made.
+func (ulhq *UserLoginHistoryQuery) Clone() *UserLoginHistoryQuery {
+ if ulhq == nil {
+ return nil
+ }
+ return &UserLoginHistoryQuery{
+ config: ulhq.config,
+ ctx: ulhq.ctx.Clone(),
+ order: append([]userloginhistory.OrderOption{}, ulhq.order...),
+ inters: append([]Interceptor{}, ulhq.inters...),
+ predicates: append([]predicate.UserLoginHistory{}, ulhq.predicates...),
+ withOwner: ulhq.withOwner.Clone(),
+ // clone intermediate query.
+ sql: ulhq.sql.Clone(),
+ path: ulhq.path,
+ modifiers: append([]func(*sql.Selector){}, ulhq.modifiers...),
+ }
+}
+
+// WithOwner tells the query-builder to eager-load the nodes that are connected to
+// the "owner" edge. The optional arguments are used to configure the query builder of the edge.
+func (ulhq *UserLoginHistoryQuery) WithOwner(opts ...func(*UserQuery)) *UserLoginHistoryQuery {
+ query := (&UserClient{config: ulhq.config}).Query()
+ for _, opt := range opts {
+ opt(query)
+ }
+ ulhq.withOwner = query
+ return ulhq
+}
+
+// GroupBy is used to group vertices by one or more fields/columns.
+// It is often used with aggregate functions, like: count, max, mean, min, sum.
+//
+// Example:
+//
+// var v []struct {
+// UserID uuid.UUID `json:"user_id,omitempty"`
+// Count int `json:"count,omitempty"`
+// }
+//
+// client.UserLoginHistory.Query().
+// GroupBy(userloginhistory.FieldUserID).
+// Aggregate(db.Count()).
+// Scan(ctx, &v)
+func (ulhq *UserLoginHistoryQuery) GroupBy(field string, fields ...string) *UserLoginHistoryGroupBy {
+ ulhq.ctx.Fields = append([]string{field}, fields...)
+ grbuild := &UserLoginHistoryGroupBy{build: ulhq}
+ grbuild.flds = &ulhq.ctx.Fields
+ grbuild.label = userloginhistory.Label
+ grbuild.scan = grbuild.Scan
+ return grbuild
+}
+
+// Select allows the selection one or more fields/columns for the given query,
+// instead of selecting all fields in the entity.
+//
+// Example:
+//
+// var v []struct {
+// UserID uuid.UUID `json:"user_id,omitempty"`
+// }
+//
+// client.UserLoginHistory.Query().
+// Select(userloginhistory.FieldUserID).
+// Scan(ctx, &v)
+func (ulhq *UserLoginHistoryQuery) Select(fields ...string) *UserLoginHistorySelect {
+ ulhq.ctx.Fields = append(ulhq.ctx.Fields, fields...)
+ sbuild := &UserLoginHistorySelect{UserLoginHistoryQuery: ulhq}
+ sbuild.label = userloginhistory.Label
+ sbuild.flds, sbuild.scan = &ulhq.ctx.Fields, sbuild.Scan
+ return sbuild
+}
+
+// Aggregate returns a UserLoginHistorySelect configured with the given aggregations.
+func (ulhq *UserLoginHistoryQuery) Aggregate(fns ...AggregateFunc) *UserLoginHistorySelect {
+ return ulhq.Select().Aggregate(fns...)
+}
+
+func (ulhq *UserLoginHistoryQuery) prepareQuery(ctx context.Context) error {
+ for _, inter := range ulhq.inters {
+ if inter == nil {
+ return fmt.Errorf("db: uninitialized interceptor (forgotten import db/runtime?)")
+ }
+ if trv, ok := inter.(Traverser); ok {
+ if err := trv.Traverse(ctx, ulhq); err != nil {
+ return err
+ }
+ }
+ }
+ for _, f := range ulhq.ctx.Fields {
+ if !userloginhistory.ValidColumn(f) {
+ return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
+ }
+ }
+ if ulhq.path != nil {
+ prev, err := ulhq.path(ctx)
+ if err != nil {
+ return err
+ }
+ ulhq.sql = prev
+ }
+ return nil
+}
+
+func (ulhq *UserLoginHistoryQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*UserLoginHistory, error) {
+ var (
+ nodes = []*UserLoginHistory{}
+ withFKs = ulhq.withFKs
+ _spec = ulhq.querySpec()
+ loadedTypes = [1]bool{
+ ulhq.withOwner != nil,
+ }
+ )
+ if ulhq.withOwner != nil {
+ withFKs = true
+ }
+ if withFKs {
+ _spec.Node.Columns = append(_spec.Node.Columns, userloginhistory.ForeignKeys...)
+ }
+ _spec.ScanValues = func(columns []string) ([]any, error) {
+ return (*UserLoginHistory).scanValues(nil, columns)
+ }
+ _spec.Assign = func(columns []string, values []any) error {
+ node := &UserLoginHistory{config: ulhq.config}
+ nodes = append(nodes, node)
+ node.Edges.loadedTypes = loadedTypes
+ return node.assignValues(columns, values)
+ }
+ if len(ulhq.modifiers) > 0 {
+ _spec.Modifiers = ulhq.modifiers
+ }
+ for i := range hooks {
+ hooks[i](ctx, _spec)
+ }
+ if err := sqlgraph.QueryNodes(ctx, ulhq.driver, _spec); err != nil {
+ return nil, err
+ }
+ if len(nodes) == 0 {
+ return nodes, nil
+ }
+ if query := ulhq.withOwner; query != nil {
+ if err := ulhq.loadOwner(ctx, query, nodes, nil,
+ func(n *UserLoginHistory, e *User) { n.Edges.Owner = e }); err != nil {
+ return nil, err
+ }
+ }
+ return nodes, nil
+}
+
+func (ulhq *UserLoginHistoryQuery) loadOwner(ctx context.Context, query *UserQuery, nodes []*UserLoginHistory, init func(*UserLoginHistory), assign func(*UserLoginHistory, *User)) error {
+ ids := make([]uuid.UUID, 0, len(nodes))
+ nodeids := make(map[uuid.UUID][]*UserLoginHistory)
+ for i := range nodes {
+ if nodes[i].user_login_histories == nil {
+ continue
+ }
+ fk := *nodes[i].user_login_histories
+ if _, ok := nodeids[fk]; !ok {
+ ids = append(ids, fk)
+ }
+ nodeids[fk] = append(nodeids[fk], nodes[i])
+ }
+ if len(ids) == 0 {
+ return nil
+ }
+ query.Where(user.IDIn(ids...))
+ neighbors, err := query.All(ctx)
+ if err != nil {
+ return err
+ }
+ for _, n := range neighbors {
+ nodes, ok := nodeids[n.ID]
+ if !ok {
+ return fmt.Errorf(`unexpected foreign-key "user_login_histories" returned %v`, n.ID)
+ }
+ for i := range nodes {
+ assign(nodes[i], n)
+ }
+ }
+ return nil
+}
+
+func (ulhq *UserLoginHistoryQuery) sqlCount(ctx context.Context) (int, error) {
+ _spec := ulhq.querySpec()
+ if len(ulhq.modifiers) > 0 {
+ _spec.Modifiers = ulhq.modifiers
+ }
+ _spec.Node.Columns = ulhq.ctx.Fields
+ if len(ulhq.ctx.Fields) > 0 {
+ _spec.Unique = ulhq.ctx.Unique != nil && *ulhq.ctx.Unique
+ }
+ return sqlgraph.CountNodes(ctx, ulhq.driver, _spec)
+}
+
+func (ulhq *UserLoginHistoryQuery) querySpec() *sqlgraph.QuerySpec {
+ _spec := sqlgraph.NewQuerySpec(userloginhistory.Table, userloginhistory.Columns, sqlgraph.NewFieldSpec(userloginhistory.FieldID, field.TypeUUID))
+ _spec.From = ulhq.sql
+ if unique := ulhq.ctx.Unique; unique != nil {
+ _spec.Unique = *unique
+ } else if ulhq.path != nil {
+ _spec.Unique = true
+ }
+ if fields := ulhq.ctx.Fields; len(fields) > 0 {
+ _spec.Node.Columns = make([]string, 0, len(fields))
+ _spec.Node.Columns = append(_spec.Node.Columns, userloginhistory.FieldID)
+ for i := range fields {
+ if fields[i] != userloginhistory.FieldID {
+ _spec.Node.Columns = append(_spec.Node.Columns, fields[i])
+ }
+ }
+ }
+ if ps := ulhq.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if limit := ulhq.ctx.Limit; limit != nil {
+ _spec.Limit = *limit
+ }
+ if offset := ulhq.ctx.Offset; offset != nil {
+ _spec.Offset = *offset
+ }
+ if ps := ulhq.order; len(ps) > 0 {
+ _spec.Order = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ return _spec
+}
+
+func (ulhq *UserLoginHistoryQuery) sqlQuery(ctx context.Context) *sql.Selector {
+ builder := sql.Dialect(ulhq.driver.Dialect())
+ t1 := builder.Table(userloginhistory.Table)
+ columns := ulhq.ctx.Fields
+ if len(columns) == 0 {
+ columns = userloginhistory.Columns
+ }
+ selector := builder.Select(t1.Columns(columns...)...).From(t1)
+ if ulhq.sql != nil {
+ selector = ulhq.sql
+ selector.Select(selector.Columns(columns...)...)
+ }
+ if ulhq.ctx.Unique != nil && *ulhq.ctx.Unique {
+ selector.Distinct()
+ }
+ for _, m := range ulhq.modifiers {
+ m(selector)
+ }
+ for _, p := range ulhq.predicates {
+ p(selector)
+ }
+ for _, p := range ulhq.order {
+ p(selector)
+ }
+ if offset := ulhq.ctx.Offset; offset != nil {
+ // limit is mandatory for offset clause. We start
+ // with default value, and override it below if needed.
+ selector.Offset(*offset).Limit(math.MaxInt32)
+ }
+ if limit := ulhq.ctx.Limit; limit != nil {
+ selector.Limit(*limit)
+ }
+ return selector
+}
+
+// ForUpdate locks the selected rows against concurrent updates, and prevent them from being
+// updated, deleted or "selected ... for update" by other sessions, until the transaction is
+// either committed or rolled-back.
+func (ulhq *UserLoginHistoryQuery) ForUpdate(opts ...sql.LockOption) *UserLoginHistoryQuery {
+ if ulhq.driver.Dialect() == dialect.Postgres {
+ ulhq.Unique(false)
+ }
+ ulhq.modifiers = append(ulhq.modifiers, func(s *sql.Selector) {
+ s.ForUpdate(opts...)
+ })
+ return ulhq
+}
+
+// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock
+// on any rows that are read. Other sessions can read the rows, but cannot modify them
+// until your transaction commits.
+func (ulhq *UserLoginHistoryQuery) ForShare(opts ...sql.LockOption) *UserLoginHistoryQuery {
+ if ulhq.driver.Dialect() == dialect.Postgres {
+ ulhq.Unique(false)
+ }
+ ulhq.modifiers = append(ulhq.modifiers, func(s *sql.Selector) {
+ s.ForShare(opts...)
+ })
+ return ulhq
+}
+
+// Modify adds a query modifier for attaching custom logic to queries.
+func (ulhq *UserLoginHistoryQuery) Modify(modifiers ...func(s *sql.Selector)) *UserLoginHistorySelect {
+ ulhq.modifiers = append(ulhq.modifiers, modifiers...)
+ return ulhq.Select()
+}
+
+// UserLoginHistoryGroupBy is the group-by builder for UserLoginHistory entities.
+type UserLoginHistoryGroupBy struct {
+ selector
+ build *UserLoginHistoryQuery
+}
+
+// Aggregate adds the given aggregation functions to the group-by query.
+func (ulhgb *UserLoginHistoryGroupBy) Aggregate(fns ...AggregateFunc) *UserLoginHistoryGroupBy {
+ ulhgb.fns = append(ulhgb.fns, fns...)
+ return ulhgb
+}
+
+// Scan applies the selector query and scans the result into the given value.
+func (ulhgb *UserLoginHistoryGroupBy) Scan(ctx context.Context, v any) error {
+ ctx = setContextOp(ctx, ulhgb.build.ctx, ent.OpQueryGroupBy)
+ if err := ulhgb.build.prepareQuery(ctx); err != nil {
+ return err
+ }
+ return scanWithInterceptors[*UserLoginHistoryQuery, *UserLoginHistoryGroupBy](ctx, ulhgb.build, ulhgb, ulhgb.build.inters, v)
+}
+
+func (ulhgb *UserLoginHistoryGroupBy) sqlScan(ctx context.Context, root *UserLoginHistoryQuery, v any) error {
+ selector := root.sqlQuery(ctx).Select()
+ aggregation := make([]string, 0, len(ulhgb.fns))
+ for _, fn := range ulhgb.fns {
+ aggregation = append(aggregation, fn(selector))
+ }
+ if len(selector.SelectedColumns()) == 0 {
+ columns := make([]string, 0, len(*ulhgb.flds)+len(ulhgb.fns))
+ for _, f := range *ulhgb.flds {
+ columns = append(columns, selector.C(f))
+ }
+ columns = append(columns, aggregation...)
+ selector.Select(columns...)
+ }
+ selector.GroupBy(selector.Columns(*ulhgb.flds...)...)
+ if err := selector.Err(); err != nil {
+ return err
+ }
+ rows := &sql.Rows{}
+ query, args := selector.Query()
+ if err := ulhgb.build.driver.Query(ctx, query, args, rows); err != nil {
+ return err
+ }
+ defer rows.Close()
+ return sql.ScanSlice(rows, v)
+}
+
+// UserLoginHistorySelect is the builder for selecting fields of UserLoginHistory entities.
+type UserLoginHistorySelect struct {
+ *UserLoginHistoryQuery
+ selector
+}
+
+// Aggregate adds the given aggregation functions to the selector query.
+func (ulhs *UserLoginHistorySelect) Aggregate(fns ...AggregateFunc) *UserLoginHistorySelect {
+ ulhs.fns = append(ulhs.fns, fns...)
+ return ulhs
+}
+
+// Scan applies the selector query and scans the result into the given value.
+func (ulhs *UserLoginHistorySelect) Scan(ctx context.Context, v any) error {
+ ctx = setContextOp(ctx, ulhs.ctx, ent.OpQuerySelect)
+ if err := ulhs.prepareQuery(ctx); err != nil {
+ return err
+ }
+ return scanWithInterceptors[*UserLoginHistoryQuery, *UserLoginHistorySelect](ctx, ulhs.UserLoginHistoryQuery, ulhs, ulhs.inters, v)
+}
+
+func (ulhs *UserLoginHistorySelect) sqlScan(ctx context.Context, root *UserLoginHistoryQuery, v any) error {
+ selector := root.sqlQuery(ctx)
+ aggregation := make([]string, 0, len(ulhs.fns))
+ for _, fn := range ulhs.fns {
+ aggregation = append(aggregation, fn(selector))
+ }
+ switch n := len(*ulhs.selector.flds); {
+ case n == 0 && len(aggregation) > 0:
+ selector.Select(aggregation...)
+ case n != 0 && len(aggregation) > 0:
+ selector.AppendSelect(aggregation...)
+ }
+ rows := &sql.Rows{}
+ query, args := selector.Query()
+ if err := ulhs.driver.Query(ctx, query, args, rows); err != nil {
+ return err
+ }
+ defer rows.Close()
+ return sql.ScanSlice(rows, v)
+}
+
+// Modify adds a query modifier for attaching custom logic to queries.
+func (ulhs *UserLoginHistorySelect) Modify(modifiers ...func(s *sql.Selector)) *UserLoginHistorySelect {
+ ulhs.modifiers = append(ulhs.modifiers, modifiers...)
+ return ulhs
+}
diff --git a/backend/db/userloginhistory_update.go b/backend/db/userloginhistory_update.go
new file mode 100644
index 0000000..a48522c
--- /dev/null
+++ b/backend/db/userloginhistory_update.go
@@ -0,0 +1,642 @@
+// Code generated by ent, DO NOT EDIT.
+
+package db
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "time"
+
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/dialect/sql/sqlgraph"
+ "entgo.io/ent/schema/field"
+ "github.com/chaitin/MonkeyCode/backend/db/predicate"
+ "github.com/chaitin/MonkeyCode/backend/db/user"
+ "github.com/chaitin/MonkeyCode/backend/db/userloginhistory"
+ "github.com/google/uuid"
+)
+
+// UserLoginHistoryUpdate is the builder for updating UserLoginHistory entities.
+type UserLoginHistoryUpdate struct {
+ config
+ hooks []Hook
+ mutation *UserLoginHistoryMutation
+ modifiers []func(*sql.UpdateBuilder)
+}
+
+// Where appends a list predicates to the UserLoginHistoryUpdate builder.
+func (ulhu *UserLoginHistoryUpdate) Where(ps ...predicate.UserLoginHistory) *UserLoginHistoryUpdate {
+ ulhu.mutation.Where(ps...)
+ return ulhu
+}
+
+// SetUserID sets the "user_id" field.
+func (ulhu *UserLoginHistoryUpdate) SetUserID(u uuid.UUID) *UserLoginHistoryUpdate {
+ ulhu.mutation.SetUserID(u)
+ return ulhu
+}
+
+// SetNillableUserID sets the "user_id" field if the given value is not nil.
+func (ulhu *UserLoginHistoryUpdate) SetNillableUserID(u *uuid.UUID) *UserLoginHistoryUpdate {
+ if u != nil {
+ ulhu.SetUserID(*u)
+ }
+ return ulhu
+}
+
+// SetIP sets the "ip" field.
+func (ulhu *UserLoginHistoryUpdate) SetIP(s string) *UserLoginHistoryUpdate {
+ ulhu.mutation.SetIP(s)
+ return ulhu
+}
+
+// SetNillableIP sets the "ip" field if the given value is not nil.
+func (ulhu *UserLoginHistoryUpdate) SetNillableIP(s *string) *UserLoginHistoryUpdate {
+ if s != nil {
+ ulhu.SetIP(*s)
+ }
+ return ulhu
+}
+
+// SetCountry sets the "country" field.
+func (ulhu *UserLoginHistoryUpdate) SetCountry(s string) *UserLoginHistoryUpdate {
+ ulhu.mutation.SetCountry(s)
+ return ulhu
+}
+
+// SetNillableCountry sets the "country" field if the given value is not nil.
+func (ulhu *UserLoginHistoryUpdate) SetNillableCountry(s *string) *UserLoginHistoryUpdate {
+ if s != nil {
+ ulhu.SetCountry(*s)
+ }
+ return ulhu
+}
+
+// SetProvince sets the "province" field.
+func (ulhu *UserLoginHistoryUpdate) SetProvince(s string) *UserLoginHistoryUpdate {
+ ulhu.mutation.SetProvince(s)
+ return ulhu
+}
+
+// SetNillableProvince sets the "province" field if the given value is not nil.
+func (ulhu *UserLoginHistoryUpdate) SetNillableProvince(s *string) *UserLoginHistoryUpdate {
+ if s != nil {
+ ulhu.SetProvince(*s)
+ }
+ return ulhu
+}
+
+// SetCity sets the "city" field.
+func (ulhu *UserLoginHistoryUpdate) SetCity(s string) *UserLoginHistoryUpdate {
+ ulhu.mutation.SetCity(s)
+ return ulhu
+}
+
+// SetNillableCity sets the "city" field if the given value is not nil.
+func (ulhu *UserLoginHistoryUpdate) SetNillableCity(s *string) *UserLoginHistoryUpdate {
+ if s != nil {
+ ulhu.SetCity(*s)
+ }
+ return ulhu
+}
+
+// SetIsp sets the "isp" field.
+func (ulhu *UserLoginHistoryUpdate) SetIsp(s string) *UserLoginHistoryUpdate {
+ ulhu.mutation.SetIsp(s)
+ return ulhu
+}
+
+// SetNillableIsp sets the "isp" field if the given value is not nil.
+func (ulhu *UserLoginHistoryUpdate) SetNillableIsp(s *string) *UserLoginHistoryUpdate {
+ if s != nil {
+ ulhu.SetIsp(*s)
+ }
+ return ulhu
+}
+
+// SetAsn sets the "asn" field.
+func (ulhu *UserLoginHistoryUpdate) SetAsn(s string) *UserLoginHistoryUpdate {
+ ulhu.mutation.SetAsn(s)
+ return ulhu
+}
+
+// SetNillableAsn sets the "asn" field if the given value is not nil.
+func (ulhu *UserLoginHistoryUpdate) SetNillableAsn(s *string) *UserLoginHistoryUpdate {
+ if s != nil {
+ ulhu.SetAsn(*s)
+ }
+ return ulhu
+}
+
+// SetClientVersion sets the "client_version" field.
+func (ulhu *UserLoginHistoryUpdate) SetClientVersion(s string) *UserLoginHistoryUpdate {
+ ulhu.mutation.SetClientVersion(s)
+ return ulhu
+}
+
+// SetNillableClientVersion sets the "client_version" field if the given value is not nil.
+func (ulhu *UserLoginHistoryUpdate) SetNillableClientVersion(s *string) *UserLoginHistoryUpdate {
+ if s != nil {
+ ulhu.SetClientVersion(*s)
+ }
+ return ulhu
+}
+
+// SetDevice sets the "device" field.
+func (ulhu *UserLoginHistoryUpdate) SetDevice(s string) *UserLoginHistoryUpdate {
+ ulhu.mutation.SetDevice(s)
+ return ulhu
+}
+
+// SetNillableDevice sets the "device" field if the given value is not nil.
+func (ulhu *UserLoginHistoryUpdate) SetNillableDevice(s *string) *UserLoginHistoryUpdate {
+ if s != nil {
+ ulhu.SetDevice(*s)
+ }
+ return ulhu
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (ulhu *UserLoginHistoryUpdate) SetCreatedAt(t time.Time) *UserLoginHistoryUpdate {
+ ulhu.mutation.SetCreatedAt(t)
+ return ulhu
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (ulhu *UserLoginHistoryUpdate) SetNillableCreatedAt(t *time.Time) *UserLoginHistoryUpdate {
+ if t != nil {
+ ulhu.SetCreatedAt(*t)
+ }
+ return ulhu
+}
+
+// SetOwnerID sets the "owner" edge to the User entity by ID.
+func (ulhu *UserLoginHistoryUpdate) SetOwnerID(id uuid.UUID) *UserLoginHistoryUpdate {
+ ulhu.mutation.SetOwnerID(id)
+ return ulhu
+}
+
+// SetNillableOwnerID sets the "owner" edge to the User entity by ID if the given value is not nil.
+func (ulhu *UserLoginHistoryUpdate) SetNillableOwnerID(id *uuid.UUID) *UserLoginHistoryUpdate {
+ if id != nil {
+ ulhu = ulhu.SetOwnerID(*id)
+ }
+ return ulhu
+}
+
+// SetOwner sets the "owner" edge to the User entity.
+func (ulhu *UserLoginHistoryUpdate) SetOwner(u *User) *UserLoginHistoryUpdate {
+ return ulhu.SetOwnerID(u.ID)
+}
+
+// Mutation returns the UserLoginHistoryMutation object of the builder.
+func (ulhu *UserLoginHistoryUpdate) Mutation() *UserLoginHistoryMutation {
+ return ulhu.mutation
+}
+
+// ClearOwner clears the "owner" edge to the User entity.
+func (ulhu *UserLoginHistoryUpdate) ClearOwner() *UserLoginHistoryUpdate {
+ ulhu.mutation.ClearOwner()
+ return ulhu
+}
+
+// Save executes the query and returns the number of nodes affected by the update operation.
+func (ulhu *UserLoginHistoryUpdate) Save(ctx context.Context) (int, error) {
+ return withHooks(ctx, ulhu.sqlSave, ulhu.mutation, ulhu.hooks)
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (ulhu *UserLoginHistoryUpdate) SaveX(ctx context.Context) int {
+ affected, err := ulhu.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return affected
+}
+
+// Exec executes the query.
+func (ulhu *UserLoginHistoryUpdate) Exec(ctx context.Context) error {
+ _, err := ulhu.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (ulhu *UserLoginHistoryUpdate) ExecX(ctx context.Context) {
+ if err := ulhu.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
+func (ulhu *UserLoginHistoryUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *UserLoginHistoryUpdate {
+ ulhu.modifiers = append(ulhu.modifiers, modifiers...)
+ return ulhu
+}
+
+func (ulhu *UserLoginHistoryUpdate) sqlSave(ctx context.Context) (n int, err error) {
+ _spec := sqlgraph.NewUpdateSpec(userloginhistory.Table, userloginhistory.Columns, sqlgraph.NewFieldSpec(userloginhistory.FieldID, field.TypeUUID))
+ if ps := ulhu.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if value, ok := ulhu.mutation.UserID(); ok {
+ _spec.SetField(userloginhistory.FieldUserID, field.TypeUUID, value)
+ }
+ if value, ok := ulhu.mutation.IP(); ok {
+ _spec.SetField(userloginhistory.FieldIP, field.TypeString, value)
+ }
+ if value, ok := ulhu.mutation.Country(); ok {
+ _spec.SetField(userloginhistory.FieldCountry, field.TypeString, value)
+ }
+ if value, ok := ulhu.mutation.Province(); ok {
+ _spec.SetField(userloginhistory.FieldProvince, field.TypeString, value)
+ }
+ if value, ok := ulhu.mutation.City(); ok {
+ _spec.SetField(userloginhistory.FieldCity, field.TypeString, value)
+ }
+ if value, ok := ulhu.mutation.Isp(); ok {
+ _spec.SetField(userloginhistory.FieldIsp, field.TypeString, value)
+ }
+ if value, ok := ulhu.mutation.Asn(); ok {
+ _spec.SetField(userloginhistory.FieldAsn, field.TypeString, value)
+ }
+ if value, ok := ulhu.mutation.ClientVersion(); ok {
+ _spec.SetField(userloginhistory.FieldClientVersion, field.TypeString, value)
+ }
+ if value, ok := ulhu.mutation.Device(); ok {
+ _spec.SetField(userloginhistory.FieldDevice, field.TypeString, value)
+ }
+ if value, ok := ulhu.mutation.CreatedAt(); ok {
+ _spec.SetField(userloginhistory.FieldCreatedAt, field.TypeTime, value)
+ }
+ if ulhu.mutation.OwnerCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: true,
+ Table: userloginhistory.OwnerTable,
+ Columns: []string{userloginhistory.OwnerColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID),
+ },
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := ulhu.mutation.OwnerIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: true,
+ Table: userloginhistory.OwnerTable,
+ Columns: []string{userloginhistory.OwnerColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Add = append(_spec.Edges.Add, edge)
+ }
+ _spec.AddModifiers(ulhu.modifiers...)
+ if n, err = sqlgraph.UpdateNodes(ctx, ulhu.driver, _spec); err != nil {
+ if _, ok := err.(*sqlgraph.NotFoundError); ok {
+ err = &NotFoundError{userloginhistory.Label}
+ } else if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return 0, err
+ }
+ ulhu.mutation.done = true
+ return n, nil
+}
+
+// UserLoginHistoryUpdateOne is the builder for updating a single UserLoginHistory entity.
+type UserLoginHistoryUpdateOne struct {
+ config
+ fields []string
+ hooks []Hook
+ mutation *UserLoginHistoryMutation
+ modifiers []func(*sql.UpdateBuilder)
+}
+
+// SetUserID sets the "user_id" field.
+func (ulhuo *UserLoginHistoryUpdateOne) SetUserID(u uuid.UUID) *UserLoginHistoryUpdateOne {
+ ulhuo.mutation.SetUserID(u)
+ return ulhuo
+}
+
+// SetNillableUserID sets the "user_id" field if the given value is not nil.
+func (ulhuo *UserLoginHistoryUpdateOne) SetNillableUserID(u *uuid.UUID) *UserLoginHistoryUpdateOne {
+ if u != nil {
+ ulhuo.SetUserID(*u)
+ }
+ return ulhuo
+}
+
+// SetIP sets the "ip" field.
+func (ulhuo *UserLoginHistoryUpdateOne) SetIP(s string) *UserLoginHistoryUpdateOne {
+ ulhuo.mutation.SetIP(s)
+ return ulhuo
+}
+
+// SetNillableIP sets the "ip" field if the given value is not nil.
+func (ulhuo *UserLoginHistoryUpdateOne) SetNillableIP(s *string) *UserLoginHistoryUpdateOne {
+ if s != nil {
+ ulhuo.SetIP(*s)
+ }
+ return ulhuo
+}
+
+// SetCountry sets the "country" field.
+func (ulhuo *UserLoginHistoryUpdateOne) SetCountry(s string) *UserLoginHistoryUpdateOne {
+ ulhuo.mutation.SetCountry(s)
+ return ulhuo
+}
+
+// SetNillableCountry sets the "country" field if the given value is not nil.
+func (ulhuo *UserLoginHistoryUpdateOne) SetNillableCountry(s *string) *UserLoginHistoryUpdateOne {
+ if s != nil {
+ ulhuo.SetCountry(*s)
+ }
+ return ulhuo
+}
+
+// SetProvince sets the "province" field.
+func (ulhuo *UserLoginHistoryUpdateOne) SetProvince(s string) *UserLoginHistoryUpdateOne {
+ ulhuo.mutation.SetProvince(s)
+ return ulhuo
+}
+
+// SetNillableProvince sets the "province" field if the given value is not nil.
+func (ulhuo *UserLoginHistoryUpdateOne) SetNillableProvince(s *string) *UserLoginHistoryUpdateOne {
+ if s != nil {
+ ulhuo.SetProvince(*s)
+ }
+ return ulhuo
+}
+
+// SetCity sets the "city" field.
+func (ulhuo *UserLoginHistoryUpdateOne) SetCity(s string) *UserLoginHistoryUpdateOne {
+ ulhuo.mutation.SetCity(s)
+ return ulhuo
+}
+
+// SetNillableCity sets the "city" field if the given value is not nil.
+func (ulhuo *UserLoginHistoryUpdateOne) SetNillableCity(s *string) *UserLoginHistoryUpdateOne {
+ if s != nil {
+ ulhuo.SetCity(*s)
+ }
+ return ulhuo
+}
+
+// SetIsp sets the "isp" field.
+func (ulhuo *UserLoginHistoryUpdateOne) SetIsp(s string) *UserLoginHistoryUpdateOne {
+ ulhuo.mutation.SetIsp(s)
+ return ulhuo
+}
+
+// SetNillableIsp sets the "isp" field if the given value is not nil.
+func (ulhuo *UserLoginHistoryUpdateOne) SetNillableIsp(s *string) *UserLoginHistoryUpdateOne {
+ if s != nil {
+ ulhuo.SetIsp(*s)
+ }
+ return ulhuo
+}
+
+// SetAsn sets the "asn" field.
+func (ulhuo *UserLoginHistoryUpdateOne) SetAsn(s string) *UserLoginHistoryUpdateOne {
+ ulhuo.mutation.SetAsn(s)
+ return ulhuo
+}
+
+// SetNillableAsn sets the "asn" field if the given value is not nil.
+func (ulhuo *UserLoginHistoryUpdateOne) SetNillableAsn(s *string) *UserLoginHistoryUpdateOne {
+ if s != nil {
+ ulhuo.SetAsn(*s)
+ }
+ return ulhuo
+}
+
+// SetClientVersion sets the "client_version" field.
+func (ulhuo *UserLoginHistoryUpdateOne) SetClientVersion(s string) *UserLoginHistoryUpdateOne {
+ ulhuo.mutation.SetClientVersion(s)
+ return ulhuo
+}
+
+// SetNillableClientVersion sets the "client_version" field if the given value is not nil.
+func (ulhuo *UserLoginHistoryUpdateOne) SetNillableClientVersion(s *string) *UserLoginHistoryUpdateOne {
+ if s != nil {
+ ulhuo.SetClientVersion(*s)
+ }
+ return ulhuo
+}
+
+// SetDevice sets the "device" field.
+func (ulhuo *UserLoginHistoryUpdateOne) SetDevice(s string) *UserLoginHistoryUpdateOne {
+ ulhuo.mutation.SetDevice(s)
+ return ulhuo
+}
+
+// SetNillableDevice sets the "device" field if the given value is not nil.
+func (ulhuo *UserLoginHistoryUpdateOne) SetNillableDevice(s *string) *UserLoginHistoryUpdateOne {
+ if s != nil {
+ ulhuo.SetDevice(*s)
+ }
+ return ulhuo
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (ulhuo *UserLoginHistoryUpdateOne) SetCreatedAt(t time.Time) *UserLoginHistoryUpdateOne {
+ ulhuo.mutation.SetCreatedAt(t)
+ return ulhuo
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (ulhuo *UserLoginHistoryUpdateOne) SetNillableCreatedAt(t *time.Time) *UserLoginHistoryUpdateOne {
+ if t != nil {
+ ulhuo.SetCreatedAt(*t)
+ }
+ return ulhuo
+}
+
+// SetOwnerID sets the "owner" edge to the User entity by ID.
+func (ulhuo *UserLoginHistoryUpdateOne) SetOwnerID(id uuid.UUID) *UserLoginHistoryUpdateOne {
+ ulhuo.mutation.SetOwnerID(id)
+ return ulhuo
+}
+
+// SetNillableOwnerID sets the "owner" edge to the User entity by ID if the given value is not nil.
+func (ulhuo *UserLoginHistoryUpdateOne) SetNillableOwnerID(id *uuid.UUID) *UserLoginHistoryUpdateOne {
+ if id != nil {
+ ulhuo = ulhuo.SetOwnerID(*id)
+ }
+ return ulhuo
+}
+
+// SetOwner sets the "owner" edge to the User entity.
+func (ulhuo *UserLoginHistoryUpdateOne) SetOwner(u *User) *UserLoginHistoryUpdateOne {
+ return ulhuo.SetOwnerID(u.ID)
+}
+
+// Mutation returns the UserLoginHistoryMutation object of the builder.
+func (ulhuo *UserLoginHistoryUpdateOne) Mutation() *UserLoginHistoryMutation {
+ return ulhuo.mutation
+}
+
+// ClearOwner clears the "owner" edge to the User entity.
+func (ulhuo *UserLoginHistoryUpdateOne) ClearOwner() *UserLoginHistoryUpdateOne {
+ ulhuo.mutation.ClearOwner()
+ return ulhuo
+}
+
+// Where appends a list predicates to the UserLoginHistoryUpdate builder.
+func (ulhuo *UserLoginHistoryUpdateOne) Where(ps ...predicate.UserLoginHistory) *UserLoginHistoryUpdateOne {
+ ulhuo.mutation.Where(ps...)
+ return ulhuo
+}
+
+// Select allows selecting one or more fields (columns) of the returned entity.
+// The default is selecting all fields defined in the entity schema.
+func (ulhuo *UserLoginHistoryUpdateOne) Select(field string, fields ...string) *UserLoginHistoryUpdateOne {
+ ulhuo.fields = append([]string{field}, fields...)
+ return ulhuo
+}
+
+// Save executes the query and returns the updated UserLoginHistory entity.
+func (ulhuo *UserLoginHistoryUpdateOne) Save(ctx context.Context) (*UserLoginHistory, error) {
+ return withHooks(ctx, ulhuo.sqlSave, ulhuo.mutation, ulhuo.hooks)
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (ulhuo *UserLoginHistoryUpdateOne) SaveX(ctx context.Context) *UserLoginHistory {
+ node, err := ulhuo.Save(ctx)
+ if err != nil {
+ panic(err)
+ }
+ return node
+}
+
+// Exec executes the query on the entity.
+func (ulhuo *UserLoginHistoryUpdateOne) Exec(ctx context.Context) error {
+ _, err := ulhuo.Save(ctx)
+ return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (ulhuo *UserLoginHistoryUpdateOne) ExecX(ctx context.Context) {
+ if err := ulhuo.Exec(ctx); err != nil {
+ panic(err)
+ }
+}
+
+// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
+func (ulhuo *UserLoginHistoryUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *UserLoginHistoryUpdateOne {
+ ulhuo.modifiers = append(ulhuo.modifiers, modifiers...)
+ return ulhuo
+}
+
+func (ulhuo *UserLoginHistoryUpdateOne) sqlSave(ctx context.Context) (_node *UserLoginHistory, err error) {
+ _spec := sqlgraph.NewUpdateSpec(userloginhistory.Table, userloginhistory.Columns, sqlgraph.NewFieldSpec(userloginhistory.FieldID, field.TypeUUID))
+ id, ok := ulhuo.mutation.ID()
+ if !ok {
+ return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "UserLoginHistory.id" for update`)}
+ }
+ _spec.Node.ID.Value = id
+ if fields := ulhuo.fields; len(fields) > 0 {
+ _spec.Node.Columns = make([]string, 0, len(fields))
+ _spec.Node.Columns = append(_spec.Node.Columns, userloginhistory.FieldID)
+ for _, f := range fields {
+ if !userloginhistory.ValidColumn(f) {
+ return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
+ }
+ if f != userloginhistory.FieldID {
+ _spec.Node.Columns = append(_spec.Node.Columns, f)
+ }
+ }
+ }
+ if ps := ulhuo.mutation.predicates; len(ps) > 0 {
+ _spec.Predicate = func(selector *sql.Selector) {
+ for i := range ps {
+ ps[i](selector)
+ }
+ }
+ }
+ if value, ok := ulhuo.mutation.UserID(); ok {
+ _spec.SetField(userloginhistory.FieldUserID, field.TypeUUID, value)
+ }
+ if value, ok := ulhuo.mutation.IP(); ok {
+ _spec.SetField(userloginhistory.FieldIP, field.TypeString, value)
+ }
+ if value, ok := ulhuo.mutation.Country(); ok {
+ _spec.SetField(userloginhistory.FieldCountry, field.TypeString, value)
+ }
+ if value, ok := ulhuo.mutation.Province(); ok {
+ _spec.SetField(userloginhistory.FieldProvince, field.TypeString, value)
+ }
+ if value, ok := ulhuo.mutation.City(); ok {
+ _spec.SetField(userloginhistory.FieldCity, field.TypeString, value)
+ }
+ if value, ok := ulhuo.mutation.Isp(); ok {
+ _spec.SetField(userloginhistory.FieldIsp, field.TypeString, value)
+ }
+ if value, ok := ulhuo.mutation.Asn(); ok {
+ _spec.SetField(userloginhistory.FieldAsn, field.TypeString, value)
+ }
+ if value, ok := ulhuo.mutation.ClientVersion(); ok {
+ _spec.SetField(userloginhistory.FieldClientVersion, field.TypeString, value)
+ }
+ if value, ok := ulhuo.mutation.Device(); ok {
+ _spec.SetField(userloginhistory.FieldDevice, field.TypeString, value)
+ }
+ if value, ok := ulhuo.mutation.CreatedAt(); ok {
+ _spec.SetField(userloginhistory.FieldCreatedAt, field.TypeTime, value)
+ }
+ if ulhuo.mutation.OwnerCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: true,
+ Table: userloginhistory.OwnerTable,
+ Columns: []string{userloginhistory.OwnerColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID),
+ },
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := ulhuo.mutation.OwnerIDs(); len(nodes) > 0 {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2O,
+ Inverse: true,
+ Table: userloginhistory.OwnerTable,
+ Columns: []string{userloginhistory.OwnerColumn},
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID),
+ },
+ }
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
+ _spec.Edges.Add = append(_spec.Edges.Add, edge)
+ }
+ _spec.AddModifiers(ulhuo.modifiers...)
+ _node = &UserLoginHistory{config: ulhuo.config}
+ _spec.Assign = _node.assignValues
+ _spec.ScanValues = _node.scanValues
+ if err = sqlgraph.UpdateNode(ctx, ulhuo.driver, _spec); err != nil {
+ if _, ok := err.(*sqlgraph.NotFoundError); ok {
+ err = &NotFoundError{userloginhistory.Label}
+ } else if sqlgraph.IsConstraintError(err) {
+ err = &ConstraintError{msg: err.Error(), wrap: err}
+ }
+ return nil, err
+ }
+ ulhuo.mutation.done = true
+ return _node, nil
+}
diff --git a/backend/docs/docs.go b/backend/docs/docs.go
new file mode 100644
index 0000000..0047c04
--- /dev/null
+++ b/backend/docs/docs.go
@@ -0,0 +1,6 @@
+package docs
+
+import _ "embed"
+
+//go:embed swagger.json
+var SwaggerJSON []byte
diff --git a/backend/docs/swagger.json b/backend/docs/swagger.json
new file mode 100644
index 0000000..715ad54
--- /dev/null
+++ b/backend/docs/swagger.json
@@ -0,0 +1,2824 @@
+{
+ "swagger": "2.0",
+ "info": {
+ "description": "MonkeyCode API",
+ "title": "MonkeyCode API",
+ "contact": {},
+ "version": "1.0"
+ },
+ "paths": {
+ "/api/v1/admin/create": {
+ "post": {
+ "description": "创建管理员",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "User"
+ ],
+ "summary": "创建管理员",
+ "operationId": "create-admin",
+ "parameters": [
+ {
+ "description": "创建管理员参数",
+ "name": "param",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/domain.CreateAdminReq"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/web.Resp"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/domain.AdminUser"
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ }
+ },
+ "/api/v1/admin/delete": {
+ "delete": {
+ "description": "删除管理员",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "User"
+ ],
+ "summary": "删除管理员",
+ "operationId": "delete-admin",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "管理员ID",
+ "name": "id",
+ "in": "query",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/web.Resp"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "type": "object"
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ }
+ },
+ "/api/v1/admin/list": {
+ "get": {
+ "description": "获取管理员用户列表",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "User"
+ ],
+ "summary": "获取管理员用户列表",
+ "operationId": "list-admin-user",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "下一页标识",
+ "name": "next_token",
+ "in": "query"
+ },
+ {
+ "type": "integer",
+ "description": "分页",
+ "name": "page",
+ "in": "query"
+ },
+ {
+ "type": "integer",
+ "description": "每页多少条记录",
+ "name": "size",
+ "in": "query"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/web.Resp"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/domain.ListAdminUserResp"
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ }
+ },
+ "/api/v1/admin/login": {
+ "post": {
+ "description": "管理员登录",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "User"
+ ],
+ "summary": "管理员登录",
+ "operationId": "admin-login",
+ "parameters": [
+ {
+ "description": "登录参数",
+ "name": "param",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/domain.LoginReq"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/web.Resp"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/domain.AdminUser"
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ }
+ },
+ "/api/v1/admin/login-history": {
+ "get": {
+ "description": "获取管理员登录历史",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "User"
+ ],
+ "summary": "获取管理员登录历史",
+ "operationId": "admin-login-history",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "下一页标识",
+ "name": "next_token",
+ "in": "query"
+ },
+ {
+ "type": "integer",
+ "description": "分页",
+ "name": "page",
+ "in": "query"
+ },
+ {
+ "type": "integer",
+ "description": "每页多少条记录",
+ "name": "size",
+ "in": "query"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/web.Resp"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/domain.ListAdminLoginHistoryResp"
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ }
+ },
+ "/api/v1/admin/setting": {
+ "get": {
+ "description": "获取系统设置",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "User"
+ ],
+ "summary": "获取系统设置",
+ "operationId": "get-setting",
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/web.Resp"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/domain.Setting"
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ },
+ "put": {
+ "description": "更新系统设置",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "User"
+ ],
+ "summary": "更新系统设置",
+ "operationId": "update-setting",
+ "parameters": [
+ {
+ "description": "更新系统设置参数",
+ "name": "param",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/domain.UpdateSettingReq"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/web.Resp"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/domain.Setting"
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ }
+ },
+ "/api/v1/billing/chat/info": {
+ "get": {
+ "description": "获取对话内容",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Billing"
+ ],
+ "summary": "获取对话内容",
+ "operationId": "chat-info",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "对话记录ID",
+ "name": "id",
+ "in": "query",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/web.Resp"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/domain.ChatInfo"
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ }
+ },
+ "/api/v1/billing/chat/record": {
+ "get": {
+ "description": "获取对话记录",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Billing"
+ ],
+ "summary": "获取对话记录",
+ "operationId": "list-chat-record",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "下一页标识",
+ "name": "next_token",
+ "in": "query"
+ },
+ {
+ "type": "integer",
+ "description": "分页",
+ "name": "page",
+ "in": "query"
+ },
+ {
+ "type": "integer",
+ "description": "每页多少条记录",
+ "name": "size",
+ "in": "query"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/web.Resp"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/domain.ListChatRecordResp"
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ }
+ },
+ "/api/v1/billing/completion/info": {
+ "get": {
+ "description": "获取补全内容",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Billing"
+ ],
+ "summary": "获取补全内容",
+ "operationId": "completion-info",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "补全记录ID",
+ "name": "id",
+ "in": "query",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/web.Resp"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/domain.CompletionInfo"
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ }
+ },
+ "/api/v1/billing/completion/record": {
+ "get": {
+ "description": "获取补全记录",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Billing"
+ ],
+ "summary": "获取补全记录",
+ "operationId": "list-completion-record",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "下一页标识",
+ "name": "next_token",
+ "in": "query"
+ },
+ {
+ "type": "integer",
+ "description": "分页",
+ "name": "page",
+ "in": "query"
+ },
+ {
+ "type": "integer",
+ "description": "每页多少条记录",
+ "name": "size",
+ "in": "query"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/web.Resp"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/domain.ListCompletionRecordResp"
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ }
+ },
+ "/api/v1/dashboard/category-stat": {
+ "get": {
+ "description": "获取分类统计信息",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Dashboard"
+ ],
+ "summary": "获取分类统计信息",
+ "operationId": "category-stat-dashboard",
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/web.Resp"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/domain.CategoryStat"
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ }
+ },
+ "/api/v1/dashboard/statistics": {
+ "get": {
+ "description": "获取统计信息",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Dashboard"
+ ],
+ "summary": "获取统计信息",
+ "operationId": "statistics-dashboard",
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/web.Resp"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/domain.Statistics"
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ }
+ },
+ "/api/v1/dashboard/time-stat": {
+ "get": {
+ "description": "获取时间统计信息",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Dashboard"
+ ],
+ "summary": "获取时间统计信息",
+ "operationId": "time-stat-dashboard",
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/web.Resp"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/domain.TimeStat"
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ }
+ },
+ "/api/v1/dashboard/user-code-rank": {
+ "get": {
+ "description": "用户贡献榜",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Dashboard"
+ ],
+ "summary": "用户贡献榜",
+ "operationId": "user-code-rank-dashboard",
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/web.Resp"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/domain.UserCodeRank"
+ }
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ }
+ },
+ "/api/v1/dashboard/user-events": {
+ "get": {
+ "description": "获取用户事件",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Dashboard"
+ ],
+ "summary": "获取用户事件",
+ "operationId": "user-events-dashboard",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "用户ID",
+ "name": "user_id",
+ "in": "query",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/web.Resp"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/domain.UserEvent"
+ }
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ }
+ },
+ "/api/v1/dashboard/user-heatmap": {
+ "get": {
+ "description": "用户热力图",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Dashboard"
+ ],
+ "summary": "用户热力图",
+ "operationId": "user-heatmap-dashboard",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "用户ID",
+ "name": "user_id",
+ "in": "query",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/web.Resp"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/domain.UserHeatmapResp"
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ }
+ },
+ "/api/v1/dashboard/user-stat": {
+ "get": {
+ "description": "获取用户统计信息",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Dashboard"
+ ],
+ "summary": "获取用户统计信息",
+ "operationId": "user-stat-dashboard",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "用户ID",
+ "name": "user_id",
+ "in": "query"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/web.Resp"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/domain.UserStat"
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ }
+ },
+ "/api/v1/model": {
+ "get": {
+ "description": "获取模型列表",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Model"
+ ],
+ "summary": "获取模型列表",
+ "operationId": "list-model",
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/web.Resp"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/domain.AllModelResp"
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ },
+ "put": {
+ "description": "更新模型",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Model"
+ ],
+ "summary": "更新模型",
+ "operationId": "update-model",
+ "parameters": [
+ {
+ "description": "模型",
+ "name": "model",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/domain.UpdateModelReq"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/web.Resp"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/domain.Model"
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ },
+ "post": {
+ "description": "创建模型",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Model"
+ ],
+ "summary": "创建模型",
+ "operationId": "create-model",
+ "parameters": [
+ {
+ "description": "模型",
+ "name": "model",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/domain.CreateModelReq"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/web.Resp"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/domain.Model"
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ }
+ },
+ "/api/v1/model/check": {
+ "post": {
+ "description": "检查模型",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Model"
+ ],
+ "summary": "检查模型",
+ "operationId": "check-model",
+ "parameters": [
+ {
+ "description": "模型",
+ "name": "model",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/domain.CheckModelReq"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/web.Resp"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/domain.Model"
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ }
+ },
+ "/api/v1/model/my": {
+ "get": {
+ "description": "获取我的模型列表",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Model"
+ ],
+ "summary": "获取我的模型列表",
+ "operationId": "my-model-list",
+ "parameters": [
+ {
+ "enum": [
+ "llm",
+ "coder",
+ "embedding",
+ "audio",
+ "reranker"
+ ],
+ "type": "string",
+ "x-enum-varnames": [
+ "ModelTypeLLM",
+ "ModelTypeCoder",
+ "ModelTypeEmbedding",
+ "ModelTypeAudio",
+ "ModelTypeReranker"
+ ],
+ "description": "模型类型 llm:对话模型 coder:代码模型",
+ "name": "model_type",
+ "in": "query"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/web.Resp"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/domain.Model"
+ }
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ }
+ },
+ "/api/v1/model/token-usage": {
+ "get": {
+ "description": "获取模型token使用情况",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Model"
+ ],
+ "summary": "获取模型token使用情况",
+ "operationId": "get-token-usage",
+ "parameters": [
+ {
+ "enum": [
+ "llm",
+ "coder",
+ "embedding",
+ "audio",
+ "reranker"
+ ],
+ "type": "string",
+ "x-enum-varnames": [
+ "ModelTypeLLM",
+ "ModelTypeCoder",
+ "ModelTypeEmbedding",
+ "ModelTypeAudio",
+ "ModelTypeReranker"
+ ],
+ "description": "模型类型 llm:对话模型 coder:代码模型",
+ "name": "model_type",
+ "in": "query",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/web.Resp"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/domain.ModelTokenUsageResp"
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ }
+ },
+ "/api/v1/static/vsix": {
+ "get": {
+ "description": "下载VSCode插件",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/octet-stream"
+ ],
+ "tags": [
+ "User"
+ ],
+ "summary": "下载VSCode插件",
+ "operationId": "vsix-download",
+ "responses": {}
+ }
+ },
+ "/api/v1/user/delete": {
+ "delete": {
+ "description": "删除用户",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "User"
+ ],
+ "summary": "删除用户",
+ "operationId": "delete-user",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "用户ID",
+ "name": "id",
+ "in": "query",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/web.Resp"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "type": "object"
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ }
+ },
+ "/api/v1/user/invite": {
+ "get": {
+ "description": "获取用户邀请码",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "User"
+ ],
+ "summary": "获取用户邀请码",
+ "operationId": "invite",
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/web.Resp"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/domain.InviteResp"
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ }
+ },
+ "/api/v1/user/list": {
+ "get": {
+ "description": "获取用户列表",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "User"
+ ],
+ "summary": "获取用户列表",
+ "operationId": "list-user",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "下一页标识",
+ "name": "next_token",
+ "in": "query"
+ },
+ {
+ "type": "integer",
+ "description": "分页",
+ "name": "page",
+ "in": "query"
+ },
+ {
+ "type": "integer",
+ "description": "每页多少条记录",
+ "name": "size",
+ "in": "query"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/web.Resp"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/domain.ListUserResp"
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ }
+ },
+ "/api/v1/user/login": {
+ "post": {
+ "description": "用户登录",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "User"
+ ],
+ "summary": "用户登录",
+ "operationId": "login",
+ "parameters": [
+ {
+ "description": "登录参数",
+ "name": "param",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/domain.LoginReq"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/web.Resp"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/domain.LoginResp"
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ }
+ },
+ "/api/v1/user/login-history": {
+ "get": {
+ "description": "获取用户登录历史",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "User"
+ ],
+ "summary": "获取用户登录历史",
+ "operationId": "login-history",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "下一页标识",
+ "name": "next_token",
+ "in": "query"
+ },
+ {
+ "type": "integer",
+ "description": "分页",
+ "name": "page",
+ "in": "query"
+ },
+ {
+ "type": "integer",
+ "description": "每页多少条记录",
+ "name": "size",
+ "in": "query"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/web.Resp"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/domain.ListLoginHistoryResp"
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ }
+ },
+ "/api/v1/user/register": {
+ "post": {
+ "description": "注册用户",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "User"
+ ],
+ "summary": "注册用户",
+ "operationId": "register",
+ "parameters": [
+ {
+ "description": "注册参数",
+ "name": "param",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/domain.RegisterReq"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/web.Resp"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/domain.User"
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ }
+ },
+ "/api/v1/user/update": {
+ "put": {
+ "description": "更新用户",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "User"
+ ],
+ "summary": "更新用户",
+ "operationId": "update-user",
+ "parameters": [
+ {
+ "description": "更新用户参数",
+ "name": "param",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/domain.UpdateUserReq"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/web.Resp"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/domain.User"
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ }
+ },
+ "/v1/chat/completions": {
+ "post": {
+ "description": "处理聊天补全请求",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "OpenAIV1"
+ ],
+ "summary": "处理聊天补全请求",
+ "operationId": "chat-completion",
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "$ref": "#/definitions/web.Resp"
+ }
+ }
+ }
+ }
+ },
+ "/v1/completion/accept": {
+ "post": {
+ "description": "接受补全请求",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "OpenAIV1"
+ ],
+ "summary": "接受补全请求",
+ "operationId": "accept-completion",
+ "parameters": [
+ {
+ "description": "补全请求",
+ "name": "param",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/domain.AcceptCompletionReq"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "$ref": "#/definitions/web.Resp"
+ }
+ }
+ }
+ }
+ },
+ "/v1/completions": {
+ "post": {
+ "description": "处理文本补全请求",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "OpenAIV1"
+ ],
+ "summary": "处理文本补全请求",
+ "operationId": "completions",
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "$ref": "#/definitions/web.Resp"
+ }
+ }
+ }
+ }
+ },
+ "/v1/embeddings": {
+ "post": {
+ "description": "处理嵌入请求",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "OpenAIV1"
+ ],
+ "summary": "处理嵌入请求",
+ "operationId": "embeddings",
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "$ref": "#/definitions/web.Resp"
+ }
+ }
+ }
+ }
+ },
+ "/v1/models": {
+ "get": {
+ "description": "模型列表",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "OpenAIV1"
+ ],
+ "summary": "模型列表",
+ "operationId": "model-list",
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/definitions/web.Resp"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "data": {
+ "$ref": "#/definitions/domain.ModelListResp"
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ }
+ }
+ },
+ "definitions": {
+ "consts.AdminStatus": {
+ "type": "string",
+ "enum": [
+ "active",
+ "inactive"
+ ],
+ "x-enum-varnames": [
+ "AdminStatusActive",
+ "AdminStatusInactive"
+ ]
+ },
+ "consts.ModelStatus": {
+ "type": "string",
+ "enum": [
+ "active",
+ "inactive"
+ ],
+ "x-enum-varnames": [
+ "ModelStatusActive",
+ "ModelStatusInactive"
+ ]
+ },
+ "consts.ModelType": {
+ "type": "string",
+ "enum": [
+ "llm",
+ "coder",
+ "embedding",
+ "audio",
+ "reranker"
+ ],
+ "x-enum-varnames": [
+ "ModelTypeLLM",
+ "ModelTypeCoder",
+ "ModelTypeEmbedding",
+ "ModelTypeAudio",
+ "ModelTypeReranker"
+ ]
+ },
+ "consts.UserStatus": {
+ "type": "string",
+ "enum": [
+ "active",
+ "inactive",
+ "locked"
+ ],
+ "x-enum-varnames": [
+ "UserStatusActive",
+ "UserStatusInactive",
+ "UserStatusLocked"
+ ]
+ },
+ "domain.AcceptCompletionReq": {
+ "type": "object",
+ "properties": {
+ "completion": {
+ "description": "补全内容",
+ "type": "string"
+ },
+ "id": {
+ "description": "记录ID",
+ "type": "string"
+ }
+ }
+ },
+ "domain.AdminLoginHistory": {
+ "type": "object",
+ "properties": {
+ "client_version": {
+ "description": "客户端版本",
+ "type": "string"
+ },
+ "created_at": {
+ "description": "登录时间",
+ "type": "integer"
+ },
+ "device": {
+ "description": "设备信息",
+ "type": "string"
+ },
+ "ip_info": {
+ "description": "IP信息",
+ "allOf": [
+ {
+ "$ref": "#/definitions/domain.IPInfo"
+ }
+ ]
+ },
+ "user": {
+ "description": "用户信息",
+ "allOf": [
+ {
+ "$ref": "#/definitions/domain.AdminUser"
+ }
+ ]
+ }
+ }
+ },
+ "domain.AdminUser": {
+ "type": "object",
+ "properties": {
+ "created_at": {
+ "description": "创建时间",
+ "type": "integer"
+ },
+ "id": {
+ "description": "用户ID",
+ "type": "string"
+ },
+ "last_active_at": {
+ "description": "最后活跃时间",
+ "type": "integer"
+ },
+ "status": {
+ "description": "用户状态 active: 正常 inactive: 禁用",
+ "allOf": [
+ {
+ "$ref": "#/definitions/consts.AdminStatus"
+ }
+ ]
+ },
+ "username": {
+ "description": "用户名",
+ "type": "string"
+ }
+ }
+ },
+ "domain.AllModelResp": {
+ "type": "object",
+ "properties": {
+ "providers": {
+ "description": "提供商列表",
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/domain.ProviderModel"
+ }
+ }
+ }
+ },
+ "domain.CategoryPoint": {
+ "type": "object",
+ "properties": {
+ "category": {
+ "description": "分类",
+ "type": "string"
+ },
+ "value": {
+ "description": "值",
+ "type": "integer"
+ }
+ }
+ },
+ "domain.CategoryStat": {
+ "type": "object",
+ "properties": {
+ "program_language": {
+ "description": "编程语言占比",
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/domain.CategoryPoint"
+ }
+ },
+ "work_mode": {
+ "description": "工作模式占比",
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/domain.CategoryPoint"
+ }
+ }
+ }
+ },
+ "domain.ChatInfo": {
+ "type": "object",
+ "properties": {
+ "content": {
+ "type": "string"
+ },
+ "created_at": {
+ "type": "integer"
+ },
+ "id": {
+ "type": "string"
+ }
+ }
+ },
+ "domain.ChatRecord": {
+ "type": "object",
+ "properties": {
+ "created_at": {
+ "description": "创建时间",
+ "type": "integer"
+ },
+ "id": {
+ "description": "记录ID",
+ "type": "string"
+ },
+ "input_tokens": {
+ "description": "输入token",
+ "type": "integer"
+ },
+ "model": {
+ "description": "模型",
+ "allOf": [
+ {
+ "$ref": "#/definitions/domain.Model"
+ }
+ ]
+ },
+ "output_tokens": {
+ "description": "输出token",
+ "type": "integer"
+ },
+ "question": {
+ "description": "问题",
+ "type": "string"
+ },
+ "user": {
+ "description": "用户",
+ "allOf": [
+ {
+ "$ref": "#/definitions/domain.User"
+ }
+ ]
+ },
+ "work_mode": {
+ "description": "工作模式",
+ "type": "string"
+ }
+ }
+ },
+ "domain.CheckModelReq": {
+ "type": "object",
+ "required": [
+ "api_base",
+ "api_key",
+ "model_name",
+ "provider"
+ ],
+ "properties": {
+ "api_base": {
+ "description": "接口地址",
+ "type": "string"
+ },
+ "api_key": {
+ "description": "接口密钥",
+ "type": "string"
+ },
+ "model_name": {
+ "description": "模型名称",
+ "type": "string"
+ },
+ "provider": {
+ "description": "提供商",
+ "type": "string"
+ }
+ }
+ },
+ "domain.CompletionInfo": {
+ "type": "object",
+ "properties": {
+ "content": {
+ "type": "string"
+ },
+ "created_at": {
+ "type": "integer"
+ },
+ "id": {
+ "type": "string"
+ }
+ }
+ },
+ "domain.CompletionRecord": {
+ "type": "object",
+ "properties": {
+ "created_at": {
+ "description": "创建时间",
+ "type": "integer"
+ },
+ "id": {
+ "description": "记录ID",
+ "type": "string"
+ },
+ "input_tokens": {
+ "description": "输入token",
+ "type": "integer"
+ },
+ "is_accept": {
+ "description": "是否采纳",
+ "type": "boolean"
+ },
+ "output_tokens": {
+ "description": "输出token",
+ "type": "integer"
+ },
+ "program_language": {
+ "description": "编程语言",
+ "type": "string"
+ },
+ "user": {
+ "description": "用户",
+ "allOf": [
+ {
+ "$ref": "#/definitions/domain.User"
+ }
+ ]
+ }
+ }
+ },
+ "domain.CreateAdminReq": {
+ "type": "object",
+ "properties": {
+ "password": {
+ "description": "密码",
+ "type": "string"
+ },
+ "username": {
+ "description": "用户名",
+ "type": "string"
+ }
+ }
+ },
+ "domain.CreateModelReq": {
+ "type": "object",
+ "properties": {
+ "api_base": {
+ "description": "接口地址 如:https://api.qwen.com",
+ "type": "string"
+ },
+ "api_key": {
+ "description": "接口密钥 如:sk-xxxx",
+ "type": "string"
+ },
+ "model_name": {
+ "description": "模型名称 如: deepseek-v3",
+ "type": "string"
+ },
+ "model_type": {
+ "description": "模型类型 llm:对话模型 coder:代码模型",
+ "allOf": [
+ {
+ "$ref": "#/definitions/consts.ModelType"
+ }
+ ]
+ },
+ "provider": {
+ "description": "提供商",
+ "type": "string"
+ }
+ }
+ },
+ "domain.IPInfo": {
+ "type": "object",
+ "properties": {
+ "asn": {
+ "description": "ASN",
+ "type": "string"
+ },
+ "city": {
+ "description": "城市",
+ "type": "string"
+ },
+ "country": {
+ "description": "国家",
+ "type": "string"
+ },
+ "ip": {
+ "description": "IP地址",
+ "type": "string"
+ },
+ "isp": {
+ "description": "运营商",
+ "type": "string"
+ },
+ "province": {
+ "description": "省份",
+ "type": "string"
+ }
+ }
+ },
+ "domain.InviteResp": {
+ "type": "object",
+ "properties": {
+ "code": {
+ "description": "邀请码",
+ "type": "string"
+ }
+ }
+ },
+ "domain.ListAdminLoginHistoryResp": {
+ "type": "object",
+ "properties": {
+ "has_next_page": {
+ "type": "boolean"
+ },
+ "login_histories": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/domain.AdminLoginHistory"
+ }
+ },
+ "next_token": {
+ "type": "string"
+ },
+ "total_count": {
+ "type": "integer"
+ }
+ }
+ },
+ "domain.ListAdminUserResp": {
+ "type": "object",
+ "properties": {
+ "has_next_page": {
+ "type": "boolean"
+ },
+ "next_token": {
+ "type": "string"
+ },
+ "total_count": {
+ "type": "integer"
+ },
+ "users": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/domain.AdminUser"
+ }
+ }
+ }
+ },
+ "domain.ListChatRecordResp": {
+ "type": "object",
+ "properties": {
+ "has_next_page": {
+ "type": "boolean"
+ },
+ "next_token": {
+ "type": "string"
+ },
+ "records": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/domain.ChatRecord"
+ }
+ },
+ "total_count": {
+ "type": "integer"
+ }
+ }
+ },
+ "domain.ListCompletionRecordResp": {
+ "type": "object",
+ "properties": {
+ "has_next_page": {
+ "type": "boolean"
+ },
+ "next_token": {
+ "type": "string"
+ },
+ "records": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/domain.CompletionRecord"
+ }
+ },
+ "total_count": {
+ "type": "integer"
+ }
+ }
+ },
+ "domain.ListLoginHistoryResp": {
+ "type": "object",
+ "properties": {
+ "has_next_page": {
+ "type": "boolean"
+ },
+ "login_histories": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/domain.UserLoginHistory"
+ }
+ },
+ "next_token": {
+ "type": "string"
+ },
+ "total_count": {
+ "type": "integer"
+ }
+ }
+ },
+ "domain.ListUserResp": {
+ "type": "object",
+ "properties": {
+ "has_next_page": {
+ "type": "boolean"
+ },
+ "next_token": {
+ "type": "string"
+ },
+ "total_count": {
+ "type": "integer"
+ },
+ "users": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/domain.User"
+ }
+ }
+ }
+ },
+ "domain.LoginReq": {
+ "type": "object",
+ "properties": {
+ "password": {
+ "description": "密码",
+ "type": "string"
+ },
+ "session_id": {
+ "description": "会话Id",
+ "type": "string"
+ },
+ "username": {
+ "description": "用户名",
+ "type": "string"
+ }
+ }
+ },
+ "domain.LoginResp": {
+ "type": "object",
+ "properties": {
+ "redirect_url": {
+ "description": "重定向URL",
+ "type": "string"
+ }
+ }
+ },
+ "domain.Model": {
+ "type": "object",
+ "properties": {
+ "api_base": {
+ "description": "接口地址 如:https://api.qwen.com",
+ "type": "string"
+ },
+ "api_key": {
+ "description": "接口密钥 如:sk-xxxx",
+ "type": "string"
+ },
+ "created_at": {
+ "description": "创建时间",
+ "type": "integer"
+ },
+ "id": {
+ "description": "模型ID",
+ "type": "string"
+ },
+ "input": {
+ "description": "输入token数",
+ "type": "integer"
+ },
+ "is_active": {
+ "description": "是否启用",
+ "type": "boolean"
+ },
+ "model_name": {
+ "description": "模型名称 如: deepseek-v3",
+ "type": "string"
+ },
+ "model_type": {
+ "description": "模型类型 llm:对话模型 coder:代码模型",
+ "allOf": [
+ {
+ "$ref": "#/definitions/consts.ModelType"
+ }
+ ]
+ },
+ "output": {
+ "description": "输出token数",
+ "type": "integer"
+ },
+ "provider": {
+ "description": "提供商",
+ "type": "string"
+ },
+ "status": {
+ "description": "状态 active:启用 inactive:禁用",
+ "allOf": [
+ {
+ "$ref": "#/definitions/consts.ModelStatus"
+ }
+ ]
+ },
+ "updated_at": {
+ "description": "更新时间",
+ "type": "integer"
+ }
+ }
+ },
+ "domain.ModelBasic": {
+ "type": "object",
+ "properties": {
+ "api_base": {
+ "description": "接口地址 如:https://api.qwen.com",
+ "type": "string"
+ },
+ "name": {
+ "description": "模型名称",
+ "type": "string"
+ },
+ "provider": {
+ "description": "提供商",
+ "type": "string"
+ }
+ }
+ },
+ "domain.ModelData": {
+ "type": "object",
+ "properties": {
+ "api_base": {
+ "type": "string"
+ },
+ "base_model": {
+ "type": "string"
+ },
+ "created": {
+ "type": "integer"
+ },
+ "id": {
+ "type": "string"
+ },
+ "is_active": {
+ "type": "boolean"
+ },
+ "name": {
+ "type": "string"
+ },
+ "object": {
+ "type": "string"
+ },
+ "owned_by": {
+ "type": "string"
+ },
+ "type": {
+ "type": "string"
+ }
+ }
+ },
+ "domain.ModelListResp": {
+ "type": "object",
+ "properties": {
+ "data": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/domain.ModelData"
+ }
+ },
+ "object": {
+ "type": "string"
+ }
+ }
+ },
+ "domain.ModelTokenUsage": {
+ "type": "object",
+ "properties": {
+ "timestamp": {
+ "description": "时间戳",
+ "type": "integer"
+ },
+ "tokens": {
+ "description": "使用token数",
+ "type": "integer"
+ }
+ }
+ },
+ "domain.ModelTokenUsageResp": {
+ "type": "object",
+ "properties": {
+ "input_usage": {
+ "description": "输入token使用记录",
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/domain.ModelTokenUsage"
+ }
+ },
+ "output_usage": {
+ "description": "输出token使用记录",
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/domain.ModelTokenUsage"
+ }
+ },
+ "total_input": {
+ "description": "总输入token数",
+ "type": "integer"
+ },
+ "total_output": {
+ "description": "总输出token数",
+ "type": "integer"
+ }
+ }
+ },
+ "domain.ProviderModel": {
+ "type": "object",
+ "properties": {
+ "models": {
+ "description": "模型列表",
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/domain.ModelBasic"
+ }
+ },
+ "provider": {
+ "description": "提供商",
+ "type": "string"
+ }
+ }
+ },
+ "domain.RegisterReq": {
+ "type": "object",
+ "properties": {
+ "code": {
+ "description": "邀请码",
+ "type": "string"
+ },
+ "email": {
+ "description": "邮箱",
+ "type": "string"
+ },
+ "password": {
+ "description": "密码",
+ "type": "string"
+ }
+ }
+ },
+ "domain.Setting": {
+ "type": "object",
+ "properties": {
+ "created_at": {
+ "description": "创建时间",
+ "type": "integer"
+ },
+ "disable_password_login": {
+ "description": "是否禁用密码登录",
+ "type": "boolean"
+ },
+ "enable_sso": {
+ "description": "是否开启SSO",
+ "type": "boolean"
+ },
+ "force_two_factor_auth": {
+ "description": "是否强制两步验证",
+ "type": "boolean"
+ },
+ "updated_at": {
+ "description": "更新时间",
+ "type": "integer"
+ }
+ }
+ },
+ "domain.Statistics": {
+ "type": "object",
+ "properties": {
+ "disabled_users": {
+ "description": "禁用用户数",
+ "type": "integer"
+ },
+ "total_users": {
+ "description": "总用户数",
+ "type": "integer"
+ }
+ }
+ },
+ "domain.TimeStat": {
+ "type": "object",
+ "properties": {
+ "accepted_per": {
+ "description": "接受率统计",
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "timestamp": {
+ "description": "时间戳",
+ "type": "integer"
+ },
+ "value": {
+ "description": "值",
+ "type": "number"
+ }
+ }
+ }
+ },
+ "active_users": {
+ "description": "活跃用户数统计",
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "timestamp": {
+ "description": "时间戳",
+ "type": "integer"
+ },
+ "value": {
+ "description": "值",
+ "type": "integer"
+ }
+ }
+ }
+ },
+ "chats": {
+ "description": "对话任务数统计",
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "timestamp": {
+ "description": "时间戳",
+ "type": "integer"
+ },
+ "value": {
+ "description": "值",
+ "type": "integer"
+ }
+ }
+ }
+ },
+ "code_completions": {
+ "description": "补全任务数统计",
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "timestamp": {
+ "description": "时间戳",
+ "type": "integer"
+ },
+ "value": {
+ "description": "值",
+ "type": "integer"
+ }
+ }
+ }
+ },
+ "lines_of_code": {
+ "description": "代码行数统计",
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "timestamp": {
+ "description": "时间戳",
+ "type": "integer"
+ },
+ "value": {
+ "description": "值",
+ "type": "integer"
+ }
+ }
+ }
+ },
+ "real_time_tokens": {
+ "description": "实时token数统计",
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "timestamp": {
+ "description": "时间戳",
+ "type": "integer"
+ },
+ "value": {
+ "description": "值",
+ "type": "integer"
+ }
+ }
+ }
+ },
+ "total_accepted_per": {
+ "description": "近90天平均接受率",
+ "type": "number"
+ },
+ "total_chats": {
+ "description": "近90天对话任务数",
+ "type": "integer"
+ },
+ "total_completions": {
+ "description": "近90天补全任务数",
+ "type": "integer"
+ },
+ "total_lines_of_code": {
+ "description": "近90天代码行数",
+ "type": "integer"
+ },
+ "total_users": {
+ "description": "近90天活跃用户数",
+ "type": "integer"
+ }
+ }
+ },
+ "domain.UpdateModelReq": {
+ "type": "object",
+ "properties": {
+ "api_base": {
+ "description": "接口地址 如:https://api.qwen.com",
+ "type": "string"
+ },
+ "api_key": {
+ "description": "接口密钥 如:sk-xxxx",
+ "type": "string"
+ },
+ "id": {
+ "description": "模型ID",
+ "type": "string"
+ },
+ "model_name": {
+ "description": "模型名称",
+ "type": "string"
+ },
+ "provider": {
+ "description": "提供商",
+ "type": "string"
+ },
+ "status": {
+ "description": "状态 active:启用 inactive:禁用",
+ "allOf": [
+ {
+ "$ref": "#/definitions/consts.ModelStatus"
+ }
+ ]
+ }
+ }
+ },
+ "domain.UpdateSettingReq": {
+ "type": "object",
+ "properties": {
+ "disable_password_login": {
+ "description": "是否禁用密码登录",
+ "type": "boolean"
+ },
+ "enable_sso": {
+ "description": "是否开启SSO",
+ "type": "boolean"
+ },
+ "force_two_factor_auth": {
+ "description": "是否强制两步验证",
+ "type": "boolean"
+ }
+ }
+ },
+ "domain.UpdateUserReq": {
+ "type": "object",
+ "required": [
+ "id"
+ ],
+ "properties": {
+ "id": {
+ "description": "用户ID",
+ "type": "string"
+ },
+ "password": {
+ "description": "重置密码",
+ "type": "string"
+ },
+ "status": {
+ "description": "用户状态 active: 正常 locked: 锁定 inactive: 禁用",
+ "allOf": [
+ {
+ "$ref": "#/definitions/consts.UserStatus"
+ }
+ ]
+ }
+ }
+ },
+ "domain.User": {
+ "type": "object",
+ "properties": {
+ "created_at": {
+ "description": "创建时间",
+ "type": "integer"
+ },
+ "email": {
+ "description": "邮箱",
+ "type": "string"
+ },
+ "id": {
+ "description": "用户ID",
+ "type": "string"
+ },
+ "last_active_at": {
+ "description": "最后活跃时间",
+ "type": "integer"
+ },
+ "status": {
+ "description": "用户状态 active: 正常 locked: 锁定 inactive: 禁用",
+ "allOf": [
+ {
+ "$ref": "#/definitions/consts.UserStatus"
+ }
+ ]
+ },
+ "two_step_auth": {
+ "description": "是否开启两步验证",
+ "type": "boolean"
+ },
+ "username": {
+ "description": "用户名",
+ "type": "string"
+ }
+ }
+ },
+ "domain.UserCodeRank": {
+ "type": "object",
+ "properties": {
+ "lines": {
+ "description": "代码行数",
+ "type": "integer"
+ },
+ "username": {
+ "description": "用户名",
+ "type": "string"
+ }
+ }
+ },
+ "domain.UserEvent": {
+ "type": "object",
+ "properties": {
+ "created_at": {
+ "description": "事件时间",
+ "type": "integer"
+ },
+ "name": {
+ "description": "事件名称",
+ "type": "string"
+ }
+ }
+ },
+ "domain.UserHeatmap": {
+ "type": "object",
+ "properties": {
+ "count": {
+ "type": "integer"
+ },
+ "date": {
+ "type": "integer"
+ }
+ }
+ },
+ "domain.UserHeatmapResp": {
+ "type": "object",
+ "properties": {
+ "max_count": {
+ "type": "integer"
+ },
+ "points": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/domain.UserHeatmap"
+ }
+ }
+ }
+ },
+ "domain.UserLoginHistory": {
+ "type": "object",
+ "properties": {
+ "client_version": {
+ "description": "客户端版本",
+ "type": "string"
+ },
+ "created_at": {
+ "description": "登录时间",
+ "type": "integer"
+ },
+ "device": {
+ "description": "设备信息",
+ "type": "string"
+ },
+ "ip_info": {
+ "description": "IP信息",
+ "allOf": [
+ {
+ "$ref": "#/definitions/domain.IPInfo"
+ }
+ ]
+ },
+ "user": {
+ "description": "用户信息",
+ "allOf": [
+ {
+ "$ref": "#/definitions/domain.User"
+ }
+ ]
+ }
+ }
+ },
+ "domain.UserStat": {
+ "type": "object",
+ "properties": {
+ "accepted_per": {
+ "description": "接受率统计",
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "timestamp": {
+ "description": "时间戳",
+ "type": "integer"
+ },
+ "value": {
+ "description": "值",
+ "type": "number"
+ }
+ }
+ }
+ },
+ "chats": {
+ "description": "对话任务数统计",
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "timestamp": {
+ "description": "时间戳",
+ "type": "integer"
+ },
+ "value": {
+ "description": "值",
+ "type": "integer"
+ }
+ }
+ }
+ },
+ "code_completions": {
+ "description": "补全任务数统计",
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "timestamp": {
+ "description": "时间戳",
+ "type": "integer"
+ },
+ "value": {
+ "description": "值",
+ "type": "integer"
+ }
+ }
+ }
+ },
+ "lines_of_code": {
+ "description": "代码行数统计",
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "timestamp": {
+ "description": "时间戳",
+ "type": "integer"
+ },
+ "value": {
+ "description": "值",
+ "type": "integer"
+ }
+ }
+ }
+ },
+ "program_language": {
+ "description": "编程语言占比",
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/domain.CategoryPoint"
+ }
+ },
+ "total_accepted_per": {
+ "description": "近90天总接受率",
+ "type": "number"
+ },
+ "total_chats": {
+ "description": "近90天总对话任务数",
+ "type": "integer"
+ },
+ "total_completions": {
+ "description": "近90天总补全任务数",
+ "type": "integer"
+ },
+ "total_lines_of_code": {
+ "description": "近90天总代码行数",
+ "type": "integer"
+ },
+ "work_mode": {
+ "description": "工作模式占比",
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/domain.CategoryPoint"
+ }
+ }
+ }
+ },
+ "web.Resp": {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer"
+ },
+ "data": {},
+ "message": {
+ "type": "string"
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/backend/domain/billing.go b/backend/domain/billing.go
new file mode 100644
index 0000000..8674a9c
--- /dev/null
+++ b/backend/domain/billing.go
@@ -0,0 +1,172 @@
+package domain
+
+import (
+ "context"
+
+ "github.com/GoYoko/web"
+
+ "github.com/chaitin/MonkeyCode/backend/db"
+ "github.com/chaitin/MonkeyCode/backend/pkg/cvt"
+)
+
+type BillingUsecase interface {
+ ListChatRecord(ctx context.Context, page *web.Pagination) (*ListChatRecordResp, error)
+ ListCompletionRecord(ctx context.Context, page *web.Pagination) (*ListCompletionRecordResp, error)
+ CompletionInfo(ctx context.Context, id string) (*CompletionInfo, error)
+ ChatInfo(ctx context.Context, id string) (*ChatInfo, error)
+}
+
+type BillingRepo interface {
+ ListChatRecord(ctx context.Context, page *web.Pagination) (*ListChatRecordResp, error)
+ ListCompletionRecord(ctx context.Context, page *web.Pagination) (*ListCompletionRecordResp, error)
+ CompletionInfo(ctx context.Context, id string) (*CompletionInfo, error)
+ ChatInfo(ctx context.Context, id string) (*ChatInfo, error)
+}
+
+type ListChatRecordResp struct {
+ *db.PageInfo
+
+ Records []*ChatRecord `json:"records"`
+}
+
+type ListCompletionRecordResp struct {
+ *db.PageInfo
+
+ Records []*CompletionRecord `json:"records"`
+}
+
+type ChatRecord struct {
+ ID string `json:"id"` // 记录ID
+ User *User `json:"user"` // 用户
+ Model *Model `json:"model"` // 模型
+ Question string `json:"question"` // 问题
+ WorkMode string `json:"work_mode"` // 工作模式
+ InputTokens int64 `json:"input_tokens"` // 输入token
+ OutputTokens int64 `json:"output_tokens"` // 输出token
+ CreatedAt int64 `json:"created_at"` // 创建时间
+}
+
+func (c *ChatRecord) From(e *db.Record) *ChatRecord {
+ if e == nil {
+ return c
+ }
+ c.ID = e.ID.String()
+ c.Question = e.Prompt
+ c.User = cvt.From(e.Edges.User, &User{})
+ c.Model = cvt.From(e.Edges.Model, &Model{})
+ c.WorkMode = e.WorkMode
+ c.InputTokens = e.InputTokens
+ c.OutputTokens = e.OutputTokens
+ c.CreatedAt = e.CreatedAt.Unix()
+ return c
+}
+
+type CompletionRecord struct {
+ ID string `json:"id"` // 记录ID
+ User *User `json:"user"` // 用户
+ IsAccept bool `json:"is_accept"` // 是否采纳
+ ProgramLanguage string `json:"program_language"` // 编程语言
+ InputTokens int64 `json:"input_tokens"` // 输入token
+ OutputTokens int64 `json:"output_tokens"` // 输出token
+ CreatedAt int64 `json:"created_at"` // 创建时间
+}
+
+func (c *CompletionRecord) From(e *db.Record) *CompletionRecord {
+ if e == nil {
+ return c
+ }
+ c.ID = e.ID.String()
+ c.IsAccept = e.IsAccept
+ c.User = cvt.From(e.Edges.User, &User{})
+ c.ProgramLanguage = e.ProgramLanguage
+ c.InputTokens = e.InputTokens
+ c.OutputTokens = e.OutputTokens
+ c.CreatedAt = e.CreatedAt.Unix()
+ return c
+}
+
+type CompletionInfo struct {
+ ID string `json:"id"`
+ Content string `json:"content"`
+ CreatedAt int64 `json:"created_at"`
+}
+
+func (c *CompletionInfo) From(e *db.Record) *CompletionInfo {
+ if e == nil {
+ return c
+ }
+ c.ID = e.ID.String()
+ c.Content = e.Completion
+ c.CreatedAt = e.CreatedAt.Unix()
+ return c
+}
+
+type ChatInfo struct {
+ ID string `json:"id"`
+ Content string `json:"content"`
+ CreatedAt int64 `json:"created_at"`
+}
+
+func (c *ChatInfo) From(e *db.Record) *ChatInfo {
+ if e == nil {
+ return c
+ }
+ c.ID = e.ID.String()
+ c.Content = e.Completion
+ c.CreatedAt = e.CreatedAt.Unix()
+ return c
+}
+
+type BillingUsage struct {
+ ID string `json:"id"`
+ CreatedAt int64 `json:"created_at"`
+ UpdatedAt int64 `json:"updated_at"`
+ UserID string `json:"user_id"`
+ ModelName string `json:"model_name"`
+ Tokens int64 `json:"tokens"`
+ Operation string `json:"operation"`
+}
+
+type BillingQuota struct {
+ ID string `json:"id"`
+ CreatedAt int64 `json:"created_at"`
+ UpdatedAt int64 `json:"updated_at"`
+ UserID string `json:"user_id"`
+ Total int64 `json:"total"`
+ Used int64 `json:"used"`
+ Remain int64 `json:"remain"`
+}
+
+func (b *BillingQuota) From(e *db.BillingQuota) *BillingQuota {
+ if e == nil {
+ return b
+ }
+ b.ID = e.ID
+ b.UserID = e.UserID
+ b.Total = e.Total
+ b.Used = e.Used
+ b.Remain = e.Remain
+ b.CreatedAt = e.CreatedAt.Unix()
+ b.UpdatedAt = e.UpdatedAt.Unix()
+ return b
+}
+
+type ApiKey struct {
+ ID string `json:"id"`
+ CreatedAt int64 `json:"created_at"`
+ UpdatedAt int64 `json:"updated_at"`
+ UserID string `json:"user_id"`
+ Key string `json:"key"`
+}
+
+func (a *ApiKey) From(e *db.ApiKey) *ApiKey {
+ if e == nil {
+ return a
+ }
+ a.ID = e.ID.String()
+ a.UserID = e.UserID.String()
+ a.Key = e.Key
+ a.CreatedAt = e.CreatedAt.Unix()
+ a.UpdatedAt = e.UpdatedAt.Unix()
+ return a
+}
diff --git a/backend/domain/dashboard.go b/backend/domain/dashboard.go
new file mode 100644
index 0000000..6547259
--- /dev/null
+++ b/backend/domain/dashboard.go
@@ -0,0 +1,103 @@
+package domain
+
+import (
+ "context"
+
+ "github.com/chaitin/MonkeyCode/backend/db"
+)
+
+type DashboardUsecase interface {
+ Statistics(ctx context.Context) (*Statistics, error)
+ CategoryStat(ctx context.Context) (*CategoryStat, error)
+ TimeStat(ctx context.Context) (*TimeStat, error)
+ UserCodeRank(ctx context.Context) ([]*UserCodeRank, error)
+ UserStat(ctx context.Context, userID string) (*UserStat, error)
+ UserEvents(ctx context.Context, userID string) ([]*UserEvent, error)
+ UserHeatmap(ctx context.Context, userID string) (*UserHeatmapResp, error)
+}
+
+type DashboardRepo interface {
+ Statistics(ctx context.Context) (*Statistics, error)
+ CategoryStat(ctx context.Context) (*CategoryStat, error)
+ TimeStat(ctx context.Context) (*TimeStat, error)
+ UserCodeRank(ctx context.Context) ([]*UserCodeRank, error)
+ UserStat(ctx context.Context, userID string) (*UserStat, error)
+ UserEvents(ctx context.Context, userID string) ([]*UserEvent, error)
+ UserHeatmap(ctx context.Context, userID string) ([]*UserHeatmap, error)
+}
+
+type Statistics struct {
+ TotalUsers int64 `json:"total_users"` // 总用户数
+ DisabledUsers int64 `json:"disabled_users"` // 禁用用户数
+}
+
+type UserHeatmapResp struct {
+ MaxCount int64 `json:"max_count"`
+ Points []*UserHeatmap `json:"points"`
+}
+
+type UserHeatmap struct {
+ Date int64 `json:"date"`
+ Count int64 `json:"count"`
+}
+
+type UserCodeRank struct {
+ Username string `json:"username"` // 用户名
+ Lines int64 `json:"lines"` // 代码行数
+}
+
+func (u *UserCodeRank) From(d *db.Record) *UserCodeRank {
+ if d == nil {
+ return u
+ }
+ u.Username = d.Edges.User.Username
+ u.Lines = d.CodeLines
+ return u
+}
+
+type UserStat struct {
+ TotalChats int64 `json:"total_chats"` // 近90天总对话任务数
+ TotalCompletions int64 `json:"total_completions"` // 近90天总补全任务数
+ TotalLinesOfCode int64 `json:"total_lines_of_code"` // 近90天总代码行数
+ TotalAcceptedPer float64 `json:"total_accepted_per"` // 近90天总接受率
+ Chats []TimePoint[int64] `json:"chats"` // 对话任务数统计
+ Completions []TimePoint[int64] `json:"code_completions"` // 补全任务数统计
+ LinesOfCode []TimePoint[int64] `json:"lines_of_code"` // 代码行数统计
+ AcceptedPer []TimePoint[float64] `json:"accepted_per"` // 接受率统计
+ WorkMode []CategoryPoint `json:"work_mode"` // 工作模式占比
+ ProgramLanguage []CategoryPoint `json:"program_language"` // 编程语言占比
+}
+
+type UserEvent struct {
+ Name string `json:"name"` // 事件名称
+ CreatedAt int64 `json:"created_at"` // 事件时间
+}
+
+type TimePoint[V any] struct {
+ Timestamp int64 `json:"timestamp"` // 时间戳
+ Value V `json:"value"` // 值
+}
+
+type CategoryPoint struct {
+ Category string `json:"category"` // 分类
+ Value int64 `json:"value"` // 值
+}
+
+type CategoryStat struct {
+ WorkMode []CategoryPoint `json:"work_mode"` // 工作模式占比
+ ProgramLanguage []CategoryPoint `json:"program_language"` // 编程语言占比
+}
+
+type TimeStat struct {
+ TotalUsers int64 `json:"total_users"` // 近90天活跃用户数
+ TotalChats int64 `json:"total_chats"` // 近90天对话任务数
+ TotalCompletions int64 `json:"total_completions"` // 近90天补全任务数
+ TotalLinesOfCode int64 `json:"total_lines_of_code"` // 近90天代码行数
+ TotalAcceptedPer float64 `json:"total_accepted_per"` // 近90天平均接受率
+ ActiveUsers []TimePoint[int64] `json:"active_users"` // 活跃用户数统计
+ RealTimeTokens []TimePoint[int64] `json:"real_time_tokens"` // 实时token数统计
+ Chats []TimePoint[int64] `json:"chats"` // 对话任务数统计
+ Completions []TimePoint[int64] `json:"code_completions"` // 补全任务数统计
+ LinesOfCode []TimePoint[int64] `json:"lines_of_code"` // 代码行数统计
+ AcceptedPer []TimePoint[float64] `json:"accepted_per"` // 接受率统计
+}
diff --git a/backend/domain/model.go b/backend/domain/model.go
new file mode 100644
index 0000000..699fe2e
--- /dev/null
+++ b/backend/domain/model.go
@@ -0,0 +1,128 @@
+package domain
+
+import (
+ "context"
+
+ "github.com/google/uuid"
+
+ "github.com/chaitin/MonkeyCode/backend/consts"
+ "github.com/chaitin/MonkeyCode/backend/db"
+)
+
+type ModelUsecase interface {
+ List(ctx context.Context) (*AllModelResp, error)
+ MyModelList(ctx context.Context, req *MyModelListReq) ([]*Model, error)
+ Create(ctx context.Context, req *CreateModelReq) (*Model, error)
+ Update(ctx context.Context, req *UpdateModelReq) (*Model, error)
+ Check(ctx context.Context, req *CheckModelReq) (*Model, error)
+ GetTokenUsage(ctx context.Context, modelType consts.ModelType) (*ModelTokenUsageResp, error)
+}
+
+type ModelRepo interface {
+ Create(ctx context.Context, m *CreateModelReq) (*db.Model, error)
+ Update(ctx context.Context, id string, fn func(up *db.ModelUpdateOne)) (*db.Model, error)
+ MyModelList(ctx context.Context, req *MyModelListReq) ([]*db.Model, error)
+ ModelUsage(ctx context.Context, ids []uuid.UUID) (map[uuid.UUID]ModelUsage, error)
+ GetTokenUsage(ctx context.Context, modelType consts.ModelType) (*ModelTokenUsageResp, error)
+}
+
+type MyModelListReq struct {
+ UserID string `json:"-"`
+ ModelType consts.ModelType `json:"model_type" query:"model_type"` // 模型类型 llm:对话模型 coder:代码模型
+}
+
+type CheckModelReq struct {
+ Provider string `json:"provider" validate:"required"` // 提供商
+ ModelName string `json:"model_name" validate:"required"` // 模型名称
+ APIBase string `json:"api_base" validate:"required"` // 接口地址
+ APIKey string `json:"api_key" validate:"required"` // 接口密钥
+}
+
+type AllModelResp struct {
+ Providers []ProviderModel `json:"providers"` // 提供商列表
+}
+
+type ProviderModel struct {
+ Provider string `json:"provider"` // 提供商
+ Models []ModelBasic `json:"models"` // 模型列表
+}
+
+type GetTokenUsageReq struct {
+ ModelType consts.ModelType `json:"model_type" query:"model_type" validate:"required,oneof=llm coder"` // 模型类型 llm:对话模型 coder:代码模型
+}
+
+type CreateModelReq struct {
+ UserID string `json:"-"`
+ ModelName string `json:"model_name"` // 模型名称 如: deepseek-v3
+ Provider string `json:"provider"` // 提供商
+ APIBase string `json:"api_base"` // 接口地址 如:https://api.qwen.com
+ APIKey string `json:"api_key"` // 接口密钥 如:sk-xxxx
+ ModelType consts.ModelType `json:"model_type"` // 模型类型 llm:对话模型 coder:代码模型
+}
+
+type UpdateModelReq struct {
+ ID string `json:"id"` // 模型ID
+ ModelName *string `json:"model_name"` // 模型名称
+ Provider *string `json:"provider"` // 提供商
+ APIBase *string `json:"api_base"` // 接口地址 如:https://api.qwen.com
+ APIKey *string `json:"api_key"` // 接口密钥 如:sk-xxxx
+ Status *consts.ModelStatus `json:"status"` // 状态 active:启用 inactive:禁用
+}
+
+type ModelTokenUsageResp struct {
+ TotalInput int64 `json:"total_input"` // 总输入token数
+ TotalOutput int64 `json:"total_output"` // 总输出token数
+ InputUsage []ModelTokenUsage `json:"input_usage"` // 输入token使用记录
+ OutputUsage []ModelTokenUsage `json:"output_usage"` // 输出token使用记录
+}
+
+type ModelTokenUsage struct {
+ Timestamp int64 `json:"timestamp"` // 时间戳
+ Tokens int64 `json:"tokens"` // 使用token数
+}
+
+type ModelBasic struct {
+ Name string `json:"name"` // 模型名称
+ Provider string `json:"provider"` // 提供商
+ APIBase string `json:"api_base"` // 接口地址 如:https://api.qwen.com
+}
+
+type ModelUsage struct {
+ ModelID uuid.UUID `json:"model_id"` // 模型ID
+ Input int64 `json:"input"` // 输入token数
+ Output int64 `json:"output"` // 输出token数
+}
+
+type Model struct {
+ ID string `json:"id"` // 模型ID
+ ModelName string `json:"model_name"` // 模型名称 如: deepseek-v3
+ Provider string `json:"provider"` // 提供商
+ APIBase string `json:"api_base"` // 接口地址 如:https://api.qwen.com
+ APIKey string `json:"api_key"` // 接口密钥 如:sk-xxxx
+ ModelType consts.ModelType `json:"model_type"` // 模型类型 llm:对话模型 coder:代码模型
+ Status consts.ModelStatus `json:"status"` // 状态 active:启用 inactive:禁用
+ IsActive bool `json:"is_active"` // 是否启用
+ Input int64 `json:"input"` // 输入token数
+ Output int64 `json:"output"` // 输出token数
+ CreatedAt int64 `json:"created_at"` // 创建时间
+ UpdatedAt int64 `json:"updated_at"` // 更新时间
+}
+
+func (m *Model) From(e *db.Model) *Model {
+ if e == nil {
+ return m
+ }
+
+ m.ID = e.ID.String()
+ m.ModelName = e.ModelName
+ m.Provider = e.Provider
+ m.APIBase = e.APIBase
+ m.APIKey = e.APIKey
+ m.ModelType = e.ModelType
+ m.Status = e.Status
+ m.IsActive = e.Status == consts.ModelStatusActive
+ m.CreatedAt = e.CreatedAt.Unix()
+ m.UpdatedAt = e.UpdatedAt.Unix()
+
+ return m
+}
diff --git a/backend/domain/openai.go b/backend/domain/openai.go
new file mode 100644
index 0000000..ddb652f
--- /dev/null
+++ b/backend/domain/openai.go
@@ -0,0 +1,72 @@
+package domain
+
+import (
+ "context"
+
+ "github.com/rokku-c/go-openai"
+
+ "github.com/chaitin/MonkeyCode/backend/consts"
+ "github.com/chaitin/MonkeyCode/backend/db"
+)
+
+type OpenAIUsecase interface {
+ ModelList(ctx context.Context) (*ModelListResp, error)
+ GetConfig(ctx context.Context, req *ConfigReq) (*ConfigResp, error)
+}
+
+type OpenAIRepo interface {
+ GetApiKey(ctx context.Context, key string) (*db.ApiKey, error)
+ ModelList(ctx context.Context) ([]*db.Model, error)
+}
+
+type CompletionRequest struct {
+ openai.CompletionRequest
+
+ Metadata map[string]string `json:"metadata"`
+}
+
+type ModelListResp struct {
+ Object string `json:"object"`
+ Data []*ModelData `json:"data"`
+}
+
+type ModelData struct {
+ ID string `json:"id"`
+ Object string `json:"object"`
+ Created int64 `json:"created"`
+ OwnedBy string `json:"owned_by"`
+ Name string `json:"name"`
+ Type string `json:"type"`
+ BaseModel string `json:"base_model"`
+ APIBase string `json:"api_base"`
+ IsActive bool `json:"is_active"`
+}
+
+func (m *ModelData) From(e *db.Model) *ModelData {
+ if e == nil {
+ return m
+ }
+
+ m.ID = e.ID.String()
+ m.Object = "model"
+ m.Created = e.CreatedAt.Unix()
+ if e.Edges.User != nil {
+ m.OwnedBy = e.Edges.User.Username
+ }
+ m.Name = e.ModelName
+ m.Type = string(e.ModelType)
+ m.BaseModel = e.ModelName
+ m.APIBase = e.APIBase
+ m.IsActive = e.Status == consts.ModelStatusActive
+ return m
+}
+
+type ConfigReq struct {
+ Key string
+ Type consts.ConfigType `json:"type"`
+}
+
+type ConfigResp struct {
+ Type consts.ConfigType `json:"type"`
+ Content string `json:"content"`
+}
diff --git a/backend/domain/proxy.go b/backend/domain/proxy.go
new file mode 100644
index 0000000..55652b4
--- /dev/null
+++ b/backend/domain/proxy.go
@@ -0,0 +1,53 @@
+package domain
+
+import (
+ "context"
+ "net/http"
+
+ "github.com/rokku-c/go-openai"
+
+ "github.com/chaitin/MonkeyCode/backend/consts"
+ "github.com/chaitin/MonkeyCode/backend/db"
+)
+
+// Proxy LLM API代理接口
+type Proxy interface {
+ AcceptCompletion(ctx context.Context, req *AcceptCompletionReq) error
+ HandleCompletion(ctx context.Context, w http.ResponseWriter, req CompletionRequest)
+ HandleChatCompletion(ctx context.Context, w http.ResponseWriter, req *openai.ChatCompletionRequest)
+ HandleEmbeddings(ctx context.Context, w http.ResponseWriter, req *openai.EmbeddingRequest)
+}
+
+type ProxyUsecase interface {
+ SelectModelWithLoadBalancing(modelName string, modelType consts.ModelType) (*Model, error)
+ Record(ctx context.Context, record *RecordParam) error
+ ValidateApiKey(ctx context.Context, key string) (*ApiKey, error)
+ AcceptCompletion(ctx context.Context, req *AcceptCompletionReq) error
+}
+
+type ProxyRepo interface {
+ Record(ctx context.Context, record *db.Record) error
+ UpdateByTaskID(ctx context.Context, taskID string, fn func(*db.RecordUpdateOne)) error
+ SelectModelWithLoadBalancing(modelName string, modelType consts.ModelType) (*db.Model, error)
+ ValidateApiKey(ctx context.Context, key string) (*db.ApiKey, error)
+}
+
+type AcceptCompletionReq struct {
+ ID string `json:"id"` // 记录ID
+ Completion string `json:"completion"` // 补全内容
+}
+
+type RecordParam struct {
+ TaskID string
+ UserID string
+ ModelID string
+ ModelType consts.ModelType
+ Prompt string
+ ProgramLanguage string
+ InputTokens int64
+ OutputTokens int64
+ IsAccept bool
+ Completion string
+ WorkMode string
+ CodeLines int64
+}
diff --git a/backend/domain/user.go b/backend/domain/user.go
new file mode 100644
index 0000000..7abb9a5
--- /dev/null
+++ b/backend/domain/user.go
@@ -0,0 +1,273 @@
+package domain
+
+import (
+ "context"
+
+ "github.com/GoYoko/web"
+
+ "github.com/chaitin/MonkeyCode/backend/consts"
+ "github.com/chaitin/MonkeyCode/backend/db"
+ "github.com/chaitin/MonkeyCode/backend/pkg/cvt"
+)
+
+type UserUsecase interface {
+ Login(ctx context.Context, req *LoginReq) (*LoginResp, error)
+ Update(ctx context.Context, req *UpdateUserReq) (*User, error)
+ Delete(ctx context.Context, id string) error
+ InitAdmin(ctx context.Context) error
+ AdminLogin(ctx context.Context, req *LoginReq) (*AdminUser, error)
+ DeleteAdmin(ctx context.Context, id string) error
+ CreateAdmin(ctx context.Context, req *CreateAdminReq) (*AdminUser, error)
+ VSCodeAuthInit(ctx context.Context, req *VSCodeAuthInitReq) (*VSCodeAuthInitResp, error)
+ List(ctx context.Context, req ListReq) (*ListUserResp, error)
+ AdminList(ctx context.Context, page *web.Pagination) (*ListAdminUserResp, error)
+ LoginHistory(ctx context.Context, page *web.Pagination) (*ListLoginHistoryResp, error)
+ AdminLoginHistory(ctx context.Context, page *web.Pagination) (*ListAdminLoginHistoryResp, error)
+ Invite(ctx context.Context, userID string) (*InviteResp, error)
+ Register(ctx context.Context, req *RegisterReq) (*User, error)
+ GetSetting(ctx context.Context) (*Setting, error)
+ UpdateSetting(ctx context.Context, req *UpdateSettingReq) (*Setting, error)
+}
+
+type UserRepo interface {
+ List(ctx context.Context, page *web.Pagination) ([]*db.User, *db.PageInfo, error)
+ Update(ctx context.Context, id string, fn func(*db.UserUpdateOne) error) (*db.User, error)
+ Delete(ctx context.Context, id string) error
+ InitAdmin(ctx context.Context, username, password string) error
+ CreateUser(ctx context.Context, user *db.User) (*db.User, error)
+ CreateAdmin(ctx context.Context, admin *db.Admin) (*db.Admin, error)
+ DeleteAdmin(ctx context.Context, id string) error
+ AdminByName(ctx context.Context, username string) (*db.Admin, error)
+ GetByName(ctx context.Context, username string) (*db.User, error)
+ GetOrCreateApiKey(ctx context.Context, userID string) (*db.ApiKey, error)
+ AdminList(ctx context.Context, page *web.Pagination) ([]*db.Admin, *db.PageInfo, error)
+ CreateInviteCode(ctx context.Context, userID string, code string) (*db.InviteCode, error)
+ ValidateInviteCode(ctx context.Context, code string) (*db.InviteCode, error)
+ UserLoginHistory(ctx context.Context, page *web.Pagination) ([]*db.UserLoginHistory, *db.PageInfo, error)
+ AdminLoginHistory(ctx context.Context, page *web.Pagination) ([]*db.AdminLoginHistory, *db.PageInfo, error)
+ GetSetting(ctx context.Context) (*db.Setting, error)
+ UpdateSetting(ctx context.Context, fn func(*db.SettingUpdateOne)) (*db.Setting, error)
+}
+
+type UpdateUserReq struct {
+ ID string `json:"id" validate:"required"` // 用户ID
+ Status *consts.UserStatus `json:"status"` // 用户状态 active: 正常 locked: 锁定 inactive: 禁用
+ Password *string `json:"password"` // 重置密码
+}
+
+type CreateAdminReq struct {
+ Username string `json:"username"` // 用户名
+ Password string `json:"password"` // 密码
+}
+
+type VSCodeAuthInitReq struct {
+ ClientID string `json:"client_id" validate:"required"` // 客户端ID
+ RedirectURI string `json:"redirect_uri" validate:"required"` // 重定向URI
+ State string `json:"state" validate:"required"` // 状态
+}
+
+type VSCodeAuthInitResp struct {
+ AuthURL string `json:"auth_url"` // 授权URL
+}
+
+type LoginReq struct {
+ SessionID string `json:"session_id"` // 会话Id
+ Username string `json:"username"` // 用户名
+ Password string `json:"password"` // 密码
+}
+
+type AdminLoginReq struct {
+ Account string `json:"account"` // 用户名
+ Password string `json:"password"` // 密码
+}
+
+type LoginResp struct {
+ RedirectURL string `json:"redirect_url"` // 重定向URL
+}
+
+type ListReq struct {
+ web.Pagination
+
+ Search string `json:"search" query:"search"` // 搜索
+}
+
+type RegisterReq struct {
+ Email string `json:"email"` // 邮箱
+ Password string `json:"password"` // 密码
+ Code string `json:"code"` // 邀请码
+}
+
+type ListLoginHistoryResp struct {
+ *db.PageInfo
+
+ LoginHistories []*UserLoginHistory `json:"login_histories"`
+}
+
+type ListAdminLoginHistoryResp struct {
+ *db.PageInfo
+
+ LoginHistories []*AdminLoginHistory `json:"login_histories"`
+}
+
+type InviteResp struct {
+ Code string `json:"code"` // 邀请码
+}
+
+type IPInfo struct {
+ IP string `json:"ip"` // IP地址
+ Country string `json:"country"` // 国家
+ Province string `json:"province"` // 省份
+ City string `json:"city"` // 城市
+ ISP string `json:"isp"` // 运营商
+ ASN string `json:"asn"` // ASN
+}
+
+type UserLoginHistory struct {
+ User *User `json:"user"` // 用户信息
+ IPInfo *IPInfo `json:"ip_info"` // IP信息
+ ClientVersion string `json:"client_version"` // 客户端版本
+ Device string `json:"device"` // 设备信息
+ CreatedAt int64 `json:"created_at"` // 登录时间
+}
+
+func (l *UserLoginHistory) From(e *db.UserLoginHistory) *UserLoginHistory {
+ if e == nil {
+ return l
+ }
+
+ l.User = cvt.From(e.Edges.Owner, &User{})
+ l.IPInfo = &IPInfo{
+ IP: e.IP,
+ Country: e.Country,
+ Province: e.Province,
+ City: e.City,
+ ISP: e.Isp,
+ ASN: e.Asn,
+ }
+ l.ClientVersion = e.ClientVersion
+ l.Device = e.Device
+ l.CreatedAt = e.CreatedAt.Unix()
+
+ return l
+}
+
+type AdminLoginHistory struct {
+ User *AdminUser `json:"user"` // 用户信息
+ IPInfo *IPInfo `json:"ip_info"` // IP信息
+ ClientVersion string `json:"client_version"` // 客户端版本
+ Device string `json:"device"` // 设备信息
+ CreatedAt int64 `json:"created_at"` // 登录时间
+}
+
+func (l *AdminLoginHistory) From(e *db.AdminLoginHistory) *AdminLoginHistory {
+ if e == nil {
+ return l
+ }
+
+ l.User = cvt.From(e.Edges.Owner, &AdminUser{})
+ l.IPInfo = &IPInfo{
+ IP: e.IP,
+ Country: e.Country,
+ Province: e.Province,
+ City: e.City,
+ ISP: e.Isp,
+ ASN: e.Asn,
+ }
+ l.ClientVersion = e.ClientVersion
+ l.Device = e.Device
+ l.CreatedAt = e.CreatedAt.Unix()
+
+ return l
+}
+
+type ListUserResp struct {
+ *db.PageInfo
+
+ Users []*User `json:"users"`
+}
+
+type ListAdminUserResp struct {
+ *db.PageInfo
+
+ Users []*AdminUser `json:"users"`
+}
+
+type User struct {
+ ID string `json:"id"` // 用户ID
+ Username string `json:"username"` // 用户名
+ Email string `json:"email"` // 邮箱
+ TwoStepAuth bool `json:"two_step_auth"` // 是否开启两步验证
+ Status consts.UserStatus `json:"status"` // 用户状态 active: 正常 locked: 锁定 inactive: 禁用
+ CreatedAt int64 `json:"created_at"` // 创建时间
+ LastActiveAt int64 `json:"last_active_at"` // 最后活跃时间
+}
+
+func (u *User) From(e *db.User) *User {
+ if e == nil {
+ return u
+ }
+
+ u.ID = e.ID.String()
+ u.Username = e.Username
+ u.Email = e.Email
+ u.Status = e.Status
+ u.CreatedAt = e.CreatedAt.Unix()
+
+ return u
+}
+
+type AdminUser struct {
+ ID string `json:"id"` // 用户ID
+ Username string `json:"username"` // 用户名
+ LastActiveAt int64 `json:"last_active_at"` // 最后活跃时间
+ Status consts.AdminStatus `json:"status"` // 用户状态 active: 正常 inactive: 禁用
+ CreatedAt int64 `json:"created_at"` // 创建时间
+}
+
+func (a *AdminUser) From(e *db.Admin) *AdminUser {
+ if e == nil {
+ return a
+ }
+
+ a.ID = e.ID.String()
+ a.Username = e.Username
+ a.LastActiveAt = e.LastActiveAt.Unix()
+ a.Status = e.Status
+ a.CreatedAt = e.CreatedAt.Unix()
+
+ return a
+}
+
+type VSCodeSession struct {
+ ID string `json:"id"` // 会话ID
+ State string `json:"state"` // 状态
+ RedirectURI string `json:"redirect_uri"` // 重定向URI
+}
+
+type UpdateSettingReq struct {
+ EnableSSO *bool `json:"enable_sso"` // 是否开启SSO
+ ForceTwoFactorAuth *bool `json:"force_two_factor_auth"` // 是否强制两步验证
+ DisablePasswordLogin *bool `json:"disable_password_login"` // 是否禁用密码登录
+}
+
+type Setting struct {
+ EnableSSO bool `json:"enable_sso"` // 是否开启SSO
+ ForceTwoFactorAuth bool `json:"force_two_factor_auth"` // 是否强制两步验证
+ DisablePasswordLogin bool `json:"disable_password_login"` // 是否禁用密码登录
+ CreatedAt int64 `json:"created_at"` // 创建时间
+ UpdatedAt int64 `json:"updated_at"` // 更新时间
+}
+
+func (s *Setting) From(e *db.Setting) *Setting {
+ if e == nil {
+ return s
+ }
+
+ s.EnableSSO = e.EnableSSO
+ s.ForceTwoFactorAuth = e.ForceTwoFactorAuth
+ s.DisablePasswordLogin = e.DisablePasswordLogin
+ s.CreatedAt = e.CreatedAt.Unix()
+ s.UpdatedAt = e.UpdatedAt.Unix()
+
+ return s
+}
diff --git a/backend/ent/entc.go b/backend/ent/entc.go
new file mode 100644
index 0000000..67335d4
--- /dev/null
+++ b/backend/ent/entc.go
@@ -0,0 +1,35 @@
+//go:build ignore
+// +build ignore
+
+package main
+
+import (
+ "log"
+
+ "entgo.io/ent/entc"
+ "entgo.io/ent/entc/gen"
+
+ "github.com/chaitin/MonkeyCode/backend/pkg/entx"
+)
+
+func main() {
+ if err := entc.Generate(
+ "./schema",
+ &gen.Config{
+ Target: "../db",
+ Package: "github.com/chaitin/MonkeyCode/backend/db",
+ Features: []gen.Feature{
+ gen.FeatureUpsert,
+ gen.FeatureModifier,
+ gen.FeatureExecQuery,
+ gen.FeatureIntercept,
+ gen.FeatureLock,
+ },
+ },
+ entc.Extensions(
+ &entx.Page{},
+ ),
+ ); err != nil {
+ log.Fatal("running ent codegen:", err)
+ }
+}
diff --git a/backend/ent/generate.go b/backend/ent/generate.go
new file mode 100644
index 0000000..8232761
--- /dev/null
+++ b/backend/ent/generate.go
@@ -0,0 +1,3 @@
+package ent
+
+//go:generate go run -mod=mod entc.go
diff --git a/backend/ent/schema/admin.go b/backend/ent/schema/admin.go
new file mode 100644
index 0000000..18754df
--- /dev/null
+++ b/backend/ent/schema/admin.go
@@ -0,0 +1,47 @@
+package schema
+
+import (
+ "time"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect/entsql"
+ "entgo.io/ent/schema"
+ "entgo.io/ent/schema/edge"
+ "entgo.io/ent/schema/field"
+ "github.com/google/uuid"
+
+ "github.com/chaitin/MonkeyCode/backend/consts"
+)
+
+// Admin holds the schema definition for the Admin entity.
+type Admin struct {
+ ent.Schema
+}
+
+func (Admin) Annotations() []schema.Annotation {
+ return []schema.Annotation{
+ entsql.Annotation{
+ Table: "admins",
+ },
+ }
+}
+
+// Fields of the Admin.
+func (Admin) Fields() []ent.Field {
+ return []ent.Field{
+ field.UUID("id", uuid.UUID{}),
+ field.String("username").Unique(),
+ field.String("password"),
+ field.String("status").GoType(consts.AdminStatus("")),
+ field.Time("last_active_at").Default(time.Now),
+ field.Time("created_at").Default(time.Now),
+ field.Time("updated_at").Default(time.Now).UpdateDefault(time.Now),
+ }
+}
+
+// Edges of the Admin.
+func (Admin) Edges() []ent.Edge {
+ return []ent.Edge{
+ edge.To("login_histories", AdminLoginHistory.Type),
+ }
+}
diff --git a/backend/ent/schema/adminloginhistory.go b/backend/ent/schema/adminloginhistory.go
new file mode 100644
index 0000000..2c424cb
--- /dev/null
+++ b/backend/ent/schema/adminloginhistory.go
@@ -0,0 +1,49 @@
+package schema
+
+import (
+ "time"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect/entsql"
+ "entgo.io/ent/schema"
+ "entgo.io/ent/schema/edge"
+ "entgo.io/ent/schema/field"
+ "github.com/google/uuid"
+)
+
+// AdminLoginHistory holds the schema definition for the AdminLoginHistory entity.
+type AdminLoginHistory struct {
+ ent.Schema
+}
+
+func (AdminLoginHistory) Annotations() []schema.Annotation {
+ return []schema.Annotation{
+ entsql.Annotation{
+ Table: "admin_login_histories",
+ },
+ }
+}
+
+// Fields of the AdminLoginHistory.
+func (AdminLoginHistory) Fields() []ent.Field {
+ return []ent.Field{
+ field.UUID("id", uuid.UUID{}),
+ field.UUID("admin_id", uuid.UUID{}),
+ field.String("ip"),
+ field.String("country"),
+ field.String("province"),
+ field.String("city"),
+ field.String("isp"),
+ field.String("asn"),
+ field.String("client_version"),
+ field.String("device"),
+ field.Time("created_at").Default(time.Now),
+ }
+}
+
+// Edges of the AdminLoginHistory.
+func (AdminLoginHistory) Edges() []ent.Edge {
+ return []ent.Edge{
+ edge.From("owner", Admin.Type).Ref("login_histories").Unique(),
+ }
+}
diff --git a/backend/ent/schema/apikey.go b/backend/ent/schema/apikey.go
new file mode 100644
index 0000000..f935325
--- /dev/null
+++ b/backend/ent/schema/apikey.go
@@ -0,0 +1,45 @@
+package schema
+
+import (
+ "time"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect/entsql"
+ "entgo.io/ent/schema"
+ "entgo.io/ent/schema/field"
+ "github.com/google/uuid"
+
+ "github.com/chaitin/MonkeyCode/backend/consts"
+)
+
+// ApiKey holds the schema definition for the ApiKey entity.
+type ApiKey struct {
+ ent.Schema
+}
+
+func (ApiKey) Annotations() []schema.Annotation {
+ return []schema.Annotation{
+ entsql.Annotation{
+ Table: "api_keys",
+ },
+ }
+}
+
+// Fields of the ApiKey.
+func (ApiKey) Fields() []ent.Field {
+ return []ent.Field{
+ field.UUID("id", uuid.UUID{}),
+ field.UUID("user_id", uuid.UUID{}),
+ field.String("key"),
+ field.String("name"),
+ field.String("status").GoType(consts.ApiKeyStatus("")).Default(string(consts.ApiKeyStatusActive)),
+ field.Time("last_used").Optional(),
+ field.Time("created_at").Default(time.Now),
+ field.Time("updated_at").Default(time.Now).UpdateDefault(time.Now),
+ }
+}
+
+// Edges of the ApiKey.
+func (ApiKey) Edges() []ent.Edge {
+ return nil
+}
diff --git a/backend/ent/schema/billingplan.go b/backend/ent/schema/billingplan.go
new file mode 100644
index 0000000..3fef094
--- /dev/null
+++ b/backend/ent/schema/billingplan.go
@@ -0,0 +1,40 @@
+package schema
+
+import (
+ "time"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect/entsql"
+ "entgo.io/ent/schema"
+ "entgo.io/ent/schema/field"
+)
+
+// BillingPlan holds the schema definition for the BillingPlan entity.
+type BillingPlan struct {
+ ent.Schema
+}
+
+func (BillingPlan) Annotations() []schema.Annotation {
+ return []schema.Annotation{
+ entsql.Annotation{
+ Table: "billing_plans",
+ },
+ }
+}
+
+// Fields of the BillingPlan.
+func (BillingPlan) Fields() []ent.Field {
+ return []ent.Field{
+ field.String("id").Unique(),
+ field.String("name").Unique(),
+ field.String("description"),
+ field.JSON("rules", map[string]any{}),
+ field.Time("created_at").Default(time.Now),
+ field.Time("updated_at").Default(time.Now).UpdateDefault(time.Now),
+ }
+}
+
+// Edges of the BillingPlan.
+func (BillingPlan) Edges() []ent.Edge {
+ return nil
+}
diff --git a/backend/ent/schema/billingquota.go b/backend/ent/schema/billingquota.go
new file mode 100644
index 0000000..2df02a4
--- /dev/null
+++ b/backend/ent/schema/billingquota.go
@@ -0,0 +1,49 @@
+package schema
+
+import (
+ "time"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect/entsql"
+ "entgo.io/ent/schema"
+ "entgo.io/ent/schema/field"
+
+ "github.com/chaitin/MonkeyCode/backend/pkg/entx"
+)
+
+// BillingQuota holds the schema definition for the BillingQuota entity.
+type BillingQuota struct {
+ ent.Schema
+}
+
+func (BillingQuota) Annotations() []schema.Annotation {
+ return []schema.Annotation{
+ entsql.Annotation{
+ Table: "billing_quotas",
+ },
+ }
+}
+
+func (BillingQuota) Mixin() []ent.Mixin {
+ return []ent.Mixin{
+ entx.SoftDeleteMixin{},
+ }
+}
+
+// Fields of the BillingQuota.
+func (BillingQuota) Fields() []ent.Field {
+ return []ent.Field{
+ field.String("id").Unique(),
+ field.String("user_id").Unique(),
+ field.Int64("total"),
+ field.Int64("used"),
+ field.Int64("remain"),
+ field.Time("created_at").Default(time.Now),
+ field.Time("updated_at").Default(time.Now).UpdateDefault(time.Now),
+ }
+}
+
+// Edges of the BillingQuota.
+func (BillingQuota) Edges() []ent.Edge {
+ return nil
+}
diff --git a/backend/ent/schema/billingrecord.go b/backend/ent/schema/billingrecord.go
new file mode 100644
index 0000000..8523beb
--- /dev/null
+++ b/backend/ent/schema/billingrecord.go
@@ -0,0 +1,46 @@
+package schema
+
+import (
+ "time"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect/entsql"
+ "entgo.io/ent/schema"
+ "entgo.io/ent/schema/field"
+)
+
+// BillingRecord holds the schema definition for the BillingRecord entity.
+type BillingRecord struct {
+ ent.Schema
+}
+
+func (BillingRecord) Annotations() []schema.Annotation {
+ return []schema.Annotation{
+ entsql.Annotation{
+ Table: "billing_records",
+ },
+ }
+}
+
+// Fields of the BillingRecord.
+func (BillingRecord) Fields() []ent.Field {
+ return []ent.Field{
+ field.String("id").Unique(),
+ field.String("tenant_id").Unique(),
+ field.String("user_id").Unique(),
+ field.String("model"),
+ field.String("operation"),
+ field.Int64("input_tokens"),
+ field.Int64("output_tokens"),
+ field.Int64("cost"),
+ field.Time("request_time").Default(time.Now),
+ field.JSON("metadata", map[string]any{}),
+ field.Time("created_at").Default(time.Now),
+ field.Time("updated_at").Default(time.Now).UpdateDefault(time.Now),
+ }
+}
+
+// Edges of the BillingRecord.
+func (BillingRecord) Edges() []ent.Edge {
+ return nil
+}
diff --git a/backend/ent/schema/billingusage.go b/backend/ent/schema/billingusage.go
new file mode 100644
index 0000000..7e7efca
--- /dev/null
+++ b/backend/ent/schema/billingusage.go
@@ -0,0 +1,49 @@
+package schema
+
+import (
+ "time"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect/entsql"
+ "entgo.io/ent/schema"
+ "entgo.io/ent/schema/field"
+
+ "github.com/chaitin/MonkeyCode/backend/pkg/entx"
+)
+
+// BillingUsage holds the schema definition for the BillingUsage entity.
+type BillingUsage struct {
+ ent.Schema
+}
+
+func (BillingUsage) Annotations() []schema.Annotation {
+ return []schema.Annotation{
+ entsql.Annotation{
+ Table: "billing_usages",
+ },
+ }
+}
+
+func (BillingUsage) Mixin() []ent.Mixin {
+ return []ent.Mixin{
+ entx.SoftDeleteMixin{},
+ }
+}
+
+// Fields of the BillingUsage.
+func (BillingUsage) Fields() []ent.Field {
+ return []ent.Field{
+ field.String("id").Unique(),
+ field.String("user_id").Unique(),
+ field.String("model_name"),
+ field.Int64("tokens"),
+ field.String("operation"),
+ field.Time("created_at").Default(time.Now),
+ field.Time("updated_at").Default(time.Now).UpdateDefault(time.Now),
+ }
+}
+
+// Edges of the BillingUsage.
+func (BillingUsage) Edges() []ent.Edge {
+ return nil
+}
diff --git a/backend/ent/schema/invitecode.go b/backend/ent/schema/invitecode.go
new file mode 100644
index 0000000..c266e71
--- /dev/null
+++ b/backend/ent/schema/invitecode.go
@@ -0,0 +1,40 @@
+package schema
+
+import (
+ "time"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect/entsql"
+ "entgo.io/ent/schema"
+ "entgo.io/ent/schema/field"
+ "github.com/google/uuid"
+)
+
+// InviteCode holds the schema definition for the InviteCode entity.
+type InviteCode struct {
+ ent.Schema
+}
+
+func (InviteCode) Annotations() []schema.Annotation {
+ return []schema.Annotation{
+ entsql.Annotation{
+ Table: "invite_codes",
+ },
+ }
+}
+
+// Fields of the InviteCode.
+func (InviteCode) Fields() []ent.Field {
+ return []ent.Field{
+ field.UUID("id", uuid.UUID{}),
+ field.UUID("admin_id", uuid.UUID{}),
+ field.String("code").Unique(),
+ field.Time("created_at").Default(time.Now),
+ field.Time("updated_at").Default(time.Now).UpdateDefault(time.Now),
+ }
+}
+
+// Edges of the InviteCode.
+func (InviteCode) Edges() []ent.Edge {
+ return nil
+}
diff --git a/backend/ent/schema/model.go b/backend/ent/schema/model.go
new file mode 100644
index 0000000..3037a92
--- /dev/null
+++ b/backend/ent/schema/model.go
@@ -0,0 +1,54 @@
+package schema
+
+import (
+ "time"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect/entsql"
+ "entgo.io/ent/schema"
+ "entgo.io/ent/schema/edge"
+ "entgo.io/ent/schema/field"
+ "github.com/google/uuid"
+
+ "github.com/chaitin/MonkeyCode/backend/consts"
+)
+
+// Model holds the schema definition for the Model entity.
+type Model struct {
+ ent.Schema
+}
+
+func (Model) Annotations() []schema.Annotation {
+ return []schema.Annotation{
+ entsql.Annotation{
+ Table: "models",
+ },
+ }
+}
+
+// Fields of the Model.
+func (Model) Fields() []ent.Field {
+ return []ent.Field{
+ field.UUID("id", uuid.UUID{}),
+ field.UUID("user_id", uuid.UUID{}).Optional(),
+ field.String("model_name"),
+ field.String("model_type").GoType(consts.ModelType("")),
+ field.String("api_base"),
+ field.String("api_key"),
+ field.String("api_version").Optional(),
+ field.String("description").Optional(),
+ field.String("provider"),
+ field.String("status").GoType(consts.ModelStatus("")).Default(string(consts.ModelStatusActive)),
+ field.Int("context_length").Optional(),
+ field.Time("created_at").Default(time.Now),
+ field.Time("updated_at").Default(time.Now).UpdateDefault(time.Now),
+ }
+}
+
+// Edges of the Model.
+func (Model) Edges() []ent.Edge {
+ return []ent.Edge{
+ edge.To("records", Record.Type),
+ edge.From("user", User.Type).Ref("models").Field("user_id").Unique(),
+ }
+}
diff --git a/backend/ent/schema/record.go b/backend/ent/schema/record.go
new file mode 100644
index 0000000..f743f3c
--- /dev/null
+++ b/backend/ent/schema/record.go
@@ -0,0 +1,56 @@
+package schema
+
+import (
+ "time"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect/entsql"
+ "entgo.io/ent/schema"
+ "entgo.io/ent/schema/edge"
+ "entgo.io/ent/schema/field"
+ "github.com/google/uuid"
+
+ "github.com/chaitin/MonkeyCode/backend/consts"
+)
+
+// Record holds the schema definition for the Record entity.
+type Record struct {
+ ent.Schema
+}
+
+func (Record) Annotations() []schema.Annotation {
+ return []schema.Annotation{
+ entsql.Annotation{
+ Table: "records",
+ },
+ }
+}
+
+// Fields of the Record.
+func (Record) Fields() []ent.Field {
+ return []ent.Field{
+ field.UUID("id", uuid.UUID{}),
+ field.UUID("user_id", uuid.UUID{}).Optional(),
+ field.UUID("model_id", uuid.UUID{}).Optional(),
+ field.String("task_id"),
+ field.String("model_type").GoType(consts.ModelType("")).Optional(),
+ field.String("prompt").Optional(),
+ field.String("completion").Optional(),
+ field.Bool("is_accept").Default(false),
+ field.String("program_language").Optional(),
+ field.String("work_mode").Optional(),
+ field.Int64("code_lines").Optional(),
+ field.Int64("input_tokens"),
+ field.Int64("output_tokens"),
+ field.Time("created_at").Default(time.Now),
+ field.Time("updated_at").Default(time.Now).UpdateDefault(time.Now),
+ }
+}
+
+// Edges of the Record.
+func (Record) Edges() []ent.Edge {
+ return []ent.Edge{
+ edge.From("user", User.Type).Ref("records").Field("user_id").Unique(),
+ edge.From("model", Model.Type).Ref("records").Field("model_id").Unique(),
+ }
+}
diff --git a/backend/ent/schema/setting.go b/backend/ent/schema/setting.go
new file mode 100644
index 0000000..b58e519
--- /dev/null
+++ b/backend/ent/schema/setting.go
@@ -0,0 +1,42 @@
+package schema
+
+import (
+ "time"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect/entsql"
+ "entgo.io/ent/schema"
+ "entgo.io/ent/schema/field"
+
+ "github.com/google/uuid"
+)
+
+// Setting holds the schema definition for the Setting entity.
+type Setting struct {
+ ent.Schema
+}
+
+func (Setting) Annotations() []schema.Annotation {
+ return []schema.Annotation{
+ entsql.Annotation{
+ Table: "settings",
+ },
+ }
+}
+
+// Fields of the Setting.
+func (Setting) Fields() []ent.Field {
+ return []ent.Field{
+ field.UUID("id", uuid.UUID{}),
+ field.Bool("enable_sso").Default(false),
+ field.Bool("force_two_factor_auth").Default(false),
+ field.Bool("disable_password_login").Default(false),
+ field.Time("created_at").Default(time.Now),
+ field.Time("updated_at").Default(time.Now).UpdateDefault(time.Now),
+ }
+}
+
+// Edges of the Setting.
+func (Setting) Edges() []ent.Edge {
+ return nil
+}
diff --git a/backend/ent/schema/user.go b/backend/ent/schema/user.go
new file mode 100644
index 0000000..cee8ba3
--- /dev/null
+++ b/backend/ent/schema/user.go
@@ -0,0 +1,49 @@
+package schema
+
+import (
+ "time"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect/entsql"
+ "entgo.io/ent/schema"
+ "entgo.io/ent/schema/edge"
+ "entgo.io/ent/schema/field"
+ "github.com/google/uuid"
+
+ "github.com/chaitin/MonkeyCode/backend/consts"
+)
+
+// User holds the schema definition for the User entity.
+type User struct {
+ ent.Schema
+}
+
+func (User) Annotations() []schema.Annotation {
+ return []schema.Annotation{
+ entsql.Annotation{
+ Table: "users",
+ },
+ }
+}
+
+// Fields of the User.
+func (User) Fields() []ent.Field {
+ return []ent.Field{
+ field.UUID("id", uuid.UUID{}),
+ field.String("username").Unique(),
+ field.String("password"),
+ field.String("email").Unique(),
+ field.String("status").GoType(consts.UserStatus("")).Default(string(consts.UserStatusActive)),
+ field.Time("created_at").Default(time.Now),
+ field.Time("updated_at").Default(time.Now),
+ }
+}
+
+// Edges of the User.
+func (User) Edges() []ent.Edge {
+ return []ent.Edge{
+ edge.To("records", Record.Type),
+ edge.To("login_histories", UserLoginHistory.Type),
+ edge.To("models", Model.Type),
+ }
+}
diff --git a/backend/ent/schema/userloginhistory.go b/backend/ent/schema/userloginhistory.go
new file mode 100644
index 0000000..f05fa00
--- /dev/null
+++ b/backend/ent/schema/userloginhistory.go
@@ -0,0 +1,49 @@
+package schema
+
+import (
+ "time"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect/entsql"
+ "entgo.io/ent/schema"
+ "entgo.io/ent/schema/edge"
+ "entgo.io/ent/schema/field"
+ "github.com/google/uuid"
+)
+
+// UserLoginHistory holds the schema definition for the UserLoginHistory entity.
+type UserLoginHistory struct {
+ ent.Schema
+}
+
+func (UserLoginHistory) Annotations() []schema.Annotation {
+ return []schema.Annotation{
+ entsql.Annotation{
+ Table: "user_login_histories",
+ },
+ }
+}
+
+// Fields of the UserLoginHistory.
+func (UserLoginHistory) Fields() []ent.Field {
+ return []ent.Field{
+ field.UUID("id", uuid.UUID{}),
+ field.UUID("user_id", uuid.UUID{}),
+ field.String("ip"),
+ field.String("country"),
+ field.String("province"),
+ field.String("city"),
+ field.String("isp"),
+ field.String("asn"),
+ field.String("client_version"),
+ field.String("device"),
+ field.Time("created_at").Default(time.Now),
+ }
+}
+
+// Edges of the UserLoginHistory.
+func (UserLoginHistory) Edges() []ent.Edge {
+ return []ent.Edge{
+ edge.From("owner", User.Type).Ref("login_histories").Unique(),
+ }
+}
diff --git a/backend/errcode/errcode.go b/backend/errcode/errcode.go
new file mode 100644
index 0000000..780bd1b
--- /dev/null
+++ b/backend/errcode/errcode.go
@@ -0,0 +1,18 @@
+package errcode
+
+import (
+ "embed"
+
+ "github.com/GoYoko/web"
+)
+
+//go:embed locale.*.toml
+var LocalFS embed.FS
+
+var (
+ ErrPermission = web.NewBadRequestErr("err-permission")
+ ErrUserNotFound = web.NewBadRequestErr("err-user-not-found")
+ ErrPassword = web.NewBadRequestErr("err-password")
+ ErrInviteCodeInvalid = web.NewBadRequestErr("err-invite-code-invalid")
+ ErrEmailInvalid = web.NewBadRequestErr("err-email-invalid")
+)
diff --git a/backend/errcode/locale.zh.toml b/backend/errcode/locale.zh.toml
new file mode 100644
index 0000000..7e0eb8e
--- /dev/null
+++ b/backend/errcode/locale.zh.toml
@@ -0,0 +1,14 @@
+[err-permission]
+other = "无权操作"
+
+[err-user-not-found]
+other = "用户不存在"
+
+[err-password]
+other = "密码错误"
+
+[err-invite-code-invalid]
+other = "邀请码无效"
+
+[err-email-invalid]
+other = "邮箱格式错误"
\ No newline at end of file
diff --git a/backend/go.mod b/backend/go.mod
new file mode 100644
index 0000000..153d31d
--- /dev/null
+++ b/backend/go.mod
@@ -0,0 +1,69 @@
+module github.com/chaitin/MonkeyCode/backend
+
+go 1.23.7
+
+require (
+ entgo.io/ent v0.14.4
+ github.com/GoYoko/web v1.0.0
+ github.com/golang-migrate/migrate/v4 v4.18.3
+ github.com/google/uuid v1.6.0
+ github.com/google/wire v0.6.0
+ github.com/labstack/echo/v4 v4.13.4
+ github.com/lib/pq v1.10.9
+ github.com/redis/go-redis/v9 v9.7.3
+ github.com/rokku-c/go-openai v1.35.7-fix2
+ github.com/spf13/viper v1.20.1
+ golang.org/x/crypto v0.39.0
+ golang.org/x/text v0.26.0
+)
+
+require (
+ ariga.io/atlas v0.32.1 // indirect
+ github.com/BurntSushi/toml v1.5.0 // indirect
+ github.com/agext/levenshtein v1.2.3 // indirect
+ github.com/apparentlymart/go-textseg/v15 v15.0.0 // indirect
+ github.com/bmatcuk/doublestar v1.3.4 // indirect
+ github.com/cespare/xxhash/v2 v2.3.0 // indirect
+ github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
+ github.com/fsnotify/fsnotify v1.9.0 // indirect
+ github.com/gabriel-vasile/mimetype v1.4.9 // indirect
+ github.com/go-openapi/inflect v0.21.2 // indirect
+ github.com/go-playground/locales v0.14.1 // indirect
+ github.com/go-playground/universal-translator v0.18.1 // indirect
+ github.com/go-playground/validator/v10 v10.26.0 // indirect
+ github.com/go-viper/mapstructure/v2 v2.2.1 // indirect
+ github.com/google/go-cmp v0.7.0 // indirect
+ github.com/hashicorp/errwrap v1.1.0 // indirect
+ github.com/hashicorp/go-multierror v1.1.1 // indirect
+ github.com/hashicorp/hcl/v2 v2.23.0 // indirect
+ github.com/labstack/gommon v0.4.2 // indirect
+ github.com/leodido/go-urn v1.4.0 // indirect
+ github.com/mattn/go-colorable v0.1.14 // indirect
+ github.com/mattn/go-isatty v0.0.20 // indirect
+ github.com/mitchellh/go-wordwrap v1.0.1 // indirect
+ github.com/nicksnyder/go-i18n/v2 v2.6.0 // indirect
+ github.com/pelletier/go-toml/v2 v2.2.4 // indirect
+ github.com/rogpeppe/go-internal v1.14.1 // indirect
+ github.com/rs/xid v1.6.0 // indirect
+ github.com/sagikazarmark/locafero v0.9.0 // indirect
+ github.com/sourcegraph/conc v0.3.0 // indirect
+ github.com/spf13/afero v1.14.0 // indirect
+ github.com/spf13/cast v1.7.1 // indirect
+ github.com/spf13/pflag v1.0.6 // indirect
+ github.com/subosito/gotenv v1.6.0 // indirect
+ github.com/valyala/bytebufferpool v1.0.0 // indirect
+ github.com/valyala/fasttemplate v1.2.2 // indirect
+ github.com/zclconf/go-cty v1.16.2 // indirect
+ github.com/zclconf/go-cty-yaml v1.1.0 // indirect
+ go.opentelemetry.io/otel/metric v1.35.0 // indirect
+ go.opentelemetry.io/otel/trace v1.35.0 // indirect
+ go.uber.org/atomic v1.11.0 // indirect
+ go.uber.org/multierr v1.11.0 // indirect
+ golang.org/x/mod v0.25.0 // indirect
+ golang.org/x/net v0.41.0 // indirect
+ golang.org/x/sync v0.15.0 // indirect
+ golang.org/x/sys v0.33.0 // indirect
+ golang.org/x/time v0.11.0 // indirect
+ golang.org/x/tools v0.33.0 // indirect
+ gopkg.in/yaml.v3 v3.0.1 // indirect
+)
diff --git a/backend/go.sum b/backend/go.sum
new file mode 100644
index 0000000..03da42c
--- /dev/null
+++ b/backend/go.sum
@@ -0,0 +1,243 @@
+ariga.io/atlas v0.32.1 h1:cVCxz6D2SRvlKn/1Yne+WaZEFBjji7lR4DklgP+6Py0=
+ariga.io/atlas v0.32.1/go.mod h1:Oe1xWPuu5q9LzyrWfbZmEZxFYeu4BHTyzfjeW2aZp/w=
+entgo.io/ent v0.14.4 h1:/DhDraSLXIkBhyiVoJeSshr4ZYi7femzhj6/TckzZuI=
+entgo.io/ent v0.14.4/go.mod h1:aDPE/OziPEu8+OWbzy4UlvWmD2/kbRuWfK2A40hcxJM=
+github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 h1:L/gRVlceqvL25UVaW/CKtUDjefjrs0SPonmDGUVOYP0=
+github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
+github.com/BurntSushi/toml v1.5.0 h1:W5quZX/G/csjUnuI8SUYlsHs9M38FC7znL0lIO+DvMg=
+github.com/BurntSushi/toml v1.5.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
+github.com/DATA-DOG/go-sqlmock v1.5.0 h1:Shsta01QNfFxHCfpW6YH2STWB0MudeXXEWMr20OEh60=
+github.com/DATA-DOG/go-sqlmock v1.5.0/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM=
+github.com/GoYoko/web v1.0.0 h1:kcNxz8BvpKavE0/iqatOmUeCXVghaoD5xYDiHDulVaE=
+github.com/GoYoko/web v1.0.0/go.mod h1:DL9/gvuUG2jcBE1XUIY+9QBrrhdshzPEdxMCzR9jUHo=
+github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
+github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
+github.com/agext/levenshtein v1.2.3 h1:YB2fHEn0UJagG8T1rrWknE3ZQzWM06O8AMAatNn7lmo=
+github.com/agext/levenshtein v1.2.3/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558=
+github.com/apparentlymart/go-textseg/v15 v15.0.0 h1:uYvfpb3DyLSCGWnctWKGj857c6ew1u1fNQOlOtuGxQY=
+github.com/apparentlymart/go-textseg/v15 v15.0.0/go.mod h1:K8XmNZdhEBkdlyDdvbmmsvpAG721bKi0joRfFdHIWJ4=
+github.com/bmatcuk/doublestar v1.3.4 h1:gPypJ5xD31uhX6Tf54sDPUOBXTqKH4c9aPY66CyQrS0=
+github.com/bmatcuk/doublestar v1.3.4/go.mod h1:wiQtGV+rzVYxB7WIlirSN++5HPtPlXEo9MEoZQC/PmE=
+github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
+github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
+github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
+github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
+github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
+github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
+github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
+github.com/dhui/dktest v0.4.5 h1:uUfYBIVREmj/Rw6MvgmqNAYzTiKOHJak+enB5Di73MM=
+github.com/dhui/dktest v0.4.5/go.mod h1:tmcyeHDKagvlDrz7gDKq4UAJOLIfVZYkfD5OnHDwcCo=
+github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=
+github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=
+github.com/docker/docker v27.2.0+incompatible h1:Rk9nIVdfH3+Vz4cyI/uhbINhEZ/oLmc+CBXmH6fbNk4=
+github.com/docker/docker v27.2.0+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=
+github.com/docker/go-connections v0.5.0 h1:USnMq7hx7gwdVZq1L49hLXaFtUdTADjXGp+uj1Br63c=
+github.com/docker/go-connections v0.5.0/go.mod h1:ov60Kzw0kKElRwhNs9UlUHAE/F9Fe6GLaXnqyDdmEXc=
+github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=
+github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
+github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
+github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
+github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
+github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
+github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
+github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
+github.com/gabriel-vasile/mimetype v1.4.9 h1:5k+WDwEsD9eTLL8Tz3L0VnmVh9QxGjRmjBvAG7U/oYY=
+github.com/gabriel-vasile/mimetype v1.4.9/go.mod h1:WnSQhFKJuBlRyLiKohA/2DtIlPFAbguNaG7QCHcyGok=
+github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
+github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
+github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
+github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
+github.com/go-openapi/inflect v0.21.2 h1:0gClGlGcxifcJR56zwvhaOulnNgnhc4qTAkob5ObnSM=
+github.com/go-openapi/inflect v0.21.2/go.mod h1:INezMuUu7SJQc2AyR3WO0DqqYUJSj8Kb4hBd7WtjlAw=
+github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
+github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
+github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
+github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
+github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
+github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
+github.com/go-playground/validator/v10 v10.26.0 h1:SP05Nqhjcvz81uJaRfEV0YBSSSGMc/iMaVtFbr3Sw2k=
+github.com/go-playground/validator/v10 v10.26.0/go.mod h1:I5QpIEbmr8On7W0TktmJAumgzX4CA1XNl4ZmDuVHKKo=
+github.com/go-test/deep v1.0.3 h1:ZrJSEWsXzPOxaZnFteGEfooLba+ju3FYIbOrS+rQd68=
+github.com/go-test/deep v1.0.3/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA=
+github.com/go-viper/mapstructure/v2 v2.2.1 h1:ZAaOCxANMuZx5RCeg0mBdEZk7DZasvvZIxtHqx8aGss=
+github.com/go-viper/mapstructure/v2 v2.2.1/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
+github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
+github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
+github.com/golang-migrate/migrate/v4 v4.18.3 h1:EYGkoOsvgHHfm5U/naS1RP/6PL/Xv3S4B/swMiAmDLs=
+github.com/golang-migrate/migrate/v4 v4.18.3/go.mod h1:99BKpIi6ruaaXRM1A77eqZ+FWPQ3cfRa+ZVy5bmWMaY=
+github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
+github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
+github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
+github.com/google/subcommands v1.2.0/go.mod h1:ZjhPrFU+Olkh9WazFPsl27BQ4UPiG37m3yTrtFlrHVk=
+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
+github.com/google/wire v0.6.0 h1:HBkoIh4BdSxoyo9PveV8giw7ZsaBOvzWKfcg/6MrVwI=
+github.com/google/wire v0.6.0/go.mod h1:F4QhpQ9EDIdJ1Mbop/NZBRB+5yrR6qg3BnctaoUk6NA=
+github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
+github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I=
+github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
+github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo=
+github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM=
+github.com/hashicorp/hcl/v2 v2.23.0 h1:Fphj1/gCylPxHutVSEOf2fBOh1VE4AuLV7+kbJf3qos=
+github.com/hashicorp/hcl/v2 v2.23.0/go.mod h1:62ZYHrXgPoX8xBnzl8QzbWq4dyDsDtfCRgIq1rbJEvA=
+github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
+github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
+github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
+github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
+github.com/labstack/echo/v4 v4.13.4 h1:oTZZW+T3s9gAu5L8vmzihV7/lkXGZuITzTQkTEhcXEA=
+github.com/labstack/echo/v4 v4.13.4/go.mod h1:g63b33BZ5vZzcIUF8AtRH40DrTlXnx4UMC8rBdndmjQ=
+github.com/labstack/gommon v0.4.2 h1:F8qTUNXgG1+6WQmqoUWnz8WiEU60mXVVw0P4ht1WRA0=
+github.com/labstack/gommon v0.4.2/go.mod h1:QlUFxVM+SNXhDL/Z7YhocGIBYOiwB0mXm1+1bAPHPyU=
+github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
+github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
+github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
+github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
+github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
+github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
+github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
+github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
+github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
+github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
+github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0=
+github.com/mitchellh/go-wordwrap v1.0.1/go.mod h1:R62XHJLzvMFRBbcrT7m7WgmE1eOyTSsCt+hzestvNj0=
+github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=
+github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo=
+github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0=
+github.com/moby/term v0.5.0/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y=
+github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A=
+github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc=
+github.com/nicksnyder/go-i18n/v2 v2.6.0 h1:C/m2NNWNiTB6SK4Ao8df5EWm3JETSTIGNXBpMJTxzxQ=
+github.com/nicksnyder/go-i18n/v2 v2.6.0/go.mod h1:88sRqr0C6OPyJn0/KRNaEz1uWorjxIKP7rUUcvycecE=
+github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
+github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
+github.com/opencontainers/image-spec v1.1.0 h1:8SG7/vwALn54lVB/0yZ/MMwhFrPYtpEHQb2IpWsCzug=
+github.com/opencontainers/image-spec v1.1.0/go.mod h1:W4s4sFTMaBeK1BQLXbG4AdM2szdn85PY75RI83NrTrM=
+github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
+github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
+github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
+github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/redis/go-redis/v9 v9.7.3 h1:YpPyAayJV+XErNsatSElgRZZVCwXX9QzkKYNvO7x0wM=
+github.com/redis/go-redis/v9 v9.7.3/go.mod h1:bGUrSggJ9X9GUmZpZNEOQKaANxSGgOEBRltRTZHSvrA=
+github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
+github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
+github.com/rokku-c/go-openai v1.35.7-fix2 h1:EfRf9p3TeEKc4J9Z9XjWkOYR6rb4dJGZtV05yJFArFI=
+github.com/rokku-c/go-openai v1.35.7-fix2/go.mod h1:cfP+tvFhvqlhYJHmkPz0PBbth2bSBratH6n0kQ4xKgQ=
+github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=
+github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
+github.com/sagikazarmark/locafero v0.9.0 h1:GbgQGNtTrEmddYDSAH9QLRyfAHY12md+8YFTqyMTC9k=
+github.com/sagikazarmark/locafero v0.9.0/go.mod h1:UBUyz37V+EdMS3hDF3QWIiVr/2dPrx49OMO0Bn0hJqk=
+github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo=
+github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0=
+github.com/spf13/afero v1.14.0 h1:9tH6MapGnn/j0eb0yIXiLjERO8RB6xIVZRDCX7PtqWA=
+github.com/spf13/afero v1.14.0/go.mod h1:acJQ8t0ohCGuMN3O+Pv0V0hgMxNYDlvdk+VTfyZmbYo=
+github.com/spf13/cast v1.7.1 h1:cuNEagBQEHWN1FnbGEjCXL2szYEXqfJPbP2HNUaca9Y=
+github.com/spf13/cast v1.7.1/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
+github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o=
+github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
+github.com/spf13/viper v1.20.1 h1:ZMi+z/lvLyPSCoNtFCpqjy0S4kPbirhpTMwl8BkW9X4=
+github.com/spf13/viper v1.20.1/go.mod h1:P9Mdzt1zoHIG8m2eZQinpiBjo6kCmZSKBClNNqjJvu4=
+github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
+github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
+github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
+github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
+github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
+github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
+github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo=
+github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
+github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
+github.com/zclconf/go-cty v1.16.2 h1:LAJSwc3v81IRBZyUVQDUdZ7hs3SYs9jv0eZJDWHD/70=
+github.com/zclconf/go-cty v1.16.2/go.mod h1:VvMs5i0vgZdhYawQNq5kePSpLAoz8u1xvZgrPIxfnZE=
+github.com/zclconf/go-cty-debug v0.0.0-20240509010212-0d6042c53940 h1:4r45xpDWB6ZMSMNJFMOjqrGHynW3DIBuR2H9j0ug+Mo=
+github.com/zclconf/go-cty-debug v0.0.0-20240509010212-0d6042c53940/go.mod h1:CmBdvvj3nqzfzJ6nTCIwDTPZ56aVGvDrmztiO5g3qrM=
+github.com/zclconf/go-cty-yaml v1.1.0 h1:nP+jp0qPHv2IhUVqmQSzjvqAWcObN0KBkUl2rWBdig0=
+github.com/zclconf/go-cty-yaml v1.1.0/go.mod h1:9YLUH4g7lOhVWqUbctnVlZ5KLpg7JAprQNgxSZ1Gyxs=
+go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=
+go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=
+go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.54.0 h1:TT4fX+nBOA/+LUkobKGW1ydGcn+G3vRw9+g5HwCphpk=
+go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.54.0/go.mod h1:L7UH0GbB0p47T4Rri3uHjbpCFYrVrwc1I25QhNPiGK8=
+go.opentelemetry.io/otel v1.35.0 h1:xKWKPxrxB6OtMCbmMY021CqC45J+3Onta9MqjhnusiQ=
+go.opentelemetry.io/otel v1.35.0/go.mod h1:UEqy8Zp11hpkUrL73gSlELM0DupHoiq72dR+Zqel/+Y=
+go.opentelemetry.io/otel/metric v1.35.0 h1:0znxYu2SNyuMSQT4Y9WDWej0VpcsxkuklLa4/siN90M=
+go.opentelemetry.io/otel/metric v1.35.0/go.mod h1:nKVFgxBZ2fReX6IlyW28MgZojkoAkJGaE8CpgeAU3oE=
+go.opentelemetry.io/otel/trace v1.35.0 h1:dPpEfJu1sDIqruz7BHFG3c7528f6ddfSWfFDVt/xgMs=
+go.opentelemetry.io/otel/trace v1.35.0/go.mod h1:WUk7DtFp1Aw2MkvqGdwiXYDZZNvA/1J8o6xRXLrIkyc=
+go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
+go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
+go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
+go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
+golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
+golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
+golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
+golang.org/x/crypto v0.18.0/go.mod h1:R0j02AL6hcrfOiy9T4ZYp/rcWeMxM3L6QYxlOuEG1mg=
+golang.org/x/crypto v0.39.0 h1:SHs+kF4LP+f+p14esP5jAoDpHU8Gu/v9lFRK6IT5imM=
+golang.org/x/crypto v0.39.0/go.mod h1:L+Xg3Wf6HoL4Bn4238Z6ft6KfEpN0tJGo53AAPC632U=
+golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
+golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
+golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
+golang.org/x/mod v0.14.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
+golang.org/x/mod v0.25.0 h1:n7a+ZbQKQA/Ysbyb0/6IbB1H/X41mKgbhfv7AfG/44w=
+golang.org/x/mod v0.25.0/go.mod h1:IXM97Txy2VM4PJ3gI61r1YEk/gAj6zAHN3AdZt6S9Ww=
+golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
+golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
+golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
+golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
+golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
+golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
+golang.org/x/net v0.20.0/go.mod h1:z8BVo6PvndSri0LbOE3hAn0apkU+1YvI6E70E9jsnvY=
+golang.org/x/net v0.41.0 h1:vBTly1HeNPEn3wtREYfy4GZ/NECgw2Cnl+nK6Nz3uvw=
+golang.org/x/net v0.41.0/go.mod h1:B/K4NNqkfmg07DQYrbwvSluqCJOOXwUjeb/5lOisjbA=
+golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
+golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
+golang.org/x/sync v0.15.0 h1:KWH3jNZsfyT6xfAfKiz6MRNmd46ByHDYaZ7KSkCtdW8=
+golang.org/x/sync v0.15.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
+golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
+golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=
+golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
+golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
+golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
+golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
+golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
+golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=
+golang.org/x/term v0.16.0/go.mod h1:yn7UURbUtPyrVJPGPq404EukNFxcm/foM+bV/bfcDsY=
+golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
+golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
+golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
+golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
+golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
+golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
+golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
+golang.org/x/text v0.26.0 h1:P42AVeLghgTYr4+xUnTRKDMqpar+PtX7KWuNQL21L8M=
+golang.org/x/text v0.26.0/go.mod h1:QK15LZJUUQVJxhz7wXgxSy/CJaTFjd0G+YLonydOVQA=
+golang.org/x/time v0.11.0 h1:/bpjEDfN9tkoN/ryeYHnv5hcMlc8ncjMcM4XBk5NWV0=
+golang.org/x/time v0.11.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
+golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
+golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
+golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
+golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
+golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
+golang.org/x/tools v0.17.0/go.mod h1:xsh6VxdV005rRVaS6SSAf9oiAqljS7UZUacMZ8Bnsps=
+golang.org/x/tools v0.33.0 h1:4qz2S3zmRxbGIhDIAgjxvFutSvH5EfnsYrRBj0UI0bc=
+golang.org/x/tools v0.33.0/go.mod h1:CIJMaWEY88juyUfo7UbgPqbC8rU2OqfAV1h2Qp0oMYI=
+golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
+gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
diff --git a/backend/internal/billing/handler/http/v1/billing.go b/backend/internal/billing/handler/http/v1/billing.go
new file mode 100644
index 0000000..abb22d5
--- /dev/null
+++ b/backend/internal/billing/handler/http/v1/billing.go
@@ -0,0 +1,107 @@
+package v1
+
+import (
+ "github.com/GoYoko/web"
+ "github.com/chaitin/MonkeyCode/backend/domain"
+ "github.com/chaitin/MonkeyCode/backend/internal/middleware"
+)
+
+type BillingHandler struct {
+ usecase domain.BillingUsecase
+}
+
+func NewBillingHandler(
+ w *web.Web,
+ usecase domain.BillingUsecase,
+ auth *middleware.AuthMiddleware,
+) *BillingHandler {
+ b := &BillingHandler{
+ usecase: usecase,
+ }
+
+ g := w.Group("/api/v1/billing")
+ g.Use(auth.Auth())
+
+ g.GET("/chat/record", web.BaseHandler(b.ListChatRecord, web.WithPage()))
+ g.GET("/completion/record", web.BaseHandler(b.ListCompletionRecord, web.WithPage()))
+ g.GET("/completion/info", web.BaseHandler(b.CompletionInfo))
+ g.GET("/chat/info", web.BaseHandler(b.ChatInfo))
+
+ return b
+}
+
+// ListChatRecord 获取对话记录
+//
+// @Tags Billing
+// @Summary 获取对话记录
+// @Description 获取对话记录
+// @ID list-chat-record
+// @Accept json
+// @Produce json
+// @Param page query web.Pagination true "分页"
+// @Success 200 {object} web.Resp{data=domain.ListChatRecordResp}
+// @Router /api/v1/billing/chat/record [get]
+func (h *BillingHandler) ListChatRecord(c *web.Context) error {
+ records, err := h.usecase.ListChatRecord(c.Request().Context(), c.Page())
+ if err != nil {
+ return err
+ }
+ return c.Success(records)
+}
+
+// ListCompletionRecord 获取补全记录
+//
+// @Tags Billing
+// @Summary 获取补全记录
+// @Description 获取补全记录
+// @ID list-completion-record
+// @Accept json
+// @Produce json
+// @Param page query web.Pagination true "分页"
+// @Success 200 {object} web.Resp{data=domain.ListCompletionRecordResp}
+// @Router /api/v1/billing/completion/record [get]
+func (h *BillingHandler) ListCompletionRecord(c *web.Context) error {
+ records, err := h.usecase.ListCompletionRecord(c.Request().Context(), c.Page())
+ if err != nil {
+ return err
+ }
+ return c.Success(records)
+}
+
+// CompletionInfo 获取补全内容
+//
+// @Tags Billing
+// @Summary 获取补全内容
+// @Description 获取补全内容
+// @ID completion-info
+// @Accept json
+// @Produce json
+// @Param id query string true "补全记录ID"
+// @Success 200 {object} web.Resp{data=domain.CompletionInfo}
+// @Router /api/v1/billing/completion/info [get]
+func (h *BillingHandler) CompletionInfo(c *web.Context) error {
+ info, err := h.usecase.CompletionInfo(c.Request().Context(), c.QueryParam("id"))
+ if err != nil {
+ return err
+ }
+ return c.Success(info)
+}
+
+// ChatInfo 获取对话内容
+//
+// @Tags Billing
+// @Summary 获取对话内容
+// @Description 获取对话内容
+// @ID chat-info
+// @Accept json
+// @Produce json
+// @Param id query string true "对话记录ID"
+// @Success 200 {object} web.Resp{data=domain.ChatInfo}
+// @Router /api/v1/billing/chat/info [get]
+func (h *BillingHandler) ChatInfo(c *web.Context) error {
+ info, err := h.usecase.ChatInfo(c.Request().Context(), c.QueryParam("id"))
+ if err != nil {
+ return err
+ }
+ return c.Success(info)
+}
diff --git a/backend/internal/billing/repo/billing.go b/backend/internal/billing/repo/billing.go
new file mode 100644
index 0000000..6e8ac2b
--- /dev/null
+++ b/backend/internal/billing/repo/billing.go
@@ -0,0 +1,95 @@
+package repo
+
+import (
+ "context"
+
+ "entgo.io/ent/dialect/sql"
+ "github.com/google/uuid"
+
+ "github.com/GoYoko/web"
+
+ "github.com/chaitin/MonkeyCode/backend/consts"
+ "github.com/chaitin/MonkeyCode/backend/db"
+ "github.com/chaitin/MonkeyCode/backend/db/record"
+ "github.com/chaitin/MonkeyCode/backend/domain"
+ "github.com/chaitin/MonkeyCode/backend/pkg/cvt"
+)
+
+type BillingRepo struct {
+ db *db.Client
+}
+
+func NewBillingRepo(db *db.Client) domain.BillingRepo {
+ return &BillingRepo{db: db}
+}
+
+// ChatInfo implements domain.BillingRepo.
+func (b *BillingRepo) ChatInfo(ctx context.Context, id string) (*domain.ChatInfo, error) {
+ uid, err := uuid.Parse(id)
+ if err != nil {
+ return nil, err
+ }
+
+ record, err := b.db.Record.Query().Where(record.ID(uid)).First(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ return cvt.From(record, &domain.ChatInfo{}), nil
+}
+
+// CompletionInfo implements domain.BillingRepo.
+func (b *BillingRepo) CompletionInfo(ctx context.Context, id string) (*domain.CompletionInfo, error) {
+ uid, err := uuid.Parse(id)
+ if err != nil {
+ return nil, err
+ }
+
+ record, err := b.db.Record.Query().Where(record.ID(uid)).First(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ return cvt.From(record, &domain.CompletionInfo{}), nil
+}
+
+// ListChatRecord implements domain.BillingRepo.
+func (b *BillingRepo) ListChatRecord(ctx context.Context, page *web.Pagination) (*domain.ListChatRecordResp, error) {
+ q := b.db.Record.Query().
+ WithUser().
+ WithModel().
+ Where(record.ModelType(consts.ModelTypeLLM)).
+ Order(record.ByCreatedAt(sql.OrderDesc()))
+
+ records, p, err := q.Page(ctx, page.Page, page.Size)
+ if err != nil {
+ return nil, err
+ }
+
+ return &domain.ListChatRecordResp{
+ PageInfo: p,
+ Records: cvt.Iter(records, func(_ int, r *db.Record) *domain.ChatRecord {
+ return cvt.From(r, &domain.ChatRecord{})
+ }),
+ }, nil
+}
+
+// ListCompletionRecord implements domain.BillingRepo.
+func (b *BillingRepo) ListCompletionRecord(ctx context.Context, page *web.Pagination) (*domain.ListCompletionRecordResp, error) {
+ q := b.db.Record.Query().
+ WithUser().
+ WithModel().
+ Where(record.ModelType(consts.ModelTypeCoder)).
+ Order(record.ByCreatedAt(sql.OrderDesc()))
+ records, p, err := q.Page(ctx, page.Page, page.Size)
+ if err != nil {
+ return nil, err
+ }
+
+ return &domain.ListCompletionRecordResp{
+ PageInfo: p,
+ Records: cvt.Iter(records, func(_ int, r *db.Record) *domain.CompletionRecord {
+ return cvt.From(r, &domain.CompletionRecord{})
+ }),
+ }, nil
+}
diff --git a/backend/internal/billing/usecase/billing.go b/backend/internal/billing/usecase/billing.go
new file mode 100644
index 0000000..ba1530d
--- /dev/null
+++ b/backend/internal/billing/usecase/billing.go
@@ -0,0 +1,37 @@
+package usecase
+
+import (
+ "context"
+
+ "github.com/GoYoko/web"
+
+ "github.com/chaitin/MonkeyCode/backend/domain"
+)
+
+type BillingUsecase struct {
+ repo domain.BillingRepo
+}
+
+func NewBillingUsecase(repo domain.BillingRepo) domain.BillingUsecase {
+ return &BillingUsecase{repo: repo}
+}
+
+// ListChatRecord implements domain.BillingUsecase.
+func (b *BillingUsecase) ListChatRecord(ctx context.Context, page *web.Pagination) (*domain.ListChatRecordResp, error) {
+ return b.repo.ListChatRecord(ctx, page)
+}
+
+// ListCompletionRecord implements domain.BillingUsecase.
+func (b *BillingUsecase) ListCompletionRecord(ctx context.Context, page *web.Pagination) (*domain.ListCompletionRecordResp, error) {
+ return b.repo.ListCompletionRecord(ctx, page)
+}
+
+// CompletionInfo implements domain.BillingUsecase.
+func (b *BillingUsecase) CompletionInfo(ctx context.Context, id string) (*domain.CompletionInfo, error) {
+ return b.repo.CompletionInfo(ctx, id)
+}
+
+// ChatInfo implements domain.BillingUsecase.
+func (b *BillingUsecase) ChatInfo(ctx context.Context, id string) (*domain.ChatInfo, error) {
+ return b.repo.ChatInfo(ctx, id)
+}
diff --git a/backend/internal/dashboard/handler/v1/dashboard.go b/backend/internal/dashboard/handler/v1/dashboard.go
new file mode 100644
index 0000000..aded30e
--- /dev/null
+++ b/backend/internal/dashboard/handler/v1/dashboard.go
@@ -0,0 +1,161 @@
+package v1
+
+import (
+ "github.com/GoYoko/web"
+
+ "github.com/chaitin/MonkeyCode/backend/domain"
+ "github.com/chaitin/MonkeyCode/backend/internal/middleware"
+)
+
+type DashboardHandler struct {
+ usecase domain.DashboardUsecase
+}
+
+func NewDashboardHandler(
+ w *web.Web,
+ usecase domain.DashboardUsecase,
+ auth *middleware.AuthMiddleware,
+) *DashboardHandler {
+ h := &DashboardHandler{usecase: usecase}
+
+ g := w.Group("/api/v1/dashboard")
+ g.Use(auth.Auth())
+ g.GET("/statistics", web.BaseHandler(h.Statistics))
+ g.GET("/category-stat", web.BaseHandler(h.CategoryStat))
+ g.GET("/time-stat", web.BaseHandler(h.TimeStat))
+ g.GET("/user-stat", web.BaseHandler(h.UserStat))
+ g.GET("/user-events", web.BaseHandler(h.UserEvents))
+ g.GET("/user-code-rank", web.BaseHandler(h.UserCodeRank))
+ g.GET("/user-heatmap", web.BaseHandler(h.UserHeatmap))
+
+ return h
+}
+
+// Statistics 获取统计信息
+//
+// @Tags Dashboard
+// @Summary 获取统计信息
+// @Description 获取统计信息
+// @ID statistics-dashboard
+// @Accept json
+// @Produce json
+// @Success 200 {object} web.Resp{data=domain.Statistics}
+// @Router /api/v1/dashboard/statistics [get]
+func (h *DashboardHandler) Statistics(c *web.Context) error {
+ statistics, err := h.usecase.Statistics(c.Request().Context())
+ if err != nil {
+ return err
+ }
+ return c.Success(statistics)
+}
+
+// CategoryStat 获取分类统计信息
+//
+// @Tags Dashboard
+// @Summary 获取分类统计信息
+// @Description 获取分类统计信息
+// @ID category-stat-dashboard
+// @Accept json
+// @Produce json
+// @Success 200 {object} web.Resp{data=domain.CategoryStat}
+// @Router /api/v1/dashboard/category-stat [get]
+func (h *DashboardHandler) CategoryStat(c *web.Context) error {
+ categoryStat, err := h.usecase.CategoryStat(c.Request().Context())
+ if err != nil {
+ return err
+ }
+ return c.Success(categoryStat)
+}
+
+// TimeStat 获取时间统计信息
+//
+// @Tags Dashboard
+// @Summary 获取时间统计信息
+// @Description 获取时间统计信息
+// @ID time-stat-dashboard
+// @Accept json
+// @Produce json
+// @Success 200 {object} web.Resp{data=domain.TimeStat}
+// @Router /api/v1/dashboard/time-stat [get]
+func (h *DashboardHandler) TimeStat(c *web.Context) error {
+ timeStat, err := h.usecase.TimeStat(c.Request().Context())
+ if err != nil {
+ return err
+ }
+ return c.Success(timeStat)
+}
+
+// UserStat 获取用户统计信息
+//
+// @Tags Dashboard
+// @Summary 获取用户统计信息
+// @Description 获取用户统计信息
+// @ID user-stat-dashboard
+// @Accept json
+// @Produce json
+// @Param user_id query string false "用户ID"
+// @Success 200 {object} web.Resp{data=domain.UserStat}
+// @Router /api/v1/dashboard/user-stat [get]
+func (h *DashboardHandler) UserStat(c *web.Context) error {
+ userStat, err := h.usecase.UserStat(c.Request().Context(), c.QueryParam("user_id"))
+ if err != nil {
+ return err
+ }
+ return c.Success(userStat)
+}
+
+// UserEvents 获取用户事件
+//
+// @Tags Dashboard
+// @Summary 获取用户事件
+// @Description 获取用户事件
+// @ID user-events-dashboard
+// @Accept json
+// @Produce json
+// @Param user_id query string true "用户ID"
+// @Success 200 {object} web.Resp{data=[]domain.UserEvent}
+// @Router /api/v1/dashboard/user-events [get]
+func (h *DashboardHandler) UserEvents(c *web.Context) error {
+ userEvents, err := h.usecase.UserEvents(c.Request().Context(), c.QueryParam("user_id"))
+ if err != nil {
+ return err
+ }
+ return c.Success(userEvents)
+}
+
+// UserCodeRank 用户贡献榜
+//
+// @Tags Dashboard
+// @Summary 用户贡献榜
+// @Description 用户贡献榜
+// @ID user-code-rank-dashboard
+// @Accept json
+// @Produce json
+// @Success 200 {object} web.Resp{data=[]domain.UserCodeRank}
+// @Router /api/v1/dashboard/user-code-rank [get]
+func (h *DashboardHandler) UserCodeRank(c *web.Context) error {
+ userCodeRank, err := h.usecase.UserCodeRank(c.Request().Context())
+ if err != nil {
+ return err
+ }
+ return c.Success(userCodeRank)
+}
+
+// UserHeatmap 用户热力图
+//
+// @Tags Dashboard
+// @Summary 用户热力图
+// @Description 用户热力图
+// @ID user-heatmap-dashboard
+// @Accept json
+// @Produce json
+// @Param user_id query string true "用户ID"
+// @Success 200 {object} web.Resp{data=domain.UserHeatmapResp}
+// @Router /api/v1/dashboard/user-heatmap [get]
+func (h *DashboardHandler) UserHeatmap(c *web.Context) error {
+ userHeatmap, err := h.usecase.UserHeatmap(c.Request().Context(), c.QueryParam("user_id"))
+ if err != nil {
+ return err
+ }
+ return c.Success(userHeatmap)
+}
diff --git a/backend/internal/dashboard/repo/dashboard.go b/backend/internal/dashboard/repo/dashboard.go
new file mode 100644
index 0000000..c055bd4
--- /dev/null
+++ b/backend/internal/dashboard/repo/dashboard.go
@@ -0,0 +1,362 @@
+package repo
+
+import (
+ "context"
+ "time"
+
+ "entgo.io/ent/dialect/sql"
+ "github.com/google/uuid"
+
+ "github.com/chaitin/MonkeyCode/backend/pkg/cvt"
+
+ "github.com/chaitin/MonkeyCode/backend/consts"
+ "github.com/chaitin/MonkeyCode/backend/db"
+ "github.com/chaitin/MonkeyCode/backend/db/record"
+ "github.com/chaitin/MonkeyCode/backend/db/user"
+ "github.com/chaitin/MonkeyCode/backend/domain"
+)
+
+type DashboardRepo struct {
+ db *db.Client
+}
+
+func NewDashboardRepo(db *db.Client) domain.DashboardRepo {
+ return &DashboardRepo{db: db}
+}
+
+// CategoryStat implements domain.DashboardRepo.
+func (d *DashboardRepo) CategoryStat(ctx context.Context) (*domain.CategoryStat, error) {
+ var cs []domain.CategoryPoint
+ if err := d.db.Record.Query().
+ Where(record.CreatedAtGTE(time.Now().AddDate(0, 0, -90))).
+ Where(record.WorkModeNEQ("")).
+ Modify(func(s *sql.Selector) {
+ s.Select(
+ sql.As("work_mode", "category"),
+ sql.As("COUNT(*)", "value"),
+ ).GroupBy(record.FieldWorkMode).
+ OrderBy(sql.Desc("value"))
+ }).
+ Scan(ctx, &cs); err != nil {
+ return nil, err
+ }
+ var ps []domain.CategoryPoint
+ if err := d.db.Record.Query().
+ Where(record.CreatedAtGTE(time.Now().AddDate(0, 0, -90))).
+ Where(record.ProgramLanguageNotNil()).
+ Modify(func(s *sql.Selector) {
+ s.Select(
+ sql.As("program_language", "category"),
+ sql.As("COUNT(*)", "value"),
+ ).GroupBy(record.FieldProgramLanguage).
+ OrderBy(sql.Desc("value"))
+ }).
+ Scan(ctx, &ps); err != nil {
+ return nil, err
+ }
+
+ return &domain.CategoryStat{
+ WorkMode: cs,
+ ProgramLanguage: ps,
+ }, nil
+}
+
+// Statistics implements domain.DashboardRepo.
+func (d *DashboardRepo) Statistics(ctx context.Context) (*domain.Statistics, error) {
+ totalUsers, err := d.db.User.Query().Count(ctx)
+ if err != nil {
+ return nil, err
+ }
+ disabledUsers, err := d.db.User.Query().Where(user.Status(consts.UserStatusInactive)).Count(ctx)
+ if err != nil {
+ return nil, err
+ }
+ return &domain.Statistics{
+ TotalUsers: int64(totalUsers),
+ DisabledUsers: int64(disabledUsers),
+ }, nil
+}
+
+type DateValue struct {
+ Date time.Time `json:"date"`
+ UserCount int64 `json:"user_count"`
+ LlmCount int64 `json:"llm_count"`
+ CodeCount int64 `json:"code_count"`
+ AcceptedCount int64 `json:"accepted_count"`
+ CodeLines int64 `json:"code_lines"`
+ Count int64 `json:"count"`
+}
+
+// TimeStat implements domain.DashboardRepo.
+func (d *DashboardRepo) TimeStat(ctx context.Context) (*domain.TimeStat, error) {
+ ds := make([]DateValue, 0)
+ if err := d.db.Record.Query().
+ Where(record.CreatedAtGTE(time.Now().AddDate(0, 0, -90))).
+ Modify(func(s *sql.Selector) {
+ s.Select(
+ sql.As("date_trunc('day', created_at)", "date"),
+ sql.As("COUNT(DISTINCT user_id)", "user_count"),
+ sql.As("COUNT(*) FILTER (WHERE model_type = 'llm')", "llm_count"),
+ sql.As("COUNT(*) FILTER (WHERE model_type = 'coder')", "code_count"),
+ sql.As("COUNT(*) FILTER (WHERE is_accept = true AND model_type = 'coder')", "accepted_count"),
+ sql.As(sql.Sum(record.FieldCodeLines), "code_lines"),
+ ).GroupBy("date").
+ OrderBy(sql.Asc("date"))
+ }).
+ Scan(ctx, &ds); err != nil {
+ return nil, err
+ }
+
+ dsOneHour := make([]DateValue, 0)
+ if err := d.db.Record.Query().
+ Where(record.CreatedAtGTE(time.Now().Add(-time.Hour))).
+ Modify(func(s *sql.Selector) {
+ s.Select(
+ sql.As("date_trunc('minute', created_at)", "date"),
+ sql.As(sql.Count("*"), "count"),
+ ).GroupBy("date").
+ OrderBy(sql.Asc("date"))
+ }).
+ Scan(ctx, &dsOneHour); err != nil {
+ return nil, err
+ }
+
+ ts := &domain.TimeStat{
+ ActiveUsers: []domain.TimePoint[int64]{},
+ RealTimeTokens: []domain.TimePoint[int64]{},
+ Chats: []domain.TimePoint[int64]{},
+ Completions: []domain.TimePoint[int64]{},
+ LinesOfCode: []domain.TimePoint[int64]{},
+ AcceptedPer: []domain.TimePoint[float64]{},
+ }
+
+ for _, v := range dsOneHour {
+ ts.RealTimeTokens = append(ts.RealTimeTokens, domain.TimePoint[int64]{
+ Timestamp: v.Date.Unix(),
+ Value: v.Count,
+ })
+ }
+
+ for _, v := range ds {
+ ts.TotalUsers += v.UserCount
+ ts.TotalChats += v.LlmCount
+ ts.TotalCompletions += v.CodeCount
+ ts.TotalLinesOfCode += v.CodeLines
+ ts.ActiveUsers = append(ts.ActiveUsers, domain.TimePoint[int64]{
+ Timestamp: v.Date.Unix(),
+ Value: v.UserCount,
+ })
+ ts.Chats = append(ts.Chats, domain.TimePoint[int64]{
+ Timestamp: v.Date.Unix(),
+ Value: v.LlmCount,
+ })
+ ts.Completions = append(ts.Completions, domain.TimePoint[int64]{
+ Timestamp: v.Date.Unix(),
+ Value: v.CodeCount,
+ })
+ ts.LinesOfCode = append(ts.LinesOfCode, domain.TimePoint[int64]{
+ Timestamp: v.Date.Unix(),
+ Value: v.CodeLines,
+ })
+ if v.CodeCount > 0 {
+ ts.AcceptedPer = append(ts.AcceptedPer, domain.TimePoint[float64]{
+ Timestamp: v.Date.Unix(),
+ Value: float64(v.AcceptedCount) / float64(v.CodeCount) * 100,
+ })
+ }
+ }
+
+ return ts, nil
+}
+
+type UserCodeRank struct {
+ UserID uuid.UUID `json:"user_id"`
+ CodeLines int64 `json:"code_lines"`
+}
+
+// UserCodeRank implements domain.DashboardRepo.
+func (d *DashboardRepo) UserCodeRank(ctx context.Context) ([]*domain.UserCodeRank, error) {
+ var rs []UserCodeRank
+ if err := d.db.Record.Query().
+ Where(record.CreatedAtGTE(time.Now().AddDate(0, 0, -90))).
+ Modify(func(s *sql.Selector) {
+ s.Select(
+ sql.As("user_id", "user_id"),
+ sql.As(sql.Sum(record.FieldCodeLines), "code_lines"),
+ ).GroupBy(record.FieldUserID).
+ OrderBy(sql.Desc("code_lines"))
+ }).
+ Scan(ctx, &rs); err != nil {
+ return nil, err
+ }
+
+ ids := cvt.Iter(rs, func(_ int, v UserCodeRank) uuid.UUID {
+ return v.UserID
+ })
+ users, err := d.db.User.Query().
+ Where(user.IDIn(ids...)).
+ All(ctx)
+ if err != nil {
+ return nil, err
+ }
+ m := cvt.IterToMap(users, func(_ int, v *db.User) (uuid.UUID, *db.User) {
+ return v.ID, v
+ })
+ return cvt.Iter(rs, func(_ int, v UserCodeRank) *domain.UserCodeRank {
+ return &domain.UserCodeRank{
+ Username: m[v.UserID].Username,
+ Lines: v.CodeLines,
+ }
+ }), nil
+}
+
+// UserEvents implements domain.DashboardRepo.
+func (d *DashboardRepo) UserEvents(ctx context.Context, userID string) ([]*domain.UserEvent, error) {
+ id, err := uuid.Parse(userID)
+ if err != nil {
+ return nil, err
+ }
+ rs, err := d.db.Record.Query().
+ WithUser().
+ Where(record.CreatedAtGTE(time.Now().AddDate(0, 0, -90))).
+ Where(record.HasUserWith(user.ID(id))).
+ Order(record.ByCreatedAt(sql.OrderDesc())).
+ Limit(100).
+ All(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ return cvt.Iter(rs, func(_ int, v *db.Record) *domain.UserEvent {
+ return &domain.UserEvent{
+ Name: v.Edges.User.Username,
+ CreatedAt: v.CreatedAt.Unix(),
+ }
+ }), nil
+}
+
+// UserStat implements domain.DashboardRepo.
+func (d *DashboardRepo) UserStat(ctx context.Context, userID string) (*domain.UserStat, error) {
+ id, err := uuid.Parse(userID)
+ if err != nil {
+ return nil, err
+ }
+ var ds []DateValue
+ if err := d.db.Record.Query().
+ Where(record.HasUserWith(user.ID(id))).
+ Where(record.CreatedAtGTE(time.Now().AddDate(0, 0, -90))).
+ Modify(func(s *sql.Selector) {
+ s.Select(
+ sql.As("date_trunc('day', created_at)", "date"),
+ sql.As("COUNT(DISTINCT user_id)", "user_count"),
+ sql.As("COUNT(*) FILTER (WHERE model_type = 'llm')", "llm_count"),
+ sql.As("COUNT(*) FILTER (WHERE model_type = 'coder')", "code_count"),
+ sql.As("COUNT(*) FILTER (WHERE is_accept = true AND model_type = 'coder')", "accepted_count"),
+ sql.As(sql.Sum(record.FieldCodeLines), "code_lines"),
+ ).GroupBy("date").
+ OrderBy(sql.Asc("date"))
+ }).
+ Scan(ctx, &ds); err != nil {
+ return nil, err
+ }
+
+ var cs []domain.CategoryPoint
+ if err := d.db.Record.Query().
+ Where(record.CreatedAtGTE(time.Now().AddDate(0, 0, -90))).
+ Where(record.HasUserWith(user.ID(id))).
+ Where(record.WorkModeNotNil()).
+ Modify(func(s *sql.Selector) {
+ s.Select(
+ sql.As("work_mode", "category"),
+ sql.As("COUNT(*)", "value"),
+ ).GroupBy(record.FieldWorkMode).
+ OrderBy(sql.Desc("value"))
+ }).
+ Scan(ctx, &cs); err != nil {
+ return nil, err
+ }
+ var ps []domain.CategoryPoint
+ if err := d.db.Record.Query().
+ Where(record.CreatedAtGTE(time.Now().AddDate(0, 0, -90))).
+ Where(record.HasUserWith(user.ID(id))).
+ Where(record.ProgramLanguageNotNil()).
+ Modify(func(s *sql.Selector) {
+ s.Select(
+ sql.As("program_language", "category"),
+ sql.As("COUNT(*)", "value"),
+ ).GroupBy(record.FieldProgramLanguage).
+ OrderBy(sql.Desc("value"))
+ }).
+ Scan(ctx, &ps); err != nil {
+ return nil, err
+ }
+
+ us := &domain.UserStat{
+ WorkMode: cs,
+ ProgramLanguage: ps,
+ Chats: []domain.TimePoint[int64]{},
+ Completions: []domain.TimePoint[int64]{},
+ LinesOfCode: []domain.TimePoint[int64]{},
+ AcceptedPer: []domain.TimePoint[float64]{},
+ }
+ acceptedCount := int64(0)
+ codeCount := int64(0)
+ for _, v := range ds {
+ us.TotalChats += v.LlmCount
+ us.TotalCompletions += v.CodeCount
+ us.TotalLinesOfCode += v.CodeLines
+ acceptedCount += v.AcceptedCount
+ codeCount += v.CodeCount
+ us.Chats = append(us.Chats, domain.TimePoint[int64]{
+ Timestamp: v.Date.Unix(),
+ Value: v.LlmCount,
+ })
+ us.Completions = append(us.Completions, domain.TimePoint[int64]{
+ Timestamp: v.Date.Unix(),
+ Value: v.CodeCount,
+ })
+ us.LinesOfCode = append(us.LinesOfCode, domain.TimePoint[int64]{
+ Timestamp: v.Date.Unix(),
+ Value: v.CodeLines,
+ })
+ if v.CodeCount > 0 {
+ us.AcceptedPer = append(us.AcceptedPer, domain.TimePoint[float64]{
+ Timestamp: v.Date.Unix(),
+ Value: float64(v.AcceptedCount) / float64(v.CodeCount) * 100,
+ })
+ }
+ }
+ if codeCount > 0 {
+ us.TotalAcceptedPer = float64(acceptedCount) / float64(codeCount) * 100
+ }
+ return us, nil
+}
+
+func (d *DashboardRepo) UserHeatmap(ctx context.Context, userID string) ([]*domain.UserHeatmap, error) {
+ id, err := uuid.Parse(userID)
+ if err != nil {
+ return nil, err
+ }
+
+ var rs []DateValue
+ if err := d.db.Record.Query().
+ Where(record.HasUserWith(user.ID(id))).
+ Where(record.CreatedAtGTE(time.Now().AddDate(-1, 0, 0))).
+ Modify(func(s *sql.Selector) {
+ s.Select(
+ sql.As("date_trunc('day', created_at)", "date"),
+ sql.As("COUNT(*)", "count"),
+ ).GroupBy("date").
+ OrderBy(sql.Asc("date"))
+ }).
+ Scan(ctx, &rs); err != nil {
+ return nil, err
+ }
+
+ return cvt.Iter(rs, func(_ int, v DateValue) *domain.UserHeatmap {
+ return &domain.UserHeatmap{
+ Date: v.Date.Unix(),
+ Count: v.Count,
+ }
+ }), nil
+}
diff --git a/backend/internal/dashboard/usecase/dashboard.go b/backend/internal/dashboard/usecase/dashboard.go
new file mode 100644
index 0000000..4148e7f
--- /dev/null
+++ b/backend/internal/dashboard/usecase/dashboard.go
@@ -0,0 +1,60 @@
+package usecase
+
+import (
+ "context"
+ "slices"
+
+ "github.com/chaitin/MonkeyCode/backend/domain"
+)
+
+type DashboardUsecase struct {
+ repo domain.DashboardRepo
+}
+
+func NewDashboardUsecase(repo domain.DashboardRepo) domain.DashboardUsecase {
+ return &DashboardUsecase{
+ repo: repo,
+ }
+}
+
+func (u *DashboardUsecase) Statistics(ctx context.Context) (*domain.Statistics, error) {
+ return u.repo.Statistics(ctx)
+}
+
+func (u *DashboardUsecase) CategoryStat(ctx context.Context) (*domain.CategoryStat, error) {
+ return u.repo.CategoryStat(ctx)
+}
+
+func (u *DashboardUsecase) TimeStat(ctx context.Context) (*domain.TimeStat, error) {
+ return u.repo.TimeStat(ctx)
+}
+
+func (u *DashboardUsecase) UserStat(ctx context.Context, username string) (*domain.UserStat, error) {
+ return u.repo.UserStat(ctx, username)
+}
+
+func (u *DashboardUsecase) UserEvents(ctx context.Context, username string) ([]*domain.UserEvent, error) {
+ return u.repo.UserEvents(ctx, username)
+}
+
+func (u *DashboardUsecase) UserCodeRank(ctx context.Context) ([]*domain.UserCodeRank, error) {
+ return u.repo.UserCodeRank(ctx)
+}
+
+func (u *DashboardUsecase) UserHeatmap(ctx context.Context, userID string) (*domain.UserHeatmapResp, error) {
+ rs, err := u.repo.UserHeatmap(ctx, userID)
+ if err != nil {
+ return nil, err
+ }
+ var count int64
+ if len(rs) > 0 {
+ maxCount := slices.MaxFunc(rs, func(a, b *domain.UserHeatmap) int {
+ return int(a.Count - b.Count)
+ })
+ count = maxCount.Count
+ }
+ return &domain.UserHeatmapResp{
+ MaxCount: count,
+ Points: rs,
+ }, nil
+}
diff --git a/backend/internal/middleware/auth.go b/backend/internal/middleware/auth.go
new file mode 100644
index 0000000..c96b73d
--- /dev/null
+++ b/backend/internal/middleware/auth.go
@@ -0,0 +1,46 @@
+package middleware
+
+import (
+ "log/slog"
+ "net/http"
+
+ "github.com/labstack/echo/v4"
+
+ "github.com/chaitin/MonkeyCode/backend/consts"
+ "github.com/chaitin/MonkeyCode/backend/domain"
+ "github.com/chaitin/MonkeyCode/backend/pkg/session"
+)
+
+const (
+ userKey = "session:user"
+)
+
+type AuthMiddleware struct {
+ session *session.Session
+ logger *slog.Logger
+}
+
+func NewAuthMiddleware(session *session.Session, logger *slog.Logger) *AuthMiddleware {
+ return &AuthMiddleware{
+ session: session,
+ logger: logger,
+ }
+}
+
+func (m *AuthMiddleware) Auth() echo.MiddlewareFunc {
+ return func(next echo.HandlerFunc) echo.HandlerFunc {
+ return func(c echo.Context) error {
+ user, err := session.Get[domain.AdminUser](m.session, c, consts.SessionName)
+ if err != nil {
+ m.logger.Error("auth failed", "error", err)
+ return c.String(http.StatusUnauthorized, "Unauthorized")
+ }
+ c.Set(userKey, &user)
+ return next(c)
+ }
+ }
+}
+
+func GetUser(c echo.Context) *domain.AdminUser {
+ return c.Get(userKey).(*domain.AdminUser)
+}
diff --git a/backend/internal/middleware/logger.go b/backend/internal/middleware/logger.go
new file mode 100644
index 0000000..494ccff
--- /dev/null
+++ b/backend/internal/middleware/logger.go
@@ -0,0 +1,23 @@
+package middleware
+
+import (
+ "context"
+
+ "github.com/google/uuid"
+
+ "github.com/labstack/echo/v4"
+
+ "github.com/chaitin/MonkeyCode/backend/pkg/logger"
+)
+
+func RequestID() echo.MiddlewareFunc {
+ return func(next echo.HandlerFunc) echo.HandlerFunc {
+ return func(c echo.Context) error {
+ ctx := c.Request().Context()
+ requestID := uuid.New().String()
+ ctx = context.WithValue(ctx, logger.RequestIDKey, requestID)
+ c.SetRequest(c.Request().WithContext(ctx))
+ return next(c)
+ }
+ }
+}
diff --git a/backend/internal/middleware/proxy.go b/backend/internal/middleware/proxy.go
new file mode 100644
index 0000000..ac1269b
--- /dev/null
+++ b/backend/internal/middleware/proxy.go
@@ -0,0 +1,57 @@
+package middleware
+
+import (
+ "context"
+ "net/http"
+ "strings"
+
+ "github.com/labstack/echo/v4"
+
+ "github.com/chaitin/MonkeyCode/backend/domain"
+ "github.com/chaitin/MonkeyCode/backend/pkg/logger"
+)
+
+const (
+ ApiContextKey = "session:apikey"
+)
+
+type ProxyMiddleware struct {
+ usecase domain.ProxyUsecase
+}
+
+func NewProxyMiddleware(
+ usecase domain.ProxyUsecase,
+) *ProxyMiddleware {
+ return &ProxyMiddleware{
+ usecase: usecase,
+ }
+}
+
+func (p *ProxyMiddleware) Auth() echo.MiddlewareFunc {
+ return func(next echo.HandlerFunc) echo.HandlerFunc {
+ return func(c echo.Context) error {
+ apiKey := c.Request().Header.Get("X-API-Key")
+ if apiKey == "" {
+ apiKey = strings.TrimPrefix(c.Request().Header.Get("Authorization"), "Bearer ")
+ }
+ if apiKey == "" {
+ return c.JSON(http.StatusUnauthorized, echo.Map{"error": "Unauthorized"})
+ }
+
+ key, err := p.usecase.ValidateApiKey(c.Request().Context(), apiKey)
+ if err != nil {
+ return c.JSON(http.StatusUnauthorized, echo.Map{"error": "Unauthorized"})
+ }
+
+ ctx := c.Request().Context()
+ ctx = context.WithValue(ctx, logger.UserIDKey, key.UserID)
+ c.SetRequest(c.Request().WithContext(ctx))
+ c.Set(ApiContextKey, key)
+ return next(c)
+ }
+ }
+}
+
+func GetApiKey(c echo.Context) *domain.ApiKey {
+ return c.Get(ApiContextKey).(*domain.ApiKey)
+}
diff --git a/backend/internal/model/handler/http/v1/model.go b/backend/internal/model/handler/http/v1/model.go
new file mode 100644
index 0000000..432d682
--- /dev/null
+++ b/backend/internal/model/handler/http/v1/model.go
@@ -0,0 +1,153 @@
+package v1
+
+import (
+ "log/slog"
+
+ "github.com/GoYoko/web"
+
+ "github.com/chaitin/MonkeyCode/backend/domain"
+ "github.com/chaitin/MonkeyCode/backend/internal/middleware"
+)
+
+type ModelHandler struct {
+ usecase domain.ModelUsecase
+ logger *slog.Logger
+}
+
+func NewModelHandler(
+ w *web.Web,
+ usecase domain.ModelUsecase,
+ auth *middleware.AuthMiddleware,
+ logger *slog.Logger,
+) *ModelHandler {
+ m := &ModelHandler{usecase: usecase, logger: logger.With("handler", "model")}
+
+ g := w.Group("/api/v1/model")
+ g.Use(auth.Auth())
+
+ g.POST("/check", web.BindHandler(m.Check))
+ g.GET("", web.BaseHandler(m.List))
+ g.POST("", web.BindHandler(m.Create))
+ g.PUT("", web.BindHandler(m.Update))
+ g.GET("/token-usage", web.BindHandler(m.GetTokenUsage))
+ g.GET("/my", web.BindHandler(m.MyModelList))
+
+ return m
+}
+
+// Check 检查模型
+//
+// @Tags Model
+// @Summary 检查模型
+// @Description 检查模型
+// @ID check-model
+// @Accept json
+// @Produce json
+// @Param model body domain.CheckModelReq true "模型"
+// @Success 200 {object} web.Resp{data=domain.Model}
+// @Router /api/v1/model/check [post]
+func (h *ModelHandler) Check(c *web.Context, req domain.CheckModelReq) error {
+ m, err := h.usecase.Check(c.Request().Context(), &req)
+ if err != nil {
+ return err
+ }
+ return c.Success(m)
+}
+
+// List 获取模型列表
+//
+// @Tags Model
+// @Summary 获取模型列表
+// @Description 获取模型列表
+// @ID list-model
+// @Accept json
+// @Produce json
+// @Success 200 {object} web.Resp{data=domain.AllModelResp}
+// @Router /api/v1/model [get]
+func (h *ModelHandler) List(c *web.Context) error {
+ models, err := h.usecase.List(c.Request().Context())
+ if err != nil {
+ return err
+ }
+ return c.Success(models)
+}
+
+// MyModelList 获取我的模型列表
+//
+// @Tags Model
+// @Summary 获取我的模型列表
+// @Description 获取我的模型列表
+// @ID my-model-list
+// @Accept json
+// @Produce json
+// @Param model_type query domain.MyModelListReq true "模型类型"
+// @Success 200 {object} web.Resp{data=[]domain.Model}
+// @Router /api/v1/model/my [get]
+func (h *ModelHandler) MyModelList(c *web.Context, req domain.MyModelListReq) error {
+ user := middleware.GetUser(c)
+ req.UserID = user.ID
+ models, err := h.usecase.MyModelList(c.Request().Context(), &req)
+ if err != nil {
+ return err
+ }
+ return c.Success(models)
+}
+
+// Create 创建模型
+//
+// @Tags Model
+// @Summary 创建模型
+// @Description 创建模型
+// @ID create-model
+// @Accept json
+// @Produce json
+// @Param model body domain.CreateModelReq true "模型"
+// @Success 200 {object} web.Resp{data=domain.Model}
+// @Router /api/v1/model [post]
+func (h *ModelHandler) Create(c *web.Context, req domain.CreateModelReq) error {
+ user := middleware.GetUser(c)
+ req.UserID = user.ID
+ m, err := h.usecase.Create(c.Request().Context(), &req)
+ if err != nil {
+ return err
+ }
+ return c.Success(m)
+}
+
+// Update 更新模型
+//
+// @Tags Model
+// @Summary 更新模型
+// @Description 更新模型
+// @ID update-model
+// @Accept json
+// @Produce json
+// @Param model body domain.UpdateModelReq true "模型"
+// @Success 200 {object} web.Resp{data=domain.Model}
+// @Router /api/v1/model [put]
+func (h *ModelHandler) Update(c *web.Context, req domain.UpdateModelReq) error {
+ m, err := h.usecase.Update(c.Request().Context(), &req)
+ if err != nil {
+ return err
+ }
+ return c.Success(m)
+}
+
+// GetTokenUsage 获取模型token使用情况
+//
+// @Tags Model
+// @Summary 获取模型token使用情况
+// @Description 获取模型token使用情况
+// @ID get-token-usage
+// @Accept json
+// @Produce json
+// @Param param query domain.GetTokenUsageReq true "模型类型"
+// @Success 200 {object} web.Resp{data=domain.ModelTokenUsageResp}
+// @Router /api/v1/model/token-usage [get]
+func (h *ModelHandler) GetTokenUsage(c *web.Context, req domain.GetTokenUsageReq) error {
+ resp, err := h.usecase.GetTokenUsage(c.Request().Context(), req.ModelType)
+ if err != nil {
+ return err
+ }
+ return c.Success(resp)
+}
diff --git a/backend/internal/model/repo/model.go b/backend/internal/model/repo/model.go
new file mode 100644
index 0000000..437757c
--- /dev/null
+++ b/backend/internal/model/repo/model.go
@@ -0,0 +1,151 @@
+package repo
+
+import (
+ "context"
+ "time"
+
+ entsql "entgo.io/ent/dialect/sql"
+ "github.com/google/uuid"
+
+ "github.com/chaitin/MonkeyCode/backend/consts"
+ "github.com/chaitin/MonkeyCode/backend/db"
+ "github.com/chaitin/MonkeyCode/backend/db/model"
+ "github.com/chaitin/MonkeyCode/backend/db/record"
+ "github.com/chaitin/MonkeyCode/backend/domain"
+ "github.com/chaitin/MonkeyCode/backend/pkg/cvt"
+ "github.com/chaitin/MonkeyCode/backend/pkg/entx"
+)
+
+type ModelRepo struct {
+ db *db.Client
+}
+
+func NewModelRepo(db *db.Client) domain.ModelRepo {
+ return &ModelRepo{db: db}
+}
+
+func (r *ModelRepo) Create(ctx context.Context, m *domain.CreateModelReq) (*db.Model, error) {
+ uid, err := uuid.Parse(m.UserID)
+ if err != nil {
+ return nil, err
+ }
+ return r.db.Model.Create().
+ SetUserID(uid).
+ SetModelName(m.ModelName).
+ SetProvider(m.Provider).
+ SetAPIBase(m.APIBase).
+ SetAPIKey(m.APIKey).
+ SetModelType(m.ModelType).
+ SetStatus(consts.ModelStatusActive).
+ Save(ctx)
+}
+
+func (r *ModelRepo) Update(ctx context.Context, id string, fn func(up *db.ModelUpdateOne)) (*db.Model, error) {
+ modelID, err := uuid.Parse(id)
+ if err != nil {
+ return nil, err
+ }
+ var m *db.Model
+ err = entx.WithTx(ctx, r.db, func(tx *db.Tx) error {
+ old, err := tx.Model.Get(ctx, modelID)
+ if err != nil {
+ return err
+ }
+
+ up := tx.Model.UpdateOneID(old.ID)
+ fn(up)
+ if n, err := up.Save(ctx); err != nil {
+ return err
+ } else {
+ m = n
+ }
+ return nil
+ })
+ return m, err
+}
+
+func (r *ModelRepo) MyModelList(ctx context.Context, req *domain.MyModelListReq) ([]*db.Model, error) {
+ userID, err := uuid.Parse(req.UserID)
+ if err != nil {
+ return nil, err
+ }
+ q := r.db.Model.Query().Where(model.UserID(userID)).Where(model.ModelType(req.ModelType))
+ return q.All(ctx)
+}
+
+func (r *ModelRepo) ModelUsage(ctx context.Context, ids []uuid.UUID) (map[uuid.UUID]domain.ModelUsage, error) {
+ var usages []domain.ModelUsage
+ err := r.db.Record.Query().
+ Where(record.ModelIDIn(ids...)).
+ Modify(func(s *entsql.Selector) {
+ s.Select(
+ entsql.As(record.FieldModelID, "model_id"),
+ entsql.As(entsql.Sum(record.FieldInputTokens), "input"),
+ entsql.As(entsql.Sum(record.FieldOutputTokens), "output"),
+ ).
+ GroupBy("model_id").
+ OrderBy("model_id")
+ }).
+ Scan(ctx, &usages)
+ if err != nil {
+ return nil, err
+ }
+
+ return cvt.IterToMap(usages, func(_ int, u domain.ModelUsage) (uuid.UUID, domain.ModelUsage) {
+ return u.ModelID, u
+ }), nil
+}
+
+type TokenUsage struct {
+ Input int64 `json:"input"` // 输入token数
+ Output int64 `json:"output"` // 输出token数
+}
+
+type DailyUsage struct {
+ Date time.Time `json:"date"` // 时间戳
+ InputTokens int64 `json:"input_tokens"` // 输入token数
+ OutputTokens int64 `json:"output_tokens"` // 输出token数
+}
+
+func (r *ModelRepo) GetTokenUsage(ctx context.Context, modelType consts.ModelType) (*domain.ModelTokenUsageResp, error) {
+ var dailyUsages []DailyUsage
+ err := r.db.Record.Query().
+ Where(
+ record.ModelType(modelType),
+ record.CreatedAtGTE(time.Now().AddDate(0, 0, -90)),
+ ).
+ Modify(func(s *entsql.Selector) {
+ s.Select(
+ entsql.As("date_trunc('day', created_at)", "date"),
+ entsql.As(entsql.Sum(record.FieldInputTokens), "input_tokens"),
+ entsql.As(entsql.Sum(record.FieldOutputTokens), "output_tokens"),
+ ).
+ GroupBy("date").
+ OrderBy("date")
+ }).
+ Scan(ctx, &dailyUsages)
+
+ if err != nil {
+ return nil, err
+ }
+
+ resp := &domain.ModelTokenUsageResp{
+ InputUsage: []domain.ModelTokenUsage{},
+ OutputUsage: []domain.ModelTokenUsage{},
+ }
+
+ for _, usage := range dailyUsages {
+ resp.TotalInput += usage.InputTokens
+ resp.TotalOutput += usage.OutputTokens
+ resp.InputUsage = append(resp.InputUsage, domain.ModelTokenUsage{
+ Timestamp: usage.Date.Unix(),
+ Tokens: usage.InputTokens,
+ })
+ resp.OutputUsage = append(resp.OutputUsage, domain.ModelTokenUsage{
+ Timestamp: usage.Date.Unix(),
+ Tokens: usage.OutputTokens,
+ })
+ }
+
+ return resp, nil
+}
diff --git a/backend/internal/model/usecase/model.go b/backend/internal/model/usecase/model.go
new file mode 100644
index 0000000..3862f67
--- /dev/null
+++ b/backend/internal/model/usecase/model.go
@@ -0,0 +1,133 @@
+package usecase
+
+import (
+ "context"
+
+ "github.com/google/uuid"
+
+ "github.com/chaitin/MonkeyCode/backend/pkg/cvt"
+
+ "github.com/chaitin/MonkeyCode/backend/consts"
+ "github.com/chaitin/MonkeyCode/backend/db"
+ "github.com/chaitin/MonkeyCode/backend/domain"
+)
+
+type ModelUsecase struct {
+ repo domain.ModelRepo
+}
+
+func NewModelUsecase(repo domain.ModelRepo) domain.ModelUsecase {
+ return &ModelUsecase{repo: repo}
+}
+
+func (m *ModelUsecase) Check(ctx context.Context, req *domain.CheckModelReq) (*domain.Model, error) {
+ return nil, nil
+}
+
+func (m *ModelUsecase) MyModelList(ctx context.Context, req *domain.MyModelListReq) ([]*domain.Model, error) {
+ models, err := m.repo.MyModelList(ctx, req)
+ if err != nil {
+ return nil, err
+ }
+ ids := cvt.Iter(models, func(_ int, e *db.Model) uuid.UUID {
+ return e.ID
+ })
+ usages, err := m.repo.ModelUsage(ctx, ids)
+ if err != nil {
+ return nil, err
+ }
+ return cvt.Iter(models, func(_ int, e *db.Model) *domain.Model {
+ tmp := cvt.From(e, &domain.Model{}).From(e)
+ if usage, ok := usages[e.ID]; ok {
+ tmp.Input = usage.Input
+ tmp.Output = usage.Output
+ }
+ return tmp
+ }), nil
+}
+
+func (m *ModelUsecase) List(ctx context.Context) (*domain.AllModelResp, error) {
+ return &domain.AllModelResp{
+ Providers: []domain.ProviderModel{
+ {
+ Provider: "百智云",
+ Models: []domain.ModelBasic{
+ {
+ Provider: "百智云",
+ Name: "deepseek-v3",
+ APIBase: "https://model-square.app.baizhi.cloud/v1",
+ },
+ {
+ Provider: "百智云",
+ Name: "deepseek-r1",
+ APIBase: "https://model-square.app.baizhi.cloud/v1",
+ },
+ {
+ Provider: "百智云",
+ Name: "qwen2.5-coder-1.5b-instruct",
+ APIBase: "https://model-square.app.baizhi.cloud/v1",
+ },
+ {
+ Provider: "百智云",
+ Name: "qwen2.5-coder-7b-instruct",
+ APIBase: "https://model-square.app.baizhi.cloud/v1",
+ },
+ },
+ },
+ {
+ Provider: "DeepSeek",
+ Models: []domain.ModelBasic{
+ {
+ Provider: "DeepSeek",
+ Name: "deepseek-chat",
+ APIBase: "https://api.deepseek.com",
+ },
+ {
+ Provider: "DeepSeek",
+ Name: "deepseek-reasoner",
+ APIBase: "https://api.deepseek.com",
+ },
+ },
+ },
+ },
+ }, nil
+}
+
+// Create implements domain.ModelUsecase.
+func (m *ModelUsecase) Create(ctx context.Context, req *domain.CreateModelReq) (*domain.Model, error) {
+ model, err := m.repo.Create(ctx, req)
+ if err != nil {
+ return nil, err
+ }
+ return cvt.From(model, &domain.Model{}), nil
+}
+
+// GetTokenUsage implements domain.ModelUsecase.
+func (m *ModelUsecase) GetTokenUsage(ctx context.Context, modelType consts.ModelType) (*domain.ModelTokenUsageResp, error) {
+ return m.repo.GetTokenUsage(ctx, modelType)
+}
+
+// Update implements domain.ModelUsecase.
+func (m *ModelUsecase) Update(ctx context.Context, req *domain.UpdateModelReq) (*domain.Model, error) {
+ model, err := m.repo.Update(ctx, req.ID, func(up *db.ModelUpdateOne) {
+ if req.ModelName != nil {
+ up.SetModelName(*req.ModelName)
+ }
+ if req.Provider != nil {
+ up.SetProvider(*req.Provider)
+ }
+ if req.APIBase != nil {
+ up.SetAPIBase(*req.APIBase)
+ }
+ if req.APIKey != nil {
+ up.SetAPIKey(*req.APIKey)
+ }
+ if req.Status != nil {
+ up.SetStatus(*req.Status)
+ }
+ })
+ if err != nil {
+ return nil, err
+ }
+ return cvt.From(model, &domain.Model{}), nil
+}
diff --git a/backend/internal/openai/handler/v1/v1.go b/backend/internal/openai/handler/v1/v1.go
new file mode 100644
index 0000000..15f1bf8
--- /dev/null
+++ b/backend/internal/openai/handler/v1/v1.go
@@ -0,0 +1,165 @@
+package v1
+
+import (
+ "log/slog"
+ "net/http"
+
+ "github.com/labstack/echo/v4"
+ "github.com/rokku-c/go-openai"
+
+ "github.com/GoYoko/web"
+
+ "github.com/chaitin/MonkeyCode/backend/domain"
+ "github.com/chaitin/MonkeyCode/backend/internal/middleware"
+)
+
+type V1Handler struct {
+ logger *slog.Logger
+ proxy domain.Proxy
+ usecase domain.OpenAIUsecase
+}
+
+func NewV1Handler(
+ logger *slog.Logger,
+ w *web.Web,
+ proxy domain.Proxy,
+ usecase domain.OpenAIUsecase,
+ middleware *middleware.ProxyMiddleware,
+) *V1Handler {
+ h := &V1Handler{
+ logger: logger.With(slog.String("handler", "openai")),
+ proxy: proxy,
+ usecase: usecase,
+ }
+ w.GET("/api/config", web.BindHandler(h.GetConfig), middleware.Auth())
+
+ g := w.Group("/v1", middleware.Auth())
+ g.GET("/models", web.BaseHandler(h.ModelList))
+ g.POST("/completion/accept", web.BindHandler(h.AcceptCompletion))
+ g.POST("/chat/completions", web.BindHandler(h.ChatCompletion))
+ g.POST("/completions", web.BindHandler(h.Completions))
+ g.POST("/embeddings", web.BindHandler(h.Embeddings))
+ return h
+}
+
+func BadRequest(c *web.Context, msg string) error {
+ c.JSON(http.StatusBadRequest, echo.Map{
+ "error": echo.Map{
+ "message": msg,
+ "type": "invalid_request_error",
+ },
+ })
+ return nil
+}
+
+// AcceptCompletion 接受补全请求
+//
+// @Tags OpenAIV1
+// @Summary 接受补全请求
+// @Description 接受补全请求
+// @ID accept-completion
+// @Accept json
+// @Produce json
+// @Param param body domain.AcceptCompletionReq true "补全请求"
+// @Success 200 {object} web.Resp{}
+// @Router /v1/completion/accept [post]
+func (h *V1Handler) AcceptCompletion(c *web.Context, req domain.AcceptCompletionReq) error {
+ if err := h.proxy.AcceptCompletion(c.Request().Context(), &req); err != nil {
+ return BadRequest(c, err.Error())
+ }
+ return nil
+}
+
+// ModelList 模型列表
+//
+// @Tags OpenAIV1
+// @Summary 模型列表
+// @Description 模型列表
+// @ID model-list
+// @Accept json
+// @Produce json
+// @Success 200 {object} web.Resp{data=domain.ModelListResp}
+// @Router /v1/models [get]
+func (h *V1Handler) ModelList(c *web.Context) error {
+ resp, err := h.usecase.ModelList(c.Request().Context())
+ if err != nil {
+ return err
+ }
+ return c.Success(resp)
+}
+
+// ChatCompletion 处理聊天补全请求
+//
+// @Tags OpenAIV1
+// @Summary 处理聊天补全请求
+// @Description 处理聊天补全请求
+// @ID chat-completion
+// @Accept json
+// @Produce json
+// @Success 200 {object} web.Resp{}
+// @Router /v1/chat/completions [post]
+func (h *V1Handler) ChatCompletion(c *web.Context, req openai.ChatCompletionRequest) error {
+ // TODO: 记录请求到文件
+ if req.Model == "" {
+ return BadRequest(c, "模型不能为空")
+ }
+ h.logger.With("request", req).DebugContext(c.Request().Context(), "处理聊天补全请求")
+
+ // if len(req.Tools) > 0 && req.Model != "qwen-max" {
+ // if h.toolsCall(c, req, req.Stream, req.Model) {
+ // return nil
+ // }
+ // }
+
+ h.proxy.HandleChatCompletion(c.Request().Context(), c.Response(), &req)
+ return nil
+}
+
+// Completions 处理文本补全请求
+//
+// @Tags OpenAIV1
+// @Summary 处理文本补全请求
+// @Description 处理文本补全请求
+// @ID completions
+// @Accept json
+// @Produce json
+// @Success 200 {object} web.Resp{}
+// @Router /v1/completions [post]
+func (h *V1Handler) Completions(c *web.Context, req domain.CompletionRequest) error {
+ // TODO: 记录请求到文件
+ if req.Model == "" {
+ return BadRequest(c, "模型不能为空")
+ }
+ h.logger.With("request", req).DebugContext(c.Request().Context(), "处理文本补全请求")
+ h.proxy.HandleCompletion(c.Request().Context(), c.Response(), req)
+ return nil
+}
+
+// Embeddings 处理嵌入请求
+//
+// @Tags OpenAIV1
+// @Summary 处理嵌入请求
+// @Description 处理嵌入请求
+// @ID embeddings
+// @Accept json
+// @Produce json
+// @Success 200 {object} web.Resp{}
+// @Router /v1/embeddings [post]
+func (h *V1Handler) Embeddings(c *web.Context, req openai.EmbeddingRequest) error {
+ if req.Model == "" {
+ return BadRequest(c, "模型不能为空")
+ }
+
+ h.proxy.HandleEmbeddings(c.Request().Context(), c.Response(), &req)
+ return nil
+}
+
+func (h *V1Handler) GetConfig(c *web.Context, req domain.ConfigReq) error {
+ key := middleware.GetApiKey(c)
+ req.Key = key.Key
+ resp, err := h.usecase.GetConfig(c.Request().Context(), &req)
+ if err != nil {
+ return err
+ }
+ return c.JSON(http.StatusOK, resp)
+}
diff --git a/backend/internal/openai/repo/openai.go b/backend/internal/openai/repo/openai.go
new file mode 100644
index 0000000..5d5bce3
--- /dev/null
+++ b/backend/internal/openai/repo/openai.go
@@ -0,0 +1,34 @@
+package repo
+
+import (
+ "context"
+
+ "entgo.io/ent/dialect/sql"
+ "github.com/chaitin/MonkeyCode/backend/consts"
+ "github.com/chaitin/MonkeyCode/backend/db"
+ "github.com/chaitin/MonkeyCode/backend/db/apikey"
+ "github.com/chaitin/MonkeyCode/backend/db/model"
+ "github.com/chaitin/MonkeyCode/backend/domain"
+)
+
+type OpenAIRepo struct {
+ db *db.Client
+}
+
+func NewOpenAIRepo(db *db.Client) domain.OpenAIRepo {
+ return OpenAIRepo{db: db}
+}
+
+// GetApiKey implements domain.OpenAIRepo.
+func (o OpenAIRepo) GetApiKey(ctx context.Context, key string) (*db.ApiKey, error) {
+ return o.db.ApiKey.Query().Where(apikey.Key(key)).Only(ctx)
+}
+
+// ModelList implements domain.OpenAIRepo.
+func (o OpenAIRepo) ModelList(ctx context.Context) ([]*db.Model, error) {
+ return o.db.Model.Query().
+ WithUser().
+ Where(model.Status(consts.ModelStatusActive)).
+ Order(model.ByCreatedAt(sql.OrderDesc())).
+ All(ctx)
+}
diff --git a/backend/internal/openai/usecase/openai.go b/backend/internal/openai/usecase/openai.go
new file mode 100644
index 0000000..f615863
--- /dev/null
+++ b/backend/internal/openai/usecase/openai.go
@@ -0,0 +1,92 @@
+package openai
+
+import (
+ "bytes"
+ "context"
+ "log/slog"
+ "text/template"
+
+ "github.com/chaitin/MonkeyCode/backend/pkg/cvt"
+
+ "github.com/chaitin/MonkeyCode/backend/config"
+ "github.com/chaitin/MonkeyCode/backend/consts"
+ "github.com/chaitin/MonkeyCode/backend/db"
+ "github.com/chaitin/MonkeyCode/backend/domain"
+)
+
+type OpenAIUsecase struct {
+ repo domain.OpenAIRepo
+ cfg *config.Config
+ logger *slog.Logger
+}
+
+func NewOpenAIUsecase(cfg *config.Config, repo domain.OpenAIRepo, logger *slog.Logger) domain.OpenAIUsecase {
+ return &OpenAIUsecase{
+ repo: repo,
+ cfg: cfg,
+ logger: logger,
+ }
+}
+
+func (u *OpenAIUsecase) ModelList(ctx context.Context) (*domain.ModelListResp, error) {
+ models, err := u.repo.ModelList(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ for _, v := range models {
+ u.logger.DebugContext(ctx, "model", slog.Any("model", v))
+ }
+
+ resp := &domain.ModelListResp{
+ Object: "list",
+ Data: cvt.Iter(models, func(_ int, m *db.Model) *domain.ModelData {
+ return cvt.From(m, &domain.ModelData{})
+ }),
+ }
+
+ return resp, nil
+}
+
+func (u *OpenAIUsecase) GetConfig(ctx context.Context, req *domain.ConfigReq) (*domain.ConfigResp, error) {
+ apiKey, err := u.repo.GetApiKey(ctx, req.Key)
+ if err != nil {
+ return nil, err
+ }
+
+ model, err := u.repo.ModelList(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ chatModel := ""
+ codeModel := ""
+ for _, m := range model {
+ switch m.ModelType {
+ case consts.ModelTypeLLM:
+ chatModel = m.ModelName
+ case consts.ModelTypeCoder:
+ codeModel = m.ModelName
+ }
+ }
+
+ t, err := template.New("config").Parse(string(config.ConfigTmpl))
+ if err != nil {
+ return nil, err
+ }
+
+ cnt := bytes.NewBuffer(nil)
+ if err := t.Execute(cnt, map[string]string{
+ "apiBase": u.cfg.BaseUrl,
+ "apikey": apiKey.Key,
+ "chatModel": chatModel,
+ "codeModel": codeModel,
+ }); err != nil {
+ return nil, err
+ }
+
+ return &domain.ConfigResp{
+ Type: req.Type,
+ Content: cnt.String(),
+ }, nil
+}
diff --git a/backend/internal/provider.go b/backend/internal/provider.go
new file mode 100644
index 0000000..548e1b3
--- /dev/null
+++ b/backend/internal/provider.go
@@ -0,0 +1,48 @@
+package internal
+
+import (
+ "github.com/google/wire"
+
+ billingv1 "github.com/chaitin/MonkeyCode/backend/internal/billing/handler/http/v1"
+ billingrepo "github.com/chaitin/MonkeyCode/backend/internal/billing/repo"
+ billingusecase "github.com/chaitin/MonkeyCode/backend/internal/billing/usecase"
+ dashv1 "github.com/chaitin/MonkeyCode/backend/internal/dashboard/handler/v1"
+ dashrepo "github.com/chaitin/MonkeyCode/backend/internal/dashboard/repo"
+ dashusecase "github.com/chaitin/MonkeyCode/backend/internal/dashboard/usecase"
+ "github.com/chaitin/MonkeyCode/backend/internal/middleware"
+ modelv1 "github.com/chaitin/MonkeyCode/backend/internal/model/handler/http/v1"
+ modelrepo "github.com/chaitin/MonkeyCode/backend/internal/model/repo"
+ modelusecase "github.com/chaitin/MonkeyCode/backend/internal/model/usecase"
+ v1 "github.com/chaitin/MonkeyCode/backend/internal/openai/handler/v1"
+ openairepo "github.com/chaitin/MonkeyCode/backend/internal/openai/repo"
+ openai "github.com/chaitin/MonkeyCode/backend/internal/openai/usecase"
+ "github.com/chaitin/MonkeyCode/backend/internal/proxy"
+ proxyrepo "github.com/chaitin/MonkeyCode/backend/internal/proxy/repo"
+ proxyusecase "github.com/chaitin/MonkeyCode/backend/internal/proxy/usecase"
+ userV1 "github.com/chaitin/MonkeyCode/backend/internal/user/handler/v1"
+ userrepo "github.com/chaitin/MonkeyCode/backend/internal/user/repo"
+ userusecase "github.com/chaitin/MonkeyCode/backend/internal/user/usecase"
+)
+
+var Provider = wire.NewSet(
+ proxy.NewLLMProxy,
+ v1.NewV1Handler,
+ openai.NewOpenAIUsecase,
+ openairepo.NewOpenAIRepo,
+ modelv1.NewModelHandler,
+ proxyusecase.NewProxyUsecase,
+ proxyrepo.NewProxyRepo,
+ modelusecase.NewModelUsecase,
+ modelrepo.NewModelRepo,
+ dashv1.NewDashboardHandler,
+ dashusecase.NewDashboardUsecase,
+ dashrepo.NewDashboardRepo,
+ middleware.NewProxyMiddleware,
+ middleware.NewAuthMiddleware,
+ userV1.NewUserHandler,
+ userrepo.NewUserRepo,
+ userusecase.NewUserUsecase,
+ billingv1.NewBillingHandler,
+ billingrepo.NewBillingRepo,
+ billingusecase.NewBillingUsecase,
+)
diff --git a/backend/internal/proxy/proxy.go b/backend/internal/proxy/proxy.go
new file mode 100644
index 0000000..57ace15
--- /dev/null
+++ b/backend/internal/proxy/proxy.go
@@ -0,0 +1,827 @@
+package proxy
+
+import (
+ "bufio"
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/url"
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "github.com/rokku-c/go-openai"
+
+ "github.com/chaitin/MonkeyCode/backend/config"
+ "github.com/chaitin/MonkeyCode/backend/consts"
+ "github.com/chaitin/MonkeyCode/backend/domain"
+ "github.com/chaitin/MonkeyCode/backend/pkg/logger"
+ "github.com/chaitin/MonkeyCode/backend/pkg/request"
+)
+
+// ErrResp 错误响应
+type ErrResp struct {
+ Error struct {
+ Message string `json:"message"`
+ Type string `json:"type"`
+ Code string `json:"code,omitempty"`
+ } `json:"error"`
+}
+
+// RequestResponseLog 请求响应日志结构
+type RequestResponseLog struct {
+ Timestamp time.Time `json:"timestamp"`
+ RequestID string `json:"request_id"`
+ Endpoint string `json:"endpoint"`
+ ModelName string `json:"model_name"`
+ ModelType consts.ModelType `json:"model_type"`
+ UpstreamURL string `json:"upstream_url"`
+ RequestBody any `json:"request_body"`
+ RequestHeader map[string][]string `json:"request_header"`
+ StatusCode int `json:"status_code"`
+ ResponseBody any `json:"response_body"`
+ ResponseHeader map[string][]string `json:"response_header"`
+ Latency int64 `json:"latency_ms"`
+ Error string `json:"error,omitempty"`
+ IsStream bool `json:"is_stream"`
+ SourceIP string `json:"source_ip"` // 请求来源IP地址
+}
+
+// LLMProxy LLM API代理实现
+type LLMProxy struct {
+ usecase domain.ProxyUsecase
+ cfg *config.Config
+ client *http.Client
+ logger *slog.Logger
+ requestLogPath string // 请求日志保存路径
+}
+
+// NewLLMProxy 创建LLM API代理实例
+func NewLLMProxy(
+ usecase domain.ProxyUsecase,
+ cfg *config.Config,
+ logger *slog.Logger,
+) domain.Proxy {
+ // 解析超时时间
+ timeout, err := time.ParseDuration(cfg.LLMProxy.Timeout)
+ if err != nil {
+ timeout = 30 * time.Second
+ logger.Warn("解析超时时间失败, 使用默认值 30s", "error", err)
+ }
+
+ // 解析保持连接时间
+ keepAlive, err := time.ParseDuration(cfg.LLMProxy.KeepAlive)
+ if err != nil {
+ keepAlive = 60 * time.Second
+ logger.Warn("解析保持连接时间失败, 使用默认值 60s", "error", err)
+ }
+
+ // 创建HTTP客户端
+ client := &http.Client{
+ Timeout: timeout,
+ Transport: &http.Transport{
+ MaxIdleConns: cfg.LLMProxy.ClientPoolSize,
+ MaxConnsPerHost: cfg.LLMProxy.ClientPoolSize,
+ MaxIdleConnsPerHost: cfg.LLMProxy.ClientPoolSize,
+ IdleConnTimeout: keepAlive,
+ TLSHandshakeTimeout: 10 * time.Second,
+ ExpectContinueTimeout: 1 * time.Second,
+ DisableCompression: false,
+ ForceAttemptHTTP2: true,
+ },
+ }
+
+ // 获取日志配置
+ requestLogPath := ""
+ if cfg.LLMProxy.RequestLogPath != "" {
+ requestLogPath = cfg.LLMProxy.RequestLogPath
+ // 确保目录存在
+ if err := os.MkdirAll(requestLogPath, 0755); err != nil {
+ logger.Warn("创建请求日志目录失败", "error", err, "path", requestLogPath)
+ }
+ }
+
+ return &LLMProxy{
+ usecase: usecase,
+ client: client,
+ cfg: cfg,
+ requestLogPath: requestLogPath,
+ logger: logger,
+ }
+}
+
+// saveRequestResponseLog 保存请求响应日志到文件
+func (p *LLMProxy) saveRequestResponseLog(log *RequestResponseLog) {
+ if p.requestLogPath == "" {
+ return
+ }
+
+ // 创建文件名,格式:YYYYMMDD_HHMMSS_请求ID.json
+ timestamp := log.Timestamp.Format("20060102_150405") + fmt.Sprintf("_%03d", log.Timestamp.Nanosecond()/1e6)
+ filename := fmt.Sprintf("%s_%s.json", timestamp, log.RequestID)
+ filepath := filepath.Join(p.requestLogPath, filename)
+
+ // 将日志序列化为JSON
+ logData, err := json.MarshalIndent(log, "", " ")
+ if err != nil {
+ p.logger.Error("序列化请求日志失败", "error", err)
+ return
+ }
+
+ // 写入文件
+ if err := os.WriteFile(filepath, logData, 0644); err != nil {
+ p.logger.Error("写入请求日志文件失败", "error", err, "path", filepath)
+ return
+ }
+
+ p.logger.Debug("请求响应日志已保存", "path", filepath)
+}
+
+func (p *LLMProxy) AcceptCompletion(ctx context.Context, req *domain.AcceptCompletionReq) error {
+ return p.usecase.AcceptCompletion(ctx, req)
+}
+
+func writeErrResp(w http.ResponseWriter, code int, message, errorType string) {
+ resp := ErrResp{
+ Error: struct {
+ Message string `json:"message"`
+ Type string `json:"type"`
+ Code string `json:"code,omitempty"`
+ }{
+ Message: message,
+ Type: errorType,
+ },
+ }
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(code)
+ b, _ := json.Marshal(resp)
+ w.Write(b)
+}
+
+type Ctx struct {
+ UserID string
+ RequestID string
+ SourceIP string
+}
+
+func (p *LLMProxy) handle(ctx context.Context, fn func(ctx *Ctx, log *RequestResponseLog) error) {
+ // 获取用户ID
+ userID := "unknown"
+ if id, ok := ctx.Value(logger.UserIDKey).(string); ok {
+ userID = id
+ }
+
+ requestID := "unknown"
+ if id, ok := ctx.Value(logger.RequestIDKey).(string); ok {
+ requestID = id
+ }
+
+ sourceip := "unknown"
+ if ip, ok := ctx.Value("remote_addr").(string); ok {
+ sourceip = ip
+ }
+
+ // 创建请求日志结构
+ l := &RequestResponseLog{
+ Timestamp: time.Now(),
+ RequestID: requestID,
+ ModelType: consts.ModelTypeCoder,
+ SourceIP: sourceip,
+ }
+
+ c := &Ctx{
+ UserID: userID,
+ RequestID: requestID,
+ SourceIP: sourceip,
+ }
+
+ if err := fn(c, l); err != nil {
+ p.logger.With("userID", userID, "requestID", requestID, "sourceip", sourceip).ErrorContext(ctx, "处理请求失败", "error", err)
+ l.Error = err.Error()
+ }
+
+ p.saveRequestResponseLog(l)
+}
+
+func (p *LLMProxy) HandleCompletion(ctx context.Context, w http.ResponseWriter, req domain.CompletionRequest) {
+ if req.Stream {
+ p.handleCompletionStream(ctx, w, req)
+ } else {
+ p.handleCompletion(ctx, w, req)
+ }
+}
+
+func (p *LLMProxy) handleCompletionStream(ctx context.Context, w http.ResponseWriter, req domain.CompletionRequest) {
+ endpoint := "/completions"
+ p.handle(ctx, func(c *Ctx, log *RequestResponseLog) error {
+ // 使用负载均衡算法选择模型
+ m, err := p.usecase.SelectModelWithLoadBalancing(req.Model, consts.ModelTypeCoder)
+ if err != nil {
+ p.logger.With("modelName", req.Model, "modelType", consts.ModelTypeCoder).WarnContext(ctx, "模型选择失败", "error", err)
+ writeErrResp(w, http.StatusNotFound, "模型未找到", "proxy_error")
+ return err
+ }
+
+ // 构造上游API URL
+ upstream := m.APIBase + endpoint
+ log.UpstreamURL = upstream
+ startTime := time.Now()
+
+ // 创建上游请求
+ body, err := json.Marshal(req)
+ if err != nil {
+ p.logger.ErrorContext(ctx, "序列化请求体失败", "error", err)
+ return fmt.Errorf("序列化请求体失败: %w", err)
+ }
+
+ upreq, err := http.NewRequestWithContext(ctx, http.MethodPost, upstream, bytes.NewReader(body))
+ if err != nil {
+ p.logger.With("upstream", upstream).WarnContext(ctx, "创建上游流式请求失败", "error", err)
+ return fmt.Errorf("创建上游请求失败: %w", err)
+ }
+
+ // 设置请求头
+ upreq.Header.Set("Content-Type", "application/json")
+ upreq.Header.Set("Accept", "text/event-stream")
+ if m.APIKey != "" && m.APIKey != "none" {
+ upreq.Header.Set("Authorization", "Bearer "+m.APIKey)
+ }
+
+ // 保存请求头(去除敏感信息)
+ requestHeaders := make(map[string][]string)
+ for k, v := range upreq.Header {
+ if k != "Authorization" {
+ requestHeaders[k] = v
+ } else {
+ // 敏感信息脱敏
+ requestHeaders[k] = []string{"Bearer ***"}
+ }
+ }
+ log.RequestHeader = requestHeaders
+
+ p.logger.With(
+ "upstreamURL", upstream,
+ "modelName", m.ModelName,
+ "modelType", consts.ModelTypeLLM,
+ "apiBase", m.APIBase,
+ "requestHeader", upreq.Header,
+ "requestBody", upreq,
+ ).DebugContext(ctx, "转发流式请求到上游API")
+
+ // 发送请求
+ resp, err := p.client.Do(upreq)
+ if err != nil {
+ p.logger.With("upstreamURL", upstream).WarnContext(ctx, "发送上游流式请求失败", "error", err)
+ return fmt.Errorf("发送上游请求失败: %w", err)
+ }
+ defer resp.Body.Close()
+
+ // 检查响应状态
+ if resp.StatusCode != http.StatusOK {
+ responseBody, _ := io.ReadAll(resp.Body)
+
+ // 更新日志错误信息
+ log.StatusCode = resp.StatusCode
+ log.ResponseHeader = resp.Header
+ log.ResponseBody = string(responseBody)
+ log.Latency = time.Since(startTime).Milliseconds()
+
+ // 在debug级别记录错误的流式响应内容
+ p.logger.With(
+ "statusCode", resp.StatusCode,
+ "responseHeader", resp.Header,
+ "responseBody", string(responseBody),
+ ).DebugContext(ctx, "上游流式响应错误原始内容")
+
+ var errorResp ErrResp
+ if err := json.Unmarshal(responseBody, &errorResp); err == nil {
+ p.logger.With(
+ "endpoint", endpoint,
+ "upstreamURL", upstream,
+ "requestBody", upreq,
+ "statusCode", resp.StatusCode,
+ "errorType", errorResp.Error.Type,
+ "errorCode", errorResp.Error.Code,
+ "errorMessage", errorResp.Error.Message,
+ "latency", time.Since(startTime),
+ ).WarnContext(ctx, "上游API流式请求异常详情")
+
+ return fmt.Errorf("上游API返回错误: %s", errorResp.Error.Message)
+ }
+
+ p.logger.With(
+ "endpoint", endpoint,
+ "upstreamURL", upstream,
+ "requestBody", upreq,
+ "statusCode", resp.StatusCode,
+ "responseBody", string(responseBody),
+ ).WarnContext(ctx, "上游API流式请求异常详情")
+
+ return fmt.Errorf("上游API返回非200状态码: %d, 响应: %s", resp.StatusCode, string(responseBody))
+ }
+
+ // 更新日志信息
+ log.StatusCode = resp.StatusCode
+ log.ResponseHeader = resp.Header
+
+ // 在debug级别记录流式响应头信息
+ p.logger.With(
+ "statusCode", resp.StatusCode,
+ "responseHeader", resp.Header,
+ ).DebugContext(ctx, "上游流式响应头信息")
+
+ // 设置响应头
+ w.Header().Set("Content-Type", "text/event-stream")
+ w.Header().Set("Cache-Control", "no-cache")
+ w.Header().Set("Connection", "keep-alive")
+ w.Header().Set("Transfer-Encoding", "chunked")
+
+ rc := &domain.RecordParam{
+ UserID: c.UserID,
+ ModelID: m.ID,
+ ModelType: consts.ModelTypeLLM,
+ Prompt: req.Prompt.(string),
+ }
+ buf := bufio.NewWriterSize(w, 32*1024)
+ defer buf.Flush()
+
+ ch := make(chan []byte, 1024)
+ defer close(ch)
+
+ go func(rc *domain.RecordParam) {
+ for line := range ch {
+ if bytes.HasPrefix(line, []byte("data:")) {
+ line = bytes.TrimPrefix(line, []byte("data: "))
+ line = bytes.TrimSpace(line)
+ if len(line) == 0 {
+ continue
+ }
+
+ if bytes.Equal(line, []byte("[DONE]")) {
+ break
+ }
+
+ var t openai.CompletionResponse
+ if err := json.Unmarshal(line, &t); err != nil {
+ p.logger.With("line", string(line)).WarnContext(ctx, "解析流式数据失败", "error", err)
+ continue
+ }
+
+ p.logger.With("response", t).DebugContext(ctx, "流式响应数据")
+ if len(t.Choices) > 0 {
+ rc.Completion += t.Choices[0].Text
+ }
+ rc.InputTokens += int64(t.Usage.PromptTokens)
+ rc.OutputTokens += int64(t.Usage.CompletionTokens)
+ }
+ }
+
+ p.logger.With("record", rc).DebugContext(ctx, "流式记录")
+ if err := p.usecase.Record(context.Background(), rc); err != nil {
+ p.logger.With("modelID", m.ID, "modelName", m.ModelName, "modelType", consts.ModelTypeLLM).
+ WarnContext(ctx, "插入流式记录失败", "error", err)
+ }
+ }(rc)
+
+ err = streamRead(ctx, resp.Body, func(line []byte) error {
+ ch <- line
+ if _, err := buf.Write(line); err != nil {
+ return fmt.Errorf("写入响应失败: %w", err)
+ }
+ return buf.Flush()
+ })
+ return err
+ })
+}
+
+func (p *LLMProxy) handleCompletion(ctx context.Context, w http.ResponseWriter, req domain.CompletionRequest) {
+ endpoint := "/completions"
+ p.handle(ctx, func(c *Ctx, log *RequestResponseLog) error {
+ // 使用负载均衡算法选择模型
+ m, err := p.usecase.SelectModelWithLoadBalancing(req.Model, consts.ModelTypeCoder)
+ if err != nil {
+ p.logger.With("modelName", req.Model, "modelType", consts.ModelTypeCoder).WarnContext(ctx, "模型选择失败", "error", err)
+ writeErrResp(w, http.StatusNotFound, "模型未找到", "proxy_error")
+ return err
+ }
+
+ // 构造上游API URL
+ upstream := m.APIBase + endpoint
+ log.UpstreamURL = upstream
+ u, err := url.Parse(upstream)
+ if err != nil {
+ p.logger.With("upstreamURL", upstream).WarnContext(ctx, "解析上游URL失败", "error", err)
+ writeErrResp(w, http.StatusInternalServerError, "无效的上游URL", "proxy_error")
+ return err
+ }
+
+ startTime := time.Now()
+
+ client := request.NewClient(u.Scheme, u.Host, 30*time.Second)
+ client.SetDebug(p.cfg.Debug)
+ resp, err := request.Post[openai.CompletionResponse](client, u.Path, req, request.WithHeader(request.Header{
+ "Authorization": "Bearer " + m.APIKey,
+ }))
+ if err != nil {
+ p.logger.With("upstreamURL", upstream).WarnContext(ctx, "发送上游请求失败", "error", err)
+ writeErrResp(w, http.StatusInternalServerError, "发送上游请求失败", "proxy_error")
+ log.Latency = time.Since(startTime).Milliseconds()
+ return err
+ }
+
+ latency := time.Since(startTime)
+
+ // 记录请求信息
+ p.logger.With(
+ "statusCode", http.StatusOK,
+ "upstreamURL", upstream,
+ "modelName", req.Model,
+ "modelType", consts.ModelTypeCoder,
+ "apiBase", m.APIBase,
+ "requestBody", req,
+ "resp", resp,
+ "latency", latency.String(),
+ ).DebugContext(ctx, "转发请求到上游API")
+
+ go p.recordCompletion(c, m.ID, req, resp)
+
+ // 更新请求日志
+ log.StatusCode = http.StatusOK
+ log.ResponseBody = resp
+ log.ResponseHeader = resp.Header()
+ log.Latency = latency.Milliseconds()
+
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ b, err := json.Marshal(resp)
+ if err != nil {
+ p.logger.With("response", resp).WarnContext(ctx, "序列化响应失败", "error", err)
+ return err
+ }
+ w.Write(b)
+ return nil
+ })
+}
+
+func (p *LLMProxy) recordCompletion(c *Ctx, modelID string, req domain.CompletionRequest, resp *openai.CompletionResponse) {
+ ctx := context.Background()
+ prompt := req.Prompt.(string)
+ rc := &domain.RecordParam{
+ TaskID: resp.ID,
+ UserID: c.UserID,
+ ModelID: modelID,
+ ModelType: consts.ModelTypeCoder,
+ Prompt: prompt,
+ ProgramLanguage: req.Metadata["program_language"],
+ InputTokens: int64(resp.Usage.PromptTokens),
+ OutputTokens: int64(resp.Usage.CompletionTokens),
+ }
+
+ for _, choice := range resp.Choices {
+ rc.Completion += choice.Text
+ }
+ lines := strings.Count(rc.Completion, "\n") + 1
+ rc.CodeLines = int64(lines)
+
+ if err := p.usecase.Record(ctx, rc); err != nil {
+ p.logger.With("modelID", modelID, "modelName", req.Model, "modelType", consts.ModelTypeCoder).WarnContext(ctx, "记录请求失败", "error", err)
+ }
+}
+
+func (p *LLMProxy) HandleChatCompletion(ctx context.Context, w http.ResponseWriter, req *openai.ChatCompletionRequest) {
+ if req.Stream {
+ p.handleChatCompletionStream(ctx, w, req)
+ } else {
+ p.handleChatCompletion(ctx, w, req)
+ }
+}
+
+func streamRead(ctx context.Context, r io.Reader, fn func([]byte) error) error {
+ reader := bufio.NewReaderSize(r, 32*1024)
+ for {
+ select {
+ case <-ctx.Done():
+ return fmt.Errorf("流式请求被取消: %w", ctx.Err())
+ default:
+ line, err := reader.ReadBytes('\n')
+ if err == io.EOF {
+ return nil
+ }
+ if err != nil {
+ return fmt.Errorf("读取流式数据失败: %w", err)
+ }
+
+ line = bytes.TrimSpace(line)
+ if len(line) == 0 {
+ continue
+ }
+
+ line = append(line, '\n')
+ line = append(line, '\n')
+
+ fn(line)
+ }
+ }
+}
+
+func (p *LLMProxy) handleChatCompletionStream(ctx context.Context, w http.ResponseWriter, req *openai.ChatCompletionRequest) {
+ endpoint := "/chat/completions"
+ p.handle(ctx, func(c *Ctx, log *RequestResponseLog) error {
+ // 记录开始时间用于性能监控
+ startTime := time.Now()
+
+ // 使用负载均衡算法选择模型
+ m, err := p.usecase.SelectModelWithLoadBalancing(req.Model, consts.ModelTypeLLM)
+ if err != nil {
+ p.logger.With("modelName", req.Model, "modelType", consts.ModelTypeLLM).WarnContext(ctx, "流式请求模型选择失败", "error", err)
+ writeErrResp(w, http.StatusNotFound, "模型未找到", "proxy_error")
+ return err
+ }
+
+ prompt := req.Metadata["message"]
+ workMode := req.Metadata["work_mode"]
+ taskID := req.Metadata["task_id"]
+
+ // 构造上游API URL
+ upstream := m.APIBase + endpoint
+ log.UpstreamURL = upstream
+
+ // 创建上游请求
+ body, err := json.Marshal(req)
+ if err != nil {
+ p.logger.ErrorContext(ctx, "序列化请求体失败", "error", err)
+ return fmt.Errorf("序列化请求体失败: %w", err)
+ }
+
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, upstream, bytes.NewReader(body))
+ if err != nil {
+ p.logger.With("upstream", upstream).WarnContext(ctx, "创建上游流式请求失败", "error", err)
+ return fmt.Errorf("创建上游请求失败: %w", err)
+ }
+
+ // 设置请求头
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Accept", "text/event-stream")
+ if m.APIKey != "" && m.APIKey != "none" {
+ req.Header.Set("Authorization", "Bearer "+m.APIKey)
+ }
+
+ // 保存请求头(去除敏感信息)
+ requestHeaders := make(map[string][]string)
+ for k, v := range req.Header {
+ if k != "Authorization" {
+ requestHeaders[k] = v
+ } else {
+ // 敏感信息脱敏
+ requestHeaders[k] = []string{"Bearer ***"}
+ }
+ }
+ log.RequestHeader = requestHeaders
+
+ p.logger.With(
+ "upstreamURL", upstream,
+ "modelName", m.ModelName,
+ "modelType", consts.ModelTypeLLM,
+ "apiBase", m.APIBase,
+ "work_mode", workMode,
+ "requestHeader", req.Header,
+ "requestBody", req,
+ "taskID", taskID,
+ ).DebugContext(ctx, "转发流式请求到上游API")
+
+ // 发送请求
+ resp, err := p.client.Do(req)
+ if err != nil {
+ p.logger.With("upstreamURL", upstream).WarnContext(ctx, "发送上游流式请求失败", "error", err)
+ return fmt.Errorf("发送上游请求失败: %w", err)
+ }
+ defer resp.Body.Close()
+
+ // 检查响应状态
+ if resp.StatusCode != http.StatusOK {
+ responseBody, _ := io.ReadAll(resp.Body)
+
+ // 更新日志错误信息
+ log.StatusCode = resp.StatusCode
+ log.ResponseHeader = resp.Header
+ log.ResponseBody = string(responseBody)
+ log.Latency = time.Since(startTime).Milliseconds()
+
+ // 在debug级别记录错误的流式响应内容
+ p.logger.With(
+ "statusCode", resp.StatusCode,
+ "responseHeader", resp.Header,
+ "responseBody", string(responseBody),
+ ).DebugContext(ctx, "上游流式响应错误原始内容")
+
+ var errorResp ErrResp
+ if err := json.Unmarshal(responseBody, &errorResp); err == nil {
+ p.logger.With(
+ "endpoint", endpoint,
+ "upstreamURL", upstream,
+ "requestBody", req,
+ "statusCode", resp.StatusCode,
+ "errorType", errorResp.Error.Type,
+ "errorCode", errorResp.Error.Code,
+ "errorMessage", errorResp.Error.Message,
+ "latency", time.Since(startTime),
+ ).WarnContext(ctx, "上游API流式请求异常详情")
+
+ return fmt.Errorf("上游API返回错误: %s", errorResp.Error.Message)
+ }
+
+ p.logger.With(
+ "endpoint", endpoint,
+ "upstreamURL", upstream,
+ "requestBody", req,
+ "statusCode", resp.StatusCode,
+ "responseBody", string(responseBody),
+ ).WarnContext(ctx, "上游API流式请求异常详情")
+
+ return fmt.Errorf("上游API返回非200状态码: %d, 响应: %s", resp.StatusCode, string(responseBody))
+ }
+
+ // 更新日志信息
+ log.StatusCode = resp.StatusCode
+ log.ResponseHeader = resp.Header
+
+ // 在debug级别记录流式响应头信息
+ p.logger.With(
+ "statusCode", resp.StatusCode,
+ "responseHeader", resp.Header,
+ ).DebugContext(ctx, "上游流式响应头信息")
+
+ // 设置响应头
+ w.Header().Set("Content-Type", "text/event-stream")
+ w.Header().Set("Cache-Control", "no-cache")
+ w.Header().Set("Connection", "keep-alive")
+ w.Header().Set("Transfer-Encoding", "chunked")
+
+ rc := &domain.RecordParam{
+ UserID: c.UserID,
+ ModelID: m.ID,
+ ModelType: consts.ModelTypeLLM,
+ WorkMode: workMode,
+ Prompt: prompt,
+ TaskID: taskID,
+ }
+ buf := bufio.NewWriterSize(w, 32*1024)
+ defer buf.Flush()
+
+ ch := make(chan []byte, 1024)
+ defer close(ch)
+
+ go func(rc *domain.RecordParam) {
+ for line := range ch {
+ if bytes.HasPrefix(line, []byte("data:")) {
+ line = bytes.TrimPrefix(line, []byte("data: "))
+ line = bytes.TrimSpace(line)
+ if len(line) == 0 {
+ continue
+ }
+
+ if bytes.Equal(line, []byte("[DONE]")) {
+ break
+ }
+
+ var t openai.ChatCompletionStreamResponse
+ if err := json.Unmarshal(line, &t); err != nil {
+ p.logger.With("line", string(line)).WarnContext(ctx, "解析流式数据失败", "error", err)
+ continue
+ }
+
+ p.logger.With("response", t).DebugContext(ctx, "流式响应数据")
+ if len(t.Choices) > 0 {
+ rc.Completion += t.Choices[0].Delta.Content
+ }
+ if t.Usage != nil {
+ rc.InputTokens += int64(t.Usage.PromptTokens)
+ rc.OutputTokens += int64(t.Usage.CompletionTokens)
+ }
+ }
+ }
+
+ p.logger.With("record", rc).DebugContext(ctx, "流式记录")
+ if err := p.usecase.Record(context.Background(), rc); err != nil {
+ p.logger.With("modelID", m.ID, "modelName", m.ModelName, "modelType", consts.ModelTypeLLM).
+ WarnContext(ctx, "插入流式记录失败", "error", err)
+ }
+ }(rc)
+
+ err = streamRead(ctx, resp.Body, func(line []byte) error {
+ ch <- line
+ if _, err := buf.Write(line); err != nil {
+ return fmt.Errorf("写入响应失败: %w", err)
+ }
+ return buf.Flush()
+ })
+ return err
+ })
+}
+
+func (p *LLMProxy) handleChatCompletion(ctx context.Context, w http.ResponseWriter, req *openai.ChatCompletionRequest) {
+ endpoint := "/chat/completions"
+ p.handle(ctx, func(c *Ctx, log *RequestResponseLog) error {
+ // 使用负载均衡算法选择模型
+ m, err := p.usecase.SelectModelWithLoadBalancing(req.Model, consts.ModelTypeCoder)
+ if err != nil {
+ p.logger.With("modelName", req.Model, "modelType", consts.ModelTypeCoder).WarnContext(ctx, "模型选择失败", "error", err)
+ writeErrResp(w, http.StatusNotFound, "模型未找到", "proxy_error")
+ return err
+ }
+
+ // 构造上游API URL
+ upstream := m.APIBase + endpoint
+ log.UpstreamURL = upstream
+ u, err := url.Parse(upstream)
+ if err != nil {
+ p.logger.With("upstreamURL", upstream).WarnContext(ctx, "解析上游URL失败", "error", err)
+ writeErrResp(w, http.StatusInternalServerError, "无效的上游URL", "proxy_error")
+ return err
+ }
+
+ startTime := time.Now()
+ prompt := req.Metadata["message"]
+ workMode := req.Metadata["work_mode"]
+ taskID := req.Metadata["task_id"]
+
+ client := request.NewClient(u.Scheme, u.Host, 30*time.Second)
+ resp, err := request.Post[openai.ChatCompletionResponse](client, u.Path, req, request.WithHeader(request.Header{
+ "Authorization": "Bearer " + m.APIKey,
+ }))
+ if err != nil {
+ p.logger.With("upstreamURL", upstream).WarnContext(ctx, "发送上游请求失败", "error", err)
+ writeErrResp(w, http.StatusInternalServerError, "发送上游请求失败", "proxy_error")
+ log.Latency = time.Since(startTime).Milliseconds()
+ return err
+ }
+
+ // 记录请求信息
+ p.logger.With(
+ "upstreamURL", upstream,
+ "modelName", req.Model,
+ "modelType", consts.ModelTypeCoder,
+ "apiBase", m.APIBase,
+ "requestBody", req,
+ ).DebugContext(ctx, "转发请求到上游API")
+
+ go func() {
+ rc := &domain.RecordParam{
+ TaskID: taskID,
+ UserID: c.UserID,
+ Prompt: prompt,
+ WorkMode: workMode,
+ ModelID: m.ID,
+ ModelType: m.ModelType,
+ InputTokens: int64(resp.Usage.PromptTokens),
+ OutputTokens: int64(resp.Usage.CompletionTokens),
+ ProgramLanguage: req.Metadata["program_language"],
+ }
+
+ for _, choice := range resp.Choices {
+ rc.Completion += choice.Message.Content + "\n\n"
+ }
+
+ p.logger.With("record", rc).DebugContext(ctx, "记录")
+
+ if err := p.usecase.Record(ctx, rc); err != nil {
+ p.logger.With("modelID", m.ID, "modelName", req.Model, "modelType", consts.ModelTypeCoder).WarnContext(ctx, "记录请求失败", "error", err)
+ }
+ }()
+
+ // 计算请求耗时
+ latency := time.Since(startTime)
+
+ // 更新请求日志
+ log.StatusCode = http.StatusOK
+ log.ResponseBody = resp
+ log.ResponseHeader = resp.Header()
+ log.Latency = latency.Milliseconds()
+
+ // 记录响应状态
+ p.logger.With(
+ "statusCode", http.StatusOK,
+ "responseHeader", resp.Header(),
+ "responseBody", resp,
+ "latency", latency.String(),
+ ).DebugContext(ctx, "上游API响应")
+
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ b, err := json.Marshal(resp)
+ if err != nil {
+ p.logger.With("response", resp).WarnContext(ctx, "序列化响应失败", "error", err)
+ return err
+ }
+ w.Write(b)
+ return nil
+ })
+}
+
+func (p *LLMProxy) HandleEmbeddings(ctx context.Context, w http.ResponseWriter, req *openai.EmbeddingRequest) {
+}
diff --git a/backend/internal/proxy/repo/proxy.go b/backend/internal/proxy/repo/proxy.go
new file mode 100644
index 0000000..6ae69ce
--- /dev/null
+++ b/backend/internal/proxy/repo/proxy.go
@@ -0,0 +1,72 @@
+package repo
+
+import (
+ "context"
+
+ "github.com/chaitin/MonkeyCode/backend/consts"
+ "github.com/chaitin/MonkeyCode/backend/db"
+ "github.com/chaitin/MonkeyCode/backend/db/apikey"
+ "github.com/chaitin/MonkeyCode/backend/db/model"
+ "github.com/chaitin/MonkeyCode/backend/db/record"
+ "github.com/chaitin/MonkeyCode/backend/domain"
+ "github.com/chaitin/MonkeyCode/backend/pkg/entx"
+)
+
+type ProxyRepo struct {
+ db *db.Client
+}
+
+func NewProxyRepo(db *db.Client) domain.ProxyRepo {
+ return &ProxyRepo{db: db}
+}
+
+func (r *ProxyRepo) SelectModelWithLoadBalancing(modelName string, modelType consts.ModelType) (*db.Model, error) {
+ ctx := context.Background()
+ m, err := r.db.Model.Query().
+ Where(model.ModelName(modelName), model.ModelType(modelType)).
+ First(ctx)
+ if err != nil {
+ return nil, err
+ }
+ return m, nil
+}
+
+func (r *ProxyRepo) ValidateApiKey(ctx context.Context, key string) (*db.ApiKey, error) {
+ a, err := r.db.ApiKey.Query().
+ Where(apikey.Key(key), apikey.Status(consts.ApiKeyStatusActive)).
+ Only(ctx)
+ if err != nil {
+ return nil, err
+ }
+ return a, nil
+}
+
+func (r *ProxyRepo) Record(ctx context.Context, record *db.Record) error {
+ return r.db.Record.Create().
+ SetUserID(record.UserID).
+ SetModelID(record.ModelID).
+ SetTaskID(record.TaskID).
+ SetPrompt(record.Prompt).
+ SetProgramLanguage(record.ProgramLanguage).
+ SetInputTokens(record.InputTokens).
+ SetOutputTokens(record.OutputTokens).
+ SetIsAccept(record.IsAccept).
+ SetModelType(record.ModelType).
+ SetCompletion(record.Completion).
+ SetWorkMode(record.WorkMode).
+ SetCodeLines(record.CodeLines).
+ Exec(ctx)
+}
+
+func (r *ProxyRepo) UpdateByTaskID(ctx context.Context, taskID string, fn func(*db.RecordUpdateOne)) error {
+ rc, err := r.db.Record.Query().Where(record.TaskID(taskID)).Only(ctx)
+ if err != nil {
+ return err
+ }
+
+ return entx.WithTx(ctx, r.db, func(tx *db.Tx) error {
+ up := tx.Record.UpdateOneID(rc.ID)
+ fn(up)
+ return up.Exec(ctx)
+ })
+}
diff --git a/backend/internal/proxy/usecase/proxy.go b/backend/internal/proxy/usecase/proxy.go
new file mode 100644
index 0000000..797bdc8
--- /dev/null
+++ b/backend/internal/proxy/usecase/proxy.go
@@ -0,0 +1,71 @@
+package usecase
+
+import (
+ "context"
+
+ "github.com/google/uuid"
+
+ "github.com/chaitin/MonkeyCode/backend/pkg/cvt"
+
+ "github.com/chaitin/MonkeyCode/backend/consts"
+ "github.com/chaitin/MonkeyCode/backend/db"
+ "github.com/chaitin/MonkeyCode/backend/domain"
+)
+
+type ProxyUsecase struct {
+ repo domain.ProxyRepo
+}
+
+func NewProxyUsecase(repo domain.ProxyRepo) domain.ProxyUsecase {
+ return &ProxyUsecase{repo: repo}
+}
+
+func (p *ProxyUsecase) Record(ctx context.Context, record *domain.RecordParam) error {
+ userID, err := uuid.Parse(record.UserID)
+ if err != nil {
+ return err
+ }
+ modelID, err := uuid.Parse(record.ModelID)
+ if err != nil {
+ return err
+ }
+
+ return p.repo.Record(ctx, &db.Record{
+ UserID: userID,
+ ModelID: modelID,
+ Prompt: record.Prompt,
+ TaskID: record.TaskID,
+ ProgramLanguage: record.ProgramLanguage,
+ InputTokens: record.InputTokens,
+ OutputTokens: record.OutputTokens,
+ IsAccept: record.IsAccept,
+ ModelType: record.ModelType,
+ Completion: record.Completion,
+ WorkMode: record.WorkMode,
+ CodeLines: record.CodeLines,
+ })
+}
+
+// SelectModelWithLoadBalancing implements domain.ProxyUsecase.
+func (p *ProxyUsecase) SelectModelWithLoadBalancing(modelName string, modelType consts.ModelType) (*domain.Model, error) {
+ model, err := p.repo.SelectModelWithLoadBalancing(modelName, modelType)
+ if err != nil {
+ return nil, err
+ }
+ return cvt.From(model, &domain.Model{}), nil
+}
+
+func (p *ProxyUsecase) ValidateApiKey(ctx context.Context, key string) (*domain.ApiKey, error) {
+ apiKey, err := p.repo.ValidateApiKey(ctx, key)
+ if err != nil {
+ return nil, err
+ }
+ return cvt.From(apiKey, &domain.ApiKey{}), nil
+}
+
+func (p *ProxyUsecase) AcceptCompletion(ctx context.Context, req *domain.AcceptCompletionReq) error {
+ return p.repo.UpdateByTaskID(ctx, req.ID, func(ruo *db.RecordUpdateOne) {
+ ruo.SetIsAccept(true)
+ ruo.SetCompletion(req.Completion)
+ })
+}
diff --git a/backend/internal/user/handler/v1/user.go b/backend/internal/user/handler/v1/user.go
new file mode 100644
index 0000000..40bec4d
--- /dev/null
+++ b/backend/internal/user/handler/v1/user.go
@@ -0,0 +1,374 @@
+package v1
+
+import (
+ "context"
+ "log/slog"
+ "net/http"
+
+ "github.com/GoYoko/web"
+
+ "github.com/chaitin/MonkeyCode/backend/config"
+ "github.com/chaitin/MonkeyCode/backend/consts"
+ "github.com/chaitin/MonkeyCode/backend/domain"
+ "github.com/chaitin/MonkeyCode/backend/errcode"
+ "github.com/chaitin/MonkeyCode/backend/internal/middleware"
+ "github.com/chaitin/MonkeyCode/backend/pkg/session"
+ "github.com/chaitin/MonkeyCode/backend/pkg/vsix"
+)
+
+type UserHandler struct {
+ usecase domain.UserUsecase
+ session *session.Session
+ logger *slog.Logger
+ cfg *config.Config
+}
+
+func NewUserHandler(
+ w *web.Web,
+ usecase domain.UserUsecase,
+ auth *middleware.AuthMiddleware,
+ session *session.Session,
+ logger *slog.Logger,
+ cfg *config.Config,
+) *UserHandler {
+ u := &UserHandler{
+ usecase: usecase,
+ session: session,
+ logger: logger,
+ cfg: cfg,
+ }
+
+ w.GET("/api/v1/static/vsix", web.BaseHandler(u.VSIXDownload))
+ w.POST("/api/v1/vscode/init-auth", web.BindHandler(u.VSCodeAuthInit))
+
+ // admin
+ admin := w.Group("/api/v1/admin")
+ admin.POST("/login", web.BindHandler(u.AdminLogin))
+
+ admin.Use(auth.Auth())
+ admin.GET("/setting", web.BaseHandler(u.GetSetting))
+ admin.PUT("/setting", web.BindHandler(u.UpdateSetting))
+ admin.POST("/create", web.BindHandler(u.CreateAdmin))
+ admin.GET("/list", web.BaseHandler(u.AdminList, web.WithPage()))
+ admin.GET("/login-history", web.BaseHandler(u.AdminLoginHistory, web.WithPage()))
+ admin.DELETE("/delete", web.BaseHandler(u.DeleteAdmin))
+
+ g := w.Group("/api/v1/user")
+ g.POST("/register", web.BindHandler(u.Register))
+ g.POST("/login", web.BindHandler(u.Login))
+
+ g.Use(auth.Auth())
+
+ g.PUT("/update", web.BindHandler(u.Update))
+ g.DELETE("/delete", web.BaseHandler(u.Delete))
+ g.GET("/invite", web.BaseHandler(u.Invite))
+ g.GET("/list", web.BindHandler(u.List, web.WithPage()))
+ g.GET("/login-history", web.BaseHandler(u.LoginHistory, web.WithPage()))
+
+ return u
+}
+
+func (h *UserHandler) VSCodeAuthInit(c *web.Context, req domain.VSCodeAuthInitReq) error {
+ resp, err := h.usecase.VSCodeAuthInit(c.Request().Context(), &req)
+ if err != nil {
+ return err
+ }
+ return c.JSON(http.StatusOK, resp)
+}
+
+// VSIXDownload 下载VSCode插件
+//
+// @Tags User
+// @Summary 下载VSCode插件
+// @Description 下载VSCode插件
+// @ID vsix-download
+// @Accept json
+// @Produce octet-stream
+// @Router /api/v1/static/vsix [get]
+func (h *UserHandler) VSIXDownload(c *web.Context) error {
+ c.Response().Header().Set("Content-Type", "application/octet-stream")
+ c.Response().Header().Set("Content-Disposition", "attachment; filename=monkeycode.vsix")
+ if err := vsix.ChangeVsixEndpoint(h.cfg.VSCode.VSIXFile, "extension/package.json", h.cfg.BaseUrl, c.Response().Writer); err != nil {
+ return err
+ }
+ return nil
+}
+
+// Login 用户登录
+//
+// @Tags User
+// @Summary 用户登录
+// @Description 用户登录
+// @ID login
+// @Accept json
+// @Produce json
+// @Param param body domain.LoginReq true "登录参数"
+// @Success 200 {object} web.Resp{data=domain.LoginResp}
+// @Router /api/v1/user/login [post]
+func (h *UserHandler) Login(c *web.Context, req domain.LoginReq) error {
+ resp, err := h.usecase.Login(c.Request().Context(), &req)
+ if err != nil {
+ return err
+ }
+ return c.Success(resp)
+}
+
+// Update 更新用户
+//
+// @Tags User
+// @Summary 更新用户
+// @Description 更新用户
+// @ID update-user
+// @Accept json
+// @Produce json
+// @Param param body domain.UpdateUserReq true "更新用户参数"
+// @Success 200 {object} web.Resp{data=domain.User}
+// @Router /api/v1/user/update [put]
+func (h *UserHandler) Update(c *web.Context, req domain.UpdateUserReq) error {
+ resp, err := h.usecase.Update(c.Request().Context(), &req)
+ if err != nil {
+ return err
+ }
+ return c.Success(resp)
+}
+
+// Delete 删除用户
+//
+// @Tags User
+// @Summary 删除用户
+// @Description 删除用户
+// @ID delete-user
+// @Accept json
+// @Produce json
+// @Param id query string true "用户ID"
+// @Success 200 {object} web.Resp{data=nil}
+// @Router /api/v1/user/delete [delete]
+func (h *UserHandler) Delete(c *web.Context) error {
+ err := h.usecase.Delete(c.Request().Context(), c.QueryParam("id"))
+ if err != nil {
+ return err
+ }
+ return c.Success(nil)
+}
+
+// DeleteAdmin 删除管理员
+//
+// @Tags User
+// @Summary 删除管理员
+// @Description 删除管理员
+// @ID delete-admin
+// @Accept json
+// @Produce json
+// @Param id query string true "管理员ID"
+// @Success 200 {object} web.Resp{data=nil}
+// @Router /api/v1/admin/delete [delete]
+func (h *UserHandler) DeleteAdmin(c *web.Context) error {
+ err := h.usecase.DeleteAdmin(c.Request().Context(), c.QueryParam("id"))
+ if err != nil {
+ return err
+ }
+ return c.Success(nil)
+}
+
+// AdminLogin 管理员登录
+//
+// @Tags User
+// @Summary 管理员登录
+// @Description 管理员登录
+// @ID admin-login
+// @Accept json
+// @Produce json
+// @Param param body domain.LoginReq true "登录参数"
+// @Success 200 {object} web.Resp{data=domain.AdminUser}
+// @Router /api/v1/admin/login [post]
+func (h *UserHandler) AdminLogin(c *web.Context, req domain.LoginReq) error {
+ resp, err := h.usecase.AdminLogin(c.Request().Context(), &req)
+ if err != nil {
+ return err
+ }
+
+ h.logger.With("header", c.Request().Header).With("host", c.Request().Host).Info("admin login", "username", resp.Username)
+ if _, err := h.session.Save(c, consts.SessionName, c.Request().Host, resp); err != nil {
+ return err
+ }
+ return c.Success(resp)
+}
+
+// List 获取用户列表
+//
+// @Tags User
+// @Summary 获取用户列表
+// @Description 获取用户列表
+// @ID list-user
+// @Accept json
+// @Produce json
+// @Param page query web.Pagination true "分页"
+// @Success 200 {object} web.Resp{data=domain.ListUserResp}
+// @Router /api/v1/user/list [get]
+func (h *UserHandler) List(c *web.Context, req domain.ListReq) error {
+ resp, err := h.usecase.List(c.Request().Context(), req)
+ if err != nil {
+ return err
+ }
+ return c.Success(resp)
+}
+
+// LoginHistory 获取用户登录历史
+//
+// @Tags User
+// @Summary 获取用户登录历史
+// @Description 获取用户登录历史
+// @ID login-history
+// @Accept json
+// @Produce json
+// @Param page query web.Pagination true "分页"
+// @Success 200 {object} web.Resp{data=domain.ListLoginHistoryResp}
+// @Router /api/v1/user/login-history [get]
+func (h *UserHandler) LoginHistory(c *web.Context) error {
+ resp, err := h.usecase.LoginHistory(c.Request().Context(), c.Page())
+ if err != nil {
+ return err
+ }
+ return c.Success(resp)
+}
+
+// Invite 获取用户邀请码
+//
+// @Tags User
+// @Summary 获取用户邀请码
+// @Description 获取用户邀请码
+// @ID invite
+// @Accept json
+// @Produce json
+// @Success 200 {object} web.Resp{data=domain.InviteResp}
+// @Router /api/v1/user/invite [get]
+func (h *UserHandler) Invite(c *web.Context) error {
+ user := middleware.GetUser(c)
+ resp, err := h.usecase.Invite(c.Request().Context(), user.ID)
+ if err != nil {
+ return err
+ }
+ return c.Success(resp)
+}
+
+// Register 注册用户
+//
+// @Tags User
+// @Summary 注册用户
+// @Description 注册用户
+// @ID register
+// @Accept json
+// @Produce json
+// @Param param body domain.RegisterReq true "注册参数"
+// @Success 200 {object} web.Resp{data=domain.User}
+// @Router /api/v1/user/register [post]
+func (h *UserHandler) Register(c *web.Context, req domain.RegisterReq) error {
+ resp, err := h.usecase.Register(c.Request().Context(), &req)
+ if err != nil {
+ return err
+ }
+
+ return c.Success(resp)
+}
+
+// CreateAdmin 创建管理员
+//
+// @Tags User
+// @Summary 创建管理员
+// @Description 创建管理员
+// @ID create-admin
+// @Accept json
+// @Produce json
+// @Param param body domain.CreateAdminReq true "创建管理员参数"
+// @Success 200 {object} web.Resp{data=domain.AdminUser}
+// @Router /api/v1/admin/create [post]
+func (h *UserHandler) CreateAdmin(c *web.Context, req domain.CreateAdminReq) error {
+ user := middleware.GetUser(c)
+ if user.Username != "admin" {
+ return errcode.ErrPermission
+ }
+ resp, err := h.usecase.CreateAdmin(c.Request().Context(), &req)
+ if err != nil {
+ return err
+ }
+ return c.Success(resp)
+}
+
+// AdminList 获取管理员用户列表
+//
+// @Tags User
+// @Summary 获取管理员用户列表
+// @Description 获取管理员用户列表
+// @ID list-admin-user
+// @Accept json
+// @Produce json
+// @Param page query web.Pagination true "分页"
+// @Success 200 {object} web.Resp{data=domain.ListAdminUserResp}
+// @Router /api/v1/admin/list [get]
+func (h *UserHandler) AdminList(c *web.Context) error {
+ resp, err := h.usecase.AdminList(c.Request().Context(), c.Page())
+ if err != nil {
+ return err
+ }
+ return c.Success(resp)
+}
+
+// AdminLoginHistory 获取管理员登录历史
+//
+// @Tags User
+// @Summary 获取管理员登录历史
+// @Description 获取管理员登录历史
+// @ID admin-login-history
+// @Accept json
+// @Produce json
+// @Param page query web.Pagination true "分页"
+// @Success 200 {object} web.Resp{data=domain.ListAdminLoginHistoryResp}
+// @Router /api/v1/admin/login-history [get]
+func (h *UserHandler) AdminLoginHistory(c *web.Context) error {
+ resp, err := h.usecase.AdminLoginHistory(c.Request().Context(), c.Page())
+ if err != nil {
+ return err
+ }
+ return c.Success(resp)
+}
+
+// GetSetting 获取系统设置
+//
+// @Tags User
+// @Summary 获取系统设置
+// @Description 获取系统设置
+// @ID get-setting
+// @Accept json
+// @Produce json
+// @Success 200 {object} web.Resp{data=domain.Setting}
+// @Router /api/v1/admin/setting [get]
+func (h *UserHandler) GetSetting(c *web.Context) error {
+ resp, err := h.usecase.GetSetting(c.Request().Context())
+ if err != nil {
+ return err
+ }
+ return c.Success(resp)
+}
+
+// UpdateSetting 更新系统设置
+//
+// @Tags User
+// @Summary 更新系统设置
+// @Description 更新系统设置
+// @ID update-setting
+// @Accept json
+// @Produce json
+// @Param param body domain.UpdateSettingReq true "更新系统设置参数"
+// @Success 200 {object} web.Resp{data=domain.Setting}
+// @Router /api/v1/admin/setting [put]
+func (h *UserHandler) UpdateSetting(c *web.Context, req domain.UpdateSettingReq) error {
+ resp, err := h.usecase.UpdateSetting(c.Request().Context(), &req)
+ if err != nil {
+ return err
+ }
+ return c.Success(resp)
+}
+
+func (h *UserHandler) InitAdmin() error {
+ return h.usecase.InitAdmin(context.Background())
+}
diff --git a/backend/internal/user/repo/user.go b/backend/internal/user/repo/user.go
new file mode 100644
index 0000000..5279f77
--- /dev/null
+++ b/backend/internal/user/repo/user.go
@@ -0,0 +1,212 @@
+package repo
+
+import (
+ "context"
+ "errors"
+
+ "github.com/google/uuid"
+
+ "github.com/GoYoko/web"
+
+ "github.com/chaitin/MonkeyCode/backend/consts"
+ "github.com/chaitin/MonkeyCode/backend/db"
+ "github.com/chaitin/MonkeyCode/backend/db/admin"
+ "github.com/chaitin/MonkeyCode/backend/db/apikey"
+ "github.com/chaitin/MonkeyCode/backend/db/invitecode"
+ "github.com/chaitin/MonkeyCode/backend/db/user"
+ "github.com/chaitin/MonkeyCode/backend/domain"
+ "github.com/chaitin/MonkeyCode/backend/pkg/entx"
+)
+
+type UserRepo struct {
+ db *db.Client
+}
+
+func NewUserRepo(db *db.Client) domain.UserRepo {
+ return &UserRepo{db: db}
+}
+
+func (r *UserRepo) InitAdmin(ctx context.Context, username, password string) error {
+ _, err := r.AdminByName(ctx, username)
+ if db.IsNotFound(err) {
+ _, err = r.CreateAdmin(ctx, &db.Admin{
+ Username: username,
+ Password: password,
+ Status: consts.AdminStatusActive,
+ })
+ }
+ if err != nil {
+ return err
+ }
+ return nil
+}
+
+func (r *UserRepo) CreateAdmin(ctx context.Context, admin *db.Admin) (*db.Admin, error) {
+ return r.db.Admin.Create().
+ SetUsername(admin.Username).
+ SetPassword(admin.Password).
+ SetStatus(admin.Status).
+ Save(ctx)
+
+}
+
+func (r *UserRepo) AdminByName(ctx context.Context, username string) (*db.Admin, error) {
+ return r.db.Admin.Query().Where(admin.Username(username)).Only(ctx)
+}
+
+func (r *UserRepo) GetByName(ctx context.Context, username string) (*db.User, error) {
+ return r.db.User.Query().Where(
+ user.Or(
+ user.Username(username),
+ user.Email(username),
+ ),
+ ).Only(ctx)
+}
+
+func (r *UserRepo) ValidateInviteCode(ctx context.Context, code string) (*db.InviteCode, error) {
+ return r.db.InviteCode.Query().Where(invitecode.Code(code)).Only(ctx)
+}
+
+func (r *UserRepo) CreateUser(ctx context.Context, user *db.User) (*db.User, error) {
+ return r.db.User.Create().
+ SetUsername(user.Username).
+ SetEmail(user.Email).
+ SetPassword(user.Password).
+ SetStatus(user.Status).
+ Save(ctx)
+}
+
+func (r *UserRepo) UserLoginHistory(ctx context.Context, page *web.Pagination) ([]*db.UserLoginHistory, *db.PageInfo, error) {
+ q := r.db.UserLoginHistory.Query()
+ return q.Page(ctx, page.Page, page.Size)
+}
+
+func (r *UserRepo) AdminLoginHistory(ctx context.Context, page *web.Pagination) ([]*db.AdminLoginHistory, *db.PageInfo, error) {
+ q := r.db.AdminLoginHistory.Query()
+ return q.Page(ctx, page.Page, page.Size)
+}
+
+func (r *UserRepo) CreateInviteCode(ctx context.Context, userID string, code string) (*db.InviteCode, error) {
+ adminID, err := uuid.Parse(userID)
+ if err != nil {
+ return nil, err
+ }
+
+ return r.db.InviteCode.Create().
+ SetAdminID(adminID).
+ SetCode(code).
+ Save(ctx)
+}
+
+func (r *UserRepo) AdminList(ctx context.Context, page *web.Pagination) ([]*db.Admin, *db.PageInfo, error) {
+ q := r.db.Admin.Query()
+ return q.Page(ctx, page.Page, page.Size)
+}
+
+func (r *UserRepo) List(ctx context.Context, page *web.Pagination) ([]*db.User, *db.PageInfo, error) {
+ q := r.db.User.Query()
+ return q.Page(ctx, page.Page, page.Size)
+}
+
+func (r *UserRepo) GetOrCreateApiKey(ctx context.Context, userID string) (*db.ApiKey, error) {
+ i, err := uuid.Parse(userID)
+ if err != nil {
+ return nil, err
+ }
+
+ var apiKey *db.ApiKey
+ err = entx.WithTx(ctx, r.db, func(tx *db.Tx) error {
+ k, err := tx.ApiKey.Query().Where(apikey.UserID(i)).First(ctx)
+ if db.IsNotFound(err) {
+ n, err := tx.ApiKey.Create().
+ SetUserID(i).
+ SetKey(uuid.NewString()).
+ SetName("default").
+ SetStatus(consts.ApiKeyStatusActive).
+ Save(ctx)
+ if err != nil {
+ return err
+ }
+ apiKey = n
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ apiKey = k
+ return nil
+ })
+ return apiKey, err
+}
+
+func (r *UserRepo) GetSetting(ctx context.Context) (*db.Setting, error) {
+ s, err := r.db.Setting.Query().First(ctx)
+ if db.IsNotFound(err) {
+ return r.db.Setting.Create().
+ SetEnableSSO(false).
+ SetForceTwoFactorAuth(false).
+ SetDisablePasswordLogin(false).
+ Save(ctx)
+ }
+ if err != nil {
+ return nil, err
+ }
+ return s, nil
+}
+
+func (r *UserRepo) UpdateSetting(ctx context.Context, fn func(*db.SettingUpdateOne)) (*db.Setting, error) {
+ var s *db.Setting
+ err := entx.WithTx(ctx, r.db, func(tx *db.Tx) error {
+ s, err := tx.Setting.Query().First(ctx)
+ if err != nil {
+ return err
+ }
+ up := tx.Setting.UpdateOneID(s.ID)
+ fn(up)
+ return up.Exec(ctx)
+ })
+ return s, err
+}
+
+func (r *UserRepo) Update(ctx context.Context, id string, fn func(*db.UserUpdateOne) error) (*db.User, error) {
+ uid, err := uuid.Parse(id)
+ if err != nil {
+ return nil, err
+ }
+
+ var u *db.User
+ err = entx.WithTx(ctx, r.db, func(tx *db.Tx) error {
+ u, err = tx.User.Query().Where(user.ID(uid)).Only(ctx)
+ if err != nil {
+ return err
+ }
+ if err := fn(u.Update()); err != nil {
+ return err
+ }
+ return u.Update().Exec(ctx)
+ })
+ return u, err
+}
+
+func (r *UserRepo) Delete(ctx context.Context, id string) error {
+ uid, err := uuid.Parse(id)
+ if err != nil {
+ return err
+ }
+ return r.db.User.DeleteOneID(uid).Exec(ctx)
+}
+
+func (r *UserRepo) DeleteAdmin(ctx context.Context, id string) error {
+ uid, err := uuid.Parse(id)
+ if err != nil {
+ return err
+ }
+ admin, err := r.db.Admin.Get(ctx, uid)
+ if err != nil {
+ return err
+ }
+ if admin.Username == "admin" {
+ return errors.New("admin cannot be deleted")
+ }
+ return r.db.Admin.DeleteOne(admin).Exec(ctx)
+}
diff --git a/backend/internal/user/usecase/user.go b/backend/internal/user/usecase/user.go
new file mode 100644
index 0000000..a8e1e2c
--- /dev/null
+++ b/backend/internal/user/usecase/user.go
@@ -0,0 +1,285 @@
+package usecase
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "log/slog"
+ "strings"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/redis/go-redis/v9"
+ "golang.org/x/crypto/bcrypt"
+
+ "github.com/GoYoko/web"
+ "github.com/chaitin/MonkeyCode/backend/pkg/cvt"
+
+ "github.com/chaitin/MonkeyCode/backend/config"
+ "github.com/chaitin/MonkeyCode/backend/db"
+ "github.com/chaitin/MonkeyCode/backend/domain"
+ "github.com/chaitin/MonkeyCode/backend/errcode"
+)
+
+type UserUsecase struct {
+ cfg *config.Config
+ redis *redis.Client
+ repo domain.UserRepo
+ logger *slog.Logger
+}
+
+func NewUserUsecase(
+ cfg *config.Config,
+ redis *redis.Client,
+ repo domain.UserRepo,
+ logger *slog.Logger,
+) domain.UserUsecase {
+ u := &UserUsecase{
+ cfg: cfg,
+ redis: redis,
+ repo: repo,
+ logger: logger,
+ }
+ return u
+}
+
+func (u *UserUsecase) InitAdmin(ctx context.Context) error {
+ hash, err := bcrypt.GenerateFromPassword([]byte(u.cfg.Admin.Password), bcrypt.DefaultCost)
+ if err != nil {
+ u.logger.Error("generate admin password", "error", err)
+ return err
+ }
+ return u.repo.InitAdmin(ctx, u.cfg.Admin.User, string(hash))
+}
+
+func (u *UserUsecase) List(ctx context.Context, req domain.ListReq) (*domain.ListUserResp, error) {
+ users, p, err := u.repo.List(ctx, &req.Pagination)
+ if err != nil {
+ return nil, err
+ }
+
+ return &domain.ListUserResp{
+ PageInfo: p,
+ Users: cvt.Iter(users, func(_ int, e *db.User) *domain.User {
+ return cvt.From(e, &domain.User{}).From(e)
+ }),
+ }, nil
+}
+
+// AdminList implements domain.UserUsecase.
+func (u *UserUsecase) AdminList(ctx context.Context, page *web.Pagination) (*domain.ListAdminUserResp, error) {
+ admins, p, err := u.repo.AdminList(ctx, page)
+ if err != nil {
+ return nil, err
+ }
+
+ return &domain.ListAdminUserResp{
+ PageInfo: p,
+ Users: cvt.Iter(admins, func(_ int, e *db.Admin) *domain.AdminUser {
+ return cvt.From(e, &domain.AdminUser{}).From(e)
+ }),
+ }, nil
+}
+
+// AdminLoginHistory implements domain.UserUsecase.
+func (u *UserUsecase) AdminLoginHistory(ctx context.Context, page *web.Pagination) (*domain.ListAdminLoginHistoryResp, error) {
+ histories, p, err := u.repo.AdminLoginHistory(ctx, page)
+ if err != nil {
+ return nil, err
+ }
+
+ return &domain.ListAdminLoginHistoryResp{
+ PageInfo: p,
+ LoginHistories: cvt.Iter(histories, func(_ int, e *db.AdminLoginHistory) *domain.AdminLoginHistory {
+ return cvt.From(e, &domain.AdminLoginHistory{}).From(e)
+ }),
+ }, nil
+}
+
+// Invite implements domain.UserUsecase.
+func (u *UserUsecase) Invite(ctx context.Context, userID string) (*domain.InviteResp, error) {
+ icode := uuid.NewString()
+ code, err := u.repo.CreateInviteCode(ctx, userID, icode)
+ if err != nil {
+ return nil, err
+ }
+ return &domain.InviteResp{
+ Code: code.Code,
+ }, nil
+}
+
+// LoginHistory implements domain.UserUsecase.
+func (u *UserUsecase) LoginHistory(ctx context.Context, page *web.Pagination) (*domain.ListLoginHistoryResp, error) {
+ histories, p, err := u.repo.UserLoginHistory(ctx, page)
+ if err != nil {
+ return nil, err
+ }
+
+ return &domain.ListLoginHistoryResp{
+ PageInfo: p,
+ LoginHistories: cvt.Iter(histories, func(_ int, e *db.UserLoginHistory) *domain.UserLoginHistory {
+ return cvt.From(e, &domain.UserLoginHistory{}).From(e)
+ }),
+ }, nil
+}
+
+// Register implements domain.UserUsecase.
+func (u *UserUsecase) Register(ctx context.Context, req *domain.RegisterReq) (*domain.User, error) {
+ if _, err := u.repo.ValidateInviteCode(ctx, req.Code); err != nil {
+ return nil, errcode.ErrInviteCodeInvalid.Wrap(err)
+ }
+
+ hash, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
+ if err != nil {
+ return nil, err
+ }
+ parts := strings.Split(req.Email, "@")
+ if len(parts) != 2 {
+ return nil, errcode.ErrEmailInvalid
+ }
+ user := &db.User{
+ Username: parts[0],
+ Email: req.Email,
+ Password: string(hash),
+ }
+ n, err := u.repo.CreateUser(ctx, user)
+ if err != nil {
+ return nil, err
+ }
+
+ return cvt.From(n, &domain.User{}), nil
+}
+
+func (u *UserUsecase) Login(ctx context.Context, req *domain.LoginReq) (*domain.LoginResp, error) {
+ s, err := u.redis.Get(ctx, fmt.Sprintf("vscode:session:%s", req.SessionID)).Result()
+ if err != nil {
+ return nil, err
+ }
+ session := &domain.VSCodeSession{}
+ if err := json.Unmarshal([]byte(s), session); err != nil {
+ return nil, err
+ }
+
+ user, err := u.repo.GetByName(ctx, req.Username)
+ if err != nil {
+ return nil, errcode.ErrUserNotFound.Wrap(err)
+ }
+ if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.Password)); err != nil {
+ return nil, errcode.ErrPassword.Wrap(err)
+ }
+
+ apiKey, err := u.repo.GetOrCreateApiKey(ctx, user.ID.String())
+ if err != nil {
+ return nil, err
+ }
+
+ r := fmt.Sprintf("%s?state=%s&api_key=%s&expires_in=3600&username=%s", session.RedirectURI, session.State, apiKey.Key, user.Username)
+ return &domain.LoginResp{
+ RedirectURL: r,
+ }, nil
+}
+
+func (u *UserUsecase) AdminLogin(ctx context.Context, req *domain.LoginReq) (*domain.AdminUser, error) {
+ admin, err := u.repo.AdminByName(ctx, req.Username)
+ if err != nil {
+ return nil, errcode.ErrUserNotFound.Wrap(err)
+ }
+ if err := bcrypt.CompareHashAndPassword([]byte(admin.Password), []byte(req.Password)); err != nil {
+ return nil, errcode.ErrPassword.Wrap(err)
+ }
+ return cvt.From(admin, &domain.AdminUser{}), nil
+}
+
+func (u *UserUsecase) VSCodeAuthInit(ctx context.Context, req *domain.VSCodeAuthInitReq) (*domain.VSCodeAuthInitResp, error) {
+ i := uuid.NewString()
+ session := &domain.VSCodeSession{
+ ID: i,
+ State: req.State,
+ RedirectURI: req.RedirectURI,
+ }
+
+ b, err := json.Marshal(session)
+ if err != nil {
+ return nil, err
+ }
+ if err := u.redis.Set(ctx, fmt.Sprintf("vscode:session:%s", i), b, 15*time.Minute).Err(); err != nil {
+ return nil, err
+ }
+ return &domain.VSCodeAuthInitResp{
+ AuthURL: fmt.Sprintf("%s?session_id=%s", u.cfg.BaseUrl+"/auth", i),
+ }, nil
+}
+
+func (u *UserUsecase) CreateAdmin(ctx context.Context, req *domain.CreateAdminReq) (*domain.AdminUser, error) {
+ hash, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
+ if err != nil {
+ return nil, err
+ }
+ admin := &db.Admin{
+ Username: req.Username,
+ Password: string(hash),
+ }
+ n, err := u.repo.CreateAdmin(ctx, admin)
+ if err != nil {
+ return nil, err
+ }
+ return &domain.AdminUser{
+ ID: n.ID.String(),
+ Username: n.Username,
+ CreatedAt: n.CreatedAt.Unix(),
+ }, nil
+}
+
+func (u *UserUsecase) GetSetting(ctx context.Context) (*domain.Setting, error) {
+ s, err := u.repo.GetSetting(ctx)
+ if err != nil {
+ return nil, err
+ }
+ return cvt.From(s, &domain.Setting{}), nil
+}
+
+func (u *UserUsecase) UpdateSetting(ctx context.Context, req *domain.UpdateSettingReq) (*domain.Setting, error) {
+ s, err := u.repo.UpdateSetting(ctx, func(s *db.SettingUpdateOne) {
+ if req.EnableSSO != nil {
+ s.SetEnableSSO(*req.EnableSSO)
+ }
+ if req.ForceTwoFactorAuth != nil {
+ s.SetForceTwoFactorAuth(*req.ForceTwoFactorAuth)
+ }
+ if req.DisablePasswordLogin != nil {
+ s.SetDisablePasswordLogin(*req.DisablePasswordLogin)
+ }
+ })
+ if err != nil {
+ return nil, err
+ }
+ return cvt.From(s, &domain.Setting{}), nil
+}
+
+func (u *UserUsecase) Update(ctx context.Context, req *domain.UpdateUserReq) (*domain.User, error) {
+ user, err := u.repo.Update(ctx, req.ID, func(u *db.UserUpdateOne) error {
+ if req.Status != nil {
+ u.SetStatus(*req.Status)
+ }
+ if req.Password != nil {
+ hash, err := bcrypt.GenerateFromPassword([]byte(*req.Password), bcrypt.DefaultCost)
+ if err != nil {
+ return err
+ }
+ u.SetPassword(string(hash))
+ }
+ return nil
+ })
+ if err != nil {
+ return nil, err
+ }
+ return cvt.From(user, &domain.User{}), nil
+}
+
+func (u *UserUsecase) Delete(ctx context.Context, id string) error {
+ return u.repo.Delete(ctx, id)
+}
+
+func (u *UserUsecase) DeleteAdmin(ctx context.Context, id string) error {
+ return u.repo.DeleteAdmin(ctx, id)
+}
diff --git a/backend/internal/user/usecase/user_test.go b/backend/internal/user/usecase/user_test.go
new file mode 100644
index 0000000..dadeffb
--- /dev/null
+++ b/backend/internal/user/usecase/user_test.go
@@ -0,0 +1,17 @@
+package usecase
+
+import (
+ "fmt"
+ "testing"
+
+ "golang.org/x/crypto/bcrypt"
+)
+
+func TestBcrypt(t *testing.T) {
+ password := "admin88"
+ hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
+ if err != nil {
+ t.Fatal(err)
+ }
+ fmt.Println(string(hash))
+}
diff --git a/backend/migration/000001_create_uuid_extension.down.sql b/backend/migration/000001_create_uuid_extension.down.sql
new file mode 100644
index 0000000..e69de29
diff --git a/backend/migration/000001_create_uuid_extension.up.sql b/backend/migration/000001_create_uuid_extension.up.sql
new file mode 100644
index 0000000..682131d
--- /dev/null
+++ b/backend/migration/000001_create_uuid_extension.up.sql
@@ -0,0 +1 @@
+CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
\ No newline at end of file
diff --git a/backend/migration/000002_create_core_table.down.sql b/backend/migration/000002_create_core_table.down.sql
new file mode 100644
index 0000000..e69de29
diff --git a/backend/migration/000002_create_core_table.up.sql b/backend/migration/000002_create_core_table.up.sql
new file mode 100644
index 0000000..4f33fba
--- /dev/null
+++ b/backend/migration/000002_create_core_table.up.sql
@@ -0,0 +1,133 @@
+CREATE TABLE IF NOT EXISTS admins (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ username VARCHAR(255) UNIQUE NOT NULL,
+ password VARCHAR(255) NOT NULL,
+ status VARCHAR(20) DEFAULT 'active',
+ last_active_at TIMESTAMPTZ,
+ created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
+ updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
+);
+
+CREATE INDEX IF NOT EXISTS idx_admins_username ON admins (username);
+
+CREATE TABLE IF NOT EXISTS invite_codes (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ admin_id UUID NOT NULL,
+ code VARCHAR(255) UNIQUE NOT NULL,
+ created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
+ updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
+);
+
+-- 用户表
+CREATE TABLE IF NOT EXISTS users (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ username VARCHAR(255) UNIQUE NOT NULL,
+ password VARCHAR(255) NOT NULL,
+ email VARCHAR(255) UNIQUE,
+ status VARCHAR(20) DEFAULT 'active',
+ created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
+ updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
+);
+
+CREATE INDEX IF NOT EXISTS idx_users_username ON users (username);
+
+CREATE TABLE IF NOT EXISTS user_login_histories (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ user_id UUID NOT NULL,
+ ip VARCHAR(255),
+ country VARCHAR(255),
+ province VARCHAR(255),
+ city VARCHAR(255),
+ isp VARCHAR(255),
+ asn VARCHAR(255),
+ client_version VARCHAR(255),
+ device VARCHAR(255),
+ created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
+);
+
+CREATE INDEX IF NOT EXISTS idx_user_login_histories_user_id ON user_login_histories (user_id);
+
+CREATE TABLE IF NOT EXISTS admin_login_histories (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ admin_id UUID NOT NULL,
+ ip VARCHAR(255),
+ country VARCHAR(255),
+ province VARCHAR(255),
+ city VARCHAR(255),
+ isp VARCHAR(255),
+ asn VARCHAR(255),
+ client_version VARCHAR(255),
+ device VARCHAR(255),
+ created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
+);
+
+CREATE INDEX IF NOT EXISTS idx_admin_login_histories_admin_id ON admin_login_histories (admin_id);
+
+-- 模型表
+CREATE TABLE IF NOT EXISTS models (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ user_id UUID NOT NULL,
+ model_name VARCHAR(255) NOT NULL,
+ model_type VARCHAR(50) NOT NULL,
+ api_base VARCHAR(255),
+ api_key VARCHAR(255),
+ api_version VARCHAR(50),
+ description TEXT,
+ provider VARCHAR(50) NOT NULL,
+ context_length INTEGER DEFAULT 4096,
+ status VARCHAR(20) DEFAULT 'active',
+ capabilities JSONB,
+ parameters JSONB,
+ pricing JSONB,
+ created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
+ updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
+);
+
+CREATE INDEX IF NOT EXISTS idx_model_api_type ON models (model_name, api_base, model_type);
+
+CREATE TABLE IF NOT EXISTS api_keys (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ user_id UUID NOT NULL,
+ key VARCHAR(64) NOT NULL UNIQUE,
+ name VARCHAR(64) NOT NULL,
+ status VARCHAR(16) NOT NULL DEFAULT 'active',
+ last_used TIMESTAMPTZ,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
+);
+
+CREATE UNIQUE INDEX IF NOT EXISTS unique_idx_api_keys_user_id ON api_keys(user_id);
+CREATE INDEX IF NOT EXISTS idx_api_keys_key ON api_keys(key);
+
+CREATE TABLE IF NOT EXISTS records (
+ id UUID PRIMARY KEY DEFAULT uuid_generate_v1(),
+ user_id UUID NOT NULL,
+ model_id UUID NOT NULL,
+ task_id VARCHAR(255),
+ model_type VARCHAR(255) NOT NULL,
+ prompt TEXT,
+ completion TEXT,
+ is_accept BOOLEAN DEFAULT FALSE,
+ program_language VARCHAR(255),
+ work_mode VARCHAR(255),
+ code_lines BIGINT,
+ input_tokens BIGINT,
+ output_tokens BIGINT,
+ created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
+ updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
+);
+
+CREATE INDEX IF NOT EXISTS idx_records_user_id ON records (user_id);
+CREATE INDEX IF NOT EXISTS idx_records_model_id ON records (model_id);
+CREATE INDEX IF NOT EXISTS idx_records_task_id ON records (task_id);
+CREATE INDEX IF NOT EXISTS idx_records_created_at ON records (created_at);
+CREATE INDEX IF NOT EXISTS idx_records_updated_at ON records (updated_at);
+
+CREATE TABLE IF NOT EXISTS settings (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ enable_sso BOOLEAN DEFAULT FALSE,
+ force_two_factor_auth BOOLEAN DEFAULT FALSE,
+ disable_password_login BOOLEAN DEFAULT FALSE,
+ created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
+ updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
+);
diff --git a/backend/pkg/cvt/cvt.go b/backend/pkg/cvt/cvt.go
new file mode 100644
index 0000000..c5e8aa5
--- /dev/null
+++ b/backend/pkg/cvt/cvt.go
@@ -0,0 +1,256 @@
+package cvt
+
+import (
+ "slices"
+)
+
+// Iter 用来迭代类型T的列表, 然后返回类型为R的列表
+func Iter[T any, R any](ts []T, fn func(int, T) R) []R {
+ r := make([]R, len(ts))
+ for i, v := range ts {
+ r[i] = fn(i, v)
+ }
+ return r
+}
+
+// IterToMap 迭代类型T的列表, 然后转换成一个 map[K]V.
+// K: 可以是任何可比较的值
+// V: 是任务类型
+func IterToMap[T any, K comparable, V any](ts []T, fn func(int, T) (K, V)) map[K]V {
+ m := make(map[K]V)
+ for i, v := range ts {
+ k, v := fn(i, v)
+ m[k] = v
+ }
+ return m
+}
+
+// ForEach 简单的迭代
+func ForEach[T any](ts []T, fn func(int, T)) {
+ for i, t := range ts {
+ fn(i, t)
+ }
+}
+
+// Filter 过滤迭代
+func Filter[T any, R any](ts []T, fn func(int, T) (R, bool)) []R {
+ r := make([]R, 0)
+ for i, v := range ts {
+ if res, ok := fn(i, v); ok {
+ r = append(r, res)
+ }
+ }
+ return r
+}
+
+// Unique 去重
+func Unique[T comparable](ts []T) []T {
+ m := make(map[T]struct{})
+ news := make([]T, 0)
+ for _, v := range ts {
+ if _, ok := m[v]; ok {
+ continue
+ }
+
+ m[v] = struct{}{}
+ news = append(news, v)
+ }
+ return news
+}
+
+// UniqueFn 根据fn去重
+func UniqueFn[T any, K comparable](ts []T, fn func(T) K) []T {
+ m := make(map[K]struct{})
+ news := make([]T, 0)
+ for _, v := range ts {
+ k := fn(v)
+ if _, ok := m[k]; ok {
+ continue
+ }
+
+ m[k] = struct{}{}
+ news = append(news, v)
+ }
+ return news
+}
+
+// Union 并集
+func Union[T comparable](a, b []T) []T {
+ return Unique(append(a, b...))
+}
+
+// Intersection 交集
+func Intersection[T comparable](a, b []T) []T {
+ return Filter(a, func(i int, t T) (T, bool) {
+ return t, slices.Contains(b, t)
+ })
+}
+
+// Difference 差集
+func Difference[T comparable](a, b []T) []T {
+ return Filter(a, func(i int, t T) (T, bool) {
+ return t, !slices.Contains(b, t)
+ })
+}
+
+// GroupBy 分组
+func GroupBy[T any, K comparable, V any](collection []T, fn func(item T) (K, V)) map[K][]V {
+ result := map[K][]V{}
+
+ for _, item := range collection {
+ k, v := fn(item)
+
+ result[k] = append(result[k], v)
+ }
+
+ return result
+}
+
+// SumBy 求和
+func SumBy[K comparable, T any](ts []T, fn func(item T) K) map[K]int64 {
+ result := map[K]int64{}
+ for _, item := range ts {
+ k := fn(item)
+ result[k]++
+ }
+ return result
+}
+
+// MapToList map 转成 slice
+func MapToList[K comparable, V any, R any](m map[K]V, fn func(K, V) R) []R {
+ r := make([]R, 0)
+ for k, v := range m {
+ r = append(r, fn(k, v))
+ }
+ return r
+}
+
+// NilWithZero t不为nil则执行fn. 否则返回类型为R的空值
+func NilWithZero[T any, R any](t *T, fn func(*T) R) R {
+ if t != nil {
+ return fn(t)
+ }
+ var b R
+ return b
+}
+
+// ZeroWithDefault 给t一个默认值def
+func ZeroWithDefault[T comparable](t T, def T) T {
+ var zero T
+ if t == zero {
+ return def
+ }
+ return t
+}
+
+// NilWithDefault 给空指针t一个默认值def
+func NilWithDefault[T any](t, def *T) *T {
+ if t != nil {
+ return t
+ }
+ return def
+}
+
+// Contains 列表包含
+func Contains[T any](ts []T, fn func(T) bool) bool {
+ return slices.ContainsFunc(ts, fn)
+}
+
+// GetN 安全获取slice的索引值. 没有返回空值
+func GetN[T any](ts []T, i int) T {
+ if len(ts) > i {
+ return ts[i]
+ }
+ var t T
+ return t
+}
+
+// RangeByStep 步进ts
+func RangeByStep[T any](ts []T, step int, fn func([]T)) {
+ for len(ts) > 0 {
+ if len(ts) < step {
+ fn(ts)
+ ts = nil
+ } else {
+ fn(ts[:step])
+ ts = ts[step:]
+ }
+ }
+}
+
+// EqualIfNotZero 当b不为空时, 进行比较操作
+func EqualIfNotZero[T comparable](a, b T) bool {
+ var zero T
+ if b == zero {
+ return true
+ }
+
+ return a == b
+}
+
+// CanditionVar 条件变量
+func CanditionVar[T any](fn ...func() (T, bool)) T {
+ var t T
+ for _, f := range fn {
+ if v, ok := f(); ok {
+ return v
+ }
+ }
+ return t
+}
+
+type Identifier interface {
+ GetID() string
+}
+
+// TopN 根据ID获取出现次数最多的前n个
+func TopN[T Identifier](ts []T, n int) []T {
+ all := make(map[string]T)
+ counter := make(map[string]int)
+ for _, t := range ts {
+ counter[t.GetID()]++
+ all[t.GetID()] = t
+ }
+
+ res := make([]T, 0)
+ for i := 0; i < n; i++ {
+ maxID := ""
+ maxC := 0
+ for k, c := range counter {
+ if c > maxC {
+ maxC = c
+ maxID = k
+ }
+ }
+ if maxID == "" {
+ break
+ }
+ res = append(res, all[maxID])
+ delete(counter, maxID)
+ }
+ return res
+}
+
+// Assert 段言a的类型是否为T, 如何不是返回类型为T的空值
+func Assert[T any](a any) T {
+ if t, ok := a.(T); ok {
+ return t
+ }
+ var t T
+ return t
+}
+
+type Fromer[A, B any] interface {
+ From(a A) B
+}
+
+// From 从A对象转换为B对象
+func From[A, B any](a A, f Fromer[A, B]) B {
+ return f.From(a)
+}
+
+// Zero 返回类型为T的空值
+func Zero[T any]() *T {
+ var zero T
+ return &zero
+}
diff --git a/backend/pkg/entx/entx.go b/backend/pkg/entx/entx.go
new file mode 100644
index 0000000..c360750
--- /dev/null
+++ b/backend/pkg/entx/entx.go
@@ -0,0 +1,17 @@
+package entx
+
+import (
+ "entgo.io/ent/entc"
+ "entgo.io/ent/entc/gen"
+)
+
+type Page struct {
+ entc.DefaultExtension
+}
+
+func (*Page) Templates() []*gen.Template {
+ return []*gen.Template{
+ gen.MustParse(gen.NewTemplate("page").
+ ParseFiles("../templates/page.tmpl")),
+ }
+}
diff --git a/backend/pkg/entx/softdelete.go b/backend/pkg/entx/softdelete.go
new file mode 100644
index 0000000..590fd2e
--- /dev/null
+++ b/backend/pkg/entx/softdelete.go
@@ -0,0 +1,87 @@
+package entx
+
+import (
+ "context"
+ "fmt"
+ "time"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect/sql"
+ "entgo.io/ent/schema/field"
+ "entgo.io/ent/schema/mixin"
+
+ gen "github.com/chaitin/MonkeyCode/backend/db"
+ "github.com/chaitin/MonkeyCode/backend/db/hook"
+ "github.com/chaitin/MonkeyCode/backend/db/intercept"
+)
+
+// SoftDeleteMixin implements the soft delete pattern for schemas.
+type SoftDeleteMixin struct {
+ mixin.Schema
+}
+
+// Fields of the SoftDeleteMixin.
+func (SoftDeleteMixin) Fields() []ent.Field {
+ return []ent.Field{
+ field.Time("deleted_at").
+ Optional(),
+ }
+}
+
+type softDeleteKey struct{}
+
+// SkipSoftDelete returns a new context that skips the soft-delete interceptor/mutators.
+func SkipSoftDelete(parent context.Context) context.Context {
+ return context.WithValue(parent, softDeleteKey{}, true)
+}
+
+// Interceptors of the SoftDeleteMixin.
+func (d SoftDeleteMixin) Interceptors() []ent.Interceptor {
+ return []ent.Interceptor{
+ intercept.TraverseFunc(func(ctx context.Context, q intercept.Query) error {
+ // Skip soft-delete, means include soft-deleted entities.
+ if skip, _ := ctx.Value(softDeleteKey{}).(bool); skip {
+ return nil
+ }
+ d.P(q)
+ return nil
+ }),
+ }
+}
+
+// Hooks of the SoftDeleteMixin.
+func (d SoftDeleteMixin) Hooks() []ent.Hook {
+ return []ent.Hook{
+ hook.On(
+ func(next ent.Mutator) ent.Mutator {
+ return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) {
+ // Skip soft-delete, means delete the entity permanently.
+ if skip, _ := ctx.Value(softDeleteKey{}).(bool); skip {
+ return next.Mutate(ctx, m)
+ }
+ mx, ok := m.(interface {
+ SetOp(ent.Op)
+ Client() *gen.Client
+ SetDeletedAt(time.Time)
+ WhereP(...func(*sql.Selector))
+ })
+ if !ok {
+ return nil, fmt.Errorf("unexpected mutation type %T", m)
+ }
+ d.P(mx)
+ mx.SetOp(ent.OpUpdate)
+ mx.SetDeletedAt(time.Now())
+ return mx.Client().Mutate(ctx, m)
+ })
+ },
+ ent.OpDeleteOne|ent.OpDelete,
+ ),
+ }
+}
+
+// P adds a storage-level predicate to the queries and mutations.
+func (d SoftDeleteMixin) P(w interface{ WhereP(...func(*sql.Selector)) }) {
+ w.WhereP(
+ sql.FieldIsNull(d.Fields()[0].Descriptor().Name),
+ )
+}
diff --git a/backend/pkg/entx/tx.go b/backend/pkg/entx/tx.go
new file mode 100644
index 0000000..eabe79a
--- /dev/null
+++ b/backend/pkg/entx/tx.go
@@ -0,0 +1,31 @@
+package entx
+
+import (
+ "context"
+ "fmt"
+
+ "github.com/chaitin/MonkeyCode/backend/db"
+)
+
+func WithTx(ctx context.Context, client *db.Client, fn func(tx *db.Tx) error) error {
+ tx, err := client.Tx(ctx)
+ if err != nil {
+ return err
+ }
+ defer func() {
+ if v := recover(); v != nil {
+ tx.Rollback()
+ panic(v)
+ }
+ }()
+ if err := fn(tx); err != nil {
+ if rerr := tx.Rollback(); rerr != nil {
+ err = fmt.Errorf("%w: rolling back transaction: %v", err, rerr)
+ }
+ return err
+ }
+ if err := tx.Commit(); err != nil {
+ return fmt.Errorf("committing transaction: %w", err)
+ }
+ return nil
+}
diff --git a/backend/pkg/logger/context.go b/backend/pkg/logger/context.go
new file mode 100644
index 0000000..871047a
--- /dev/null
+++ b/backend/pkg/logger/context.go
@@ -0,0 +1,43 @@
+package logger
+
+import (
+ "context"
+ "log/slog"
+)
+
+type contextKey string
+
+const (
+ RequestIDKey contextKey = "request_id"
+ UserIDKey contextKey = "user_id"
+)
+
+type ContextLogger struct {
+ slog.Handler
+}
+
+func (c *ContextLogger) Enabled(ctx context.Context, level slog.Level) bool {
+ return c.Handler.Enabled(ctx, level)
+}
+
+func (c *ContextLogger) WithAttrs(attrs []slog.Attr) slog.Handler {
+ return &ContextLogger{Handler: c.Handler.WithAttrs(attrs)}
+}
+
+func (c *ContextLogger) WithGroup(name string) slog.Handler {
+ return &ContextLogger{Handler: c.Handler.WithGroup(name)}
+}
+
+func (c *ContextLogger) Handle(ctx context.Context, r slog.Record) error {
+ newRecord := r.Clone()
+
+ if i, ok := ctx.Value(RequestIDKey).(string); ok {
+ newRecord.AddAttrs(slog.String("request_id", i))
+ }
+
+ if i, ok := ctx.Value(UserIDKey).(string); ok {
+ newRecord.AddAttrs(slog.String("user_id", i))
+ }
+
+ return c.Handler.Handle(ctx, newRecord)
+}
diff --git a/backend/pkg/logger/logger.go b/backend/pkg/logger/logger.go
new file mode 100644
index 0000000..bf4d4d7
--- /dev/null
+++ b/backend/pkg/logger/logger.go
@@ -0,0 +1,51 @@
+package logger
+
+import (
+ "log/slog"
+ "os"
+)
+
+type Config struct {
+ Level string
+}
+
+var level = new(slog.LevelVar)
+
+func NewLogger(cfg *Config) *slog.Logger {
+ switch cfg.Level {
+ case "debug":
+ level.Set(slog.LevelDebug)
+ case "info":
+ level.Set(slog.LevelInfo)
+ case "warn":
+ level.Set(slog.LevelWarn)
+ case "error":
+ level.Set(slog.LevelError)
+ default:
+ level.Set(slog.LevelWarn)
+ }
+ base := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
+ Level: level,
+ })
+ handler := &ContextLogger{Handler: base}
+ return slog.New(handler)
+}
+
+func SetLevel(lv string) {
+ switch lv {
+ case "debug":
+ level.Set(slog.LevelDebug)
+ case "info":
+ level.Set(slog.LevelInfo)
+ case "warn":
+ level.Set(slog.LevelWarn)
+ case "error":
+ level.Set(slog.LevelError)
+ default:
+ level.Set(slog.LevelWarn)
+ }
+}
+
+func Level() string {
+ return level.String()
+}
diff --git a/backend/pkg/promptparser/promptparse.go b/backend/pkg/promptparser/promptparse.go
new file mode 100644
index 0000000..fcc10b9
--- /dev/null
+++ b/backend/pkg/promptparser/promptparse.go
@@ -0,0 +1,65 @@
+package promptparser
+
+import (
+ "fmt"
+ "regexp"
+)
+
+type PromptParser interface {
+ Parse(prompt string) (*Info, error)
+}
+
+type Info struct {
+ Prompt string
+ ProgramLanguage string
+ WorkMode string
+}
+
+type Kind int
+
+const (
+ KindNormal Kind = iota + 1
+ KindTask
+)
+
+func New(kind Kind) PromptParser {
+ switch kind {
+ case KindNormal:
+ return &NormalParser{}
+ case KindTask:
+ return &TaskParse{}
+ default:
+ return nil
+ }
+}
+
+type NormalParser struct {
+}
+
+// Parse implements PromptParser.
+func (n *NormalParser) Parse(prompt string) (*Info, error) {
+ // re := regexp.MustCompile(`You are a code completion assistant for (\w+). Complete the code, don't explain it. Only return code that should come next.(.*)`)
+ re := regexp.MustCompile(`You are a code completion assistant for (\w+). Complete the code naturally, providing complete and meaningful code blocks when appropriate. Return only the code that should come next, without explanations.(.*)`)
+ match := re.FindStringSubmatch(prompt)
+ if len(match) < 3 {
+ return nil, fmt.Errorf("invalid prompt")
+ }
+ return &Info{
+ ProgramLanguage: match[1],
+ Prompt: match[2],
+ }, nil
+}
+
+type TaskParse struct {
+}
+
+func (m *TaskParse) Parse(prompt string) (*Info, error) {
+ re := regexp.MustCompile(`(.*)(.*)(.*)`)
+ match := re.FindStringSubmatch(prompt)
+ if len(match) < 5 {
+ return nil, fmt.Errorf("invalid prompt")
+ }
+ return &Info{
+ Prompt: match[1],
+ }, nil
+}
diff --git a/backend/pkg/provider.go b/backend/pkg/provider.go
new file mode 100644
index 0000000..0da99a1
--- /dev/null
+++ b/backend/pkg/provider.go
@@ -0,0 +1,36 @@
+package pkg
+
+import (
+ "github.com/google/wire"
+ "github.com/labstack/echo/v4/middleware"
+ "golang.org/x/text/language"
+
+ "github.com/GoYoko/web"
+ "github.com/GoYoko/web/locale"
+
+ "github.com/chaitin/MonkeyCode/backend/config"
+ "github.com/chaitin/MonkeyCode/backend/errcode"
+ mid "github.com/chaitin/MonkeyCode/backend/internal/middleware"
+ "github.com/chaitin/MonkeyCode/backend/pkg/logger"
+ "github.com/chaitin/MonkeyCode/backend/pkg/session"
+ "github.com/chaitin/MonkeyCode/backend/pkg/store"
+)
+
+var Provider = wire.NewSet(
+ NewWeb,
+ logger.NewLogger,
+ store.NewEntDB,
+ store.NewRedisCli,
+ session.NewSession,
+)
+
+func NewWeb(cfg *config.Config) *web.Web {
+ w := web.New()
+ l := locale.NewLocalizerWithFile(language.Chinese, errcode.LocalFS, []string{"locale.zh.toml"})
+ w.SetLocale(l)
+ w.Use(mid.RequestID())
+ if cfg.Debug {
+ w.Use(middleware.Logger())
+ }
+ return w
+}
diff --git a/backend/pkg/request/ops.go b/backend/pkg/request/ops.go
new file mode 100644
index 0000000..9a5930e
--- /dev/null
+++ b/backend/pkg/request/ops.go
@@ -0,0 +1,43 @@
+package request
+
+import "net/http"
+
+type ReqOpt func(c *Client)
+
+type Opt func(ctx *Ctx)
+
+func WithDebug() ReqOpt {
+ return func(c *Client) {
+ c.debug = true
+ }
+}
+
+func WithTransport(tr *http.Transport) ReqOpt {
+ return func(c *Client) {
+ c.tr = tr
+ }
+}
+
+func WithHeader(h Header) Opt {
+ return func(ctx *Ctx) {
+ ctx.header = h
+ }
+}
+
+func WithQuery(q Query) Opt {
+ return func(ctx *Ctx) {
+ ctx.query = q
+ }
+}
+
+func WithBody(body any) Opt {
+ return func(ctx *Ctx) {
+ ctx.body = body
+ }
+}
+
+func WithContentType(contentType string) Opt {
+ return func(ctx *Ctx) {
+ ctx.contentType = contentType
+ }
+}
diff --git a/backend/pkg/request/request.go b/backend/pkg/request/request.go
new file mode 100644
index 0000000..b3711a7
--- /dev/null
+++ b/backend/pkg/request/request.go
@@ -0,0 +1,187 @@
+package request
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "io"
+ "log"
+ "mime/multipart"
+ "net/http"
+ "net/url"
+ "strings"
+ "time"
+
+ "github.com/google/uuid"
+)
+
+type Client struct {
+ scheme string
+ host string
+ client *http.Client
+ tr *http.Transport
+ debug bool
+}
+
+func NewClient(scheme string, host string, timeout time.Duration, opts ...ReqOpt) *Client {
+ req := &Client{
+ scheme: scheme,
+ host: host,
+ client: &http.Client{
+ Timeout: timeout,
+ },
+ debug: false,
+ }
+
+ for _, opt := range opts {
+ opt(req)
+ }
+
+ if req.tr != nil {
+ req.client.Transport = req.tr
+ }
+
+ return req
+}
+
+func (c *Client) SetDebug(debug bool) {
+ c.debug = debug
+}
+
+func (c *Client) SetTransport(tr *http.Transport) {
+ c.client.Transport = tr
+}
+
+func sendRequest[T any](c *Client, method, path string, opts ...Opt) (*T, error) {
+ u := url.URL{
+ Scheme: c.scheme,
+ Host: c.host,
+ Path: path,
+ }
+ ctx := &Ctx{}
+ rid := uuid.NewString()
+
+ for _, opt := range opts {
+ opt(ctx)
+ }
+
+ if len(ctx.query) > 0 {
+ values := u.Query()
+ for k, v := range ctx.query {
+ values.Add(k, v)
+ }
+ u.RawQuery = values.Encode()
+ }
+
+ if c.debug {
+ log.Printf("[REQ:%s] url: %s", rid, u.String())
+ }
+
+ var body io.Reader
+ var writer *multipart.Writer
+ if ctx.body != nil {
+ bs, err := json.Marshal(ctx.body)
+ if err != nil {
+ return nil, err
+ }
+ switch ctx.contentType {
+ case "multipart/form-data":
+ m := make(map[string]string)
+ if err := json.Unmarshal(bs, &m); err != nil {
+ return nil, err
+ }
+ buf := &bytes.Buffer{}
+ writer = multipart.NewWriter(buf)
+ for k, v := range m {
+ if err := writer.WriteField(k, v); err != nil {
+ return nil, err
+ }
+ }
+ writer.Close()
+ body = buf
+ case "application/x-www-form-urlencoded":
+ m := make(map[string]string)
+ if err := json.Unmarshal(bs, &m); err != nil {
+ return nil, err
+ }
+ data := url.Values{}
+ for k, v := range m {
+ data.Add(k, v)
+ }
+ body = strings.NewReader(data.Encode())
+ default:
+ body = bytes.NewBuffer(bs)
+ }
+
+ if c.debug {
+ buf := &bytes.Buffer{}
+ json.Indent(buf, bs, "", " ")
+ log.Printf("[REQ:%s] body: %s", rid, buf.String())
+ }
+ }
+ req, err := http.NewRequest(method, u.String(), body)
+ if err != nil {
+ return nil, err
+ }
+ for k, v := range ctx.header {
+ req.Header.Add(k, v)
+ }
+ switch ctx.contentType {
+ case "multipart/form-data":
+ req.Header.Set("Content-Type", writer.FormDataContentType())
+ case "application/x-www-form-urlencoded":
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ default:
+ req.Header.Set("Content-Type", "application/json")
+ }
+ if c.debug {
+ log.Printf("[REQ:%s] headers: %+v", rid, req.Header)
+ }
+
+ resp, err := c.client.Do(req)
+ if err != nil {
+ return nil, err
+ }
+ defer resp.Body.Close()
+
+ b, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return nil, err
+ }
+ if c.debug {
+ buf := &bytes.Buffer{}
+ if err := json.Indent(buf, b, "", " "); err != nil {
+ log.Printf("[REQ:%s] resp: %s", rid, string(b))
+ } else {
+ log.Printf("[REQ:%s] resp: %s", rid, buf.String())
+ }
+ }
+
+ if resp.StatusCode != http.StatusOK {
+ return nil, fmt.Errorf("status code: %d", resp.StatusCode)
+ }
+
+ var rr T
+ if err := json.Unmarshal(b, &rr); err != nil {
+ return nil, err
+ }
+ return &rr, nil
+}
+
+func Get[T any](c *Client, path string, opts ...Opt) (*T, error) {
+ return sendRequest[T](c, http.MethodGet, path, opts...)
+}
+
+func Post[T any](c *Client, path string, body any, opts ...Opt) (*T, error) {
+ opts = append(opts, WithBody(body))
+ return sendRequest[T](c, http.MethodPost, path, opts...)
+}
+
+func Put[T any](c *Client, path string, body any, opts ...Opt) (*T, error) {
+ opts = append(opts, WithBody(body))
+ return sendRequest[T](c, http.MethodPut, path, opts...)
+}
+
+func Delete[T any](c *Client, path string, opts ...Opt) (*T, error) {
+ return sendRequest[T](c, http.MethodDelete, path, opts...)
+}
diff --git a/backend/pkg/request/types.go b/backend/pkg/request/types.go
new file mode 100644
index 0000000..db875d7
--- /dev/null
+++ b/backend/pkg/request/types.go
@@ -0,0 +1,17 @@
+package request
+
+type Ctx struct {
+ body any
+ header Header
+ query Query
+ contentType string
+}
+
+type Response[T any] struct {
+ Code int `json:"code"`
+ Data T `json:"data"`
+ Message string `json:"message"`
+}
+
+type Query map[string]string
+type Header map[string]string
diff --git a/backend/pkg/service/pprof.go b/backend/pkg/service/pprof.go
new file mode 100644
index 0000000..65a3d5d
--- /dev/null
+++ b/backend/pkg/service/pprof.go
@@ -0,0 +1,21 @@
+package service
+
+import (
+ "net/http"
+ _ "net/http/pprof"
+)
+
+type pprofSvc struct {
+}
+
+func (p *pprofSvc) Name() string {
+ return "Pprof Server"
+}
+
+func (p *pprofSvc) Start() error {
+ return http.ListenAndServe(":6060", nil)
+}
+
+func (p *pprofSvc) Stop() error {
+ return nil
+}
diff --git a/backend/pkg/service/service.go b/backend/pkg/service/service.go
new file mode 100644
index 0000000..a044e86
--- /dev/null
+++ b/backend/pkg/service/service.go
@@ -0,0 +1,109 @@
+package service
+
+import (
+ "context"
+ "fmt"
+ "log/slog"
+ "os"
+ "os/signal"
+ "sync"
+ "syscall"
+ "time"
+)
+
+type Option func(sv *Service)
+
+func WithPprof() Option {
+ return func(sv *Service) {
+ sv.Add(&pprofSvc{})
+ }
+}
+
+type Servicer interface {
+ Name() string
+ // Start never returns
+ Start() error
+ Stop() error
+}
+
+type Service struct {
+ svs []Servicer
+ logger *slog.Logger
+ stopDone chan struct{}
+}
+
+func NewService(opts ...Option) *Service {
+ sv := &Service{
+ svs: make([]Servicer, 0),
+ logger: slog.Default(),
+ stopDone: make(chan struct{}),
+ }
+ for _, opt := range opts {
+ opt(sv)
+ }
+ return sv
+}
+
+func (s *Service) Run() error {
+ ech := s.start()
+ sig := make(chan os.Signal, 1)
+ signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
+
+ select {
+ case <-sig:
+ s.logger.Info("Received signal to stop")
+ case err := <-ech:
+ s.logger.Error("Received error from service start", "error", err)
+ }
+
+ timeout, cancel2 := context.WithTimeout(context.Background(), 15*time.Second)
+ defer cancel2()
+
+ go func() {
+ if err := s.stop(); err != nil {
+ s.logger.Error("Service stop failed", "error", err)
+ }
+ }()
+
+ select {
+ case <-timeout.Done():
+ s.logger.Info("Service stop timeout")
+ case <-s.stopDone:
+ s.logger.Info("Service stop done")
+ }
+ return nil
+}
+
+func (s *Service) Add(sv Servicer) {
+ s.svs = append(s.svs, sv)
+}
+
+func (s *Service) start() chan error {
+ ech := make(chan error, len(s.svs))
+ for _, sv := range s.svs {
+ go func(sv Servicer) {
+ s.logger.Info("Starting service", "name", sv.Name())
+ err := sv.Start()
+ ech <- fmt.Errorf("[%s] Service shutdown: %w", sv.Name(), err)
+ }(sv)
+ }
+ return ech
+}
+
+func (s *Service) stop() error {
+ wg := sync.WaitGroup{}
+ for i := len(s.svs) - 1; i >= 0; i-- {
+ wg.Add(1)
+ go func(sv Servicer) {
+ defer wg.Done()
+ s.logger.Info("Stopping service", "name", sv.Name())
+ if err := sv.Stop(); err != nil {
+ s.logger.Error("Service stop failed", "name", sv.Name(), "error", err)
+ }
+ }(s.svs[i])
+ }
+ wg.Wait()
+
+ close(s.stopDone)
+ return nil
+}
diff --git a/backend/pkg/session/session.go b/backend/pkg/session/session.go
new file mode 100644
index 0000000..32fe4fa
--- /dev/null
+++ b/backend/pkg/session/session.go
@@ -0,0 +1,89 @@
+package session
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net"
+ "net/http"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/labstack/echo/v4"
+ "github.com/redis/go-redis/v9"
+
+ "github.com/chaitin/MonkeyCode/backend/config"
+)
+
+type Session struct {
+ cfg *config.Config
+ rdb *redis.Client
+}
+
+func NewSession(cfg *config.Config) *Session {
+ addr := net.JoinHostPort(cfg.Redis.Host, fmt.Sprint(cfg.Redis.Port))
+ rdb := redis.NewClient(&redis.Options{
+ Addr: addr,
+ Password: cfg.Redis.Pass,
+ DB: 3,
+ })
+
+ return &Session{
+ cfg: cfg,
+ rdb: rdb,
+ }
+}
+
+func (s *Session) Save(c echo.Context, name, domain string, data any) (string, error) {
+ expire := time.Duration(s.cfg.Session.ExpireDay) * 24 * time.Hour
+ id := uuid.New().String()
+ b, err := json.Marshal(data)
+ if err != nil {
+ return "", err
+ }
+
+ if ok, _ := s.rdb.SetNX(context.Background(), id, string(b), expire).Result(); !ok {
+ return "", fmt.Errorf("failed to save session")
+ }
+
+ c.SetCookie(&http.Cookie{
+ Name: name,
+ Value: id,
+ Path: "/",
+ Domain: domain,
+ MaxAge: int(s.cfg.Session.ExpireDay) * 24 * 60 * 60,
+ Secure: false,
+ HttpOnly: true,
+ })
+
+ return id, nil
+}
+
+func (s *Session) Del(c echo.Context, name string) error {
+ ck, err := c.Cookie(name)
+ if err != nil {
+ return err
+ }
+ if err := s.rdb.Del(c.Request().Context(), ck.Value).Err(); err != nil {
+ return err
+ }
+ ck.MaxAge = -1
+ c.SetCookie(ck)
+ return nil
+}
+
+func Get[T any](s *Session, c echo.Context, name string) (T, error) {
+ var t T
+ ck, err := c.Cookie(name)
+ if err != nil {
+ return t, err
+ }
+ ss, err := s.rdb.Get(c.Request().Context(), ck.Value).Result()
+ if err != nil {
+ return t, err
+ }
+ if err := json.Unmarshal([]byte(ss), &t); err != nil {
+ return t, err
+ }
+ return t, err
+}
diff --git a/backend/pkg/sse/sse.go b/backend/pkg/sse/sse.go
new file mode 100644
index 0000000..4dbb475
--- /dev/null
+++ b/backend/pkg/sse/sse.go
@@ -0,0 +1,85 @@
+package sse
+
+import (
+ "bytes"
+ "fmt"
+ "io"
+
+ "github.com/google/uuid"
+)
+
+// Event represents Server-Sent Event.
+// SSE explanation: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#event_stream_format
+type Event struct {
+ // ID is used to set the EventSource object's last event ID value.
+ ID []byte
+ // Data field is for the message. When the EventSource receives multiple consecutive lines
+ // that begin with data:, it concatenates them, inserting a newline character between each one.
+ // Trailing newlines are removed.
+ Data []byte
+ // Event is a string identifying the type of event described. If this is specified, an event
+ // will be dispatched on the browser to the listener for the specified event name; the website
+ // source code should use addEventListener() to listen for named events. The onmessage handler
+ // is called if no event name is specified for a message.
+ Event []byte
+ // Retry is the reconnection time. If the connection to the server is lost, the browser will
+ // wait for the specified time before attempting to reconnect. This must be an integer, specifying
+ // the reconnection time in milliseconds. If a non-integer value is specified, the field is ignored.
+ Retry []byte
+ // Comment line can be used to prevent connections from timing out; a server can send a comment
+ // periodically to keep the connection alive.
+ Comment []byte
+}
+
+// MarshalTo marshals Event to given Writer
+func (ev *Event) MarshalTo(w io.Writer) error {
+ // Marshalling part is taken from: https://github.com/r3labs/sse/blob/c6d5381ee3ca63828b321c16baa008fd6c0b4564/http.go#L16
+ if len(ev.Data) == 0 && len(ev.Comment) == 0 {
+ return nil
+ }
+
+ if len(ev.Data) > 0 {
+ if _, err := fmt.Fprintf(w, "id: %s\n", ev.ID); err != nil {
+ return err
+ }
+
+ sd := bytes.Split(ev.Data, []byte("\n"))
+ for i := range sd {
+ if _, err := fmt.Fprintf(w, "data: %s\n", sd[i]); err != nil {
+ return err
+ }
+ }
+
+ if len(ev.Event) > 0 {
+ if _, err := fmt.Fprintf(w, "event: %s\n", ev.Event); err != nil {
+ return err
+ }
+ }
+
+ if len(ev.Retry) > 0 {
+ if _, err := fmt.Fprintf(w, "retry: %s\n", ev.Retry); err != nil {
+ return err
+ }
+ }
+ }
+
+ if len(ev.Comment) > 0 {
+ if _, err := fmt.Fprintf(w, ": %s\n", ev.Comment); err != nil {
+ return err
+ }
+ }
+
+ if _, err := fmt.Fprint(w, "\n"); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func WriteEvent(w io.Writer, data []byte) error {
+ ev := &Event{
+ ID: []byte(uuid.New().String()),
+ Data: data,
+ }
+ return ev.MarshalTo(w)
+}
diff --git a/backend/pkg/store/driver.go b/backend/pkg/store/driver.go
new file mode 100644
index 0000000..cacd41f
--- /dev/null
+++ b/backend/pkg/store/driver.go
@@ -0,0 +1,79 @@
+package store
+
+import (
+ "context"
+ "database/sql"
+ "log/slog"
+ "strings"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect"
+ esql "entgo.io/ent/dialect/sql"
+)
+
+type multiDriver struct {
+ r, w dialect.Driver
+ logger *slog.Logger
+}
+
+func NewMultiDriver(r, w dialect.Driver, logger *slog.Logger) dialect.Driver {
+ return &multiDriver{r: r, w: w, logger: logger}
+}
+
+var _ dialect.Driver = (*multiDriver)(nil)
+
+func (d *multiDriver) Query(ctx context.Context, query string, args, v any) error {
+ e := d.r
+ if ent.QueryFromContext(ctx) == nil {
+ e = d.w
+ }
+ if err := e.Query(ctx, query, args, v); err != nil {
+ d.logger.Error("query error", "query", strings.ReplaceAll(query, `"`, ""), "args", args)
+ return err
+ }
+ return nil
+}
+
+func (d *multiDriver) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) {
+ v := &esql.Rows{}
+ err := d.r.Query(ctx, query, args, v)
+ if err != nil {
+ d.logger.Error("query error", "query", strings.ReplaceAll(query, `"`, ""), "args", args)
+ return nil, err
+ }
+ return v.ColumnScanner.(*sql.Rows), nil
+}
+
+func (d *multiDriver) Exec(ctx context.Context, query string, args, v any) error {
+ if err := d.w.Exec(ctx, query, args, v); err != nil {
+ d.logger.Error("exec error", "query", strings.ReplaceAll(query, `"`, ""), "args", args)
+ return err
+ }
+ return nil
+}
+
+func (d *multiDriver) Tx(ctx context.Context) (dialect.Tx, error) {
+ return d.w.Tx(ctx)
+}
+
+func (d *multiDriver) BeginTx(ctx context.Context, opts *sql.TxOptions) (dialect.Tx, error) {
+ return d.w.(interface {
+ BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error)
+ }).BeginTx(ctx, opts)
+}
+
+func (d *multiDriver) Close() error {
+ rerr := d.r.Close()
+ werr := d.w.Close()
+ if rerr != nil {
+ return rerr
+ }
+ if werr != nil {
+ return werr
+ }
+ return nil
+}
+
+func (d *multiDriver) Dialect() string {
+ return d.r.Dialect()
+}
diff --git a/backend/pkg/store/entdb.go b/backend/pkg/store/entdb.go
new file mode 100644
index 0000000..cead629
--- /dev/null
+++ b/backend/pkg/store/entdb.go
@@ -0,0 +1,64 @@
+package store
+
+import (
+ dql "database/sql"
+ "log/slog"
+ "time"
+
+ "entgo.io/ent/dialect"
+ "entgo.io/ent/dialect/sql"
+ "github.com/golang-migrate/migrate/v4"
+ "github.com/golang-migrate/migrate/v4/database/postgres"
+ _ "github.com/golang-migrate/migrate/v4/source/file"
+ _ "github.com/lib/pq"
+
+ "github.com/chaitin/MonkeyCode/backend/config"
+ "github.com/chaitin/MonkeyCode/backend/db"
+ _ "github.com/chaitin/MonkeyCode/backend/db/runtime"
+)
+
+func NewEntDB(cfg *config.Config, logger *slog.Logger) (*db.Client, error) {
+ w, err := sql.Open(dialect.Postgres, cfg.Database.Master)
+ if err != nil {
+ return nil, err
+ }
+ w.DB().SetMaxOpenConns(cfg.Database.MaxOpenConns)
+ w.DB().SetMaxIdleConns(cfg.Database.MaxIdleConns)
+ w.DB().SetConnMaxLifetime(time.Duration(cfg.Database.ConnMaxLifetime) * time.Minute)
+ r, err := sql.Open(dialect.Postgres, cfg.Database.Slave)
+ if err != nil {
+ return nil, err
+ }
+
+ r.DB().SetMaxOpenConns(cfg.Database.MaxOpenConns)
+ r.DB().SetMaxIdleConns(cfg.Database.MaxIdleConns)
+ r.DB().SetConnMaxLifetime(time.Duration(cfg.Database.ConnMaxLifetime) * time.Minute)
+ c := db.NewClient(db.Driver(NewMultiDriver(r, w, logger)))
+ if cfg.Debug {
+ c = c.Debug()
+ }
+
+ return c, nil
+}
+
+func MigrateSQL(cfg *config.Config, logger *slog.Logger) error {
+ db, err := dql.Open("postgres", cfg.Database.Master)
+ if err != nil {
+ return err
+ }
+ driver, err := postgres.WithInstance(db, &postgres.Config{})
+ if err != nil {
+ return err
+ }
+ m, err := migrate.NewWithDatabaseInstance(
+ "file://migration",
+ "postgres", driver)
+ if err != nil {
+ return err
+ }
+ if err := m.Up(); err != nil {
+ logger.With("component", "db").With("err", err).Warn("migrate db failed")
+ }
+
+ return nil
+}
diff --git a/backend/pkg/store/redis.go b/backend/pkg/store/redis.go
new file mode 100644
index 0000000..7e3ba01
--- /dev/null
+++ b/backend/pkg/store/redis.go
@@ -0,0 +1,56 @@
+package store
+
+import (
+ "context"
+ "net"
+
+ "github.com/redis/go-redis/v9"
+
+ "github.com/chaitin/MonkeyCode/backend/config"
+)
+
+func NewRedisCli(cfg *config.Config) *redis.Client {
+ addr := net.JoinHostPort(cfg.Redis.Host, cfg.Redis.Port)
+ rdb := redis.NewClient(&redis.Options{
+ Addr: addr,
+ Password: cfg.Redis.Pass,
+ DB: cfg.Redis.DB,
+ MaxIdleConns: 3,
+ })
+ return rdb
+}
+
+type RedisResult struct {
+ Key string
+ Value int64
+}
+
+func ScanRedis(ctx context.Context, rdb *redis.Client, pattern string, limit int, fn func(rs []*RedisResult) error) error {
+ iter := rdb.Scan(ctx, 0, pattern, int64(limit)).Iterator()
+
+ rs := make([]*RedisResult, 0)
+ for iter.Next(ctx) {
+ value, err := rdb.Get(ctx, iter.Val()).Int64()
+ if err != nil {
+ return err
+ }
+ rs = append(rs, &RedisResult{
+ Key: iter.Val(),
+ Value: value,
+ })
+
+ if len(rs) >= limit {
+ if err := fn(rs); err != nil {
+ return err
+ }
+ rs = make([]*RedisResult, 0)
+ }
+ }
+
+ if len(rs) > 0 {
+ if err := fn(rs); err != nil {
+ return err
+ }
+ }
+ return nil
+}
diff --git a/backend/pkg/vsix/vsix.go b/backend/pkg/vsix/vsix.go
new file mode 100644
index 0000000..d6bb6de
--- /dev/null
+++ b/backend/pkg/vsix/vsix.go
@@ -0,0 +1,63 @@
+package vsix
+
+import (
+ "archive/zip"
+ "html/template"
+ "io"
+)
+
+func ChangeVsixEndpoint(vsixFile, target, endpoint string, w io.Writer) error {
+ reader, err := zip.OpenReader(vsixFile)
+ if err != nil {
+ return err
+ }
+ defer reader.Close()
+
+ newWriter := zip.NewWriter(w)
+ defer newWriter.Close()
+
+ for _, file := range reader.File {
+ rc, err := file.Open()
+ if err != nil {
+ return err
+ }
+ defer rc.Close()
+
+ if file.Name == target {
+ writer, err := newWriter.Create(file.Name)
+ if err != nil {
+ return err
+ }
+ content, err := io.ReadAll(rc)
+ if err != nil {
+ return err
+ }
+ tmpl, err := template.New("package.json").Parse(string(content))
+ if err != nil {
+ return err
+ }
+ if err := tmpl.Execute(writer, map[string]any{
+ "defaultEndpoint": endpoint,
+ }); err != nil {
+ return err
+ }
+ } else {
+ writer, err := newWriter.Create(file.Name)
+ if err != nil {
+ return err
+ }
+
+ _, err = io.Copy(writer, rc)
+ if err != nil {
+ return err
+ }
+ }
+ }
+
+ err = newWriter.Close()
+ if err != nil {
+ return err
+ }
+
+ return nil
+}
diff --git a/backend/templates/page.tmpl b/backend/templates/page.tmpl
new file mode 100644
index 0000000..5aa61ed
--- /dev/null
+++ b/backend/templates/page.tmpl
@@ -0,0 +1,32 @@
+{{ define "page" }}
+
+{{/* Add the base header for the generated file */}}
+{{ $pkg := base $.Config.Package }}
+{{ template "header" $ }}
+
+// PageInfo 分页信息
+type PageInfo struct {
+ NextToken string `json:"next_token,omitempty"`
+ HasNextPage bool `json:"has_next_page"`
+ TotalCount int64 `json:"total_count"`
+}
+
+{{/* Loop over all nodes and add the Greet method */}}
+{{ range $n := $.Nodes }}
+ {{ $receiver := $n.Receiver }}
+ func ({{ $receiver }} *{{ $n.QueryName }}) Page(ctx context.Context, page, size int) ([]*{{ $n.Name }}, *PageInfo, error) {
+ cnt, err := {{ $receiver }}.Count(ctx)
+ if err != nil {
+ return nil, nil, err
+ }
+ offset := size * (page - 1)
+ rs, err := {{ $receiver }}.Offset(offset).Limit(size).All(ctx)
+ if err != nil {
+ return nil, nil, err
+ }
+ has := (page * size) < cnt
+ return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil
+ }
+{{ end }}
+
+{{ end }}
\ No newline at end of file