diff --git a/.github/workflows/backend-ci-cd.yml b/.github/workflows/backend-ci-cd.yml index 0f59278..b7faa6f 100644 --- a/.github/workflows/backend-ci-cd.yml +++ b/.github/workflows/backend-ci-cd.yml @@ -45,6 +45,10 @@ jobs: - name: Download dependencies run: go mod download + - name: Generate Swagger.json + run: | + touch docs/swagger.json + - name: Run tests run: go test -v ./... diff --git a/.gitignore b/.gitignore index 7d2f331..ab8e379 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ -backend/assets \ No newline at end of file +backend/assets +backend/docs/swagger.json \ No newline at end of file diff --git a/backend/Makefile b/backend/Makefile index cfe0e7d..b8de149 100644 --- a/backend/Makefile +++ b/backend/Makefile @@ -23,17 +23,15 @@ image: --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 +wire-pro: + wire pro/cmd/server/wire.go pro/cmd/server/main.go + +wire-scanner: + wire cmd/scanner/wire.go cmd/scanner/main.go + swag: swag fmt -d internal && swag init --pd -g cmd/server/main.go -ot "json" diff --git a/backend/build/Dockerfile b/backend/build/Dockerfile index 17b05f7..fc30dd7 100644 --- a/backend/build/Dockerfile +++ b/backend/build/Dockerfile @@ -19,9 +19,15 @@ GOOS=$TARGETOS GOARCH=$TARGETARCH \ go build \ -ldflags "-w -s -X 'github.com/chaitin/MonkeyCode/backend/pkg/version.Version=${VERSION}' -X 'github.com/chaitin/MonkeyCode/backend/pkg/version.BuildTime=${BUILD_TIME}' -X 'github.com/chaitin/MonkeyCode/backend/pkg/version.GitCommit=${GIT_COMMIT}'" \ -o /out/main \ -cmd/server/main.go cmd/server/wire_gen.go +pro/cmd/server/main.go pro/cmd/server/wire_gen.go -FROM alpine:3.21 as binary +FROM debian:bullseye-20250721-slim as binary + +RUN apt-get update && \ + apt-get install -y ca-certificates && \ + apt-get clean && \ + rm -rf /var/lib/apt/lists/* && \ + update-ca-certificates WORKDIR /app diff --git a/backend/cmd/server/wire.go b/backend/cmd/server/wire.go index 53f46f7..faa6ec4 100644 --- a/backend/cmd/server/wire.go +++ b/backend/cmd/server/wire.go @@ -18,6 +18,7 @@ import ( 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" + securityv1 "github.com/chaitin/MonkeyCode/backend/internal/security/handler/http/v1" sockethandler "github.com/chaitin/MonkeyCode/backend/internal/socket/handler" userV1 "github.com/chaitin/MonkeyCode/backend/internal/user/handler/v1" "github.com/chaitin/MonkeyCode/backend/pkg/report" @@ -39,6 +40,7 @@ type Server struct { report *report.Reporter reportuse domain.ReportUsecase euse domain.ExtensionUsecase + securityV1 *securityv1.SecurityHandler codeSnippetV1 *codesnippetv1.CodeSnippetHandler } diff --git a/backend/cmd/server/wire_gen.go b/backend/cmd/server/wire_gen.go index e4a9856..74575db 100644 --- a/backend/cmd/server/wire_gen.go +++ b/backend/cmd/server/wire_gen.go @@ -12,34 +12,37 @@ import ( "github.com/chaitin/MonkeyCode/backend/db" "github.com/chaitin/MonkeyCode/backend/domain" v1_5 "github.com/chaitin/MonkeyCode/backend/internal/billing/handler/http/v1" - repo7 "github.com/chaitin/MonkeyCode/backend/internal/billing/repo" - usecase6 "github.com/chaitin/MonkeyCode/backend/internal/billing/usecase" - v1_6 "github.com/chaitin/MonkeyCode/backend/internal/codesnippet/handler/http/v1" - repo9 "github.com/chaitin/MonkeyCode/backend/internal/codesnippet/repo" - usecase8 "github.com/chaitin/MonkeyCode/backend/internal/codesnippet/usecase" + repo8 "github.com/chaitin/MonkeyCode/backend/internal/billing/repo" + usecase7 "github.com/chaitin/MonkeyCode/backend/internal/billing/usecase" + v1_7 "github.com/chaitin/MonkeyCode/backend/internal/codesnippet/handler/http/v1" + repo10 "github.com/chaitin/MonkeyCode/backend/internal/codesnippet/repo" + usecase9 "github.com/chaitin/MonkeyCode/backend/internal/codesnippet/usecase" v1_4 "github.com/chaitin/MonkeyCode/backend/internal/dashboard/handler/v1" - repo6 "github.com/chaitin/MonkeyCode/backend/internal/dashboard/repo" - usecase5 "github.com/chaitin/MonkeyCode/backend/internal/dashboard/usecase" - repo4 "github.com/chaitin/MonkeyCode/backend/internal/extension/repo" + repo7 "github.com/chaitin/MonkeyCode/backend/internal/dashboard/repo" + usecase6 "github.com/chaitin/MonkeyCode/backend/internal/dashboard/usecase" + repo5 "github.com/chaitin/MonkeyCode/backend/internal/extension/repo" usecase2 "github.com/chaitin/MonkeyCode/backend/internal/extension/usecase" "github.com/chaitin/MonkeyCode/backend/internal/middleware" v1_2 "github.com/chaitin/MonkeyCode/backend/internal/model/handler/http/v1" repo2 "github.com/chaitin/MonkeyCode/backend/internal/model/repo" usecase4 "github.com/chaitin/MonkeyCode/backend/internal/model/usecase" "github.com/chaitin/MonkeyCode/backend/internal/openai/handler/v1" - repo3 "github.com/chaitin/MonkeyCode/backend/internal/openai/repo" + repo4 "github.com/chaitin/MonkeyCode/backend/internal/openai/repo" "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" - repo10 "github.com/chaitin/MonkeyCode/backend/internal/report/repo" - usecase9 "github.com/chaitin/MonkeyCode/backend/internal/report/usecase" + repo11 "github.com/chaitin/MonkeyCode/backend/internal/report/repo" + usecase10 "github.com/chaitin/MonkeyCode/backend/internal/report/usecase" + v1_6 "github.com/chaitin/MonkeyCode/backend/internal/security/handler/http/v1" + repo3 "github.com/chaitin/MonkeyCode/backend/internal/security/repo" + usecase5 "github.com/chaitin/MonkeyCode/backend/internal/security/usecase" "github.com/chaitin/MonkeyCode/backend/internal/socket/handler" v1_3 "github.com/chaitin/MonkeyCode/backend/internal/user/handler/v1" - repo5 "github.com/chaitin/MonkeyCode/backend/internal/user/repo" + repo6 "github.com/chaitin/MonkeyCode/backend/internal/user/repo" usecase3 "github.com/chaitin/MonkeyCode/backend/internal/user/usecase" - repo8 "github.com/chaitin/MonkeyCode/backend/internal/workspace/repo" - usecase7 "github.com/chaitin/MonkeyCode/backend/internal/workspace/usecase" + repo9 "github.com/chaitin/MonkeyCode/backend/internal/workspace/repo" + usecase8 "github.com/chaitin/MonkeyCode/backend/internal/workspace/usecase" "github.com/chaitin/MonkeyCode/backend/pkg" "github.com/chaitin/MonkeyCode/backend/pkg/ipdb" "github.com/chaitin/MonkeyCode/backend/pkg/logger" @@ -67,17 +70,18 @@ func newServer() (*Server, error) { redisClient := store.NewRedisCli(configConfig) proxyRepo := repo.NewProxyRepo(client, redisClient) modelRepo := repo2.NewModelRepo(client) - proxyUsecase := usecase.NewProxyUsecase(proxyRepo, modelRepo, slogLogger) + securityScanningRepo := repo3.NewSecurityScanningRepo(client) + proxyUsecase := usecase.NewProxyUsecase(proxyRepo, modelRepo, securityScanningRepo, slogLogger, configConfig, redisClient) llmProxy := proxy.NewLLMProxy(slogLogger, configConfig, proxyUsecase) - openAIRepo := repo3.NewOpenAIRepo(client) + openAIRepo := repo4.NewOpenAIRepo(client) openAIUsecase := openai.NewOpenAIUsecase(configConfig, openAIRepo, modelRepo, slogLogger) - extensionRepo := repo4.NewExtensionRepo(client) + extensionRepo := repo5.NewExtensionRepo(client) extensionUsecase := usecase2.NewExtensionUsecase(extensionRepo, configConfig, slogLogger) ipdbIPDB, err := ipdb.NewIPDB(slogLogger) if err != nil { return nil, err } - userRepo := repo5.NewUserRepo(client, ipdbIPDB, redisClient, configConfig) + userRepo := repo6.NewUserRepo(client, ipdbIPDB, redisClient, configConfig) sessionSession := session.NewSession(configConfig) userUsecase := usecase3.NewUserUsecase(configConfig, redisClient, userRepo, slogLogger, sessionSession) proxyMiddleware := middleware.NewProxyMiddleware(proxyUsecase) @@ -87,28 +91,30 @@ func newServer() (*Server, error) { authMiddleware := middleware.NewAuthMiddleware(sessionSession, slogLogger) readOnlyMiddleware := middleware.NewReadOnlyMiddleware(configConfig) modelHandler := v1_2.NewModelHandler(web, modelUsecase, authMiddleware, activeMiddleware, readOnlyMiddleware, slogLogger) - dashboardRepo := repo6.NewDashboardRepo(client) - dashboardUsecase := usecase5.NewDashboardUsecase(dashboardRepo) - billingRepo := repo7.NewBillingRepo(client) - billingUsecase := usecase6.NewBillingUsecase(billingRepo) - userHandler := v1_3.NewUserHandler(web, userUsecase, extensionUsecase, dashboardUsecase, billingUsecase, authMiddleware, activeMiddleware, readOnlyMiddleware, sessionSession, slogLogger, configConfig) + securityScanningUsecase := usecase5.NewSecurityScanningUsecase(securityScanningRepo) + dashboardRepo := repo7.NewDashboardRepo(client) + dashboardUsecase := usecase6.NewDashboardUsecase(dashboardRepo) + billingRepo := repo8.NewBillingRepo(client) + billingUsecase := usecase7.NewBillingUsecase(billingRepo) + userHandler := v1_3.NewUserHandler(web, userUsecase, extensionUsecase, securityScanningUsecase, dashboardUsecase, billingUsecase, authMiddleware, activeMiddleware, readOnlyMiddleware, sessionSession, slogLogger, configConfig) dashboardHandler := v1_4.NewDashboardHandler(web, dashboardUsecase, authMiddleware, activeMiddleware) billingHandler := v1_5.NewBillingHandler(web, billingUsecase, authMiddleware, activeMiddleware) - workspaceFileRepo := repo8.NewWorkspaceFileRepo(client) - workspaceRepo := repo8.NewWorkspaceRepo(client) - workspaceUsecase := usecase7.NewWorkspaceUsecase(workspaceRepo, configConfig, slogLogger) - codeSnippetRepo := repo9.NewCodeSnippetRepo(client, slogLogger) - codeSnippetUsecase := usecase8.NewCodeSnippetUsecase(codeSnippetRepo, slogLogger) - workspaceFileUsecase := usecase7.NewWorkspaceFileUsecase(workspaceFileRepo, workspaceUsecase, codeSnippetUsecase, configConfig, slogLogger) + workspaceFileRepo := repo9.NewWorkspaceFileRepo(client) + workspaceRepo := repo9.NewWorkspaceRepo(client) + workspaceUsecase := usecase8.NewWorkspaceUsecase(workspaceRepo, configConfig, slogLogger) + codeSnippetRepo := repo10.NewCodeSnippetRepo(client, slogLogger) + codeSnippetUsecase := usecase9.NewCodeSnippetUsecase(codeSnippetRepo, slogLogger) + workspaceFileUsecase := usecase8.NewWorkspaceFileUsecase(workspaceFileRepo, workspaceUsecase, codeSnippetUsecase, configConfig, slogLogger) socketHandler, err := handler.NewSocketHandler(configConfig, slogLogger, workspaceFileUsecase, workspaceUsecase, userUsecase) if err != nil { return nil, err } versionInfo := version.NewVersionInfo() reporter := report.NewReport(slogLogger, configConfig, versionInfo) - reportRepo := repo10.NewReportRepo(client) - reportUsecase := usecase9.NewReportUsecase(reportRepo, slogLogger, reporter, redisClient) - codeSnippetHandler := v1_6.NewCodeSnippetHandler(web, codeSnippetUsecase, authMiddleware, activeMiddleware, readOnlyMiddleware, proxyMiddleware, slogLogger) + reportRepo := repo11.NewReportRepo(client) + reportUsecase := usecase10.NewReportUsecase(reportRepo, slogLogger, reporter, redisClient) + securityHandler := v1_6.NewSecurityHandler(web, securityScanningUsecase, authMiddleware, activeMiddleware) + codeSnippetHandler := v1_7.NewCodeSnippetHandler(web, codeSnippetUsecase, authMiddleware, activeMiddleware, readOnlyMiddleware, proxyMiddleware, slogLogger) server := &Server{ config: configConfig, web: web, @@ -124,6 +130,7 @@ func newServer() (*Server, error) { report: reporter, reportuse: reportUsecase, euse: extensionUsecase, + securityV1: securityHandler, codeSnippetV1: codeSnippetHandler, } return server, nil @@ -146,5 +153,6 @@ type Server struct { report *report.Reporter reportuse domain.ReportUsecase euse domain.ExtensionUsecase - codeSnippetV1 *v1_6.CodeSnippetHandler + securityV1 *v1_6.SecurityHandler + codeSnippetV1 *v1_7.CodeSnippetHandler } diff --git a/backend/config/config.go b/backend/config/config.go index 2171d76..13164a2 100644 --- a/backend/config/config.go +++ b/backend/config/config.go @@ -76,6 +76,10 @@ type Config struct { DataReport struct { Key string `mapstructure:"key"` } `mapstructure:"data_report"` + + Security struct { + QueueLimit int `mapstructure:"queue_limit"` + } `mapstructure:"security"` } func (c *Config) GetBaseURL(req *http.Request, settings *domain.Setting) string { @@ -142,6 +146,7 @@ func Init() (*Config, error) { v.SetDefault("extension.limit", 1) v.SetDefault("extension.limit_second", 10) v.SetDefault("data_report.key", "") + v.SetDefault("security.queue_limit", 5) c := Config{} if err := v.Unmarshal(&c); err != nil { diff --git a/backend/consts/security.go b/backend/consts/security.go new file mode 100644 index 0000000..0f5d520 --- /dev/null +++ b/backend/consts/security.go @@ -0,0 +1,61 @@ +package consts + +import "fmt" + +type SecurityScanningStatus string + +const ( + SecurityScanningStatusPending SecurityScanningStatus = "pending" + SecurityScanningStatusRunning SecurityScanningStatus = "running" + SecurityScanningStatusSuccess SecurityScanningStatus = "success" + SecurityScanningStatusFailed SecurityScanningStatus = "failed" +) + +// 风险等级 +type SecurityScanningRiskLevel string + +const ( + SecurityScanningRiskLevelSevere SecurityScanningRiskLevel = "severe" // 严重 + SecurityScanningRiskLevelCritical SecurityScanningRiskLevel = "critical" // 高危 + SecurityScanningRiskLevelSuggest SecurityScanningRiskLevel = "suggest" // 建议 +) + +type SecurityScanningLanguage string + +const ( + SecurityScanningLanguageCpp SecurityScanningLanguage = "C/C++" + SecurityScanningLanguageJava SecurityScanningLanguage = "Java" + SecurityScanningLanguagePython SecurityScanningLanguage = "Python" + SecurityScanningLanguageJavaScript SecurityScanningLanguage = "JavaScript" + SecurityScanningLanguageGo SecurityScanningLanguage = "Go" + SecurityScanningLanguagePHP SecurityScanningLanguage = "PHP" + SecurityScanningLanguageCS SecurityScanningLanguage = "C#" + SecurityScanningLanguageSwift SecurityScanningLanguage = "Swift" + SecurityScanningLanguageRuby SecurityScanningLanguage = "Ruby" + SecurityScanningLanguageRust SecurityScanningLanguage = "Rust" + SecurityScanningLanguageHTML SecurityScanningLanguage = "HTML" + SecurityScanningLanguageObjectiveC SecurityScanningLanguage = "Objective-C/C++" + SecurityScanningLanguageOCaml SecurityScanningLanguage = "OCaml" + SecurityScanningLanguageKotlin SecurityScanningLanguage = "Kotlin" + SecurityScanningLanguageScala SecurityScanningLanguage = "Scala" + SecurityScanningLanguageSolidity SecurityScanningLanguage = "Solidity" + SecurityScanningLanguageCOBOL SecurityScanningLanguage = "COBOL" + SecurityScanningLanguageShell SecurityScanningLanguage = "Shell" + SecurityScanningLanguageSQL SecurityScanningLanguage = "SQL" + SecurityScanningLanguageFortran SecurityScanningLanguage = "Fortran" + SecurityScanningLanguageDart SecurityScanningLanguage = "Dart" + SecurityScanningLanguageGroovy SecurityScanningLanguage = "Groovy" + SecurityScanningLanguageLua SecurityScanningLanguage = "Lua" + SecurityScanningLanguageSecrets SecurityScanningLanguage = "Secrets" + SecurityScanningLanguageIaC SecurityScanningLanguage = "IaC" +) + +func (s SecurityScanningLanguage) RuleName() string { + if s == SecurityScanningLanguageIaC { + return "基础设施即代码(IaC)扫描" + } + if s == SecurityScanningLanguageSecrets { + return "硬编码敏感信息检测" + } + return fmt.Sprintf("%s 安全扫描", s) +} diff --git a/backend/db/client.go b/backend/db/client.go index 8983ef4..6d0e739 100644 --- a/backend/db/client.go +++ b/backend/db/client.go @@ -30,6 +30,8 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/model" "github.com/chaitin/MonkeyCode/backend/db/modelprovider" "github.com/chaitin/MonkeyCode/backend/db/modelprovidermodel" + "github.com/chaitin/MonkeyCode/backend/db/securityscanning" + "github.com/chaitin/MonkeyCode/backend/db/securityscanningresult" "github.com/chaitin/MonkeyCode/backend/db/setting" "github.com/chaitin/MonkeyCode/backend/db/task" "github.com/chaitin/MonkeyCode/backend/db/taskrecord" @@ -75,6 +77,10 @@ type Client struct { ModelProvider *ModelProviderClient // ModelProviderModel is the client for interacting with the ModelProviderModel builders. ModelProviderModel *ModelProviderModelClient + // SecurityScanning is the client for interacting with the SecurityScanning builders. + SecurityScanning *SecurityScanningClient + // SecurityScanningResult is the client for interacting with the SecurityScanningResult builders. + SecurityScanningResult *SecurityScanningResultClient // Setting is the client for interacting with the Setting builders. Setting *SettingClient // Task is the client for interacting with the Task builders. @@ -116,6 +122,8 @@ func (c *Client) init() { c.Model = NewModelClient(c.config) c.ModelProvider = NewModelProviderClient(c.config) c.ModelProviderModel = NewModelProviderModelClient(c.config) + c.SecurityScanning = NewSecurityScanningClient(c.config) + c.SecurityScanningResult = NewSecurityScanningResultClient(c.config) c.Setting = NewSettingClient(c.config) c.Task = NewTaskClient(c.config) c.TaskRecord = NewTaskRecordClient(c.config) @@ -214,30 +222,32 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { 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), - CodeSnippet: NewCodeSnippetClient(cfg), - Extension: NewExtensionClient(cfg), - InviteCode: NewInviteCodeClient(cfg), - License: NewLicenseClient(cfg), - Model: NewModelClient(cfg), - ModelProvider: NewModelProviderClient(cfg), - ModelProviderModel: NewModelProviderModelClient(cfg), - Setting: NewSettingClient(cfg), - Task: NewTaskClient(cfg), - TaskRecord: NewTaskRecordClient(cfg), - User: NewUserClient(cfg), - UserIdentity: NewUserIdentityClient(cfg), - UserLoginHistory: NewUserLoginHistoryClient(cfg), - Workspace: NewWorkspaceClient(cfg), - WorkspaceFile: NewWorkspaceFileClient(cfg), + 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), + CodeSnippet: NewCodeSnippetClient(cfg), + Extension: NewExtensionClient(cfg), + InviteCode: NewInviteCodeClient(cfg), + License: NewLicenseClient(cfg), + Model: NewModelClient(cfg), + ModelProvider: NewModelProviderClient(cfg), + ModelProviderModel: NewModelProviderModelClient(cfg), + SecurityScanning: NewSecurityScanningClient(cfg), + SecurityScanningResult: NewSecurityScanningResultClient(cfg), + Setting: NewSettingClient(cfg), + Task: NewTaskClient(cfg), + TaskRecord: NewTaskRecordClient(cfg), + User: NewUserClient(cfg), + UserIdentity: NewUserIdentityClient(cfg), + UserLoginHistory: NewUserLoginHistoryClient(cfg), + Workspace: NewWorkspaceClient(cfg), + WorkspaceFile: NewWorkspaceFileClient(cfg), }, nil } @@ -255,30 +265,32 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) 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), - CodeSnippet: NewCodeSnippetClient(cfg), - Extension: NewExtensionClient(cfg), - InviteCode: NewInviteCodeClient(cfg), - License: NewLicenseClient(cfg), - Model: NewModelClient(cfg), - ModelProvider: NewModelProviderClient(cfg), - ModelProviderModel: NewModelProviderModelClient(cfg), - Setting: NewSettingClient(cfg), - Task: NewTaskClient(cfg), - TaskRecord: NewTaskRecordClient(cfg), - User: NewUserClient(cfg), - UserIdentity: NewUserIdentityClient(cfg), - UserLoginHistory: NewUserLoginHistoryClient(cfg), - Workspace: NewWorkspaceClient(cfg), - WorkspaceFile: NewWorkspaceFileClient(cfg), + 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), + CodeSnippet: NewCodeSnippetClient(cfg), + Extension: NewExtensionClient(cfg), + InviteCode: NewInviteCodeClient(cfg), + License: NewLicenseClient(cfg), + Model: NewModelClient(cfg), + ModelProvider: NewModelProviderClient(cfg), + ModelProviderModel: NewModelProviderModelClient(cfg), + SecurityScanning: NewSecurityScanningClient(cfg), + SecurityScanningResult: NewSecurityScanningResultClient(cfg), + Setting: NewSettingClient(cfg), + Task: NewTaskClient(cfg), + TaskRecord: NewTaskRecordClient(cfg), + User: NewUserClient(cfg), + UserIdentity: NewUserIdentityClient(cfg), + UserLoginHistory: NewUserLoginHistoryClient(cfg), + Workspace: NewWorkspaceClient(cfg), + WorkspaceFile: NewWorkspaceFileClient(cfg), }, nil } @@ -310,9 +322,9 @@ 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.CodeSnippet, c.Extension, c.InviteCode, - c.License, c.Model, c.ModelProvider, c.ModelProviderModel, c.Setting, c.Task, - c.TaskRecord, c.User, c.UserIdentity, c.UserLoginHistory, c.Workspace, - c.WorkspaceFile, + c.License, c.Model, c.ModelProvider, c.ModelProviderModel, c.SecurityScanning, + c.SecurityScanningResult, c.Setting, c.Task, c.TaskRecord, c.User, + c.UserIdentity, c.UserLoginHistory, c.Workspace, c.WorkspaceFile, } { n.Use(hooks...) } @@ -324,9 +336,9 @@ 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.CodeSnippet, c.Extension, c.InviteCode, - c.License, c.Model, c.ModelProvider, c.ModelProviderModel, c.Setting, c.Task, - c.TaskRecord, c.User, c.UserIdentity, c.UserLoginHistory, c.Workspace, - c.WorkspaceFile, + c.License, c.Model, c.ModelProvider, c.ModelProviderModel, c.SecurityScanning, + c.SecurityScanningResult, c.Setting, c.Task, c.TaskRecord, c.User, + c.UserIdentity, c.UserLoginHistory, c.Workspace, c.WorkspaceFile, } { n.Intercept(interceptors...) } @@ -363,6 +375,10 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { return c.ModelProvider.mutate(ctx, m) case *ModelProviderModelMutation: return c.ModelProviderModel.mutate(ctx, m) + case *SecurityScanningMutation: + return c.SecurityScanning.mutate(ctx, m) + case *SecurityScanningResultMutation: + return c.SecurityScanningResult.mutate(ctx, m) case *SettingMutation: return c.Setting.mutate(ctx, m) case *TaskMutation: @@ -2378,6 +2394,336 @@ func (c *ModelProviderModelClient) mutate(ctx context.Context, m *ModelProviderM } } +// SecurityScanningClient is a client for the SecurityScanning schema. +type SecurityScanningClient struct { + config +} + +// NewSecurityScanningClient returns a client for the SecurityScanning from the given config. +func NewSecurityScanningClient(c config) *SecurityScanningClient { + return &SecurityScanningClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `securityscanning.Hooks(f(g(h())))`. +func (c *SecurityScanningClient) Use(hooks ...Hook) { + c.hooks.SecurityScanning = append(c.hooks.SecurityScanning, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `securityscanning.Intercept(f(g(h())))`. +func (c *SecurityScanningClient) Intercept(interceptors ...Interceptor) { + c.inters.SecurityScanning = append(c.inters.SecurityScanning, interceptors...) +} + +// Create returns a builder for creating a SecurityScanning entity. +func (c *SecurityScanningClient) Create() *SecurityScanningCreate { + mutation := newSecurityScanningMutation(c.config, OpCreate) + return &SecurityScanningCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of SecurityScanning entities. +func (c *SecurityScanningClient) CreateBulk(builders ...*SecurityScanningCreate) *SecurityScanningCreateBulk { + return &SecurityScanningCreateBulk{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 *SecurityScanningClient) MapCreateBulk(slice any, setFunc func(*SecurityScanningCreate, int)) *SecurityScanningCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &SecurityScanningCreateBulk{err: fmt.Errorf("calling to SecurityScanningClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*SecurityScanningCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &SecurityScanningCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for SecurityScanning. +func (c *SecurityScanningClient) Update() *SecurityScanningUpdate { + mutation := newSecurityScanningMutation(c.config, OpUpdate) + return &SecurityScanningUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *SecurityScanningClient) UpdateOne(ss *SecurityScanning) *SecurityScanningUpdateOne { + mutation := newSecurityScanningMutation(c.config, OpUpdateOne, withSecurityScanning(ss)) + return &SecurityScanningUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *SecurityScanningClient) UpdateOneID(id uuid.UUID) *SecurityScanningUpdateOne { + mutation := newSecurityScanningMutation(c.config, OpUpdateOne, withSecurityScanningID(id)) + return &SecurityScanningUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for SecurityScanning. +func (c *SecurityScanningClient) Delete() *SecurityScanningDelete { + mutation := newSecurityScanningMutation(c.config, OpDelete) + return &SecurityScanningDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *SecurityScanningClient) DeleteOne(ss *SecurityScanning) *SecurityScanningDeleteOne { + return c.DeleteOneID(ss.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *SecurityScanningClient) DeleteOneID(id uuid.UUID) *SecurityScanningDeleteOne { + builder := c.Delete().Where(securityscanning.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &SecurityScanningDeleteOne{builder} +} + +// Query returns a query builder for SecurityScanning. +func (c *SecurityScanningClient) Query() *SecurityScanningQuery { + return &SecurityScanningQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeSecurityScanning}, + inters: c.Interceptors(), + } +} + +// Get returns a SecurityScanning entity by its id. +func (c *SecurityScanningClient) Get(ctx context.Context, id uuid.UUID) (*SecurityScanning, error) { + return c.Query().Where(securityscanning.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *SecurityScanningClient) GetX(ctx context.Context, id uuid.UUID) *SecurityScanning { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryUser queries the user edge of a SecurityScanning. +func (c *SecurityScanningClient) QueryUser(ss *SecurityScanning) *UserQuery { + query := (&UserClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := ss.ID + step := sqlgraph.NewStep( + sqlgraph.From(securityscanning.Table, securityscanning.FieldID, id), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, securityscanning.UserTable, securityscanning.UserColumn), + ) + fromV = sqlgraph.Neighbors(ss.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryResults queries the results edge of a SecurityScanning. +func (c *SecurityScanningClient) QueryResults(ss *SecurityScanning) *SecurityScanningResultQuery { + query := (&SecurityScanningResultClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := ss.ID + step := sqlgraph.NewStep( + sqlgraph.From(securityscanning.Table, securityscanning.FieldID, id), + sqlgraph.To(securityscanningresult.Table, securityscanningresult.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, securityscanning.ResultsTable, securityscanning.ResultsColumn), + ) + fromV = sqlgraph.Neighbors(ss.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryWorkspaceEdge queries the workspace_edge edge of a SecurityScanning. +func (c *SecurityScanningClient) QueryWorkspaceEdge(ss *SecurityScanning) *WorkspaceQuery { + query := (&WorkspaceClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := ss.ID + step := sqlgraph.NewStep( + sqlgraph.From(securityscanning.Table, securityscanning.FieldID, id), + sqlgraph.To(workspace.Table, workspace.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, securityscanning.WorkspaceEdgeTable, securityscanning.WorkspaceEdgeColumn), + ) + fromV = sqlgraph.Neighbors(ss.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *SecurityScanningClient) Hooks() []Hook { + return c.hooks.SecurityScanning +} + +// Interceptors returns the client interceptors. +func (c *SecurityScanningClient) Interceptors() []Interceptor { + return c.inters.SecurityScanning +} + +func (c *SecurityScanningClient) mutate(ctx context.Context, m *SecurityScanningMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&SecurityScanningCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&SecurityScanningUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&SecurityScanningUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&SecurityScanningDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown SecurityScanning mutation op: %q", m.Op()) + } +} + +// SecurityScanningResultClient is a client for the SecurityScanningResult schema. +type SecurityScanningResultClient struct { + config +} + +// NewSecurityScanningResultClient returns a client for the SecurityScanningResult from the given config. +func NewSecurityScanningResultClient(c config) *SecurityScanningResultClient { + return &SecurityScanningResultClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `securityscanningresult.Hooks(f(g(h())))`. +func (c *SecurityScanningResultClient) Use(hooks ...Hook) { + c.hooks.SecurityScanningResult = append(c.hooks.SecurityScanningResult, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `securityscanningresult.Intercept(f(g(h())))`. +func (c *SecurityScanningResultClient) Intercept(interceptors ...Interceptor) { + c.inters.SecurityScanningResult = append(c.inters.SecurityScanningResult, interceptors...) +} + +// Create returns a builder for creating a SecurityScanningResult entity. +func (c *SecurityScanningResultClient) Create() *SecurityScanningResultCreate { + mutation := newSecurityScanningResultMutation(c.config, OpCreate) + return &SecurityScanningResultCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of SecurityScanningResult entities. +func (c *SecurityScanningResultClient) CreateBulk(builders ...*SecurityScanningResultCreate) *SecurityScanningResultCreateBulk { + return &SecurityScanningResultCreateBulk{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 *SecurityScanningResultClient) MapCreateBulk(slice any, setFunc func(*SecurityScanningResultCreate, int)) *SecurityScanningResultCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &SecurityScanningResultCreateBulk{err: fmt.Errorf("calling to SecurityScanningResultClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*SecurityScanningResultCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &SecurityScanningResultCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for SecurityScanningResult. +func (c *SecurityScanningResultClient) Update() *SecurityScanningResultUpdate { + mutation := newSecurityScanningResultMutation(c.config, OpUpdate) + return &SecurityScanningResultUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *SecurityScanningResultClient) UpdateOne(ssr *SecurityScanningResult) *SecurityScanningResultUpdateOne { + mutation := newSecurityScanningResultMutation(c.config, OpUpdateOne, withSecurityScanningResult(ssr)) + return &SecurityScanningResultUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *SecurityScanningResultClient) UpdateOneID(id uuid.UUID) *SecurityScanningResultUpdateOne { + mutation := newSecurityScanningResultMutation(c.config, OpUpdateOne, withSecurityScanningResultID(id)) + return &SecurityScanningResultUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for SecurityScanningResult. +func (c *SecurityScanningResultClient) Delete() *SecurityScanningResultDelete { + mutation := newSecurityScanningResultMutation(c.config, OpDelete) + return &SecurityScanningResultDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *SecurityScanningResultClient) DeleteOne(ssr *SecurityScanningResult) *SecurityScanningResultDeleteOne { + return c.DeleteOneID(ssr.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *SecurityScanningResultClient) DeleteOneID(id uuid.UUID) *SecurityScanningResultDeleteOne { + builder := c.Delete().Where(securityscanningresult.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &SecurityScanningResultDeleteOne{builder} +} + +// Query returns a query builder for SecurityScanningResult. +func (c *SecurityScanningResultClient) Query() *SecurityScanningResultQuery { + return &SecurityScanningResultQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeSecurityScanningResult}, + inters: c.Interceptors(), + } +} + +// Get returns a SecurityScanningResult entity by its id. +func (c *SecurityScanningResultClient) Get(ctx context.Context, id uuid.UUID) (*SecurityScanningResult, error) { + return c.Query().Where(securityscanningresult.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *SecurityScanningResultClient) GetX(ctx context.Context, id uuid.UUID) *SecurityScanningResult { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QuerySecurityScanning queries the security_scanning edge of a SecurityScanningResult. +func (c *SecurityScanningResultClient) QuerySecurityScanning(ssr *SecurityScanningResult) *SecurityScanningQuery { + query := (&SecurityScanningClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := ssr.ID + step := sqlgraph.NewStep( + sqlgraph.From(securityscanningresult.Table, securityscanningresult.FieldID, id), + sqlgraph.To(securityscanning.Table, securityscanning.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, securityscanningresult.SecurityScanningTable, securityscanningresult.SecurityScanningColumn), + ) + fromV = sqlgraph.Neighbors(ssr.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *SecurityScanningResultClient) Hooks() []Hook { + return c.hooks.SecurityScanningResult +} + +// Interceptors returns the client interceptors. +func (c *SecurityScanningResultClient) Interceptors() []Interceptor { + return c.inters.SecurityScanningResult +} + +func (c *SecurityScanningResultClient) mutate(ctx context.Context, m *SecurityScanningResultMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&SecurityScanningResultCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&SecurityScanningResultUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&SecurityScanningResultUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&SecurityScanningResultDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown SecurityScanningResult mutation op: %q", m.Op()) + } +} + // SettingClient is a client for the Setting schema. type SettingClient struct { config @@ -3061,6 +3407,22 @@ func (c *UserClient) QueryAPIKeys(u *User) *ApiKeyQuery { return query } +// QuerySecurityScannings queries the security_scannings edge of a User. +func (c *UserClient) QuerySecurityScannings(u *User) *SecurityScanningQuery { + query := (&SecurityScanningClient{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(securityscanning.Table, securityscanning.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, user.SecurityScanningsTable, user.SecurityScanningsColumn), + ) + fromV = sqlgraph.Neighbors(u.driver.Dialect(), step) + return fromV, nil + } + return query +} + // Hooks returns the client hooks. func (c *UserClient) Hooks() []Hook { hooks := c.hooks.User @@ -3528,6 +3890,22 @@ func (c *WorkspaceClient) QueryFiles(w *Workspace) *WorkspaceFileQuery { return query } +// QuerySecurityScannings queries the security_scannings edge of a Workspace. +func (c *WorkspaceClient) QuerySecurityScannings(w *Workspace) *SecurityScanningQuery { + query := (&SecurityScanningClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := w.ID + step := sqlgraph.NewStep( + sqlgraph.From(workspace.Table, workspace.FieldID, id), + sqlgraph.To(securityscanning.Table, securityscanning.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, workspace.SecurityScanningsTable, workspace.SecurityScanningsColumn), + ) + fromV = sqlgraph.Neighbors(w.driver.Dialect(), step) + return fromV, nil + } + return query +} + // Hooks returns the client hooks. func (c *WorkspaceClient) Hooks() []Hook { return c.hooks.Workspace @@ -3739,14 +4117,16 @@ type ( hooks struct { Admin, AdminLoginHistory, ApiKey, BillingPlan, BillingQuota, BillingRecord, BillingUsage, CodeSnippet, Extension, InviteCode, License, Model, - ModelProvider, ModelProviderModel, Setting, Task, TaskRecord, User, - UserIdentity, UserLoginHistory, Workspace, WorkspaceFile []ent.Hook + ModelProvider, ModelProviderModel, SecurityScanning, SecurityScanningResult, + Setting, Task, TaskRecord, User, UserIdentity, UserLoginHistory, Workspace, + WorkspaceFile []ent.Hook } inters struct { Admin, AdminLoginHistory, ApiKey, BillingPlan, BillingQuota, BillingRecord, BillingUsage, CodeSnippet, Extension, InviteCode, License, Model, - ModelProvider, ModelProviderModel, Setting, Task, TaskRecord, User, - UserIdentity, UserLoginHistory, Workspace, WorkspaceFile []ent.Interceptor + ModelProvider, ModelProviderModel, SecurityScanning, SecurityScanningResult, + Setting, Task, TaskRecord, User, UserIdentity, UserLoginHistory, Workspace, + WorkspaceFile []ent.Interceptor } ) diff --git a/backend/db/ent.go b/backend/db/ent.go index 5cff07e..9a1f4c7 100644 --- a/backend/db/ent.go +++ b/backend/db/ent.go @@ -26,6 +26,8 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/model" "github.com/chaitin/MonkeyCode/backend/db/modelprovider" "github.com/chaitin/MonkeyCode/backend/db/modelprovidermodel" + "github.com/chaitin/MonkeyCode/backend/db/securityscanning" + "github.com/chaitin/MonkeyCode/backend/db/securityscanningresult" "github.com/chaitin/MonkeyCode/backend/db/setting" "github.com/chaitin/MonkeyCode/backend/db/task" "github.com/chaitin/MonkeyCode/backend/db/taskrecord" @@ -94,28 +96,30 @@ var ( 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, - codesnippet.Table: codesnippet.ValidColumn, - extension.Table: extension.ValidColumn, - invitecode.Table: invitecode.ValidColumn, - license.Table: license.ValidColumn, - model.Table: model.ValidColumn, - modelprovider.Table: modelprovider.ValidColumn, - modelprovidermodel.Table: modelprovidermodel.ValidColumn, - setting.Table: setting.ValidColumn, - task.Table: task.ValidColumn, - taskrecord.Table: taskrecord.ValidColumn, - user.Table: user.ValidColumn, - useridentity.Table: useridentity.ValidColumn, - userloginhistory.Table: userloginhistory.ValidColumn, - workspace.Table: workspace.ValidColumn, - workspacefile.Table: workspacefile.ValidColumn, + 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, + codesnippet.Table: codesnippet.ValidColumn, + extension.Table: extension.ValidColumn, + invitecode.Table: invitecode.ValidColumn, + license.Table: license.ValidColumn, + model.Table: model.ValidColumn, + modelprovider.Table: modelprovider.ValidColumn, + modelprovidermodel.Table: modelprovidermodel.ValidColumn, + securityscanning.Table: securityscanning.ValidColumn, + securityscanningresult.Table: securityscanningresult.ValidColumn, + setting.Table: setting.ValidColumn, + task.Table: task.ValidColumn, + taskrecord.Table: taskrecord.ValidColumn, + user.Table: user.ValidColumn, + useridentity.Table: useridentity.ValidColumn, + userloginhistory.Table: userloginhistory.ValidColumn, + workspace.Table: workspace.ValidColumn, + workspacefile.Table: workspacefile.ValidColumn, }) }) return columnCheck(table, column) diff --git a/backend/db/hook/hook.go b/backend/db/hook/hook.go index 4f3e149..16263b7 100644 --- a/backend/db/hook/hook.go +++ b/backend/db/hook/hook.go @@ -177,6 +177,30 @@ func (f ModelProviderModelFunc) Mutate(ctx context.Context, m db.Mutation) (db.V return nil, fmt.Errorf("unexpected mutation type %T. expect *db.ModelProviderModelMutation", m) } +// The SecurityScanningFunc type is an adapter to allow the use of ordinary +// function as SecurityScanning mutator. +type SecurityScanningFunc func(context.Context, *db.SecurityScanningMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f SecurityScanningFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.SecurityScanningMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.SecurityScanningMutation", m) +} + +// The SecurityScanningResultFunc type is an adapter to allow the use of ordinary +// function as SecurityScanningResult mutator. +type SecurityScanningResultFunc func(context.Context, *db.SecurityScanningResultMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f SecurityScanningResultFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.SecurityScanningResultMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.SecurityScanningResultMutation", 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) diff --git a/backend/db/intercept/intercept.go b/backend/db/intercept/intercept.go index 9bca46c..54a61ff 100644 --- a/backend/db/intercept/intercept.go +++ b/backend/db/intercept/intercept.go @@ -23,6 +23,8 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/modelprovider" "github.com/chaitin/MonkeyCode/backend/db/modelprovidermodel" "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/securityscanning" + "github.com/chaitin/MonkeyCode/backend/db/securityscanningresult" "github.com/chaitin/MonkeyCode/backend/db/setting" "github.com/chaitin/MonkeyCode/backend/db/task" "github.com/chaitin/MonkeyCode/backend/db/taskrecord" @@ -467,6 +469,60 @@ func (f TraverseModelProviderModel) Traverse(ctx context.Context, q db.Query) er return fmt.Errorf("unexpected query type %T. expect *db.ModelProviderModelQuery", q) } +// The SecurityScanningFunc type is an adapter to allow the use of ordinary function as a Querier. +type SecurityScanningFunc func(context.Context, *db.SecurityScanningQuery) (db.Value, error) + +// Query calls f(ctx, q). +func (f SecurityScanningFunc) Query(ctx context.Context, q db.Query) (db.Value, error) { + if q, ok := q.(*db.SecurityScanningQuery); ok { + return f(ctx, q) + } + return nil, fmt.Errorf("unexpected query type %T. expect *db.SecurityScanningQuery", q) +} + +// The TraverseSecurityScanning type is an adapter to allow the use of ordinary function as Traverser. +type TraverseSecurityScanning func(context.Context, *db.SecurityScanningQuery) error + +// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline. +func (f TraverseSecurityScanning) Intercept(next db.Querier) db.Querier { + return next +} + +// Traverse calls f(ctx, q). +func (f TraverseSecurityScanning) Traverse(ctx context.Context, q db.Query) error { + if q, ok := q.(*db.SecurityScanningQuery); ok { + return f(ctx, q) + } + return fmt.Errorf("unexpected query type %T. expect *db.SecurityScanningQuery", q) +} + +// The SecurityScanningResultFunc type is an adapter to allow the use of ordinary function as a Querier. +type SecurityScanningResultFunc func(context.Context, *db.SecurityScanningResultQuery) (db.Value, error) + +// Query calls f(ctx, q). +func (f SecurityScanningResultFunc) Query(ctx context.Context, q db.Query) (db.Value, error) { + if q, ok := q.(*db.SecurityScanningResultQuery); ok { + return f(ctx, q) + } + return nil, fmt.Errorf("unexpected query type %T. expect *db.SecurityScanningResultQuery", q) +} + +// The TraverseSecurityScanningResult type is an adapter to allow the use of ordinary function as Traverser. +type TraverseSecurityScanningResult func(context.Context, *db.SecurityScanningResultQuery) error + +// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline. +func (f TraverseSecurityScanningResult) Intercept(next db.Querier) db.Querier { + return next +} + +// Traverse calls f(ctx, q). +func (f TraverseSecurityScanningResult) Traverse(ctx context.Context, q db.Query) error { + if q, ok := q.(*db.SecurityScanningResultQuery); ok { + return f(ctx, q) + } + return fmt.Errorf("unexpected query type %T. expect *db.SecurityScanningResultQuery", 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) @@ -714,6 +770,10 @@ func NewQuery(q db.Query) (Query, error) { return &query[*db.ModelProviderQuery, predicate.ModelProvider, modelprovider.OrderOption]{typ: db.TypeModelProvider, tq: q}, nil case *db.ModelProviderModelQuery: return &query[*db.ModelProviderModelQuery, predicate.ModelProviderModel, modelprovidermodel.OrderOption]{typ: db.TypeModelProviderModel, tq: q}, nil + case *db.SecurityScanningQuery: + return &query[*db.SecurityScanningQuery, predicate.SecurityScanning, securityscanning.OrderOption]{typ: db.TypeSecurityScanning, tq: q}, nil + case *db.SecurityScanningResultQuery: + return &query[*db.SecurityScanningResultQuery, predicate.SecurityScanningResult, securityscanningresult.OrderOption]{typ: db.TypeSecurityScanningResult, tq: q}, nil case *db.SettingQuery: return &query[*db.SettingQuery, predicate.Setting, setting.OrderOption]{typ: db.TypeSetting, tq: q}, nil case *db.TaskQuery: diff --git a/backend/db/license/license.go b/backend/db/license/license.go index ba19bcc..b9de07c 100644 --- a/backend/db/license/license.go +++ b/backend/db/license/license.go @@ -9,23 +9,23 @@ import ( ) const ( - // Label 定义数据库中 license 表的标签名称 + // Label holds the string label denoting the license type in the database. Label = "license" - // FieldID 定义数据库中 id 字段的名称 + // FieldID holds the string denoting the id field in the database. FieldID = "id" - // FieldType 定义数据库中 type 字段的名称 + // FieldType holds the string denoting the type field in the database. FieldType = "type" - // FieldData 定义数据库中 data 字段的名称 + // FieldData holds the string denoting the data field in the database. FieldData = "data" - // FieldCode 定义数据库中 code 字段的名称 + // FieldCode holds the string denoting the code field in the database. FieldCode = "code" - // FieldCreatedAt 定义数据库中 created_at 字段的名称 + // FieldCreatedAt holds the string denoting the created_at field in the database. FieldCreatedAt = "created_at" - // Table 定义数据库中 license 表的名称 + // Table holds the table name of the license in the database. Table = "license" ) -// Columns 包含 license 表的所有字段名称 +// Columns holds all SQL columns for license fields. var Columns = []string{ FieldID, FieldType, @@ -34,7 +34,7 @@ var Columns = []string{ FieldCreatedAt, } -// ValidColumn 检查给定的列名是否为有效的 license 表字段 +// 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] { @@ -45,31 +45,31 @@ func ValidColumn(column string) bool { } var ( - // DefaultCreatedAt 定义 created_at 字段在创建时的默认值生成函数 + // DefaultCreatedAt holds the default value on creation for the "created_at" field. DefaultCreatedAt func() time.Time - // IDValidator 是 id 字段的验证器,在保存前由构建器调用 + // IDValidator is a validator for the "id" field. It is called by the builders before save. IDValidator func(int) error ) -// OrderOption 定义 License 查询的排序选项 +// OrderOption defines the ordering options for the License queries. type OrderOption func(*sql.Selector) -// ByID 按 id 字段对结果进行排序 +// ByID orders the results by the id field. func ByID(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldID, opts...).ToFunc() } -// ByType 按 type 字段对结果进行排序 +// ByType orders the results by the type field. func ByType(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldType, opts...).ToFunc() } -// ByCode 按 code 字段对结果进行排序 +// ByCode orders the results by the code field. func ByCode(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldCode, opts...).ToFunc() } -// ByCreatedAt 按 created_at 字段对结果进行排序 +// ByCreatedAt orders the results by the created_at field. func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() } diff --git a/backend/db/license_create.go b/backend/db/license_create.go index 7ec50c5..c751e7c 100644 --- a/backend/db/license_create.go +++ b/backend/db/license_create.go @@ -24,8 +24,8 @@ type LicenseCreate struct { } // SetType sets the "type" field. -func (lc *LicenseCreate) SetType(dt consts.LicenseType) *LicenseCreate { - lc.mutation.SetType(dt) +func (lc *LicenseCreate) SetType(ct consts.LicenseType) *LicenseCreate { + lc.mutation.SetType(ct) return lc } diff --git a/backend/db/license_query.go b/backend/db/license_query.go index 0dfbb90..4e26f7f 100644 --- a/backend/db/license_query.go +++ b/backend/db/license_query.go @@ -265,7 +265,7 @@ func (lq *LicenseQuery) Clone() *LicenseQuery { // Example: // // var v []struct { -// Type domain.LicenseType `json:"type,omitempty"` +// Type consts.LicenseType `json:"type,omitempty"` // Count int `json:"count,omitempty"` // } // @@ -288,7 +288,7 @@ func (lq *LicenseQuery) GroupBy(field string, fields ...string) *LicenseGroupBy // Example: // // var v []struct { -// Type domain.LicenseType `json:"type,omitempty"` +// Type consts.LicenseType `json:"type,omitempty"` // } // // client.License.Query(). diff --git a/backend/db/license_update.go b/backend/db/license_update.go index 0d5c384..4f10fe5 100644 --- a/backend/db/license_update.go +++ b/backend/db/license_update.go @@ -31,15 +31,15 @@ func (lu *LicenseUpdate) Where(ps ...predicate.License) *LicenseUpdate { } // SetType sets the "type" field. -func (lu *LicenseUpdate) SetType(dt consts.LicenseType) *LicenseUpdate { - lu.mutation.SetType(dt) +func (lu *LicenseUpdate) SetType(ct consts.LicenseType) *LicenseUpdate { + lu.mutation.SetType(ct) return lu } // SetNillableType sets the "type" field if the given value is not nil. -func (lu *LicenseUpdate) SetNillableType(dt *consts.LicenseType) *LicenseUpdate { - if dt != nil { - lu.SetType(*dt) +func (lu *LicenseUpdate) SetNillableType(ct *consts.LicenseType) *LicenseUpdate { + if ct != nil { + lu.SetType(*ct) } return lu } @@ -178,15 +178,15 @@ type LicenseUpdateOne struct { } // SetType sets the "type" field. -func (luo *LicenseUpdateOne) SetType(dt consts.LicenseType) *LicenseUpdateOne { - luo.mutation.SetType(dt) +func (luo *LicenseUpdateOne) SetType(ct consts.LicenseType) *LicenseUpdateOne { + luo.mutation.SetType(ct) return luo } // SetNillableType sets the "type" field if the given value is not nil. -func (luo *LicenseUpdateOne) SetNillableType(dt *consts.LicenseType) *LicenseUpdateOne { - if dt != nil { - luo.SetType(*dt) +func (luo *LicenseUpdateOne) SetNillableType(ct *consts.LicenseType) *LicenseUpdateOne { + if ct != nil { + luo.SetType(*ct) } return luo } diff --git a/backend/db/migrate/schema.go b/backend/db/migrate/schema.go index d5aee84..810d87c 100644 --- a/backend/db/migrate/schema.go +++ b/backend/db/migrate/schema.go @@ -320,6 +320,76 @@ var ( }, }, } + // SecurityScanningsColumns holds the columns for the "security_scannings" table. + SecurityScanningsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeUUID}, + {Name: "status", Type: field.TypeString}, + {Name: "workspace", Type: field.TypeString}, + {Name: "language", Type: field.TypeString}, + {Name: "rule", Type: field.TypeString, Nullable: true}, + {Name: "error_message", Type: field.TypeString, Nullable: true}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "user_id", Type: field.TypeUUID}, + {Name: "workspace_id", Type: field.TypeUUID}, + } + // SecurityScanningsTable holds the schema information for the "security_scannings" table. + SecurityScanningsTable = &schema.Table{ + Name: "security_scannings", + Columns: SecurityScanningsColumns, + PrimaryKey: []*schema.Column{SecurityScanningsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "security_scannings_users_security_scannings", + Columns: []*schema.Column{SecurityScanningsColumns[8]}, + RefColumns: []*schema.Column{UsersColumns[0]}, + OnDelete: schema.NoAction, + }, + { + Symbol: "security_scannings_workspaces_security_scannings", + Columns: []*schema.Column{SecurityScanningsColumns[9]}, + RefColumns: []*schema.Column{WorkspacesColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + } + // SecurityScanningResultsColumns holds the columns for the "security_scanning_results" table. + SecurityScanningResultsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeUUID}, + {Name: "check_id", Type: field.TypeString}, + {Name: "engine_kind", Type: field.TypeString}, + {Name: "lines", Type: field.TypeString, Size: 2147483647}, + {Name: "path", Type: field.TypeString, Size: 2147483647}, + {Name: "message", Type: field.TypeString, Size: 2147483647}, + {Name: "message_zh", Type: field.TypeString, Size: 2147483647}, + {Name: "severity", Type: field.TypeString}, + {Name: "abstract_en", Type: field.TypeString, Size: 2147483647}, + {Name: "abstract_zh", Type: field.TypeString, Size: 2147483647}, + {Name: "category_en", Type: field.TypeString, Size: 2147483647}, + {Name: "category_zh", Type: field.TypeString, Size: 2147483647}, + {Name: "confidence", Type: field.TypeString}, + {Name: "cwe", Type: field.TypeJSON}, + {Name: "impact", Type: field.TypeString}, + {Name: "owasp", Type: field.TypeJSON}, + {Name: "start_position", Type: field.TypeJSON}, + {Name: "end_position", Type: field.TypeJSON}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "security_scanning_id", Type: field.TypeUUID}, + } + // SecurityScanningResultsTable holds the schema information for the "security_scanning_results" table. + SecurityScanningResultsTable = &schema.Table{ + Name: "security_scanning_results", + Columns: SecurityScanningResultsColumns, + PrimaryKey: []*schema.Column{SecurityScanningResultsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "security_scanning_results_security_scannings_results", + Columns: []*schema.Column{SecurityScanningResultsColumns[19]}, + RefColumns: []*schema.Column{SecurityScanningsColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + } // SettingsColumns holds the columns for the "settings" table. SettingsColumns = []*schema.Column{ {Name: "id", Type: field.TypeUUID}, @@ -625,6 +695,8 @@ var ( ModelsTable, ModelProvidersTable, ModelProviderModelsTable, + SecurityScanningsTable, + SecurityScanningResultsTable, SettingsTable, TasksTable, TaskRecordsTable, @@ -684,6 +756,15 @@ func init() { ModelProviderModelsTable.Annotation = &entsql.Annotation{ Table: "model_provider_models", } + SecurityScanningsTable.ForeignKeys[0].RefTable = UsersTable + SecurityScanningsTable.ForeignKeys[1].RefTable = WorkspacesTable + SecurityScanningsTable.Annotation = &entsql.Annotation{ + Table: "security_scannings", + } + SecurityScanningResultsTable.ForeignKeys[0].RefTable = SecurityScanningsTable + SecurityScanningResultsTable.Annotation = &entsql.Annotation{ + Table: "security_scanning_results", + } SettingsTable.Annotation = &entsql.Annotation{ Table: "settings", } diff --git a/backend/db/mutation.go b/backend/db/mutation.go index 4fe27f3..b2e7a2c 100644 --- a/backend/db/mutation.go +++ b/backend/db/mutation.go @@ -27,6 +27,8 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/modelprovider" "github.com/chaitin/MonkeyCode/backend/db/modelprovidermodel" "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/securityscanning" + "github.com/chaitin/MonkeyCode/backend/db/securityscanningresult" "github.com/chaitin/MonkeyCode/backend/db/setting" "github.com/chaitin/MonkeyCode/backend/db/task" "github.com/chaitin/MonkeyCode/backend/db/taskrecord" @@ -48,28 +50,30 @@ const ( OpUpdateOne = ent.OpUpdateOne // Node types. - TypeAdmin = "Admin" - TypeAdminLoginHistory = "AdminLoginHistory" - TypeApiKey = "ApiKey" - TypeBillingPlan = "BillingPlan" - TypeBillingQuota = "BillingQuota" - TypeBillingRecord = "BillingRecord" - TypeBillingUsage = "BillingUsage" - TypeCodeSnippet = "CodeSnippet" - TypeExtension = "Extension" - TypeInviteCode = "InviteCode" - TypeLicense = "License" - TypeModel = "Model" - TypeModelProvider = "ModelProvider" - TypeModelProviderModel = "ModelProviderModel" - TypeSetting = "Setting" - TypeTask = "Task" - TypeTaskRecord = "TaskRecord" - TypeUser = "User" - TypeUserIdentity = "UserIdentity" - TypeUserLoginHistory = "UserLoginHistory" - TypeWorkspace = "Workspace" - TypeWorkspaceFile = "WorkspaceFile" + TypeAdmin = "Admin" + TypeAdminLoginHistory = "AdminLoginHistory" + TypeApiKey = "ApiKey" + TypeBillingPlan = "BillingPlan" + TypeBillingQuota = "BillingQuota" + TypeBillingRecord = "BillingRecord" + TypeBillingUsage = "BillingUsage" + TypeCodeSnippet = "CodeSnippet" + TypeExtension = "Extension" + TypeInviteCode = "InviteCode" + TypeLicense = "License" + TypeModel = "Model" + TypeModelProvider = "ModelProvider" + TypeModelProviderModel = "ModelProviderModel" + TypeSecurityScanning = "SecurityScanning" + TypeSecurityScanningResult = "SecurityScanningResult" + TypeSetting = "Setting" + TypeTask = "Task" + TypeTaskRecord = "TaskRecord" + TypeUser = "User" + TypeUserIdentity = "UserIdentity" + TypeUserLoginHistory = "UserLoginHistory" + TypeWorkspace = "Workspace" + TypeWorkspaceFile = "WorkspaceFile" ) // AdminMutation represents an operation that mutates the Admin nodes in the graph. @@ -8319,8 +8323,8 @@ func (m *LicenseMutation) IDs(ctx context.Context) ([]int, error) { } // SetType sets the "type" field. -func (m *LicenseMutation) SetType(dt consts.LicenseType) { - m._type = &dt +func (m *LicenseMutation) SetType(ct consts.LicenseType) { + m._type = &ct } // GetType returns the value of the "type" field in the mutation. @@ -11453,6 +11457,2399 @@ func (m *ModelProviderModelMutation) ResetEdge(name string) error { return fmt.Errorf("unknown ModelProviderModel edge %s", name) } +// SecurityScanningMutation represents an operation that mutates the SecurityScanning nodes in the graph. +type SecurityScanningMutation struct { + config + op Op + typ string + id *uuid.UUID + status *consts.SecurityScanningStatus + workspace *string + language *consts.SecurityScanningLanguage + rule *string + error_message *string + created_at *time.Time + updated_at *time.Time + clearedFields map[string]struct{} + user *uuid.UUID + cleareduser bool + results map[uuid.UUID]struct{} + removedresults map[uuid.UUID]struct{} + clearedresults bool + workspace_edge *uuid.UUID + clearedworkspace_edge bool + done bool + oldValue func(context.Context) (*SecurityScanning, error) + predicates []predicate.SecurityScanning +} + +var _ ent.Mutation = (*SecurityScanningMutation)(nil) + +// securityscanningOption allows management of the mutation configuration using functional options. +type securityscanningOption func(*SecurityScanningMutation) + +// newSecurityScanningMutation creates new mutation for the SecurityScanning entity. +func newSecurityScanningMutation(c config, op Op, opts ...securityscanningOption) *SecurityScanningMutation { + m := &SecurityScanningMutation{ + config: c, + op: op, + typ: TypeSecurityScanning, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withSecurityScanningID sets the ID field of the mutation. +func withSecurityScanningID(id uuid.UUID) securityscanningOption { + return func(m *SecurityScanningMutation) { + var ( + err error + once sync.Once + value *SecurityScanning + ) + m.oldValue = func(ctx context.Context) (*SecurityScanning, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().SecurityScanning.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withSecurityScanning sets the old SecurityScanning of the mutation. +func withSecurityScanning(node *SecurityScanning) securityscanningOption { + return func(m *SecurityScanningMutation) { + m.oldValue = func(context.Context) (*SecurityScanning, 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 SecurityScanningMutation) 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 SecurityScanningMutation) 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 SecurityScanning entities. +func (m *SecurityScanningMutation) 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 *SecurityScanningMutation) 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 *SecurityScanningMutation) 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().SecurityScanning.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 *SecurityScanningMutation) SetUserID(u uuid.UUID) { + m.user = &u +} + +// UserID returns the value of the "user_id" field in the mutation. +func (m *SecurityScanningMutation) 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 SecurityScanning entity. +// If the SecurityScanning 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 *SecurityScanningMutation) 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 *SecurityScanningMutation) ResetUserID() { + m.user = nil +} + +// SetWorkspaceID sets the "workspace_id" field. +func (m *SecurityScanningMutation) SetWorkspaceID(u uuid.UUID) { + m.workspace_edge = &u +} + +// WorkspaceID returns the value of the "workspace_id" field in the mutation. +func (m *SecurityScanningMutation) WorkspaceID() (r uuid.UUID, exists bool) { + v := m.workspace_edge + if v == nil { + return + } + return *v, true +} + +// OldWorkspaceID returns the old "workspace_id" field's value of the SecurityScanning entity. +// If the SecurityScanning 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 *SecurityScanningMutation) OldWorkspaceID(ctx context.Context) (v uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldWorkspaceID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldWorkspaceID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldWorkspaceID: %w", err) + } + return oldValue.WorkspaceID, nil +} + +// ResetWorkspaceID resets all changes to the "workspace_id" field. +func (m *SecurityScanningMutation) ResetWorkspaceID() { + m.workspace_edge = nil +} + +// SetStatus sets the "status" field. +func (m *SecurityScanningMutation) SetStatus(css consts.SecurityScanningStatus) { + m.status = &css +} + +// Status returns the value of the "status" field in the mutation. +func (m *SecurityScanningMutation) Status() (r consts.SecurityScanningStatus, exists bool) { + v := m.status + if v == nil { + return + } + return *v, true +} + +// OldStatus returns the old "status" field's value of the SecurityScanning entity. +// If the SecurityScanning 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 *SecurityScanningMutation) OldStatus(ctx context.Context) (v consts.SecurityScanningStatus, 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 *SecurityScanningMutation) ResetStatus() { + m.status = nil +} + +// SetWorkspace sets the "workspace" field. +func (m *SecurityScanningMutation) SetWorkspace(s string) { + m.workspace = &s +} + +// Workspace returns the value of the "workspace" field in the mutation. +func (m *SecurityScanningMutation) Workspace() (r string, exists bool) { + v := m.workspace + if v == nil { + return + } + return *v, true +} + +// OldWorkspace returns the old "workspace" field's value of the SecurityScanning entity. +// If the SecurityScanning 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 *SecurityScanningMutation) OldWorkspace(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldWorkspace is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldWorkspace requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldWorkspace: %w", err) + } + return oldValue.Workspace, nil +} + +// ResetWorkspace resets all changes to the "workspace" field. +func (m *SecurityScanningMutation) ResetWorkspace() { + m.workspace = nil +} + +// SetLanguage sets the "language" field. +func (m *SecurityScanningMutation) SetLanguage(csl consts.SecurityScanningLanguage) { + m.language = &csl +} + +// Language returns the value of the "language" field in the mutation. +func (m *SecurityScanningMutation) Language() (r consts.SecurityScanningLanguage, exists bool) { + v := m.language + if v == nil { + return + } + return *v, true +} + +// OldLanguage returns the old "language" field's value of the SecurityScanning entity. +// If the SecurityScanning 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 *SecurityScanningMutation) OldLanguage(ctx context.Context) (v consts.SecurityScanningLanguage, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldLanguage is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldLanguage requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldLanguage: %w", err) + } + return oldValue.Language, nil +} + +// ResetLanguage resets all changes to the "language" field. +func (m *SecurityScanningMutation) ResetLanguage() { + m.language = nil +} + +// SetRule sets the "rule" field. +func (m *SecurityScanningMutation) SetRule(s string) { + m.rule = &s +} + +// Rule returns the value of the "rule" field in the mutation. +func (m *SecurityScanningMutation) Rule() (r string, exists bool) { + v := m.rule + if v == nil { + return + } + return *v, true +} + +// OldRule returns the old "rule" field's value of the SecurityScanning entity. +// If the SecurityScanning 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 *SecurityScanningMutation) OldRule(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRule is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRule requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRule: %w", err) + } + return oldValue.Rule, nil +} + +// ClearRule clears the value of the "rule" field. +func (m *SecurityScanningMutation) ClearRule() { + m.rule = nil + m.clearedFields[securityscanning.FieldRule] = struct{}{} +} + +// RuleCleared returns if the "rule" field was cleared in this mutation. +func (m *SecurityScanningMutation) RuleCleared() bool { + _, ok := m.clearedFields[securityscanning.FieldRule] + return ok +} + +// ResetRule resets all changes to the "rule" field. +func (m *SecurityScanningMutation) ResetRule() { + m.rule = nil + delete(m.clearedFields, securityscanning.FieldRule) +} + +// SetErrorMessage sets the "error_message" field. +func (m *SecurityScanningMutation) SetErrorMessage(s string) { + m.error_message = &s +} + +// ErrorMessage returns the value of the "error_message" field in the mutation. +func (m *SecurityScanningMutation) ErrorMessage() (r string, exists bool) { + v := m.error_message + if v == nil { + return + } + return *v, true +} + +// OldErrorMessage returns the old "error_message" field's value of the SecurityScanning entity. +// If the SecurityScanning 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 *SecurityScanningMutation) OldErrorMessage(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldErrorMessage is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldErrorMessage requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldErrorMessage: %w", err) + } + return oldValue.ErrorMessage, nil +} + +// ClearErrorMessage clears the value of the "error_message" field. +func (m *SecurityScanningMutation) ClearErrorMessage() { + m.error_message = nil + m.clearedFields[securityscanning.FieldErrorMessage] = struct{}{} +} + +// ErrorMessageCleared returns if the "error_message" field was cleared in this mutation. +func (m *SecurityScanningMutation) ErrorMessageCleared() bool { + _, ok := m.clearedFields[securityscanning.FieldErrorMessage] + return ok +} + +// ResetErrorMessage resets all changes to the "error_message" field. +func (m *SecurityScanningMutation) ResetErrorMessage() { + m.error_message = nil + delete(m.clearedFields, securityscanning.FieldErrorMessage) +} + +// SetCreatedAt sets the "created_at" field. +func (m *SecurityScanningMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *SecurityScanningMutation) 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 SecurityScanning entity. +// If the SecurityScanning 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 *SecurityScanningMutation) 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 *SecurityScanningMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *SecurityScanningMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *SecurityScanningMutation) 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 SecurityScanning entity. +// If the SecurityScanning 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 *SecurityScanningMutation) 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 *SecurityScanningMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// ClearUser clears the "user" edge to the User entity. +func (m *SecurityScanningMutation) ClearUser() { + m.cleareduser = true + m.clearedFields[securityscanning.FieldUserID] = struct{}{} +} + +// UserCleared reports if the "user" edge to the User entity was cleared. +func (m *SecurityScanningMutation) UserCleared() bool { + return m.cleareduser +} + +// UserIDs returns the "user" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// UserID instead. It exists only for internal usage by the builders. +func (m *SecurityScanningMutation) 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 *SecurityScanningMutation) ResetUser() { + m.user = nil + m.cleareduser = false +} + +// AddResultIDs adds the "results" edge to the SecurityScanningResult entity by ids. +func (m *SecurityScanningMutation) AddResultIDs(ids ...uuid.UUID) { + if m.results == nil { + m.results = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.results[ids[i]] = struct{}{} + } +} + +// ClearResults clears the "results" edge to the SecurityScanningResult entity. +func (m *SecurityScanningMutation) ClearResults() { + m.clearedresults = true +} + +// ResultsCleared reports if the "results" edge to the SecurityScanningResult entity was cleared. +func (m *SecurityScanningMutation) ResultsCleared() bool { + return m.clearedresults +} + +// RemoveResultIDs removes the "results" edge to the SecurityScanningResult entity by IDs. +func (m *SecurityScanningMutation) RemoveResultIDs(ids ...uuid.UUID) { + if m.removedresults == nil { + m.removedresults = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.results, ids[i]) + m.removedresults[ids[i]] = struct{}{} + } +} + +// RemovedResults returns the removed IDs of the "results" edge to the SecurityScanningResult entity. +func (m *SecurityScanningMutation) RemovedResultsIDs() (ids []uuid.UUID) { + for id := range m.removedresults { + ids = append(ids, id) + } + return +} + +// ResultsIDs returns the "results" edge IDs in the mutation. +func (m *SecurityScanningMutation) ResultsIDs() (ids []uuid.UUID) { + for id := range m.results { + ids = append(ids, id) + } + return +} + +// ResetResults resets all changes to the "results" edge. +func (m *SecurityScanningMutation) ResetResults() { + m.results = nil + m.clearedresults = false + m.removedresults = nil +} + +// SetWorkspaceEdgeID sets the "workspace_edge" edge to the Workspace entity by id. +func (m *SecurityScanningMutation) SetWorkspaceEdgeID(id uuid.UUID) { + m.workspace_edge = &id +} + +// ClearWorkspaceEdge clears the "workspace_edge" edge to the Workspace entity. +func (m *SecurityScanningMutation) ClearWorkspaceEdge() { + m.clearedworkspace_edge = true + m.clearedFields[securityscanning.FieldWorkspaceID] = struct{}{} +} + +// WorkspaceEdgeCleared reports if the "workspace_edge" edge to the Workspace entity was cleared. +func (m *SecurityScanningMutation) WorkspaceEdgeCleared() bool { + return m.clearedworkspace_edge +} + +// WorkspaceEdgeID returns the "workspace_edge" edge ID in the mutation. +func (m *SecurityScanningMutation) WorkspaceEdgeID() (id uuid.UUID, exists bool) { + if m.workspace_edge != nil { + return *m.workspace_edge, true + } + return +} + +// WorkspaceEdgeIDs returns the "workspace_edge" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// WorkspaceEdgeID instead. It exists only for internal usage by the builders. +func (m *SecurityScanningMutation) WorkspaceEdgeIDs() (ids []uuid.UUID) { + if id := m.workspace_edge; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetWorkspaceEdge resets all changes to the "workspace_edge" edge. +func (m *SecurityScanningMutation) ResetWorkspaceEdge() { + m.workspace_edge = nil + m.clearedworkspace_edge = false +} + +// Where appends a list predicates to the SecurityScanningMutation builder. +func (m *SecurityScanningMutation) Where(ps ...predicate.SecurityScanning) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the SecurityScanningMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *SecurityScanningMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.SecurityScanning, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *SecurityScanningMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *SecurityScanningMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (SecurityScanning). +func (m *SecurityScanningMutation) 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 *SecurityScanningMutation) Fields() []string { + fields := make([]string, 0, 9) + if m.user != nil { + fields = append(fields, securityscanning.FieldUserID) + } + if m.workspace_edge != nil { + fields = append(fields, securityscanning.FieldWorkspaceID) + } + if m.status != nil { + fields = append(fields, securityscanning.FieldStatus) + } + if m.workspace != nil { + fields = append(fields, securityscanning.FieldWorkspace) + } + if m.language != nil { + fields = append(fields, securityscanning.FieldLanguage) + } + if m.rule != nil { + fields = append(fields, securityscanning.FieldRule) + } + if m.error_message != nil { + fields = append(fields, securityscanning.FieldErrorMessage) + } + if m.created_at != nil { + fields = append(fields, securityscanning.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, securityscanning.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 *SecurityScanningMutation) Field(name string) (ent.Value, bool) { + switch name { + case securityscanning.FieldUserID: + return m.UserID() + case securityscanning.FieldWorkspaceID: + return m.WorkspaceID() + case securityscanning.FieldStatus: + return m.Status() + case securityscanning.FieldWorkspace: + return m.Workspace() + case securityscanning.FieldLanguage: + return m.Language() + case securityscanning.FieldRule: + return m.Rule() + case securityscanning.FieldErrorMessage: + return m.ErrorMessage() + case securityscanning.FieldCreatedAt: + return m.CreatedAt() + case securityscanning.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 *SecurityScanningMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case securityscanning.FieldUserID: + return m.OldUserID(ctx) + case securityscanning.FieldWorkspaceID: + return m.OldWorkspaceID(ctx) + case securityscanning.FieldStatus: + return m.OldStatus(ctx) + case securityscanning.FieldWorkspace: + return m.OldWorkspace(ctx) + case securityscanning.FieldLanguage: + return m.OldLanguage(ctx) + case securityscanning.FieldRule: + return m.OldRule(ctx) + case securityscanning.FieldErrorMessage: + return m.OldErrorMessage(ctx) + case securityscanning.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case securityscanning.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + } + return nil, fmt.Errorf("unknown SecurityScanning 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 *SecurityScanningMutation) SetField(name string, value ent.Value) error { + switch name { + case securityscanning.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 securityscanning.FieldWorkspaceID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetWorkspaceID(v) + return nil + case securityscanning.FieldStatus: + v, ok := value.(consts.SecurityScanningStatus) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStatus(v) + return nil + case securityscanning.FieldWorkspace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetWorkspace(v) + return nil + case securityscanning.FieldLanguage: + v, ok := value.(consts.SecurityScanningLanguage) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLanguage(v) + return nil + case securityscanning.FieldRule: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRule(v) + return nil + case securityscanning.FieldErrorMessage: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetErrorMessage(v) + return nil + case securityscanning.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 securityscanning.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 SecurityScanning field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *SecurityScanningMutation) 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 *SecurityScanningMutation) 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 *SecurityScanningMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown SecurityScanning numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *SecurityScanningMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(securityscanning.FieldRule) { + fields = append(fields, securityscanning.FieldRule) + } + if m.FieldCleared(securityscanning.FieldErrorMessage) { + fields = append(fields, securityscanning.FieldErrorMessage) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *SecurityScanningMutation) 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 *SecurityScanningMutation) ClearField(name string) error { + switch name { + case securityscanning.FieldRule: + m.ClearRule() + return nil + case securityscanning.FieldErrorMessage: + m.ClearErrorMessage() + return nil + } + return fmt.Errorf("unknown SecurityScanning 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 *SecurityScanningMutation) ResetField(name string) error { + switch name { + case securityscanning.FieldUserID: + m.ResetUserID() + return nil + case securityscanning.FieldWorkspaceID: + m.ResetWorkspaceID() + return nil + case securityscanning.FieldStatus: + m.ResetStatus() + return nil + case securityscanning.FieldWorkspace: + m.ResetWorkspace() + return nil + case securityscanning.FieldLanguage: + m.ResetLanguage() + return nil + case securityscanning.FieldRule: + m.ResetRule() + return nil + case securityscanning.FieldErrorMessage: + m.ResetErrorMessage() + return nil + case securityscanning.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case securityscanning.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + } + return fmt.Errorf("unknown SecurityScanning field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *SecurityScanningMutation) AddedEdges() []string { + edges := make([]string, 0, 3) + if m.user != nil { + edges = append(edges, securityscanning.EdgeUser) + } + if m.results != nil { + edges = append(edges, securityscanning.EdgeResults) + } + if m.workspace_edge != nil { + edges = append(edges, securityscanning.EdgeWorkspaceEdge) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *SecurityScanningMutation) AddedIDs(name string) []ent.Value { + switch name { + case securityscanning.EdgeUser: + if id := m.user; id != nil { + return []ent.Value{*id} + } + case securityscanning.EdgeResults: + ids := make([]ent.Value, 0, len(m.results)) + for id := range m.results { + ids = append(ids, id) + } + return ids + case securityscanning.EdgeWorkspaceEdge: + if id := m.workspace_edge; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *SecurityScanningMutation) RemovedEdges() []string { + edges := make([]string, 0, 3) + if m.removedresults != nil { + edges = append(edges, securityscanning.EdgeResults) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *SecurityScanningMutation) RemovedIDs(name string) []ent.Value { + switch name { + case securityscanning.EdgeResults: + ids := make([]ent.Value, 0, len(m.removedresults)) + for id := range m.removedresults { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *SecurityScanningMutation) ClearedEdges() []string { + edges := make([]string, 0, 3) + if m.cleareduser { + edges = append(edges, securityscanning.EdgeUser) + } + if m.clearedresults { + edges = append(edges, securityscanning.EdgeResults) + } + if m.clearedworkspace_edge { + edges = append(edges, securityscanning.EdgeWorkspaceEdge) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *SecurityScanningMutation) EdgeCleared(name string) bool { + switch name { + case securityscanning.EdgeUser: + return m.cleareduser + case securityscanning.EdgeResults: + return m.clearedresults + case securityscanning.EdgeWorkspaceEdge: + return m.clearedworkspace_edge + } + 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 *SecurityScanningMutation) ClearEdge(name string) error { + switch name { + case securityscanning.EdgeUser: + m.ClearUser() + return nil + case securityscanning.EdgeWorkspaceEdge: + m.ClearWorkspaceEdge() + return nil + } + return fmt.Errorf("unknown SecurityScanning 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 *SecurityScanningMutation) ResetEdge(name string) error { + switch name { + case securityscanning.EdgeUser: + m.ResetUser() + return nil + case securityscanning.EdgeResults: + m.ResetResults() + return nil + case securityscanning.EdgeWorkspaceEdge: + m.ResetWorkspaceEdge() + return nil + } + return fmt.Errorf("unknown SecurityScanning edge %s", name) +} + +// SecurityScanningResultMutation represents an operation that mutates the SecurityScanningResult nodes in the graph. +type SecurityScanningResultMutation struct { + config + op Op + typ string + id *uuid.UUID + check_id *string + engine_kind *string + lines *string + _path *string + message *string + message_zh *string + severity *string + abstract_en *string + abstract_zh *string + category_en *string + category_zh *string + confidence *string + cwe *[]interface{} + appendcwe []interface{} + impact *string + owasp *[]interface{} + appendowasp []interface{} + start_position **types.Position + end_position **types.Position + created_at *time.Time + clearedFields map[string]struct{} + security_scanning *uuid.UUID + clearedsecurity_scanning bool + done bool + oldValue func(context.Context) (*SecurityScanningResult, error) + predicates []predicate.SecurityScanningResult +} + +var _ ent.Mutation = (*SecurityScanningResultMutation)(nil) + +// securityscanningresultOption allows management of the mutation configuration using functional options. +type securityscanningresultOption func(*SecurityScanningResultMutation) + +// newSecurityScanningResultMutation creates new mutation for the SecurityScanningResult entity. +func newSecurityScanningResultMutation(c config, op Op, opts ...securityscanningresultOption) *SecurityScanningResultMutation { + m := &SecurityScanningResultMutation{ + config: c, + op: op, + typ: TypeSecurityScanningResult, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withSecurityScanningResultID sets the ID field of the mutation. +func withSecurityScanningResultID(id uuid.UUID) securityscanningresultOption { + return func(m *SecurityScanningResultMutation) { + var ( + err error + once sync.Once + value *SecurityScanningResult + ) + m.oldValue = func(ctx context.Context) (*SecurityScanningResult, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().SecurityScanningResult.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withSecurityScanningResult sets the old SecurityScanningResult of the mutation. +func withSecurityScanningResult(node *SecurityScanningResult) securityscanningresultOption { + return func(m *SecurityScanningResultMutation) { + m.oldValue = func(context.Context) (*SecurityScanningResult, 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 SecurityScanningResultMutation) 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 SecurityScanningResultMutation) 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 SecurityScanningResult entities. +func (m *SecurityScanningResultMutation) 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 *SecurityScanningResultMutation) 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 *SecurityScanningResultMutation) 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().SecurityScanningResult.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetSecurityScanningID sets the "security_scanning_id" field. +func (m *SecurityScanningResultMutation) SetSecurityScanningID(u uuid.UUID) { + m.security_scanning = &u +} + +// SecurityScanningID returns the value of the "security_scanning_id" field in the mutation. +func (m *SecurityScanningResultMutation) SecurityScanningID() (r uuid.UUID, exists bool) { + v := m.security_scanning + if v == nil { + return + } + return *v, true +} + +// OldSecurityScanningID returns the old "security_scanning_id" field's value of the SecurityScanningResult entity. +// If the SecurityScanningResult 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 *SecurityScanningResultMutation) OldSecurityScanningID(ctx context.Context) (v uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSecurityScanningID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSecurityScanningID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSecurityScanningID: %w", err) + } + return oldValue.SecurityScanningID, nil +} + +// ResetSecurityScanningID resets all changes to the "security_scanning_id" field. +func (m *SecurityScanningResultMutation) ResetSecurityScanningID() { + m.security_scanning = nil +} + +// SetCheckID sets the "check_id" field. +func (m *SecurityScanningResultMutation) SetCheckID(s string) { + m.check_id = &s +} + +// CheckID returns the value of the "check_id" field in the mutation. +func (m *SecurityScanningResultMutation) CheckID() (r string, exists bool) { + v := m.check_id + if v == nil { + return + } + return *v, true +} + +// OldCheckID returns the old "check_id" field's value of the SecurityScanningResult entity. +// If the SecurityScanningResult 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 *SecurityScanningResultMutation) OldCheckID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCheckID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCheckID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCheckID: %w", err) + } + return oldValue.CheckID, nil +} + +// ResetCheckID resets all changes to the "check_id" field. +func (m *SecurityScanningResultMutation) ResetCheckID() { + m.check_id = nil +} + +// SetEngineKind sets the "engine_kind" field. +func (m *SecurityScanningResultMutation) SetEngineKind(s string) { + m.engine_kind = &s +} + +// EngineKind returns the value of the "engine_kind" field in the mutation. +func (m *SecurityScanningResultMutation) EngineKind() (r string, exists bool) { + v := m.engine_kind + if v == nil { + return + } + return *v, true +} + +// OldEngineKind returns the old "engine_kind" field's value of the SecurityScanningResult entity. +// If the SecurityScanningResult 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 *SecurityScanningResultMutation) OldEngineKind(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEngineKind is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEngineKind requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEngineKind: %w", err) + } + return oldValue.EngineKind, nil +} + +// ResetEngineKind resets all changes to the "engine_kind" field. +func (m *SecurityScanningResultMutation) ResetEngineKind() { + m.engine_kind = nil +} + +// SetLines sets the "lines" field. +func (m *SecurityScanningResultMutation) SetLines(s string) { + m.lines = &s +} + +// Lines returns the value of the "lines" field in the mutation. +func (m *SecurityScanningResultMutation) Lines() (r string, exists bool) { + v := m.lines + if v == nil { + return + } + return *v, true +} + +// OldLines returns the old "lines" field's value of the SecurityScanningResult entity. +// If the SecurityScanningResult 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 *SecurityScanningResultMutation) OldLines(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldLines is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldLines requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldLines: %w", err) + } + return oldValue.Lines, nil +} + +// ResetLines resets all changes to the "lines" field. +func (m *SecurityScanningResultMutation) ResetLines() { + m.lines = nil +} + +// SetPath sets the "path" field. +func (m *SecurityScanningResultMutation) SetPath(s string) { + m._path = &s +} + +// Path returns the value of the "path" field in the mutation. +func (m *SecurityScanningResultMutation) Path() (r string, exists bool) { + v := m._path + if v == nil { + return + } + return *v, true +} + +// OldPath returns the old "path" field's value of the SecurityScanningResult entity. +// If the SecurityScanningResult 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 *SecurityScanningResultMutation) OldPath(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPath is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPath requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPath: %w", err) + } + return oldValue.Path, nil +} + +// ResetPath resets all changes to the "path" field. +func (m *SecurityScanningResultMutation) ResetPath() { + m._path = nil +} + +// SetMessage sets the "message" field. +func (m *SecurityScanningResultMutation) SetMessage(s string) { + m.message = &s +} + +// Message returns the value of the "message" field in the mutation. +func (m *SecurityScanningResultMutation) Message() (r string, exists bool) { + v := m.message + if v == nil { + return + } + return *v, true +} + +// OldMessage returns the old "message" field's value of the SecurityScanningResult entity. +// If the SecurityScanningResult 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 *SecurityScanningResultMutation) OldMessage(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMessage is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMessage requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMessage: %w", err) + } + return oldValue.Message, nil +} + +// ResetMessage resets all changes to the "message" field. +func (m *SecurityScanningResultMutation) ResetMessage() { + m.message = nil +} + +// SetMessageZh sets the "message_zh" field. +func (m *SecurityScanningResultMutation) SetMessageZh(s string) { + m.message_zh = &s +} + +// MessageZh returns the value of the "message_zh" field in the mutation. +func (m *SecurityScanningResultMutation) MessageZh() (r string, exists bool) { + v := m.message_zh + if v == nil { + return + } + return *v, true +} + +// OldMessageZh returns the old "message_zh" field's value of the SecurityScanningResult entity. +// If the SecurityScanningResult 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 *SecurityScanningResultMutation) OldMessageZh(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMessageZh is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMessageZh requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMessageZh: %w", err) + } + return oldValue.MessageZh, nil +} + +// ResetMessageZh resets all changes to the "message_zh" field. +func (m *SecurityScanningResultMutation) ResetMessageZh() { + m.message_zh = nil +} + +// SetSeverity sets the "severity" field. +func (m *SecurityScanningResultMutation) SetSeverity(s string) { + m.severity = &s +} + +// Severity returns the value of the "severity" field in the mutation. +func (m *SecurityScanningResultMutation) Severity() (r string, exists bool) { + v := m.severity + if v == nil { + return + } + return *v, true +} + +// OldSeverity returns the old "severity" field's value of the SecurityScanningResult entity. +// If the SecurityScanningResult 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 *SecurityScanningResultMutation) OldSeverity(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSeverity is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSeverity requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSeverity: %w", err) + } + return oldValue.Severity, nil +} + +// ResetSeverity resets all changes to the "severity" field. +func (m *SecurityScanningResultMutation) ResetSeverity() { + m.severity = nil +} + +// SetAbstractEn sets the "abstract_en" field. +func (m *SecurityScanningResultMutation) SetAbstractEn(s string) { + m.abstract_en = &s +} + +// AbstractEn returns the value of the "abstract_en" field in the mutation. +func (m *SecurityScanningResultMutation) AbstractEn() (r string, exists bool) { + v := m.abstract_en + if v == nil { + return + } + return *v, true +} + +// OldAbstractEn returns the old "abstract_en" field's value of the SecurityScanningResult entity. +// If the SecurityScanningResult 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 *SecurityScanningResultMutation) OldAbstractEn(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAbstractEn is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAbstractEn requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAbstractEn: %w", err) + } + return oldValue.AbstractEn, nil +} + +// ResetAbstractEn resets all changes to the "abstract_en" field. +func (m *SecurityScanningResultMutation) ResetAbstractEn() { + m.abstract_en = nil +} + +// SetAbstractZh sets the "abstract_zh" field. +func (m *SecurityScanningResultMutation) SetAbstractZh(s string) { + m.abstract_zh = &s +} + +// AbstractZh returns the value of the "abstract_zh" field in the mutation. +func (m *SecurityScanningResultMutation) AbstractZh() (r string, exists bool) { + v := m.abstract_zh + if v == nil { + return + } + return *v, true +} + +// OldAbstractZh returns the old "abstract_zh" field's value of the SecurityScanningResult entity. +// If the SecurityScanningResult 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 *SecurityScanningResultMutation) OldAbstractZh(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAbstractZh is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAbstractZh requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAbstractZh: %w", err) + } + return oldValue.AbstractZh, nil +} + +// ResetAbstractZh resets all changes to the "abstract_zh" field. +func (m *SecurityScanningResultMutation) ResetAbstractZh() { + m.abstract_zh = nil +} + +// SetCategoryEn sets the "category_en" field. +func (m *SecurityScanningResultMutation) SetCategoryEn(s string) { + m.category_en = &s +} + +// CategoryEn returns the value of the "category_en" field in the mutation. +func (m *SecurityScanningResultMutation) CategoryEn() (r string, exists bool) { + v := m.category_en + if v == nil { + return + } + return *v, true +} + +// OldCategoryEn returns the old "category_en" field's value of the SecurityScanningResult entity. +// If the SecurityScanningResult 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 *SecurityScanningResultMutation) OldCategoryEn(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCategoryEn is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCategoryEn requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCategoryEn: %w", err) + } + return oldValue.CategoryEn, nil +} + +// ResetCategoryEn resets all changes to the "category_en" field. +func (m *SecurityScanningResultMutation) ResetCategoryEn() { + m.category_en = nil +} + +// SetCategoryZh sets the "category_zh" field. +func (m *SecurityScanningResultMutation) SetCategoryZh(s string) { + m.category_zh = &s +} + +// CategoryZh returns the value of the "category_zh" field in the mutation. +func (m *SecurityScanningResultMutation) CategoryZh() (r string, exists bool) { + v := m.category_zh + if v == nil { + return + } + return *v, true +} + +// OldCategoryZh returns the old "category_zh" field's value of the SecurityScanningResult entity. +// If the SecurityScanningResult 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 *SecurityScanningResultMutation) OldCategoryZh(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCategoryZh is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCategoryZh requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCategoryZh: %w", err) + } + return oldValue.CategoryZh, nil +} + +// ResetCategoryZh resets all changes to the "category_zh" field. +func (m *SecurityScanningResultMutation) ResetCategoryZh() { + m.category_zh = nil +} + +// SetConfidence sets the "confidence" field. +func (m *SecurityScanningResultMutation) SetConfidence(s string) { + m.confidence = &s +} + +// Confidence returns the value of the "confidence" field in the mutation. +func (m *SecurityScanningResultMutation) Confidence() (r string, exists bool) { + v := m.confidence + if v == nil { + return + } + return *v, true +} + +// OldConfidence returns the old "confidence" field's value of the SecurityScanningResult entity. +// If the SecurityScanningResult 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 *SecurityScanningResultMutation) OldConfidence(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldConfidence is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldConfidence requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldConfidence: %w", err) + } + return oldValue.Confidence, nil +} + +// ResetConfidence resets all changes to the "confidence" field. +func (m *SecurityScanningResultMutation) ResetConfidence() { + m.confidence = nil +} + +// SetCwe sets the "cwe" field. +func (m *SecurityScanningResultMutation) SetCwe(i []interface{}) { + m.cwe = &i + m.appendcwe = nil +} + +// Cwe returns the value of the "cwe" field in the mutation. +func (m *SecurityScanningResultMutation) Cwe() (r []interface{}, exists bool) { + v := m.cwe + if v == nil { + return + } + return *v, true +} + +// OldCwe returns the old "cwe" field's value of the SecurityScanningResult entity. +// If the SecurityScanningResult 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 *SecurityScanningResultMutation) OldCwe(ctx context.Context) (v []interface{}, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCwe is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCwe requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCwe: %w", err) + } + return oldValue.Cwe, nil +} + +// AppendCwe adds i to the "cwe" field. +func (m *SecurityScanningResultMutation) AppendCwe(i []interface{}) { + m.appendcwe = append(m.appendcwe, i...) +} + +// AppendedCwe returns the list of values that were appended to the "cwe" field in this mutation. +func (m *SecurityScanningResultMutation) AppendedCwe() ([]interface{}, bool) { + if len(m.appendcwe) == 0 { + return nil, false + } + return m.appendcwe, true +} + +// ResetCwe resets all changes to the "cwe" field. +func (m *SecurityScanningResultMutation) ResetCwe() { + m.cwe = nil + m.appendcwe = nil +} + +// SetImpact sets the "impact" field. +func (m *SecurityScanningResultMutation) SetImpact(s string) { + m.impact = &s +} + +// Impact returns the value of the "impact" field in the mutation. +func (m *SecurityScanningResultMutation) Impact() (r string, exists bool) { + v := m.impact + if v == nil { + return + } + return *v, true +} + +// OldImpact returns the old "impact" field's value of the SecurityScanningResult entity. +// If the SecurityScanningResult 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 *SecurityScanningResultMutation) OldImpact(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldImpact is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldImpact requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldImpact: %w", err) + } + return oldValue.Impact, nil +} + +// ResetImpact resets all changes to the "impact" field. +func (m *SecurityScanningResultMutation) ResetImpact() { + m.impact = nil +} + +// SetOwasp sets the "owasp" field. +func (m *SecurityScanningResultMutation) SetOwasp(i []interface{}) { + m.owasp = &i + m.appendowasp = nil +} + +// Owasp returns the value of the "owasp" field in the mutation. +func (m *SecurityScanningResultMutation) Owasp() (r []interface{}, exists bool) { + v := m.owasp + if v == nil { + return + } + return *v, true +} + +// OldOwasp returns the old "owasp" field's value of the SecurityScanningResult entity. +// If the SecurityScanningResult 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 *SecurityScanningResultMutation) OldOwasp(ctx context.Context) (v []interface{}, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldOwasp is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldOwasp requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldOwasp: %w", err) + } + return oldValue.Owasp, nil +} + +// AppendOwasp adds i to the "owasp" field. +func (m *SecurityScanningResultMutation) AppendOwasp(i []interface{}) { + m.appendowasp = append(m.appendowasp, i...) +} + +// AppendedOwasp returns the list of values that were appended to the "owasp" field in this mutation. +func (m *SecurityScanningResultMutation) AppendedOwasp() ([]interface{}, bool) { + if len(m.appendowasp) == 0 { + return nil, false + } + return m.appendowasp, true +} + +// ResetOwasp resets all changes to the "owasp" field. +func (m *SecurityScanningResultMutation) ResetOwasp() { + m.owasp = nil + m.appendowasp = nil +} + +// SetStartPosition sets the "start_position" field. +func (m *SecurityScanningResultMutation) SetStartPosition(t *types.Position) { + m.start_position = &t +} + +// StartPosition returns the value of the "start_position" field in the mutation. +func (m *SecurityScanningResultMutation) StartPosition() (r *types.Position, exists bool) { + v := m.start_position + if v == nil { + return + } + return *v, true +} + +// OldStartPosition returns the old "start_position" field's value of the SecurityScanningResult entity. +// If the SecurityScanningResult 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 *SecurityScanningResultMutation) OldStartPosition(ctx context.Context) (v *types.Position, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldStartPosition is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldStartPosition requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldStartPosition: %w", err) + } + return oldValue.StartPosition, nil +} + +// ResetStartPosition resets all changes to the "start_position" field. +func (m *SecurityScanningResultMutation) ResetStartPosition() { + m.start_position = nil +} + +// SetEndPosition sets the "end_position" field. +func (m *SecurityScanningResultMutation) SetEndPosition(t *types.Position) { + m.end_position = &t +} + +// EndPosition returns the value of the "end_position" field in the mutation. +func (m *SecurityScanningResultMutation) EndPosition() (r *types.Position, exists bool) { + v := m.end_position + if v == nil { + return + } + return *v, true +} + +// OldEndPosition returns the old "end_position" field's value of the SecurityScanningResult entity. +// If the SecurityScanningResult 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 *SecurityScanningResultMutation) OldEndPosition(ctx context.Context) (v *types.Position, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEndPosition is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEndPosition requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEndPosition: %w", err) + } + return oldValue.EndPosition, nil +} + +// ResetEndPosition resets all changes to the "end_position" field. +func (m *SecurityScanningResultMutation) ResetEndPosition() { + m.end_position = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *SecurityScanningResultMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *SecurityScanningResultMutation) 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 SecurityScanningResult entity. +// If the SecurityScanningResult 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 *SecurityScanningResultMutation) 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 *SecurityScanningResultMutation) ResetCreatedAt() { + m.created_at = nil +} + +// ClearSecurityScanning clears the "security_scanning" edge to the SecurityScanning entity. +func (m *SecurityScanningResultMutation) ClearSecurityScanning() { + m.clearedsecurity_scanning = true + m.clearedFields[securityscanningresult.FieldSecurityScanningID] = struct{}{} +} + +// SecurityScanningCleared reports if the "security_scanning" edge to the SecurityScanning entity was cleared. +func (m *SecurityScanningResultMutation) SecurityScanningCleared() bool { + return m.clearedsecurity_scanning +} + +// SecurityScanningIDs returns the "security_scanning" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// SecurityScanningID instead. It exists only for internal usage by the builders. +func (m *SecurityScanningResultMutation) SecurityScanningIDs() (ids []uuid.UUID) { + if id := m.security_scanning; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetSecurityScanning resets all changes to the "security_scanning" edge. +func (m *SecurityScanningResultMutation) ResetSecurityScanning() { + m.security_scanning = nil + m.clearedsecurity_scanning = false +} + +// Where appends a list predicates to the SecurityScanningResultMutation builder. +func (m *SecurityScanningResultMutation) Where(ps ...predicate.SecurityScanningResult) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the SecurityScanningResultMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *SecurityScanningResultMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.SecurityScanningResult, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *SecurityScanningResultMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *SecurityScanningResultMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (SecurityScanningResult). +func (m *SecurityScanningResultMutation) 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 *SecurityScanningResultMutation) Fields() []string { + fields := make([]string, 0, 19) + if m.security_scanning != nil { + fields = append(fields, securityscanningresult.FieldSecurityScanningID) + } + if m.check_id != nil { + fields = append(fields, securityscanningresult.FieldCheckID) + } + if m.engine_kind != nil { + fields = append(fields, securityscanningresult.FieldEngineKind) + } + if m.lines != nil { + fields = append(fields, securityscanningresult.FieldLines) + } + if m._path != nil { + fields = append(fields, securityscanningresult.FieldPath) + } + if m.message != nil { + fields = append(fields, securityscanningresult.FieldMessage) + } + if m.message_zh != nil { + fields = append(fields, securityscanningresult.FieldMessageZh) + } + if m.severity != nil { + fields = append(fields, securityscanningresult.FieldSeverity) + } + if m.abstract_en != nil { + fields = append(fields, securityscanningresult.FieldAbstractEn) + } + if m.abstract_zh != nil { + fields = append(fields, securityscanningresult.FieldAbstractZh) + } + if m.category_en != nil { + fields = append(fields, securityscanningresult.FieldCategoryEn) + } + if m.category_zh != nil { + fields = append(fields, securityscanningresult.FieldCategoryZh) + } + if m.confidence != nil { + fields = append(fields, securityscanningresult.FieldConfidence) + } + if m.cwe != nil { + fields = append(fields, securityscanningresult.FieldCwe) + } + if m.impact != nil { + fields = append(fields, securityscanningresult.FieldImpact) + } + if m.owasp != nil { + fields = append(fields, securityscanningresult.FieldOwasp) + } + if m.start_position != nil { + fields = append(fields, securityscanningresult.FieldStartPosition) + } + if m.end_position != nil { + fields = append(fields, securityscanningresult.FieldEndPosition) + } + if m.created_at != nil { + fields = append(fields, securityscanningresult.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 *SecurityScanningResultMutation) Field(name string) (ent.Value, bool) { + switch name { + case securityscanningresult.FieldSecurityScanningID: + return m.SecurityScanningID() + case securityscanningresult.FieldCheckID: + return m.CheckID() + case securityscanningresult.FieldEngineKind: + return m.EngineKind() + case securityscanningresult.FieldLines: + return m.Lines() + case securityscanningresult.FieldPath: + return m.Path() + case securityscanningresult.FieldMessage: + return m.Message() + case securityscanningresult.FieldMessageZh: + return m.MessageZh() + case securityscanningresult.FieldSeverity: + return m.Severity() + case securityscanningresult.FieldAbstractEn: + return m.AbstractEn() + case securityscanningresult.FieldAbstractZh: + return m.AbstractZh() + case securityscanningresult.FieldCategoryEn: + return m.CategoryEn() + case securityscanningresult.FieldCategoryZh: + return m.CategoryZh() + case securityscanningresult.FieldConfidence: + return m.Confidence() + case securityscanningresult.FieldCwe: + return m.Cwe() + case securityscanningresult.FieldImpact: + return m.Impact() + case securityscanningresult.FieldOwasp: + return m.Owasp() + case securityscanningresult.FieldStartPosition: + return m.StartPosition() + case securityscanningresult.FieldEndPosition: + return m.EndPosition() + case securityscanningresult.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 *SecurityScanningResultMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case securityscanningresult.FieldSecurityScanningID: + return m.OldSecurityScanningID(ctx) + case securityscanningresult.FieldCheckID: + return m.OldCheckID(ctx) + case securityscanningresult.FieldEngineKind: + return m.OldEngineKind(ctx) + case securityscanningresult.FieldLines: + return m.OldLines(ctx) + case securityscanningresult.FieldPath: + return m.OldPath(ctx) + case securityscanningresult.FieldMessage: + return m.OldMessage(ctx) + case securityscanningresult.FieldMessageZh: + return m.OldMessageZh(ctx) + case securityscanningresult.FieldSeverity: + return m.OldSeverity(ctx) + case securityscanningresult.FieldAbstractEn: + return m.OldAbstractEn(ctx) + case securityscanningresult.FieldAbstractZh: + return m.OldAbstractZh(ctx) + case securityscanningresult.FieldCategoryEn: + return m.OldCategoryEn(ctx) + case securityscanningresult.FieldCategoryZh: + return m.OldCategoryZh(ctx) + case securityscanningresult.FieldConfidence: + return m.OldConfidence(ctx) + case securityscanningresult.FieldCwe: + return m.OldCwe(ctx) + case securityscanningresult.FieldImpact: + return m.OldImpact(ctx) + case securityscanningresult.FieldOwasp: + return m.OldOwasp(ctx) + case securityscanningresult.FieldStartPosition: + return m.OldStartPosition(ctx) + case securityscanningresult.FieldEndPosition: + return m.OldEndPosition(ctx) + case securityscanningresult.FieldCreatedAt: + return m.OldCreatedAt(ctx) + } + return nil, fmt.Errorf("unknown SecurityScanningResult 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 *SecurityScanningResultMutation) SetField(name string, value ent.Value) error { + switch name { + case securityscanningresult.FieldSecurityScanningID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSecurityScanningID(v) + return nil + case securityscanningresult.FieldCheckID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCheckID(v) + return nil + case securityscanningresult.FieldEngineKind: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEngineKind(v) + return nil + case securityscanningresult.FieldLines: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLines(v) + return nil + case securityscanningresult.FieldPath: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPath(v) + return nil + case securityscanningresult.FieldMessage: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMessage(v) + return nil + case securityscanningresult.FieldMessageZh: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMessageZh(v) + return nil + case securityscanningresult.FieldSeverity: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSeverity(v) + return nil + case securityscanningresult.FieldAbstractEn: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAbstractEn(v) + return nil + case securityscanningresult.FieldAbstractZh: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAbstractZh(v) + return nil + case securityscanningresult.FieldCategoryEn: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCategoryEn(v) + return nil + case securityscanningresult.FieldCategoryZh: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCategoryZh(v) + return nil + case securityscanningresult.FieldConfidence: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetConfidence(v) + return nil + case securityscanningresult.FieldCwe: + v, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCwe(v) + return nil + case securityscanningresult.FieldImpact: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetImpact(v) + return nil + case securityscanningresult.FieldOwasp: + v, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetOwasp(v) + return nil + case securityscanningresult.FieldStartPosition: + v, ok := value.(*types.Position) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStartPosition(v) + return nil + case securityscanningresult.FieldEndPosition: + v, ok := value.(*types.Position) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEndPosition(v) + return nil + case securityscanningresult.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 SecurityScanningResult field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *SecurityScanningResultMutation) 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 *SecurityScanningResultMutation) 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 *SecurityScanningResultMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown SecurityScanningResult numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *SecurityScanningResultMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *SecurityScanningResultMutation) 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 *SecurityScanningResultMutation) ClearField(name string) error { + return fmt.Errorf("unknown SecurityScanningResult 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 *SecurityScanningResultMutation) ResetField(name string) error { + switch name { + case securityscanningresult.FieldSecurityScanningID: + m.ResetSecurityScanningID() + return nil + case securityscanningresult.FieldCheckID: + m.ResetCheckID() + return nil + case securityscanningresult.FieldEngineKind: + m.ResetEngineKind() + return nil + case securityscanningresult.FieldLines: + m.ResetLines() + return nil + case securityscanningresult.FieldPath: + m.ResetPath() + return nil + case securityscanningresult.FieldMessage: + m.ResetMessage() + return nil + case securityscanningresult.FieldMessageZh: + m.ResetMessageZh() + return nil + case securityscanningresult.FieldSeverity: + m.ResetSeverity() + return nil + case securityscanningresult.FieldAbstractEn: + m.ResetAbstractEn() + return nil + case securityscanningresult.FieldAbstractZh: + m.ResetAbstractZh() + return nil + case securityscanningresult.FieldCategoryEn: + m.ResetCategoryEn() + return nil + case securityscanningresult.FieldCategoryZh: + m.ResetCategoryZh() + return nil + case securityscanningresult.FieldConfidence: + m.ResetConfidence() + return nil + case securityscanningresult.FieldCwe: + m.ResetCwe() + return nil + case securityscanningresult.FieldImpact: + m.ResetImpact() + return nil + case securityscanningresult.FieldOwasp: + m.ResetOwasp() + return nil + case securityscanningresult.FieldStartPosition: + m.ResetStartPosition() + return nil + case securityscanningresult.FieldEndPosition: + m.ResetEndPosition() + return nil + case securityscanningresult.FieldCreatedAt: + m.ResetCreatedAt() + return nil + } + return fmt.Errorf("unknown SecurityScanningResult field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *SecurityScanningResultMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.security_scanning != nil { + edges = append(edges, securityscanningresult.EdgeSecurityScanning) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *SecurityScanningResultMutation) AddedIDs(name string) []ent.Value { + switch name { + case securityscanningresult.EdgeSecurityScanning: + if id := m.security_scanning; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *SecurityScanningResultMutation) 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 *SecurityScanningResultMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *SecurityScanningResultMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedsecurity_scanning { + edges = append(edges, securityscanningresult.EdgeSecurityScanning) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *SecurityScanningResultMutation) EdgeCleared(name string) bool { + switch name { + case securityscanningresult.EdgeSecurityScanning: + return m.clearedsecurity_scanning + } + 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 *SecurityScanningResultMutation) ClearEdge(name string) error { + switch name { + case securityscanningresult.EdgeSecurityScanning: + m.ClearSecurityScanning() + return nil + } + return fmt.Errorf("unknown SecurityScanningResult 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 *SecurityScanningResultMutation) ResetEdge(name string) error { + switch name { + case securityscanningresult.EdgeSecurityScanning: + m.ResetSecurityScanning() + return nil + } + return fmt.Errorf("unknown SecurityScanningResult edge %s", name) +} + // SettingMutation represents an operation that mutates the Setting nodes in the graph. type SettingMutation struct { config @@ -15090,43 +17487,46 @@ func (m *TaskRecordMutation) ResetEdge(name string) error { // UserMutation represents an operation that mutates the User nodes in the graph. type UserMutation struct { config - op Op - typ string - id *uuid.UUID - deleted_at *time.Time - username *string - password *string - email *string - avatar_url *string - platform *consts.UserPlatform - status *consts.UserStatus - 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 - models map[uuid.UUID]struct{} - removedmodels map[uuid.UUID]struct{} - clearedmodels bool - tasks map[uuid.UUID]struct{} - removedtasks map[uuid.UUID]struct{} - clearedtasks bool - identities map[uuid.UUID]struct{} - removedidentities map[uuid.UUID]struct{} - clearedidentities bool - workspaces map[uuid.UUID]struct{} - removedworkspaces map[uuid.UUID]struct{} - clearedworkspaces bool - workspace_files map[uuid.UUID]struct{} - removedworkspace_files map[uuid.UUID]struct{} - clearedworkspace_files bool - api_keys map[uuid.UUID]struct{} - removedapi_keys map[uuid.UUID]struct{} - clearedapi_keys bool - done bool - oldValue func(context.Context) (*User, error) - predicates []predicate.User + op Op + typ string + id *uuid.UUID + deleted_at *time.Time + username *string + password *string + email *string + avatar_url *string + platform *consts.UserPlatform + status *consts.UserStatus + 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 + models map[uuid.UUID]struct{} + removedmodels map[uuid.UUID]struct{} + clearedmodels bool + tasks map[uuid.UUID]struct{} + removedtasks map[uuid.UUID]struct{} + clearedtasks bool + identities map[uuid.UUID]struct{} + removedidentities map[uuid.UUID]struct{} + clearedidentities bool + workspaces map[uuid.UUID]struct{} + removedworkspaces map[uuid.UUID]struct{} + clearedworkspaces bool + workspace_files map[uuid.UUID]struct{} + removedworkspace_files map[uuid.UUID]struct{} + clearedworkspace_files bool + api_keys map[uuid.UUID]struct{} + removedapi_keys map[uuid.UUID]struct{} + clearedapi_keys bool + security_scannings map[uuid.UUID]struct{} + removedsecurity_scannings map[uuid.UUID]struct{} + clearedsecurity_scannings bool + done bool + oldValue func(context.Context) (*User, error) + predicates []predicate.User } var _ ent.Mutation = (*UserMutation)(nil) @@ -16000,6 +18400,60 @@ func (m *UserMutation) ResetAPIKeys() { m.removedapi_keys = nil } +// AddSecurityScanningIDs adds the "security_scannings" edge to the SecurityScanning entity by ids. +func (m *UserMutation) AddSecurityScanningIDs(ids ...uuid.UUID) { + if m.security_scannings == nil { + m.security_scannings = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.security_scannings[ids[i]] = struct{}{} + } +} + +// ClearSecurityScannings clears the "security_scannings" edge to the SecurityScanning entity. +func (m *UserMutation) ClearSecurityScannings() { + m.clearedsecurity_scannings = true +} + +// SecurityScanningsCleared reports if the "security_scannings" edge to the SecurityScanning entity was cleared. +func (m *UserMutation) SecurityScanningsCleared() bool { + return m.clearedsecurity_scannings +} + +// RemoveSecurityScanningIDs removes the "security_scannings" edge to the SecurityScanning entity by IDs. +func (m *UserMutation) RemoveSecurityScanningIDs(ids ...uuid.UUID) { + if m.removedsecurity_scannings == nil { + m.removedsecurity_scannings = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.security_scannings, ids[i]) + m.removedsecurity_scannings[ids[i]] = struct{}{} + } +} + +// RemovedSecurityScannings returns the removed IDs of the "security_scannings" edge to the SecurityScanning entity. +func (m *UserMutation) RemovedSecurityScanningsIDs() (ids []uuid.UUID) { + for id := range m.removedsecurity_scannings { + ids = append(ids, id) + } + return +} + +// SecurityScanningsIDs returns the "security_scannings" edge IDs in the mutation. +func (m *UserMutation) SecurityScanningsIDs() (ids []uuid.UUID) { + for id := range m.security_scannings { + ids = append(ids, id) + } + return +} + +// ResetSecurityScannings resets all changes to the "security_scannings" edge. +func (m *UserMutation) ResetSecurityScannings() { + m.security_scannings = nil + m.clearedsecurity_scannings = false + m.removedsecurity_scannings = nil +} + // Where appends a list predicates to the UserMutation builder. func (m *UserMutation) Where(ps ...predicate.User) { m.predicates = append(m.predicates, ps...) @@ -16302,7 +18756,7 @@ func (m *UserMutation) ResetField(name string) error { // AddedEdges returns all edge names that were set/added in this mutation. func (m *UserMutation) AddedEdges() []string { - edges := make([]string, 0, 7) + edges := make([]string, 0, 8) if m.login_histories != nil { edges = append(edges, user.EdgeLoginHistories) } @@ -16324,6 +18778,9 @@ func (m *UserMutation) AddedEdges() []string { if m.api_keys != nil { edges = append(edges, user.EdgeAPIKeys) } + if m.security_scannings != nil { + edges = append(edges, user.EdgeSecurityScannings) + } return edges } @@ -16373,13 +18830,19 @@ func (m *UserMutation) AddedIDs(name string) []ent.Value { ids = append(ids, id) } return ids + case user.EdgeSecurityScannings: + ids := make([]ent.Value, 0, len(m.security_scannings)) + for id := range m.security_scannings { + 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, 7) + edges := make([]string, 0, 8) if m.removedlogin_histories != nil { edges = append(edges, user.EdgeLoginHistories) } @@ -16401,6 +18864,9 @@ func (m *UserMutation) RemovedEdges() []string { if m.removedapi_keys != nil { edges = append(edges, user.EdgeAPIKeys) } + if m.removedsecurity_scannings != nil { + edges = append(edges, user.EdgeSecurityScannings) + } return edges } @@ -16450,13 +18916,19 @@ func (m *UserMutation) RemovedIDs(name string) []ent.Value { ids = append(ids, id) } return ids + case user.EdgeSecurityScannings: + ids := make([]ent.Value, 0, len(m.removedsecurity_scannings)) + for id := range m.removedsecurity_scannings { + 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, 7) + edges := make([]string, 0, 8) if m.clearedlogin_histories { edges = append(edges, user.EdgeLoginHistories) } @@ -16478,6 +18950,9 @@ func (m *UserMutation) ClearedEdges() []string { if m.clearedapi_keys { edges = append(edges, user.EdgeAPIKeys) } + if m.clearedsecurity_scannings { + edges = append(edges, user.EdgeSecurityScannings) + } return edges } @@ -16499,6 +18974,8 @@ func (m *UserMutation) EdgeCleared(name string) bool { return m.clearedworkspace_files case user.EdgeAPIKeys: return m.clearedapi_keys + case user.EdgeSecurityScannings: + return m.clearedsecurity_scannings } return false } @@ -16536,6 +19013,9 @@ func (m *UserMutation) ResetEdge(name string) error { case user.EdgeAPIKeys: m.ResetAPIKeys() return nil + case user.EdgeSecurityScannings: + m.ResetSecurityScannings() + return nil } return fmt.Errorf("unknown User edge %s", name) } @@ -18680,25 +21160,28 @@ func (m *UserLoginHistoryMutation) ResetEdge(name string) error { // WorkspaceMutation represents an operation that mutates the Workspace nodes in the graph. type WorkspaceMutation struct { config - op Op - typ string - id *uuid.UUID - name *string - description *string - root_path *string - settings *map[string]interface{} - last_accessed_at *time.Time - created_at *time.Time - updated_at *time.Time - clearedFields map[string]struct{} - owner *uuid.UUID - clearedowner bool - files map[uuid.UUID]struct{} - removedfiles map[uuid.UUID]struct{} - clearedfiles bool - done bool - oldValue func(context.Context) (*Workspace, error) - predicates []predicate.Workspace + op Op + typ string + id *uuid.UUID + name *string + description *string + root_path *string + settings *map[string]interface{} + last_accessed_at *time.Time + created_at *time.Time + updated_at *time.Time + clearedFields map[string]struct{} + owner *uuid.UUID + clearedowner bool + files map[uuid.UUID]struct{} + removedfiles map[uuid.UUID]struct{} + clearedfiles bool + security_scannings map[uuid.UUID]struct{} + removedsecurity_scannings map[uuid.UUID]struct{} + clearedsecurity_scannings bool + done bool + oldValue func(context.Context) (*Workspace, error) + predicates []predicate.Workspace } var _ ent.Mutation = (*WorkspaceMutation)(nil) @@ -19226,6 +21709,60 @@ func (m *WorkspaceMutation) ResetFiles() { m.removedfiles = nil } +// AddSecurityScanningIDs adds the "security_scannings" edge to the SecurityScanning entity by ids. +func (m *WorkspaceMutation) AddSecurityScanningIDs(ids ...uuid.UUID) { + if m.security_scannings == nil { + m.security_scannings = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.security_scannings[ids[i]] = struct{}{} + } +} + +// ClearSecurityScannings clears the "security_scannings" edge to the SecurityScanning entity. +func (m *WorkspaceMutation) ClearSecurityScannings() { + m.clearedsecurity_scannings = true +} + +// SecurityScanningsCleared reports if the "security_scannings" edge to the SecurityScanning entity was cleared. +func (m *WorkspaceMutation) SecurityScanningsCleared() bool { + return m.clearedsecurity_scannings +} + +// RemoveSecurityScanningIDs removes the "security_scannings" edge to the SecurityScanning entity by IDs. +func (m *WorkspaceMutation) RemoveSecurityScanningIDs(ids ...uuid.UUID) { + if m.removedsecurity_scannings == nil { + m.removedsecurity_scannings = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.security_scannings, ids[i]) + m.removedsecurity_scannings[ids[i]] = struct{}{} + } +} + +// RemovedSecurityScannings returns the removed IDs of the "security_scannings" edge to the SecurityScanning entity. +func (m *WorkspaceMutation) RemovedSecurityScanningsIDs() (ids []uuid.UUID) { + for id := range m.removedsecurity_scannings { + ids = append(ids, id) + } + return +} + +// SecurityScanningsIDs returns the "security_scannings" edge IDs in the mutation. +func (m *WorkspaceMutation) SecurityScanningsIDs() (ids []uuid.UUID) { + for id := range m.security_scannings { + ids = append(ids, id) + } + return +} + +// ResetSecurityScannings resets all changes to the "security_scannings" edge. +func (m *WorkspaceMutation) ResetSecurityScannings() { + m.security_scannings = nil + m.clearedsecurity_scannings = false + m.removedsecurity_scannings = nil +} + // Where appends a list predicates to the WorkspaceMutation builder. func (m *WorkspaceMutation) Where(ps ...predicate.Workspace) { m.predicates = append(m.predicates, ps...) @@ -19499,13 +22036,16 @@ func (m *WorkspaceMutation) ResetField(name string) error { // AddedEdges returns all edge names that were set/added in this mutation. func (m *WorkspaceMutation) AddedEdges() []string { - edges := make([]string, 0, 2) + edges := make([]string, 0, 3) if m.owner != nil { edges = append(edges, workspace.EdgeOwner) } if m.files != nil { edges = append(edges, workspace.EdgeFiles) } + if m.security_scannings != nil { + edges = append(edges, workspace.EdgeSecurityScannings) + } return edges } @@ -19523,16 +22063,25 @@ func (m *WorkspaceMutation) AddedIDs(name string) []ent.Value { ids = append(ids, id) } return ids + case workspace.EdgeSecurityScannings: + ids := make([]ent.Value, 0, len(m.security_scannings)) + for id := range m.security_scannings { + ids = append(ids, id) + } + return ids } return nil } // RemovedEdges returns all edge names that were removed in this mutation. func (m *WorkspaceMutation) RemovedEdges() []string { - edges := make([]string, 0, 2) + edges := make([]string, 0, 3) if m.removedfiles != nil { edges = append(edges, workspace.EdgeFiles) } + if m.removedsecurity_scannings != nil { + edges = append(edges, workspace.EdgeSecurityScannings) + } return edges } @@ -19546,19 +22095,28 @@ func (m *WorkspaceMutation) RemovedIDs(name string) []ent.Value { ids = append(ids, id) } return ids + case workspace.EdgeSecurityScannings: + ids := make([]ent.Value, 0, len(m.removedsecurity_scannings)) + for id := range m.removedsecurity_scannings { + ids = append(ids, id) + } + return ids } return nil } // ClearedEdges returns all edge names that were cleared in this mutation. func (m *WorkspaceMutation) ClearedEdges() []string { - edges := make([]string, 0, 2) + edges := make([]string, 0, 3) if m.clearedowner { edges = append(edges, workspace.EdgeOwner) } if m.clearedfiles { edges = append(edges, workspace.EdgeFiles) } + if m.clearedsecurity_scannings { + edges = append(edges, workspace.EdgeSecurityScannings) + } return edges } @@ -19570,6 +22128,8 @@ func (m *WorkspaceMutation) EdgeCleared(name string) bool { return m.clearedowner case workspace.EdgeFiles: return m.clearedfiles + case workspace.EdgeSecurityScannings: + return m.clearedsecurity_scannings } return false } @@ -19595,6 +22155,9 @@ func (m *WorkspaceMutation) ResetEdge(name string) error { case workspace.EdgeFiles: m.ResetFiles() return nil + case workspace.EdgeSecurityScannings: + m.ResetSecurityScannings() + return nil } return fmt.Errorf("unknown Workspace edge %s", name) } diff --git a/backend/db/page.go b/backend/db/page.go index ae2261c..0eaeb88 100644 --- a/backend/db/page.go +++ b/backend/db/page.go @@ -207,6 +207,34 @@ func (mpm *ModelProviderModelQuery) Page(ctx context.Context, page, size int) ([ return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil } +func (ss *SecurityScanningQuery) Page(ctx context.Context, page, size int) ([]*SecurityScanning, *PageInfo, error) { + cnt, err := ss.Count(ctx) + if err != nil { + return nil, nil, err + } + offset := size * (page - 1) + rs, err := ss.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 (ssr *SecurityScanningResultQuery) Page(ctx context.Context, page, size int) ([]*SecurityScanningResult, *PageInfo, error) { + cnt, err := ssr.Count(ctx) + if err != nil { + return nil, nil, err + } + offset := size * (page - 1) + rs, err := ssr.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 { diff --git a/backend/db/predicate/predicate.go b/backend/db/predicate/predicate.go index 55e3799..e4d8d1a 100644 --- a/backend/db/predicate/predicate.go +++ b/backend/db/predicate/predicate.go @@ -48,6 +48,12 @@ type ModelProvider func(*sql.Selector) // ModelProviderModel is the predicate function for modelprovidermodel builders. type ModelProviderModel func(*sql.Selector) +// SecurityScanning is the predicate function for securityscanning builders. +type SecurityScanning func(*sql.Selector) + +// SecurityScanningResult is the predicate function for securityscanningresult builders. +type SecurityScanningResult func(*sql.Selector) + // Setting is the predicate function for setting builders. type Setting func(*sql.Selector) diff --git a/backend/db/runtime/runtime.go b/backend/db/runtime/runtime.go index f8b01db..5bfe1e6 100644 --- a/backend/db/runtime/runtime.go +++ b/backend/db/runtime/runtime.go @@ -19,6 +19,8 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/model" "github.com/chaitin/MonkeyCode/backend/db/modelprovider" "github.com/chaitin/MonkeyCode/backend/db/modelprovidermodel" + "github.com/chaitin/MonkeyCode/backend/db/securityscanning" + "github.com/chaitin/MonkeyCode/backend/db/securityscanningresult" "github.com/chaitin/MonkeyCode/backend/db/setting" "github.com/chaitin/MonkeyCode/backend/db/task" "github.com/chaitin/MonkeyCode/backend/db/taskrecord" @@ -235,6 +237,22 @@ func init() { modelprovidermodelDescID := modelprovidermodelFields[0].Descriptor() // modelprovidermodel.DefaultID holds the default value on creation for the id field. modelprovidermodel.DefaultID = modelprovidermodelDescID.Default.(func() uuid.UUID) + securityscanningFields := schema.SecurityScanning{}.Fields() + _ = securityscanningFields + // securityscanningDescCreatedAt is the schema descriptor for created_at field. + securityscanningDescCreatedAt := securityscanningFields[8].Descriptor() + // securityscanning.DefaultCreatedAt holds the default value on creation for the created_at field. + securityscanning.DefaultCreatedAt = securityscanningDescCreatedAt.Default.(func() time.Time) + // securityscanningDescUpdatedAt is the schema descriptor for updated_at field. + securityscanningDescUpdatedAt := securityscanningFields[9].Descriptor() + // securityscanning.DefaultUpdatedAt holds the default value on creation for the updated_at field. + securityscanning.DefaultUpdatedAt = securityscanningDescUpdatedAt.Default.(func() time.Time) + securityscanningresultFields := schema.SecurityScanningResult{}.Fields() + _ = securityscanningresultFields + // securityscanningresultDescCreatedAt is the schema descriptor for created_at field. + securityscanningresultDescCreatedAt := securityscanningresultFields[19].Descriptor() + // securityscanningresult.DefaultCreatedAt holds the default value on creation for the created_at field. + securityscanningresult.DefaultCreatedAt = securityscanningresultDescCreatedAt.Default.(func() time.Time) settingFields := schema.Setting{}.Fields() _ = settingFields // settingDescEnableSSO is the schema descriptor for enable_sso field. diff --git a/backend/db/securityscanning.go b/backend/db/securityscanning.go new file mode 100644 index 0000000..7e4ee8e --- /dev/null +++ b/backend/db/securityscanning.go @@ -0,0 +1,260 @@ +// 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/securityscanning" + "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/workspace" + "github.com/google/uuid" +) + +// SecurityScanning is the model entity for the SecurityScanning schema. +type SecurityScanning 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"` + // WorkspaceID holds the value of the "workspace_id" field. + WorkspaceID uuid.UUID `json:"workspace_id,omitempty"` + // Status holds the value of the "status" field. + Status consts.SecurityScanningStatus `json:"status,omitempty"` + // Workspace holds the value of the "workspace" field. + Workspace string `json:"workspace,omitempty"` + // Language holds the value of the "language" field. + Language consts.SecurityScanningLanguage `json:"language,omitempty"` + // Rule holds the value of the "rule" field. + Rule string `json:"rule,omitempty"` + // ErrorMessage holds the value of the "error_message" field. + ErrorMessage string `json:"error_message,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 SecurityScanningQuery when eager-loading is set. + Edges SecurityScanningEdges `json:"edges"` + selectValues sql.SelectValues +} + +// SecurityScanningEdges holds the relations/edges for other nodes in the graph. +type SecurityScanningEdges struct { + // User holds the value of the user edge. + User *User `json:"user,omitempty"` + // Results holds the value of the results edge. + Results []*SecurityScanningResult `json:"results,omitempty"` + // WorkspaceEdge holds the value of the workspace_edge edge. + WorkspaceEdge *Workspace `json:"workspace_edge,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [3]bool +} + +// UserOrErr returns the User value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e SecurityScanningEdges) 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"} +} + +// ResultsOrErr returns the Results value or an error if the edge +// was not loaded in eager-loading. +func (e SecurityScanningEdges) ResultsOrErr() ([]*SecurityScanningResult, error) { + if e.loadedTypes[1] { + return e.Results, nil + } + return nil, &NotLoadedError{edge: "results"} +} + +// WorkspaceEdgeOrErr returns the WorkspaceEdge value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e SecurityScanningEdges) WorkspaceEdgeOrErr() (*Workspace, error) { + if e.WorkspaceEdge != nil { + return e.WorkspaceEdge, nil + } else if e.loadedTypes[2] { + return nil, &NotFoundError{label: workspace.Label} + } + return nil, &NotLoadedError{edge: "workspace_edge"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*SecurityScanning) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case securityscanning.FieldStatus, securityscanning.FieldWorkspace, securityscanning.FieldLanguage, securityscanning.FieldRule, securityscanning.FieldErrorMessage: + values[i] = new(sql.NullString) + case securityscanning.FieldCreatedAt, securityscanning.FieldUpdatedAt: + values[i] = new(sql.NullTime) + case securityscanning.FieldID, securityscanning.FieldUserID, securityscanning.FieldWorkspaceID: + 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 SecurityScanning fields. +func (ss *SecurityScanning) 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 securityscanning.FieldID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value != nil { + ss.ID = *value + } + case securityscanning.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 { + ss.UserID = *value + } + case securityscanning.FieldWorkspaceID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field workspace_id", values[i]) + } else if value != nil { + ss.WorkspaceID = *value + } + case securityscanning.FieldStatus: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field status", values[i]) + } else if value.Valid { + ss.Status = consts.SecurityScanningStatus(value.String) + } + case securityscanning.FieldWorkspace: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field workspace", values[i]) + } else if value.Valid { + ss.Workspace = value.String + } + case securityscanning.FieldLanguage: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field language", values[i]) + } else if value.Valid { + ss.Language = consts.SecurityScanningLanguage(value.String) + } + case securityscanning.FieldRule: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field rule", values[i]) + } else if value.Valid { + ss.Rule = value.String + } + case securityscanning.FieldErrorMessage: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field error_message", values[i]) + } else if value.Valid { + ss.ErrorMessage = value.String + } + case securityscanning.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 { + ss.CreatedAt = value.Time + } + case securityscanning.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 { + ss.UpdatedAt = value.Time + } + default: + ss.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the SecurityScanning. +// This includes values selected through modifiers, order, etc. +func (ss *SecurityScanning) Value(name string) (ent.Value, error) { + return ss.selectValues.Get(name) +} + +// QueryUser queries the "user" edge of the SecurityScanning entity. +func (ss *SecurityScanning) QueryUser() *UserQuery { + return NewSecurityScanningClient(ss.config).QueryUser(ss) +} + +// QueryResults queries the "results" edge of the SecurityScanning entity. +func (ss *SecurityScanning) QueryResults() *SecurityScanningResultQuery { + return NewSecurityScanningClient(ss.config).QueryResults(ss) +} + +// QueryWorkspaceEdge queries the "workspace_edge" edge of the SecurityScanning entity. +func (ss *SecurityScanning) QueryWorkspaceEdge() *WorkspaceQuery { + return NewSecurityScanningClient(ss.config).QueryWorkspaceEdge(ss) +} + +// Update returns a builder for updating this SecurityScanning. +// Note that you need to call SecurityScanning.Unwrap() before calling this method if this SecurityScanning +// was returned from a transaction, and the transaction was committed or rolled back. +func (ss *SecurityScanning) Update() *SecurityScanningUpdateOne { + return NewSecurityScanningClient(ss.config).UpdateOne(ss) +} + +// Unwrap unwraps the SecurityScanning 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 (ss *SecurityScanning) Unwrap() *SecurityScanning { + _tx, ok := ss.config.driver.(*txDriver) + if !ok { + panic("db: SecurityScanning is not a transactional entity") + } + ss.config.driver = _tx.drv + return ss +} + +// String implements the fmt.Stringer. +func (ss *SecurityScanning) String() string { + var builder strings.Builder + builder.WriteString("SecurityScanning(") + builder.WriteString(fmt.Sprintf("id=%v, ", ss.ID)) + builder.WriteString("user_id=") + builder.WriteString(fmt.Sprintf("%v", ss.UserID)) + builder.WriteString(", ") + builder.WriteString("workspace_id=") + builder.WriteString(fmt.Sprintf("%v", ss.WorkspaceID)) + builder.WriteString(", ") + builder.WriteString("status=") + builder.WriteString(fmt.Sprintf("%v", ss.Status)) + builder.WriteString(", ") + builder.WriteString("workspace=") + builder.WriteString(ss.Workspace) + builder.WriteString(", ") + builder.WriteString("language=") + builder.WriteString(fmt.Sprintf("%v", ss.Language)) + builder.WriteString(", ") + builder.WriteString("rule=") + builder.WriteString(ss.Rule) + builder.WriteString(", ") + builder.WriteString("error_message=") + builder.WriteString(ss.ErrorMessage) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(ss.CreatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("updated_at=") + builder.WriteString(ss.UpdatedAt.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// SecurityScannings is a parsable slice of SecurityScanning. +type SecurityScannings []*SecurityScanning diff --git a/backend/db/securityscanning/securityscanning.go b/backend/db/securityscanning/securityscanning.go new file mode 100644 index 0000000..9678de0 --- /dev/null +++ b/backend/db/securityscanning/securityscanning.go @@ -0,0 +1,197 @@ +// Code generated by ent, DO NOT EDIT. + +package securityscanning + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the securityscanning type in the database. + Label = "security_scanning" + // 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" + // FieldWorkspaceID holds the string denoting the workspace_id field in the database. + FieldWorkspaceID = "workspace_id" + // FieldStatus holds the string denoting the status field in the database. + FieldStatus = "status" + // FieldWorkspace holds the string denoting the workspace field in the database. + FieldWorkspace = "workspace" + // FieldLanguage holds the string denoting the language field in the database. + FieldLanguage = "language" + // FieldRule holds the string denoting the rule field in the database. + FieldRule = "rule" + // FieldErrorMessage holds the string denoting the error_message field in the database. + FieldErrorMessage = "error_message" + // 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" + // EdgeResults holds the string denoting the results edge name in mutations. + EdgeResults = "results" + // EdgeWorkspaceEdge holds the string denoting the workspace_edge edge name in mutations. + EdgeWorkspaceEdge = "workspace_edge" + // Table holds the table name of the securityscanning in the database. + Table = "security_scannings" + // UserTable is the table that holds the user relation/edge. + UserTable = "security_scannings" + // 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" + // ResultsTable is the table that holds the results relation/edge. + ResultsTable = "security_scanning_results" + // ResultsInverseTable is the table name for the SecurityScanningResult entity. + // It exists in this package in order to avoid circular dependency with the "securityscanningresult" package. + ResultsInverseTable = "security_scanning_results" + // ResultsColumn is the table column denoting the results relation/edge. + ResultsColumn = "security_scanning_id" + // WorkspaceEdgeTable is the table that holds the workspace_edge relation/edge. + WorkspaceEdgeTable = "security_scannings" + // WorkspaceEdgeInverseTable is the table name for the Workspace entity. + // It exists in this package in order to avoid circular dependency with the "workspace" package. + WorkspaceEdgeInverseTable = "workspaces" + // WorkspaceEdgeColumn is the table column denoting the workspace_edge relation/edge. + WorkspaceEdgeColumn = "workspace_id" +) + +// Columns holds all SQL columns for securityscanning fields. +var Columns = []string{ + FieldID, + FieldUserID, + FieldWorkspaceID, + FieldStatus, + FieldWorkspace, + FieldLanguage, + FieldRule, + FieldErrorMessage, + 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 +) + +// OrderOption defines the ordering options for the SecurityScanning 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() +} + +// ByWorkspaceID orders the results by the workspace_id field. +func ByWorkspaceID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldWorkspaceID, opts...).ToFunc() +} + +// ByStatus orders the results by the status field. +func ByStatus(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldStatus, opts...).ToFunc() +} + +// ByWorkspace orders the results by the workspace field. +func ByWorkspace(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldWorkspace, opts...).ToFunc() +} + +// ByLanguage orders the results by the language field. +func ByLanguage(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldLanguage, opts...).ToFunc() +} + +// ByRule orders the results by the rule field. +func ByRule(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRule, opts...).ToFunc() +} + +// ByErrorMessage orders the results by the error_message field. +func ByErrorMessage(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldErrorMessage, 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...)) + } +} + +// ByResultsCount orders the results by results count. +func ByResultsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newResultsStep(), opts...) + } +} + +// ByResults orders the results by results terms. +func ByResults(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newResultsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByWorkspaceEdgeField orders the results by workspace_edge field. +func ByWorkspaceEdgeField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newWorkspaceEdgeStep(), 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 newResultsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ResultsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ResultsTable, ResultsColumn), + ) +} +func newWorkspaceEdgeStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(WorkspaceEdgeInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, WorkspaceEdgeTable, WorkspaceEdgeColumn), + ) +} diff --git a/backend/db/securityscanning/where.go b/backend/db/securityscanning/where.go new file mode 100644 index 0000000..4906157 --- /dev/null +++ b/backend/db/securityscanning/where.go @@ -0,0 +1,692 @@ +// Code generated by ent, DO NOT EDIT. + +package securityscanning + +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.SecurityScanning { + return predicate.SecurityScanning(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id uuid.UUID) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id uuid.UUID) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...uuid.UUID) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...uuid.UUID) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id uuid.UUID) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id uuid.UUID) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id uuid.UUID) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id uuid.UUID) predicate.SecurityScanning { + return predicate.SecurityScanning(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.SecurityScanning { + return predicate.SecurityScanning(sql.FieldEQ(FieldUserID, v)) +} + +// WorkspaceID applies equality check predicate on the "workspace_id" field. It's identical to WorkspaceIDEQ. +func WorkspaceID(v uuid.UUID) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldEQ(FieldWorkspaceID, v)) +} + +// Status applies equality check predicate on the "status" field. It's identical to StatusEQ. +func Status(v consts.SecurityScanningStatus) predicate.SecurityScanning { + vc := string(v) + return predicate.SecurityScanning(sql.FieldEQ(FieldStatus, vc)) +} + +// Workspace applies equality check predicate on the "workspace" field. It's identical to WorkspaceEQ. +func Workspace(v string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldEQ(FieldWorkspace, v)) +} + +// Language applies equality check predicate on the "language" field. It's identical to LanguageEQ. +func Language(v consts.SecurityScanningLanguage) predicate.SecurityScanning { + vc := string(v) + return predicate.SecurityScanning(sql.FieldEQ(FieldLanguage, vc)) +} + +// Rule applies equality check predicate on the "rule" field. It's identical to RuleEQ. +func Rule(v string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldEQ(FieldRule, v)) +} + +// ErrorMessage applies equality check predicate on the "error_message" field. It's identical to ErrorMessageEQ. +func ErrorMessage(v string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldEQ(FieldErrorMessage, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.SecurityScanning { + return predicate.SecurityScanning(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.SecurityScanning { + return predicate.SecurityScanning(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UserIDEQ applies the EQ predicate on the "user_id" field. +func UserIDEQ(v uuid.UUID) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldEQ(FieldUserID, v)) +} + +// UserIDNEQ applies the NEQ predicate on the "user_id" field. +func UserIDNEQ(v uuid.UUID) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldNEQ(FieldUserID, v)) +} + +// UserIDIn applies the In predicate on the "user_id" field. +func UserIDIn(vs ...uuid.UUID) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldIn(FieldUserID, vs...)) +} + +// UserIDNotIn applies the NotIn predicate on the "user_id" field. +func UserIDNotIn(vs ...uuid.UUID) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldNotIn(FieldUserID, vs...)) +} + +// WorkspaceIDEQ applies the EQ predicate on the "workspace_id" field. +func WorkspaceIDEQ(v uuid.UUID) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldEQ(FieldWorkspaceID, v)) +} + +// WorkspaceIDNEQ applies the NEQ predicate on the "workspace_id" field. +func WorkspaceIDNEQ(v uuid.UUID) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldNEQ(FieldWorkspaceID, v)) +} + +// WorkspaceIDIn applies the In predicate on the "workspace_id" field. +func WorkspaceIDIn(vs ...uuid.UUID) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldIn(FieldWorkspaceID, vs...)) +} + +// WorkspaceIDNotIn applies the NotIn predicate on the "workspace_id" field. +func WorkspaceIDNotIn(vs ...uuid.UUID) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldNotIn(FieldWorkspaceID, vs...)) +} + +// StatusEQ applies the EQ predicate on the "status" field. +func StatusEQ(v consts.SecurityScanningStatus) predicate.SecurityScanning { + vc := string(v) + return predicate.SecurityScanning(sql.FieldEQ(FieldStatus, vc)) +} + +// StatusNEQ applies the NEQ predicate on the "status" field. +func StatusNEQ(v consts.SecurityScanningStatus) predicate.SecurityScanning { + vc := string(v) + return predicate.SecurityScanning(sql.FieldNEQ(FieldStatus, vc)) +} + +// StatusIn applies the In predicate on the "status" field. +func StatusIn(vs ...consts.SecurityScanningStatus) predicate.SecurityScanning { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.SecurityScanning(sql.FieldIn(FieldStatus, v...)) +} + +// StatusNotIn applies the NotIn predicate on the "status" field. +func StatusNotIn(vs ...consts.SecurityScanningStatus) predicate.SecurityScanning { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.SecurityScanning(sql.FieldNotIn(FieldStatus, v...)) +} + +// StatusGT applies the GT predicate on the "status" field. +func StatusGT(v consts.SecurityScanningStatus) predicate.SecurityScanning { + vc := string(v) + return predicate.SecurityScanning(sql.FieldGT(FieldStatus, vc)) +} + +// StatusGTE applies the GTE predicate on the "status" field. +func StatusGTE(v consts.SecurityScanningStatus) predicate.SecurityScanning { + vc := string(v) + return predicate.SecurityScanning(sql.FieldGTE(FieldStatus, vc)) +} + +// StatusLT applies the LT predicate on the "status" field. +func StatusLT(v consts.SecurityScanningStatus) predicate.SecurityScanning { + vc := string(v) + return predicate.SecurityScanning(sql.FieldLT(FieldStatus, vc)) +} + +// StatusLTE applies the LTE predicate on the "status" field. +func StatusLTE(v consts.SecurityScanningStatus) predicate.SecurityScanning { + vc := string(v) + return predicate.SecurityScanning(sql.FieldLTE(FieldStatus, vc)) +} + +// StatusContains applies the Contains predicate on the "status" field. +func StatusContains(v consts.SecurityScanningStatus) predicate.SecurityScanning { + vc := string(v) + return predicate.SecurityScanning(sql.FieldContains(FieldStatus, vc)) +} + +// StatusHasPrefix applies the HasPrefix predicate on the "status" field. +func StatusHasPrefix(v consts.SecurityScanningStatus) predicate.SecurityScanning { + vc := string(v) + return predicate.SecurityScanning(sql.FieldHasPrefix(FieldStatus, vc)) +} + +// StatusHasSuffix applies the HasSuffix predicate on the "status" field. +func StatusHasSuffix(v consts.SecurityScanningStatus) predicate.SecurityScanning { + vc := string(v) + return predicate.SecurityScanning(sql.FieldHasSuffix(FieldStatus, vc)) +} + +// StatusEqualFold applies the EqualFold predicate on the "status" field. +func StatusEqualFold(v consts.SecurityScanningStatus) predicate.SecurityScanning { + vc := string(v) + return predicate.SecurityScanning(sql.FieldEqualFold(FieldStatus, vc)) +} + +// StatusContainsFold applies the ContainsFold predicate on the "status" field. +func StatusContainsFold(v consts.SecurityScanningStatus) predicate.SecurityScanning { + vc := string(v) + return predicate.SecurityScanning(sql.FieldContainsFold(FieldStatus, vc)) +} + +// WorkspaceEQ applies the EQ predicate on the "workspace" field. +func WorkspaceEQ(v string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldEQ(FieldWorkspace, v)) +} + +// WorkspaceNEQ applies the NEQ predicate on the "workspace" field. +func WorkspaceNEQ(v string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldNEQ(FieldWorkspace, v)) +} + +// WorkspaceIn applies the In predicate on the "workspace" field. +func WorkspaceIn(vs ...string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldIn(FieldWorkspace, vs...)) +} + +// WorkspaceNotIn applies the NotIn predicate on the "workspace" field. +func WorkspaceNotIn(vs ...string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldNotIn(FieldWorkspace, vs...)) +} + +// WorkspaceGT applies the GT predicate on the "workspace" field. +func WorkspaceGT(v string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldGT(FieldWorkspace, v)) +} + +// WorkspaceGTE applies the GTE predicate on the "workspace" field. +func WorkspaceGTE(v string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldGTE(FieldWorkspace, v)) +} + +// WorkspaceLT applies the LT predicate on the "workspace" field. +func WorkspaceLT(v string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldLT(FieldWorkspace, v)) +} + +// WorkspaceLTE applies the LTE predicate on the "workspace" field. +func WorkspaceLTE(v string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldLTE(FieldWorkspace, v)) +} + +// WorkspaceContains applies the Contains predicate on the "workspace" field. +func WorkspaceContains(v string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldContains(FieldWorkspace, v)) +} + +// WorkspaceHasPrefix applies the HasPrefix predicate on the "workspace" field. +func WorkspaceHasPrefix(v string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldHasPrefix(FieldWorkspace, v)) +} + +// WorkspaceHasSuffix applies the HasSuffix predicate on the "workspace" field. +func WorkspaceHasSuffix(v string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldHasSuffix(FieldWorkspace, v)) +} + +// WorkspaceEqualFold applies the EqualFold predicate on the "workspace" field. +func WorkspaceEqualFold(v string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldEqualFold(FieldWorkspace, v)) +} + +// WorkspaceContainsFold applies the ContainsFold predicate on the "workspace" field. +func WorkspaceContainsFold(v string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldContainsFold(FieldWorkspace, v)) +} + +// LanguageEQ applies the EQ predicate on the "language" field. +func LanguageEQ(v consts.SecurityScanningLanguage) predicate.SecurityScanning { + vc := string(v) + return predicate.SecurityScanning(sql.FieldEQ(FieldLanguage, vc)) +} + +// LanguageNEQ applies the NEQ predicate on the "language" field. +func LanguageNEQ(v consts.SecurityScanningLanguage) predicate.SecurityScanning { + vc := string(v) + return predicate.SecurityScanning(sql.FieldNEQ(FieldLanguage, vc)) +} + +// LanguageIn applies the In predicate on the "language" field. +func LanguageIn(vs ...consts.SecurityScanningLanguage) predicate.SecurityScanning { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.SecurityScanning(sql.FieldIn(FieldLanguage, v...)) +} + +// LanguageNotIn applies the NotIn predicate on the "language" field. +func LanguageNotIn(vs ...consts.SecurityScanningLanguage) predicate.SecurityScanning { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.SecurityScanning(sql.FieldNotIn(FieldLanguage, v...)) +} + +// LanguageGT applies the GT predicate on the "language" field. +func LanguageGT(v consts.SecurityScanningLanguage) predicate.SecurityScanning { + vc := string(v) + return predicate.SecurityScanning(sql.FieldGT(FieldLanguage, vc)) +} + +// LanguageGTE applies the GTE predicate on the "language" field. +func LanguageGTE(v consts.SecurityScanningLanguage) predicate.SecurityScanning { + vc := string(v) + return predicate.SecurityScanning(sql.FieldGTE(FieldLanguage, vc)) +} + +// LanguageLT applies the LT predicate on the "language" field. +func LanguageLT(v consts.SecurityScanningLanguage) predicate.SecurityScanning { + vc := string(v) + return predicate.SecurityScanning(sql.FieldLT(FieldLanguage, vc)) +} + +// LanguageLTE applies the LTE predicate on the "language" field. +func LanguageLTE(v consts.SecurityScanningLanguage) predicate.SecurityScanning { + vc := string(v) + return predicate.SecurityScanning(sql.FieldLTE(FieldLanguage, vc)) +} + +// LanguageContains applies the Contains predicate on the "language" field. +func LanguageContains(v consts.SecurityScanningLanguage) predicate.SecurityScanning { + vc := string(v) + return predicate.SecurityScanning(sql.FieldContains(FieldLanguage, vc)) +} + +// LanguageHasPrefix applies the HasPrefix predicate on the "language" field. +func LanguageHasPrefix(v consts.SecurityScanningLanguage) predicate.SecurityScanning { + vc := string(v) + return predicate.SecurityScanning(sql.FieldHasPrefix(FieldLanguage, vc)) +} + +// LanguageHasSuffix applies the HasSuffix predicate on the "language" field. +func LanguageHasSuffix(v consts.SecurityScanningLanguage) predicate.SecurityScanning { + vc := string(v) + return predicate.SecurityScanning(sql.FieldHasSuffix(FieldLanguage, vc)) +} + +// LanguageEqualFold applies the EqualFold predicate on the "language" field. +func LanguageEqualFold(v consts.SecurityScanningLanguage) predicate.SecurityScanning { + vc := string(v) + return predicate.SecurityScanning(sql.FieldEqualFold(FieldLanguage, vc)) +} + +// LanguageContainsFold applies the ContainsFold predicate on the "language" field. +func LanguageContainsFold(v consts.SecurityScanningLanguage) predicate.SecurityScanning { + vc := string(v) + return predicate.SecurityScanning(sql.FieldContainsFold(FieldLanguage, vc)) +} + +// RuleEQ applies the EQ predicate on the "rule" field. +func RuleEQ(v string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldEQ(FieldRule, v)) +} + +// RuleNEQ applies the NEQ predicate on the "rule" field. +func RuleNEQ(v string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldNEQ(FieldRule, v)) +} + +// RuleIn applies the In predicate on the "rule" field. +func RuleIn(vs ...string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldIn(FieldRule, vs...)) +} + +// RuleNotIn applies the NotIn predicate on the "rule" field. +func RuleNotIn(vs ...string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldNotIn(FieldRule, vs...)) +} + +// RuleGT applies the GT predicate on the "rule" field. +func RuleGT(v string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldGT(FieldRule, v)) +} + +// RuleGTE applies the GTE predicate on the "rule" field. +func RuleGTE(v string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldGTE(FieldRule, v)) +} + +// RuleLT applies the LT predicate on the "rule" field. +func RuleLT(v string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldLT(FieldRule, v)) +} + +// RuleLTE applies the LTE predicate on the "rule" field. +func RuleLTE(v string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldLTE(FieldRule, v)) +} + +// RuleContains applies the Contains predicate on the "rule" field. +func RuleContains(v string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldContains(FieldRule, v)) +} + +// RuleHasPrefix applies the HasPrefix predicate on the "rule" field. +func RuleHasPrefix(v string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldHasPrefix(FieldRule, v)) +} + +// RuleHasSuffix applies the HasSuffix predicate on the "rule" field. +func RuleHasSuffix(v string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldHasSuffix(FieldRule, v)) +} + +// RuleIsNil applies the IsNil predicate on the "rule" field. +func RuleIsNil() predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldIsNull(FieldRule)) +} + +// RuleNotNil applies the NotNil predicate on the "rule" field. +func RuleNotNil() predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldNotNull(FieldRule)) +} + +// RuleEqualFold applies the EqualFold predicate on the "rule" field. +func RuleEqualFold(v string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldEqualFold(FieldRule, v)) +} + +// RuleContainsFold applies the ContainsFold predicate on the "rule" field. +func RuleContainsFold(v string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldContainsFold(FieldRule, v)) +} + +// ErrorMessageEQ applies the EQ predicate on the "error_message" field. +func ErrorMessageEQ(v string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldEQ(FieldErrorMessage, v)) +} + +// ErrorMessageNEQ applies the NEQ predicate on the "error_message" field. +func ErrorMessageNEQ(v string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldNEQ(FieldErrorMessage, v)) +} + +// ErrorMessageIn applies the In predicate on the "error_message" field. +func ErrorMessageIn(vs ...string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldIn(FieldErrorMessage, vs...)) +} + +// ErrorMessageNotIn applies the NotIn predicate on the "error_message" field. +func ErrorMessageNotIn(vs ...string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldNotIn(FieldErrorMessage, vs...)) +} + +// ErrorMessageGT applies the GT predicate on the "error_message" field. +func ErrorMessageGT(v string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldGT(FieldErrorMessage, v)) +} + +// ErrorMessageGTE applies the GTE predicate on the "error_message" field. +func ErrorMessageGTE(v string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldGTE(FieldErrorMessage, v)) +} + +// ErrorMessageLT applies the LT predicate on the "error_message" field. +func ErrorMessageLT(v string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldLT(FieldErrorMessage, v)) +} + +// ErrorMessageLTE applies the LTE predicate on the "error_message" field. +func ErrorMessageLTE(v string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldLTE(FieldErrorMessage, v)) +} + +// ErrorMessageContains applies the Contains predicate on the "error_message" field. +func ErrorMessageContains(v string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldContains(FieldErrorMessage, v)) +} + +// ErrorMessageHasPrefix applies the HasPrefix predicate on the "error_message" field. +func ErrorMessageHasPrefix(v string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldHasPrefix(FieldErrorMessage, v)) +} + +// ErrorMessageHasSuffix applies the HasSuffix predicate on the "error_message" field. +func ErrorMessageHasSuffix(v string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldHasSuffix(FieldErrorMessage, v)) +} + +// ErrorMessageIsNil applies the IsNil predicate on the "error_message" field. +func ErrorMessageIsNil() predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldIsNull(FieldErrorMessage)) +} + +// ErrorMessageNotNil applies the NotNil predicate on the "error_message" field. +func ErrorMessageNotNil() predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldNotNull(FieldErrorMessage)) +} + +// ErrorMessageEqualFold applies the EqualFold predicate on the "error_message" field. +func ErrorMessageEqualFold(v string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldEqualFold(FieldErrorMessage, v)) +} + +// ErrorMessageContainsFold applies the ContainsFold predicate on the "error_message" field. +func ErrorMessageContainsFold(v string) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldContainsFold(FieldErrorMessage, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// HasUser applies the HasEdge predicate on the "user" edge. +func HasUser() predicate.SecurityScanning { + return predicate.SecurityScanning(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.SecurityScanning { + return predicate.SecurityScanning(func(s *sql.Selector) { + step := newUserStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasResults applies the HasEdge predicate on the "results" edge. +func HasResults() predicate.SecurityScanning { + return predicate.SecurityScanning(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ResultsTable, ResultsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasResultsWith applies the HasEdge predicate on the "results" edge with a given conditions (other predicates). +func HasResultsWith(preds ...predicate.SecurityScanningResult) predicate.SecurityScanning { + return predicate.SecurityScanning(func(s *sql.Selector) { + step := newResultsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasWorkspaceEdge applies the HasEdge predicate on the "workspace_edge" edge. +func HasWorkspaceEdge() predicate.SecurityScanning { + return predicate.SecurityScanning(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, WorkspaceEdgeTable, WorkspaceEdgeColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasWorkspaceEdgeWith applies the HasEdge predicate on the "workspace_edge" edge with a given conditions (other predicates). +func HasWorkspaceEdgeWith(preds ...predicate.Workspace) predicate.SecurityScanning { + return predicate.SecurityScanning(func(s *sql.Selector) { + step := newWorkspaceEdgeStep() + 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.SecurityScanning) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.SecurityScanning) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.SecurityScanning) predicate.SecurityScanning { + return predicate.SecurityScanning(sql.NotPredicates(p)) +} diff --git a/backend/db/securityscanning_create.go b/backend/db/securityscanning_create.go new file mode 100644 index 0000000..02d7749 --- /dev/null +++ b/backend/db/securityscanning_create.go @@ -0,0 +1,1078 @@ +// 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/securityscanning" + "github.com/chaitin/MonkeyCode/backend/db/securityscanningresult" + "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/workspace" + "github.com/google/uuid" +) + +// SecurityScanningCreate is the builder for creating a SecurityScanning entity. +type SecurityScanningCreate struct { + config + mutation *SecurityScanningMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetUserID sets the "user_id" field. +func (ssc *SecurityScanningCreate) SetUserID(u uuid.UUID) *SecurityScanningCreate { + ssc.mutation.SetUserID(u) + return ssc +} + +// SetWorkspaceID sets the "workspace_id" field. +func (ssc *SecurityScanningCreate) SetWorkspaceID(u uuid.UUID) *SecurityScanningCreate { + ssc.mutation.SetWorkspaceID(u) + return ssc +} + +// SetStatus sets the "status" field. +func (ssc *SecurityScanningCreate) SetStatus(css consts.SecurityScanningStatus) *SecurityScanningCreate { + ssc.mutation.SetStatus(css) + return ssc +} + +// SetWorkspace sets the "workspace" field. +func (ssc *SecurityScanningCreate) SetWorkspace(s string) *SecurityScanningCreate { + ssc.mutation.SetWorkspace(s) + return ssc +} + +// SetLanguage sets the "language" field. +func (ssc *SecurityScanningCreate) SetLanguage(csl consts.SecurityScanningLanguage) *SecurityScanningCreate { + ssc.mutation.SetLanguage(csl) + return ssc +} + +// SetRule sets the "rule" field. +func (ssc *SecurityScanningCreate) SetRule(s string) *SecurityScanningCreate { + ssc.mutation.SetRule(s) + return ssc +} + +// SetNillableRule sets the "rule" field if the given value is not nil. +func (ssc *SecurityScanningCreate) SetNillableRule(s *string) *SecurityScanningCreate { + if s != nil { + ssc.SetRule(*s) + } + return ssc +} + +// SetErrorMessage sets the "error_message" field. +func (ssc *SecurityScanningCreate) SetErrorMessage(s string) *SecurityScanningCreate { + ssc.mutation.SetErrorMessage(s) + return ssc +} + +// SetNillableErrorMessage sets the "error_message" field if the given value is not nil. +func (ssc *SecurityScanningCreate) SetNillableErrorMessage(s *string) *SecurityScanningCreate { + if s != nil { + ssc.SetErrorMessage(*s) + } + return ssc +} + +// SetCreatedAt sets the "created_at" field. +func (ssc *SecurityScanningCreate) SetCreatedAt(t time.Time) *SecurityScanningCreate { + ssc.mutation.SetCreatedAt(t) + return ssc +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (ssc *SecurityScanningCreate) SetNillableCreatedAt(t *time.Time) *SecurityScanningCreate { + if t != nil { + ssc.SetCreatedAt(*t) + } + return ssc +} + +// SetUpdatedAt sets the "updated_at" field. +func (ssc *SecurityScanningCreate) SetUpdatedAt(t time.Time) *SecurityScanningCreate { + ssc.mutation.SetUpdatedAt(t) + return ssc +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (ssc *SecurityScanningCreate) SetNillableUpdatedAt(t *time.Time) *SecurityScanningCreate { + if t != nil { + ssc.SetUpdatedAt(*t) + } + return ssc +} + +// SetID sets the "id" field. +func (ssc *SecurityScanningCreate) SetID(u uuid.UUID) *SecurityScanningCreate { + ssc.mutation.SetID(u) + return ssc +} + +// SetUser sets the "user" edge to the User entity. +func (ssc *SecurityScanningCreate) SetUser(u *User) *SecurityScanningCreate { + return ssc.SetUserID(u.ID) +} + +// AddResultIDs adds the "results" edge to the SecurityScanningResult entity by IDs. +func (ssc *SecurityScanningCreate) AddResultIDs(ids ...uuid.UUID) *SecurityScanningCreate { + ssc.mutation.AddResultIDs(ids...) + return ssc +} + +// AddResults adds the "results" edges to the SecurityScanningResult entity. +func (ssc *SecurityScanningCreate) AddResults(s ...*SecurityScanningResult) *SecurityScanningCreate { + ids := make([]uuid.UUID, len(s)) + for i := range s { + ids[i] = s[i].ID + } + return ssc.AddResultIDs(ids...) +} + +// SetWorkspaceEdgeID sets the "workspace_edge" edge to the Workspace entity by ID. +func (ssc *SecurityScanningCreate) SetWorkspaceEdgeID(id uuid.UUID) *SecurityScanningCreate { + ssc.mutation.SetWorkspaceEdgeID(id) + return ssc +} + +// SetWorkspaceEdge sets the "workspace_edge" edge to the Workspace entity. +func (ssc *SecurityScanningCreate) SetWorkspaceEdge(w *Workspace) *SecurityScanningCreate { + return ssc.SetWorkspaceEdgeID(w.ID) +} + +// Mutation returns the SecurityScanningMutation object of the builder. +func (ssc *SecurityScanningCreate) Mutation() *SecurityScanningMutation { + return ssc.mutation +} + +// Save creates the SecurityScanning in the database. +func (ssc *SecurityScanningCreate) Save(ctx context.Context) (*SecurityScanning, error) { + ssc.defaults() + return withHooks(ctx, ssc.sqlSave, ssc.mutation, ssc.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (ssc *SecurityScanningCreate) SaveX(ctx context.Context) *SecurityScanning { + v, err := ssc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (ssc *SecurityScanningCreate) Exec(ctx context.Context) error { + _, err := ssc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ssc *SecurityScanningCreate) ExecX(ctx context.Context) { + if err := ssc.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (ssc *SecurityScanningCreate) defaults() { + if _, ok := ssc.mutation.CreatedAt(); !ok { + v := securityscanning.DefaultCreatedAt() + ssc.mutation.SetCreatedAt(v) + } + if _, ok := ssc.mutation.UpdatedAt(); !ok { + v := securityscanning.DefaultUpdatedAt() + ssc.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (ssc *SecurityScanningCreate) check() error { + if _, ok := ssc.mutation.UserID(); !ok { + return &ValidationError{Name: "user_id", err: errors.New(`db: missing required field "SecurityScanning.user_id"`)} + } + if _, ok := ssc.mutation.WorkspaceID(); !ok { + return &ValidationError{Name: "workspace_id", err: errors.New(`db: missing required field "SecurityScanning.workspace_id"`)} + } + if _, ok := ssc.mutation.Status(); !ok { + return &ValidationError{Name: "status", err: errors.New(`db: missing required field "SecurityScanning.status"`)} + } + if _, ok := ssc.mutation.Workspace(); !ok { + return &ValidationError{Name: "workspace", err: errors.New(`db: missing required field "SecurityScanning.workspace"`)} + } + if _, ok := ssc.mutation.Language(); !ok { + return &ValidationError{Name: "language", err: errors.New(`db: missing required field "SecurityScanning.language"`)} + } + if _, ok := ssc.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "SecurityScanning.created_at"`)} + } + if _, ok := ssc.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "SecurityScanning.updated_at"`)} + } + if len(ssc.mutation.UserIDs()) == 0 { + return &ValidationError{Name: "user", err: errors.New(`db: missing required edge "SecurityScanning.user"`)} + } + if len(ssc.mutation.WorkspaceEdgeIDs()) == 0 { + return &ValidationError{Name: "workspace_edge", err: errors.New(`db: missing required edge "SecurityScanning.workspace_edge"`)} + } + return nil +} + +func (ssc *SecurityScanningCreate) sqlSave(ctx context.Context) (*SecurityScanning, error) { + if err := ssc.check(); err != nil { + return nil, err + } + _node, _spec := ssc.createSpec() + if err := sqlgraph.CreateNode(ctx, ssc.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 + } + } + ssc.mutation.id = &_node.ID + ssc.mutation.done = true + return _node, nil +} + +func (ssc *SecurityScanningCreate) createSpec() (*SecurityScanning, *sqlgraph.CreateSpec) { + var ( + _node = &SecurityScanning{config: ssc.config} + _spec = sqlgraph.NewCreateSpec(securityscanning.Table, sqlgraph.NewFieldSpec(securityscanning.FieldID, field.TypeUUID)) + ) + _spec.OnConflict = ssc.conflict + if id, ok := ssc.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = &id + } + if value, ok := ssc.mutation.Status(); ok { + _spec.SetField(securityscanning.FieldStatus, field.TypeString, value) + _node.Status = value + } + if value, ok := ssc.mutation.Workspace(); ok { + _spec.SetField(securityscanning.FieldWorkspace, field.TypeString, value) + _node.Workspace = value + } + if value, ok := ssc.mutation.Language(); ok { + _spec.SetField(securityscanning.FieldLanguage, field.TypeString, value) + _node.Language = value + } + if value, ok := ssc.mutation.Rule(); ok { + _spec.SetField(securityscanning.FieldRule, field.TypeString, value) + _node.Rule = value + } + if value, ok := ssc.mutation.ErrorMessage(); ok { + _spec.SetField(securityscanning.FieldErrorMessage, field.TypeString, value) + _node.ErrorMessage = value + } + if value, ok := ssc.mutation.CreatedAt(); ok { + _spec.SetField(securityscanning.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := ssc.mutation.UpdatedAt(); ok { + _spec.SetField(securityscanning.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if nodes := ssc.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: securityscanning.UserTable, + Columns: []string{securityscanning.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 := ssc.mutation.ResultsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: securityscanning.ResultsTable, + Columns: []string{securityscanning.ResultsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(securityscanningresult.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := ssc.mutation.WorkspaceEdgeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: securityscanning.WorkspaceEdgeTable, + Columns: []string{securityscanning.WorkspaceEdgeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(workspace.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.WorkspaceID = 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.SecurityScanning.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.SecurityScanningUpsert) { +// SetUserID(v+v). +// }). +// Exec(ctx) +func (ssc *SecurityScanningCreate) OnConflict(opts ...sql.ConflictOption) *SecurityScanningUpsertOne { + ssc.conflict = opts + return &SecurityScanningUpsertOne{ + create: ssc, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.SecurityScanning.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (ssc *SecurityScanningCreate) OnConflictColumns(columns ...string) *SecurityScanningUpsertOne { + ssc.conflict = append(ssc.conflict, sql.ConflictColumns(columns...)) + return &SecurityScanningUpsertOne{ + create: ssc, + } +} + +type ( + // SecurityScanningUpsertOne is the builder for "upsert"-ing + // one SecurityScanning node. + SecurityScanningUpsertOne struct { + create *SecurityScanningCreate + } + + // SecurityScanningUpsert is the "OnConflict" setter. + SecurityScanningUpsert struct { + *sql.UpdateSet + } +) + +// SetUserID sets the "user_id" field. +func (u *SecurityScanningUpsert) SetUserID(v uuid.UUID) *SecurityScanningUpsert { + u.Set(securityscanning.FieldUserID, v) + return u +} + +// UpdateUserID sets the "user_id" field to the value that was provided on create. +func (u *SecurityScanningUpsert) UpdateUserID() *SecurityScanningUpsert { + u.SetExcluded(securityscanning.FieldUserID) + return u +} + +// SetWorkspaceID sets the "workspace_id" field. +func (u *SecurityScanningUpsert) SetWorkspaceID(v uuid.UUID) *SecurityScanningUpsert { + u.Set(securityscanning.FieldWorkspaceID, v) + return u +} + +// UpdateWorkspaceID sets the "workspace_id" field to the value that was provided on create. +func (u *SecurityScanningUpsert) UpdateWorkspaceID() *SecurityScanningUpsert { + u.SetExcluded(securityscanning.FieldWorkspaceID) + return u +} + +// SetStatus sets the "status" field. +func (u *SecurityScanningUpsert) SetStatus(v consts.SecurityScanningStatus) *SecurityScanningUpsert { + u.Set(securityscanning.FieldStatus, v) + return u +} + +// UpdateStatus sets the "status" field to the value that was provided on create. +func (u *SecurityScanningUpsert) UpdateStatus() *SecurityScanningUpsert { + u.SetExcluded(securityscanning.FieldStatus) + return u +} + +// SetWorkspace sets the "workspace" field. +func (u *SecurityScanningUpsert) SetWorkspace(v string) *SecurityScanningUpsert { + u.Set(securityscanning.FieldWorkspace, v) + return u +} + +// UpdateWorkspace sets the "workspace" field to the value that was provided on create. +func (u *SecurityScanningUpsert) UpdateWorkspace() *SecurityScanningUpsert { + u.SetExcluded(securityscanning.FieldWorkspace) + return u +} + +// SetLanguage sets the "language" field. +func (u *SecurityScanningUpsert) SetLanguage(v consts.SecurityScanningLanguage) *SecurityScanningUpsert { + u.Set(securityscanning.FieldLanguage, v) + return u +} + +// UpdateLanguage sets the "language" field to the value that was provided on create. +func (u *SecurityScanningUpsert) UpdateLanguage() *SecurityScanningUpsert { + u.SetExcluded(securityscanning.FieldLanguage) + return u +} + +// SetRule sets the "rule" field. +func (u *SecurityScanningUpsert) SetRule(v string) *SecurityScanningUpsert { + u.Set(securityscanning.FieldRule, v) + return u +} + +// UpdateRule sets the "rule" field to the value that was provided on create. +func (u *SecurityScanningUpsert) UpdateRule() *SecurityScanningUpsert { + u.SetExcluded(securityscanning.FieldRule) + return u +} + +// ClearRule clears the value of the "rule" field. +func (u *SecurityScanningUpsert) ClearRule() *SecurityScanningUpsert { + u.SetNull(securityscanning.FieldRule) + return u +} + +// SetErrorMessage sets the "error_message" field. +func (u *SecurityScanningUpsert) SetErrorMessage(v string) *SecurityScanningUpsert { + u.Set(securityscanning.FieldErrorMessage, v) + return u +} + +// UpdateErrorMessage sets the "error_message" field to the value that was provided on create. +func (u *SecurityScanningUpsert) UpdateErrorMessage() *SecurityScanningUpsert { + u.SetExcluded(securityscanning.FieldErrorMessage) + return u +} + +// ClearErrorMessage clears the value of the "error_message" field. +func (u *SecurityScanningUpsert) ClearErrorMessage() *SecurityScanningUpsert { + u.SetNull(securityscanning.FieldErrorMessage) + return u +} + +// SetCreatedAt sets the "created_at" field. +func (u *SecurityScanningUpsert) SetCreatedAt(v time.Time) *SecurityScanningUpsert { + u.Set(securityscanning.FieldCreatedAt, v) + return u +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *SecurityScanningUpsert) UpdateCreatedAt() *SecurityScanningUpsert { + u.SetExcluded(securityscanning.FieldCreatedAt) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *SecurityScanningUpsert) SetUpdatedAt(v time.Time) *SecurityScanningUpsert { + u.Set(securityscanning.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *SecurityScanningUpsert) UpdateUpdatedAt() *SecurityScanningUpsert { + u.SetExcluded(securityscanning.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.SecurityScanning.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(securityscanning.FieldID) +// }), +// ). +// Exec(ctx) +func (u *SecurityScanningUpsertOne) UpdateNewValues() *SecurityScanningUpsertOne { + 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(securityscanning.FieldID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.SecurityScanning.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *SecurityScanningUpsertOne) Ignore() *SecurityScanningUpsertOne { + 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 *SecurityScanningUpsertOne) DoNothing() *SecurityScanningUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the SecurityScanningCreate.OnConflict +// documentation for more info. +func (u *SecurityScanningUpsertOne) Update(set func(*SecurityScanningUpsert)) *SecurityScanningUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&SecurityScanningUpsert{UpdateSet: update}) + })) + return u +} + +// SetUserID sets the "user_id" field. +func (u *SecurityScanningUpsertOne) SetUserID(v uuid.UUID) *SecurityScanningUpsertOne { + return u.Update(func(s *SecurityScanningUpsert) { + s.SetUserID(v) + }) +} + +// UpdateUserID sets the "user_id" field to the value that was provided on create. +func (u *SecurityScanningUpsertOne) UpdateUserID() *SecurityScanningUpsertOne { + return u.Update(func(s *SecurityScanningUpsert) { + s.UpdateUserID() + }) +} + +// SetWorkspaceID sets the "workspace_id" field. +func (u *SecurityScanningUpsertOne) SetWorkspaceID(v uuid.UUID) *SecurityScanningUpsertOne { + return u.Update(func(s *SecurityScanningUpsert) { + s.SetWorkspaceID(v) + }) +} + +// UpdateWorkspaceID sets the "workspace_id" field to the value that was provided on create. +func (u *SecurityScanningUpsertOne) UpdateWorkspaceID() *SecurityScanningUpsertOne { + return u.Update(func(s *SecurityScanningUpsert) { + s.UpdateWorkspaceID() + }) +} + +// SetStatus sets the "status" field. +func (u *SecurityScanningUpsertOne) SetStatus(v consts.SecurityScanningStatus) *SecurityScanningUpsertOne { + return u.Update(func(s *SecurityScanningUpsert) { + s.SetStatus(v) + }) +} + +// UpdateStatus sets the "status" field to the value that was provided on create. +func (u *SecurityScanningUpsertOne) UpdateStatus() *SecurityScanningUpsertOne { + return u.Update(func(s *SecurityScanningUpsert) { + s.UpdateStatus() + }) +} + +// SetWorkspace sets the "workspace" field. +func (u *SecurityScanningUpsertOne) SetWorkspace(v string) *SecurityScanningUpsertOne { + return u.Update(func(s *SecurityScanningUpsert) { + s.SetWorkspace(v) + }) +} + +// UpdateWorkspace sets the "workspace" field to the value that was provided on create. +func (u *SecurityScanningUpsertOne) UpdateWorkspace() *SecurityScanningUpsertOne { + return u.Update(func(s *SecurityScanningUpsert) { + s.UpdateWorkspace() + }) +} + +// SetLanguage sets the "language" field. +func (u *SecurityScanningUpsertOne) SetLanguage(v consts.SecurityScanningLanguage) *SecurityScanningUpsertOne { + return u.Update(func(s *SecurityScanningUpsert) { + s.SetLanguage(v) + }) +} + +// UpdateLanguage sets the "language" field to the value that was provided on create. +func (u *SecurityScanningUpsertOne) UpdateLanguage() *SecurityScanningUpsertOne { + return u.Update(func(s *SecurityScanningUpsert) { + s.UpdateLanguage() + }) +} + +// SetRule sets the "rule" field. +func (u *SecurityScanningUpsertOne) SetRule(v string) *SecurityScanningUpsertOne { + return u.Update(func(s *SecurityScanningUpsert) { + s.SetRule(v) + }) +} + +// UpdateRule sets the "rule" field to the value that was provided on create. +func (u *SecurityScanningUpsertOne) UpdateRule() *SecurityScanningUpsertOne { + return u.Update(func(s *SecurityScanningUpsert) { + s.UpdateRule() + }) +} + +// ClearRule clears the value of the "rule" field. +func (u *SecurityScanningUpsertOne) ClearRule() *SecurityScanningUpsertOne { + return u.Update(func(s *SecurityScanningUpsert) { + s.ClearRule() + }) +} + +// SetErrorMessage sets the "error_message" field. +func (u *SecurityScanningUpsertOne) SetErrorMessage(v string) *SecurityScanningUpsertOne { + return u.Update(func(s *SecurityScanningUpsert) { + s.SetErrorMessage(v) + }) +} + +// UpdateErrorMessage sets the "error_message" field to the value that was provided on create. +func (u *SecurityScanningUpsertOne) UpdateErrorMessage() *SecurityScanningUpsertOne { + return u.Update(func(s *SecurityScanningUpsert) { + s.UpdateErrorMessage() + }) +} + +// ClearErrorMessage clears the value of the "error_message" field. +func (u *SecurityScanningUpsertOne) ClearErrorMessage() *SecurityScanningUpsertOne { + return u.Update(func(s *SecurityScanningUpsert) { + s.ClearErrorMessage() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *SecurityScanningUpsertOne) SetCreatedAt(v time.Time) *SecurityScanningUpsertOne { + return u.Update(func(s *SecurityScanningUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *SecurityScanningUpsertOne) UpdateCreatedAt() *SecurityScanningUpsertOne { + return u.Update(func(s *SecurityScanningUpsert) { + s.UpdateCreatedAt() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *SecurityScanningUpsertOne) SetUpdatedAt(v time.Time) *SecurityScanningUpsertOne { + return u.Update(func(s *SecurityScanningUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *SecurityScanningUpsertOne) UpdateUpdatedAt() *SecurityScanningUpsertOne { + return u.Update(func(s *SecurityScanningUpsert) { + s.UpdateUpdatedAt() + }) +} + +// Exec executes the query. +func (u *SecurityScanningUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for SecurityScanningCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *SecurityScanningUpsertOne) 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 *SecurityScanningUpsertOne) 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: SecurityScanningUpsertOne.ID is not supported by MySQL driver. Use SecurityScanningUpsertOne.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 *SecurityScanningUpsertOne) IDX(ctx context.Context) uuid.UUID { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// SecurityScanningCreateBulk is the builder for creating many SecurityScanning entities in bulk. +type SecurityScanningCreateBulk struct { + config + err error + builders []*SecurityScanningCreate + conflict []sql.ConflictOption +} + +// Save creates the SecurityScanning entities in the database. +func (sscb *SecurityScanningCreateBulk) Save(ctx context.Context) ([]*SecurityScanning, error) { + if sscb.err != nil { + return nil, sscb.err + } + specs := make([]*sqlgraph.CreateSpec, len(sscb.builders)) + nodes := make([]*SecurityScanning, len(sscb.builders)) + mutators := make([]Mutator, len(sscb.builders)) + for i := range sscb.builders { + func(i int, root context.Context) { + builder := sscb.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*SecurityScanningMutation) + 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, sscb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = sscb.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, sscb.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, sscb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (sscb *SecurityScanningCreateBulk) SaveX(ctx context.Context) []*SecurityScanning { + v, err := sscb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (sscb *SecurityScanningCreateBulk) Exec(ctx context.Context) error { + _, err := sscb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (sscb *SecurityScanningCreateBulk) ExecX(ctx context.Context) { + if err := sscb.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.SecurityScanning.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.SecurityScanningUpsert) { +// SetUserID(v+v). +// }). +// Exec(ctx) +func (sscb *SecurityScanningCreateBulk) OnConflict(opts ...sql.ConflictOption) *SecurityScanningUpsertBulk { + sscb.conflict = opts + return &SecurityScanningUpsertBulk{ + create: sscb, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.SecurityScanning.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (sscb *SecurityScanningCreateBulk) OnConflictColumns(columns ...string) *SecurityScanningUpsertBulk { + sscb.conflict = append(sscb.conflict, sql.ConflictColumns(columns...)) + return &SecurityScanningUpsertBulk{ + create: sscb, + } +} + +// SecurityScanningUpsertBulk is the builder for "upsert"-ing +// a bulk of SecurityScanning nodes. +type SecurityScanningUpsertBulk struct { + create *SecurityScanningCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.SecurityScanning.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(securityscanning.FieldID) +// }), +// ). +// Exec(ctx) +func (u *SecurityScanningUpsertBulk) UpdateNewValues() *SecurityScanningUpsertBulk { + 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(securityscanning.FieldID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.SecurityScanning.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *SecurityScanningUpsertBulk) Ignore() *SecurityScanningUpsertBulk { + 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 *SecurityScanningUpsertBulk) DoNothing() *SecurityScanningUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the SecurityScanningCreateBulk.OnConflict +// documentation for more info. +func (u *SecurityScanningUpsertBulk) Update(set func(*SecurityScanningUpsert)) *SecurityScanningUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&SecurityScanningUpsert{UpdateSet: update}) + })) + return u +} + +// SetUserID sets the "user_id" field. +func (u *SecurityScanningUpsertBulk) SetUserID(v uuid.UUID) *SecurityScanningUpsertBulk { + return u.Update(func(s *SecurityScanningUpsert) { + s.SetUserID(v) + }) +} + +// UpdateUserID sets the "user_id" field to the value that was provided on create. +func (u *SecurityScanningUpsertBulk) UpdateUserID() *SecurityScanningUpsertBulk { + return u.Update(func(s *SecurityScanningUpsert) { + s.UpdateUserID() + }) +} + +// SetWorkspaceID sets the "workspace_id" field. +func (u *SecurityScanningUpsertBulk) SetWorkspaceID(v uuid.UUID) *SecurityScanningUpsertBulk { + return u.Update(func(s *SecurityScanningUpsert) { + s.SetWorkspaceID(v) + }) +} + +// UpdateWorkspaceID sets the "workspace_id" field to the value that was provided on create. +func (u *SecurityScanningUpsertBulk) UpdateWorkspaceID() *SecurityScanningUpsertBulk { + return u.Update(func(s *SecurityScanningUpsert) { + s.UpdateWorkspaceID() + }) +} + +// SetStatus sets the "status" field. +func (u *SecurityScanningUpsertBulk) SetStatus(v consts.SecurityScanningStatus) *SecurityScanningUpsertBulk { + return u.Update(func(s *SecurityScanningUpsert) { + s.SetStatus(v) + }) +} + +// UpdateStatus sets the "status" field to the value that was provided on create. +func (u *SecurityScanningUpsertBulk) UpdateStatus() *SecurityScanningUpsertBulk { + return u.Update(func(s *SecurityScanningUpsert) { + s.UpdateStatus() + }) +} + +// SetWorkspace sets the "workspace" field. +func (u *SecurityScanningUpsertBulk) SetWorkspace(v string) *SecurityScanningUpsertBulk { + return u.Update(func(s *SecurityScanningUpsert) { + s.SetWorkspace(v) + }) +} + +// UpdateWorkspace sets the "workspace" field to the value that was provided on create. +func (u *SecurityScanningUpsertBulk) UpdateWorkspace() *SecurityScanningUpsertBulk { + return u.Update(func(s *SecurityScanningUpsert) { + s.UpdateWorkspace() + }) +} + +// SetLanguage sets the "language" field. +func (u *SecurityScanningUpsertBulk) SetLanguage(v consts.SecurityScanningLanguage) *SecurityScanningUpsertBulk { + return u.Update(func(s *SecurityScanningUpsert) { + s.SetLanguage(v) + }) +} + +// UpdateLanguage sets the "language" field to the value that was provided on create. +func (u *SecurityScanningUpsertBulk) UpdateLanguage() *SecurityScanningUpsertBulk { + return u.Update(func(s *SecurityScanningUpsert) { + s.UpdateLanguage() + }) +} + +// SetRule sets the "rule" field. +func (u *SecurityScanningUpsertBulk) SetRule(v string) *SecurityScanningUpsertBulk { + return u.Update(func(s *SecurityScanningUpsert) { + s.SetRule(v) + }) +} + +// UpdateRule sets the "rule" field to the value that was provided on create. +func (u *SecurityScanningUpsertBulk) UpdateRule() *SecurityScanningUpsertBulk { + return u.Update(func(s *SecurityScanningUpsert) { + s.UpdateRule() + }) +} + +// ClearRule clears the value of the "rule" field. +func (u *SecurityScanningUpsertBulk) ClearRule() *SecurityScanningUpsertBulk { + return u.Update(func(s *SecurityScanningUpsert) { + s.ClearRule() + }) +} + +// SetErrorMessage sets the "error_message" field. +func (u *SecurityScanningUpsertBulk) SetErrorMessage(v string) *SecurityScanningUpsertBulk { + return u.Update(func(s *SecurityScanningUpsert) { + s.SetErrorMessage(v) + }) +} + +// UpdateErrorMessage sets the "error_message" field to the value that was provided on create. +func (u *SecurityScanningUpsertBulk) UpdateErrorMessage() *SecurityScanningUpsertBulk { + return u.Update(func(s *SecurityScanningUpsert) { + s.UpdateErrorMessage() + }) +} + +// ClearErrorMessage clears the value of the "error_message" field. +func (u *SecurityScanningUpsertBulk) ClearErrorMessage() *SecurityScanningUpsertBulk { + return u.Update(func(s *SecurityScanningUpsert) { + s.ClearErrorMessage() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *SecurityScanningUpsertBulk) SetCreatedAt(v time.Time) *SecurityScanningUpsertBulk { + return u.Update(func(s *SecurityScanningUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *SecurityScanningUpsertBulk) UpdateCreatedAt() *SecurityScanningUpsertBulk { + return u.Update(func(s *SecurityScanningUpsert) { + s.UpdateCreatedAt() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *SecurityScanningUpsertBulk) SetUpdatedAt(v time.Time) *SecurityScanningUpsertBulk { + return u.Update(func(s *SecurityScanningUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *SecurityScanningUpsertBulk) UpdateUpdatedAt() *SecurityScanningUpsertBulk { + return u.Update(func(s *SecurityScanningUpsert) { + s.UpdateUpdatedAt() + }) +} + +// Exec executes the query. +func (u *SecurityScanningUpsertBulk) 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 SecurityScanningCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for SecurityScanningCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *SecurityScanningUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/securityscanning_delete.go b/backend/db/securityscanning_delete.go new file mode 100644 index 0000000..156ef37 --- /dev/null +++ b/backend/db/securityscanning_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/securityscanning" +) + +// SecurityScanningDelete is the builder for deleting a SecurityScanning entity. +type SecurityScanningDelete struct { + config + hooks []Hook + mutation *SecurityScanningMutation +} + +// Where appends a list predicates to the SecurityScanningDelete builder. +func (ssd *SecurityScanningDelete) Where(ps ...predicate.SecurityScanning) *SecurityScanningDelete { + ssd.mutation.Where(ps...) + return ssd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (ssd *SecurityScanningDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, ssd.sqlExec, ssd.mutation, ssd.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (ssd *SecurityScanningDelete) ExecX(ctx context.Context) int { + n, err := ssd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (ssd *SecurityScanningDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(securityscanning.Table, sqlgraph.NewFieldSpec(securityscanning.FieldID, field.TypeUUID)) + if ps := ssd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, ssd.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + ssd.mutation.done = true + return affected, err +} + +// SecurityScanningDeleteOne is the builder for deleting a single SecurityScanning entity. +type SecurityScanningDeleteOne struct { + ssd *SecurityScanningDelete +} + +// Where appends a list predicates to the SecurityScanningDelete builder. +func (ssdo *SecurityScanningDeleteOne) Where(ps ...predicate.SecurityScanning) *SecurityScanningDeleteOne { + ssdo.ssd.mutation.Where(ps...) + return ssdo +} + +// Exec executes the deletion query. +func (ssdo *SecurityScanningDeleteOne) Exec(ctx context.Context) error { + n, err := ssdo.ssd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{securityscanning.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (ssdo *SecurityScanningDeleteOne) ExecX(ctx context.Context) { + if err := ssdo.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/securityscanning_query.go b/backend/db/securityscanning_query.go new file mode 100644 index 0000000..5d9be77 --- /dev/null +++ b/backend/db/securityscanning_query.go @@ -0,0 +1,807 @@ +// 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/predicate" + "github.com/chaitin/MonkeyCode/backend/db/securityscanning" + "github.com/chaitin/MonkeyCode/backend/db/securityscanningresult" + "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/workspace" + "github.com/google/uuid" +) + +// SecurityScanningQuery is the builder for querying SecurityScanning entities. +type SecurityScanningQuery struct { + config + ctx *QueryContext + order []securityscanning.OrderOption + inters []Interceptor + predicates []predicate.SecurityScanning + withUser *UserQuery + withResults *SecurityScanningResultQuery + withWorkspaceEdge *WorkspaceQuery + 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 SecurityScanningQuery builder. +func (ssq *SecurityScanningQuery) Where(ps ...predicate.SecurityScanning) *SecurityScanningQuery { + ssq.predicates = append(ssq.predicates, ps...) + return ssq +} + +// Limit the number of records to be returned by this query. +func (ssq *SecurityScanningQuery) Limit(limit int) *SecurityScanningQuery { + ssq.ctx.Limit = &limit + return ssq +} + +// Offset to start from. +func (ssq *SecurityScanningQuery) Offset(offset int) *SecurityScanningQuery { + ssq.ctx.Offset = &offset + return ssq +} + +// 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 (ssq *SecurityScanningQuery) Unique(unique bool) *SecurityScanningQuery { + ssq.ctx.Unique = &unique + return ssq +} + +// Order specifies how the records should be ordered. +func (ssq *SecurityScanningQuery) Order(o ...securityscanning.OrderOption) *SecurityScanningQuery { + ssq.order = append(ssq.order, o...) + return ssq +} + +// QueryUser chains the current query on the "user" edge. +func (ssq *SecurityScanningQuery) QueryUser() *UserQuery { + query := (&UserClient{config: ssq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := ssq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := ssq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(securityscanning.Table, securityscanning.FieldID, selector), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, securityscanning.UserTable, securityscanning.UserColumn), + ) + fromU = sqlgraph.SetNeighbors(ssq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryResults chains the current query on the "results" edge. +func (ssq *SecurityScanningQuery) QueryResults() *SecurityScanningResultQuery { + query := (&SecurityScanningResultClient{config: ssq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := ssq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := ssq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(securityscanning.Table, securityscanning.FieldID, selector), + sqlgraph.To(securityscanningresult.Table, securityscanningresult.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, securityscanning.ResultsTable, securityscanning.ResultsColumn), + ) + fromU = sqlgraph.SetNeighbors(ssq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryWorkspaceEdge chains the current query on the "workspace_edge" edge. +func (ssq *SecurityScanningQuery) QueryWorkspaceEdge() *WorkspaceQuery { + query := (&WorkspaceClient{config: ssq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := ssq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := ssq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(securityscanning.Table, securityscanning.FieldID, selector), + sqlgraph.To(workspace.Table, workspace.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, securityscanning.WorkspaceEdgeTable, securityscanning.WorkspaceEdgeColumn), + ) + fromU = sqlgraph.SetNeighbors(ssq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first SecurityScanning entity from the query. +// Returns a *NotFoundError when no SecurityScanning was found. +func (ssq *SecurityScanningQuery) First(ctx context.Context) (*SecurityScanning, error) { + nodes, err := ssq.Limit(1).All(setContextOp(ctx, ssq.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{securityscanning.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (ssq *SecurityScanningQuery) FirstX(ctx context.Context) *SecurityScanning { + node, err := ssq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first SecurityScanning ID from the query. +// Returns a *NotFoundError when no SecurityScanning ID was found. +func (ssq *SecurityScanningQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = ssq.Limit(1).IDs(setContextOp(ctx, ssq.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{securityscanning.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (ssq *SecurityScanningQuery) FirstIDX(ctx context.Context) uuid.UUID { + id, err := ssq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single SecurityScanning entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one SecurityScanning entity is found. +// Returns a *NotFoundError when no SecurityScanning entities are found. +func (ssq *SecurityScanningQuery) Only(ctx context.Context) (*SecurityScanning, error) { + nodes, err := ssq.Limit(2).All(setContextOp(ctx, ssq.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{securityscanning.Label} + default: + return nil, &NotSingularError{securityscanning.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (ssq *SecurityScanningQuery) OnlyX(ctx context.Context) *SecurityScanning { + node, err := ssq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only SecurityScanning ID in the query. +// Returns a *NotSingularError when more than one SecurityScanning ID is found. +// Returns a *NotFoundError when no entities are found. +func (ssq *SecurityScanningQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = ssq.Limit(2).IDs(setContextOp(ctx, ssq.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{securityscanning.Label} + default: + err = &NotSingularError{securityscanning.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (ssq *SecurityScanningQuery) OnlyIDX(ctx context.Context) uuid.UUID { + id, err := ssq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of SecurityScannings. +func (ssq *SecurityScanningQuery) All(ctx context.Context) ([]*SecurityScanning, error) { + ctx = setContextOp(ctx, ssq.ctx, ent.OpQueryAll) + if err := ssq.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*SecurityScanning, *SecurityScanningQuery]() + return withInterceptors[[]*SecurityScanning](ctx, ssq, qr, ssq.inters) +} + +// AllX is like All, but panics if an error occurs. +func (ssq *SecurityScanningQuery) AllX(ctx context.Context) []*SecurityScanning { + nodes, err := ssq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of SecurityScanning IDs. +func (ssq *SecurityScanningQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) { + if ssq.ctx.Unique == nil && ssq.path != nil { + ssq.Unique(true) + } + ctx = setContextOp(ctx, ssq.ctx, ent.OpQueryIDs) + if err = ssq.Select(securityscanning.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (ssq *SecurityScanningQuery) IDsX(ctx context.Context) []uuid.UUID { + ids, err := ssq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (ssq *SecurityScanningQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, ssq.ctx, ent.OpQueryCount) + if err := ssq.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, ssq, querierCount[*SecurityScanningQuery](), ssq.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (ssq *SecurityScanningQuery) CountX(ctx context.Context) int { + count, err := ssq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (ssq *SecurityScanningQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, ssq.ctx, ent.OpQueryExist) + switch _, err := ssq.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 (ssq *SecurityScanningQuery) ExistX(ctx context.Context) bool { + exist, err := ssq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the SecurityScanningQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (ssq *SecurityScanningQuery) Clone() *SecurityScanningQuery { + if ssq == nil { + return nil + } + return &SecurityScanningQuery{ + config: ssq.config, + ctx: ssq.ctx.Clone(), + order: append([]securityscanning.OrderOption{}, ssq.order...), + inters: append([]Interceptor{}, ssq.inters...), + predicates: append([]predicate.SecurityScanning{}, ssq.predicates...), + withUser: ssq.withUser.Clone(), + withResults: ssq.withResults.Clone(), + withWorkspaceEdge: ssq.withWorkspaceEdge.Clone(), + // clone intermediate query. + sql: ssq.sql.Clone(), + path: ssq.path, + modifiers: append([]func(*sql.Selector){}, ssq.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 (ssq *SecurityScanningQuery) WithUser(opts ...func(*UserQuery)) *SecurityScanningQuery { + query := (&UserClient{config: ssq.config}).Query() + for _, opt := range opts { + opt(query) + } + ssq.withUser = query + return ssq +} + +// WithResults tells the query-builder to eager-load the nodes that are connected to +// the "results" edge. The optional arguments are used to configure the query builder of the edge. +func (ssq *SecurityScanningQuery) WithResults(opts ...func(*SecurityScanningResultQuery)) *SecurityScanningQuery { + query := (&SecurityScanningResultClient{config: ssq.config}).Query() + for _, opt := range opts { + opt(query) + } + ssq.withResults = query + return ssq +} + +// WithWorkspaceEdge tells the query-builder to eager-load the nodes that are connected to +// the "workspace_edge" edge. The optional arguments are used to configure the query builder of the edge. +func (ssq *SecurityScanningQuery) WithWorkspaceEdge(opts ...func(*WorkspaceQuery)) *SecurityScanningQuery { + query := (&WorkspaceClient{config: ssq.config}).Query() + for _, opt := range opts { + opt(query) + } + ssq.withWorkspaceEdge = query + return ssq +} + +// 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.SecurityScanning.Query(). +// GroupBy(securityscanning.FieldUserID). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (ssq *SecurityScanningQuery) GroupBy(field string, fields ...string) *SecurityScanningGroupBy { + ssq.ctx.Fields = append([]string{field}, fields...) + grbuild := &SecurityScanningGroupBy{build: ssq} + grbuild.flds = &ssq.ctx.Fields + grbuild.label = securityscanning.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.SecurityScanning.Query(). +// Select(securityscanning.FieldUserID). +// Scan(ctx, &v) +func (ssq *SecurityScanningQuery) Select(fields ...string) *SecurityScanningSelect { + ssq.ctx.Fields = append(ssq.ctx.Fields, fields...) + sbuild := &SecurityScanningSelect{SecurityScanningQuery: ssq} + sbuild.label = securityscanning.Label + sbuild.flds, sbuild.scan = &ssq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a SecurityScanningSelect configured with the given aggregations. +func (ssq *SecurityScanningQuery) Aggregate(fns ...AggregateFunc) *SecurityScanningSelect { + return ssq.Select().Aggregate(fns...) +} + +func (ssq *SecurityScanningQuery) prepareQuery(ctx context.Context) error { + for _, inter := range ssq.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, ssq); err != nil { + return err + } + } + } + for _, f := range ssq.ctx.Fields { + if !securityscanning.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + } + if ssq.path != nil { + prev, err := ssq.path(ctx) + if err != nil { + return err + } + ssq.sql = prev + } + return nil +} + +func (ssq *SecurityScanningQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*SecurityScanning, error) { + var ( + nodes = []*SecurityScanning{} + _spec = ssq.querySpec() + loadedTypes = [3]bool{ + ssq.withUser != nil, + ssq.withResults != nil, + ssq.withWorkspaceEdge != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*SecurityScanning).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &SecurityScanning{config: ssq.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(ssq.modifiers) > 0 { + _spec.Modifiers = ssq.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, ssq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := ssq.withUser; query != nil { + if err := ssq.loadUser(ctx, query, nodes, nil, + func(n *SecurityScanning, e *User) { n.Edges.User = e }); err != nil { + return nil, err + } + } + if query := ssq.withResults; query != nil { + if err := ssq.loadResults(ctx, query, nodes, + func(n *SecurityScanning) { n.Edges.Results = []*SecurityScanningResult{} }, + func(n *SecurityScanning, e *SecurityScanningResult) { n.Edges.Results = append(n.Edges.Results, e) }); err != nil { + return nil, err + } + } + if query := ssq.withWorkspaceEdge; query != nil { + if err := ssq.loadWorkspaceEdge(ctx, query, nodes, nil, + func(n *SecurityScanning, e *Workspace) { n.Edges.WorkspaceEdge = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (ssq *SecurityScanningQuery) loadUser(ctx context.Context, query *UserQuery, nodes []*SecurityScanning, init func(*SecurityScanning), assign func(*SecurityScanning, *User)) error { + ids := make([]uuid.UUID, 0, len(nodes)) + nodeids := make(map[uuid.UUID][]*SecurityScanning) + 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 (ssq *SecurityScanningQuery) loadResults(ctx context.Context, query *SecurityScanningResultQuery, nodes []*SecurityScanning, init func(*SecurityScanning), assign func(*SecurityScanning, *SecurityScanningResult)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[uuid.UUID]*SecurityScanning) + 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(securityscanningresult.FieldSecurityScanningID) + } + query.Where(predicate.SecurityScanningResult(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(securityscanning.ResultsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.SecurityScanningID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "security_scanning_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} +func (ssq *SecurityScanningQuery) loadWorkspaceEdge(ctx context.Context, query *WorkspaceQuery, nodes []*SecurityScanning, init func(*SecurityScanning), assign func(*SecurityScanning, *Workspace)) error { + ids := make([]uuid.UUID, 0, len(nodes)) + nodeids := make(map[uuid.UUID][]*SecurityScanning) + for i := range nodes { + fk := nodes[i].WorkspaceID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(workspace.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 "workspace_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (ssq *SecurityScanningQuery) sqlCount(ctx context.Context) (int, error) { + _spec := ssq.querySpec() + if len(ssq.modifiers) > 0 { + _spec.Modifiers = ssq.modifiers + } + _spec.Node.Columns = ssq.ctx.Fields + if len(ssq.ctx.Fields) > 0 { + _spec.Unique = ssq.ctx.Unique != nil && *ssq.ctx.Unique + } + return sqlgraph.CountNodes(ctx, ssq.driver, _spec) +} + +func (ssq *SecurityScanningQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(securityscanning.Table, securityscanning.Columns, sqlgraph.NewFieldSpec(securityscanning.FieldID, field.TypeUUID)) + _spec.From = ssq.sql + if unique := ssq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if ssq.path != nil { + _spec.Unique = true + } + if fields := ssq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, securityscanning.FieldID) + for i := range fields { + if fields[i] != securityscanning.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if ssq.withUser != nil { + _spec.Node.AddColumnOnce(securityscanning.FieldUserID) + } + if ssq.withWorkspaceEdge != nil { + _spec.Node.AddColumnOnce(securityscanning.FieldWorkspaceID) + } + } + if ps := ssq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := ssq.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := ssq.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := ssq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (ssq *SecurityScanningQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(ssq.driver.Dialect()) + t1 := builder.Table(securityscanning.Table) + columns := ssq.ctx.Fields + if len(columns) == 0 { + columns = securityscanning.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if ssq.sql != nil { + selector = ssq.sql + selector.Select(selector.Columns(columns...)...) + } + if ssq.ctx.Unique != nil && *ssq.ctx.Unique { + selector.Distinct() + } + for _, m := range ssq.modifiers { + m(selector) + } + for _, p := range ssq.predicates { + p(selector) + } + for _, p := range ssq.order { + p(selector) + } + if offset := ssq.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 := ssq.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 (ssq *SecurityScanningQuery) ForUpdate(opts ...sql.LockOption) *SecurityScanningQuery { + if ssq.driver.Dialect() == dialect.Postgres { + ssq.Unique(false) + } + ssq.modifiers = append(ssq.modifiers, func(s *sql.Selector) { + s.ForUpdate(opts...) + }) + return ssq +} + +// 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 (ssq *SecurityScanningQuery) ForShare(opts ...sql.LockOption) *SecurityScanningQuery { + if ssq.driver.Dialect() == dialect.Postgres { + ssq.Unique(false) + } + ssq.modifiers = append(ssq.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return ssq +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (ssq *SecurityScanningQuery) Modify(modifiers ...func(s *sql.Selector)) *SecurityScanningSelect { + ssq.modifiers = append(ssq.modifiers, modifiers...) + return ssq.Select() +} + +// SecurityScanningGroupBy is the group-by builder for SecurityScanning entities. +type SecurityScanningGroupBy struct { + selector + build *SecurityScanningQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (ssgb *SecurityScanningGroupBy) Aggregate(fns ...AggregateFunc) *SecurityScanningGroupBy { + ssgb.fns = append(ssgb.fns, fns...) + return ssgb +} + +// Scan applies the selector query and scans the result into the given value. +func (ssgb *SecurityScanningGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, ssgb.build.ctx, ent.OpQueryGroupBy) + if err := ssgb.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*SecurityScanningQuery, *SecurityScanningGroupBy](ctx, ssgb.build, ssgb, ssgb.build.inters, v) +} + +func (ssgb *SecurityScanningGroupBy) sqlScan(ctx context.Context, root *SecurityScanningQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(ssgb.fns)) + for _, fn := range ssgb.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*ssgb.flds)+len(ssgb.fns)) + for _, f := range *ssgb.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*ssgb.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := ssgb.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// SecurityScanningSelect is the builder for selecting fields of SecurityScanning entities. +type SecurityScanningSelect struct { + *SecurityScanningQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (sss *SecurityScanningSelect) Aggregate(fns ...AggregateFunc) *SecurityScanningSelect { + sss.fns = append(sss.fns, fns...) + return sss +} + +// Scan applies the selector query and scans the result into the given value. +func (sss *SecurityScanningSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, sss.ctx, ent.OpQuerySelect) + if err := sss.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*SecurityScanningQuery, *SecurityScanningSelect](ctx, sss.SecurityScanningQuery, sss, sss.inters, v) +} + +func (sss *SecurityScanningSelect) sqlScan(ctx context.Context, root *SecurityScanningQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(sss.fns)) + for _, fn := range sss.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*sss.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 := sss.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 (sss *SecurityScanningSelect) Modify(modifiers ...func(s *sql.Selector)) *SecurityScanningSelect { + sss.modifiers = append(sss.modifiers, modifiers...) + return sss +} diff --git a/backend/db/securityscanning_update.go b/backend/db/securityscanning_update.go new file mode 100644 index 0000000..9bc4475 --- /dev/null +++ b/backend/db/securityscanning_update.go @@ -0,0 +1,889 @@ +// 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/predicate" + "github.com/chaitin/MonkeyCode/backend/db/securityscanning" + "github.com/chaitin/MonkeyCode/backend/db/securityscanningresult" + "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/workspace" + "github.com/google/uuid" +) + +// SecurityScanningUpdate is the builder for updating SecurityScanning entities. +type SecurityScanningUpdate struct { + config + hooks []Hook + mutation *SecurityScanningMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the SecurityScanningUpdate builder. +func (ssu *SecurityScanningUpdate) Where(ps ...predicate.SecurityScanning) *SecurityScanningUpdate { + ssu.mutation.Where(ps...) + return ssu +} + +// SetUserID sets the "user_id" field. +func (ssu *SecurityScanningUpdate) SetUserID(u uuid.UUID) *SecurityScanningUpdate { + ssu.mutation.SetUserID(u) + return ssu +} + +// SetNillableUserID sets the "user_id" field if the given value is not nil. +func (ssu *SecurityScanningUpdate) SetNillableUserID(u *uuid.UUID) *SecurityScanningUpdate { + if u != nil { + ssu.SetUserID(*u) + } + return ssu +} + +// SetWorkspaceID sets the "workspace_id" field. +func (ssu *SecurityScanningUpdate) SetWorkspaceID(u uuid.UUID) *SecurityScanningUpdate { + ssu.mutation.SetWorkspaceID(u) + return ssu +} + +// SetNillableWorkspaceID sets the "workspace_id" field if the given value is not nil. +func (ssu *SecurityScanningUpdate) SetNillableWorkspaceID(u *uuid.UUID) *SecurityScanningUpdate { + if u != nil { + ssu.SetWorkspaceID(*u) + } + return ssu +} + +// SetStatus sets the "status" field. +func (ssu *SecurityScanningUpdate) SetStatus(css consts.SecurityScanningStatus) *SecurityScanningUpdate { + ssu.mutation.SetStatus(css) + return ssu +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (ssu *SecurityScanningUpdate) SetNillableStatus(css *consts.SecurityScanningStatus) *SecurityScanningUpdate { + if css != nil { + ssu.SetStatus(*css) + } + return ssu +} + +// SetWorkspace sets the "workspace" field. +func (ssu *SecurityScanningUpdate) SetWorkspace(s string) *SecurityScanningUpdate { + ssu.mutation.SetWorkspace(s) + return ssu +} + +// SetNillableWorkspace sets the "workspace" field if the given value is not nil. +func (ssu *SecurityScanningUpdate) SetNillableWorkspace(s *string) *SecurityScanningUpdate { + if s != nil { + ssu.SetWorkspace(*s) + } + return ssu +} + +// SetLanguage sets the "language" field. +func (ssu *SecurityScanningUpdate) SetLanguage(csl consts.SecurityScanningLanguage) *SecurityScanningUpdate { + ssu.mutation.SetLanguage(csl) + return ssu +} + +// SetNillableLanguage sets the "language" field if the given value is not nil. +func (ssu *SecurityScanningUpdate) SetNillableLanguage(csl *consts.SecurityScanningLanguage) *SecurityScanningUpdate { + if csl != nil { + ssu.SetLanguage(*csl) + } + return ssu +} + +// SetRule sets the "rule" field. +func (ssu *SecurityScanningUpdate) SetRule(s string) *SecurityScanningUpdate { + ssu.mutation.SetRule(s) + return ssu +} + +// SetNillableRule sets the "rule" field if the given value is not nil. +func (ssu *SecurityScanningUpdate) SetNillableRule(s *string) *SecurityScanningUpdate { + if s != nil { + ssu.SetRule(*s) + } + return ssu +} + +// ClearRule clears the value of the "rule" field. +func (ssu *SecurityScanningUpdate) ClearRule() *SecurityScanningUpdate { + ssu.mutation.ClearRule() + return ssu +} + +// SetErrorMessage sets the "error_message" field. +func (ssu *SecurityScanningUpdate) SetErrorMessage(s string) *SecurityScanningUpdate { + ssu.mutation.SetErrorMessage(s) + return ssu +} + +// SetNillableErrorMessage sets the "error_message" field if the given value is not nil. +func (ssu *SecurityScanningUpdate) SetNillableErrorMessage(s *string) *SecurityScanningUpdate { + if s != nil { + ssu.SetErrorMessage(*s) + } + return ssu +} + +// ClearErrorMessage clears the value of the "error_message" field. +func (ssu *SecurityScanningUpdate) ClearErrorMessage() *SecurityScanningUpdate { + ssu.mutation.ClearErrorMessage() + return ssu +} + +// SetCreatedAt sets the "created_at" field. +func (ssu *SecurityScanningUpdate) SetCreatedAt(t time.Time) *SecurityScanningUpdate { + ssu.mutation.SetCreatedAt(t) + return ssu +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (ssu *SecurityScanningUpdate) SetNillableCreatedAt(t *time.Time) *SecurityScanningUpdate { + if t != nil { + ssu.SetCreatedAt(*t) + } + return ssu +} + +// SetUpdatedAt sets the "updated_at" field. +func (ssu *SecurityScanningUpdate) SetUpdatedAt(t time.Time) *SecurityScanningUpdate { + ssu.mutation.SetUpdatedAt(t) + return ssu +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (ssu *SecurityScanningUpdate) SetNillableUpdatedAt(t *time.Time) *SecurityScanningUpdate { + if t != nil { + ssu.SetUpdatedAt(*t) + } + return ssu +} + +// SetUser sets the "user" edge to the User entity. +func (ssu *SecurityScanningUpdate) SetUser(u *User) *SecurityScanningUpdate { + return ssu.SetUserID(u.ID) +} + +// AddResultIDs adds the "results" edge to the SecurityScanningResult entity by IDs. +func (ssu *SecurityScanningUpdate) AddResultIDs(ids ...uuid.UUID) *SecurityScanningUpdate { + ssu.mutation.AddResultIDs(ids...) + return ssu +} + +// AddResults adds the "results" edges to the SecurityScanningResult entity. +func (ssu *SecurityScanningUpdate) AddResults(s ...*SecurityScanningResult) *SecurityScanningUpdate { + ids := make([]uuid.UUID, len(s)) + for i := range s { + ids[i] = s[i].ID + } + return ssu.AddResultIDs(ids...) +} + +// SetWorkspaceEdgeID sets the "workspace_edge" edge to the Workspace entity by ID. +func (ssu *SecurityScanningUpdate) SetWorkspaceEdgeID(id uuid.UUID) *SecurityScanningUpdate { + ssu.mutation.SetWorkspaceEdgeID(id) + return ssu +} + +// SetWorkspaceEdge sets the "workspace_edge" edge to the Workspace entity. +func (ssu *SecurityScanningUpdate) SetWorkspaceEdge(w *Workspace) *SecurityScanningUpdate { + return ssu.SetWorkspaceEdgeID(w.ID) +} + +// Mutation returns the SecurityScanningMutation object of the builder. +func (ssu *SecurityScanningUpdate) Mutation() *SecurityScanningMutation { + return ssu.mutation +} + +// ClearUser clears the "user" edge to the User entity. +func (ssu *SecurityScanningUpdate) ClearUser() *SecurityScanningUpdate { + ssu.mutation.ClearUser() + return ssu +} + +// ClearResults clears all "results" edges to the SecurityScanningResult entity. +func (ssu *SecurityScanningUpdate) ClearResults() *SecurityScanningUpdate { + ssu.mutation.ClearResults() + return ssu +} + +// RemoveResultIDs removes the "results" edge to SecurityScanningResult entities by IDs. +func (ssu *SecurityScanningUpdate) RemoveResultIDs(ids ...uuid.UUID) *SecurityScanningUpdate { + ssu.mutation.RemoveResultIDs(ids...) + return ssu +} + +// RemoveResults removes "results" edges to SecurityScanningResult entities. +func (ssu *SecurityScanningUpdate) RemoveResults(s ...*SecurityScanningResult) *SecurityScanningUpdate { + ids := make([]uuid.UUID, len(s)) + for i := range s { + ids[i] = s[i].ID + } + return ssu.RemoveResultIDs(ids...) +} + +// ClearWorkspaceEdge clears the "workspace_edge" edge to the Workspace entity. +func (ssu *SecurityScanningUpdate) ClearWorkspaceEdge() *SecurityScanningUpdate { + ssu.mutation.ClearWorkspaceEdge() + return ssu +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (ssu *SecurityScanningUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, ssu.sqlSave, ssu.mutation, ssu.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (ssu *SecurityScanningUpdate) SaveX(ctx context.Context) int { + affected, err := ssu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (ssu *SecurityScanningUpdate) Exec(ctx context.Context) error { + _, err := ssu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ssu *SecurityScanningUpdate) ExecX(ctx context.Context) { + if err := ssu.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (ssu *SecurityScanningUpdate) check() error { + if ssu.mutation.UserCleared() && len(ssu.mutation.UserIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "SecurityScanning.user"`) + } + if ssu.mutation.WorkspaceEdgeCleared() && len(ssu.mutation.WorkspaceEdgeIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "SecurityScanning.workspace_edge"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (ssu *SecurityScanningUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *SecurityScanningUpdate { + ssu.modifiers = append(ssu.modifiers, modifiers...) + return ssu +} + +func (ssu *SecurityScanningUpdate) sqlSave(ctx context.Context) (n int, err error) { + if err := ssu.check(); err != nil { + return n, err + } + _spec := sqlgraph.NewUpdateSpec(securityscanning.Table, securityscanning.Columns, sqlgraph.NewFieldSpec(securityscanning.FieldID, field.TypeUUID)) + if ps := ssu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := ssu.mutation.Status(); ok { + _spec.SetField(securityscanning.FieldStatus, field.TypeString, value) + } + if value, ok := ssu.mutation.Workspace(); ok { + _spec.SetField(securityscanning.FieldWorkspace, field.TypeString, value) + } + if value, ok := ssu.mutation.Language(); ok { + _spec.SetField(securityscanning.FieldLanguage, field.TypeString, value) + } + if value, ok := ssu.mutation.Rule(); ok { + _spec.SetField(securityscanning.FieldRule, field.TypeString, value) + } + if ssu.mutation.RuleCleared() { + _spec.ClearField(securityscanning.FieldRule, field.TypeString) + } + if value, ok := ssu.mutation.ErrorMessage(); ok { + _spec.SetField(securityscanning.FieldErrorMessage, field.TypeString, value) + } + if ssu.mutation.ErrorMessageCleared() { + _spec.ClearField(securityscanning.FieldErrorMessage, field.TypeString) + } + if value, ok := ssu.mutation.CreatedAt(); ok { + _spec.SetField(securityscanning.FieldCreatedAt, field.TypeTime, value) + } + if value, ok := ssu.mutation.UpdatedAt(); ok { + _spec.SetField(securityscanning.FieldUpdatedAt, field.TypeTime, value) + } + if ssu.mutation.UserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: securityscanning.UserTable, + Columns: []string{securityscanning.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ssu.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: securityscanning.UserTable, + Columns: []string{securityscanning.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 ssu.mutation.ResultsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: securityscanning.ResultsTable, + Columns: []string{securityscanning.ResultsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(securityscanningresult.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ssu.mutation.RemovedResultsIDs(); len(nodes) > 0 && !ssu.mutation.ResultsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: securityscanning.ResultsTable, + Columns: []string{securityscanning.ResultsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(securityscanningresult.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 := ssu.mutation.ResultsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: securityscanning.ResultsTable, + Columns: []string{securityscanning.ResultsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(securityscanningresult.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if ssu.mutation.WorkspaceEdgeCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: securityscanning.WorkspaceEdgeTable, + Columns: []string{securityscanning.WorkspaceEdgeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(workspace.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ssu.mutation.WorkspaceEdgeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: securityscanning.WorkspaceEdgeTable, + Columns: []string{securityscanning.WorkspaceEdgeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(workspace.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(ssu.modifiers...) + if n, err = sqlgraph.UpdateNodes(ctx, ssu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{securityscanning.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + ssu.mutation.done = true + return n, nil +} + +// SecurityScanningUpdateOne is the builder for updating a single SecurityScanning entity. +type SecurityScanningUpdateOne struct { + config + fields []string + hooks []Hook + mutation *SecurityScanningMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetUserID sets the "user_id" field. +func (ssuo *SecurityScanningUpdateOne) SetUserID(u uuid.UUID) *SecurityScanningUpdateOne { + ssuo.mutation.SetUserID(u) + return ssuo +} + +// SetNillableUserID sets the "user_id" field if the given value is not nil. +func (ssuo *SecurityScanningUpdateOne) SetNillableUserID(u *uuid.UUID) *SecurityScanningUpdateOne { + if u != nil { + ssuo.SetUserID(*u) + } + return ssuo +} + +// SetWorkspaceID sets the "workspace_id" field. +func (ssuo *SecurityScanningUpdateOne) SetWorkspaceID(u uuid.UUID) *SecurityScanningUpdateOne { + ssuo.mutation.SetWorkspaceID(u) + return ssuo +} + +// SetNillableWorkspaceID sets the "workspace_id" field if the given value is not nil. +func (ssuo *SecurityScanningUpdateOne) SetNillableWorkspaceID(u *uuid.UUID) *SecurityScanningUpdateOne { + if u != nil { + ssuo.SetWorkspaceID(*u) + } + return ssuo +} + +// SetStatus sets the "status" field. +func (ssuo *SecurityScanningUpdateOne) SetStatus(css consts.SecurityScanningStatus) *SecurityScanningUpdateOne { + ssuo.mutation.SetStatus(css) + return ssuo +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (ssuo *SecurityScanningUpdateOne) SetNillableStatus(css *consts.SecurityScanningStatus) *SecurityScanningUpdateOne { + if css != nil { + ssuo.SetStatus(*css) + } + return ssuo +} + +// SetWorkspace sets the "workspace" field. +func (ssuo *SecurityScanningUpdateOne) SetWorkspace(s string) *SecurityScanningUpdateOne { + ssuo.mutation.SetWorkspace(s) + return ssuo +} + +// SetNillableWorkspace sets the "workspace" field if the given value is not nil. +func (ssuo *SecurityScanningUpdateOne) SetNillableWorkspace(s *string) *SecurityScanningUpdateOne { + if s != nil { + ssuo.SetWorkspace(*s) + } + return ssuo +} + +// SetLanguage sets the "language" field. +func (ssuo *SecurityScanningUpdateOne) SetLanguage(csl consts.SecurityScanningLanguage) *SecurityScanningUpdateOne { + ssuo.mutation.SetLanguage(csl) + return ssuo +} + +// SetNillableLanguage sets the "language" field if the given value is not nil. +func (ssuo *SecurityScanningUpdateOne) SetNillableLanguage(csl *consts.SecurityScanningLanguage) *SecurityScanningUpdateOne { + if csl != nil { + ssuo.SetLanguage(*csl) + } + return ssuo +} + +// SetRule sets the "rule" field. +func (ssuo *SecurityScanningUpdateOne) SetRule(s string) *SecurityScanningUpdateOne { + ssuo.mutation.SetRule(s) + return ssuo +} + +// SetNillableRule sets the "rule" field if the given value is not nil. +func (ssuo *SecurityScanningUpdateOne) SetNillableRule(s *string) *SecurityScanningUpdateOne { + if s != nil { + ssuo.SetRule(*s) + } + return ssuo +} + +// ClearRule clears the value of the "rule" field. +func (ssuo *SecurityScanningUpdateOne) ClearRule() *SecurityScanningUpdateOne { + ssuo.mutation.ClearRule() + return ssuo +} + +// SetErrorMessage sets the "error_message" field. +func (ssuo *SecurityScanningUpdateOne) SetErrorMessage(s string) *SecurityScanningUpdateOne { + ssuo.mutation.SetErrorMessage(s) + return ssuo +} + +// SetNillableErrorMessage sets the "error_message" field if the given value is not nil. +func (ssuo *SecurityScanningUpdateOne) SetNillableErrorMessage(s *string) *SecurityScanningUpdateOne { + if s != nil { + ssuo.SetErrorMessage(*s) + } + return ssuo +} + +// ClearErrorMessage clears the value of the "error_message" field. +func (ssuo *SecurityScanningUpdateOne) ClearErrorMessage() *SecurityScanningUpdateOne { + ssuo.mutation.ClearErrorMessage() + return ssuo +} + +// SetCreatedAt sets the "created_at" field. +func (ssuo *SecurityScanningUpdateOne) SetCreatedAt(t time.Time) *SecurityScanningUpdateOne { + ssuo.mutation.SetCreatedAt(t) + return ssuo +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (ssuo *SecurityScanningUpdateOne) SetNillableCreatedAt(t *time.Time) *SecurityScanningUpdateOne { + if t != nil { + ssuo.SetCreatedAt(*t) + } + return ssuo +} + +// SetUpdatedAt sets the "updated_at" field. +func (ssuo *SecurityScanningUpdateOne) SetUpdatedAt(t time.Time) *SecurityScanningUpdateOne { + ssuo.mutation.SetUpdatedAt(t) + return ssuo +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (ssuo *SecurityScanningUpdateOne) SetNillableUpdatedAt(t *time.Time) *SecurityScanningUpdateOne { + if t != nil { + ssuo.SetUpdatedAt(*t) + } + return ssuo +} + +// SetUser sets the "user" edge to the User entity. +func (ssuo *SecurityScanningUpdateOne) SetUser(u *User) *SecurityScanningUpdateOne { + return ssuo.SetUserID(u.ID) +} + +// AddResultIDs adds the "results" edge to the SecurityScanningResult entity by IDs. +func (ssuo *SecurityScanningUpdateOne) AddResultIDs(ids ...uuid.UUID) *SecurityScanningUpdateOne { + ssuo.mutation.AddResultIDs(ids...) + return ssuo +} + +// AddResults adds the "results" edges to the SecurityScanningResult entity. +func (ssuo *SecurityScanningUpdateOne) AddResults(s ...*SecurityScanningResult) *SecurityScanningUpdateOne { + ids := make([]uuid.UUID, len(s)) + for i := range s { + ids[i] = s[i].ID + } + return ssuo.AddResultIDs(ids...) +} + +// SetWorkspaceEdgeID sets the "workspace_edge" edge to the Workspace entity by ID. +func (ssuo *SecurityScanningUpdateOne) SetWorkspaceEdgeID(id uuid.UUID) *SecurityScanningUpdateOne { + ssuo.mutation.SetWorkspaceEdgeID(id) + return ssuo +} + +// SetWorkspaceEdge sets the "workspace_edge" edge to the Workspace entity. +func (ssuo *SecurityScanningUpdateOne) SetWorkspaceEdge(w *Workspace) *SecurityScanningUpdateOne { + return ssuo.SetWorkspaceEdgeID(w.ID) +} + +// Mutation returns the SecurityScanningMutation object of the builder. +func (ssuo *SecurityScanningUpdateOne) Mutation() *SecurityScanningMutation { + return ssuo.mutation +} + +// ClearUser clears the "user" edge to the User entity. +func (ssuo *SecurityScanningUpdateOne) ClearUser() *SecurityScanningUpdateOne { + ssuo.mutation.ClearUser() + return ssuo +} + +// ClearResults clears all "results" edges to the SecurityScanningResult entity. +func (ssuo *SecurityScanningUpdateOne) ClearResults() *SecurityScanningUpdateOne { + ssuo.mutation.ClearResults() + return ssuo +} + +// RemoveResultIDs removes the "results" edge to SecurityScanningResult entities by IDs. +func (ssuo *SecurityScanningUpdateOne) RemoveResultIDs(ids ...uuid.UUID) *SecurityScanningUpdateOne { + ssuo.mutation.RemoveResultIDs(ids...) + return ssuo +} + +// RemoveResults removes "results" edges to SecurityScanningResult entities. +func (ssuo *SecurityScanningUpdateOne) RemoveResults(s ...*SecurityScanningResult) *SecurityScanningUpdateOne { + ids := make([]uuid.UUID, len(s)) + for i := range s { + ids[i] = s[i].ID + } + return ssuo.RemoveResultIDs(ids...) +} + +// ClearWorkspaceEdge clears the "workspace_edge" edge to the Workspace entity. +func (ssuo *SecurityScanningUpdateOne) ClearWorkspaceEdge() *SecurityScanningUpdateOne { + ssuo.mutation.ClearWorkspaceEdge() + return ssuo +} + +// Where appends a list predicates to the SecurityScanningUpdate builder. +func (ssuo *SecurityScanningUpdateOne) Where(ps ...predicate.SecurityScanning) *SecurityScanningUpdateOne { + ssuo.mutation.Where(ps...) + return ssuo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (ssuo *SecurityScanningUpdateOne) Select(field string, fields ...string) *SecurityScanningUpdateOne { + ssuo.fields = append([]string{field}, fields...) + return ssuo +} + +// Save executes the query and returns the updated SecurityScanning entity. +func (ssuo *SecurityScanningUpdateOne) Save(ctx context.Context) (*SecurityScanning, error) { + return withHooks(ctx, ssuo.sqlSave, ssuo.mutation, ssuo.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (ssuo *SecurityScanningUpdateOne) SaveX(ctx context.Context) *SecurityScanning { + node, err := ssuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (ssuo *SecurityScanningUpdateOne) Exec(ctx context.Context) error { + _, err := ssuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ssuo *SecurityScanningUpdateOne) ExecX(ctx context.Context) { + if err := ssuo.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (ssuo *SecurityScanningUpdateOne) check() error { + if ssuo.mutation.UserCleared() && len(ssuo.mutation.UserIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "SecurityScanning.user"`) + } + if ssuo.mutation.WorkspaceEdgeCleared() && len(ssuo.mutation.WorkspaceEdgeIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "SecurityScanning.workspace_edge"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (ssuo *SecurityScanningUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *SecurityScanningUpdateOne { + ssuo.modifiers = append(ssuo.modifiers, modifiers...) + return ssuo +} + +func (ssuo *SecurityScanningUpdateOne) sqlSave(ctx context.Context) (_node *SecurityScanning, err error) { + if err := ssuo.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(securityscanning.Table, securityscanning.Columns, sqlgraph.NewFieldSpec(securityscanning.FieldID, field.TypeUUID)) + id, ok := ssuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "SecurityScanning.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := ssuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, securityscanning.FieldID) + for _, f := range fields { + if !securityscanning.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != securityscanning.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := ssuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := ssuo.mutation.Status(); ok { + _spec.SetField(securityscanning.FieldStatus, field.TypeString, value) + } + if value, ok := ssuo.mutation.Workspace(); ok { + _spec.SetField(securityscanning.FieldWorkspace, field.TypeString, value) + } + if value, ok := ssuo.mutation.Language(); ok { + _spec.SetField(securityscanning.FieldLanguage, field.TypeString, value) + } + if value, ok := ssuo.mutation.Rule(); ok { + _spec.SetField(securityscanning.FieldRule, field.TypeString, value) + } + if ssuo.mutation.RuleCleared() { + _spec.ClearField(securityscanning.FieldRule, field.TypeString) + } + if value, ok := ssuo.mutation.ErrorMessage(); ok { + _spec.SetField(securityscanning.FieldErrorMessage, field.TypeString, value) + } + if ssuo.mutation.ErrorMessageCleared() { + _spec.ClearField(securityscanning.FieldErrorMessage, field.TypeString) + } + if value, ok := ssuo.mutation.CreatedAt(); ok { + _spec.SetField(securityscanning.FieldCreatedAt, field.TypeTime, value) + } + if value, ok := ssuo.mutation.UpdatedAt(); ok { + _spec.SetField(securityscanning.FieldUpdatedAt, field.TypeTime, value) + } + if ssuo.mutation.UserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: securityscanning.UserTable, + Columns: []string{securityscanning.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ssuo.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: securityscanning.UserTable, + Columns: []string{securityscanning.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 ssuo.mutation.ResultsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: securityscanning.ResultsTable, + Columns: []string{securityscanning.ResultsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(securityscanningresult.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ssuo.mutation.RemovedResultsIDs(); len(nodes) > 0 && !ssuo.mutation.ResultsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: securityscanning.ResultsTable, + Columns: []string{securityscanning.ResultsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(securityscanningresult.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 := ssuo.mutation.ResultsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: securityscanning.ResultsTable, + Columns: []string{securityscanning.ResultsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(securityscanningresult.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if ssuo.mutation.WorkspaceEdgeCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: securityscanning.WorkspaceEdgeTable, + Columns: []string{securityscanning.WorkspaceEdgeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(workspace.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ssuo.mutation.WorkspaceEdgeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: securityscanning.WorkspaceEdgeTable, + Columns: []string{securityscanning.WorkspaceEdgeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(workspace.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(ssuo.modifiers...) + _node = &SecurityScanning{config: ssuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, ssuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{securityscanning.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + ssuo.mutation.done = true + return _node, nil +} diff --git a/backend/db/securityscanningresult.go b/backend/db/securityscanningresult.go new file mode 100644 index 0000000..0b3a7e0 --- /dev/null +++ b/backend/db/securityscanningresult.go @@ -0,0 +1,346 @@ +// 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/securityscanning" + "github.com/chaitin/MonkeyCode/backend/db/securityscanningresult" + "github.com/chaitin/MonkeyCode/backend/ent/types" + "github.com/google/uuid" +) + +// SecurityScanningResult is the model entity for the SecurityScanningResult schema. +type SecurityScanningResult struct { + config `json:"-"` + // ID of the ent. + ID uuid.UUID `json:"id,omitempty"` + // SecurityScanningID holds the value of the "security_scanning_id" field. + SecurityScanningID uuid.UUID `json:"security_scanning_id,omitempty"` + // CheckID holds the value of the "check_id" field. + CheckID string `json:"check_id,omitempty"` + // EngineKind holds the value of the "engine_kind" field. + EngineKind string `json:"engine_kind,omitempty"` + // Lines holds the value of the "lines" field. + Lines string `json:"lines,omitempty"` + // Path holds the value of the "path" field. + Path string `json:"path,omitempty"` + // Message holds the value of the "message" field. + Message string `json:"message,omitempty"` + // MessageZh holds the value of the "message_zh" field. + MessageZh string `json:"message_zh,omitempty"` + // Severity holds the value of the "severity" field. + Severity string `json:"severity,omitempty"` + // AbstractEn holds the value of the "abstract_en" field. + AbstractEn string `json:"abstract_en,omitempty"` + // AbstractZh holds the value of the "abstract_zh" field. + AbstractZh string `json:"abstract_zh,omitempty"` + // CategoryEn holds the value of the "category_en" field. + CategoryEn string `json:"category_en,omitempty"` + // CategoryZh holds the value of the "category_zh" field. + CategoryZh string `json:"category_zh,omitempty"` + // Confidence holds the value of the "confidence" field. + Confidence string `json:"confidence,omitempty"` + // Cwe holds the value of the "cwe" field. + Cwe []interface{} `json:"cwe,omitempty"` + // Impact holds the value of the "impact" field. + Impact string `json:"impact,omitempty"` + // Owasp holds the value of the "owasp" field. + Owasp []interface{} `json:"owasp,omitempty"` + // StartPosition holds the value of the "start_position" field. + StartPosition *types.Position `json:"start_position,omitempty"` + // EndPosition holds the value of the "end_position" field. + EndPosition *types.Position `json:"end_position,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 SecurityScanningResultQuery when eager-loading is set. + Edges SecurityScanningResultEdges `json:"edges"` + selectValues sql.SelectValues +} + +// SecurityScanningResultEdges holds the relations/edges for other nodes in the graph. +type SecurityScanningResultEdges struct { + // SecurityScanning holds the value of the security_scanning edge. + SecurityScanning *SecurityScanning `json:"security_scanning,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// SecurityScanningOrErr returns the SecurityScanning value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e SecurityScanningResultEdges) SecurityScanningOrErr() (*SecurityScanning, error) { + if e.SecurityScanning != nil { + return e.SecurityScanning, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: securityscanning.Label} + } + return nil, &NotLoadedError{edge: "security_scanning"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*SecurityScanningResult) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case securityscanningresult.FieldCwe, securityscanningresult.FieldOwasp, securityscanningresult.FieldStartPosition, securityscanningresult.FieldEndPosition: + values[i] = new([]byte) + case securityscanningresult.FieldCheckID, securityscanningresult.FieldEngineKind, securityscanningresult.FieldLines, securityscanningresult.FieldPath, securityscanningresult.FieldMessage, securityscanningresult.FieldMessageZh, securityscanningresult.FieldSeverity, securityscanningresult.FieldAbstractEn, securityscanningresult.FieldAbstractZh, securityscanningresult.FieldCategoryEn, securityscanningresult.FieldCategoryZh, securityscanningresult.FieldConfidence, securityscanningresult.FieldImpact: + values[i] = new(sql.NullString) + case securityscanningresult.FieldCreatedAt: + values[i] = new(sql.NullTime) + case securityscanningresult.FieldID, securityscanningresult.FieldSecurityScanningID: + 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 SecurityScanningResult fields. +func (ssr *SecurityScanningResult) 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 securityscanningresult.FieldID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value != nil { + ssr.ID = *value + } + case securityscanningresult.FieldSecurityScanningID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field security_scanning_id", values[i]) + } else if value != nil { + ssr.SecurityScanningID = *value + } + case securityscanningresult.FieldCheckID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field check_id", values[i]) + } else if value.Valid { + ssr.CheckID = value.String + } + case securityscanningresult.FieldEngineKind: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field engine_kind", values[i]) + } else if value.Valid { + ssr.EngineKind = value.String + } + case securityscanningresult.FieldLines: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field lines", values[i]) + } else if value.Valid { + ssr.Lines = value.String + } + case securityscanningresult.FieldPath: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field path", values[i]) + } else if value.Valid { + ssr.Path = value.String + } + case securityscanningresult.FieldMessage: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field message", values[i]) + } else if value.Valid { + ssr.Message = value.String + } + case securityscanningresult.FieldMessageZh: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field message_zh", values[i]) + } else if value.Valid { + ssr.MessageZh = value.String + } + case securityscanningresult.FieldSeverity: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field severity", values[i]) + } else if value.Valid { + ssr.Severity = value.String + } + case securityscanningresult.FieldAbstractEn: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field abstract_en", values[i]) + } else if value.Valid { + ssr.AbstractEn = value.String + } + case securityscanningresult.FieldAbstractZh: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field abstract_zh", values[i]) + } else if value.Valid { + ssr.AbstractZh = value.String + } + case securityscanningresult.FieldCategoryEn: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field category_en", values[i]) + } else if value.Valid { + ssr.CategoryEn = value.String + } + case securityscanningresult.FieldCategoryZh: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field category_zh", values[i]) + } else if value.Valid { + ssr.CategoryZh = value.String + } + case securityscanningresult.FieldConfidence: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field confidence", values[i]) + } else if value.Valid { + ssr.Confidence = value.String + } + case securityscanningresult.FieldCwe: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field cwe", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &ssr.Cwe); err != nil { + return fmt.Errorf("unmarshal field cwe: %w", err) + } + } + case securityscanningresult.FieldImpact: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field impact", values[i]) + } else if value.Valid { + ssr.Impact = value.String + } + case securityscanningresult.FieldOwasp: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field owasp", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &ssr.Owasp); err != nil { + return fmt.Errorf("unmarshal field owasp: %w", err) + } + } + case securityscanningresult.FieldStartPosition: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field start_position", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &ssr.StartPosition); err != nil { + return fmt.Errorf("unmarshal field start_position: %w", err) + } + } + case securityscanningresult.FieldEndPosition: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field end_position", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &ssr.EndPosition); err != nil { + return fmt.Errorf("unmarshal field end_position: %w", err) + } + } + case securityscanningresult.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 { + ssr.CreatedAt = value.Time + } + default: + ssr.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the SecurityScanningResult. +// This includes values selected through modifiers, order, etc. +func (ssr *SecurityScanningResult) Value(name string) (ent.Value, error) { + return ssr.selectValues.Get(name) +} + +// QuerySecurityScanning queries the "security_scanning" edge of the SecurityScanningResult entity. +func (ssr *SecurityScanningResult) QuerySecurityScanning() *SecurityScanningQuery { + return NewSecurityScanningResultClient(ssr.config).QuerySecurityScanning(ssr) +} + +// Update returns a builder for updating this SecurityScanningResult. +// Note that you need to call SecurityScanningResult.Unwrap() before calling this method if this SecurityScanningResult +// was returned from a transaction, and the transaction was committed or rolled back. +func (ssr *SecurityScanningResult) Update() *SecurityScanningResultUpdateOne { + return NewSecurityScanningResultClient(ssr.config).UpdateOne(ssr) +} + +// Unwrap unwraps the SecurityScanningResult 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 (ssr *SecurityScanningResult) Unwrap() *SecurityScanningResult { + _tx, ok := ssr.config.driver.(*txDriver) + if !ok { + panic("db: SecurityScanningResult is not a transactional entity") + } + ssr.config.driver = _tx.drv + return ssr +} + +// String implements the fmt.Stringer. +func (ssr *SecurityScanningResult) String() string { + var builder strings.Builder + builder.WriteString("SecurityScanningResult(") + builder.WriteString(fmt.Sprintf("id=%v, ", ssr.ID)) + builder.WriteString("security_scanning_id=") + builder.WriteString(fmt.Sprintf("%v", ssr.SecurityScanningID)) + builder.WriteString(", ") + builder.WriteString("check_id=") + builder.WriteString(ssr.CheckID) + builder.WriteString(", ") + builder.WriteString("engine_kind=") + builder.WriteString(ssr.EngineKind) + builder.WriteString(", ") + builder.WriteString("lines=") + builder.WriteString(ssr.Lines) + builder.WriteString(", ") + builder.WriteString("path=") + builder.WriteString(ssr.Path) + builder.WriteString(", ") + builder.WriteString("message=") + builder.WriteString(ssr.Message) + builder.WriteString(", ") + builder.WriteString("message_zh=") + builder.WriteString(ssr.MessageZh) + builder.WriteString(", ") + builder.WriteString("severity=") + builder.WriteString(ssr.Severity) + builder.WriteString(", ") + builder.WriteString("abstract_en=") + builder.WriteString(ssr.AbstractEn) + builder.WriteString(", ") + builder.WriteString("abstract_zh=") + builder.WriteString(ssr.AbstractZh) + builder.WriteString(", ") + builder.WriteString("category_en=") + builder.WriteString(ssr.CategoryEn) + builder.WriteString(", ") + builder.WriteString("category_zh=") + builder.WriteString(ssr.CategoryZh) + builder.WriteString(", ") + builder.WriteString("confidence=") + builder.WriteString(ssr.Confidence) + builder.WriteString(", ") + builder.WriteString("cwe=") + builder.WriteString(fmt.Sprintf("%v", ssr.Cwe)) + builder.WriteString(", ") + builder.WriteString("impact=") + builder.WriteString(ssr.Impact) + builder.WriteString(", ") + builder.WriteString("owasp=") + builder.WriteString(fmt.Sprintf("%v", ssr.Owasp)) + builder.WriteString(", ") + builder.WriteString("start_position=") + builder.WriteString(fmt.Sprintf("%v", ssr.StartPosition)) + builder.WriteString(", ") + builder.WriteString("end_position=") + builder.WriteString(fmt.Sprintf("%v", ssr.EndPosition)) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(ssr.CreatedAt.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// SecurityScanningResults is a parsable slice of SecurityScanningResult. +type SecurityScanningResults []*SecurityScanningResult diff --git a/backend/db/securityscanningresult/securityscanningresult.go b/backend/db/securityscanningresult/securityscanningresult.go new file mode 100644 index 0000000..6388673 --- /dev/null +++ b/backend/db/securityscanningresult/securityscanningresult.go @@ -0,0 +1,202 @@ +// Code generated by ent, DO NOT EDIT. + +package securityscanningresult + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the securityscanningresult type in the database. + Label = "security_scanning_result" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldSecurityScanningID holds the string denoting the security_scanning_id field in the database. + FieldSecurityScanningID = "security_scanning_id" + // FieldCheckID holds the string denoting the check_id field in the database. + FieldCheckID = "check_id" + // FieldEngineKind holds the string denoting the engine_kind field in the database. + FieldEngineKind = "engine_kind" + // FieldLines holds the string denoting the lines field in the database. + FieldLines = "lines" + // FieldPath holds the string denoting the path field in the database. + FieldPath = "path" + // FieldMessage holds the string denoting the message field in the database. + FieldMessage = "message" + // FieldMessageZh holds the string denoting the message_zh field in the database. + FieldMessageZh = "message_zh" + // FieldSeverity holds the string denoting the severity field in the database. + FieldSeverity = "severity" + // FieldAbstractEn holds the string denoting the abstract_en field in the database. + FieldAbstractEn = "abstract_en" + // FieldAbstractZh holds the string denoting the abstract_zh field in the database. + FieldAbstractZh = "abstract_zh" + // FieldCategoryEn holds the string denoting the category_en field in the database. + FieldCategoryEn = "category_en" + // FieldCategoryZh holds the string denoting the category_zh field in the database. + FieldCategoryZh = "category_zh" + // FieldConfidence holds the string denoting the confidence field in the database. + FieldConfidence = "confidence" + // FieldCwe holds the string denoting the cwe field in the database. + FieldCwe = "cwe" + // FieldImpact holds the string denoting the impact field in the database. + FieldImpact = "impact" + // FieldOwasp holds the string denoting the owasp field in the database. + FieldOwasp = "owasp" + // FieldStartPosition holds the string denoting the start_position field in the database. + FieldStartPosition = "start_position" + // FieldEndPosition holds the string denoting the end_position field in the database. + FieldEndPosition = "end_position" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // EdgeSecurityScanning holds the string denoting the security_scanning edge name in mutations. + EdgeSecurityScanning = "security_scanning" + // Table holds the table name of the securityscanningresult in the database. + Table = "security_scanning_results" + // SecurityScanningTable is the table that holds the security_scanning relation/edge. + SecurityScanningTable = "security_scanning_results" + // SecurityScanningInverseTable is the table name for the SecurityScanning entity. + // It exists in this package in order to avoid circular dependency with the "securityscanning" package. + SecurityScanningInverseTable = "security_scannings" + // SecurityScanningColumn is the table column denoting the security_scanning relation/edge. + SecurityScanningColumn = "security_scanning_id" +) + +// Columns holds all SQL columns for securityscanningresult fields. +var Columns = []string{ + FieldID, + FieldSecurityScanningID, + FieldCheckID, + FieldEngineKind, + FieldLines, + FieldPath, + FieldMessage, + FieldMessageZh, + FieldSeverity, + FieldAbstractEn, + FieldAbstractZh, + FieldCategoryEn, + FieldCategoryZh, + FieldConfidence, + FieldCwe, + FieldImpact, + FieldOwasp, + FieldStartPosition, + FieldEndPosition, + FieldCreatedAt, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time +) + +// OrderOption defines the ordering options for the SecurityScanningResult 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() +} + +// BySecurityScanningID orders the results by the security_scanning_id field. +func BySecurityScanningID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSecurityScanningID, opts...).ToFunc() +} + +// ByCheckID orders the results by the check_id field. +func ByCheckID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCheckID, opts...).ToFunc() +} + +// ByEngineKind orders the results by the engine_kind field. +func ByEngineKind(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldEngineKind, opts...).ToFunc() +} + +// ByLines orders the results by the lines field. +func ByLines(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldLines, opts...).ToFunc() +} + +// ByPath orders the results by the path field. +func ByPath(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPath, opts...).ToFunc() +} + +// ByMessage orders the results by the message field. +func ByMessage(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldMessage, opts...).ToFunc() +} + +// ByMessageZh orders the results by the message_zh field. +func ByMessageZh(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldMessageZh, opts...).ToFunc() +} + +// BySeverity orders the results by the severity field. +func BySeverity(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSeverity, opts...).ToFunc() +} + +// ByAbstractEn orders the results by the abstract_en field. +func ByAbstractEn(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAbstractEn, opts...).ToFunc() +} + +// ByAbstractZh orders the results by the abstract_zh field. +func ByAbstractZh(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAbstractZh, opts...).ToFunc() +} + +// ByCategoryEn orders the results by the category_en field. +func ByCategoryEn(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCategoryEn, opts...).ToFunc() +} + +// ByCategoryZh orders the results by the category_zh field. +func ByCategoryZh(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCategoryZh, opts...).ToFunc() +} + +// ByConfidence orders the results by the confidence field. +func ByConfidence(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldConfidence, opts...).ToFunc() +} + +// ByImpact orders the results by the impact field. +func ByImpact(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldImpact, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// BySecurityScanningField orders the results by security_scanning field. +func BySecurityScanningField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newSecurityScanningStep(), sql.OrderByField(field, opts...)) + } +} +func newSecurityScanningStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(SecurityScanningInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SecurityScanningTable, SecurityScanningColumn), + ) +} diff --git a/backend/db/securityscanningresult/where.go b/backend/db/securityscanningresult/where.go new file mode 100644 index 0000000..c4ec26a --- /dev/null +++ b/backend/db/securityscanningresult/where.go @@ -0,0 +1,1075 @@ +// Code generated by ent, DO NOT EDIT. + +package securityscanningresult + +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.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id uuid.UUID) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id uuid.UUID) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...uuid.UUID) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...uuid.UUID) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id uuid.UUID) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id uuid.UUID) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id uuid.UUID) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id uuid.UUID) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldLTE(FieldID, id)) +} + +// SecurityScanningID applies equality check predicate on the "security_scanning_id" field. It's identical to SecurityScanningIDEQ. +func SecurityScanningID(v uuid.UUID) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEQ(FieldSecurityScanningID, v)) +} + +// CheckID applies equality check predicate on the "check_id" field. It's identical to CheckIDEQ. +func CheckID(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEQ(FieldCheckID, v)) +} + +// EngineKind applies equality check predicate on the "engine_kind" field. It's identical to EngineKindEQ. +func EngineKind(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEQ(FieldEngineKind, v)) +} + +// Lines applies equality check predicate on the "lines" field. It's identical to LinesEQ. +func Lines(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEQ(FieldLines, v)) +} + +// Path applies equality check predicate on the "path" field. It's identical to PathEQ. +func Path(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEQ(FieldPath, v)) +} + +// Message applies equality check predicate on the "message" field. It's identical to MessageEQ. +func Message(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEQ(FieldMessage, v)) +} + +// MessageZh applies equality check predicate on the "message_zh" field. It's identical to MessageZhEQ. +func MessageZh(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEQ(FieldMessageZh, v)) +} + +// Severity applies equality check predicate on the "severity" field. It's identical to SeverityEQ. +func Severity(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEQ(FieldSeverity, v)) +} + +// AbstractEn applies equality check predicate on the "abstract_en" field. It's identical to AbstractEnEQ. +func AbstractEn(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEQ(FieldAbstractEn, v)) +} + +// AbstractZh applies equality check predicate on the "abstract_zh" field. It's identical to AbstractZhEQ. +func AbstractZh(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEQ(FieldAbstractZh, v)) +} + +// CategoryEn applies equality check predicate on the "category_en" field. It's identical to CategoryEnEQ. +func CategoryEn(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEQ(FieldCategoryEn, v)) +} + +// CategoryZh applies equality check predicate on the "category_zh" field. It's identical to CategoryZhEQ. +func CategoryZh(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEQ(FieldCategoryZh, v)) +} + +// Confidence applies equality check predicate on the "confidence" field. It's identical to ConfidenceEQ. +func Confidence(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEQ(FieldConfidence, v)) +} + +// Impact applies equality check predicate on the "impact" field. It's identical to ImpactEQ. +func Impact(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEQ(FieldImpact, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEQ(FieldCreatedAt, v)) +} + +// SecurityScanningIDEQ applies the EQ predicate on the "security_scanning_id" field. +func SecurityScanningIDEQ(v uuid.UUID) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEQ(FieldSecurityScanningID, v)) +} + +// SecurityScanningIDNEQ applies the NEQ predicate on the "security_scanning_id" field. +func SecurityScanningIDNEQ(v uuid.UUID) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldNEQ(FieldSecurityScanningID, v)) +} + +// SecurityScanningIDIn applies the In predicate on the "security_scanning_id" field. +func SecurityScanningIDIn(vs ...uuid.UUID) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldIn(FieldSecurityScanningID, vs...)) +} + +// SecurityScanningIDNotIn applies the NotIn predicate on the "security_scanning_id" field. +func SecurityScanningIDNotIn(vs ...uuid.UUID) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldNotIn(FieldSecurityScanningID, vs...)) +} + +// CheckIDEQ applies the EQ predicate on the "check_id" field. +func CheckIDEQ(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEQ(FieldCheckID, v)) +} + +// CheckIDNEQ applies the NEQ predicate on the "check_id" field. +func CheckIDNEQ(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldNEQ(FieldCheckID, v)) +} + +// CheckIDIn applies the In predicate on the "check_id" field. +func CheckIDIn(vs ...string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldIn(FieldCheckID, vs...)) +} + +// CheckIDNotIn applies the NotIn predicate on the "check_id" field. +func CheckIDNotIn(vs ...string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldNotIn(FieldCheckID, vs...)) +} + +// CheckIDGT applies the GT predicate on the "check_id" field. +func CheckIDGT(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldGT(FieldCheckID, v)) +} + +// CheckIDGTE applies the GTE predicate on the "check_id" field. +func CheckIDGTE(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldGTE(FieldCheckID, v)) +} + +// CheckIDLT applies the LT predicate on the "check_id" field. +func CheckIDLT(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldLT(FieldCheckID, v)) +} + +// CheckIDLTE applies the LTE predicate on the "check_id" field. +func CheckIDLTE(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldLTE(FieldCheckID, v)) +} + +// CheckIDContains applies the Contains predicate on the "check_id" field. +func CheckIDContains(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldContains(FieldCheckID, v)) +} + +// CheckIDHasPrefix applies the HasPrefix predicate on the "check_id" field. +func CheckIDHasPrefix(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldHasPrefix(FieldCheckID, v)) +} + +// CheckIDHasSuffix applies the HasSuffix predicate on the "check_id" field. +func CheckIDHasSuffix(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldHasSuffix(FieldCheckID, v)) +} + +// CheckIDEqualFold applies the EqualFold predicate on the "check_id" field. +func CheckIDEqualFold(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEqualFold(FieldCheckID, v)) +} + +// CheckIDContainsFold applies the ContainsFold predicate on the "check_id" field. +func CheckIDContainsFold(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldContainsFold(FieldCheckID, v)) +} + +// EngineKindEQ applies the EQ predicate on the "engine_kind" field. +func EngineKindEQ(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEQ(FieldEngineKind, v)) +} + +// EngineKindNEQ applies the NEQ predicate on the "engine_kind" field. +func EngineKindNEQ(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldNEQ(FieldEngineKind, v)) +} + +// EngineKindIn applies the In predicate on the "engine_kind" field. +func EngineKindIn(vs ...string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldIn(FieldEngineKind, vs...)) +} + +// EngineKindNotIn applies the NotIn predicate on the "engine_kind" field. +func EngineKindNotIn(vs ...string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldNotIn(FieldEngineKind, vs...)) +} + +// EngineKindGT applies the GT predicate on the "engine_kind" field. +func EngineKindGT(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldGT(FieldEngineKind, v)) +} + +// EngineKindGTE applies the GTE predicate on the "engine_kind" field. +func EngineKindGTE(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldGTE(FieldEngineKind, v)) +} + +// EngineKindLT applies the LT predicate on the "engine_kind" field. +func EngineKindLT(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldLT(FieldEngineKind, v)) +} + +// EngineKindLTE applies the LTE predicate on the "engine_kind" field. +func EngineKindLTE(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldLTE(FieldEngineKind, v)) +} + +// EngineKindContains applies the Contains predicate on the "engine_kind" field. +func EngineKindContains(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldContains(FieldEngineKind, v)) +} + +// EngineKindHasPrefix applies the HasPrefix predicate on the "engine_kind" field. +func EngineKindHasPrefix(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldHasPrefix(FieldEngineKind, v)) +} + +// EngineKindHasSuffix applies the HasSuffix predicate on the "engine_kind" field. +func EngineKindHasSuffix(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldHasSuffix(FieldEngineKind, v)) +} + +// EngineKindEqualFold applies the EqualFold predicate on the "engine_kind" field. +func EngineKindEqualFold(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEqualFold(FieldEngineKind, v)) +} + +// EngineKindContainsFold applies the ContainsFold predicate on the "engine_kind" field. +func EngineKindContainsFold(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldContainsFold(FieldEngineKind, v)) +} + +// LinesEQ applies the EQ predicate on the "lines" field. +func LinesEQ(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEQ(FieldLines, v)) +} + +// LinesNEQ applies the NEQ predicate on the "lines" field. +func LinesNEQ(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldNEQ(FieldLines, v)) +} + +// LinesIn applies the In predicate on the "lines" field. +func LinesIn(vs ...string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldIn(FieldLines, vs...)) +} + +// LinesNotIn applies the NotIn predicate on the "lines" field. +func LinesNotIn(vs ...string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldNotIn(FieldLines, vs...)) +} + +// LinesGT applies the GT predicate on the "lines" field. +func LinesGT(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldGT(FieldLines, v)) +} + +// LinesGTE applies the GTE predicate on the "lines" field. +func LinesGTE(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldGTE(FieldLines, v)) +} + +// LinesLT applies the LT predicate on the "lines" field. +func LinesLT(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldLT(FieldLines, v)) +} + +// LinesLTE applies the LTE predicate on the "lines" field. +func LinesLTE(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldLTE(FieldLines, v)) +} + +// LinesContains applies the Contains predicate on the "lines" field. +func LinesContains(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldContains(FieldLines, v)) +} + +// LinesHasPrefix applies the HasPrefix predicate on the "lines" field. +func LinesHasPrefix(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldHasPrefix(FieldLines, v)) +} + +// LinesHasSuffix applies the HasSuffix predicate on the "lines" field. +func LinesHasSuffix(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldHasSuffix(FieldLines, v)) +} + +// LinesEqualFold applies the EqualFold predicate on the "lines" field. +func LinesEqualFold(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEqualFold(FieldLines, v)) +} + +// LinesContainsFold applies the ContainsFold predicate on the "lines" field. +func LinesContainsFold(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldContainsFold(FieldLines, v)) +} + +// PathEQ applies the EQ predicate on the "path" field. +func PathEQ(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEQ(FieldPath, v)) +} + +// PathNEQ applies the NEQ predicate on the "path" field. +func PathNEQ(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldNEQ(FieldPath, v)) +} + +// PathIn applies the In predicate on the "path" field. +func PathIn(vs ...string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldIn(FieldPath, vs...)) +} + +// PathNotIn applies the NotIn predicate on the "path" field. +func PathNotIn(vs ...string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldNotIn(FieldPath, vs...)) +} + +// PathGT applies the GT predicate on the "path" field. +func PathGT(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldGT(FieldPath, v)) +} + +// PathGTE applies the GTE predicate on the "path" field. +func PathGTE(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldGTE(FieldPath, v)) +} + +// PathLT applies the LT predicate on the "path" field. +func PathLT(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldLT(FieldPath, v)) +} + +// PathLTE applies the LTE predicate on the "path" field. +func PathLTE(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldLTE(FieldPath, v)) +} + +// PathContains applies the Contains predicate on the "path" field. +func PathContains(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldContains(FieldPath, v)) +} + +// PathHasPrefix applies the HasPrefix predicate on the "path" field. +func PathHasPrefix(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldHasPrefix(FieldPath, v)) +} + +// PathHasSuffix applies the HasSuffix predicate on the "path" field. +func PathHasSuffix(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldHasSuffix(FieldPath, v)) +} + +// PathEqualFold applies the EqualFold predicate on the "path" field. +func PathEqualFold(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEqualFold(FieldPath, v)) +} + +// PathContainsFold applies the ContainsFold predicate on the "path" field. +func PathContainsFold(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldContainsFold(FieldPath, v)) +} + +// MessageEQ applies the EQ predicate on the "message" field. +func MessageEQ(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEQ(FieldMessage, v)) +} + +// MessageNEQ applies the NEQ predicate on the "message" field. +func MessageNEQ(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldNEQ(FieldMessage, v)) +} + +// MessageIn applies the In predicate on the "message" field. +func MessageIn(vs ...string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldIn(FieldMessage, vs...)) +} + +// MessageNotIn applies the NotIn predicate on the "message" field. +func MessageNotIn(vs ...string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldNotIn(FieldMessage, vs...)) +} + +// MessageGT applies the GT predicate on the "message" field. +func MessageGT(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldGT(FieldMessage, v)) +} + +// MessageGTE applies the GTE predicate on the "message" field. +func MessageGTE(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldGTE(FieldMessage, v)) +} + +// MessageLT applies the LT predicate on the "message" field. +func MessageLT(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldLT(FieldMessage, v)) +} + +// MessageLTE applies the LTE predicate on the "message" field. +func MessageLTE(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldLTE(FieldMessage, v)) +} + +// MessageContains applies the Contains predicate on the "message" field. +func MessageContains(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldContains(FieldMessage, v)) +} + +// MessageHasPrefix applies the HasPrefix predicate on the "message" field. +func MessageHasPrefix(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldHasPrefix(FieldMessage, v)) +} + +// MessageHasSuffix applies the HasSuffix predicate on the "message" field. +func MessageHasSuffix(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldHasSuffix(FieldMessage, v)) +} + +// MessageEqualFold applies the EqualFold predicate on the "message" field. +func MessageEqualFold(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEqualFold(FieldMessage, v)) +} + +// MessageContainsFold applies the ContainsFold predicate on the "message" field. +func MessageContainsFold(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldContainsFold(FieldMessage, v)) +} + +// MessageZhEQ applies the EQ predicate on the "message_zh" field. +func MessageZhEQ(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEQ(FieldMessageZh, v)) +} + +// MessageZhNEQ applies the NEQ predicate on the "message_zh" field. +func MessageZhNEQ(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldNEQ(FieldMessageZh, v)) +} + +// MessageZhIn applies the In predicate on the "message_zh" field. +func MessageZhIn(vs ...string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldIn(FieldMessageZh, vs...)) +} + +// MessageZhNotIn applies the NotIn predicate on the "message_zh" field. +func MessageZhNotIn(vs ...string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldNotIn(FieldMessageZh, vs...)) +} + +// MessageZhGT applies the GT predicate on the "message_zh" field. +func MessageZhGT(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldGT(FieldMessageZh, v)) +} + +// MessageZhGTE applies the GTE predicate on the "message_zh" field. +func MessageZhGTE(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldGTE(FieldMessageZh, v)) +} + +// MessageZhLT applies the LT predicate on the "message_zh" field. +func MessageZhLT(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldLT(FieldMessageZh, v)) +} + +// MessageZhLTE applies the LTE predicate on the "message_zh" field. +func MessageZhLTE(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldLTE(FieldMessageZh, v)) +} + +// MessageZhContains applies the Contains predicate on the "message_zh" field. +func MessageZhContains(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldContains(FieldMessageZh, v)) +} + +// MessageZhHasPrefix applies the HasPrefix predicate on the "message_zh" field. +func MessageZhHasPrefix(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldHasPrefix(FieldMessageZh, v)) +} + +// MessageZhHasSuffix applies the HasSuffix predicate on the "message_zh" field. +func MessageZhHasSuffix(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldHasSuffix(FieldMessageZh, v)) +} + +// MessageZhEqualFold applies the EqualFold predicate on the "message_zh" field. +func MessageZhEqualFold(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEqualFold(FieldMessageZh, v)) +} + +// MessageZhContainsFold applies the ContainsFold predicate on the "message_zh" field. +func MessageZhContainsFold(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldContainsFold(FieldMessageZh, v)) +} + +// SeverityEQ applies the EQ predicate on the "severity" field. +func SeverityEQ(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEQ(FieldSeverity, v)) +} + +// SeverityNEQ applies the NEQ predicate on the "severity" field. +func SeverityNEQ(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldNEQ(FieldSeverity, v)) +} + +// SeverityIn applies the In predicate on the "severity" field. +func SeverityIn(vs ...string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldIn(FieldSeverity, vs...)) +} + +// SeverityNotIn applies the NotIn predicate on the "severity" field. +func SeverityNotIn(vs ...string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldNotIn(FieldSeverity, vs...)) +} + +// SeverityGT applies the GT predicate on the "severity" field. +func SeverityGT(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldGT(FieldSeverity, v)) +} + +// SeverityGTE applies the GTE predicate on the "severity" field. +func SeverityGTE(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldGTE(FieldSeverity, v)) +} + +// SeverityLT applies the LT predicate on the "severity" field. +func SeverityLT(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldLT(FieldSeverity, v)) +} + +// SeverityLTE applies the LTE predicate on the "severity" field. +func SeverityLTE(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldLTE(FieldSeverity, v)) +} + +// SeverityContains applies the Contains predicate on the "severity" field. +func SeverityContains(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldContains(FieldSeverity, v)) +} + +// SeverityHasPrefix applies the HasPrefix predicate on the "severity" field. +func SeverityHasPrefix(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldHasPrefix(FieldSeverity, v)) +} + +// SeverityHasSuffix applies the HasSuffix predicate on the "severity" field. +func SeverityHasSuffix(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldHasSuffix(FieldSeverity, v)) +} + +// SeverityEqualFold applies the EqualFold predicate on the "severity" field. +func SeverityEqualFold(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEqualFold(FieldSeverity, v)) +} + +// SeverityContainsFold applies the ContainsFold predicate on the "severity" field. +func SeverityContainsFold(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldContainsFold(FieldSeverity, v)) +} + +// AbstractEnEQ applies the EQ predicate on the "abstract_en" field. +func AbstractEnEQ(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEQ(FieldAbstractEn, v)) +} + +// AbstractEnNEQ applies the NEQ predicate on the "abstract_en" field. +func AbstractEnNEQ(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldNEQ(FieldAbstractEn, v)) +} + +// AbstractEnIn applies the In predicate on the "abstract_en" field. +func AbstractEnIn(vs ...string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldIn(FieldAbstractEn, vs...)) +} + +// AbstractEnNotIn applies the NotIn predicate on the "abstract_en" field. +func AbstractEnNotIn(vs ...string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldNotIn(FieldAbstractEn, vs...)) +} + +// AbstractEnGT applies the GT predicate on the "abstract_en" field. +func AbstractEnGT(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldGT(FieldAbstractEn, v)) +} + +// AbstractEnGTE applies the GTE predicate on the "abstract_en" field. +func AbstractEnGTE(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldGTE(FieldAbstractEn, v)) +} + +// AbstractEnLT applies the LT predicate on the "abstract_en" field. +func AbstractEnLT(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldLT(FieldAbstractEn, v)) +} + +// AbstractEnLTE applies the LTE predicate on the "abstract_en" field. +func AbstractEnLTE(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldLTE(FieldAbstractEn, v)) +} + +// AbstractEnContains applies the Contains predicate on the "abstract_en" field. +func AbstractEnContains(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldContains(FieldAbstractEn, v)) +} + +// AbstractEnHasPrefix applies the HasPrefix predicate on the "abstract_en" field. +func AbstractEnHasPrefix(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldHasPrefix(FieldAbstractEn, v)) +} + +// AbstractEnHasSuffix applies the HasSuffix predicate on the "abstract_en" field. +func AbstractEnHasSuffix(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldHasSuffix(FieldAbstractEn, v)) +} + +// AbstractEnEqualFold applies the EqualFold predicate on the "abstract_en" field. +func AbstractEnEqualFold(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEqualFold(FieldAbstractEn, v)) +} + +// AbstractEnContainsFold applies the ContainsFold predicate on the "abstract_en" field. +func AbstractEnContainsFold(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldContainsFold(FieldAbstractEn, v)) +} + +// AbstractZhEQ applies the EQ predicate on the "abstract_zh" field. +func AbstractZhEQ(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEQ(FieldAbstractZh, v)) +} + +// AbstractZhNEQ applies the NEQ predicate on the "abstract_zh" field. +func AbstractZhNEQ(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldNEQ(FieldAbstractZh, v)) +} + +// AbstractZhIn applies the In predicate on the "abstract_zh" field. +func AbstractZhIn(vs ...string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldIn(FieldAbstractZh, vs...)) +} + +// AbstractZhNotIn applies the NotIn predicate on the "abstract_zh" field. +func AbstractZhNotIn(vs ...string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldNotIn(FieldAbstractZh, vs...)) +} + +// AbstractZhGT applies the GT predicate on the "abstract_zh" field. +func AbstractZhGT(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldGT(FieldAbstractZh, v)) +} + +// AbstractZhGTE applies the GTE predicate on the "abstract_zh" field. +func AbstractZhGTE(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldGTE(FieldAbstractZh, v)) +} + +// AbstractZhLT applies the LT predicate on the "abstract_zh" field. +func AbstractZhLT(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldLT(FieldAbstractZh, v)) +} + +// AbstractZhLTE applies the LTE predicate on the "abstract_zh" field. +func AbstractZhLTE(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldLTE(FieldAbstractZh, v)) +} + +// AbstractZhContains applies the Contains predicate on the "abstract_zh" field. +func AbstractZhContains(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldContains(FieldAbstractZh, v)) +} + +// AbstractZhHasPrefix applies the HasPrefix predicate on the "abstract_zh" field. +func AbstractZhHasPrefix(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldHasPrefix(FieldAbstractZh, v)) +} + +// AbstractZhHasSuffix applies the HasSuffix predicate on the "abstract_zh" field. +func AbstractZhHasSuffix(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldHasSuffix(FieldAbstractZh, v)) +} + +// AbstractZhEqualFold applies the EqualFold predicate on the "abstract_zh" field. +func AbstractZhEqualFold(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEqualFold(FieldAbstractZh, v)) +} + +// AbstractZhContainsFold applies the ContainsFold predicate on the "abstract_zh" field. +func AbstractZhContainsFold(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldContainsFold(FieldAbstractZh, v)) +} + +// CategoryEnEQ applies the EQ predicate on the "category_en" field. +func CategoryEnEQ(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEQ(FieldCategoryEn, v)) +} + +// CategoryEnNEQ applies the NEQ predicate on the "category_en" field. +func CategoryEnNEQ(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldNEQ(FieldCategoryEn, v)) +} + +// CategoryEnIn applies the In predicate on the "category_en" field. +func CategoryEnIn(vs ...string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldIn(FieldCategoryEn, vs...)) +} + +// CategoryEnNotIn applies the NotIn predicate on the "category_en" field. +func CategoryEnNotIn(vs ...string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldNotIn(FieldCategoryEn, vs...)) +} + +// CategoryEnGT applies the GT predicate on the "category_en" field. +func CategoryEnGT(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldGT(FieldCategoryEn, v)) +} + +// CategoryEnGTE applies the GTE predicate on the "category_en" field. +func CategoryEnGTE(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldGTE(FieldCategoryEn, v)) +} + +// CategoryEnLT applies the LT predicate on the "category_en" field. +func CategoryEnLT(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldLT(FieldCategoryEn, v)) +} + +// CategoryEnLTE applies the LTE predicate on the "category_en" field. +func CategoryEnLTE(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldLTE(FieldCategoryEn, v)) +} + +// CategoryEnContains applies the Contains predicate on the "category_en" field. +func CategoryEnContains(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldContains(FieldCategoryEn, v)) +} + +// CategoryEnHasPrefix applies the HasPrefix predicate on the "category_en" field. +func CategoryEnHasPrefix(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldHasPrefix(FieldCategoryEn, v)) +} + +// CategoryEnHasSuffix applies the HasSuffix predicate on the "category_en" field. +func CategoryEnHasSuffix(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldHasSuffix(FieldCategoryEn, v)) +} + +// CategoryEnEqualFold applies the EqualFold predicate on the "category_en" field. +func CategoryEnEqualFold(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEqualFold(FieldCategoryEn, v)) +} + +// CategoryEnContainsFold applies the ContainsFold predicate on the "category_en" field. +func CategoryEnContainsFold(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldContainsFold(FieldCategoryEn, v)) +} + +// CategoryZhEQ applies the EQ predicate on the "category_zh" field. +func CategoryZhEQ(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEQ(FieldCategoryZh, v)) +} + +// CategoryZhNEQ applies the NEQ predicate on the "category_zh" field. +func CategoryZhNEQ(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldNEQ(FieldCategoryZh, v)) +} + +// CategoryZhIn applies the In predicate on the "category_zh" field. +func CategoryZhIn(vs ...string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldIn(FieldCategoryZh, vs...)) +} + +// CategoryZhNotIn applies the NotIn predicate on the "category_zh" field. +func CategoryZhNotIn(vs ...string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldNotIn(FieldCategoryZh, vs...)) +} + +// CategoryZhGT applies the GT predicate on the "category_zh" field. +func CategoryZhGT(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldGT(FieldCategoryZh, v)) +} + +// CategoryZhGTE applies the GTE predicate on the "category_zh" field. +func CategoryZhGTE(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldGTE(FieldCategoryZh, v)) +} + +// CategoryZhLT applies the LT predicate on the "category_zh" field. +func CategoryZhLT(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldLT(FieldCategoryZh, v)) +} + +// CategoryZhLTE applies the LTE predicate on the "category_zh" field. +func CategoryZhLTE(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldLTE(FieldCategoryZh, v)) +} + +// CategoryZhContains applies the Contains predicate on the "category_zh" field. +func CategoryZhContains(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldContains(FieldCategoryZh, v)) +} + +// CategoryZhHasPrefix applies the HasPrefix predicate on the "category_zh" field. +func CategoryZhHasPrefix(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldHasPrefix(FieldCategoryZh, v)) +} + +// CategoryZhHasSuffix applies the HasSuffix predicate on the "category_zh" field. +func CategoryZhHasSuffix(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldHasSuffix(FieldCategoryZh, v)) +} + +// CategoryZhEqualFold applies the EqualFold predicate on the "category_zh" field. +func CategoryZhEqualFold(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEqualFold(FieldCategoryZh, v)) +} + +// CategoryZhContainsFold applies the ContainsFold predicate on the "category_zh" field. +func CategoryZhContainsFold(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldContainsFold(FieldCategoryZh, v)) +} + +// ConfidenceEQ applies the EQ predicate on the "confidence" field. +func ConfidenceEQ(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEQ(FieldConfidence, v)) +} + +// ConfidenceNEQ applies the NEQ predicate on the "confidence" field. +func ConfidenceNEQ(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldNEQ(FieldConfidence, v)) +} + +// ConfidenceIn applies the In predicate on the "confidence" field. +func ConfidenceIn(vs ...string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldIn(FieldConfidence, vs...)) +} + +// ConfidenceNotIn applies the NotIn predicate on the "confidence" field. +func ConfidenceNotIn(vs ...string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldNotIn(FieldConfidence, vs...)) +} + +// ConfidenceGT applies the GT predicate on the "confidence" field. +func ConfidenceGT(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldGT(FieldConfidence, v)) +} + +// ConfidenceGTE applies the GTE predicate on the "confidence" field. +func ConfidenceGTE(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldGTE(FieldConfidence, v)) +} + +// ConfidenceLT applies the LT predicate on the "confidence" field. +func ConfidenceLT(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldLT(FieldConfidence, v)) +} + +// ConfidenceLTE applies the LTE predicate on the "confidence" field. +func ConfidenceLTE(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldLTE(FieldConfidence, v)) +} + +// ConfidenceContains applies the Contains predicate on the "confidence" field. +func ConfidenceContains(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldContains(FieldConfidence, v)) +} + +// ConfidenceHasPrefix applies the HasPrefix predicate on the "confidence" field. +func ConfidenceHasPrefix(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldHasPrefix(FieldConfidence, v)) +} + +// ConfidenceHasSuffix applies the HasSuffix predicate on the "confidence" field. +func ConfidenceHasSuffix(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldHasSuffix(FieldConfidence, v)) +} + +// ConfidenceEqualFold applies the EqualFold predicate on the "confidence" field. +func ConfidenceEqualFold(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEqualFold(FieldConfidence, v)) +} + +// ConfidenceContainsFold applies the ContainsFold predicate on the "confidence" field. +func ConfidenceContainsFold(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldContainsFold(FieldConfidence, v)) +} + +// ImpactEQ applies the EQ predicate on the "impact" field. +func ImpactEQ(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEQ(FieldImpact, v)) +} + +// ImpactNEQ applies the NEQ predicate on the "impact" field. +func ImpactNEQ(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldNEQ(FieldImpact, v)) +} + +// ImpactIn applies the In predicate on the "impact" field. +func ImpactIn(vs ...string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldIn(FieldImpact, vs...)) +} + +// ImpactNotIn applies the NotIn predicate on the "impact" field. +func ImpactNotIn(vs ...string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldNotIn(FieldImpact, vs...)) +} + +// ImpactGT applies the GT predicate on the "impact" field. +func ImpactGT(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldGT(FieldImpact, v)) +} + +// ImpactGTE applies the GTE predicate on the "impact" field. +func ImpactGTE(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldGTE(FieldImpact, v)) +} + +// ImpactLT applies the LT predicate on the "impact" field. +func ImpactLT(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldLT(FieldImpact, v)) +} + +// ImpactLTE applies the LTE predicate on the "impact" field. +func ImpactLTE(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldLTE(FieldImpact, v)) +} + +// ImpactContains applies the Contains predicate on the "impact" field. +func ImpactContains(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldContains(FieldImpact, v)) +} + +// ImpactHasPrefix applies the HasPrefix predicate on the "impact" field. +func ImpactHasPrefix(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldHasPrefix(FieldImpact, v)) +} + +// ImpactHasSuffix applies the HasSuffix predicate on the "impact" field. +func ImpactHasSuffix(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldHasSuffix(FieldImpact, v)) +} + +// ImpactEqualFold applies the EqualFold predicate on the "impact" field. +func ImpactEqualFold(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEqualFold(FieldImpact, v)) +} + +// ImpactContainsFold applies the ContainsFold predicate on the "impact" field. +func ImpactContainsFold(v string) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldContainsFold(FieldImpact, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.FieldLTE(FieldCreatedAt, v)) +} + +// HasSecurityScanning applies the HasEdge predicate on the "security_scanning" edge. +func HasSecurityScanning() predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SecurityScanningTable, SecurityScanningColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasSecurityScanningWith applies the HasEdge predicate on the "security_scanning" edge with a given conditions (other predicates). +func HasSecurityScanningWith(preds ...predicate.SecurityScanning) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(func(s *sql.Selector) { + step := newSecurityScanningStep() + 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.SecurityScanningResult) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.SecurityScanningResult) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.SecurityScanningResult) predicate.SecurityScanningResult { + return predicate.SecurityScanningResult(sql.NotPredicates(p)) +} diff --git a/backend/db/securityscanningresult_create.go b/backend/db/securityscanningresult_create.go new file mode 100644 index 0000000..0b1bbe9 --- /dev/null +++ b/backend/db/securityscanningresult_create.go @@ -0,0 +1,1486 @@ +// 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/securityscanning" + "github.com/chaitin/MonkeyCode/backend/db/securityscanningresult" + "github.com/chaitin/MonkeyCode/backend/ent/types" + "github.com/google/uuid" +) + +// SecurityScanningResultCreate is the builder for creating a SecurityScanningResult entity. +type SecurityScanningResultCreate struct { + config + mutation *SecurityScanningResultMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetSecurityScanningID sets the "security_scanning_id" field. +func (ssrc *SecurityScanningResultCreate) SetSecurityScanningID(u uuid.UUID) *SecurityScanningResultCreate { + ssrc.mutation.SetSecurityScanningID(u) + return ssrc +} + +// SetCheckID sets the "check_id" field. +func (ssrc *SecurityScanningResultCreate) SetCheckID(s string) *SecurityScanningResultCreate { + ssrc.mutation.SetCheckID(s) + return ssrc +} + +// SetEngineKind sets the "engine_kind" field. +func (ssrc *SecurityScanningResultCreate) SetEngineKind(s string) *SecurityScanningResultCreate { + ssrc.mutation.SetEngineKind(s) + return ssrc +} + +// SetLines sets the "lines" field. +func (ssrc *SecurityScanningResultCreate) SetLines(s string) *SecurityScanningResultCreate { + ssrc.mutation.SetLines(s) + return ssrc +} + +// SetPath sets the "path" field. +func (ssrc *SecurityScanningResultCreate) SetPath(s string) *SecurityScanningResultCreate { + ssrc.mutation.SetPath(s) + return ssrc +} + +// SetMessage sets the "message" field. +func (ssrc *SecurityScanningResultCreate) SetMessage(s string) *SecurityScanningResultCreate { + ssrc.mutation.SetMessage(s) + return ssrc +} + +// SetMessageZh sets the "message_zh" field. +func (ssrc *SecurityScanningResultCreate) SetMessageZh(s string) *SecurityScanningResultCreate { + ssrc.mutation.SetMessageZh(s) + return ssrc +} + +// SetSeverity sets the "severity" field. +func (ssrc *SecurityScanningResultCreate) SetSeverity(s string) *SecurityScanningResultCreate { + ssrc.mutation.SetSeverity(s) + return ssrc +} + +// SetAbstractEn sets the "abstract_en" field. +func (ssrc *SecurityScanningResultCreate) SetAbstractEn(s string) *SecurityScanningResultCreate { + ssrc.mutation.SetAbstractEn(s) + return ssrc +} + +// SetAbstractZh sets the "abstract_zh" field. +func (ssrc *SecurityScanningResultCreate) SetAbstractZh(s string) *SecurityScanningResultCreate { + ssrc.mutation.SetAbstractZh(s) + return ssrc +} + +// SetCategoryEn sets the "category_en" field. +func (ssrc *SecurityScanningResultCreate) SetCategoryEn(s string) *SecurityScanningResultCreate { + ssrc.mutation.SetCategoryEn(s) + return ssrc +} + +// SetCategoryZh sets the "category_zh" field. +func (ssrc *SecurityScanningResultCreate) SetCategoryZh(s string) *SecurityScanningResultCreate { + ssrc.mutation.SetCategoryZh(s) + return ssrc +} + +// SetConfidence sets the "confidence" field. +func (ssrc *SecurityScanningResultCreate) SetConfidence(s string) *SecurityScanningResultCreate { + ssrc.mutation.SetConfidence(s) + return ssrc +} + +// SetCwe sets the "cwe" field. +func (ssrc *SecurityScanningResultCreate) SetCwe(i []interface{}) *SecurityScanningResultCreate { + ssrc.mutation.SetCwe(i) + return ssrc +} + +// SetImpact sets the "impact" field. +func (ssrc *SecurityScanningResultCreate) SetImpact(s string) *SecurityScanningResultCreate { + ssrc.mutation.SetImpact(s) + return ssrc +} + +// SetOwasp sets the "owasp" field. +func (ssrc *SecurityScanningResultCreate) SetOwasp(i []interface{}) *SecurityScanningResultCreate { + ssrc.mutation.SetOwasp(i) + return ssrc +} + +// SetStartPosition sets the "start_position" field. +func (ssrc *SecurityScanningResultCreate) SetStartPosition(t *types.Position) *SecurityScanningResultCreate { + ssrc.mutation.SetStartPosition(t) + return ssrc +} + +// SetEndPosition sets the "end_position" field. +func (ssrc *SecurityScanningResultCreate) SetEndPosition(t *types.Position) *SecurityScanningResultCreate { + ssrc.mutation.SetEndPosition(t) + return ssrc +} + +// SetCreatedAt sets the "created_at" field. +func (ssrc *SecurityScanningResultCreate) SetCreatedAt(t time.Time) *SecurityScanningResultCreate { + ssrc.mutation.SetCreatedAt(t) + return ssrc +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (ssrc *SecurityScanningResultCreate) SetNillableCreatedAt(t *time.Time) *SecurityScanningResultCreate { + if t != nil { + ssrc.SetCreatedAt(*t) + } + return ssrc +} + +// SetID sets the "id" field. +func (ssrc *SecurityScanningResultCreate) SetID(u uuid.UUID) *SecurityScanningResultCreate { + ssrc.mutation.SetID(u) + return ssrc +} + +// SetSecurityScanning sets the "security_scanning" edge to the SecurityScanning entity. +func (ssrc *SecurityScanningResultCreate) SetSecurityScanning(s *SecurityScanning) *SecurityScanningResultCreate { + return ssrc.SetSecurityScanningID(s.ID) +} + +// Mutation returns the SecurityScanningResultMutation object of the builder. +func (ssrc *SecurityScanningResultCreate) Mutation() *SecurityScanningResultMutation { + return ssrc.mutation +} + +// Save creates the SecurityScanningResult in the database. +func (ssrc *SecurityScanningResultCreate) Save(ctx context.Context) (*SecurityScanningResult, error) { + ssrc.defaults() + return withHooks(ctx, ssrc.sqlSave, ssrc.mutation, ssrc.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (ssrc *SecurityScanningResultCreate) SaveX(ctx context.Context) *SecurityScanningResult { + v, err := ssrc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (ssrc *SecurityScanningResultCreate) Exec(ctx context.Context) error { + _, err := ssrc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ssrc *SecurityScanningResultCreate) ExecX(ctx context.Context) { + if err := ssrc.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (ssrc *SecurityScanningResultCreate) defaults() { + if _, ok := ssrc.mutation.CreatedAt(); !ok { + v := securityscanningresult.DefaultCreatedAt() + ssrc.mutation.SetCreatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (ssrc *SecurityScanningResultCreate) check() error { + if _, ok := ssrc.mutation.SecurityScanningID(); !ok { + return &ValidationError{Name: "security_scanning_id", err: errors.New(`db: missing required field "SecurityScanningResult.security_scanning_id"`)} + } + if _, ok := ssrc.mutation.CheckID(); !ok { + return &ValidationError{Name: "check_id", err: errors.New(`db: missing required field "SecurityScanningResult.check_id"`)} + } + if _, ok := ssrc.mutation.EngineKind(); !ok { + return &ValidationError{Name: "engine_kind", err: errors.New(`db: missing required field "SecurityScanningResult.engine_kind"`)} + } + if _, ok := ssrc.mutation.Lines(); !ok { + return &ValidationError{Name: "lines", err: errors.New(`db: missing required field "SecurityScanningResult.lines"`)} + } + if _, ok := ssrc.mutation.Path(); !ok { + return &ValidationError{Name: "path", err: errors.New(`db: missing required field "SecurityScanningResult.path"`)} + } + if _, ok := ssrc.mutation.Message(); !ok { + return &ValidationError{Name: "message", err: errors.New(`db: missing required field "SecurityScanningResult.message"`)} + } + if _, ok := ssrc.mutation.MessageZh(); !ok { + return &ValidationError{Name: "message_zh", err: errors.New(`db: missing required field "SecurityScanningResult.message_zh"`)} + } + if _, ok := ssrc.mutation.Severity(); !ok { + return &ValidationError{Name: "severity", err: errors.New(`db: missing required field "SecurityScanningResult.severity"`)} + } + if _, ok := ssrc.mutation.AbstractEn(); !ok { + return &ValidationError{Name: "abstract_en", err: errors.New(`db: missing required field "SecurityScanningResult.abstract_en"`)} + } + if _, ok := ssrc.mutation.AbstractZh(); !ok { + return &ValidationError{Name: "abstract_zh", err: errors.New(`db: missing required field "SecurityScanningResult.abstract_zh"`)} + } + if _, ok := ssrc.mutation.CategoryEn(); !ok { + return &ValidationError{Name: "category_en", err: errors.New(`db: missing required field "SecurityScanningResult.category_en"`)} + } + if _, ok := ssrc.mutation.CategoryZh(); !ok { + return &ValidationError{Name: "category_zh", err: errors.New(`db: missing required field "SecurityScanningResult.category_zh"`)} + } + if _, ok := ssrc.mutation.Confidence(); !ok { + return &ValidationError{Name: "confidence", err: errors.New(`db: missing required field "SecurityScanningResult.confidence"`)} + } + if _, ok := ssrc.mutation.Cwe(); !ok { + return &ValidationError{Name: "cwe", err: errors.New(`db: missing required field "SecurityScanningResult.cwe"`)} + } + if _, ok := ssrc.mutation.Impact(); !ok { + return &ValidationError{Name: "impact", err: errors.New(`db: missing required field "SecurityScanningResult.impact"`)} + } + if _, ok := ssrc.mutation.Owasp(); !ok { + return &ValidationError{Name: "owasp", err: errors.New(`db: missing required field "SecurityScanningResult.owasp"`)} + } + if _, ok := ssrc.mutation.StartPosition(); !ok { + return &ValidationError{Name: "start_position", err: errors.New(`db: missing required field "SecurityScanningResult.start_position"`)} + } + if _, ok := ssrc.mutation.EndPosition(); !ok { + return &ValidationError{Name: "end_position", err: errors.New(`db: missing required field "SecurityScanningResult.end_position"`)} + } + if _, ok := ssrc.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "SecurityScanningResult.created_at"`)} + } + if len(ssrc.mutation.SecurityScanningIDs()) == 0 { + return &ValidationError{Name: "security_scanning", err: errors.New(`db: missing required edge "SecurityScanningResult.security_scanning"`)} + } + return nil +} + +func (ssrc *SecurityScanningResultCreate) sqlSave(ctx context.Context) (*SecurityScanningResult, error) { + if err := ssrc.check(); err != nil { + return nil, err + } + _node, _spec := ssrc.createSpec() + if err := sqlgraph.CreateNode(ctx, ssrc.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 + } + } + ssrc.mutation.id = &_node.ID + ssrc.mutation.done = true + return _node, nil +} + +func (ssrc *SecurityScanningResultCreate) createSpec() (*SecurityScanningResult, *sqlgraph.CreateSpec) { + var ( + _node = &SecurityScanningResult{config: ssrc.config} + _spec = sqlgraph.NewCreateSpec(securityscanningresult.Table, sqlgraph.NewFieldSpec(securityscanningresult.FieldID, field.TypeUUID)) + ) + _spec.OnConflict = ssrc.conflict + if id, ok := ssrc.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = &id + } + if value, ok := ssrc.mutation.CheckID(); ok { + _spec.SetField(securityscanningresult.FieldCheckID, field.TypeString, value) + _node.CheckID = value + } + if value, ok := ssrc.mutation.EngineKind(); ok { + _spec.SetField(securityscanningresult.FieldEngineKind, field.TypeString, value) + _node.EngineKind = value + } + if value, ok := ssrc.mutation.Lines(); ok { + _spec.SetField(securityscanningresult.FieldLines, field.TypeString, value) + _node.Lines = value + } + if value, ok := ssrc.mutation.Path(); ok { + _spec.SetField(securityscanningresult.FieldPath, field.TypeString, value) + _node.Path = value + } + if value, ok := ssrc.mutation.Message(); ok { + _spec.SetField(securityscanningresult.FieldMessage, field.TypeString, value) + _node.Message = value + } + if value, ok := ssrc.mutation.MessageZh(); ok { + _spec.SetField(securityscanningresult.FieldMessageZh, field.TypeString, value) + _node.MessageZh = value + } + if value, ok := ssrc.mutation.Severity(); ok { + _spec.SetField(securityscanningresult.FieldSeverity, field.TypeString, value) + _node.Severity = value + } + if value, ok := ssrc.mutation.AbstractEn(); ok { + _spec.SetField(securityscanningresult.FieldAbstractEn, field.TypeString, value) + _node.AbstractEn = value + } + if value, ok := ssrc.mutation.AbstractZh(); ok { + _spec.SetField(securityscanningresult.FieldAbstractZh, field.TypeString, value) + _node.AbstractZh = value + } + if value, ok := ssrc.mutation.CategoryEn(); ok { + _spec.SetField(securityscanningresult.FieldCategoryEn, field.TypeString, value) + _node.CategoryEn = value + } + if value, ok := ssrc.mutation.CategoryZh(); ok { + _spec.SetField(securityscanningresult.FieldCategoryZh, field.TypeString, value) + _node.CategoryZh = value + } + if value, ok := ssrc.mutation.Confidence(); ok { + _spec.SetField(securityscanningresult.FieldConfidence, field.TypeString, value) + _node.Confidence = value + } + if value, ok := ssrc.mutation.Cwe(); ok { + _spec.SetField(securityscanningresult.FieldCwe, field.TypeJSON, value) + _node.Cwe = value + } + if value, ok := ssrc.mutation.Impact(); ok { + _spec.SetField(securityscanningresult.FieldImpact, field.TypeString, value) + _node.Impact = value + } + if value, ok := ssrc.mutation.Owasp(); ok { + _spec.SetField(securityscanningresult.FieldOwasp, field.TypeJSON, value) + _node.Owasp = value + } + if value, ok := ssrc.mutation.StartPosition(); ok { + _spec.SetField(securityscanningresult.FieldStartPosition, field.TypeJSON, value) + _node.StartPosition = value + } + if value, ok := ssrc.mutation.EndPosition(); ok { + _spec.SetField(securityscanningresult.FieldEndPosition, field.TypeJSON, value) + _node.EndPosition = value + } + if value, ok := ssrc.mutation.CreatedAt(); ok { + _spec.SetField(securityscanningresult.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if nodes := ssrc.mutation.SecurityScanningIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: securityscanningresult.SecurityScanningTable, + Columns: []string{securityscanningresult.SecurityScanningColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(securityscanning.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.SecurityScanningID = 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.SecurityScanningResult.Create(). +// SetSecurityScanningID(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.SecurityScanningResultUpsert) { +// SetSecurityScanningID(v+v). +// }). +// Exec(ctx) +func (ssrc *SecurityScanningResultCreate) OnConflict(opts ...sql.ConflictOption) *SecurityScanningResultUpsertOne { + ssrc.conflict = opts + return &SecurityScanningResultUpsertOne{ + create: ssrc, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.SecurityScanningResult.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (ssrc *SecurityScanningResultCreate) OnConflictColumns(columns ...string) *SecurityScanningResultUpsertOne { + ssrc.conflict = append(ssrc.conflict, sql.ConflictColumns(columns...)) + return &SecurityScanningResultUpsertOne{ + create: ssrc, + } +} + +type ( + // SecurityScanningResultUpsertOne is the builder for "upsert"-ing + // one SecurityScanningResult node. + SecurityScanningResultUpsertOne struct { + create *SecurityScanningResultCreate + } + + // SecurityScanningResultUpsert is the "OnConflict" setter. + SecurityScanningResultUpsert struct { + *sql.UpdateSet + } +) + +// SetSecurityScanningID sets the "security_scanning_id" field. +func (u *SecurityScanningResultUpsert) SetSecurityScanningID(v uuid.UUID) *SecurityScanningResultUpsert { + u.Set(securityscanningresult.FieldSecurityScanningID, v) + return u +} + +// UpdateSecurityScanningID sets the "security_scanning_id" field to the value that was provided on create. +func (u *SecurityScanningResultUpsert) UpdateSecurityScanningID() *SecurityScanningResultUpsert { + u.SetExcluded(securityscanningresult.FieldSecurityScanningID) + return u +} + +// SetCheckID sets the "check_id" field. +func (u *SecurityScanningResultUpsert) SetCheckID(v string) *SecurityScanningResultUpsert { + u.Set(securityscanningresult.FieldCheckID, v) + return u +} + +// UpdateCheckID sets the "check_id" field to the value that was provided on create. +func (u *SecurityScanningResultUpsert) UpdateCheckID() *SecurityScanningResultUpsert { + u.SetExcluded(securityscanningresult.FieldCheckID) + return u +} + +// SetEngineKind sets the "engine_kind" field. +func (u *SecurityScanningResultUpsert) SetEngineKind(v string) *SecurityScanningResultUpsert { + u.Set(securityscanningresult.FieldEngineKind, v) + return u +} + +// UpdateEngineKind sets the "engine_kind" field to the value that was provided on create. +func (u *SecurityScanningResultUpsert) UpdateEngineKind() *SecurityScanningResultUpsert { + u.SetExcluded(securityscanningresult.FieldEngineKind) + return u +} + +// SetLines sets the "lines" field. +func (u *SecurityScanningResultUpsert) SetLines(v string) *SecurityScanningResultUpsert { + u.Set(securityscanningresult.FieldLines, v) + return u +} + +// UpdateLines sets the "lines" field to the value that was provided on create. +func (u *SecurityScanningResultUpsert) UpdateLines() *SecurityScanningResultUpsert { + u.SetExcluded(securityscanningresult.FieldLines) + return u +} + +// SetPath sets the "path" field. +func (u *SecurityScanningResultUpsert) SetPath(v string) *SecurityScanningResultUpsert { + u.Set(securityscanningresult.FieldPath, v) + return u +} + +// UpdatePath sets the "path" field to the value that was provided on create. +func (u *SecurityScanningResultUpsert) UpdatePath() *SecurityScanningResultUpsert { + u.SetExcluded(securityscanningresult.FieldPath) + return u +} + +// SetMessage sets the "message" field. +func (u *SecurityScanningResultUpsert) SetMessage(v string) *SecurityScanningResultUpsert { + u.Set(securityscanningresult.FieldMessage, v) + return u +} + +// UpdateMessage sets the "message" field to the value that was provided on create. +func (u *SecurityScanningResultUpsert) UpdateMessage() *SecurityScanningResultUpsert { + u.SetExcluded(securityscanningresult.FieldMessage) + return u +} + +// SetMessageZh sets the "message_zh" field. +func (u *SecurityScanningResultUpsert) SetMessageZh(v string) *SecurityScanningResultUpsert { + u.Set(securityscanningresult.FieldMessageZh, v) + return u +} + +// UpdateMessageZh sets the "message_zh" field to the value that was provided on create. +func (u *SecurityScanningResultUpsert) UpdateMessageZh() *SecurityScanningResultUpsert { + u.SetExcluded(securityscanningresult.FieldMessageZh) + return u +} + +// SetSeverity sets the "severity" field. +func (u *SecurityScanningResultUpsert) SetSeverity(v string) *SecurityScanningResultUpsert { + u.Set(securityscanningresult.FieldSeverity, v) + return u +} + +// UpdateSeverity sets the "severity" field to the value that was provided on create. +func (u *SecurityScanningResultUpsert) UpdateSeverity() *SecurityScanningResultUpsert { + u.SetExcluded(securityscanningresult.FieldSeverity) + return u +} + +// SetAbstractEn sets the "abstract_en" field. +func (u *SecurityScanningResultUpsert) SetAbstractEn(v string) *SecurityScanningResultUpsert { + u.Set(securityscanningresult.FieldAbstractEn, v) + return u +} + +// UpdateAbstractEn sets the "abstract_en" field to the value that was provided on create. +func (u *SecurityScanningResultUpsert) UpdateAbstractEn() *SecurityScanningResultUpsert { + u.SetExcluded(securityscanningresult.FieldAbstractEn) + return u +} + +// SetAbstractZh sets the "abstract_zh" field. +func (u *SecurityScanningResultUpsert) SetAbstractZh(v string) *SecurityScanningResultUpsert { + u.Set(securityscanningresult.FieldAbstractZh, v) + return u +} + +// UpdateAbstractZh sets the "abstract_zh" field to the value that was provided on create. +func (u *SecurityScanningResultUpsert) UpdateAbstractZh() *SecurityScanningResultUpsert { + u.SetExcluded(securityscanningresult.FieldAbstractZh) + return u +} + +// SetCategoryEn sets the "category_en" field. +func (u *SecurityScanningResultUpsert) SetCategoryEn(v string) *SecurityScanningResultUpsert { + u.Set(securityscanningresult.FieldCategoryEn, v) + return u +} + +// UpdateCategoryEn sets the "category_en" field to the value that was provided on create. +func (u *SecurityScanningResultUpsert) UpdateCategoryEn() *SecurityScanningResultUpsert { + u.SetExcluded(securityscanningresult.FieldCategoryEn) + return u +} + +// SetCategoryZh sets the "category_zh" field. +func (u *SecurityScanningResultUpsert) SetCategoryZh(v string) *SecurityScanningResultUpsert { + u.Set(securityscanningresult.FieldCategoryZh, v) + return u +} + +// UpdateCategoryZh sets the "category_zh" field to the value that was provided on create. +func (u *SecurityScanningResultUpsert) UpdateCategoryZh() *SecurityScanningResultUpsert { + u.SetExcluded(securityscanningresult.FieldCategoryZh) + return u +} + +// SetConfidence sets the "confidence" field. +func (u *SecurityScanningResultUpsert) SetConfidence(v string) *SecurityScanningResultUpsert { + u.Set(securityscanningresult.FieldConfidence, v) + return u +} + +// UpdateConfidence sets the "confidence" field to the value that was provided on create. +func (u *SecurityScanningResultUpsert) UpdateConfidence() *SecurityScanningResultUpsert { + u.SetExcluded(securityscanningresult.FieldConfidence) + return u +} + +// SetCwe sets the "cwe" field. +func (u *SecurityScanningResultUpsert) SetCwe(v []interface{}) *SecurityScanningResultUpsert { + u.Set(securityscanningresult.FieldCwe, v) + return u +} + +// UpdateCwe sets the "cwe" field to the value that was provided on create. +func (u *SecurityScanningResultUpsert) UpdateCwe() *SecurityScanningResultUpsert { + u.SetExcluded(securityscanningresult.FieldCwe) + return u +} + +// SetImpact sets the "impact" field. +func (u *SecurityScanningResultUpsert) SetImpact(v string) *SecurityScanningResultUpsert { + u.Set(securityscanningresult.FieldImpact, v) + return u +} + +// UpdateImpact sets the "impact" field to the value that was provided on create. +func (u *SecurityScanningResultUpsert) UpdateImpact() *SecurityScanningResultUpsert { + u.SetExcluded(securityscanningresult.FieldImpact) + return u +} + +// SetOwasp sets the "owasp" field. +func (u *SecurityScanningResultUpsert) SetOwasp(v []interface{}) *SecurityScanningResultUpsert { + u.Set(securityscanningresult.FieldOwasp, v) + return u +} + +// UpdateOwasp sets the "owasp" field to the value that was provided on create. +func (u *SecurityScanningResultUpsert) UpdateOwasp() *SecurityScanningResultUpsert { + u.SetExcluded(securityscanningresult.FieldOwasp) + return u +} + +// SetStartPosition sets the "start_position" field. +func (u *SecurityScanningResultUpsert) SetStartPosition(v *types.Position) *SecurityScanningResultUpsert { + u.Set(securityscanningresult.FieldStartPosition, v) + return u +} + +// UpdateStartPosition sets the "start_position" field to the value that was provided on create. +func (u *SecurityScanningResultUpsert) UpdateStartPosition() *SecurityScanningResultUpsert { + u.SetExcluded(securityscanningresult.FieldStartPosition) + return u +} + +// SetEndPosition sets the "end_position" field. +func (u *SecurityScanningResultUpsert) SetEndPosition(v *types.Position) *SecurityScanningResultUpsert { + u.Set(securityscanningresult.FieldEndPosition, v) + return u +} + +// UpdateEndPosition sets the "end_position" field to the value that was provided on create. +func (u *SecurityScanningResultUpsert) UpdateEndPosition() *SecurityScanningResultUpsert { + u.SetExcluded(securityscanningresult.FieldEndPosition) + return u +} + +// SetCreatedAt sets the "created_at" field. +func (u *SecurityScanningResultUpsert) SetCreatedAt(v time.Time) *SecurityScanningResultUpsert { + u.Set(securityscanningresult.FieldCreatedAt, v) + return u +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *SecurityScanningResultUpsert) UpdateCreatedAt() *SecurityScanningResultUpsert { + u.SetExcluded(securityscanningresult.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.SecurityScanningResult.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(securityscanningresult.FieldID) +// }), +// ). +// Exec(ctx) +func (u *SecurityScanningResultUpsertOne) UpdateNewValues() *SecurityScanningResultUpsertOne { + 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(securityscanningresult.FieldID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.SecurityScanningResult.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *SecurityScanningResultUpsertOne) Ignore() *SecurityScanningResultUpsertOne { + 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 *SecurityScanningResultUpsertOne) DoNothing() *SecurityScanningResultUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the SecurityScanningResultCreate.OnConflict +// documentation for more info. +func (u *SecurityScanningResultUpsertOne) Update(set func(*SecurityScanningResultUpsert)) *SecurityScanningResultUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&SecurityScanningResultUpsert{UpdateSet: update}) + })) + return u +} + +// SetSecurityScanningID sets the "security_scanning_id" field. +func (u *SecurityScanningResultUpsertOne) SetSecurityScanningID(v uuid.UUID) *SecurityScanningResultUpsertOne { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.SetSecurityScanningID(v) + }) +} + +// UpdateSecurityScanningID sets the "security_scanning_id" field to the value that was provided on create. +func (u *SecurityScanningResultUpsertOne) UpdateSecurityScanningID() *SecurityScanningResultUpsertOne { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.UpdateSecurityScanningID() + }) +} + +// SetCheckID sets the "check_id" field. +func (u *SecurityScanningResultUpsertOne) SetCheckID(v string) *SecurityScanningResultUpsertOne { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.SetCheckID(v) + }) +} + +// UpdateCheckID sets the "check_id" field to the value that was provided on create. +func (u *SecurityScanningResultUpsertOne) UpdateCheckID() *SecurityScanningResultUpsertOne { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.UpdateCheckID() + }) +} + +// SetEngineKind sets the "engine_kind" field. +func (u *SecurityScanningResultUpsertOne) SetEngineKind(v string) *SecurityScanningResultUpsertOne { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.SetEngineKind(v) + }) +} + +// UpdateEngineKind sets the "engine_kind" field to the value that was provided on create. +func (u *SecurityScanningResultUpsertOne) UpdateEngineKind() *SecurityScanningResultUpsertOne { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.UpdateEngineKind() + }) +} + +// SetLines sets the "lines" field. +func (u *SecurityScanningResultUpsertOne) SetLines(v string) *SecurityScanningResultUpsertOne { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.SetLines(v) + }) +} + +// UpdateLines sets the "lines" field to the value that was provided on create. +func (u *SecurityScanningResultUpsertOne) UpdateLines() *SecurityScanningResultUpsertOne { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.UpdateLines() + }) +} + +// SetPath sets the "path" field. +func (u *SecurityScanningResultUpsertOne) SetPath(v string) *SecurityScanningResultUpsertOne { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.SetPath(v) + }) +} + +// UpdatePath sets the "path" field to the value that was provided on create. +func (u *SecurityScanningResultUpsertOne) UpdatePath() *SecurityScanningResultUpsertOne { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.UpdatePath() + }) +} + +// SetMessage sets the "message" field. +func (u *SecurityScanningResultUpsertOne) SetMessage(v string) *SecurityScanningResultUpsertOne { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.SetMessage(v) + }) +} + +// UpdateMessage sets the "message" field to the value that was provided on create. +func (u *SecurityScanningResultUpsertOne) UpdateMessage() *SecurityScanningResultUpsertOne { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.UpdateMessage() + }) +} + +// SetMessageZh sets the "message_zh" field. +func (u *SecurityScanningResultUpsertOne) SetMessageZh(v string) *SecurityScanningResultUpsertOne { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.SetMessageZh(v) + }) +} + +// UpdateMessageZh sets the "message_zh" field to the value that was provided on create. +func (u *SecurityScanningResultUpsertOne) UpdateMessageZh() *SecurityScanningResultUpsertOne { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.UpdateMessageZh() + }) +} + +// SetSeverity sets the "severity" field. +func (u *SecurityScanningResultUpsertOne) SetSeverity(v string) *SecurityScanningResultUpsertOne { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.SetSeverity(v) + }) +} + +// UpdateSeverity sets the "severity" field to the value that was provided on create. +func (u *SecurityScanningResultUpsertOne) UpdateSeverity() *SecurityScanningResultUpsertOne { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.UpdateSeverity() + }) +} + +// SetAbstractEn sets the "abstract_en" field. +func (u *SecurityScanningResultUpsertOne) SetAbstractEn(v string) *SecurityScanningResultUpsertOne { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.SetAbstractEn(v) + }) +} + +// UpdateAbstractEn sets the "abstract_en" field to the value that was provided on create. +func (u *SecurityScanningResultUpsertOne) UpdateAbstractEn() *SecurityScanningResultUpsertOne { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.UpdateAbstractEn() + }) +} + +// SetAbstractZh sets the "abstract_zh" field. +func (u *SecurityScanningResultUpsertOne) SetAbstractZh(v string) *SecurityScanningResultUpsertOne { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.SetAbstractZh(v) + }) +} + +// UpdateAbstractZh sets the "abstract_zh" field to the value that was provided on create. +func (u *SecurityScanningResultUpsertOne) UpdateAbstractZh() *SecurityScanningResultUpsertOne { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.UpdateAbstractZh() + }) +} + +// SetCategoryEn sets the "category_en" field. +func (u *SecurityScanningResultUpsertOne) SetCategoryEn(v string) *SecurityScanningResultUpsertOne { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.SetCategoryEn(v) + }) +} + +// UpdateCategoryEn sets the "category_en" field to the value that was provided on create. +func (u *SecurityScanningResultUpsertOne) UpdateCategoryEn() *SecurityScanningResultUpsertOne { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.UpdateCategoryEn() + }) +} + +// SetCategoryZh sets the "category_zh" field. +func (u *SecurityScanningResultUpsertOne) SetCategoryZh(v string) *SecurityScanningResultUpsertOne { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.SetCategoryZh(v) + }) +} + +// UpdateCategoryZh sets the "category_zh" field to the value that was provided on create. +func (u *SecurityScanningResultUpsertOne) UpdateCategoryZh() *SecurityScanningResultUpsertOne { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.UpdateCategoryZh() + }) +} + +// SetConfidence sets the "confidence" field. +func (u *SecurityScanningResultUpsertOne) SetConfidence(v string) *SecurityScanningResultUpsertOne { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.SetConfidence(v) + }) +} + +// UpdateConfidence sets the "confidence" field to the value that was provided on create. +func (u *SecurityScanningResultUpsertOne) UpdateConfidence() *SecurityScanningResultUpsertOne { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.UpdateConfidence() + }) +} + +// SetCwe sets the "cwe" field. +func (u *SecurityScanningResultUpsertOne) SetCwe(v []interface{}) *SecurityScanningResultUpsertOne { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.SetCwe(v) + }) +} + +// UpdateCwe sets the "cwe" field to the value that was provided on create. +func (u *SecurityScanningResultUpsertOne) UpdateCwe() *SecurityScanningResultUpsertOne { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.UpdateCwe() + }) +} + +// SetImpact sets the "impact" field. +func (u *SecurityScanningResultUpsertOne) SetImpact(v string) *SecurityScanningResultUpsertOne { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.SetImpact(v) + }) +} + +// UpdateImpact sets the "impact" field to the value that was provided on create. +func (u *SecurityScanningResultUpsertOne) UpdateImpact() *SecurityScanningResultUpsertOne { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.UpdateImpact() + }) +} + +// SetOwasp sets the "owasp" field. +func (u *SecurityScanningResultUpsertOne) SetOwasp(v []interface{}) *SecurityScanningResultUpsertOne { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.SetOwasp(v) + }) +} + +// UpdateOwasp sets the "owasp" field to the value that was provided on create. +func (u *SecurityScanningResultUpsertOne) UpdateOwasp() *SecurityScanningResultUpsertOne { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.UpdateOwasp() + }) +} + +// SetStartPosition sets the "start_position" field. +func (u *SecurityScanningResultUpsertOne) SetStartPosition(v *types.Position) *SecurityScanningResultUpsertOne { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.SetStartPosition(v) + }) +} + +// UpdateStartPosition sets the "start_position" field to the value that was provided on create. +func (u *SecurityScanningResultUpsertOne) UpdateStartPosition() *SecurityScanningResultUpsertOne { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.UpdateStartPosition() + }) +} + +// SetEndPosition sets the "end_position" field. +func (u *SecurityScanningResultUpsertOne) SetEndPosition(v *types.Position) *SecurityScanningResultUpsertOne { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.SetEndPosition(v) + }) +} + +// UpdateEndPosition sets the "end_position" field to the value that was provided on create. +func (u *SecurityScanningResultUpsertOne) UpdateEndPosition() *SecurityScanningResultUpsertOne { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.UpdateEndPosition() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *SecurityScanningResultUpsertOne) SetCreatedAt(v time.Time) *SecurityScanningResultUpsertOne { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *SecurityScanningResultUpsertOne) UpdateCreatedAt() *SecurityScanningResultUpsertOne { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.UpdateCreatedAt() + }) +} + +// Exec executes the query. +func (u *SecurityScanningResultUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for SecurityScanningResultCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *SecurityScanningResultUpsertOne) 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 *SecurityScanningResultUpsertOne) 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: SecurityScanningResultUpsertOne.ID is not supported by MySQL driver. Use SecurityScanningResultUpsertOne.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 *SecurityScanningResultUpsertOne) IDX(ctx context.Context) uuid.UUID { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// SecurityScanningResultCreateBulk is the builder for creating many SecurityScanningResult entities in bulk. +type SecurityScanningResultCreateBulk struct { + config + err error + builders []*SecurityScanningResultCreate + conflict []sql.ConflictOption +} + +// Save creates the SecurityScanningResult entities in the database. +func (ssrcb *SecurityScanningResultCreateBulk) Save(ctx context.Context) ([]*SecurityScanningResult, error) { + if ssrcb.err != nil { + return nil, ssrcb.err + } + specs := make([]*sqlgraph.CreateSpec, len(ssrcb.builders)) + nodes := make([]*SecurityScanningResult, len(ssrcb.builders)) + mutators := make([]Mutator, len(ssrcb.builders)) + for i := range ssrcb.builders { + func(i int, root context.Context) { + builder := ssrcb.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*SecurityScanningResultMutation) + 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, ssrcb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = ssrcb.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, ssrcb.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, ssrcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (ssrcb *SecurityScanningResultCreateBulk) SaveX(ctx context.Context) []*SecurityScanningResult { + v, err := ssrcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (ssrcb *SecurityScanningResultCreateBulk) Exec(ctx context.Context) error { + _, err := ssrcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ssrcb *SecurityScanningResultCreateBulk) ExecX(ctx context.Context) { + if err := ssrcb.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.SecurityScanningResult.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.SecurityScanningResultUpsert) { +// SetSecurityScanningID(v+v). +// }). +// Exec(ctx) +func (ssrcb *SecurityScanningResultCreateBulk) OnConflict(opts ...sql.ConflictOption) *SecurityScanningResultUpsertBulk { + ssrcb.conflict = opts + return &SecurityScanningResultUpsertBulk{ + create: ssrcb, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.SecurityScanningResult.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (ssrcb *SecurityScanningResultCreateBulk) OnConflictColumns(columns ...string) *SecurityScanningResultUpsertBulk { + ssrcb.conflict = append(ssrcb.conflict, sql.ConflictColumns(columns...)) + return &SecurityScanningResultUpsertBulk{ + create: ssrcb, + } +} + +// SecurityScanningResultUpsertBulk is the builder for "upsert"-ing +// a bulk of SecurityScanningResult nodes. +type SecurityScanningResultUpsertBulk struct { + create *SecurityScanningResultCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.SecurityScanningResult.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(securityscanningresult.FieldID) +// }), +// ). +// Exec(ctx) +func (u *SecurityScanningResultUpsertBulk) UpdateNewValues() *SecurityScanningResultUpsertBulk { + 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(securityscanningresult.FieldID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.SecurityScanningResult.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *SecurityScanningResultUpsertBulk) Ignore() *SecurityScanningResultUpsertBulk { + 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 *SecurityScanningResultUpsertBulk) DoNothing() *SecurityScanningResultUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the SecurityScanningResultCreateBulk.OnConflict +// documentation for more info. +func (u *SecurityScanningResultUpsertBulk) Update(set func(*SecurityScanningResultUpsert)) *SecurityScanningResultUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&SecurityScanningResultUpsert{UpdateSet: update}) + })) + return u +} + +// SetSecurityScanningID sets the "security_scanning_id" field. +func (u *SecurityScanningResultUpsertBulk) SetSecurityScanningID(v uuid.UUID) *SecurityScanningResultUpsertBulk { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.SetSecurityScanningID(v) + }) +} + +// UpdateSecurityScanningID sets the "security_scanning_id" field to the value that was provided on create. +func (u *SecurityScanningResultUpsertBulk) UpdateSecurityScanningID() *SecurityScanningResultUpsertBulk { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.UpdateSecurityScanningID() + }) +} + +// SetCheckID sets the "check_id" field. +func (u *SecurityScanningResultUpsertBulk) SetCheckID(v string) *SecurityScanningResultUpsertBulk { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.SetCheckID(v) + }) +} + +// UpdateCheckID sets the "check_id" field to the value that was provided on create. +func (u *SecurityScanningResultUpsertBulk) UpdateCheckID() *SecurityScanningResultUpsertBulk { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.UpdateCheckID() + }) +} + +// SetEngineKind sets the "engine_kind" field. +func (u *SecurityScanningResultUpsertBulk) SetEngineKind(v string) *SecurityScanningResultUpsertBulk { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.SetEngineKind(v) + }) +} + +// UpdateEngineKind sets the "engine_kind" field to the value that was provided on create. +func (u *SecurityScanningResultUpsertBulk) UpdateEngineKind() *SecurityScanningResultUpsertBulk { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.UpdateEngineKind() + }) +} + +// SetLines sets the "lines" field. +func (u *SecurityScanningResultUpsertBulk) SetLines(v string) *SecurityScanningResultUpsertBulk { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.SetLines(v) + }) +} + +// UpdateLines sets the "lines" field to the value that was provided on create. +func (u *SecurityScanningResultUpsertBulk) UpdateLines() *SecurityScanningResultUpsertBulk { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.UpdateLines() + }) +} + +// SetPath sets the "path" field. +func (u *SecurityScanningResultUpsertBulk) SetPath(v string) *SecurityScanningResultUpsertBulk { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.SetPath(v) + }) +} + +// UpdatePath sets the "path" field to the value that was provided on create. +func (u *SecurityScanningResultUpsertBulk) UpdatePath() *SecurityScanningResultUpsertBulk { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.UpdatePath() + }) +} + +// SetMessage sets the "message" field. +func (u *SecurityScanningResultUpsertBulk) SetMessage(v string) *SecurityScanningResultUpsertBulk { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.SetMessage(v) + }) +} + +// UpdateMessage sets the "message" field to the value that was provided on create. +func (u *SecurityScanningResultUpsertBulk) UpdateMessage() *SecurityScanningResultUpsertBulk { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.UpdateMessage() + }) +} + +// SetMessageZh sets the "message_zh" field. +func (u *SecurityScanningResultUpsertBulk) SetMessageZh(v string) *SecurityScanningResultUpsertBulk { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.SetMessageZh(v) + }) +} + +// UpdateMessageZh sets the "message_zh" field to the value that was provided on create. +func (u *SecurityScanningResultUpsertBulk) UpdateMessageZh() *SecurityScanningResultUpsertBulk { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.UpdateMessageZh() + }) +} + +// SetSeverity sets the "severity" field. +func (u *SecurityScanningResultUpsertBulk) SetSeverity(v string) *SecurityScanningResultUpsertBulk { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.SetSeverity(v) + }) +} + +// UpdateSeverity sets the "severity" field to the value that was provided on create. +func (u *SecurityScanningResultUpsertBulk) UpdateSeverity() *SecurityScanningResultUpsertBulk { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.UpdateSeverity() + }) +} + +// SetAbstractEn sets the "abstract_en" field. +func (u *SecurityScanningResultUpsertBulk) SetAbstractEn(v string) *SecurityScanningResultUpsertBulk { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.SetAbstractEn(v) + }) +} + +// UpdateAbstractEn sets the "abstract_en" field to the value that was provided on create. +func (u *SecurityScanningResultUpsertBulk) UpdateAbstractEn() *SecurityScanningResultUpsertBulk { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.UpdateAbstractEn() + }) +} + +// SetAbstractZh sets the "abstract_zh" field. +func (u *SecurityScanningResultUpsertBulk) SetAbstractZh(v string) *SecurityScanningResultUpsertBulk { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.SetAbstractZh(v) + }) +} + +// UpdateAbstractZh sets the "abstract_zh" field to the value that was provided on create. +func (u *SecurityScanningResultUpsertBulk) UpdateAbstractZh() *SecurityScanningResultUpsertBulk { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.UpdateAbstractZh() + }) +} + +// SetCategoryEn sets the "category_en" field. +func (u *SecurityScanningResultUpsertBulk) SetCategoryEn(v string) *SecurityScanningResultUpsertBulk { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.SetCategoryEn(v) + }) +} + +// UpdateCategoryEn sets the "category_en" field to the value that was provided on create. +func (u *SecurityScanningResultUpsertBulk) UpdateCategoryEn() *SecurityScanningResultUpsertBulk { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.UpdateCategoryEn() + }) +} + +// SetCategoryZh sets the "category_zh" field. +func (u *SecurityScanningResultUpsertBulk) SetCategoryZh(v string) *SecurityScanningResultUpsertBulk { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.SetCategoryZh(v) + }) +} + +// UpdateCategoryZh sets the "category_zh" field to the value that was provided on create. +func (u *SecurityScanningResultUpsertBulk) UpdateCategoryZh() *SecurityScanningResultUpsertBulk { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.UpdateCategoryZh() + }) +} + +// SetConfidence sets the "confidence" field. +func (u *SecurityScanningResultUpsertBulk) SetConfidence(v string) *SecurityScanningResultUpsertBulk { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.SetConfidence(v) + }) +} + +// UpdateConfidence sets the "confidence" field to the value that was provided on create. +func (u *SecurityScanningResultUpsertBulk) UpdateConfidence() *SecurityScanningResultUpsertBulk { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.UpdateConfidence() + }) +} + +// SetCwe sets the "cwe" field. +func (u *SecurityScanningResultUpsertBulk) SetCwe(v []interface{}) *SecurityScanningResultUpsertBulk { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.SetCwe(v) + }) +} + +// UpdateCwe sets the "cwe" field to the value that was provided on create. +func (u *SecurityScanningResultUpsertBulk) UpdateCwe() *SecurityScanningResultUpsertBulk { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.UpdateCwe() + }) +} + +// SetImpact sets the "impact" field. +func (u *SecurityScanningResultUpsertBulk) SetImpact(v string) *SecurityScanningResultUpsertBulk { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.SetImpact(v) + }) +} + +// UpdateImpact sets the "impact" field to the value that was provided on create. +func (u *SecurityScanningResultUpsertBulk) UpdateImpact() *SecurityScanningResultUpsertBulk { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.UpdateImpact() + }) +} + +// SetOwasp sets the "owasp" field. +func (u *SecurityScanningResultUpsertBulk) SetOwasp(v []interface{}) *SecurityScanningResultUpsertBulk { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.SetOwasp(v) + }) +} + +// UpdateOwasp sets the "owasp" field to the value that was provided on create. +func (u *SecurityScanningResultUpsertBulk) UpdateOwasp() *SecurityScanningResultUpsertBulk { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.UpdateOwasp() + }) +} + +// SetStartPosition sets the "start_position" field. +func (u *SecurityScanningResultUpsertBulk) SetStartPosition(v *types.Position) *SecurityScanningResultUpsertBulk { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.SetStartPosition(v) + }) +} + +// UpdateStartPosition sets the "start_position" field to the value that was provided on create. +func (u *SecurityScanningResultUpsertBulk) UpdateStartPosition() *SecurityScanningResultUpsertBulk { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.UpdateStartPosition() + }) +} + +// SetEndPosition sets the "end_position" field. +func (u *SecurityScanningResultUpsertBulk) SetEndPosition(v *types.Position) *SecurityScanningResultUpsertBulk { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.SetEndPosition(v) + }) +} + +// UpdateEndPosition sets the "end_position" field to the value that was provided on create. +func (u *SecurityScanningResultUpsertBulk) UpdateEndPosition() *SecurityScanningResultUpsertBulk { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.UpdateEndPosition() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *SecurityScanningResultUpsertBulk) SetCreatedAt(v time.Time) *SecurityScanningResultUpsertBulk { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *SecurityScanningResultUpsertBulk) UpdateCreatedAt() *SecurityScanningResultUpsertBulk { + return u.Update(func(s *SecurityScanningResultUpsert) { + s.UpdateCreatedAt() + }) +} + +// Exec executes the query. +func (u *SecurityScanningResultUpsertBulk) 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 SecurityScanningResultCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for SecurityScanningResultCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *SecurityScanningResultUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/securityscanningresult_delete.go b/backend/db/securityscanningresult_delete.go new file mode 100644 index 0000000..e262091 --- /dev/null +++ b/backend/db/securityscanningresult_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/securityscanningresult" +) + +// SecurityScanningResultDelete is the builder for deleting a SecurityScanningResult entity. +type SecurityScanningResultDelete struct { + config + hooks []Hook + mutation *SecurityScanningResultMutation +} + +// Where appends a list predicates to the SecurityScanningResultDelete builder. +func (ssrd *SecurityScanningResultDelete) Where(ps ...predicate.SecurityScanningResult) *SecurityScanningResultDelete { + ssrd.mutation.Where(ps...) + return ssrd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (ssrd *SecurityScanningResultDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, ssrd.sqlExec, ssrd.mutation, ssrd.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (ssrd *SecurityScanningResultDelete) ExecX(ctx context.Context) int { + n, err := ssrd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (ssrd *SecurityScanningResultDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(securityscanningresult.Table, sqlgraph.NewFieldSpec(securityscanningresult.FieldID, field.TypeUUID)) + if ps := ssrd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, ssrd.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + ssrd.mutation.done = true + return affected, err +} + +// SecurityScanningResultDeleteOne is the builder for deleting a single SecurityScanningResult entity. +type SecurityScanningResultDeleteOne struct { + ssrd *SecurityScanningResultDelete +} + +// Where appends a list predicates to the SecurityScanningResultDelete builder. +func (ssrdo *SecurityScanningResultDeleteOne) Where(ps ...predicate.SecurityScanningResult) *SecurityScanningResultDeleteOne { + ssrdo.ssrd.mutation.Where(ps...) + return ssrdo +} + +// Exec executes the deletion query. +func (ssrdo *SecurityScanningResultDeleteOne) Exec(ctx context.Context) error { + n, err := ssrdo.ssrd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{securityscanningresult.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (ssrdo *SecurityScanningResultDeleteOne) ExecX(ctx context.Context) { + if err := ssrdo.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/securityscanningresult_query.go b/backend/db/securityscanningresult_query.go new file mode 100644 index 0000000..46b9780 --- /dev/null +++ b/backend/db/securityscanningresult_query.go @@ -0,0 +1,657 @@ +// 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/securityscanning" + "github.com/chaitin/MonkeyCode/backend/db/securityscanningresult" + "github.com/google/uuid" +) + +// SecurityScanningResultQuery is the builder for querying SecurityScanningResult entities. +type SecurityScanningResultQuery struct { + config + ctx *QueryContext + order []securityscanningresult.OrderOption + inters []Interceptor + predicates []predicate.SecurityScanningResult + withSecurityScanning *SecurityScanningQuery + 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 SecurityScanningResultQuery builder. +func (ssrq *SecurityScanningResultQuery) Where(ps ...predicate.SecurityScanningResult) *SecurityScanningResultQuery { + ssrq.predicates = append(ssrq.predicates, ps...) + return ssrq +} + +// Limit the number of records to be returned by this query. +func (ssrq *SecurityScanningResultQuery) Limit(limit int) *SecurityScanningResultQuery { + ssrq.ctx.Limit = &limit + return ssrq +} + +// Offset to start from. +func (ssrq *SecurityScanningResultQuery) Offset(offset int) *SecurityScanningResultQuery { + ssrq.ctx.Offset = &offset + return ssrq +} + +// 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 (ssrq *SecurityScanningResultQuery) Unique(unique bool) *SecurityScanningResultQuery { + ssrq.ctx.Unique = &unique + return ssrq +} + +// Order specifies how the records should be ordered. +func (ssrq *SecurityScanningResultQuery) Order(o ...securityscanningresult.OrderOption) *SecurityScanningResultQuery { + ssrq.order = append(ssrq.order, o...) + return ssrq +} + +// QuerySecurityScanning chains the current query on the "security_scanning" edge. +func (ssrq *SecurityScanningResultQuery) QuerySecurityScanning() *SecurityScanningQuery { + query := (&SecurityScanningClient{config: ssrq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := ssrq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := ssrq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(securityscanningresult.Table, securityscanningresult.FieldID, selector), + sqlgraph.To(securityscanning.Table, securityscanning.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, securityscanningresult.SecurityScanningTable, securityscanningresult.SecurityScanningColumn), + ) + fromU = sqlgraph.SetNeighbors(ssrq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first SecurityScanningResult entity from the query. +// Returns a *NotFoundError when no SecurityScanningResult was found. +func (ssrq *SecurityScanningResultQuery) First(ctx context.Context) (*SecurityScanningResult, error) { + nodes, err := ssrq.Limit(1).All(setContextOp(ctx, ssrq.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{securityscanningresult.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (ssrq *SecurityScanningResultQuery) FirstX(ctx context.Context) *SecurityScanningResult { + node, err := ssrq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first SecurityScanningResult ID from the query. +// Returns a *NotFoundError when no SecurityScanningResult ID was found. +func (ssrq *SecurityScanningResultQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = ssrq.Limit(1).IDs(setContextOp(ctx, ssrq.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{securityscanningresult.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (ssrq *SecurityScanningResultQuery) FirstIDX(ctx context.Context) uuid.UUID { + id, err := ssrq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single SecurityScanningResult entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one SecurityScanningResult entity is found. +// Returns a *NotFoundError when no SecurityScanningResult entities are found. +func (ssrq *SecurityScanningResultQuery) Only(ctx context.Context) (*SecurityScanningResult, error) { + nodes, err := ssrq.Limit(2).All(setContextOp(ctx, ssrq.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{securityscanningresult.Label} + default: + return nil, &NotSingularError{securityscanningresult.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (ssrq *SecurityScanningResultQuery) OnlyX(ctx context.Context) *SecurityScanningResult { + node, err := ssrq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only SecurityScanningResult ID in the query. +// Returns a *NotSingularError when more than one SecurityScanningResult ID is found. +// Returns a *NotFoundError when no entities are found. +func (ssrq *SecurityScanningResultQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = ssrq.Limit(2).IDs(setContextOp(ctx, ssrq.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{securityscanningresult.Label} + default: + err = &NotSingularError{securityscanningresult.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (ssrq *SecurityScanningResultQuery) OnlyIDX(ctx context.Context) uuid.UUID { + id, err := ssrq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of SecurityScanningResults. +func (ssrq *SecurityScanningResultQuery) All(ctx context.Context) ([]*SecurityScanningResult, error) { + ctx = setContextOp(ctx, ssrq.ctx, ent.OpQueryAll) + if err := ssrq.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*SecurityScanningResult, *SecurityScanningResultQuery]() + return withInterceptors[[]*SecurityScanningResult](ctx, ssrq, qr, ssrq.inters) +} + +// AllX is like All, but panics if an error occurs. +func (ssrq *SecurityScanningResultQuery) AllX(ctx context.Context) []*SecurityScanningResult { + nodes, err := ssrq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of SecurityScanningResult IDs. +func (ssrq *SecurityScanningResultQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) { + if ssrq.ctx.Unique == nil && ssrq.path != nil { + ssrq.Unique(true) + } + ctx = setContextOp(ctx, ssrq.ctx, ent.OpQueryIDs) + if err = ssrq.Select(securityscanningresult.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (ssrq *SecurityScanningResultQuery) IDsX(ctx context.Context) []uuid.UUID { + ids, err := ssrq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (ssrq *SecurityScanningResultQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, ssrq.ctx, ent.OpQueryCount) + if err := ssrq.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, ssrq, querierCount[*SecurityScanningResultQuery](), ssrq.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (ssrq *SecurityScanningResultQuery) CountX(ctx context.Context) int { + count, err := ssrq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (ssrq *SecurityScanningResultQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, ssrq.ctx, ent.OpQueryExist) + switch _, err := ssrq.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 (ssrq *SecurityScanningResultQuery) ExistX(ctx context.Context) bool { + exist, err := ssrq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the SecurityScanningResultQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (ssrq *SecurityScanningResultQuery) Clone() *SecurityScanningResultQuery { + if ssrq == nil { + return nil + } + return &SecurityScanningResultQuery{ + config: ssrq.config, + ctx: ssrq.ctx.Clone(), + order: append([]securityscanningresult.OrderOption{}, ssrq.order...), + inters: append([]Interceptor{}, ssrq.inters...), + predicates: append([]predicate.SecurityScanningResult{}, ssrq.predicates...), + withSecurityScanning: ssrq.withSecurityScanning.Clone(), + // clone intermediate query. + sql: ssrq.sql.Clone(), + path: ssrq.path, + modifiers: append([]func(*sql.Selector){}, ssrq.modifiers...), + } +} + +// WithSecurityScanning tells the query-builder to eager-load the nodes that are connected to +// the "security_scanning" edge. The optional arguments are used to configure the query builder of the edge. +func (ssrq *SecurityScanningResultQuery) WithSecurityScanning(opts ...func(*SecurityScanningQuery)) *SecurityScanningResultQuery { + query := (&SecurityScanningClient{config: ssrq.config}).Query() + for _, opt := range opts { + opt(query) + } + ssrq.withSecurityScanning = query + return ssrq +} + +// 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 { +// SecurityScanningID uuid.UUID `json:"security_scanning_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.SecurityScanningResult.Query(). +// GroupBy(securityscanningresult.FieldSecurityScanningID). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (ssrq *SecurityScanningResultQuery) GroupBy(field string, fields ...string) *SecurityScanningResultGroupBy { + ssrq.ctx.Fields = append([]string{field}, fields...) + grbuild := &SecurityScanningResultGroupBy{build: ssrq} + grbuild.flds = &ssrq.ctx.Fields + grbuild.label = securityscanningresult.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 { +// SecurityScanningID uuid.UUID `json:"security_scanning_id,omitempty"` +// } +// +// client.SecurityScanningResult.Query(). +// Select(securityscanningresult.FieldSecurityScanningID). +// Scan(ctx, &v) +func (ssrq *SecurityScanningResultQuery) Select(fields ...string) *SecurityScanningResultSelect { + ssrq.ctx.Fields = append(ssrq.ctx.Fields, fields...) + sbuild := &SecurityScanningResultSelect{SecurityScanningResultQuery: ssrq} + sbuild.label = securityscanningresult.Label + sbuild.flds, sbuild.scan = &ssrq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a SecurityScanningResultSelect configured with the given aggregations. +func (ssrq *SecurityScanningResultQuery) Aggregate(fns ...AggregateFunc) *SecurityScanningResultSelect { + return ssrq.Select().Aggregate(fns...) +} + +func (ssrq *SecurityScanningResultQuery) prepareQuery(ctx context.Context) error { + for _, inter := range ssrq.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, ssrq); err != nil { + return err + } + } + } + for _, f := range ssrq.ctx.Fields { + if !securityscanningresult.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + } + if ssrq.path != nil { + prev, err := ssrq.path(ctx) + if err != nil { + return err + } + ssrq.sql = prev + } + return nil +} + +func (ssrq *SecurityScanningResultQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*SecurityScanningResult, error) { + var ( + nodes = []*SecurityScanningResult{} + _spec = ssrq.querySpec() + loadedTypes = [1]bool{ + ssrq.withSecurityScanning != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*SecurityScanningResult).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &SecurityScanningResult{config: ssrq.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(ssrq.modifiers) > 0 { + _spec.Modifiers = ssrq.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, ssrq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := ssrq.withSecurityScanning; query != nil { + if err := ssrq.loadSecurityScanning(ctx, query, nodes, nil, + func(n *SecurityScanningResult, e *SecurityScanning) { n.Edges.SecurityScanning = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (ssrq *SecurityScanningResultQuery) loadSecurityScanning(ctx context.Context, query *SecurityScanningQuery, nodes []*SecurityScanningResult, init func(*SecurityScanningResult), assign func(*SecurityScanningResult, *SecurityScanning)) error { + ids := make([]uuid.UUID, 0, len(nodes)) + nodeids := make(map[uuid.UUID][]*SecurityScanningResult) + for i := range nodes { + fk := nodes[i].SecurityScanningID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(securityscanning.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 "security_scanning_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (ssrq *SecurityScanningResultQuery) sqlCount(ctx context.Context) (int, error) { + _spec := ssrq.querySpec() + if len(ssrq.modifiers) > 0 { + _spec.Modifiers = ssrq.modifiers + } + _spec.Node.Columns = ssrq.ctx.Fields + if len(ssrq.ctx.Fields) > 0 { + _spec.Unique = ssrq.ctx.Unique != nil && *ssrq.ctx.Unique + } + return sqlgraph.CountNodes(ctx, ssrq.driver, _spec) +} + +func (ssrq *SecurityScanningResultQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(securityscanningresult.Table, securityscanningresult.Columns, sqlgraph.NewFieldSpec(securityscanningresult.FieldID, field.TypeUUID)) + _spec.From = ssrq.sql + if unique := ssrq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if ssrq.path != nil { + _spec.Unique = true + } + if fields := ssrq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, securityscanningresult.FieldID) + for i := range fields { + if fields[i] != securityscanningresult.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if ssrq.withSecurityScanning != nil { + _spec.Node.AddColumnOnce(securityscanningresult.FieldSecurityScanningID) + } + } + if ps := ssrq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := ssrq.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := ssrq.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := ssrq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (ssrq *SecurityScanningResultQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(ssrq.driver.Dialect()) + t1 := builder.Table(securityscanningresult.Table) + columns := ssrq.ctx.Fields + if len(columns) == 0 { + columns = securityscanningresult.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if ssrq.sql != nil { + selector = ssrq.sql + selector.Select(selector.Columns(columns...)...) + } + if ssrq.ctx.Unique != nil && *ssrq.ctx.Unique { + selector.Distinct() + } + for _, m := range ssrq.modifiers { + m(selector) + } + for _, p := range ssrq.predicates { + p(selector) + } + for _, p := range ssrq.order { + p(selector) + } + if offset := ssrq.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 := ssrq.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 (ssrq *SecurityScanningResultQuery) ForUpdate(opts ...sql.LockOption) *SecurityScanningResultQuery { + if ssrq.driver.Dialect() == dialect.Postgres { + ssrq.Unique(false) + } + ssrq.modifiers = append(ssrq.modifiers, func(s *sql.Selector) { + s.ForUpdate(opts...) + }) + return ssrq +} + +// 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 (ssrq *SecurityScanningResultQuery) ForShare(opts ...sql.LockOption) *SecurityScanningResultQuery { + if ssrq.driver.Dialect() == dialect.Postgres { + ssrq.Unique(false) + } + ssrq.modifiers = append(ssrq.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return ssrq +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (ssrq *SecurityScanningResultQuery) Modify(modifiers ...func(s *sql.Selector)) *SecurityScanningResultSelect { + ssrq.modifiers = append(ssrq.modifiers, modifiers...) + return ssrq.Select() +} + +// SecurityScanningResultGroupBy is the group-by builder for SecurityScanningResult entities. +type SecurityScanningResultGroupBy struct { + selector + build *SecurityScanningResultQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (ssrgb *SecurityScanningResultGroupBy) Aggregate(fns ...AggregateFunc) *SecurityScanningResultGroupBy { + ssrgb.fns = append(ssrgb.fns, fns...) + return ssrgb +} + +// Scan applies the selector query and scans the result into the given value. +func (ssrgb *SecurityScanningResultGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, ssrgb.build.ctx, ent.OpQueryGroupBy) + if err := ssrgb.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*SecurityScanningResultQuery, *SecurityScanningResultGroupBy](ctx, ssrgb.build, ssrgb, ssrgb.build.inters, v) +} + +func (ssrgb *SecurityScanningResultGroupBy) sqlScan(ctx context.Context, root *SecurityScanningResultQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(ssrgb.fns)) + for _, fn := range ssrgb.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*ssrgb.flds)+len(ssrgb.fns)) + for _, f := range *ssrgb.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*ssrgb.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := ssrgb.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// SecurityScanningResultSelect is the builder for selecting fields of SecurityScanningResult entities. +type SecurityScanningResultSelect struct { + *SecurityScanningResultQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (ssrs *SecurityScanningResultSelect) Aggregate(fns ...AggregateFunc) *SecurityScanningResultSelect { + ssrs.fns = append(ssrs.fns, fns...) + return ssrs +} + +// Scan applies the selector query and scans the result into the given value. +func (ssrs *SecurityScanningResultSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, ssrs.ctx, ent.OpQuerySelect) + if err := ssrs.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*SecurityScanningResultQuery, *SecurityScanningResultSelect](ctx, ssrs.SecurityScanningResultQuery, ssrs, ssrs.inters, v) +} + +func (ssrs *SecurityScanningResultSelect) sqlScan(ctx context.Context, root *SecurityScanningResultQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(ssrs.fns)) + for _, fn := range ssrs.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*ssrs.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 := ssrs.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 (ssrs *SecurityScanningResultSelect) Modify(modifiers ...func(s *sql.Selector)) *SecurityScanningResultSelect { + ssrs.modifiers = append(ssrs.modifiers, modifiers...) + return ssrs +} diff --git a/backend/db/securityscanningresult_update.go b/backend/db/securityscanningresult_update.go new file mode 100644 index 0000000..15b915b --- /dev/null +++ b/backend/db/securityscanningresult_update.go @@ -0,0 +1,918 @@ +// 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/dialect/sql/sqljson" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/securityscanning" + "github.com/chaitin/MonkeyCode/backend/db/securityscanningresult" + "github.com/chaitin/MonkeyCode/backend/ent/types" + "github.com/google/uuid" +) + +// SecurityScanningResultUpdate is the builder for updating SecurityScanningResult entities. +type SecurityScanningResultUpdate struct { + config + hooks []Hook + mutation *SecurityScanningResultMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the SecurityScanningResultUpdate builder. +func (ssru *SecurityScanningResultUpdate) Where(ps ...predicate.SecurityScanningResult) *SecurityScanningResultUpdate { + ssru.mutation.Where(ps...) + return ssru +} + +// SetSecurityScanningID sets the "security_scanning_id" field. +func (ssru *SecurityScanningResultUpdate) SetSecurityScanningID(u uuid.UUID) *SecurityScanningResultUpdate { + ssru.mutation.SetSecurityScanningID(u) + return ssru +} + +// SetNillableSecurityScanningID sets the "security_scanning_id" field if the given value is not nil. +func (ssru *SecurityScanningResultUpdate) SetNillableSecurityScanningID(u *uuid.UUID) *SecurityScanningResultUpdate { + if u != nil { + ssru.SetSecurityScanningID(*u) + } + return ssru +} + +// SetCheckID sets the "check_id" field. +func (ssru *SecurityScanningResultUpdate) SetCheckID(s string) *SecurityScanningResultUpdate { + ssru.mutation.SetCheckID(s) + return ssru +} + +// SetNillableCheckID sets the "check_id" field if the given value is not nil. +func (ssru *SecurityScanningResultUpdate) SetNillableCheckID(s *string) *SecurityScanningResultUpdate { + if s != nil { + ssru.SetCheckID(*s) + } + return ssru +} + +// SetEngineKind sets the "engine_kind" field. +func (ssru *SecurityScanningResultUpdate) SetEngineKind(s string) *SecurityScanningResultUpdate { + ssru.mutation.SetEngineKind(s) + return ssru +} + +// SetNillableEngineKind sets the "engine_kind" field if the given value is not nil. +func (ssru *SecurityScanningResultUpdate) SetNillableEngineKind(s *string) *SecurityScanningResultUpdate { + if s != nil { + ssru.SetEngineKind(*s) + } + return ssru +} + +// SetLines sets the "lines" field. +func (ssru *SecurityScanningResultUpdate) SetLines(s string) *SecurityScanningResultUpdate { + ssru.mutation.SetLines(s) + return ssru +} + +// SetNillableLines sets the "lines" field if the given value is not nil. +func (ssru *SecurityScanningResultUpdate) SetNillableLines(s *string) *SecurityScanningResultUpdate { + if s != nil { + ssru.SetLines(*s) + } + return ssru +} + +// SetPath sets the "path" field. +func (ssru *SecurityScanningResultUpdate) SetPath(s string) *SecurityScanningResultUpdate { + ssru.mutation.SetPath(s) + return ssru +} + +// SetNillablePath sets the "path" field if the given value is not nil. +func (ssru *SecurityScanningResultUpdate) SetNillablePath(s *string) *SecurityScanningResultUpdate { + if s != nil { + ssru.SetPath(*s) + } + return ssru +} + +// SetMessage sets the "message" field. +func (ssru *SecurityScanningResultUpdate) SetMessage(s string) *SecurityScanningResultUpdate { + ssru.mutation.SetMessage(s) + return ssru +} + +// SetNillableMessage sets the "message" field if the given value is not nil. +func (ssru *SecurityScanningResultUpdate) SetNillableMessage(s *string) *SecurityScanningResultUpdate { + if s != nil { + ssru.SetMessage(*s) + } + return ssru +} + +// SetMessageZh sets the "message_zh" field. +func (ssru *SecurityScanningResultUpdate) SetMessageZh(s string) *SecurityScanningResultUpdate { + ssru.mutation.SetMessageZh(s) + return ssru +} + +// SetNillableMessageZh sets the "message_zh" field if the given value is not nil. +func (ssru *SecurityScanningResultUpdate) SetNillableMessageZh(s *string) *SecurityScanningResultUpdate { + if s != nil { + ssru.SetMessageZh(*s) + } + return ssru +} + +// SetSeverity sets the "severity" field. +func (ssru *SecurityScanningResultUpdate) SetSeverity(s string) *SecurityScanningResultUpdate { + ssru.mutation.SetSeverity(s) + return ssru +} + +// SetNillableSeverity sets the "severity" field if the given value is not nil. +func (ssru *SecurityScanningResultUpdate) SetNillableSeverity(s *string) *SecurityScanningResultUpdate { + if s != nil { + ssru.SetSeverity(*s) + } + return ssru +} + +// SetAbstractEn sets the "abstract_en" field. +func (ssru *SecurityScanningResultUpdate) SetAbstractEn(s string) *SecurityScanningResultUpdate { + ssru.mutation.SetAbstractEn(s) + return ssru +} + +// SetNillableAbstractEn sets the "abstract_en" field if the given value is not nil. +func (ssru *SecurityScanningResultUpdate) SetNillableAbstractEn(s *string) *SecurityScanningResultUpdate { + if s != nil { + ssru.SetAbstractEn(*s) + } + return ssru +} + +// SetAbstractZh sets the "abstract_zh" field. +func (ssru *SecurityScanningResultUpdate) SetAbstractZh(s string) *SecurityScanningResultUpdate { + ssru.mutation.SetAbstractZh(s) + return ssru +} + +// SetNillableAbstractZh sets the "abstract_zh" field if the given value is not nil. +func (ssru *SecurityScanningResultUpdate) SetNillableAbstractZh(s *string) *SecurityScanningResultUpdate { + if s != nil { + ssru.SetAbstractZh(*s) + } + return ssru +} + +// SetCategoryEn sets the "category_en" field. +func (ssru *SecurityScanningResultUpdate) SetCategoryEn(s string) *SecurityScanningResultUpdate { + ssru.mutation.SetCategoryEn(s) + return ssru +} + +// SetNillableCategoryEn sets the "category_en" field if the given value is not nil. +func (ssru *SecurityScanningResultUpdate) SetNillableCategoryEn(s *string) *SecurityScanningResultUpdate { + if s != nil { + ssru.SetCategoryEn(*s) + } + return ssru +} + +// SetCategoryZh sets the "category_zh" field. +func (ssru *SecurityScanningResultUpdate) SetCategoryZh(s string) *SecurityScanningResultUpdate { + ssru.mutation.SetCategoryZh(s) + return ssru +} + +// SetNillableCategoryZh sets the "category_zh" field if the given value is not nil. +func (ssru *SecurityScanningResultUpdate) SetNillableCategoryZh(s *string) *SecurityScanningResultUpdate { + if s != nil { + ssru.SetCategoryZh(*s) + } + return ssru +} + +// SetConfidence sets the "confidence" field. +func (ssru *SecurityScanningResultUpdate) SetConfidence(s string) *SecurityScanningResultUpdate { + ssru.mutation.SetConfidence(s) + return ssru +} + +// SetNillableConfidence sets the "confidence" field if the given value is not nil. +func (ssru *SecurityScanningResultUpdate) SetNillableConfidence(s *string) *SecurityScanningResultUpdate { + if s != nil { + ssru.SetConfidence(*s) + } + return ssru +} + +// SetCwe sets the "cwe" field. +func (ssru *SecurityScanningResultUpdate) SetCwe(i []interface{}) *SecurityScanningResultUpdate { + ssru.mutation.SetCwe(i) + return ssru +} + +// AppendCwe appends i to the "cwe" field. +func (ssru *SecurityScanningResultUpdate) AppendCwe(i []interface{}) *SecurityScanningResultUpdate { + ssru.mutation.AppendCwe(i) + return ssru +} + +// SetImpact sets the "impact" field. +func (ssru *SecurityScanningResultUpdate) SetImpact(s string) *SecurityScanningResultUpdate { + ssru.mutation.SetImpact(s) + return ssru +} + +// SetNillableImpact sets the "impact" field if the given value is not nil. +func (ssru *SecurityScanningResultUpdate) SetNillableImpact(s *string) *SecurityScanningResultUpdate { + if s != nil { + ssru.SetImpact(*s) + } + return ssru +} + +// SetOwasp sets the "owasp" field. +func (ssru *SecurityScanningResultUpdate) SetOwasp(i []interface{}) *SecurityScanningResultUpdate { + ssru.mutation.SetOwasp(i) + return ssru +} + +// AppendOwasp appends i to the "owasp" field. +func (ssru *SecurityScanningResultUpdate) AppendOwasp(i []interface{}) *SecurityScanningResultUpdate { + ssru.mutation.AppendOwasp(i) + return ssru +} + +// SetStartPosition sets the "start_position" field. +func (ssru *SecurityScanningResultUpdate) SetStartPosition(t *types.Position) *SecurityScanningResultUpdate { + ssru.mutation.SetStartPosition(t) + return ssru +} + +// SetEndPosition sets the "end_position" field. +func (ssru *SecurityScanningResultUpdate) SetEndPosition(t *types.Position) *SecurityScanningResultUpdate { + ssru.mutation.SetEndPosition(t) + return ssru +} + +// SetCreatedAt sets the "created_at" field. +func (ssru *SecurityScanningResultUpdate) SetCreatedAt(t time.Time) *SecurityScanningResultUpdate { + ssru.mutation.SetCreatedAt(t) + return ssru +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (ssru *SecurityScanningResultUpdate) SetNillableCreatedAt(t *time.Time) *SecurityScanningResultUpdate { + if t != nil { + ssru.SetCreatedAt(*t) + } + return ssru +} + +// SetSecurityScanning sets the "security_scanning" edge to the SecurityScanning entity. +func (ssru *SecurityScanningResultUpdate) SetSecurityScanning(s *SecurityScanning) *SecurityScanningResultUpdate { + return ssru.SetSecurityScanningID(s.ID) +} + +// Mutation returns the SecurityScanningResultMutation object of the builder. +func (ssru *SecurityScanningResultUpdate) Mutation() *SecurityScanningResultMutation { + return ssru.mutation +} + +// ClearSecurityScanning clears the "security_scanning" edge to the SecurityScanning entity. +func (ssru *SecurityScanningResultUpdate) ClearSecurityScanning() *SecurityScanningResultUpdate { + ssru.mutation.ClearSecurityScanning() + return ssru +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (ssru *SecurityScanningResultUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, ssru.sqlSave, ssru.mutation, ssru.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (ssru *SecurityScanningResultUpdate) SaveX(ctx context.Context) int { + affected, err := ssru.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (ssru *SecurityScanningResultUpdate) Exec(ctx context.Context) error { + _, err := ssru.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ssru *SecurityScanningResultUpdate) ExecX(ctx context.Context) { + if err := ssru.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (ssru *SecurityScanningResultUpdate) check() error { + if ssru.mutation.SecurityScanningCleared() && len(ssru.mutation.SecurityScanningIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "SecurityScanningResult.security_scanning"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (ssru *SecurityScanningResultUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *SecurityScanningResultUpdate { + ssru.modifiers = append(ssru.modifiers, modifiers...) + return ssru +} + +func (ssru *SecurityScanningResultUpdate) sqlSave(ctx context.Context) (n int, err error) { + if err := ssru.check(); err != nil { + return n, err + } + _spec := sqlgraph.NewUpdateSpec(securityscanningresult.Table, securityscanningresult.Columns, sqlgraph.NewFieldSpec(securityscanningresult.FieldID, field.TypeUUID)) + if ps := ssru.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := ssru.mutation.CheckID(); ok { + _spec.SetField(securityscanningresult.FieldCheckID, field.TypeString, value) + } + if value, ok := ssru.mutation.EngineKind(); ok { + _spec.SetField(securityscanningresult.FieldEngineKind, field.TypeString, value) + } + if value, ok := ssru.mutation.Lines(); ok { + _spec.SetField(securityscanningresult.FieldLines, field.TypeString, value) + } + if value, ok := ssru.mutation.Path(); ok { + _spec.SetField(securityscanningresult.FieldPath, field.TypeString, value) + } + if value, ok := ssru.mutation.Message(); ok { + _spec.SetField(securityscanningresult.FieldMessage, field.TypeString, value) + } + if value, ok := ssru.mutation.MessageZh(); ok { + _spec.SetField(securityscanningresult.FieldMessageZh, field.TypeString, value) + } + if value, ok := ssru.mutation.Severity(); ok { + _spec.SetField(securityscanningresult.FieldSeverity, field.TypeString, value) + } + if value, ok := ssru.mutation.AbstractEn(); ok { + _spec.SetField(securityscanningresult.FieldAbstractEn, field.TypeString, value) + } + if value, ok := ssru.mutation.AbstractZh(); ok { + _spec.SetField(securityscanningresult.FieldAbstractZh, field.TypeString, value) + } + if value, ok := ssru.mutation.CategoryEn(); ok { + _spec.SetField(securityscanningresult.FieldCategoryEn, field.TypeString, value) + } + if value, ok := ssru.mutation.CategoryZh(); ok { + _spec.SetField(securityscanningresult.FieldCategoryZh, field.TypeString, value) + } + if value, ok := ssru.mutation.Confidence(); ok { + _spec.SetField(securityscanningresult.FieldConfidence, field.TypeString, value) + } + if value, ok := ssru.mutation.Cwe(); ok { + _spec.SetField(securityscanningresult.FieldCwe, field.TypeJSON, value) + } + if value, ok := ssru.mutation.AppendedCwe(); ok { + _spec.AddModifier(func(u *sql.UpdateBuilder) { + sqljson.Append(u, securityscanningresult.FieldCwe, value) + }) + } + if value, ok := ssru.mutation.Impact(); ok { + _spec.SetField(securityscanningresult.FieldImpact, field.TypeString, value) + } + if value, ok := ssru.mutation.Owasp(); ok { + _spec.SetField(securityscanningresult.FieldOwasp, field.TypeJSON, value) + } + if value, ok := ssru.mutation.AppendedOwasp(); ok { + _spec.AddModifier(func(u *sql.UpdateBuilder) { + sqljson.Append(u, securityscanningresult.FieldOwasp, value) + }) + } + if value, ok := ssru.mutation.StartPosition(); ok { + _spec.SetField(securityscanningresult.FieldStartPosition, field.TypeJSON, value) + } + if value, ok := ssru.mutation.EndPosition(); ok { + _spec.SetField(securityscanningresult.FieldEndPosition, field.TypeJSON, value) + } + if value, ok := ssru.mutation.CreatedAt(); ok { + _spec.SetField(securityscanningresult.FieldCreatedAt, field.TypeTime, value) + } + if ssru.mutation.SecurityScanningCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: securityscanningresult.SecurityScanningTable, + Columns: []string{securityscanningresult.SecurityScanningColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(securityscanning.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ssru.mutation.SecurityScanningIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: securityscanningresult.SecurityScanningTable, + Columns: []string{securityscanningresult.SecurityScanningColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(securityscanning.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(ssru.modifiers...) + if n, err = sqlgraph.UpdateNodes(ctx, ssru.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{securityscanningresult.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + ssru.mutation.done = true + return n, nil +} + +// SecurityScanningResultUpdateOne is the builder for updating a single SecurityScanningResult entity. +type SecurityScanningResultUpdateOne struct { + config + fields []string + hooks []Hook + mutation *SecurityScanningResultMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetSecurityScanningID sets the "security_scanning_id" field. +func (ssruo *SecurityScanningResultUpdateOne) SetSecurityScanningID(u uuid.UUID) *SecurityScanningResultUpdateOne { + ssruo.mutation.SetSecurityScanningID(u) + return ssruo +} + +// SetNillableSecurityScanningID sets the "security_scanning_id" field if the given value is not nil. +func (ssruo *SecurityScanningResultUpdateOne) SetNillableSecurityScanningID(u *uuid.UUID) *SecurityScanningResultUpdateOne { + if u != nil { + ssruo.SetSecurityScanningID(*u) + } + return ssruo +} + +// SetCheckID sets the "check_id" field. +func (ssruo *SecurityScanningResultUpdateOne) SetCheckID(s string) *SecurityScanningResultUpdateOne { + ssruo.mutation.SetCheckID(s) + return ssruo +} + +// SetNillableCheckID sets the "check_id" field if the given value is not nil. +func (ssruo *SecurityScanningResultUpdateOne) SetNillableCheckID(s *string) *SecurityScanningResultUpdateOne { + if s != nil { + ssruo.SetCheckID(*s) + } + return ssruo +} + +// SetEngineKind sets the "engine_kind" field. +func (ssruo *SecurityScanningResultUpdateOne) SetEngineKind(s string) *SecurityScanningResultUpdateOne { + ssruo.mutation.SetEngineKind(s) + return ssruo +} + +// SetNillableEngineKind sets the "engine_kind" field if the given value is not nil. +func (ssruo *SecurityScanningResultUpdateOne) SetNillableEngineKind(s *string) *SecurityScanningResultUpdateOne { + if s != nil { + ssruo.SetEngineKind(*s) + } + return ssruo +} + +// SetLines sets the "lines" field. +func (ssruo *SecurityScanningResultUpdateOne) SetLines(s string) *SecurityScanningResultUpdateOne { + ssruo.mutation.SetLines(s) + return ssruo +} + +// SetNillableLines sets the "lines" field if the given value is not nil. +func (ssruo *SecurityScanningResultUpdateOne) SetNillableLines(s *string) *SecurityScanningResultUpdateOne { + if s != nil { + ssruo.SetLines(*s) + } + return ssruo +} + +// SetPath sets the "path" field. +func (ssruo *SecurityScanningResultUpdateOne) SetPath(s string) *SecurityScanningResultUpdateOne { + ssruo.mutation.SetPath(s) + return ssruo +} + +// SetNillablePath sets the "path" field if the given value is not nil. +func (ssruo *SecurityScanningResultUpdateOne) SetNillablePath(s *string) *SecurityScanningResultUpdateOne { + if s != nil { + ssruo.SetPath(*s) + } + return ssruo +} + +// SetMessage sets the "message" field. +func (ssruo *SecurityScanningResultUpdateOne) SetMessage(s string) *SecurityScanningResultUpdateOne { + ssruo.mutation.SetMessage(s) + return ssruo +} + +// SetNillableMessage sets the "message" field if the given value is not nil. +func (ssruo *SecurityScanningResultUpdateOne) SetNillableMessage(s *string) *SecurityScanningResultUpdateOne { + if s != nil { + ssruo.SetMessage(*s) + } + return ssruo +} + +// SetMessageZh sets the "message_zh" field. +func (ssruo *SecurityScanningResultUpdateOne) SetMessageZh(s string) *SecurityScanningResultUpdateOne { + ssruo.mutation.SetMessageZh(s) + return ssruo +} + +// SetNillableMessageZh sets the "message_zh" field if the given value is not nil. +func (ssruo *SecurityScanningResultUpdateOne) SetNillableMessageZh(s *string) *SecurityScanningResultUpdateOne { + if s != nil { + ssruo.SetMessageZh(*s) + } + return ssruo +} + +// SetSeverity sets the "severity" field. +func (ssruo *SecurityScanningResultUpdateOne) SetSeverity(s string) *SecurityScanningResultUpdateOne { + ssruo.mutation.SetSeverity(s) + return ssruo +} + +// SetNillableSeverity sets the "severity" field if the given value is not nil. +func (ssruo *SecurityScanningResultUpdateOne) SetNillableSeverity(s *string) *SecurityScanningResultUpdateOne { + if s != nil { + ssruo.SetSeverity(*s) + } + return ssruo +} + +// SetAbstractEn sets the "abstract_en" field. +func (ssruo *SecurityScanningResultUpdateOne) SetAbstractEn(s string) *SecurityScanningResultUpdateOne { + ssruo.mutation.SetAbstractEn(s) + return ssruo +} + +// SetNillableAbstractEn sets the "abstract_en" field if the given value is not nil. +func (ssruo *SecurityScanningResultUpdateOne) SetNillableAbstractEn(s *string) *SecurityScanningResultUpdateOne { + if s != nil { + ssruo.SetAbstractEn(*s) + } + return ssruo +} + +// SetAbstractZh sets the "abstract_zh" field. +func (ssruo *SecurityScanningResultUpdateOne) SetAbstractZh(s string) *SecurityScanningResultUpdateOne { + ssruo.mutation.SetAbstractZh(s) + return ssruo +} + +// SetNillableAbstractZh sets the "abstract_zh" field if the given value is not nil. +func (ssruo *SecurityScanningResultUpdateOne) SetNillableAbstractZh(s *string) *SecurityScanningResultUpdateOne { + if s != nil { + ssruo.SetAbstractZh(*s) + } + return ssruo +} + +// SetCategoryEn sets the "category_en" field. +func (ssruo *SecurityScanningResultUpdateOne) SetCategoryEn(s string) *SecurityScanningResultUpdateOne { + ssruo.mutation.SetCategoryEn(s) + return ssruo +} + +// SetNillableCategoryEn sets the "category_en" field if the given value is not nil. +func (ssruo *SecurityScanningResultUpdateOne) SetNillableCategoryEn(s *string) *SecurityScanningResultUpdateOne { + if s != nil { + ssruo.SetCategoryEn(*s) + } + return ssruo +} + +// SetCategoryZh sets the "category_zh" field. +func (ssruo *SecurityScanningResultUpdateOne) SetCategoryZh(s string) *SecurityScanningResultUpdateOne { + ssruo.mutation.SetCategoryZh(s) + return ssruo +} + +// SetNillableCategoryZh sets the "category_zh" field if the given value is not nil. +func (ssruo *SecurityScanningResultUpdateOne) SetNillableCategoryZh(s *string) *SecurityScanningResultUpdateOne { + if s != nil { + ssruo.SetCategoryZh(*s) + } + return ssruo +} + +// SetConfidence sets the "confidence" field. +func (ssruo *SecurityScanningResultUpdateOne) SetConfidence(s string) *SecurityScanningResultUpdateOne { + ssruo.mutation.SetConfidence(s) + return ssruo +} + +// SetNillableConfidence sets the "confidence" field if the given value is not nil. +func (ssruo *SecurityScanningResultUpdateOne) SetNillableConfidence(s *string) *SecurityScanningResultUpdateOne { + if s != nil { + ssruo.SetConfidence(*s) + } + return ssruo +} + +// SetCwe sets the "cwe" field. +func (ssruo *SecurityScanningResultUpdateOne) SetCwe(i []interface{}) *SecurityScanningResultUpdateOne { + ssruo.mutation.SetCwe(i) + return ssruo +} + +// AppendCwe appends i to the "cwe" field. +func (ssruo *SecurityScanningResultUpdateOne) AppendCwe(i []interface{}) *SecurityScanningResultUpdateOne { + ssruo.mutation.AppendCwe(i) + return ssruo +} + +// SetImpact sets the "impact" field. +func (ssruo *SecurityScanningResultUpdateOne) SetImpact(s string) *SecurityScanningResultUpdateOne { + ssruo.mutation.SetImpact(s) + return ssruo +} + +// SetNillableImpact sets the "impact" field if the given value is not nil. +func (ssruo *SecurityScanningResultUpdateOne) SetNillableImpact(s *string) *SecurityScanningResultUpdateOne { + if s != nil { + ssruo.SetImpact(*s) + } + return ssruo +} + +// SetOwasp sets the "owasp" field. +func (ssruo *SecurityScanningResultUpdateOne) SetOwasp(i []interface{}) *SecurityScanningResultUpdateOne { + ssruo.mutation.SetOwasp(i) + return ssruo +} + +// AppendOwasp appends i to the "owasp" field. +func (ssruo *SecurityScanningResultUpdateOne) AppendOwasp(i []interface{}) *SecurityScanningResultUpdateOne { + ssruo.mutation.AppendOwasp(i) + return ssruo +} + +// SetStartPosition sets the "start_position" field. +func (ssruo *SecurityScanningResultUpdateOne) SetStartPosition(t *types.Position) *SecurityScanningResultUpdateOne { + ssruo.mutation.SetStartPosition(t) + return ssruo +} + +// SetEndPosition sets the "end_position" field. +func (ssruo *SecurityScanningResultUpdateOne) SetEndPosition(t *types.Position) *SecurityScanningResultUpdateOne { + ssruo.mutation.SetEndPosition(t) + return ssruo +} + +// SetCreatedAt sets the "created_at" field. +func (ssruo *SecurityScanningResultUpdateOne) SetCreatedAt(t time.Time) *SecurityScanningResultUpdateOne { + ssruo.mutation.SetCreatedAt(t) + return ssruo +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (ssruo *SecurityScanningResultUpdateOne) SetNillableCreatedAt(t *time.Time) *SecurityScanningResultUpdateOne { + if t != nil { + ssruo.SetCreatedAt(*t) + } + return ssruo +} + +// SetSecurityScanning sets the "security_scanning" edge to the SecurityScanning entity. +func (ssruo *SecurityScanningResultUpdateOne) SetSecurityScanning(s *SecurityScanning) *SecurityScanningResultUpdateOne { + return ssruo.SetSecurityScanningID(s.ID) +} + +// Mutation returns the SecurityScanningResultMutation object of the builder. +func (ssruo *SecurityScanningResultUpdateOne) Mutation() *SecurityScanningResultMutation { + return ssruo.mutation +} + +// ClearSecurityScanning clears the "security_scanning" edge to the SecurityScanning entity. +func (ssruo *SecurityScanningResultUpdateOne) ClearSecurityScanning() *SecurityScanningResultUpdateOne { + ssruo.mutation.ClearSecurityScanning() + return ssruo +} + +// Where appends a list predicates to the SecurityScanningResultUpdate builder. +func (ssruo *SecurityScanningResultUpdateOne) Where(ps ...predicate.SecurityScanningResult) *SecurityScanningResultUpdateOne { + ssruo.mutation.Where(ps...) + return ssruo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (ssruo *SecurityScanningResultUpdateOne) Select(field string, fields ...string) *SecurityScanningResultUpdateOne { + ssruo.fields = append([]string{field}, fields...) + return ssruo +} + +// Save executes the query and returns the updated SecurityScanningResult entity. +func (ssruo *SecurityScanningResultUpdateOne) Save(ctx context.Context) (*SecurityScanningResult, error) { + return withHooks(ctx, ssruo.sqlSave, ssruo.mutation, ssruo.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (ssruo *SecurityScanningResultUpdateOne) SaveX(ctx context.Context) *SecurityScanningResult { + node, err := ssruo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (ssruo *SecurityScanningResultUpdateOne) Exec(ctx context.Context) error { + _, err := ssruo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ssruo *SecurityScanningResultUpdateOne) ExecX(ctx context.Context) { + if err := ssruo.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (ssruo *SecurityScanningResultUpdateOne) check() error { + if ssruo.mutation.SecurityScanningCleared() && len(ssruo.mutation.SecurityScanningIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "SecurityScanningResult.security_scanning"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (ssruo *SecurityScanningResultUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *SecurityScanningResultUpdateOne { + ssruo.modifiers = append(ssruo.modifiers, modifiers...) + return ssruo +} + +func (ssruo *SecurityScanningResultUpdateOne) sqlSave(ctx context.Context) (_node *SecurityScanningResult, err error) { + if err := ssruo.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(securityscanningresult.Table, securityscanningresult.Columns, sqlgraph.NewFieldSpec(securityscanningresult.FieldID, field.TypeUUID)) + id, ok := ssruo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "SecurityScanningResult.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := ssruo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, securityscanningresult.FieldID) + for _, f := range fields { + if !securityscanningresult.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != securityscanningresult.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := ssruo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := ssruo.mutation.CheckID(); ok { + _spec.SetField(securityscanningresult.FieldCheckID, field.TypeString, value) + } + if value, ok := ssruo.mutation.EngineKind(); ok { + _spec.SetField(securityscanningresult.FieldEngineKind, field.TypeString, value) + } + if value, ok := ssruo.mutation.Lines(); ok { + _spec.SetField(securityscanningresult.FieldLines, field.TypeString, value) + } + if value, ok := ssruo.mutation.Path(); ok { + _spec.SetField(securityscanningresult.FieldPath, field.TypeString, value) + } + if value, ok := ssruo.mutation.Message(); ok { + _spec.SetField(securityscanningresult.FieldMessage, field.TypeString, value) + } + if value, ok := ssruo.mutation.MessageZh(); ok { + _spec.SetField(securityscanningresult.FieldMessageZh, field.TypeString, value) + } + if value, ok := ssruo.mutation.Severity(); ok { + _spec.SetField(securityscanningresult.FieldSeverity, field.TypeString, value) + } + if value, ok := ssruo.mutation.AbstractEn(); ok { + _spec.SetField(securityscanningresult.FieldAbstractEn, field.TypeString, value) + } + if value, ok := ssruo.mutation.AbstractZh(); ok { + _spec.SetField(securityscanningresult.FieldAbstractZh, field.TypeString, value) + } + if value, ok := ssruo.mutation.CategoryEn(); ok { + _spec.SetField(securityscanningresult.FieldCategoryEn, field.TypeString, value) + } + if value, ok := ssruo.mutation.CategoryZh(); ok { + _spec.SetField(securityscanningresult.FieldCategoryZh, field.TypeString, value) + } + if value, ok := ssruo.mutation.Confidence(); ok { + _spec.SetField(securityscanningresult.FieldConfidence, field.TypeString, value) + } + if value, ok := ssruo.mutation.Cwe(); ok { + _spec.SetField(securityscanningresult.FieldCwe, field.TypeJSON, value) + } + if value, ok := ssruo.mutation.AppendedCwe(); ok { + _spec.AddModifier(func(u *sql.UpdateBuilder) { + sqljson.Append(u, securityscanningresult.FieldCwe, value) + }) + } + if value, ok := ssruo.mutation.Impact(); ok { + _spec.SetField(securityscanningresult.FieldImpact, field.TypeString, value) + } + if value, ok := ssruo.mutation.Owasp(); ok { + _spec.SetField(securityscanningresult.FieldOwasp, field.TypeJSON, value) + } + if value, ok := ssruo.mutation.AppendedOwasp(); ok { + _spec.AddModifier(func(u *sql.UpdateBuilder) { + sqljson.Append(u, securityscanningresult.FieldOwasp, value) + }) + } + if value, ok := ssruo.mutation.StartPosition(); ok { + _spec.SetField(securityscanningresult.FieldStartPosition, field.TypeJSON, value) + } + if value, ok := ssruo.mutation.EndPosition(); ok { + _spec.SetField(securityscanningresult.FieldEndPosition, field.TypeJSON, value) + } + if value, ok := ssruo.mutation.CreatedAt(); ok { + _spec.SetField(securityscanningresult.FieldCreatedAt, field.TypeTime, value) + } + if ssruo.mutation.SecurityScanningCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: securityscanningresult.SecurityScanningTable, + Columns: []string{securityscanningresult.SecurityScanningColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(securityscanning.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ssruo.mutation.SecurityScanningIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: securityscanningresult.SecurityScanningTable, + Columns: []string{securityscanningresult.SecurityScanningColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(securityscanning.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(ssruo.modifiers...) + _node = &SecurityScanningResult{config: ssruo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, ssruo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{securityscanningresult.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + ssruo.mutation.done = true + return _node, nil +} diff --git a/backend/db/tx.go b/backend/db/tx.go index 18ff40f..1e92fa0 100644 --- a/backend/db/tx.go +++ b/backend/db/tx.go @@ -42,6 +42,10 @@ type Tx struct { ModelProvider *ModelProviderClient // ModelProviderModel is the client for interacting with the ModelProviderModel builders. ModelProviderModel *ModelProviderModelClient + // SecurityScanning is the client for interacting with the SecurityScanning builders. + SecurityScanning *SecurityScanningClient + // SecurityScanningResult is the client for interacting with the SecurityScanningResult builders. + SecurityScanningResult *SecurityScanningResultClient // Setting is the client for interacting with the Setting builders. Setting *SettingClient // Task is the client for interacting with the Task builders. @@ -203,6 +207,8 @@ func (tx *Tx) init() { tx.Model = NewModelClient(tx.config) tx.ModelProvider = NewModelProviderClient(tx.config) tx.ModelProviderModel = NewModelProviderModelClient(tx.config) + tx.SecurityScanning = NewSecurityScanningClient(tx.config) + tx.SecurityScanningResult = NewSecurityScanningResultClient(tx.config) tx.Setting = NewSettingClient(tx.config) tx.Task = NewTaskClient(tx.config) tx.TaskRecord = NewTaskRecordClient(tx.config) diff --git a/backend/db/user.go b/backend/db/user.go index 81006d8..ec0b3bd 100644 --- a/backend/db/user.go +++ b/backend/db/user.go @@ -59,9 +59,11 @@ type UserEdges struct { WorkspaceFiles []*WorkspaceFile `json:"workspace_files,omitempty"` // APIKeys holds the value of the api_keys edge. APIKeys []*ApiKey `json:"api_keys,omitempty"` + // SecurityScannings holds the value of the security_scannings edge. + SecurityScannings []*SecurityScanning `json:"security_scannings,omitempty"` // loadedTypes holds the information for reporting if a // type was loaded (or requested) in eager-loading or not. - loadedTypes [7]bool + loadedTypes [8]bool } // LoginHistoriesOrErr returns the LoginHistories value or an error if the edge @@ -127,6 +129,15 @@ func (e UserEdges) APIKeysOrErr() ([]*ApiKey, error) { return nil, &NotLoadedError{edge: "api_keys"} } +// SecurityScanningsOrErr returns the SecurityScannings value or an error if the edge +// was not loaded in eager-loading. +func (e UserEdges) SecurityScanningsOrErr() ([]*SecurityScanning, error) { + if e.loadedTypes[7] { + return e.SecurityScannings, nil + } + return nil, &NotLoadedError{edge: "security_scannings"} +} + // scanValues returns the types for scanning values from sql.Rows. func (*User) scanValues(columns []string) ([]any, error) { values := make([]any, len(columns)) @@ -261,6 +272,11 @@ func (u *User) QueryAPIKeys() *ApiKeyQuery { return NewUserClient(u.config).QueryAPIKeys(u) } +// QuerySecurityScannings queries the "security_scannings" edge of the User entity. +func (u *User) QuerySecurityScannings() *SecurityScanningQuery { + return NewUserClient(u.config).QuerySecurityScannings(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. diff --git a/backend/db/user/user.go b/backend/db/user/user.go index fa8c31e..c880ce1 100644 --- a/backend/db/user/user.go +++ b/backend/db/user/user.go @@ -48,6 +48,8 @@ const ( EdgeWorkspaceFiles = "workspace_files" // EdgeAPIKeys holds the string denoting the api_keys edge name in mutations. EdgeAPIKeys = "api_keys" + // EdgeSecurityScannings holds the string denoting the security_scannings edge name in mutations. + EdgeSecurityScannings = "security_scannings" // Table holds the table name of the user in the database. Table = "users" // LoginHistoriesTable is the table that holds the login_histories relation/edge. @@ -99,6 +101,13 @@ const ( APIKeysInverseTable = "api_keys" // APIKeysColumn is the table column denoting the api_keys relation/edge. APIKeysColumn = "user_id" + // SecurityScanningsTable is the table that holds the security_scannings relation/edge. + SecurityScanningsTable = "security_scannings" + // SecurityScanningsInverseTable is the table name for the SecurityScanning entity. + // It exists in this package in order to avoid circular dependency with the "securityscanning" package. + SecurityScanningsInverseTable = "security_scannings" + // SecurityScanningsColumn is the table column denoting the security_scannings relation/edge. + SecurityScanningsColumn = "user_id" ) // Columns holds all SQL columns for user fields. @@ -293,6 +302,20 @@ func ByAPIKeys(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { sqlgraph.OrderByNeighborTerms(s, newAPIKeysStep(), append([]sql.OrderTerm{term}, terms...)...) } } + +// BySecurityScanningsCount orders the results by security_scannings count. +func BySecurityScanningsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newSecurityScanningsStep(), opts...) + } +} + +// BySecurityScannings orders the results by security_scannings terms. +func BySecurityScannings(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newSecurityScanningsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} func newLoginHistoriesStep() *sqlgraph.Step { return sqlgraph.NewStep( sqlgraph.From(Table, FieldID), @@ -342,3 +365,10 @@ func newAPIKeysStep() *sqlgraph.Step { sqlgraph.Edge(sqlgraph.O2M, false, APIKeysTable, APIKeysColumn), ) } +func newSecurityScanningsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(SecurityScanningsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, SecurityScanningsTable, SecurityScanningsColumn), + ) +} diff --git a/backend/db/user/where.go b/backend/db/user/where.go index 00c6a23..9ef025a 100644 --- a/backend/db/user/where.go +++ b/backend/db/user/where.go @@ -863,6 +863,29 @@ func HasAPIKeysWith(preds ...predicate.ApiKey) predicate.User { }) } +// HasSecurityScannings applies the HasEdge predicate on the "security_scannings" edge. +func HasSecurityScannings() predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, SecurityScanningsTable, SecurityScanningsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasSecurityScanningsWith applies the HasEdge predicate on the "security_scannings" edge with a given conditions (other predicates). +func HasSecurityScanningsWith(preds ...predicate.SecurityScanning) predicate.User { + return predicate.User(func(s *sql.Selector) { + step := newSecurityScanningsStep() + 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...)) diff --git a/backend/db/user_create.go b/backend/db/user_create.go index 5e5d35a..296f363 100644 --- a/backend/db/user_create.go +++ b/backend/db/user_create.go @@ -15,6 +15,7 @@ import ( "github.com/chaitin/MonkeyCode/backend/consts" "github.com/chaitin/MonkeyCode/backend/db/apikey" "github.com/chaitin/MonkeyCode/backend/db/model" + "github.com/chaitin/MonkeyCode/backend/db/securityscanning" "github.com/chaitin/MonkeyCode/backend/db/task" "github.com/chaitin/MonkeyCode/backend/db/user" "github.com/chaitin/MonkeyCode/backend/db/useridentity" @@ -269,6 +270,21 @@ func (uc *UserCreate) AddAPIKeys(a ...*ApiKey) *UserCreate { return uc.AddAPIKeyIDs(ids...) } +// AddSecurityScanningIDs adds the "security_scannings" edge to the SecurityScanning entity by IDs. +func (uc *UserCreate) AddSecurityScanningIDs(ids ...uuid.UUID) *UserCreate { + uc.mutation.AddSecurityScanningIDs(ids...) + return uc +} + +// AddSecurityScannings adds the "security_scannings" edges to the SecurityScanning entity. +func (uc *UserCreate) AddSecurityScannings(s ...*SecurityScanning) *UserCreate { + ids := make([]uuid.UUID, len(s)) + for i := range s { + ids[i] = s[i].ID + } + return uc.AddSecurityScanningIDs(ids...) +} + // Mutation returns the UserMutation object of the builder. func (uc *UserCreate) Mutation() *UserMutation { return uc.mutation @@ -529,6 +545,22 @@ func (uc *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) { } _spec.Edges = append(_spec.Edges, edge) } + if nodes := uc.mutation.SecurityScanningsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.SecurityScanningsTable, + Columns: []string{user.SecurityScanningsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(securityscanning.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } return _node, _spec } diff --git a/backend/db/user_query.go b/backend/db/user_query.go index 768fc9b..49d7fc7 100644 --- a/backend/db/user_query.go +++ b/backend/db/user_query.go @@ -16,6 +16,7 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/apikey" "github.com/chaitin/MonkeyCode/backend/db/model" "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/securityscanning" "github.com/chaitin/MonkeyCode/backend/db/task" "github.com/chaitin/MonkeyCode/backend/db/user" "github.com/chaitin/MonkeyCode/backend/db/useridentity" @@ -28,18 +29,19 @@ import ( // UserQuery is the builder for querying User entities. type UserQuery struct { config - ctx *QueryContext - order []user.OrderOption - inters []Interceptor - predicates []predicate.User - withLoginHistories *UserLoginHistoryQuery - withModels *ModelQuery - withTasks *TaskQuery - withIdentities *UserIdentityQuery - withWorkspaces *WorkspaceQuery - withWorkspaceFiles *WorkspaceFileQuery - withAPIKeys *ApiKeyQuery - modifiers []func(*sql.Selector) + ctx *QueryContext + order []user.OrderOption + inters []Interceptor + predicates []predicate.User + withLoginHistories *UserLoginHistoryQuery + withModels *ModelQuery + withTasks *TaskQuery + withIdentities *UserIdentityQuery + withWorkspaces *WorkspaceQuery + withWorkspaceFiles *WorkspaceFileQuery + withAPIKeys *ApiKeyQuery + withSecurityScannings *SecurityScanningQuery + modifiers []func(*sql.Selector) // intermediate query (i.e. traversal path). sql *sql.Selector path func(context.Context) (*sql.Selector, error) @@ -230,6 +232,28 @@ func (uq *UserQuery) QueryAPIKeys() *ApiKeyQuery { return query } +// QuerySecurityScannings chains the current query on the "security_scannings" edge. +func (uq *UserQuery) QuerySecurityScannings() *SecurityScanningQuery { + query := (&SecurityScanningClient{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(securityscanning.Table, securityscanning.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, user.SecurityScanningsTable, user.SecurityScanningsColumn), + ) + 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) { @@ -417,18 +441,19 @@ func (uq *UserQuery) Clone() *UserQuery { 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...), - withLoginHistories: uq.withLoginHistories.Clone(), - withModels: uq.withModels.Clone(), - withTasks: uq.withTasks.Clone(), - withIdentities: uq.withIdentities.Clone(), - withWorkspaces: uq.withWorkspaces.Clone(), - withWorkspaceFiles: uq.withWorkspaceFiles.Clone(), - withAPIKeys: uq.withAPIKeys.Clone(), + config: uq.config, + ctx: uq.ctx.Clone(), + order: append([]user.OrderOption{}, uq.order...), + inters: append([]Interceptor{}, uq.inters...), + predicates: append([]predicate.User{}, uq.predicates...), + withLoginHistories: uq.withLoginHistories.Clone(), + withModels: uq.withModels.Clone(), + withTasks: uq.withTasks.Clone(), + withIdentities: uq.withIdentities.Clone(), + withWorkspaces: uq.withWorkspaces.Clone(), + withWorkspaceFiles: uq.withWorkspaceFiles.Clone(), + withAPIKeys: uq.withAPIKeys.Clone(), + withSecurityScannings: uq.withSecurityScannings.Clone(), // clone intermediate query. sql: uq.sql.Clone(), path: uq.path, @@ -513,6 +538,17 @@ func (uq *UserQuery) WithAPIKeys(opts ...func(*ApiKeyQuery)) *UserQuery { return uq } +// WithSecurityScannings tells the query-builder to eager-load the nodes that are connected to +// the "security_scannings" edge. The optional arguments are used to configure the query builder of the edge. +func (uq *UserQuery) WithSecurityScannings(opts ...func(*SecurityScanningQuery)) *UserQuery { + query := (&SecurityScanningClient{config: uq.config}).Query() + for _, opt := range opts { + opt(query) + } + uq.withSecurityScannings = 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. // @@ -591,7 +627,7 @@ func (uq *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, e var ( nodes = []*User{} _spec = uq.querySpec() - loadedTypes = [7]bool{ + loadedTypes = [8]bool{ uq.withLoginHistories != nil, uq.withModels != nil, uq.withTasks != nil, @@ -599,6 +635,7 @@ func (uq *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, e uq.withWorkspaces != nil, uq.withWorkspaceFiles != nil, uq.withAPIKeys != nil, + uq.withSecurityScannings != nil, } ) _spec.ScanValues = func(columns []string) ([]any, error) { @@ -671,6 +708,13 @@ func (uq *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, e return nil, err } } + if query := uq.withSecurityScannings; query != nil { + if err := uq.loadSecurityScannings(ctx, query, nodes, + func(n *User) { n.Edges.SecurityScannings = []*SecurityScanning{} }, + func(n *User, e *SecurityScanning) { n.Edges.SecurityScannings = append(n.Edges.SecurityScannings, e) }); err != nil { + return nil, err + } + } return nodes, nil } @@ -884,6 +928,36 @@ func (uq *UserQuery) loadAPIKeys(ctx context.Context, query *ApiKeyQuery, nodes } return nil } +func (uq *UserQuery) loadSecurityScannings(ctx context.Context, query *SecurityScanningQuery, nodes []*User, init func(*User), assign func(*User, *SecurityScanning)) 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(securityscanning.FieldUserID) + } + query.Where(predicate.SecurityScanning(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(user.SecurityScanningsColumn), 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() diff --git a/backend/db/user_update.go b/backend/db/user_update.go index f55fd25..0118336 100644 --- a/backend/db/user_update.go +++ b/backend/db/user_update.go @@ -15,6 +15,7 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/apikey" "github.com/chaitin/MonkeyCode/backend/db/model" "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/securityscanning" "github.com/chaitin/MonkeyCode/backend/db/task" "github.com/chaitin/MonkeyCode/backend/db/user" "github.com/chaitin/MonkeyCode/backend/db/useridentity" @@ -299,6 +300,21 @@ func (uu *UserUpdate) AddAPIKeys(a ...*ApiKey) *UserUpdate { return uu.AddAPIKeyIDs(ids...) } +// AddSecurityScanningIDs adds the "security_scannings" edge to the SecurityScanning entity by IDs. +func (uu *UserUpdate) AddSecurityScanningIDs(ids ...uuid.UUID) *UserUpdate { + uu.mutation.AddSecurityScanningIDs(ids...) + return uu +} + +// AddSecurityScannings adds the "security_scannings" edges to the SecurityScanning entity. +func (uu *UserUpdate) AddSecurityScannings(s ...*SecurityScanning) *UserUpdate { + ids := make([]uuid.UUID, len(s)) + for i := range s { + ids[i] = s[i].ID + } + return uu.AddSecurityScanningIDs(ids...) +} + // Mutation returns the UserMutation object of the builder. func (uu *UserUpdate) Mutation() *UserMutation { return uu.mutation @@ -451,6 +467,27 @@ func (uu *UserUpdate) RemoveAPIKeys(a ...*ApiKey) *UserUpdate { return uu.RemoveAPIKeyIDs(ids...) } +// ClearSecurityScannings clears all "security_scannings" edges to the SecurityScanning entity. +func (uu *UserUpdate) ClearSecurityScannings() *UserUpdate { + uu.mutation.ClearSecurityScannings() + return uu +} + +// RemoveSecurityScanningIDs removes the "security_scannings" edge to SecurityScanning entities by IDs. +func (uu *UserUpdate) RemoveSecurityScanningIDs(ids ...uuid.UUID) *UserUpdate { + uu.mutation.RemoveSecurityScanningIDs(ids...) + return uu +} + +// RemoveSecurityScannings removes "security_scannings" edges to SecurityScanning entities. +func (uu *UserUpdate) RemoveSecurityScannings(s ...*SecurityScanning) *UserUpdate { + ids := make([]uuid.UUID, len(s)) + for i := range s { + ids[i] = s[i].ID + } + return uu.RemoveSecurityScanningIDs(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) @@ -850,6 +887,51 @@ func (uu *UserUpdate) sqlSave(ctx context.Context) (n int, err error) { } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if uu.mutation.SecurityScanningsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.SecurityScanningsTable, + Columns: []string{user.SecurityScanningsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(securityscanning.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uu.mutation.RemovedSecurityScanningsIDs(); len(nodes) > 0 && !uu.mutation.SecurityScanningsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.SecurityScanningsTable, + Columns: []string{user.SecurityScanningsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(securityscanning.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.SecurityScanningsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.SecurityScanningsTable, + Columns: []string{user.SecurityScanningsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(securityscanning.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 { @@ -1133,6 +1215,21 @@ func (uuo *UserUpdateOne) AddAPIKeys(a ...*ApiKey) *UserUpdateOne { return uuo.AddAPIKeyIDs(ids...) } +// AddSecurityScanningIDs adds the "security_scannings" edge to the SecurityScanning entity by IDs. +func (uuo *UserUpdateOne) AddSecurityScanningIDs(ids ...uuid.UUID) *UserUpdateOne { + uuo.mutation.AddSecurityScanningIDs(ids...) + return uuo +} + +// AddSecurityScannings adds the "security_scannings" edges to the SecurityScanning entity. +func (uuo *UserUpdateOne) AddSecurityScannings(s ...*SecurityScanning) *UserUpdateOne { + ids := make([]uuid.UUID, len(s)) + for i := range s { + ids[i] = s[i].ID + } + return uuo.AddSecurityScanningIDs(ids...) +} + // Mutation returns the UserMutation object of the builder. func (uuo *UserUpdateOne) Mutation() *UserMutation { return uuo.mutation @@ -1285,6 +1382,27 @@ func (uuo *UserUpdateOne) RemoveAPIKeys(a ...*ApiKey) *UserUpdateOne { return uuo.RemoveAPIKeyIDs(ids...) } +// ClearSecurityScannings clears all "security_scannings" edges to the SecurityScanning entity. +func (uuo *UserUpdateOne) ClearSecurityScannings() *UserUpdateOne { + uuo.mutation.ClearSecurityScannings() + return uuo +} + +// RemoveSecurityScanningIDs removes the "security_scannings" edge to SecurityScanning entities by IDs. +func (uuo *UserUpdateOne) RemoveSecurityScanningIDs(ids ...uuid.UUID) *UserUpdateOne { + uuo.mutation.RemoveSecurityScanningIDs(ids...) + return uuo +} + +// RemoveSecurityScannings removes "security_scannings" edges to SecurityScanning entities. +func (uuo *UserUpdateOne) RemoveSecurityScannings(s ...*SecurityScanning) *UserUpdateOne { + ids := make([]uuid.UUID, len(s)) + for i := range s { + ids[i] = s[i].ID + } + return uuo.RemoveSecurityScanningIDs(ids...) +} + // Where appends a list predicates to the UserUpdate builder. func (uuo *UserUpdateOne) Where(ps ...predicate.User) *UserUpdateOne { uuo.mutation.Where(ps...) @@ -1714,6 +1832,51 @@ func (uuo *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if uuo.mutation.SecurityScanningsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.SecurityScanningsTable, + Columns: []string{user.SecurityScanningsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(securityscanning.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uuo.mutation.RemovedSecurityScanningsIDs(); len(nodes) > 0 && !uuo.mutation.SecurityScanningsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.SecurityScanningsTable, + Columns: []string{user.SecurityScanningsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(securityscanning.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.SecurityScanningsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.SecurityScanningsTable, + Columns: []string{user.SecurityScanningsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(securityscanning.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 diff --git a/backend/db/workspace.go b/backend/db/workspace.go index 6d077b2..69aa4bb 100644 --- a/backend/db/workspace.go +++ b/backend/db/workspace.go @@ -48,9 +48,11 @@ type WorkspaceEdges struct { Owner *User `json:"owner,omitempty"` // Files holds the value of the files edge. Files []*WorkspaceFile `json:"files,omitempty"` + // SecurityScannings holds the value of the security_scannings edge. + SecurityScannings []*SecurityScanning `json:"security_scannings,omitempty"` // loadedTypes holds the information for reporting if a // type was loaded (or requested) in eager-loading or not. - loadedTypes [2]bool + loadedTypes [3]bool } // OwnerOrErr returns the Owner value or an error if the edge @@ -73,6 +75,15 @@ func (e WorkspaceEdges) FilesOrErr() ([]*WorkspaceFile, error) { return nil, &NotLoadedError{edge: "files"} } +// SecurityScanningsOrErr returns the SecurityScannings value or an error if the edge +// was not loaded in eager-loading. +func (e WorkspaceEdges) SecurityScanningsOrErr() ([]*SecurityScanning, error) { + if e.loadedTypes[2] { + return e.SecurityScannings, nil + } + return nil, &NotLoadedError{edge: "security_scannings"} +} + // scanValues returns the types for scanning values from sql.Rows. func (*Workspace) scanValues(columns []string) ([]any, error) { values := make([]any, len(columns)) @@ -180,6 +191,11 @@ func (w *Workspace) QueryFiles() *WorkspaceFileQuery { return NewWorkspaceClient(w.config).QueryFiles(w) } +// QuerySecurityScannings queries the "security_scannings" edge of the Workspace entity. +func (w *Workspace) QuerySecurityScannings() *SecurityScanningQuery { + return NewWorkspaceClient(w.config).QuerySecurityScannings(w) +} + // Update returns a builder for updating this Workspace. // Note that you need to call Workspace.Unwrap() before calling this method if this Workspace // was returned from a transaction, and the transaction was committed or rolled back. diff --git a/backend/db/workspace/where.go b/backend/db/workspace/where.go index 0e54dd6..8416f34 100644 --- a/backend/db/workspace/where.go +++ b/backend/db/workspace/where.go @@ -502,6 +502,29 @@ func HasFilesWith(preds ...predicate.WorkspaceFile) predicate.Workspace { }) } +// HasSecurityScannings applies the HasEdge predicate on the "security_scannings" edge. +func HasSecurityScannings() predicate.Workspace { + return predicate.Workspace(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, SecurityScanningsTable, SecurityScanningsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasSecurityScanningsWith applies the HasEdge predicate on the "security_scannings" edge with a given conditions (other predicates). +func HasSecurityScanningsWith(preds ...predicate.SecurityScanning) predicate.Workspace { + return predicate.Workspace(func(s *sql.Selector) { + step := newSecurityScanningsStep() + 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.Workspace) predicate.Workspace { return predicate.Workspace(sql.AndPredicates(predicates...)) diff --git a/backend/db/workspace/workspace.go b/backend/db/workspace/workspace.go index b2e6f0b..d7a06d4 100644 --- a/backend/db/workspace/workspace.go +++ b/backend/db/workspace/workspace.go @@ -34,6 +34,8 @@ const ( EdgeOwner = "owner" // EdgeFiles holds the string denoting the files edge name in mutations. EdgeFiles = "files" + // EdgeSecurityScannings holds the string denoting the security_scannings edge name in mutations. + EdgeSecurityScannings = "security_scannings" // Table holds the table name of the workspace in the database. Table = "workspaces" // OwnerTable is the table that holds the owner relation/edge. @@ -50,6 +52,13 @@ const ( FilesInverseTable = "workspace_files" // FilesColumn is the table column denoting the files relation/edge. FilesColumn = "workspace_id" + // SecurityScanningsTable is the table that holds the security_scannings relation/edge. + SecurityScanningsTable = "security_scannings" + // SecurityScanningsInverseTable is the table name for the SecurityScanning entity. + // It exists in this package in order to avoid circular dependency with the "securityscanning" package. + SecurityScanningsInverseTable = "security_scannings" + // SecurityScanningsColumn is the table column denoting the security_scannings relation/edge. + SecurityScanningsColumn = "workspace_id" ) // Columns holds all SQL columns for workspace fields. @@ -151,6 +160,20 @@ func ByFiles(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { sqlgraph.OrderByNeighborTerms(s, newFilesStep(), append([]sql.OrderTerm{term}, terms...)...) } } + +// BySecurityScanningsCount orders the results by security_scannings count. +func BySecurityScanningsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newSecurityScanningsStep(), opts...) + } +} + +// BySecurityScannings orders the results by security_scannings terms. +func BySecurityScannings(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newSecurityScanningsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} func newOwnerStep() *sqlgraph.Step { return sqlgraph.NewStep( sqlgraph.From(Table, FieldID), @@ -165,3 +188,10 @@ func newFilesStep() *sqlgraph.Step { sqlgraph.Edge(sqlgraph.O2M, false, FilesTable, FilesColumn), ) } +func newSecurityScanningsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(SecurityScanningsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, SecurityScanningsTable, SecurityScanningsColumn), + ) +} diff --git a/backend/db/workspace_create.go b/backend/db/workspace_create.go index d4d3b3a..e2bdf1f 100644 --- a/backend/db/workspace_create.go +++ b/backend/db/workspace_create.go @@ -12,6 +12,7 @@ import ( "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/securityscanning" "github.com/chaitin/MonkeyCode/backend/db/user" "github.com/chaitin/MonkeyCode/backend/db/workspace" "github.com/chaitin/MonkeyCode/backend/db/workspacefile" @@ -146,6 +147,21 @@ func (wc *WorkspaceCreate) AddFiles(w ...*WorkspaceFile) *WorkspaceCreate { return wc.AddFileIDs(ids...) } +// AddSecurityScanningIDs adds the "security_scannings" edge to the SecurityScanning entity by IDs. +func (wc *WorkspaceCreate) AddSecurityScanningIDs(ids ...uuid.UUID) *WorkspaceCreate { + wc.mutation.AddSecurityScanningIDs(ids...) + return wc +} + +// AddSecurityScannings adds the "security_scannings" edges to the SecurityScanning entity. +func (wc *WorkspaceCreate) AddSecurityScannings(s ...*SecurityScanning) *WorkspaceCreate { + ids := make([]uuid.UUID, len(s)) + for i := range s { + ids[i] = s[i].ID + } + return wc.AddSecurityScanningIDs(ids...) +} + // Mutation returns the WorkspaceMutation object of the builder. func (wc *WorkspaceCreate) Mutation() *WorkspaceMutation { return wc.mutation @@ -317,6 +333,22 @@ func (wc *WorkspaceCreate) createSpec() (*Workspace, *sqlgraph.CreateSpec) { } _spec.Edges = append(_spec.Edges, edge) } + if nodes := wc.mutation.SecurityScanningsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: workspace.SecurityScanningsTable, + Columns: []string{workspace.SecurityScanningsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(securityscanning.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } return _node, _spec } diff --git a/backend/db/workspace_query.go b/backend/db/workspace_query.go index 0d97f31..d1d29a3 100644 --- a/backend/db/workspace_query.go +++ b/backend/db/workspace_query.go @@ -14,6 +14,7 @@ import ( "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/securityscanning" "github.com/chaitin/MonkeyCode/backend/db/user" "github.com/chaitin/MonkeyCode/backend/db/workspace" "github.com/chaitin/MonkeyCode/backend/db/workspacefile" @@ -23,13 +24,14 @@ import ( // WorkspaceQuery is the builder for querying Workspace entities. type WorkspaceQuery struct { config - ctx *QueryContext - order []workspace.OrderOption - inters []Interceptor - predicates []predicate.Workspace - withOwner *UserQuery - withFiles *WorkspaceFileQuery - modifiers []func(*sql.Selector) + ctx *QueryContext + order []workspace.OrderOption + inters []Interceptor + predicates []predicate.Workspace + withOwner *UserQuery + withFiles *WorkspaceFileQuery + withSecurityScannings *SecurityScanningQuery + modifiers []func(*sql.Selector) // intermediate query (i.e. traversal path). sql *sql.Selector path func(context.Context) (*sql.Selector, error) @@ -110,6 +112,28 @@ func (wq *WorkspaceQuery) QueryFiles() *WorkspaceFileQuery { return query } +// QuerySecurityScannings chains the current query on the "security_scannings" edge. +func (wq *WorkspaceQuery) QuerySecurityScannings() *SecurityScanningQuery { + query := (&SecurityScanningClient{config: wq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := wq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := wq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(workspace.Table, workspace.FieldID, selector), + sqlgraph.To(securityscanning.Table, securityscanning.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, workspace.SecurityScanningsTable, workspace.SecurityScanningsColumn), + ) + fromU = sqlgraph.SetNeighbors(wq.driver.Dialect(), step) + return fromU, nil + } + return query +} + // First returns the first Workspace entity from the query. // Returns a *NotFoundError when no Workspace was found. func (wq *WorkspaceQuery) First(ctx context.Context) (*Workspace, error) { @@ -297,13 +321,14 @@ func (wq *WorkspaceQuery) Clone() *WorkspaceQuery { return nil } return &WorkspaceQuery{ - config: wq.config, - ctx: wq.ctx.Clone(), - order: append([]workspace.OrderOption{}, wq.order...), - inters: append([]Interceptor{}, wq.inters...), - predicates: append([]predicate.Workspace{}, wq.predicates...), - withOwner: wq.withOwner.Clone(), - withFiles: wq.withFiles.Clone(), + config: wq.config, + ctx: wq.ctx.Clone(), + order: append([]workspace.OrderOption{}, wq.order...), + inters: append([]Interceptor{}, wq.inters...), + predicates: append([]predicate.Workspace{}, wq.predicates...), + withOwner: wq.withOwner.Clone(), + withFiles: wq.withFiles.Clone(), + withSecurityScannings: wq.withSecurityScannings.Clone(), // clone intermediate query. sql: wq.sql.Clone(), path: wq.path, @@ -333,6 +358,17 @@ func (wq *WorkspaceQuery) WithFiles(opts ...func(*WorkspaceFileQuery)) *Workspac return wq } +// WithSecurityScannings tells the query-builder to eager-load the nodes that are connected to +// the "security_scannings" edge. The optional arguments are used to configure the query builder of the edge. +func (wq *WorkspaceQuery) WithSecurityScannings(opts ...func(*SecurityScanningQuery)) *WorkspaceQuery { + query := (&SecurityScanningClient{config: wq.config}).Query() + for _, opt := range opts { + opt(query) + } + wq.withSecurityScannings = query + return wq +} + // 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. // @@ -411,9 +447,10 @@ func (wq *WorkspaceQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Wo var ( nodes = []*Workspace{} _spec = wq.querySpec() - loadedTypes = [2]bool{ + loadedTypes = [3]bool{ wq.withOwner != nil, wq.withFiles != nil, + wq.withSecurityScannings != nil, } ) _spec.ScanValues = func(columns []string) ([]any, error) { @@ -450,6 +487,15 @@ func (wq *WorkspaceQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Wo return nil, err } } + if query := wq.withSecurityScannings; query != nil { + if err := wq.loadSecurityScannings(ctx, query, nodes, + func(n *Workspace) { n.Edges.SecurityScannings = []*SecurityScanning{} }, + func(n *Workspace, e *SecurityScanning) { + n.Edges.SecurityScannings = append(n.Edges.SecurityScannings, e) + }); err != nil { + return nil, err + } + } return nodes, nil } @@ -512,6 +558,36 @@ func (wq *WorkspaceQuery) loadFiles(ctx context.Context, query *WorkspaceFileQue } return nil } +func (wq *WorkspaceQuery) loadSecurityScannings(ctx context.Context, query *SecurityScanningQuery, nodes []*Workspace, init func(*Workspace), assign func(*Workspace, *SecurityScanning)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[uuid.UUID]*Workspace) + 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(securityscanning.FieldWorkspaceID) + } + query.Where(predicate.SecurityScanning(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(workspace.SecurityScanningsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.WorkspaceID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "workspace_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} func (wq *WorkspaceQuery) sqlCount(ctx context.Context) (int, error) { _spec := wq.querySpec() diff --git a/backend/db/workspace_update.go b/backend/db/workspace_update.go index bbab2de..46615e6 100644 --- a/backend/db/workspace_update.go +++ b/backend/db/workspace_update.go @@ -12,6 +12,7 @@ import ( "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/securityscanning" "github.com/chaitin/MonkeyCode/backend/db/user" "github.com/chaitin/MonkeyCode/backend/db/workspace" "github.com/chaitin/MonkeyCode/backend/db/workspacefile" @@ -158,6 +159,21 @@ func (wu *WorkspaceUpdate) AddFiles(w ...*WorkspaceFile) *WorkspaceUpdate { return wu.AddFileIDs(ids...) } +// AddSecurityScanningIDs adds the "security_scannings" edge to the SecurityScanning entity by IDs. +func (wu *WorkspaceUpdate) AddSecurityScanningIDs(ids ...uuid.UUID) *WorkspaceUpdate { + wu.mutation.AddSecurityScanningIDs(ids...) + return wu +} + +// AddSecurityScannings adds the "security_scannings" edges to the SecurityScanning entity. +func (wu *WorkspaceUpdate) AddSecurityScannings(s ...*SecurityScanning) *WorkspaceUpdate { + ids := make([]uuid.UUID, len(s)) + for i := range s { + ids[i] = s[i].ID + } + return wu.AddSecurityScanningIDs(ids...) +} + // Mutation returns the WorkspaceMutation object of the builder. func (wu *WorkspaceUpdate) Mutation() *WorkspaceMutation { return wu.mutation @@ -190,6 +206,27 @@ func (wu *WorkspaceUpdate) RemoveFiles(w ...*WorkspaceFile) *WorkspaceUpdate { return wu.RemoveFileIDs(ids...) } +// ClearSecurityScannings clears all "security_scannings" edges to the SecurityScanning entity. +func (wu *WorkspaceUpdate) ClearSecurityScannings() *WorkspaceUpdate { + wu.mutation.ClearSecurityScannings() + return wu +} + +// RemoveSecurityScanningIDs removes the "security_scannings" edge to SecurityScanning entities by IDs. +func (wu *WorkspaceUpdate) RemoveSecurityScanningIDs(ids ...uuid.UUID) *WorkspaceUpdate { + wu.mutation.RemoveSecurityScanningIDs(ids...) + return wu +} + +// RemoveSecurityScannings removes "security_scannings" edges to SecurityScanning entities. +func (wu *WorkspaceUpdate) RemoveSecurityScannings(s ...*SecurityScanning) *WorkspaceUpdate { + ids := make([]uuid.UUID, len(s)) + for i := range s { + ids[i] = s[i].ID + } + return wu.RemoveSecurityScanningIDs(ids...) +} + // Save executes the query and returns the number of nodes affected by the update operation. func (wu *WorkspaceUpdate) Save(ctx context.Context) (int, error) { wu.defaults() @@ -358,6 +395,51 @@ func (wu *WorkspaceUpdate) sqlSave(ctx context.Context) (n int, err error) { } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if wu.mutation.SecurityScanningsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: workspace.SecurityScanningsTable, + Columns: []string{workspace.SecurityScanningsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(securityscanning.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := wu.mutation.RemovedSecurityScanningsIDs(); len(nodes) > 0 && !wu.mutation.SecurityScanningsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: workspace.SecurityScanningsTable, + Columns: []string{workspace.SecurityScanningsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(securityscanning.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 := wu.mutation.SecurityScanningsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: workspace.SecurityScanningsTable, + Columns: []string{workspace.SecurityScanningsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(securityscanning.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(wu.modifiers...) if n, err = sqlgraph.UpdateNodes(ctx, wu.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { @@ -506,6 +588,21 @@ func (wuo *WorkspaceUpdateOne) AddFiles(w ...*WorkspaceFile) *WorkspaceUpdateOne return wuo.AddFileIDs(ids...) } +// AddSecurityScanningIDs adds the "security_scannings" edge to the SecurityScanning entity by IDs. +func (wuo *WorkspaceUpdateOne) AddSecurityScanningIDs(ids ...uuid.UUID) *WorkspaceUpdateOne { + wuo.mutation.AddSecurityScanningIDs(ids...) + return wuo +} + +// AddSecurityScannings adds the "security_scannings" edges to the SecurityScanning entity. +func (wuo *WorkspaceUpdateOne) AddSecurityScannings(s ...*SecurityScanning) *WorkspaceUpdateOne { + ids := make([]uuid.UUID, len(s)) + for i := range s { + ids[i] = s[i].ID + } + return wuo.AddSecurityScanningIDs(ids...) +} + // Mutation returns the WorkspaceMutation object of the builder. func (wuo *WorkspaceUpdateOne) Mutation() *WorkspaceMutation { return wuo.mutation @@ -538,6 +635,27 @@ func (wuo *WorkspaceUpdateOne) RemoveFiles(w ...*WorkspaceFile) *WorkspaceUpdate return wuo.RemoveFileIDs(ids...) } +// ClearSecurityScannings clears all "security_scannings" edges to the SecurityScanning entity. +func (wuo *WorkspaceUpdateOne) ClearSecurityScannings() *WorkspaceUpdateOne { + wuo.mutation.ClearSecurityScannings() + return wuo +} + +// RemoveSecurityScanningIDs removes the "security_scannings" edge to SecurityScanning entities by IDs. +func (wuo *WorkspaceUpdateOne) RemoveSecurityScanningIDs(ids ...uuid.UUID) *WorkspaceUpdateOne { + wuo.mutation.RemoveSecurityScanningIDs(ids...) + return wuo +} + +// RemoveSecurityScannings removes "security_scannings" edges to SecurityScanning entities. +func (wuo *WorkspaceUpdateOne) RemoveSecurityScannings(s ...*SecurityScanning) *WorkspaceUpdateOne { + ids := make([]uuid.UUID, len(s)) + for i := range s { + ids[i] = s[i].ID + } + return wuo.RemoveSecurityScanningIDs(ids...) +} + // Where appends a list predicates to the WorkspaceUpdate builder. func (wuo *WorkspaceUpdateOne) Where(ps ...predicate.Workspace) *WorkspaceUpdateOne { wuo.mutation.Where(ps...) @@ -736,6 +854,51 @@ func (wuo *WorkspaceUpdateOne) sqlSave(ctx context.Context) (_node *Workspace, e } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if wuo.mutation.SecurityScanningsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: workspace.SecurityScanningsTable, + Columns: []string{workspace.SecurityScanningsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(securityscanning.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := wuo.mutation.RemovedSecurityScanningsIDs(); len(nodes) > 0 && !wuo.mutation.SecurityScanningsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: workspace.SecurityScanningsTable, + Columns: []string{workspace.SecurityScanningsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(securityscanning.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 := wuo.mutation.SecurityScanningsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: workspace.SecurityScanningsTable, + Columns: []string{workspace.SecurityScanningsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(securityscanning.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(wuo.modifiers...) _node = &Workspace{config: wuo.config} _spec.Assign = _node.assignValues diff --git a/backend/docs/swagger.json b/backend/docs/swagger.json deleted file mode 100644 index 23de309..0000000 --- a/backend/docs/swagger.json +++ /dev/null @@ -1,5869 +0,0 @@ -{ - "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": [ - "Admin" - ], - "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": [ - "Admin" - ], - "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/export-completion-data": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "管理员导出所有补全相关数据", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "admin" - ], - "summary": "导出补全数据", - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/domain.ExportCompletionDataResp" - } - }, - "401": { - "description": "Unauthorized", - "schema": { - "$ref": "#/definitions/web.Resp" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/web.Resp" - } - } - } - } - }, - "/api/v1/admin/list": { - "get": { - "description": "获取管理员用户列表", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Admin" - ], - "summary": "获取管理员用户列表", - "operationId": "list-admin-user", - "parameters": [ - { - "type": "string", - "description": "下一页标识", - "name": "next_token", - "in": "query" - }, - { - "minimum": 1, - "type": "integer", - "default": 1, - "description": "分页", - "name": "page", - "in": "query" - }, - { - "minimum": 1, - "type": "integer", - "default": 10, - "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": [ - "Admin" - ], - "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": [ - "Admin" - ], - "summary": "获取管理员登录历史", - "operationId": "admin-login-history", - "parameters": [ - { - "type": "string", - "description": "下一页标识", - "name": "next_token", - "in": "query" - }, - { - "minimum": 1, - "type": "integer", - "default": 1, - "description": "分页", - "name": "page", - "in": "query" - }, - { - "minimum": 1, - "type": "integer", - "default": 10, - "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/logout": { - "post": { - "description": "管理员登出", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Admin" - ], - "summary": "管理员登出", - "operationId": "admin-logout", - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/web.Resp" - } - } - } - } - }, - "/api/v1/admin/profile": { - "get": { - "description": "管理员信息", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Admin" - ], - "summary": "管理员信息", - "operationId": "admin-profile", - "responses": { - "200": { - "description": "OK", - "schema": { - "allOf": [ - { - "$ref": "#/definitions/web.Resp" - }, - { - "type": "object", - "properties": { - "data": { - "$ref": "#/definitions/domain.AdminUser" - } - } - } - ] - } - } - } - } - }, - "/api/v1/admin/setting": { - "get": { - "description": "获取系统设置", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Admin" - ], - "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": [ - "Admin" - ], - "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": "author", - "in": "query" - }, - { - "type": "boolean", - "description": "是否接受筛选", - "name": "is_accept", - "in": "query" - }, - { - "type": "string", - "description": "语言", - "name": "language", - "in": "query" - }, - { - "type": "string", - "description": "下一页标识", - "name": "next_token", - "in": "query" - }, - { - "minimum": 1, - "type": "integer", - "default": 1, - "description": "分页", - "name": "page", - "in": "query" - }, - { - "minimum": 1, - "type": "integer", - "default": 10, - "description": "每页多少条记录", - "name": "size", - "in": "query" - }, - { - "type": "string", - "description": "工作模式", - "name": "work_mode", - "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": "author", - "in": "query" - }, - { - "type": "boolean", - "description": "是否接受筛选", - "name": "is_accept", - "in": "query" - }, - { - "type": "string", - "description": "语言", - "name": "language", - "in": "query" - }, - { - "type": "string", - "description": "下一页标识", - "name": "next_token", - "in": "query" - }, - { - "minimum": 1, - "type": "integer", - "default": 1, - "description": "分页", - "name": "page", - "in": "query" - }, - { - "minimum": 1, - "type": "integer", - "default": 10, - "description": "每页多少条记录", - "name": "size", - "in": "query" - }, - { - "type": "string", - "description": "工作模式", - "name": "work_mode", - "in": "query" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "allOf": [ - { - "$ref": "#/definitions/web.Resp" - }, - { - "type": "object", - "properties": { - "data": { - "$ref": "#/definitions/domain.ListCompletionRecordResp" - } - } - } - ] - } - } - } - } - }, - "/api/v1/cli/{command}": { - "post": { - "description": "运行monkeycode-cli命令", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "CLI" - ], - "summary": "运行monkeycode-cli命令", - "parameters": [ - { - "type": "string", - "description": "命令", - "name": "command", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "标志", - "name": "flag", - "in": "query" - }, - { - "description": "代码文件信息", - "name": "fileMetas", - "in": "body", - "required": true, - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/domain.FileMeta" - } - } - } - ], - "responses": { - "200": { - "description": "输出结果", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/domain.IndexResult" - } - } - }, - "500": { - "description": "内部错误", - "schema": { - "$ref": "#/definitions/web.Resp" - } - } - } - } - }, - "/api/v1/dashboard/category-stat": { - "get": { - "description": "获取分类统计信息", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Dashboard" - ], - "summary": "获取分类统计信息", - "operationId": "category-stat-dashboard", - "parameters": [ - { - "maximum": 90, - "minimum": 24, - "type": "integer", - "default": 90, - "description": "持续时间 (小时或天数)`", - "name": "duration", - "in": "query" - }, - { - "enum": [ - "hour", - "day" - ], - "type": "string", - "default": "day", - "description": "精度: \"hour\", \"day\"", - "name": "precision", - "in": "query", - "required": true - }, - { - "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.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", - "parameters": [ - { - "maximum": 90, - "minimum": 24, - "type": "integer", - "default": 90, - "description": "持续时间 (小时或天数)`", - "name": "duration", - "in": "query" - }, - { - "enum": [ - "hour", - "day" - ], - "type": "string", - "default": "day", - "description": "精度: \"hour\", \"day\"", - "name": "precision", - "in": "query", - "required": true - }, - { - "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.TimeStat" - } - } - } - ] - } - } - } - } - }, - "/api/v1/dashboard/user-code-rank": { - "get": { - "description": "用户贡献榜", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Dashboard" - ], - "summary": "用户贡献榜", - "operationId": "user-code-rank-dashboard", - "parameters": [ - { - "maximum": 90, - "minimum": 24, - "type": "integer", - "default": 90, - "description": "持续时间 (小时或天数)`", - "name": "duration", - "in": "query" - }, - { - "enum": [ - "hour", - "day" - ], - "type": "string", - "default": "day", - "description": "精度: \"hour\", \"day\"", - "name": "precision", - "in": "query", - "required": true - }, - { - "type": "string", - "description": "用户ID,可选参数", - "name": "user_id", - "in": "query" - } - ], - "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": [ - { - "maximum": 90, - "minimum": 24, - "type": "integer", - "default": 90, - "description": "持续时间 (小时或天数)`", - "name": "duration", - "in": "query" - }, - { - "enum": [ - "hour", - "day" - ], - "type": "string", - "default": "day", - "description": "精度: \"hour\", \"day\"", - "name": "precision", - "in": "query", - "required": true - }, - { - "type": "string", - "description": "用户ID,可选参数", - "name": "user_id", - "in": "query" - } - ], - "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": [ - { - "maximum": 90, - "minimum": 24, - "type": "integer", - "default": 90, - "description": "持续时间 (小时或天数)`", - "name": "duration", - "in": "query" - }, - { - "enum": [ - "hour", - "day" - ], - "type": "string", - "default": "day", - "description": "精度: \"hour\", \"day\"", - "name": "precision", - "in": "query", - "required": true - }, - { - "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/ide/codesnippet/context": { - "post": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "为IDE端提供代码片段上下文检索功能,使用API Key认证。支持单个查询和批量查询。", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "CodeSnippet" - ], - "summary": "IDE端上下文检索", - "operationId": "get-context", - "parameters": [ - { - "description": "检索请求参数", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/internal_codesnippet_handler_http_v1.GetContextReq" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "allOf": [ - { - "$ref": "#/definitions/web.Resp" - }, - { - "type": "object", - "properties": { - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/domain.CodeSnippet" - } - } - } - } - ] - } - } - } - } - }, - "/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" - } - } - } - ] - } - } - } - }, - "delete": { - "description": "删除模型", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Model" - ], - "summary": "删除模型", - "operationId": "delete-model", - "parameters": [ - { - "type": "string", - "description": "模型ID", - "name": "id", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/web.Resp" - } - } - } - } - }, - "/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/provider/supported": { - "get": { - "description": "获取供应商支持的模型列表", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Model" - ], - "summary": "获取供应商支持的模型列表", - "operationId": "get-provider-model-list", - "parameters": [ - { - "type": "string", - "name": "api_header", - "in": "query" - }, - { - "type": "string", - "name": "api_key", - "in": "query" - }, - { - "type": "string", - "name": "base_url", - "in": "query", - "required": true - }, - { - "enum": [ - "SiliconFlow", - "OpenAI", - "Ollama", - "DeepSeek", - "Moonshot", - "AzureOpenAI", - "BaiZhiCloud", - "Hunyuan", - "BaiLian", - "Volcengine" - ], - "type": "string", - "x-enum-varnames": [ - "ModelProviderSiliconFlow", - "ModelProviderOpenAI", - "ModelProviderOllama", - "ModelProviderDeepSeek", - "ModelProviderMoonshot", - "ModelProviderAzureOpenAI", - "ModelProviderBaiZhiCloud", - "ModelProviderHunyuan", - "ModelProviderBaiLian", - "ModelProviderVolcengine" - ], - "name": "provider", - "in": "query", - "required": true - }, - { - "enum": [ - "llm", - "coder", - "embedding", - "audio", - "reranker" - ], - "type": "string", - "x-enum-varnames": [ - "ModelTypeLLM", - "ModelTypeCoder", - "ModelTypeEmbedding", - "ModelTypeAudio", - "ModelTypeReranker" - ], - "name": "type", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "allOf": [ - { - "$ref": "#/definitions/web.Resp" - }, - { - "type": "object", - "properties": { - "data": { - "$ref": "#/definitions/domain.GetProviderModelListResp" - } - } - } - ] - } - } - } - } - }, - "/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/chat/info": { - "get": { - "description": "获取对话内容", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "User Record" - ], - "summary": "获取对话内容", - "operationId": "user-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" - } - } - } - ] - } - }, - "401": { - "description": "Unauthorized", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/v1/user/chat/record": { - "get": { - "description": "获取用户对话记录", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "User Record" - ], - "summary": "获取用户对话记录", - "operationId": "user-list-chat-record", - "parameters": [ - { - "type": "string", - "description": "作者", - "name": "author", - "in": "query" - }, - { - "type": "boolean", - "description": "是否接受筛选", - "name": "is_accept", - "in": "query" - }, - { - "type": "string", - "description": "语言", - "name": "language", - "in": "query" - }, - { - "type": "string", - "description": "下一页标识", - "name": "next_token", - "in": "query" - }, - { - "minimum": 1, - "type": "integer", - "default": 1, - "description": "分页", - "name": "page", - "in": "query" - }, - { - "minimum": 1, - "type": "integer", - "default": 10, - "description": "每页多少条记录", - "name": "size", - "in": "query" - }, - { - "type": "string", - "description": "工作模式", - "name": "work_mode", - "in": "query" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "allOf": [ - { - "$ref": "#/definitions/web.Resp" - }, - { - "type": "object", - "properties": { - "data": { - "$ref": "#/definitions/domain.ListChatRecordResp" - } - } - } - ] - } - }, - "401": { - "description": "Unauthorized", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/v1/user/completion/info": { - "get": { - "description": "获取补全内容", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "User Record" - ], - "summary": "获取补全内容", - "operationId": "user-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" - } - } - } - ] - } - }, - "401": { - "description": "Unauthorized", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/v1/user/completion/record": { - "get": { - "description": "获取补全记录", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "User Record" - ], - "summary": "获取补全记录", - "operationId": "user-list-completion-record", - "parameters": [ - { - "type": "string", - "description": "作者", - "name": "author", - "in": "query" - }, - { - "type": "boolean", - "description": "是否接受筛选", - "name": "is_accept", - "in": "query" - }, - { - "type": "string", - "description": "语言", - "name": "language", - "in": "query" - }, - { - "type": "string", - "description": "下一页标识", - "name": "next_token", - "in": "query" - }, - { - "minimum": 1, - "type": "integer", - "default": 1, - "description": "分页", - "name": "page", - "in": "query" - }, - { - "minimum": 1, - "type": "integer", - "default": 10, - "description": "每页多少条记录", - "name": "size", - "in": "query" - }, - { - "type": "string", - "description": "工作模式", - "name": "work_mode", - "in": "query" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "allOf": [ - { - "$ref": "#/definitions/web.Resp" - }, - { - "type": "object", - "properties": { - "data": { - "$ref": "#/definitions/domain.ListCompletionRecordResp" - } - } - } - ] - } - }, - "401": { - "description": "Unauthorized", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/v1/user/dashboard/events": { - "get": { - "description": "获取用户事件", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "User Dashboard" - ], - "summary": "获取用户事件", - "operationId": "user-dashboard-events", - "parameters": [ - { - "maximum": 90, - "minimum": 24, - "type": "integer", - "default": 90, - "description": "持续时间 (小时或天数)`", - "name": "duration", - "in": "query" - }, - { - "enum": [ - "hour", - "day" - ], - "type": "string", - "default": "day", - "description": "精度: \"hour\", \"day\"", - "name": "precision", - "in": "query", - "required": true - }, - { - "type": "string", - "description": "用户ID,可选参数", - "name": "user_id", - "in": "query" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "allOf": [ - { - "$ref": "#/definitions/web.Resp" - }, - { - "type": "object", - "properties": { - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/domain.UserEvent" - } - } - } - } - ] - } - }, - "401": { - "description": "Unauthorized", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/v1/user/dashboard/heatmap": { - "get": { - "description": "用户热力图", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "User Dashboard" - ], - "summary": "用户热力图", - "operationId": "user-dashboard-heatmap", - "responses": { - "200": { - "description": "OK", - "schema": { - "allOf": [ - { - "$ref": "#/definitions/web.Resp" - }, - { - "type": "object", - "properties": { - "data": { - "$ref": "#/definitions/domain.UserHeatmapResp" - } - } - } - ] - } - }, - "401": { - "description": "Unauthorized", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/v1/user/dashboard/stat": { - "get": { - "description": "获取用户统计信息", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "User Dashboard" - ], - "summary": "获取用户统计信息", - "operationId": "user-dashboard-stat", - "parameters": [ - { - "maximum": 90, - "minimum": 24, - "type": "integer", - "default": 90, - "description": "持续时间 (小时或天数)`", - "name": "duration", - "in": "query" - }, - { - "enum": [ - "hour", - "day" - ], - "type": "string", - "default": "day", - "description": "精度: \"hour\", \"day\"", - "name": "precision", - "in": "query", - "required": true - }, - { - "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" - } - } - } - ] - } - }, - "401": { - "description": "Unauthorized", - "schema": { - "type": "string" - } - } - } - } - }, - "/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" - }, - { - "minimum": 1, - "type": "integer", - "default": 1, - "description": "分页", - "name": "page", - "in": "query" - }, - { - "minimum": 1, - "type": "integer", - "default": 10, - "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" - }, - { - "minimum": 1, - "type": "integer", - "default": 1, - "description": "分页", - "name": "page", - "in": "query" - }, - { - "minimum": 1, - "type": "integer", - "default": 10, - "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/logout": { - "post": { - "description": "用户登出", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "User" - ], - "summary": "用户登出", - "operationId": "logout", - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/web.Resp" - } - } - } - } - }, - "/api/v1/user/oauth/callback": { - "get": { - "description": "用户 OAuth 回调", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "User" - ], - "summary": "用户 OAuth 回调", - "operationId": "user-oauth-callback", - "parameters": [ - { - "type": "string", - "name": "code", - "in": "query", - "required": true - }, - { - "type": "string", - "name": "state", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "allOf": [ - { - "$ref": "#/definitions/web.Resp" - }, - { - "type": "object", - "properties": { - "data": { - "type": "string" - } - } - } - ] - } - } - } - } - }, - "/api/v1/user/oauth/signup-or-in": { - "get": { - "description": "用户 OAuth 登录或注册", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "User" - ], - "summary": "用户 OAuth 登录或注册", - "operationId": "user-oauth-signup-or-in", - "parameters": [ - { - "type": "string", - "description": "邀请码", - "name": "inviate_code", - "in": "query" - }, - { - "enum": [ - "email", - "dingtalk", - "custom" - ], - "type": "string", - "x-enum-varnames": [ - "UserPlatformEmail", - "UserPlatformDingTalk", - "UserPlatformCustom" - ], - "description": "第三方平台 dingtalk", - "name": "platform", - "in": "query", - "required": true - }, - { - "type": "string", - "description": "登录成功后跳转的 URL", - "name": "redirect_url", - "in": "query" - }, - { - "type": "string", - "description": "会话ID", - "name": "session_id", - "in": "query" - }, - { - "enum": [ - "plugin", - "browser" - ], - "type": "string", - "default": "plugin", - "x-enum-varnames": [ - "LoginSourcePlugin", - "LoginSourceBrowser" - ], - "description": "登录来源 plugin: 插件 browser: 浏览器; 默认为 plugin", - "name": "source", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "allOf": [ - { - "$ref": "#/definitions/web.Resp" - }, - { - "type": "object", - "properties": { - "data": { - "$ref": "#/definitions/domain.OAuthURLResp" - } - } - } - ] - } - } - } - } - }, - "/api/v1/user/profile": { - "get": { - "description": "获取用户信息", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "User Manage" - ], - "summary": "获取用户信息", - "operationId": "user-profile", - "responses": { - "200": { - "description": "OK", - "schema": { - "allOf": [ - { - "$ref": "#/definitions/web.Resp" - }, - { - "type": "object", - "properties": { - "data": { - "$ref": "#/definitions/domain.User" - } - } - } - ] - } - }, - "401": { - "description": "Unauthorized", - "schema": { - "$ref": "#/definitions/web.Resp" - } - } - } - }, - "put": { - "description": "更新用户信息", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "User Manage" - ], - "summary": "更新用户信息", - "operationId": "user-update-profile", - "parameters": [ - { - "description": "param", - "name": "req", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.ProfileUpdateReq" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "allOf": [ - { - "$ref": "#/definitions/web.Resp" - }, - { - "type": "object", - "properties": { - "data": { - "$ref": "#/definitions/domain.User" - } - } - } - ] - } - }, - "401": { - "description": "Unauthorized", - "schema": { - "$ref": "#/definitions/web.Resp" - } - } - } - } - }, - "/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" - } - } - } - ] - } - } - } - } - }, - "/api/v1/workspace/files": { - "get": { - "description": "分页获取工作区文件列表", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "WorkspaceFile" - ], - "summary": "获取工作区文件列表", - "operationId": "list-workspace-files", - "parameters": [ - { - "type": "string", - "description": "编程语言筛选", - "name": "language", - "in": "query" - }, - { - "type": "string", - "description": "下一页标识", - "name": "next_token", - "in": "query" - }, - { - "minimum": 1, - "type": "integer", - "default": 1, - "description": "分页", - "name": "page", - "in": "query" - }, - { - "type": "string", - "description": "搜索关键词(文件路径)", - "name": "search", - "in": "query" - }, - { - "minimum": 1, - "type": "integer", - "default": 10, - "description": "每页多少条记录", - "name": "size", - "in": "query" - }, - { - "type": "string", - "description": "用户ID", - "name": "user_id", - "in": "query" - }, - { - "type": "string", - "description": "工作区ID", - "name": "workspace_id", - "in": "query" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "allOf": [ - { - "$ref": "#/definitions/web.Resp" - }, - { - "type": "object", - "properties": { - "data": { - "$ref": "#/definitions/domain.ListWorkspaceFileResp" - } - } - } - ] - } - } - } - }, - "post": { - "description": "创建一个新的工作区文件", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "WorkspaceFile" - ], - "summary": "创建工作区文件", - "operationId": "create-workspace-file", - "parameters": [ - { - "description": "文件信息", - "name": "file", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.CreateWorkspaceFileReq" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "allOf": [ - { - "$ref": "#/definitions/web.Resp" - }, - { - "type": "object", - "properties": { - "data": { - "$ref": "#/definitions/domain.WorkspaceFile" - } - } - } - ] - } - } - } - } - }, - "/api/v1/workspace/files/batch": { - "put": { - "description": "批量更新多个工作区文件", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "WorkspaceFile" - ], - "summary": "批量更新工作区文件", - "operationId": "batch-update-workspace-files", - "parameters": [ - { - "description": "文件列表", - "name": "files", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.BatchUpdateWorkspaceFileReq" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "allOf": [ - { - "$ref": "#/definitions/web.Resp" - }, - { - "type": "object", - "properties": { - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/domain.WorkspaceFile" - } - } - } - } - ] - } - } - } - }, - "post": { - "description": "批量创建多个工作区文件", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "WorkspaceFile" - ], - "summary": "批量创建工作区文件", - "operationId": "batch-create-workspace-files", - "parameters": [ - { - "description": "文件列表", - "name": "files", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.BatchCreateWorkspaceFileReq" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "allOf": [ - { - "$ref": "#/definitions/web.Resp" - }, - { - "type": "object", - "properties": { - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/domain.WorkspaceFile" - } - } - } - } - ] - } - } - } - } - }, - "/api/v1/workspace/files/by-path": { - "get": { - "description": "根据用户ID、项目ID和文件路径获取工作区文件", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "WorkspaceFile" - ], - "summary": "根据路径获取工作区文件", - "operationId": "get-workspace-file-by-path", - "parameters": [ - { - "type": "string", - "description": "用户ID", - "name": "user_id", - "in": "query" - }, - { - "type": "string", - "description": "项目ID", - "name": "project_id", - "in": "query", - "required": true - }, - { - "type": "string", - "description": "文件路径", - "name": "path", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "allOf": [ - { - "$ref": "#/definitions/web.Resp" - }, - { - "type": "object", - "properties": { - "data": { - "$ref": "#/definitions/domain.WorkspaceFile" - } - } - } - ] - } - } - } - } - }, - "/api/v1/workspace/files/get-and-save": { - "post": { - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "WorkspaceFile" - ], - "summary": "获取并保存工作区文件", - "parameters": [ - { - "description": "请求参数", - "name": "req", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.GetAndSaveReq" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/web.Resp" - } - } - } - } - }, - "/api/v1/workspace/files/sync": { - "post": { - "description": "同步本地文件到工作区,智能检测新增、修改和删除", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "WorkspaceFile" - ], - "summary": "同步工作区文件", - "operationId": "sync-workspace-files", - "parameters": [ - { - "description": "同步信息", - "name": "sync", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.SyncWorkspaceFileReq" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "allOf": [ - { - "$ref": "#/definitions/web.Resp" - }, - { - "type": "object", - "properties": { - "data": { - "$ref": "#/definitions/domain.SyncWorkspaceFileResp" - } - } - } - ] - } - } - } - } - }, - "/api/v1/workspace/files/{id}": { - "get": { - "description": "根据文件ID获取工作区文件详情", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "WorkspaceFile" - ], - "summary": "根据ID获取工作区文件", - "operationId": "get-workspace-file-by-id", - "parameters": [ - { - "type": "string", - "description": "文件ID", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "allOf": [ - { - "$ref": "#/definitions/web.Resp" - }, - { - "type": "object", - "properties": { - "data": { - "$ref": "#/definitions/domain.WorkspaceFile" - } - } - } - ] - } - } - } - }, - "put": { - "description": "更新指定的工作区文件", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "WorkspaceFile" - ], - "summary": "更新工作区文件", - "operationId": "update-workspace-file", - "parameters": [ - { - "type": "string", - "description": "文件ID", - "name": "id", - "in": "path", - "required": true - }, - { - "description": "更新信息", - "name": "file", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.UpdateWorkspaceFileReq" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "allOf": [ - { - "$ref": "#/definitions/web.Resp" - }, - { - "type": "object", - "properties": { - "data": { - "$ref": "#/definitions/domain.WorkspaceFile" - } - } - } - ] - } - } - } - }, - "delete": { - "description": "删除指定的工作区文件", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "WorkspaceFile" - ], - "summary": "删除工作区文件", - "operationId": "delete-workspace-file", - "parameters": [ - { - "type": "string", - "description": "文件ID", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/web.Resp" - } - } - } - } - }, - "/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/health": { - "get": { - "description": "固定回包 `{\"code\": 0, \"data\": \"MonkeyCode\"}`", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "OpenAIV1" - ], - "summary": "健康检查", - "operationId": "health", - "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" - } - } - } - ] - } - } - } - } - }, - "/v1/report": { - "post": { - "description": "报告,支持多种操作:accept(接受补全)、suggest(建议)、reject(拒绝补全并记录用户输入)、file_written(文件写入)", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "OpenAIV1" - ], - "summary": "报告", - "operationId": "report", - "parameters": [ - { - "description": "报告请求", - "name": "param", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.ReportReq" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/web.Resp" - } - } - } - } - } - }, - "definitions": { - "consts.AdminStatus": { - "type": "string", - "enum": [ - "active", - "inactive" - ], - "x-enum-varnames": [ - "AdminStatusActive", - "AdminStatusInactive" - ] - }, - "consts.ChatRole": { - "type": "string", - "enum": [ - "user", - "assistant", - "system" - ], - "x-enum-varnames": [ - "ChatRoleUser", - "ChatRoleAssistant", - "ChatRoleSystem" - ] - }, - "consts.LoginSource": { - "type": "string", - "enum": [ - "plugin", - "browser" - ], - "x-enum-varnames": [ - "LoginSourcePlugin", - "LoginSourceBrowser" - ] - }, - "consts.ModelProvider": { - "type": "string", - "enum": [ - "SiliconFlow", - "OpenAI", - "Ollama", - "DeepSeek", - "Moonshot", - "AzureOpenAI", - "BaiZhiCloud", - "Hunyuan", - "BaiLian", - "Volcengine" - ], - "x-enum-varnames": [ - "ModelProviderSiliconFlow", - "ModelProviderOpenAI", - "ModelProviderOllama", - "ModelProviderDeepSeek", - "ModelProviderMoonshot", - "ModelProviderAzureOpenAI", - "ModelProviderBaiZhiCloud", - "ModelProviderHunyuan", - "ModelProviderBaiLian", - "ModelProviderVolcengine" - ] - }, - "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.ReportAction": { - "type": "string", - "enum": [ - "accept", - "suggest", - "file_written", - "reject", - "new_task", - "feedback_task", - "abort_task" - ], - "x-enum-varnames": [ - "ReportActionAccept", - "ReportActionSuggest", - "ReportActionFileWritten", - "ReportActionReject", - "ReportActionNewTask", - "ReportActionFeedbackTask", - "ReportActionAbortTask" - ] - }, - "consts.UserPlatform": { - "type": "string", - "enum": [ - "email", - "dingtalk", - "custom" - ], - "x-enum-varnames": [ - "UserPlatformEmail", - "UserPlatformDingTalk", - "UserPlatformCustom" - ] - }, - "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.BatchCreateWorkspaceFileReq": { - "type": "object", - "required": [ - "files", - "user_id", - "workspace_id" - ], - "properties": { - "files": { - "description": "文件列表", - "type": "array", - "items": { - "$ref": "#/definitions/domain.CreateWorkspaceFileReq" - } - }, - "user_id": { - "description": "用户ID", - "type": "string" - }, - "workspace_id": { - "description": "工作区ID", - "type": "string" - } - } - }, - "domain.BatchUpdateWorkspaceFileReq": { - "type": "object", - "required": [ - "files" - ], - "properties": { - "files": { - "description": "文件列表", - "type": "array", - "items": { - "$ref": "#/definitions/domain.UpdateWorkspaceFileReq" - } - } - } - }, - "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.ChatContent": { - "type": "object", - "properties": { - "content": { - "description": "内容", - "type": "string" - }, - "created_at": { - "type": "integer" - }, - "role": { - "description": "角色,如user: 用户的提问 assistant: 机器人回复 system: 系统消息", - "allOf": [ - { - "$ref": "#/definitions/consts.ChatRole" - } - ] - } - } - }, - "domain.ChatInfo": { - "type": "object", - "properties": { - "contents": { - "description": "消息内容", - "type": "array", - "items": { - "$ref": "#/definitions/domain.ChatContent" - } - }, - "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", - "type" - ], - "properties": { - "api_base": { - "description": "接口地址", - "type": "string" - }, - "api_header": { - "type": "string" - }, - "api_key": { - "description": "接口密钥", - "type": "string" - }, - "api_version": { - "type": "string" - }, - "model_name": { - "description": "模型名称", - "type": "string" - }, - "provider": { - "description": "提供商", - "allOf": [ - { - "$ref": "#/definitions/consts.ModelProvider" - } - ] - }, - "type": { - "enum": [ - "llm", - "coder", - "embedding", - "rerank" - ], - "allOf": [ - { - "$ref": "#/definitions/consts.ModelType" - } - ] - } - } - }, - "domain.CodeLanguageType": { - "type": "string", - "enum": [ - "go", - "python", - "java", - "javascript", - "typescript", - "jsx", - "tsx", - "html", - "css", - "php", - "rust", - "swift", - "kotlin", - "c", - "cpp" - ], - "x-enum-varnames": [ - "CodeLanguageTypeGo", - "CodeLanguageTypePython", - "CodeLanguageTypeJava", - "CodeLanguageTypeJavaScript", - "CodeLanguageTypeTypeScript", - "CodeLanguageTypeJSX", - "CodeLanguageTypeTSX", - "CodeLanguageTypeHTML", - "CodeLanguageTypeCSS", - "CodeLanguageTypePHP", - "CodeLanguageTypeRust", - "CodeLanguageTypeSwift", - "CodeLanguageTypeKotlin", - "CodeLanguageTypeC", - "CodeLanguageTypeCpp" - ] - }, - "domain.CodeSnippet": { - "type": "object", - "properties": { - "definition": { - "description": "结构化信息", - "type": "object", - "additionalProperties": {} - }, - "definitionText": { - "description": "定义文本", - "type": "string" - }, - "dependencies": { - "description": "依赖项", - "type": "array", - "items": { - "type": "string" - } - }, - "endColumn": { - "description": "结束列号", - "type": "integer" - }, - "endLine": { - "description": "结束行号", - "type": "integer" - }, - "field": { - "description": "容器名称", - "type": "string" - }, - "fileHash": { - "description": "内容哈希", - "type": "string" - }, - "filePath": { - "description": "文件路径", - "type": "string" - }, - "id": { - "description": "代码片段ID", - "type": "string" - }, - "language": { - "description": "编程语言", - "type": "string" - }, - "name": { - "description": "代码片段名称", - "type": "string" - }, - "namespace": { - "description": "命名空间", - "type": "string" - }, - "parameters": { - "description": "参数列表", - "type": "array", - "items": { - "type": "object", - "additionalProperties": {} - } - }, - "rangeText": { - "description": "代码片段内容", - "type": "string" - }, - "scope": { - "description": "作用域信息", - "type": "array", - "items": { - "type": "string" - } - }, - "signature": { - "description": "函数签名", - "type": "string" - }, - "startColumn": { - "description": "起始列号", - "type": "integer" - }, - "startLine": { - "description": "起始行号", - "type": "integer" - }, - "type": { - "description": "代码片段类型", - "type": "string" - }, - "workspace_file_id": { - "description": "关联的workspace file ID", - "type": "string" - } - } - }, - "domain.CompletionData": { - "type": "object", - "properties": { - "code_lines": { - "description": "代码行数", - "type": "integer" - }, - "completion": { - "description": "LLM生成的补全代码", - "type": "string" - }, - "created_at": { - "description": "创建时间戳", - "type": "integer" - }, - "cursor_position": { - "description": "光标位置 {\"line\": 10, \"column\": 5}", - "type": "object", - "additionalProperties": {} - }, - "input_tokens": { - "description": "输入token数", - "type": "integer" - }, - "is_accept": { - "description": "用户是否接受补全", - "type": "boolean" - }, - "is_suggested": { - "description": "是否为建议模式", - "type": "boolean" - }, - "model_id": { - "description": "模型ID", - "type": "string" - }, - "model_name": { - "description": "模型名称", - "type": "string" - }, - "model_type": { - "description": "模型类型", - "type": "string" - }, - "output_tokens": { - "description": "输出token数", - "type": "integer" - }, - "program_language": { - "description": "编程语言", - "type": "string" - }, - "prompt": { - "description": "用户输入的提示", - "type": "string" - }, - "request_id": { - "description": "请求ID", - "type": "string" - }, - "source_code": { - "description": "当前文件原文", - "type": "string" - }, - "task_id": { - "description": "任务ID", - "type": "string" - }, - "updated_at": { - "description": "更新时间戳", - "type": "integer" - }, - "user_id": { - "description": "用户ID", - "type": "string" - }, - "user_input": { - "description": "用户最终输入的内容", - "type": "string" - }, - "work_mode": { - "description": "工作模式", - "type": "string" - } - } - }, - "domain.CompletionInfo": { - "type": "object", - "properties": { - "content": { - "type": "string" - }, - "created_at": { - "type": "integer" - }, - "id": { - "type": "string" - }, - "prompt": { - "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", - "required": [ - "api_base", - "model_name", - "provider" - ], - "properties": { - "api_base": { - "description": "接口地址 如:https://api.qwen.com", - "type": "string" - }, - "api_header": { - "type": "string" - }, - "api_key": { - "description": "接口密钥 如:sk-xxxx", - "type": "string" - }, - "api_version": { - "type": "string" - }, - "model_name": { - "description": "模型名称 如: deepseek-v3", - "type": "string" - }, - "model_type": { - "description": "模型类型 llm:对话模型 coder:代码模型", - "allOf": [ - { - "$ref": "#/definitions/consts.ModelType" - } - ] - }, - "param": { - "description": "高级参数", - "allOf": [ - { - "$ref": "#/definitions/domain.ModelParam" - } - ] - }, - "provider": { - "description": "提供商", - "enum": [ - "SiliconFlow", - "OpenAI", - "Ollama", - "DeepSeek", - "Moonshot", - "AzureOpenAI", - "BaiZhiCloud", - "Hunyuan", - "BaiLian", - "Volcengine", - "Other" - ], - "allOf": [ - { - "$ref": "#/definitions/consts.ModelProvider" - } - ] - }, - "show_name": { - "description": "模型显示名称", - "type": "string" - } - } - }, - "domain.CreateWorkspaceFileReq": { - "type": "object", - "required": [ - "hash", - "path", - "user_id", - "workspace_id" - ], - "properties": { - "content": { - "description": "文件内容", - "type": "string" - }, - "hash": { - "description": "文件哈希", - "type": "string" - }, - "language": { - "description": "编程语言", - "type": "string" - }, - "path": { - "description": "文件路径", - "type": "string" - }, - "size": { - "description": "文件大小", - "type": "integer" - }, - "user_id": { - "description": "用户ID", - "type": "string" - }, - "workspace_id": { - "description": "工作区ID", - "type": "string" - } - } - }, - "domain.CustomOAuth": { - "type": "object", - "properties": { - "access_token_url": { - "description": "自定义OAuth访问令牌URL", - "type": "string" - }, - "authorize_url": { - "description": "自定义OAuth授权URL", - "type": "string" - }, - "avatar_field": { - "description": "用户信息回包中的头像URL字段名", - "type": "string" - }, - "client_id": { - "description": "自定义客户端ID", - "type": "string" - }, - "client_secret": { - "description": "自定义客户端密钥", - "type": "string" - }, - "email_field": { - "description": "用户信息回包中的邮箱字段名", - "type": "string" - }, - "enable": { - "description": "自定义OAuth开关", - "type": "boolean" - }, - "id_field": { - "description": "用户信息回包中的ID字段名", - "type": "string" - }, - "name_field": { - "description": "用户信息回包中的用户名字段名", - "type": "string" - }, - "scopes": { - "description": "自定义OAuth Scope列表", - "type": "array", - "items": { - "type": "string" - } - }, - "userinfo_url": { - "description": "自定义OAuth用户信息URL", - "type": "string" - } - } - }, - "domain.CustomOAuthReq": { - "type": "object", - "properties": { - "access_token_url": { - "description": "自定义OAuth访问令牌URL", - "type": "string" - }, - "authorize_url": { - "description": "自定义OAuth授权URL", - "type": "string" - }, - "avatar_field": { - "description": "用户信息回包中的头像URL字段名", - "type": "string" - }, - "client_id": { - "description": "自定义客户端ID", - "type": "string" - }, - "client_secret": { - "description": "自定义客户端密钥", - "type": "string" - }, - "email_field": { - "description": "用户信息回包中的邮箱字段名", - "type": "string" - }, - "enable": { - "description": "自定义OAuth开关", - "type": "boolean" - }, - "id_field": { - "description": "用户信息回包中的ID字段名", - "type": "string" - }, - "name_field": { - "description": "用户信息回包中的用户名字段名", - "type": "string" - }, - "scopes": { - "description": "自定义OAuth Scope列表", - "type": "array", - "items": { - "type": "string" - } - }, - "userinfo_url": { - "description": "自定义OAuth用户信息URL", - "type": "string" - } - } - }, - "domain.DingtalkOAuth": { - "type": "object", - "properties": { - "client_id": { - "description": "钉钉客户端ID", - "type": "string" - }, - "client_secret": { - "description": "钉钉客户端密钥", - "type": "string" - }, - "enable": { - "description": "钉钉OAuth开关", - "type": "boolean" - } - } - }, - "domain.DingtalkOAuthReq": { - "type": "object", - "properties": { - "client_id": { - "description": "钉钉客户端ID", - "type": "string" - }, - "client_secret": { - "description": "钉钉客户端密钥", - "type": "string" - }, - "enable": { - "description": "钉钉OAuth开关", - "type": "boolean" - } - } - }, - "domain.ExportCompletionDataResp": { - "type": "object", - "properties": { - "data": { - "description": "补全数据列表", - "type": "array", - "items": { - "$ref": "#/definitions/domain.CompletionData" - } - }, - "total_count": { - "description": "总记录数", - "type": "integer" - } - } - }, - "domain.FileMeta": { - "type": "object", - "properties": { - "content": { - "description": "文件内容(可选)", - "type": "string" - }, - "fileExtension": { - "type": "string" - }, - "fileHash": { - "description": "文件哈希(可选)", - "type": "string" - }, - "filePath": { - "type": "string" - }, - "language": { - "description": "语言类型(可选)", - "allOf": [ - { - "$ref": "#/definitions/domain.CodeLanguageType" - } - ] - } - } - }, - "domain.GetAndSaveReq": { - "type": "object", - "required": [ - "code_files", - "user_id", - "workspace_id" - ], - "properties": { - "code_files": { - "description": "代码文件信息", - "type": "array", - "items": { - "$ref": "#/definitions/domain.FileMeta" - } - }, - "user_id": { - "description": "用户ID", - "type": "string" - }, - "workspace_id": { - "description": "项目ID", - "type": "string" - } - } - }, - "domain.GetProviderModelListResp": { - "type": "object", - "properties": { - "models": { - "type": "array", - "items": { - "$ref": "#/definitions/domain.ProviderModelListItem" - } - } - } - }, - "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.IndexResult": { - "type": "object", - "properties": { - "definition": { - "type": "object", - "properties": { - "name": { - "type": "string" - }, - "returnType": { - "type": "string" - }, - "type": { - "type": "string" - } - } - }, - "definitionText": { - "type": "string" - }, - "endLine": { - "type": "integer" - }, - "fileHash": { - "type": "string" - }, - "filePath": { - "type": "string" - }, - "implementText": { - "type": "string" - }, - "language": { - "type": "string" - }, - "name": { - "type": "string" - }, - "rangeText": { - "type": "string" - }, - "scope": {}, - "signature": { - "type": "string" - }, - "startLine": { - "type": "integer" - }, - "type": { - "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.ListWorkspaceFileResp": { - "type": "object", - "properties": { - "files": { - "type": "array", - "items": { - "$ref": "#/definitions/domain.WorkspaceFile" - } - }, - "has_next_page": { - "type": "boolean" - }, - "next_token": { - "type": "string" - }, - "total_count": { - "type": "integer" - } - } - }, - "domain.LoginReq": { - "type": "object", - "required": [ - "source" - ], - "properties": { - "password": { - "description": "密码", - "type": "string" - }, - "session_id": { - "description": "会话Id插件登录时必填", - "type": "string" - }, - "source": { - "description": "登录来源 plugin: 插件 browser: 浏览器; 默认为 plugin", - "default": "plugin", - "allOf": [ - { - "$ref": "#/definitions/consts.LoginSource" - } - ] - }, - "username": { - "description": "用户名", - "type": "string" - } - } - }, - "domain.LoginResp": { - "type": "object", - "properties": { - "redirect_url": { - "description": "重定向URL", - "type": "string" - }, - "user": { - "description": "用户信息", - "allOf": [ - { - "$ref": "#/definitions/domain.User" - } - ] - } - } - }, - "domain.Model": { - "type": "object", - "properties": { - "api_base": { - "description": "接口地址 如:https://api.qwen.com", - "type": "string" - }, - "api_header": { - "description": "接口头 如:Authorization: Bearer sk-xxxx", - "type": "string" - }, - "api_key": { - "description": "接口密钥 如:sk-xxxx", - "type": "string" - }, - "api_version": { - "description": "接口版本 如:2023-05-15", - "type": "string" - }, - "created_at": { - "description": "创建时间", - "type": "integer" - }, - "id": { - "description": "模型ID", - "type": "string" - }, - "input": { - "description": "输入token数", - "type": "integer" - }, - "is_active": { - "description": "是否启用", - "type": "boolean" - }, - "is_internal": { - "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" - }, - "param": { - "description": "高级参数", - "allOf": [ - { - "$ref": "#/definitions/domain.ModelParam" - } - ] - }, - "provider": { - "description": "提供商", - "allOf": [ - { - "$ref": "#/definitions/consts.ModelProvider" - } - ] - }, - "show_name": { - "description": "模型显示名称", - "type": "string" - }, - "status": { - "description": "状态 active:启用 inactive:禁用", - "allOf": [ - { - "$ref": "#/definitions/consts.ModelStatus" - } - ] - }, - "updated_at": { - "description": "更新时间", - "type": "integer" - } - } - }, - "domain.ModelBasic": { - "type": "object", - "required": [ - "provider" - ], - "properties": { - "api_base": { - "description": "接口地址 如:https://api.qwen.com", - "type": "string" - }, - "name": { - "description": "模型名称", - "type": "string" - }, - "provider": { - "description": "提供商", - "enum": [ - "SiliconFlow", - "OpenAI", - "Ollama", - "DeepSeek", - "Moonshot", - "AzureOpenAI", - "BaiZhiCloud", - "Hunyuan", - "BaiLian", - "Volcengine", - "Other" - ], - "allOf": [ - { - "$ref": "#/definitions/consts.ModelProvider" - } - ] - } - } - }, - "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.ModelParam": { - "type": "object", - "properties": { - "context_window": { - "type": "integer" - }, - "max_tokens": { - "type": "integer" - }, - "r1_enabled": { - "type": "boolean" - }, - "support_computer_use": { - "type": "boolean" - }, - "support_images": { - "type": "boolean" - }, - "support_prompt_cache": { - "type": "boolean" - } - } - }, - "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.OAuthURLResp": { - "type": "object", - "properties": { - "url": { - "type": "string" - } - } - }, - "domain.ProfileUpdateReq": { - "type": "object", - "properties": { - "avatar": { - "description": "头像", - "type": "string" - }, - "old_password": { - "description": "旧密码", - "type": "string" - }, - "password": { - "description": "密码", - "type": "string" - }, - "username": { - "description": "用户名", - "type": "string" - } - } - }, - "domain.ProviderModel": { - "type": "object", - "properties": { - "models": { - "description": "模型列表", - "type": "array", - "items": { - "$ref": "#/definitions/domain.ModelBasic" - } - }, - "provider": { - "description": "提供商", - "type": "string" - } - } - }, - "domain.ProviderModelListItem": { - "type": "object", - "properties": { - "model": { - "type": "string" - } - } - }, - "domain.RegisterReq": { - "type": "object", - "required": [ - "code", - "email", - "password", - "username" - ], - "properties": { - "code": { - "description": "邀请码", - "type": "string" - }, - "email": { - "description": "邮箱", - "type": "string" - }, - "password": { - "description": "密码", - "type": "string" - }, - "username": { - "description": "用户名", - "type": "string" - } - } - }, - "domain.ReportReq": { - "type": "object", - "properties": { - "action": { - "$ref": "#/definitions/consts.ReportAction" - }, - "content": { - "description": "内容", - "type": "string" - }, - "cursor_position": { - "description": "光标位置(用于reject action)", - "type": "object", - "additionalProperties": {} - }, - "id": { - "description": "task_id or resp_id", - "type": "string" - }, - "mode": { - "description": "模式", - "type": "string" - }, - "source_code": { - "description": "当前文件的原文(用于reject action)", - "type": "string" - }, - "tool": { - "description": "工具", - "type": "string" - }, - "user_input": { - "description": "用户输入的新文本(用于reject action)", - "type": "string" - } - } - }, - "domain.Setting": { - "type": "object", - "properties": { - "base_url": { - "description": "base url 配置,为了支持前置代理", - "type": "string" - }, - "created_at": { - "description": "创建时间", - "type": "integer" - }, - "custom_oauth": { - "description": "自定义OAuth接入", - "allOf": [ - { - "$ref": "#/definitions/domain.CustomOAuth" - } - ] - }, - "dingtalk_oauth": { - "description": "钉钉OAuth接入", - "allOf": [ - { - "$ref": "#/definitions/domain.DingtalkOAuth" - } - ] - }, - "disable_password_login": { - "description": "是否禁用密码登录", - "type": "boolean" - }, - "enable_auto_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.SyncWorkspaceFileReq": { - "type": "object", - "required": [ - "files", - "user_id", - "workspace_id" - ], - "properties": { - "files": { - "description": "要同步的文件列表", - "type": "array", - "items": { - "$ref": "#/definitions/domain.CreateWorkspaceFileReq" - } - }, - "user_id": { - "description": "用户ID", - "type": "string" - }, - "workspace_id": { - "description": "工作区ID", - "type": "string" - } - } - }, - "domain.SyncWorkspaceFileResp": { - "type": "object", - "properties": { - "created": { - "description": "新创建的文件", - "type": "array", - "items": { - "$ref": "#/definitions/domain.WorkspaceFile" - } - }, - "deleted": { - "description": "删除的文件ID", - "type": "array", - "items": { - "type": "string" - } - }, - "total": { - "description": "处理的文件总数", - "type": "integer" - }, - "updated": { - "description": "更新的文件", - "type": "array", - "items": { - "$ref": "#/definitions/domain.WorkspaceFile" - } - } - } - }, - "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", - "required": [ - "provider" - ], - "properties": { - "api_base": { - "description": "接口地址 如:https://api.qwen.com", - "type": "string" - }, - "api_header": { - "type": "string" - }, - "api_key": { - "description": "接口密钥 如:sk-xxxx", - "type": "string" - }, - "api_version": { - "type": "string" - }, - "id": { - "description": "模型ID", - "type": "string" - }, - "model_name": { - "description": "模型名称", - "type": "string" - }, - "param": { - "description": "高级参数", - "allOf": [ - { - "$ref": "#/definitions/domain.ModelParam" - } - ] - }, - "provider": { - "description": "提供商", - "enum": [ - "SiliconFlow", - "OpenAI", - "Ollama", - "DeepSeek", - "Moonshot", - "AzureOpenAI", - "BaiZhiCloud", - "Hunyuan", - "BaiLian", - "Volcengine", - "Other" - ], - "allOf": [ - { - "$ref": "#/definitions/consts.ModelProvider" - } - ] - }, - "show_name": { - "description": "模型显示名称", - "type": "string" - }, - "status": { - "description": "状态 active:启用 inactive:禁用", - "allOf": [ - { - "$ref": "#/definitions/consts.ModelStatus" - } - ] - } - } - }, - "domain.UpdateSettingReq": { - "type": "object", - "properties": { - "base_url": { - "description": "base url 配置,为了支持前置代理", - "type": "string" - }, - "custom_oauth": { - "description": "自定义OAuth配置", - "allOf": [ - { - "$ref": "#/definitions/domain.CustomOAuthReq" - } - ] - }, - "dingtalk_oauth": { - "description": "钉钉OAuth配置", - "allOf": [ - { - "$ref": "#/definitions/domain.DingtalkOAuthReq" - } - ] - }, - "disable_password_login": { - "description": "是否禁用密码登录", - "type": "boolean" - }, - "enable_auto_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.UpdateWorkspaceFileReq": { - "type": "object", - "required": [ - "id" - ], - "properties": { - "content": { - "description": "文件内容", - "type": "string" - }, - "hash": { - "description": "文件哈希", - "type": "string" - }, - "id": { - "description": "文件ID", - "type": "string" - }, - "language": { - "description": "编程语言", - "type": "string" - }, - "size": { - "description": "文件大小", - "type": "integer" - } - } - }, - "domain.User": { - "type": "object", - "properties": { - "avatar_url": { - "description": "头像URL", - "type": "string" - }, - "created_at": { - "description": "创建时间", - "type": "integer" - }, - "email": { - "description": "邮箱", - "type": "string" - }, - "id": { - "description": "用户ID", - "type": "string" - }, - "is_deleted": { - "description": "是否删除", - "type": "boolean" - }, - "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" - }, - "user": { - "description": "用户信息", - "allOf": [ - { - "$ref": "#/definitions/domain.User" - } - ] - }, - "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_id": { - "description": "插件ID vscode", - "type": "string" - }, - "client_version": { - "description": "客户端版本", - "type": "string" - }, - "created_at": { - "description": "登录时间", - "type": "integer" - }, - "device": { - "description": "设备信息", - "type": "string" - }, - "hostname": { - "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": "总接受率", - "type": "number" - }, - "total_chats": { - "description": "总对话任务数", - "type": "integer" - }, - "total_completions": { - "description": "总补全任务数", - "type": "integer" - }, - "total_lines_of_code": { - "description": "总代码行数", - "type": "integer" - }, - "work_mode": { - "description": "工作模式占比", - "type": "array", - "items": { - "$ref": "#/definitions/domain.CategoryPoint" - } - } - } - }, - "domain.WorkspaceFile": { - "type": "object", - "properties": { - "content": { - "description": "文件内容", - "type": "string" - }, - "created_at": { - "description": "创建时间", - "type": "integer" - }, - "hash": { - "description": "文件哈希", - "type": "string" - }, - "id": { - "description": "文件ID", - "type": "string" - }, - "language": { - "description": "编程语言", - "type": "string" - }, - "path": { - "description": "文件路径", - "type": "string" - }, - "size": { - "description": "文件大小", - "type": "integer" - }, - "updated_at": { - "description": "更新时间", - "type": "integer" - }, - "user_id": { - "description": "用户ID", - "type": "string" - }, - "workspace_id": { - "description": "工作区ID", - "type": "string" - } - } - }, - "internal_codesnippet_handler_http_v1.GetContextReq": { - "type": "object", - "properties": { - "limit": { - "description": "返回结果数量限制,默认10", - "type": "integer" - }, - "queries": { - "description": "批量查询参数", - "type": "array", - "items": { - "$ref": "#/definitions/internal_codesnippet_handler_http_v1.Query" - } - }, - "query": { - "description": "单个查询参数", - "allOf": [ - { - "$ref": "#/definitions/internal_codesnippet_handler_http_v1.Query" - } - ] - }, - "workspacePath": { - "description": "工作区路径(必填)", - "type": "string" - } - } - }, - "internal_codesnippet_handler_http_v1.Query": { - "type": "object", - "properties": { - "language": { - "description": "编程语言(可选)", - "type": "string" - }, - "name": { - "description": "代码片段名称(可选)", - "type": "string" - }, - "snippetType": { - "description": "代码片段类型(可选)", - "type": "string" - } - } - }, - "web.Resp": { - "type": "object", - "properties": { - "code": { - "type": "integer" - }, - "data": {}, - "message": { - "type": "string" - } - } - } - } -} \ No newline at end of file diff --git a/backend/domain/openai.go b/backend/domain/openai.go index cad5018..95ec6a9 100644 --- a/backend/domain/openai.go +++ b/backend/domain/openai.go @@ -3,9 +3,10 @@ package domain import ( "context" + "github.com/rokku-c/go-openai" + "github.com/chaitin/MonkeyCode/backend/consts" "github.com/chaitin/MonkeyCode/backend/db" - "github.com/rokku-c/go-openai" ) type OpenAIUsecase interface { diff --git a/backend/domain/proxy.go b/backend/domain/proxy.go index 745eacb..4883691 100644 --- a/backend/domain/proxy.go +++ b/backend/domain/proxy.go @@ -2,27 +2,19 @@ package domain import ( "context" - "net/http" - - "github.com/rokku-c/go-openai" "github.com/chaitin/MonkeyCode/backend/consts" "github.com/chaitin/MonkeyCode/backend/db" ) -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 Report(ctx context.Context, req *ReportReq) error + CreateSecurityScanning(ctx context.Context, req *CreateSecurityScanningReq) (string, error) + ListSecurityScanning(ctx context.Context, req *ListSecurityScanningReq) (*ListSecurityScanningBriefResp, error) } type ProxyRepo interface { diff --git a/backend/domain/security.go b/backend/domain/security.go new file mode 100644 index 0000000..fc6e9d0 --- /dev/null +++ b/backend/domain/security.go @@ -0,0 +1,171 @@ +package domain + +import ( + "context" + "path" + "sort" + + "github.com/GoYoko/web" + "github.com/google/uuid" + + "github.com/chaitin/MonkeyCode/backend/consts" + "github.com/chaitin/MonkeyCode/backend/db" + "github.com/chaitin/MonkeyCode/backend/ent/types" + "github.com/chaitin/MonkeyCode/backend/pkg/cvt" + "github.com/chaitin/MonkeyCode/backend/pkg/scan" +) + +type SecurityScanningUsecase interface { + List(ctx context.Context, req ListSecurityScanningReq) (*ListSecurityScanningResp, error) + Detail(ctx context.Context, userID, id string) ([]*SecurityScanningRiskDetail, error) +} + +type SecurityScanningRepo interface { + Get(ctx context.Context, id string) (*db.SecurityScanning, error) + Create(ctx context.Context, req CreateSecurityScanningReq) (string, error) + Update(ctx context.Context, id string, status consts.SecurityScanningStatus, result *scan.Result) error + List(ctx context.Context, req ListSecurityScanningReq) (*ListSecurityScanningResp, error) + Detail(ctx context.Context, userID, id string) ([]*SecurityScanningRiskDetail, error) + ListBrief(ctx context.Context, req ListSecurityScanningReq) (*ListSecurityScanningBriefResp, error) + AllRunning(ctx context.Context) ([]*db.SecurityScanning, error) + PageWorkspaceFiles(ctx context.Context, id string, size int, fn func([]*db.WorkspaceFile) error) error +} + +type ListSecurityScanningReq struct { + web.Pagination + UserID string `json:"-"` + BaseURL string `json:"-"` + Author string `json:"author" query:"author"` // 作者 + ProjectName string `json:"project_name" query:"project_name"` // 项目名称 +} + +type ListSecurityScanningResp struct { + *db.PageInfo + + Items []*SecurityScanningResult `json:"items"` +} + +type ListSecurityScanningBriefResp struct { + *db.PageInfo + + Items []*SecurityScanningBrief `json:"items"` +} + +type SecurityScanningBrief struct { + Workspace string `json:"workspace"` // 项目目录 + Status consts.SecurityScanningStatus `json:"status"` // 扫描状态 + ReportURL string `json:"report_url"` // 报告url + CreatedAt int64 `json:"created_at"` // 创建时间 +} + +func (s *SecurityScanningBrief) From(e *db.SecurityScanning) *SecurityScanningBrief { + if e == nil { + return s + } + + s.Status = e.Status + s.Workspace = e.Workspace + s.CreatedAt = e.CreatedAt.Unix() + + return s +} + +type CreateSecurityScanningReq struct { + UserID string `json:"user_id"` + Workspace string `json:"workspace"` // 项目目录 + Language consts.SecurityScanningLanguage `json:"language"` // 扫描语言 +} + +type SecurityScanningResult struct { + ID string `json:"id"` // 扫描任务id + Name string `json:"name"` // 扫描任务 + ProjectName string `json:"project_name"` // 项目名称 + Path string `json:"path"` // 项目路径 + Status consts.SecurityScanningStatus `json:"status"` // 扫描状态 + Risk SecurityScanningRiskResult `json:"risk"` // 风险结果 + User *User `json:"user"` // 用户 + CreatedAt int64 `json:"created_at"` // 扫描开始时间 +} + +func (s *SecurityScanningResult) From(e *db.SecurityScanning) *SecurityScanningResult { + if e == nil { + return s + } + + s.ID = e.ID.String() + s.Name = e.Language.RuleName() + s.ProjectName = path.Base(e.Workspace) + s.Path = e.Workspace + s.Status = e.Status + s.User = cvt.From(e.Edges.User, &User{}) + s.CreatedAt = e.CreatedAt.Unix() + + return s +} + +type SecurityScanningRiskResult struct { + ID uuid.UUID `json:"id"` + SevereCount int `json:"severe_count"` // 严重数 + CriticalCount int `json:"critical_count"` // 高危数 + SuggestCount int `json:"suggest_count"` // 建议数 +} + +type SecurityScanningRiskDetail struct { + ID string `json:"id"` // 风险id + Level consts.SecurityScanningRiskLevel `json:"level"` // 风险等级 + Desc string `json:"desc"` // 风险描述 + Lines string `json:"lines"` // 风险代码行 + Start *types.Position `json:"start"` // 风险代码行开始位置 + End *types.Position `json:"end"` // 风险代码行结束位置 + Fix string `json:"fix"` // 修复建议 + Filename string `json:"filename"` // 风险文件名 +} + +func (s *SecurityScanningRiskDetail) GetRiskLevelPriority() int { + switch s.Level { + case consts.SecurityScanningRiskLevelSevere: + return 1 // 严重 - 最高优先级 + case consts.SecurityScanningRiskLevelCritical: + return 2 // 高危 - 中等优先级 + case consts.SecurityScanningRiskLevelSuggest: + return 3 // 建议 - 最低优先级 + default: + return 4 // 未知等级放在最后 + } +} + +type ByRiskLevel []*SecurityScanningRiskDetail + +func (a ByRiskLevel) Len() int { return len(a) } +func (a ByRiskLevel) Swap(i, j int) { a[i], a[j] = a[j], a[i] } +func (a ByRiskLevel) Less(i, j int) bool { + return a[i].GetRiskLevelPriority() < a[j].GetRiskLevelPriority() +} + +func SortRiskDetailsByLevel(details []*SecurityScanningRiskDetail) { + sort.Sort(ByRiskLevel(details)) +} + +func (s *SecurityScanningRiskDetail) From(e *db.SecurityScanningResult) *SecurityScanningRiskDetail { + if e == nil { + return s + } + + s.ID = e.ID.String() + switch e.Severity { + case "ERROR", "CRITICAL": + s.Level = consts.SecurityScanningRiskLevelSevere + case "WARNING": + s.Level = consts.SecurityScanningRiskLevelCritical + case "INFO": + s.Level = consts.SecurityScanningRiskLevelSuggest + } + s.Desc = e.AbstractZh + s.Lines = e.Lines + s.Start = e.StartPosition + s.End = e.EndPosition + s.Filename = e.Path + s.Fix = e.MessageZh + + return s +} diff --git a/backend/ent/schema/securityscanning.go b/backend/ent/schema/securityscanning.go new file mode 100644 index 0000000..c019014 --- /dev/null +++ b/backend/ent/schema/securityscanning.go @@ -0,0 +1,52 @@ +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" +) + +// SecurityScanning holds the schema definition for the SecurityScanning entity. +type SecurityScanning struct { + ent.Schema +} + +func (SecurityScanning) Annotations() []schema.Annotation { + return []schema.Annotation{ + entsql.Annotation{ + Table: "security_scannings", + }, + } +} + +// Fields of the SecurityScanning. +func (SecurityScanning) Fields() []ent.Field { + return []ent.Field{ + field.UUID("id", uuid.UUID{}), + field.UUID("user_id", uuid.UUID{}), + field.UUID("workspace_id", uuid.UUID{}), + field.String("status").GoType(consts.SecurityScanningStatus("")), + field.String("workspace"), + field.String("language").GoType(consts.SecurityScanningLanguage("")), + field.String("rule").Optional(), + field.String("error_message").Optional(), + field.Time("created_at").Default(time.Now), + field.Time("updated_at").Default(time.Now), + } +} + +// Edges of the SecurityScanning. +func (SecurityScanning) Edges() []ent.Edge { + return []ent.Edge{ + edge.From("user", User.Type).Field("user_id").Ref("security_scannings").Unique().Required(), + edge.To("results", SecurityScanningResult.Type), + edge.From("workspace_edge", Workspace.Type).Field("workspace_id").Ref("security_scannings").Unique().Required(), + } +} diff --git a/backend/ent/schema/securityscanningresult.go b/backend/ent/schema/securityscanningresult.go new file mode 100644 index 0000000..43fe622 --- /dev/null +++ b/backend/ent/schema/securityscanningresult.go @@ -0,0 +1,57 @@ +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/chaitin/MonkeyCode/backend/ent/types" + "github.com/google/uuid" +) + +// SecurityScanningResult holds the schema definition for the SecurityScanningResult entity. +type SecurityScanningResult struct { + ent.Schema +} + +func (SecurityScanningResult) Annotations() []schema.Annotation { + return []schema.Annotation{ + entsql.Annotation{Table: "security_scanning_results"}, + } +} + +// Fields of the SecurityScanningResult. +func (SecurityScanningResult) Fields() []ent.Field { + return []ent.Field{ + field.UUID("id", uuid.UUID{}), + field.UUID("security_scanning_id", uuid.UUID{}), + field.String("check_id"), + field.String("engine_kind"), + field.Text("lines"), + field.Text("path"), + field.Text("message"), + field.Text("message_zh"), + field.String("severity"), + field.Text("abstract_en"), + field.Text("abstract_zh"), + field.Text("category_en"), + field.Text("category_zh"), + field.String("confidence"), + field.JSON("cwe", []any{}), + field.String("impact"), + field.JSON("owasp", []any{}), + field.JSON("start_position", &types.Position{}), + field.JSON("end_position", &types.Position{}), + field.Time("created_at").Default(time.Now), + } +} + +// Edges of the SecurityScanningResult. +func (SecurityScanningResult) Edges() []ent.Edge { + return []ent.Edge{ + edge.From("security_scanning", SecurityScanning.Type).Ref("results").Unique().Field("security_scanning_id").Required(), + } +} diff --git a/backend/ent/schema/user.go b/backend/ent/schema/user.go index 8fb8e44..4b851ec 100644 --- a/backend/ent/schema/user.go +++ b/backend/ent/schema/user.go @@ -58,5 +58,6 @@ func (User) Edges() []ent.Edge { edge.To("workspaces", Workspace.Type), edge.To("workspace_files", WorkspaceFile.Type), edge.To("api_keys", ApiKey.Type), + edge.To("security_scannings", SecurityScanning.Type), } } diff --git a/backend/ent/schema/workspace.go b/backend/ent/schema/workspace.go index 553d700..8774fda 100644 --- a/backend/ent/schema/workspace.go +++ b/backend/ent/schema/workspace.go @@ -45,6 +45,7 @@ func (Workspace) Edges() []ent.Edge { return []ent.Edge{ edge.From("owner", User.Type).Ref("workspaces").Field("user_id").Unique().Required(), edge.To("files", WorkspaceFile.Type), + edge.To("security_scannings", SecurityScanning.Type), } } diff --git a/backend/ent/types/types.go b/backend/ent/types/types.go index 7c8f9d1..2a6f498 100644 --- a/backend/ent/types/types.go +++ b/backend/ent/types/types.go @@ -1,5 +1,11 @@ package types +type Position struct { + Col int `json:"col"` + Line int `json:"line"` + Offset int `json:"offset"` +} + type DingtalkOAuth struct { Enable bool `json:"enable"` // 钉钉OAuth开关 ClientID string `json:"client_id"` // 钉钉客户端ID diff --git a/backend/internal/handlers.go b/backend/internal/handlers.go index d39f449..afa2bbe 100644 --- a/backend/internal/handlers.go +++ b/backend/internal/handlers.go @@ -6,6 +6,7 @@ import ( dashv1 "github.com/chaitin/MonkeyCode/backend/internal/dashboard/handler/v1" modelv1 "github.com/chaitin/MonkeyCode/backend/internal/model/handler/http/v1" v1 "github.com/chaitin/MonkeyCode/backend/internal/openai/handler/v1" + securityv1 "github.com/chaitin/MonkeyCode/backend/internal/security/handler/http/v1" sockethandler "github.com/chaitin/MonkeyCode/backend/internal/socket/handler" userV1 "github.com/chaitin/MonkeyCode/backend/internal/user/handler/v1" workspacehandlerv1 "github.com/chaitin/MonkeyCode/backend/internal/workspace/handler/http/v1" @@ -21,4 +22,5 @@ type APIHandlers struct { SocketHandler *sockethandler.SocketHandler BillingHandler *billingv1.BillingHandler WorkspaceFileHandler *workspacehandlerv1.WorkspaceFileHandler + SecurityHandler *securityv1.SecurityHandler } diff --git a/backend/internal/openai/handler/v1/v1.go b/backend/internal/openai/handler/v1/v1.go index 1d50807..e6c3180 100644 --- a/backend/internal/openai/handler/v1/v1.go +++ b/backend/internal/openai/handler/v1/v1.go @@ -60,6 +60,8 @@ func NewV1Handler( g.POST("/chat/completions", web.BaseHandler(h.ChatCompletion), active.Active("apikey")) g.POST("/completions", web.BaseHandler(h.Completions), active.Active("apikey")) g.POST("/embeddings", web.BaseHandler(h.Embeddings), active.Active("apikey")) + g.POST("/security/scanning", web.BindHandler(h.CreateSecurityScanning), active.Active("apikey")) + g.GET("/security/scanning", web.BindHandler(h.ListSecurityScanning), active.Active("apikey")) return h } @@ -215,3 +217,50 @@ func (h *V1Handler) GetConfig(c *web.Context, req domain.ConfigReq) error { func (h *V1Handler) HealthCheck(c *web.Context) error { return c.Success("MonkeyCode") } + +// CreateSecurityScanning 创建扫描任务 +// +// @Tags OpenAIV1 +// @Summary 创建扫描任务 +// @Description 创建扫描任务 +// @ID create-security-scanning +// @Accept json +// @Produce json +// @Param param body domain.CreateSecurityScanningReq true "创建扫描任务请求" +// @Success 200 {object} web.Resp{} +// @Router /v1/security/scanning [post] +func (h *V1Handler) CreateSecurityScanning(c *web.Context, req domain.CreateSecurityScanningReq) error { + key := middleware.GetApiKey(c) + req.UserID = key.UserID + id, err := h.proxyUse.CreateSecurityScanning(c.Request().Context(), &req) + if err != nil { + h.logger.With("error", err).With("id", id).ErrorContext(c.Request().Context(), "create security scanning failed") + return err + } + return c.Success(id) +} + +// ListSecurityScanning 扫描任务列表 +// +// @Tags OpenAIV1 +// @Summary 扫描任务列表 +// @Description 分页逻辑只支持用 next_token +// @ID list-security-scanning +// @Accept json +// @Produce json +// @Param param body domain.ListSecurityScanningReq true "扫描任务列表请求" +// @Success 200 {object} web.Resp{data=domain.ListSecurityScanningBriefResp} +// @Router /v1/security/scanning [get] +func (h *V1Handler) ListSecurityScanning(c *web.Context, req domain.ListSecurityScanningReq) error { + req.UserID = middleware.GetApiKey(c).UserID + s, err := h.uuse.GetSetting(c.Request().Context()) + if err != nil { + return err + } + req.BaseURL = h.config.GetBaseURL(c.Request(), s) + resp, err := h.proxyUse.ListSecurityScanning(c.Request().Context(), &req) + if err != nil { + return err + } + return c.Success(resp) +} diff --git a/backend/internal/provider.go b/backend/internal/provider.go index 0274b1f..a883811 100644 --- a/backend/internal/provider.go +++ b/backend/internal/provider.go @@ -26,6 +26,9 @@ import ( proxyusecase "github.com/chaitin/MonkeyCode/backend/internal/proxy/usecase" reportrepo "github.com/chaitin/MonkeyCode/backend/internal/report/repo" reportuse "github.com/chaitin/MonkeyCode/backend/internal/report/usecase" + securityv1 "github.com/chaitin/MonkeyCode/backend/internal/security/handler/http/v1" + securityrepo "github.com/chaitin/MonkeyCode/backend/internal/security/repo" + securityusecase "github.com/chaitin/MonkeyCode/backend/internal/security/usecase" sockethandler "github.com/chaitin/MonkeyCode/backend/internal/socket/handler" userV1 "github.com/chaitin/MonkeyCode/backend/internal/user/handler/v1" userrepo "github.com/chaitin/MonkeyCode/backend/internal/user/repo" @@ -46,6 +49,7 @@ func NewAPIHandlers( socketH *sockethandler.SocketHandler, billingV1 *billingv1.BillingHandler, workspaceFileV1 *workspacehandlerv1.WorkspaceFileHandler, + securityV1 *securityv1.SecurityHandler, ) *APIHandlers { return &APIHandlers{ OpenAIV1Handler: openaiV1, @@ -56,6 +60,7 @@ func NewAPIHandlers( SocketHandler: socketH, BillingHandler: billingV1, WorkspaceFileHandler: workspaceFileV1, + SecurityHandler: securityV1, } } @@ -97,4 +102,7 @@ var Provider = wire.NewSet( codesnippetusecase.NewCodeSnippetUsecase, codesnippetv1.NewCodeSnippetHandler, NewAPIHandlers, + securityrepo.NewSecurityScanningRepo, + securityusecase.NewSecurityScanningUsecase, + securityv1.NewSecurityHandler, ) diff --git a/backend/internal/proxy/usecase/proxy.go b/backend/internal/proxy/usecase/proxy.go index 635c98b..b0f3b15 100644 --- a/backend/internal/proxy/usecase/proxy.go +++ b/backend/internal/proxy/usecase/proxy.go @@ -2,30 +2,69 @@ package usecase import ( "context" + "fmt" "log/slog" + "os" + "path" + "strings" + "time" - "github.com/chaitin/MonkeyCode/backend/db" - "github.com/chaitin/MonkeyCode/backend/pkg/cvt" + "github.com/redis/go-redis/v9" + "github.com/chaitin/MonkeyCode/backend/config" "github.com/chaitin/MonkeyCode/backend/consts" + "github.com/chaitin/MonkeyCode/backend/db" "github.com/chaitin/MonkeyCode/backend/domain" + "github.com/chaitin/MonkeyCode/backend/pkg/cvt" + "github.com/chaitin/MonkeyCode/backend/pkg/queuerunner" + "github.com/chaitin/MonkeyCode/backend/pkg/request" + "github.com/chaitin/MonkeyCode/backend/pkg/scan" ) type ProxyUsecase struct { - repo domain.ProxyRepo - modelRepo domain.ModelRepo - logger *slog.Logger + repo domain.ProxyRepo + modelRepo domain.ModelRepo + securityRepo domain.SecurityScanningRepo + logger *slog.Logger + queuerunner *queuerunner.QueueRunner[domain.CreateSecurityScanningReq] + client *request.Client } func NewProxyUsecase( repo domain.ProxyRepo, modelRepo domain.ModelRepo, + securityRepo domain.SecurityScanningRepo, logger *slog.Logger, + cfg *config.Config, + redis *redis.Client, ) domain.ProxyUsecase { - return &ProxyUsecase{ - repo: repo, - modelRepo: modelRepo, - logger: logger.With("module", "ProxyUsecase"), + client := request.NewClient("http", "monkeycode-scanner:8888", 15*time.Second) + client.SetDebug(cfg.Debug) + p := &ProxyUsecase{ + repo: repo, + modelRepo: modelRepo, + securityRepo: securityRepo, + logger: logger.With("module", "ProxyUsecase"), + queuerunner: queuerunner.NewQueueRunner[domain.CreateSecurityScanningReq](cfg, redis, logger), + client: client, + } + go p.queuerunner.Run(context.Background()) + go p.requeue() + return p +} + +func (p *ProxyUsecase) requeue() { + scannings, err := p.securityRepo.AllRunning(context.Background()) + if err != nil { + p.logger.With("fn", "requeue").With("error", err).ErrorContext(context.Background(), "failed to get running scannings") + return + } + for _, scanning := range scannings { + p.queuerunner.Enqueue(context.Background(), scanning.ID.String(), domain.CreateSecurityScanningReq{ + UserID: scanning.UserID.String(), + Workspace: scanning.Workspace, + Language: consts.SecurityScanningLanguage(scanning.Rule), + }, p.TaskHandle) } } @@ -66,3 +105,74 @@ func (p *ProxyUsecase) Report(ctx context.Context, req *domain.ReportReq) error } return p.repo.Report(ctx, model, req) } + +func (p *ProxyUsecase) CreateSecurityScanning(ctx context.Context, req *domain.CreateSecurityScanningReq) (string, error) { + id, err := p.securityRepo.Create(ctx, *req) + if err != nil { + return "", err + } + return p.queuerunner.Enqueue(ctx, id, *req, p.TaskHandle) +} + +func (p *ProxyUsecase) TaskHandle(ctx context.Context, task *queuerunner.Task[domain.CreateSecurityScanningReq]) error { + id := task.ID + if err := p.securityRepo.Update(ctx, id, consts.SecurityScanningStatusRunning, nil); err != nil { + p.logger.With("id", task.ID).With("error", err).ErrorContext(ctx, "failed to update security scanning") + return err + } + p.logger.With("id", id).DebugContext(ctx, "task started") + + // 落盘文件 + scanning, err := p.securityRepo.Get(ctx, id) + if err != nil { + p.logger.With("id", id).With("error", err).ErrorContext(ctx, "failed to get security scanning") + return err + } + prefix := fmt.Sprintf("/app/codes/%s", id) + rootPath := path.Join(prefix, scanning.Edges.WorkspaceEdge.RootPath) + defer os.RemoveAll(prefix) + + if err = p.securityRepo.PageWorkspaceFiles(ctx, scanning.WorkspaceID.String(), 20, func(rs []*db.WorkspaceFile) error { + for _, r := range rs { + filename := path.Join(rootPath, r.Path) + dir := path.Dir(filename) + p.logger.With("path", dir).DebugContext(ctx, "create dir") + if err = os.MkdirAll(dir, 0755); err != nil { + p.logger.With("path", dir).With("id", id).With("error", err).ErrorContext(ctx, "failed to create dir") + continue + } + if err = os.WriteFile(filename, []byte(r.Content), 0644); err != nil { + p.logger.With("path", filename).With("id", id).With("error", err).ErrorContext(ctx, "failed to write file") + continue + } + } + return nil + }); err != nil { + return err + } + + rule := strings.ToLower(string(scanning.Language)) + result, err := scan.Scan(task.ID, rootPath, rule) + if err != nil { + if err = p.securityRepo.Update(ctx, id, consts.SecurityScanningStatusFailed, &scan.Result{ + Output: err.Error(), + }); err != nil { + p.logger.With("id", task.ID).With("error", err).ErrorContext(ctx, "failed to update security scanning") + } + p.logger.With("id", task.ID).With("error", err).ErrorContext(ctx, "failed to scan") + return err + } + + result.Prefix = prefix + if err := p.securityRepo.Update(ctx, id, consts.SecurityScanningStatusSuccess, result); err != nil { + p.logger.With("id", task.ID).With("error", err).ErrorContext(ctx, "failed to update security scanning") + return err + } + + p.logger.With("id", task.ID).DebugContext(ctx, "task done") + return nil +} + +func (p *ProxyUsecase) ListSecurityScanning(ctx context.Context, req *domain.ListSecurityScanningReq) (*domain.ListSecurityScanningBriefResp, error) { + return p.securityRepo.ListBrief(ctx, *req) +} diff --git a/backend/internal/security/handler/http/v1/security.go b/backend/internal/security/handler/http/v1/security.go new file mode 100644 index 0000000..d60cdd6 --- /dev/null +++ b/backend/internal/security/handler/http/v1/security.go @@ -0,0 +1,71 @@ +package v1 + +import ( + "github.com/GoYoko/web" + + "github.com/chaitin/MonkeyCode/backend/domain" + "github.com/chaitin/MonkeyCode/backend/internal/middleware" +) + +type SecurityHandler struct { + usecase domain.SecurityScanningUsecase +} + +func NewSecurityHandler( + w *web.Web, + usecase domain.SecurityScanningUsecase, + auth *middleware.AuthMiddleware, + active *middleware.ActiveMiddleware, +) *SecurityHandler { + s := &SecurityHandler{ + usecase: usecase, + } + + g := w.Group("/api/v1/security/scanning") + g.Use(auth.Auth(), active.Active("admin")) + + g.GET("", web.BindHandler(s.List)) + g.GET("/detail", web.BaseHandler(s.Detail)) + + return s +} + +// List 获取扫描结果 +// +// @Tags Security Scanning +// @Summary 获取扫描结果 +// @Description 获取扫描结果 +// @ID security-scanning-list +// @Accept json +// @Produce json +// @Param page query domain.ListSecurityScanningReq true "参数" +// @Success 200 {object} web.Resp{data=domain.ListSecurityScanningResp} +// @Failure 401 {object} string +// @Router /api/v1/security/scanning [get] +func (s *SecurityHandler) List(c *web.Context, req domain.ListSecurityScanningReq) error { + resp, err := s.usecase.List(c.Request().Context(), req) + if err != nil { + return err + } + return c.Success(resp) +} + +// Detail 获取扫描风险详情 +// +// @Tags Security Scanning +// @Summary 获取扫描风险详情 +// @Description 获取扫描风险详情 +// @ID security-scanning-detail +// @Accept json +// @Produce json +// @Param id query string true "扫描任务id" +// @Success 200 {object} web.Resp{data=[]domain.SecurityScanningRiskDetail} +// @Failure 401 {object} string +// @Router /api/v1/security/scanning/detail [get] +func (s *SecurityHandler) Detail(c *web.Context) error { + resp, err := s.usecase.Detail(c.Request().Context(), "", c.QueryParam("id")) + if err != nil { + return err + } + return c.Success(resp) +} diff --git a/backend/internal/security/repo/security.go b/backend/internal/security/repo/security.go new file mode 100644 index 0000000..ca14810 --- /dev/null +++ b/backend/internal/security/repo/security.go @@ -0,0 +1,309 @@ +package repo + +import ( + "context" + "fmt" + "strings" + + "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/securityscanning" + "github.com/chaitin/MonkeyCode/backend/db/securityscanningresult" + "github.com/chaitin/MonkeyCode/backend/db/workspace" + "github.com/chaitin/MonkeyCode/backend/db/workspacefile" + "github.com/chaitin/MonkeyCode/backend/domain" + "github.com/chaitin/MonkeyCode/backend/ent/types" + "github.com/chaitin/MonkeyCode/backend/pkg/cvt" + "github.com/chaitin/MonkeyCode/backend/pkg/entx" + "github.com/chaitin/MonkeyCode/backend/pkg/scan" +) + +type SecurityScanningRepo struct { + db *db.Client +} + +func NewSecurityScanningRepo(db *db.Client) domain.SecurityScanningRepo { + return &SecurityScanningRepo{ + db: db, + } +} + +// Create implements domain.SecurityScanningRepo. +func (s *SecurityScanningRepo) Create(ctx context.Context, req domain.CreateSecurityScanningReq) (string, error) { + id := uuid.New() + uid, err := uuid.Parse(req.UserID) + if err != nil { + return "", err + } + + w, err := s.db.Workspace.Query(). + Where(workspace.UserID(uid)). + Where(workspace.RootPath(req.Workspace)). + First(ctx) + if err != nil { + return "", err + } + + _, err = s.db.SecurityScanning.Create(). + SetID(id). + SetUserID(uid). + SetWorkspaceID(w.ID). + SetLanguage(req.Language). + SetRule(req.Language.RuleName()). + SetWorkspace(req.Workspace). + SetStatus(consts.SecurityScanningStatusPending). + Save(ctx) + + if err != nil { + return "", err + } + + return id.String(), nil +} + +// Update implements domain.SecurityScanningRepo. +func (s *SecurityScanningRepo) Update(ctx context.Context, id string, status consts.SecurityScanningStatus, result *scan.Result) error { + uid, err := uuid.Parse(id) + if err != nil { + return err + } + + return entx.WithTx(ctx, s.db, func(tx *db.Tx) error { + up := s.db.SecurityScanning.Update(). + Where(securityscanning.ID(uid)). + SetStatus(status) + + if result != nil && result.Output != "" { + up.SetErrorMessage(result.Output) + } + + if err := up.Exec(ctx); err != nil { + return err + } + + if result == nil { + return nil + } + + cs := make([]*db.SecurityScanningResultCreate, 0) + for _, item := range result.Results { + c := s.db.SecurityScanningResult.Create(). + SetSecurityScanningID(uid). + SetCheckID(item.CheckID). + SetEngineKind(item.Extra.EngineKind). + SetLines(item.Extra.Lines). + SetMessage(item.Extra.Message). + SetMessageZh(item.Extra.Metadata.MessageZh). + SetSeverity(item.Extra.Severity). + SetAbstractEn(item.Extra.Metadata.AbstractFeysh["en-US"]). + SetAbstractZh(item.Extra.Metadata.AbstractFeysh["zh-CN"]). + SetCategoryEn(item.Extra.Metadata.CategoryFeysh["en-US"]). + SetCategoryZh(item.Extra.Metadata.CategoryFeysh["zh-CN"]). + SetConfidence(item.Extra.Metadata.Confidence). + SetCwe([]any{item.Extra.Metadata.Cwe}). + SetImpact(item.Extra.Metadata.Impact). + SetOwasp([]any{item.Extra.Metadata.Owasp}). + SetPath(strings.ReplaceAll(item.Path, result.Prefix, "")). + SetStartPosition(&types.Position{ + Col: item.Start.Col, + Line: item.Start.Line, + Offset: item.Start.Offset, + }). + SetEndPosition(&types.Position{ + Col: item.End.Col, + Line: item.End.Line, + Offset: item.End.Offset, + }) + cs = append(cs, c) + if len(cs) >= 10 { + if err := s.db.SecurityScanningResult.CreateBulk(cs...).Exec(ctx); err != nil { + return err + } + cs = cs[:0] + } + } + + if len(cs) > 0 { + if err := s.db.SecurityScanningResult.CreateBulk(cs...).Exec(ctx); err != nil { + return err + } + } + + return nil + }) +} + +// List implements domain.SecurityScanningRepo. +func (s *SecurityScanningRepo) List(ctx context.Context, req domain.ListSecurityScanningReq) (*domain.ListSecurityScanningResp, error) { + query := s.db.SecurityScanning.Query(). + WithResults(). + WithUser() + + if req.UserID != "" { + uid, err := uuid.Parse(req.UserID) + if err != nil { + return nil, err + } + query.Where(securityscanning.UserID(uid)) + } + + scannings, p, err := query. + Order(db.Desc("created_at")). + Page(ctx, int(req.Page), int(req.Size)) + + if err != nil { + return nil, err + } + + ids := cvt.Iter(scannings, func(_ int, s *db.SecurityScanning) uuid.UUID { + return s.ID + }) + riskCount, err := s.RiskCountByIDs(ctx, ids) + if err != nil { + return nil, err + } + + return &domain.ListSecurityScanningResp{ + PageInfo: p, + Items: cvt.Iter(scannings, func(_ int, s *db.SecurityScanning) *domain.SecurityScanningResult { + return cvt.From(s, &domain.SecurityScanningResult{ + Risk: riskCount[s.ID], + }) + }), + }, nil +} + +// ListBrief implements domain.SecurityScanningRepo. +func (s *SecurityScanningRepo) ListBrief(ctx context.Context, req domain.ListSecurityScanningReq) (*domain.ListSecurityScanningBriefResp, error) { + query := s.db.SecurityScanning.Query(). + WithUser(). + WithResults() + + if req.UserID != "" { + uid, err := uuid.Parse(req.UserID) + if err != nil { + return nil, err + } + query.Where(securityscanning.UserID(uid)) + } + + scannings, p, err := query. + Order(securityscanning.ByCreatedAt(sql.OrderDesc())). + Page(context.Background(), int(req.Page), int(req.Size)) + + if err != nil { + return nil, err + } + + return &domain.ListSecurityScanningBriefResp{ + PageInfo: p, + Items: cvt.Iter(scannings, func(_ int, s *db.SecurityScanning) *domain.SecurityScanningBrief { + return cvt.From(s, &domain.SecurityScanningBrief{ + ReportURL: fmt.Sprintf("%s/user/codescan", req.BaseURL), + }) + }), + }, nil +} + +func (s *SecurityScanningRepo) Detail(ctx context.Context, userID, id string) ([]*domain.SecurityScanningRiskDetail, error) { + sid, err := uuid.Parse(id) + if err != nil { + return nil, err + } + + q := s.db.SecurityScanningResult.Query(). + Where(securityscanningresult.SecurityScanningID(sid)) + + if userID != "" { + uid, err := uuid.Parse(userID) + if err != nil { + return nil, err + } + q.Where(securityscanningresult.HasSecurityScanningWith(func(s *sql.Selector) { + s.Where(sql.EQ(securityscanning.FieldUserID, uid)) + })) + } + + scannings, err := q.All(ctx) + if err != nil { + return nil, err + } + + rs := cvt.Iter(scannings, func(_ int, r *db.SecurityScanningResult) *domain.SecurityScanningRiskDetail { + return cvt.From(r, &domain.SecurityScanningRiskDetail{}) + }) + domain.SortRiskDetailsByLevel(rs) + return rs, nil +} + +// RiskCountByIDs implements domain.SecurityScanningRepo. +func (s *SecurityScanningRepo) RiskCountByIDs(ctx context.Context, ids []uuid.UUID) (map[uuid.UUID]domain.SecurityScanningRiskResult, error) { + rs := make([]domain.SecurityScanningRiskResult, 0) + if err := s.db.SecurityScanningResult.Query(). + Where(securityscanningresult.SecurityScanningIDIn(ids...)). + Modify(func(s *sql.Selector) { + s.Select( + sql.As("security_scanning_id", "id"), + sql.As("count(*) filter (where severity in ('CRITICAL', 'ERROR'))", "severe_count"), + sql.As("count(*) filter (where severity = 'WARNING')", "critical_count"), + sql.As("count(*) filter (where severity = 'INFO')", "suggest_count"), + ). + GroupBy(securityscanningresult.FieldSecurityScanningID) + }). + Scan(ctx, &rs); err != nil { + return nil, err + } + return cvt.IterToMap(rs, func(_ int, r domain.SecurityScanningRiskResult) (uuid.UUID, domain.SecurityScanningRiskResult) { + return r.ID, r + }), nil +} + +// AllRunning implements domain.SecurityScanningRepo. +func (s *SecurityScanningRepo) AllRunning(ctx context.Context) ([]*db.SecurityScanning, error) { + return s.db.SecurityScanning.Query(). + Where(securityscanning.Status(consts.SecurityScanningStatusRunning)). + Order(securityscanning.ByCreatedAt(sql.OrderAsc())). + All(ctx) +} + +func (s *SecurityScanningRepo) Get(ctx context.Context, id string) (*db.SecurityScanning, error) { + sid, err := uuid.Parse(id) + if err != nil { + return nil, err + } + return s.db.SecurityScanning.Query(). + WithWorkspaceEdge(). + Where(securityscanning.ID(sid)). + First(ctx) +} + +// PageWorkspaceFiles implements domain.SecurityScanningRepo. +func (s *SecurityScanningRepo) PageWorkspaceFiles(ctx context.Context, id string, size int, fn func([]*db.WorkspaceFile) error) error { + wid, err := uuid.Parse(id) + if err != nil { + return err + } + + page := 1 + hasMore := true + + for hasMore { + rs, p, err := s.db.WorkspaceFile.Query(). + Where(workspacefile.WorkspaceID(wid)). + Order(workspacefile.ByCreatedAt(sql.OrderAsc())). + Page(ctx, page, size) + if err != nil { + return err + } + if err := fn(rs); err != nil { + return err + } + hasMore = p.HasNextPage + page++ + } + + return nil +} diff --git a/backend/internal/security/usecase/security.go b/backend/internal/security/usecase/security.go new file mode 100644 index 0000000..e9ad43e --- /dev/null +++ b/backend/internal/security/usecase/security.go @@ -0,0 +1,27 @@ +package usecase + +import ( + "context" + + "github.com/chaitin/MonkeyCode/backend/domain" +) + +type SecurityScanningUsecase struct { + repo domain.SecurityScanningRepo +} + +func NewSecurityScanningUsecase(repo domain.SecurityScanningRepo) domain.SecurityScanningUsecase { + return &SecurityScanningUsecase{ + repo: repo, + } +} + +// Detail implements domain.SecurityScanningUsecase. +func (s *SecurityScanningUsecase) Detail(ctx context.Context, userID, id string) ([]*domain.SecurityScanningRiskDetail, error) { + return s.repo.Detail(ctx, userID, id) +} + +// List implements domain.SecurityScanningUsecase. +func (s *SecurityScanningUsecase) List(ctx context.Context, req domain.ListSecurityScanningReq) (*domain.ListSecurityScanningResp, error) { + return s.repo.List(ctx, req) +} diff --git a/backend/internal/user/handler/v1/security.go b/backend/internal/user/handler/v1/security.go new file mode 100644 index 0000000..5df31f7 --- /dev/null +++ b/backend/internal/user/handler/v1/security.go @@ -0,0 +1,51 @@ +package v1 + +import ( + "github.com/GoYoko/web" + + "github.com/chaitin/MonkeyCode/backend/domain" + "github.com/chaitin/MonkeyCode/backend/internal/middleware" +) + +// List 获取用户扫描结果 +// +// @Tags User Security Scanning +// @Summary 获取用户扫描结果 +// @Description 获取用户扫描结果 +// @ID user-security-scanning-list +// @Accept json +// @Produce json +// @Param page query domain.ListSecurityScanningReq true "参数" +// @Success 200 {object} web.Resp{data=domain.ListSecurityScanningResp} +// @Failure 401 {object} string +// @Router /api/v1/user/security/scanning [get] +func (u *UserHandler) SecurityList(c *web.Context, req domain.ListSecurityScanningReq) error { + user := middleware.GetUser(c) + req.UserID = user.ID + resp, err := u.scuse.List(c.Request().Context(), req) + if err != nil { + return err + } + return c.Success(resp) +} + +// Detail 获取用户扫描风险详情 +// +// @Tags User Security Scanning +// @Summary 获取用户扫描风险详情 +// @Description 获取用户扫描风险详情 +// @ID user-security-scanning-detail +// @Accept json +// @Produce json +// @Param id query string true "扫描任务id" +// @Success 200 {object} web.Resp{data=[]domain.SecurityScanningRiskDetail} +// @Failure 401 {object} string +// @Router /api/v1/user/security/scanning/detail [get] +func (u *UserHandler) SecurityDetail(c *web.Context) error { + user := middleware.GetUser(c) + resp, err := u.scuse.Detail(c.Request().Context(), user.ID, c.QueryParam("id")) + if err != nil { + return err + } + return c.Success(resp) +} diff --git a/backend/internal/user/handler/v1/user.go b/backend/internal/user/handler/v1/user.go index d5378c4..a157f12 100644 --- a/backend/internal/user/handler/v1/user.go +++ b/backend/internal/user/handler/v1/user.go @@ -35,6 +35,7 @@ type UserHandler struct { euse domain.ExtensionUsecase duse domain.DashboardUsecase buse domain.BillingUsecase + scuse domain.SecurityScanningUsecase session *session.Session logger *slog.Logger cfg *config.Config @@ -47,6 +48,7 @@ func NewUserHandler( w *web.Web, usecase domain.UserUsecase, euse domain.ExtensionUsecase, + scuse domain.SecurityScanningUsecase, duse domain.DashboardUsecase, buse domain.BillingUsecase, auth *middleware.AuthMiddleware, @@ -61,6 +63,7 @@ func NewUserHandler( euse: euse, duse: duse, buse: buse, + scuse: scuse, session: session, logger: logger, cfg: cfg, @@ -125,6 +128,12 @@ func NewUserHandler( cplt.GET("/record", web.BindHandler(u.ListCompletionRecord, web.WithPage())) cplt.GET("/info", web.BaseHandler(u.CompletionInfo)) + // user security + sc := w.Group("/api/v1/user/security") + sc.Use(auth.UserAuth(), active.Active("user")) + sc.GET("/scanning", web.BindHandler(u.SecurityList, web.WithPage())) + sc.GET("/scanning/detail", web.BaseHandler(u.SecurityDetail)) + return u } diff --git a/backend/migration/000014_create_security_table.down.sql b/backend/migration/000014_create_security_table.down.sql new file mode 100644 index 0000000..e69de29 diff --git a/backend/migration/000014_create_security_table.up.sql b/backend/migration/000014_create_security_table.up.sql new file mode 100644 index 0000000..a1a6c59 --- /dev/null +++ b/backend/migration/000014_create_security_table.up.sql @@ -0,0 +1,37 @@ +CREATE TABLE IF NOT EXISTS security_scannings ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_id UUID NOT NULL, + workspace_id UUID NOT NULL, + status VARCHAR(50) NOT NULL, + workspace TEXT NOT NULL, + language VARCHAR(50) NOT NULL, + rule TEXT, + error_message TEXT, + created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP +); + +CREATE TABLE IF NOT EXISTS security_scanning_results ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + security_scanning_id UUID NOT NULL, + check_id VARCHAR(128), + engine_kind VARCHAR(32), + lines TEXT, + path TEXT, + message TEXT, + message_zh TEXT, + severity VARCHAR(50), + abstract_en TEXT, + abstract_zh TEXT, + category_en TEXT, + category_zh TEXT, + confidence VARCHAR(50), + cwe JSONB, + impact VARCHAR(50), + owasp JSONB, + start_position JSONB, + end_position JSONB, + created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP +); + +CREATE INDEX IF NOT EXISTS security_scanning_results_owner_id ON security_scanning_results (security_scanning_id); \ No newline at end of file diff --git a/backend/pkg/queuerunner/queuerunner.go b/backend/pkg/queuerunner/queuerunner.go new file mode 100644 index 0000000..e8a4894 --- /dev/null +++ b/backend/pkg/queuerunner/queuerunner.go @@ -0,0 +1,239 @@ +package queuerunner + +import ( + "context" + "encoding/json" + "fmt" + "log/slog" + "sync" + "time" + + "github.com/redis/go-redis/v9" + + "github.com/chaitin/MonkeyCode/backend/config" +) + +const ( + DefaultQueueName = "monkeycode:tasks:default" + ProcessingSetName = "monkeycode:tasks:processing" + TaskKeyPrefix = "monkeycode:task:" +) + +type TaskStatus string + +const ( + TaskStatusPending TaskStatus = "pending" + TaskStatusProcessing TaskStatus = "processing" + TaskStatusCompleted TaskStatus = "completed" + TaskStatusFailed TaskStatus = "failed" +) + +type Task[T any] struct { + ID string `json:"id"` + Status TaskStatus `json:"status"` + Data T `json:"data"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` + Error string `json:"error,omitempty"` +} + +type TaskHandler[T any] func(ctx context.Context, task *Task[T]) error + +type QueueRunner[T any] struct { + rdb *redis.Client + name string + handlers map[string]TaskHandler[T] + logger *slog.Logger + concurrent int + mu *sync.RWMutex +} + +func NewQueueRunner[T any]( + cfg *config.Config, + rdb *redis.Client, + logger *slog.Logger, +) *QueueRunner[T] { + return &QueueRunner[T]{ + rdb: rdb, + name: DefaultQueueName, + handlers: make(map[string]TaskHandler[T]), + logger: logger, + concurrent: cfg.Security.QueueLimit, + mu: &sync.RWMutex{}, + } +} + +func (r *QueueRunner[T]) addHandler(id string, h TaskHandler[T]) { + r.mu.Lock() + defer r.mu.Unlock() + r.handlers[id] = h +} + +func (r *QueueRunner[T]) getHandler(id string) (TaskHandler[T], bool) { + r.mu.RLock() + defer r.mu.RUnlock() + handler, exists := r.handlers[id] + return handler, exists +} + +func (r *QueueRunner[T]) delHandler(id string) { + r.mu.Lock() + defer r.mu.Unlock() + delete(r.handlers, id) +} + +func (r *QueueRunner[T]) Enqueue(ctx context.Context, id string, data T, h TaskHandler[T]) (string, error) { + task := &Task[T]{ + ID: id, + Status: TaskStatusPending, + Data: data, + CreatedAt: time.Now(), + UpdatedAt: time.Now(), + } + + r.addHandler(id, h) + + taskBytes, err := json.Marshal(task) + if err != nil { + return "", fmt.Errorf("marshal task: %w", err) + } + + pipe := r.rdb.Pipeline() + + taskKey := fmt.Sprintf("%s%s", TaskKeyPrefix, id) + pipe.Set(ctx, taskKey, taskBytes, 24*time.Hour) // 设置24小时过期时间 + + pipe.LPush(ctx, r.name, id) + + _, err = pipe.Exec(ctx) + if err != nil { + return "", fmt.Errorf("enqueue task: %w", err) + } + + return id, nil +} + +func (r *QueueRunner[T]) GetTask(ctx context.Context, taskID string) (*Task[T], error) { + taskKey := fmt.Sprintf("%s%s", TaskKeyPrefix, taskID) + taskBytes, err := r.rdb.Get(ctx, taskKey).Bytes() + if err != nil { + if err == redis.Nil { + return nil, fmt.Errorf("task not found: %s", taskID) + } + return nil, fmt.Errorf("get task: %w", err) + } + + var task Task[T] + if err := json.Unmarshal(taskBytes, &task); err != nil { + return nil, fmt.Errorf("unmarshal task: %w", err) + } + + return &task, nil +} + +func (r *QueueRunner[T]) UpdateTaskStatus(ctx context.Context, taskID string, status TaskStatus, err error) error { + task, getErr := r.GetTask(ctx, taskID) + if getErr != nil { + return getErr + } + + task.Status = status + task.UpdatedAt = time.Now() + if err != nil { + task.Error = err.Error() + } + + taskBytes, marshalErr := json.Marshal(task) + if marshalErr != nil { + return fmt.Errorf("marshal task: %w", marshalErr) + } + + taskKey := fmt.Sprintf("%s%s", TaskKeyPrefix, taskID) + if setErr := r.rdb.Set(ctx, taskKey, taskBytes, 24*time.Hour).Err(); setErr != nil { + return fmt.Errorf("update task status: %w", setErr) + } + + return nil +} + +func (r *QueueRunner[T]) processTask(ctx context.Context, taskID string) error { + task, err := r.GetTask(ctx, taskID) + if err != nil { + return fmt.Errorf("get task: %w", err) + } + + handler, ok := r.getHandler(task.ID) + if !ok { + err := fmt.Errorf("no handler for task id: %s", task.ID) + _ = r.UpdateTaskStatus(ctx, taskID, TaskStatusFailed, err) + r.delHandler(taskID) + return err + } + + if err := r.UpdateTaskStatus(ctx, taskID, TaskStatusProcessing, nil); err != nil { + r.delHandler(taskID) + return fmt.Errorf("update task status: %w", err) + } + + handleErr := handler(ctx, task) + + if handleErr != nil { + if err := r.UpdateTaskStatus(ctx, taskID, TaskStatusFailed, handleErr); err != nil { + r.logger.ErrorContext(ctx, "Failed to update task status", "error", err, "task_id", taskID) + } + r.delHandler(taskID) + return handleErr + } + + if err := r.UpdateTaskStatus(ctx, taskID, TaskStatusCompleted, nil); err != nil { + r.logger.ErrorContext(ctx, "Failed to update task status", "error", err, "task_id", taskID) + r.delHandler(taskID) + return err + } + + // Task processed successfully, remove handler + r.delHandler(taskID) + return nil +} + +func (r *QueueRunner[T]) Run(ctx context.Context) error { + r.logger.InfoContext(ctx, "Starting queue runner", "queue", r.name, "concurrent", r.concurrent) + + for i := 0; i < r.concurrent; i++ { + go func(workerID int) { + r.logger.InfoContext(ctx, "Starting worker", "worker_id", workerID) + for { + select { + case <-ctx.Done(): + r.logger.InfoContext(ctx, "Worker stopped", "worker_id", workerID) + return + default: + } + + result, err := r.rdb.BRPop(ctx, 5*time.Second, r.name).Result() + if err != nil { + if err == redis.Nil { + continue + } + r.logger.ErrorContext(ctx, "Failed to pop task from queue", "error", err, "worker_id", workerID) + time.Sleep(time.Second) + continue + } + + if len(result) != 2 { + r.logger.ErrorContext(ctx, "Invalid result from BRPOP", "result", result, "worker_id", workerID) + continue + } + + taskID := result[1] + r.logger.InfoContext(ctx, "Processing task", "task_id", taskID, "worker_id", workerID) + + if err := r.processTask(ctx, taskID); err != nil { + r.logger.ErrorContext(ctx, "Failed to process task", "error", err, "task_id", taskID, "worker_id", workerID) + } + } + }(i) + } + + return nil +} diff --git a/backend/pkg/scan/scan.go b/backend/pkg/scan/scan.go new file mode 100644 index 0000000..6ce0c6a --- /dev/null +++ b/backend/pkg/scan/scan.go @@ -0,0 +1,51 @@ +package scan + +import ( + "encoding/json" + "fmt" + "log" + "os" + "os/exec" + "strings" +) + +func Scan(id string, workspace, rule string) (*Result, error) { + if _, err := os.Stat(workspace); err != nil { + return nil, fmt.Errorf("failed to stat workspace: %w", err) + } + output := fmt.Sprintf("/tmp/%s.json", id) + cmd := exec.Command( + "/app/assets/sgp/sgp", + "--metrics=off", + "--disable-version-check", + "--disable-nosem", + "--time", + "--json", + "--output", output, + "--config", rule, + workspace, + ) + defer os.Remove(output) + + log.Printf("[Scan] Executing command: %s %s", cmd.Path, strings.Join(cmd.Args[1:], " ")) + + out, err := cmd.CombinedOutput() + if err != nil { + return nil, fmt.Errorf("failed to run command: %w out: %s", err, string(out)) + } + + b, err := os.ReadFile(output) + if err != nil { + return nil, fmt.Errorf("failed to read output file: %w", err) + } + + var r Result + if err := json.Unmarshal(b, &r); err != nil { + return nil, fmt.Errorf("failed to unmarshal JSON: %w", err) + } + + r.ID = id + r.Output = string(out) + + return &r, nil +} diff --git a/backend/pkg/scan/types.go b/backend/pkg/scan/types.go new file mode 100644 index 0000000..7054ab3 --- /dev/null +++ b/backend/pkg/scan/types.go @@ -0,0 +1,56 @@ +package scan + +type Position struct { + Col int `json:"col"` + Line int `json:"line"` + Offset int `json:"offset"` +} + +type Metavar struct { + AbstractContent string `json:"abstract_content"` + End Position `json:"end"` + Start Position `json:"start"` +} + +type Metadata struct { + AbstractFeysh map[string]string `json:"abstract_feysh"` + Category string `json:"category"` + CategoryFeysh map[string]string `json:"category_feysh"` + Confidence string `json:"confidence"` + Cwe any `json:"cwe,omitempty"` + FeyshID string `json:"feysh_id"` + Gb []string `json:"gb,omitempty"` + Impact string `json:"impact"` + License string `json:"license"` + MessageZh string `json:"message_zh"` + NameFeysh map[string]string `json:"name_feysh"` + Owasp any `json:"owasp,omitempty"` +} + +type Extra struct { + EngineKind string `json:"engine_kind"` + Fingerprint string `json:"fingerprint"` + Fix string `json:"fix"` + IsIgnored bool `json:"is_ignored"` + Lines string `json:"lines"` + Message string `json:"message"` + Metadata Metadata `json:"metadata"` + Metavars map[string]Metavar `json:"metavars"` + Severity string `json:"severity"` + ValidationState string `json:"validation_state"` +} + +type ResultItem struct { + CheckID string `json:"check_id"` + End Position `json:"end"` + Extra Extra `json:"extra"` + Path string `json:"path"` + Start Position `json:"start"` +} + +type Result struct { + ID string + Output string + Prefix string + Results []ResultItem `json:"results"` +} diff --git a/backend/pro b/backend/pro index cb3420b..6320fb5 160000 --- a/backend/pro +++ b/backend/pro @@ -1 +1 @@ -Subproject commit cb3420b603e9250d6ed20eb3a9b0ce05299ddd40 +Subproject commit 6320fb59825885e6e26800249f8622aed69533cd diff --git a/ui/nginx.conf b/ui/nginx.conf index 0acb46d..850cd85 100644 --- a/ui/nginx.conf +++ b/ui/nginx.conf @@ -50,6 +50,14 @@ http { proxy_pass http://backend; } + location /socket.io { + proxy_pass http://backend; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade"; + proxy_set_header Host $host; + } + location /v1/chat/completions { proxy_pass http://backend; proxy_http_version 1.1;