From 9388e149d645d7dec588ee4f4c9d8dbc7f03d51d Mon Sep 17 00:00:00 2001 From: Haoxin Li Date: Fri, 25 Jul 2025 19:35:00 +0800 Subject: [PATCH] feat: Add CodeSnippet entity and related functionality - Introduced CodeSnippet schema with fields for snippet details and relationships to WorkspaceFile. - Enhanced WorkspaceFileUpdate and WorkspaceFileUpdateOne to manage snippets, including adding, removing, and clearing snippet relationships. - Updated Swagger documentation to include new API endpoints for CLI command execution and workspace file management. - Implemented domain structures for handling code files and AST parsing results. - Refactored Workspace and WorkspaceFile use cases to support new functionalities. - Adjusted CLI command execution to handle code file information in JSON format. - Improved error handling and logging throughout the workspace and file management processes. --- backend/cmd/server/wire_gen.go | 6 +- backend/db/client.go | 199 +- backend/db/codesnippet.go | 333 ++++ backend/db/codesnippet/codesnippet.go | 187 ++ backend/db/codesnippet/where.go | 1008 ++++++++++ backend/db/codesnippet_create.go | 1667 ++++++++++++++++ backend/db/codesnippet_delete.go | 88 + backend/db/codesnippet_query.go | 657 +++++++ backend/db/codesnippet_update.go | 1140 +++++++++++ backend/db/ent.go | 2 + backend/db/hook/hook.go | 12 + backend/db/intercept/intercept.go | 30 + backend/db/migrate/schema.go | 63 + backend/db/mutation.go | 1751 ++++++++++++++++- backend/db/page.go | 14 + backend/db/predicate/predicate.go | 3 + backend/db/tx.go | 3 + backend/db/workspacefile.go | 18 +- backend/db/workspacefile/where.go | 23 + backend/db/workspacefile/workspacefile.go | 30 + backend/db/workspacefile_create.go | 32 + backend/db/workspacefile_query.go | 77 +- backend/db/workspacefile_update.go | 163 ++ backend/docs/swagger.json | 248 +++ backend/domain/ast.go | 13 + backend/domain/workspace.go | 150 +- backend/ent/schema/codesnippet.go | 78 + backend/ent/schema/workspacefile.go | 1 + backend/internal/provider.go | 2 + backend/internal/socket/handler/socket.go | 26 +- .../workspace/handler/http/v1/workspace.go | 19 +- .../internal/workspace/usecase/workspace.go | 36 +- backend/pkg/cli/cli.go | 50 +- 33 files changed, 8023 insertions(+), 106 deletions(-) create mode 100644 backend/db/codesnippet.go create mode 100644 backend/db/codesnippet/codesnippet.go create mode 100644 backend/db/codesnippet/where.go create mode 100644 backend/db/codesnippet_create.go create mode 100644 backend/db/codesnippet_delete.go create mode 100644 backend/db/codesnippet_query.go create mode 100644 backend/db/codesnippet_update.go create mode 100644 backend/domain/ast.go create mode 100644 backend/ent/schema/codesnippet.go diff --git a/backend/cmd/server/wire_gen.go b/backend/cmd/server/wire_gen.go index 771c53b..2f0b7f7 100644 --- a/backend/cmd/server/wire_gen.go +++ b/backend/cmd/server/wire_gen.go @@ -91,8 +91,10 @@ func newServer() (*Server, error) { dashboardHandler := v1_4.NewDashboardHandler(web, dashboardUsecase, authMiddleware, activeMiddleware) billingHandler := v1_5.NewBillingHandler(web, billingUsecase, authMiddleware, activeMiddleware) workspaceFileRepo := repo8.NewWorkspaceFileRepo(client) - workspaceFileUsecase := usecase7.NewWorkspaceFileUsecase(workspaceFileRepo, configConfig, slogLogger) - socketHandler, err := handler.NewSocketHandler(configConfig, slogLogger, workspaceFileUsecase, userUsecase) + workspaceRepo := repo8.NewWorkspaceRepo(client) + workspaceUsecase := usecase7.NewWorkspaceUsecase(workspaceRepo, configConfig, slogLogger) + workspaceFileUsecase := usecase7.NewWorkspaceFileUsecase(workspaceFileRepo, workspaceUsecase, configConfig, slogLogger) + socketHandler, err := handler.NewSocketHandler(configConfig, slogLogger, workspaceFileUsecase, workspaceUsecase, userUsecase) if err != nil { return nil, err } diff --git a/backend/db/client.go b/backend/db/client.go index 71cf629..b985066 100644 --- a/backend/db/client.go +++ b/backend/db/client.go @@ -23,6 +23,7 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/billingquota" "github.com/chaitin/MonkeyCode/backend/db/billingrecord" "github.com/chaitin/MonkeyCode/backend/db/billingusage" + "github.com/chaitin/MonkeyCode/backend/db/codesnippet" "github.com/chaitin/MonkeyCode/backend/db/extension" "github.com/chaitin/MonkeyCode/backend/db/invitecode" "github.com/chaitin/MonkeyCode/backend/db/model" @@ -59,6 +60,8 @@ type Client struct { BillingRecord *BillingRecordClient // BillingUsage is the client for interacting with the BillingUsage builders. BillingUsage *BillingUsageClient + // CodeSnippet is the client for interacting with the CodeSnippet builders. + CodeSnippet *CodeSnippetClient // Extension is the client for interacting with the Extension builders. Extension *ExtensionClient // InviteCode is the client for interacting with the InviteCode builders. @@ -103,6 +106,7 @@ func (c *Client) init() { c.BillingQuota = NewBillingQuotaClient(c.config) c.BillingRecord = NewBillingRecordClient(c.config) c.BillingUsage = NewBillingUsageClient(c.config) + c.CodeSnippet = NewCodeSnippetClient(c.config) c.Extension = NewExtensionClient(c.config) c.InviteCode = NewInviteCodeClient(c.config) c.Model = NewModelClient(c.config) @@ -215,6 +219,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { BillingQuota: NewBillingQuotaClient(cfg), BillingRecord: NewBillingRecordClient(cfg), BillingUsage: NewBillingUsageClient(cfg), + CodeSnippet: NewCodeSnippetClient(cfg), Extension: NewExtensionClient(cfg), InviteCode: NewInviteCodeClient(cfg), Model: NewModelClient(cfg), @@ -254,6 +259,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) BillingQuota: NewBillingQuotaClient(cfg), BillingRecord: NewBillingRecordClient(cfg), BillingUsage: NewBillingUsageClient(cfg), + CodeSnippet: NewCodeSnippetClient(cfg), Extension: NewExtensionClient(cfg), InviteCode: NewInviteCodeClient(cfg), Model: NewModelClient(cfg), @@ -297,9 +303,10 @@ func (c *Client) Close() error { 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.Extension, c.InviteCode, c.Model, - c.ModelProvider, c.ModelProviderModel, c.Setting, c.Task, c.TaskRecord, c.User, - c.UserIdentity, c.UserLoginHistory, c.Workspace, c.WorkspaceFile, + c.BillingRecord, c.BillingUsage, c.CodeSnippet, c.Extension, c.InviteCode, + c.Model, c.ModelProvider, c.ModelProviderModel, c.Setting, c.Task, + c.TaskRecord, c.User, c.UserIdentity, c.UserLoginHistory, c.Workspace, + c.WorkspaceFile, } { n.Use(hooks...) } @@ -310,9 +317,10 @@ func (c *Client) Use(hooks ...Hook) { 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.Extension, c.InviteCode, c.Model, - c.ModelProvider, c.ModelProviderModel, c.Setting, c.Task, c.TaskRecord, c.User, - c.UserIdentity, c.UserLoginHistory, c.Workspace, c.WorkspaceFile, + c.BillingRecord, c.BillingUsage, c.CodeSnippet, c.Extension, c.InviteCode, + c.Model, c.ModelProvider, c.ModelProviderModel, c.Setting, c.Task, + c.TaskRecord, c.User, c.UserIdentity, c.UserLoginHistory, c.Workspace, + c.WorkspaceFile, } { n.Intercept(interceptors...) } @@ -335,6 +343,8 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { return c.BillingRecord.mutate(ctx, m) case *BillingUsageMutation: return c.BillingUsage.mutate(ctx, m) + case *CodeSnippetMutation: + return c.CodeSnippet.mutate(ctx, m) case *ExtensionMutation: return c.Extension.mutate(ctx, m) case *InviteCodeMutation: @@ -1349,6 +1359,155 @@ func (c *BillingUsageClient) mutate(ctx context.Context, m *BillingUsageMutation } } +// CodeSnippetClient is a client for the CodeSnippet schema. +type CodeSnippetClient struct { + config +} + +// NewCodeSnippetClient returns a client for the CodeSnippet from the given config. +func NewCodeSnippetClient(c config) *CodeSnippetClient { + return &CodeSnippetClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `codesnippet.Hooks(f(g(h())))`. +func (c *CodeSnippetClient) Use(hooks ...Hook) { + c.hooks.CodeSnippet = append(c.hooks.CodeSnippet, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `codesnippet.Intercept(f(g(h())))`. +func (c *CodeSnippetClient) Intercept(interceptors ...Interceptor) { + c.inters.CodeSnippet = append(c.inters.CodeSnippet, interceptors...) +} + +// Create returns a builder for creating a CodeSnippet entity. +func (c *CodeSnippetClient) Create() *CodeSnippetCreate { + mutation := newCodeSnippetMutation(c.config, OpCreate) + return &CodeSnippetCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of CodeSnippet entities. +func (c *CodeSnippetClient) CreateBulk(builders ...*CodeSnippetCreate) *CodeSnippetCreateBulk { + return &CodeSnippetCreateBulk{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 *CodeSnippetClient) MapCreateBulk(slice any, setFunc func(*CodeSnippetCreate, int)) *CodeSnippetCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &CodeSnippetCreateBulk{err: fmt.Errorf("calling to CodeSnippetClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*CodeSnippetCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &CodeSnippetCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for CodeSnippet. +func (c *CodeSnippetClient) Update() *CodeSnippetUpdate { + mutation := newCodeSnippetMutation(c.config, OpUpdate) + return &CodeSnippetUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *CodeSnippetClient) UpdateOne(cs *CodeSnippet) *CodeSnippetUpdateOne { + mutation := newCodeSnippetMutation(c.config, OpUpdateOne, withCodeSnippet(cs)) + return &CodeSnippetUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *CodeSnippetClient) UpdateOneID(id uuid.UUID) *CodeSnippetUpdateOne { + mutation := newCodeSnippetMutation(c.config, OpUpdateOne, withCodeSnippetID(id)) + return &CodeSnippetUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for CodeSnippet. +func (c *CodeSnippetClient) Delete() *CodeSnippetDelete { + mutation := newCodeSnippetMutation(c.config, OpDelete) + return &CodeSnippetDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *CodeSnippetClient) DeleteOne(cs *CodeSnippet) *CodeSnippetDeleteOne { + return c.DeleteOneID(cs.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *CodeSnippetClient) DeleteOneID(id uuid.UUID) *CodeSnippetDeleteOne { + builder := c.Delete().Where(codesnippet.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &CodeSnippetDeleteOne{builder} +} + +// Query returns a query builder for CodeSnippet. +func (c *CodeSnippetClient) Query() *CodeSnippetQuery { + return &CodeSnippetQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeCodeSnippet}, + inters: c.Interceptors(), + } +} + +// Get returns a CodeSnippet entity by its id. +func (c *CodeSnippetClient) Get(ctx context.Context, id uuid.UUID) (*CodeSnippet, error) { + return c.Query().Where(codesnippet.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *CodeSnippetClient) GetX(ctx context.Context, id uuid.UUID) *CodeSnippet { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QuerySourceFile queries the source_file edge of a CodeSnippet. +func (c *CodeSnippetClient) QuerySourceFile(cs *CodeSnippet) *WorkspaceFileQuery { + query := (&WorkspaceFileClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := cs.ID + step := sqlgraph.NewStep( + sqlgraph.From(codesnippet.Table, codesnippet.FieldID, id), + sqlgraph.To(workspacefile.Table, workspacefile.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, codesnippet.SourceFileTable, codesnippet.SourceFileColumn), + ) + fromV = sqlgraph.Neighbors(cs.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *CodeSnippetClient) Hooks() []Hook { + return c.hooks.CodeSnippet +} + +// Interceptors returns the client interceptors. +func (c *CodeSnippetClient) Interceptors() []Interceptor { + return c.inters.CodeSnippet +} + +func (c *CodeSnippetClient) mutate(ctx context.Context, m *CodeSnippetMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&CodeSnippetCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&CodeSnippetUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&CodeSnippetUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&CodeSnippetDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown CodeSnippet mutation op: %q", m.Op()) + } +} + // ExtensionClient is a client for the Extension schema. type ExtensionClient struct { config @@ -3393,6 +3552,22 @@ func (c *WorkspaceFileClient) QueryWorkspace(wf *WorkspaceFile) *WorkspaceQuery return query } +// QuerySnippets queries the snippets edge of a WorkspaceFile. +func (c *WorkspaceFileClient) QuerySnippets(wf *WorkspaceFile) *CodeSnippetQuery { + query := (&CodeSnippetClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := wf.ID + step := sqlgraph.NewStep( + sqlgraph.From(workspacefile.Table, workspacefile.FieldID, id), + sqlgraph.To(codesnippet.Table, codesnippet.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, workspacefile.SnippetsTable, workspacefile.SnippetsColumn), + ) + fromV = sqlgraph.Neighbors(wf.driver.Dialect(), step) + return fromV, nil + } + return query +} + // Hooks returns the client hooks. func (c *WorkspaceFileClient) Hooks() []Hook { return c.hooks.WorkspaceFile @@ -3422,15 +3597,15 @@ func (c *WorkspaceFileClient) mutate(ctx context.Context, m *WorkspaceFileMutati type ( hooks struct { Admin, AdminLoginHistory, ApiKey, BillingPlan, BillingQuota, BillingRecord, - BillingUsage, Extension, InviteCode, Model, ModelProvider, ModelProviderModel, - Setting, Task, TaskRecord, User, UserIdentity, UserLoginHistory, Workspace, - WorkspaceFile []ent.Hook + BillingUsage, CodeSnippet, Extension, InviteCode, Model, ModelProvider, + ModelProviderModel, Setting, Task, TaskRecord, User, UserIdentity, + UserLoginHistory, Workspace, WorkspaceFile []ent.Hook } inters struct { Admin, AdminLoginHistory, ApiKey, BillingPlan, BillingQuota, BillingRecord, - BillingUsage, Extension, InviteCode, Model, ModelProvider, ModelProviderModel, - Setting, Task, TaskRecord, User, UserIdentity, UserLoginHistory, Workspace, - WorkspaceFile []ent.Interceptor + BillingUsage, CodeSnippet, Extension, InviteCode, Model, ModelProvider, + ModelProviderModel, Setting, Task, TaskRecord, User, UserIdentity, + UserLoginHistory, Workspace, WorkspaceFile []ent.Interceptor } ) diff --git a/backend/db/codesnippet.go b/backend/db/codesnippet.go new file mode 100644 index 0000000..a338f88 --- /dev/null +++ b/backend/db/codesnippet.go @@ -0,0 +1,333 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "encoding/json" + "fmt" + "strings" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/chaitin/MonkeyCode/backend/db/codesnippet" + "github.com/chaitin/MonkeyCode/backend/db/workspacefile" + "github.com/google/uuid" +) + +// CodeSnippet is the model entity for the CodeSnippet schema. +type CodeSnippet struct { + config `json:"-"` + // ID of the ent. + ID uuid.UUID `json:"id,omitempty"` + // 关联的源文件ID + WorkspaceFileID uuid.UUID `json:"workspace_file_id,omitempty"` + // 符号名称 (e.g., function name, class name) + Name string `json:"name,omitempty"` + // 片段类型 (e.g., import_or_include, function_or_method) + SnippetType string `json:"snippet_type,omitempty"` + // 代码语言 + Language string `json:"language,omitempty"` + // 代码片段原文 (rangeText) + Content string `json:"content,omitempty"` + // 代码片段内容的哈希值,用于去重 + Hash string `json:"hash,omitempty"` + // 在源文件中的起始行号 + StartLine int `json:"start_line,omitempty"` + // 在源文件中的结束行号 + EndLine int `json:"end_line,omitempty"` + // 在源文件中的起始列号 + StartColumn int `json:"start_column,omitempty"` + // 在源文件中的结束列号 + EndColumn int `json:"end_column,omitempty"` + // 所处的namespace名称 + Namespace string `json:"namespace,omitempty"` + // 所处的class/struct/interface名称 + ContainerName string `json:"container_name,omitempty"` + // 作用域链 + Scope []string `json:"scope,omitempty"` + // 依赖项 + Dependencies []string `json:"dependencies,omitempty"` + // 参数信息列表 (ParameterInfo[]) + Parameters []map[string]interface{} `json:"parameters,omitempty"` + // 函数/方法签名 + Signature string `json:"signature,omitempty"` + // 定义文本,用于提供定义参考 + DefinitionText string `json:"definition_text,omitempty"` + // 结构化信息 (definition) + StructuredInfo map[string]interface{} `json:"structured_info,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the CodeSnippetQuery when eager-loading is set. + Edges CodeSnippetEdges `json:"edges"` + selectValues sql.SelectValues +} + +// CodeSnippetEdges holds the relations/edges for other nodes in the graph. +type CodeSnippetEdges struct { + // SourceFile holds the value of the source_file edge. + SourceFile *WorkspaceFile `json:"source_file,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// SourceFileOrErr returns the SourceFile value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e CodeSnippetEdges) SourceFileOrErr() (*WorkspaceFile, error) { + if e.SourceFile != nil { + return e.SourceFile, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: workspacefile.Label} + } + return nil, &NotLoadedError{edge: "source_file"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*CodeSnippet) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case codesnippet.FieldScope, codesnippet.FieldDependencies, codesnippet.FieldParameters, codesnippet.FieldStructuredInfo: + values[i] = new([]byte) + case codesnippet.FieldStartLine, codesnippet.FieldEndLine, codesnippet.FieldStartColumn, codesnippet.FieldEndColumn: + values[i] = new(sql.NullInt64) + case codesnippet.FieldName, codesnippet.FieldSnippetType, codesnippet.FieldLanguage, codesnippet.FieldContent, codesnippet.FieldHash, codesnippet.FieldNamespace, codesnippet.FieldContainerName, codesnippet.FieldSignature, codesnippet.FieldDefinitionText: + values[i] = new(sql.NullString) + case codesnippet.FieldID, codesnippet.FieldWorkspaceFileID: + 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 CodeSnippet fields. +func (cs *CodeSnippet) 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 codesnippet.FieldID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value != nil { + cs.ID = *value + } + case codesnippet.FieldWorkspaceFileID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field workspace_file_id", values[i]) + } else if value != nil { + cs.WorkspaceFileID = *value + } + case codesnippet.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + cs.Name = value.String + } + case codesnippet.FieldSnippetType: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field snippet_type", values[i]) + } else if value.Valid { + cs.SnippetType = value.String + } + case codesnippet.FieldLanguage: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field language", values[i]) + } else if value.Valid { + cs.Language = value.String + } + case codesnippet.FieldContent: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field content", values[i]) + } else if value.Valid { + cs.Content = value.String + } + case codesnippet.FieldHash: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field hash", values[i]) + } else if value.Valid { + cs.Hash = value.String + } + case codesnippet.FieldStartLine: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field start_line", values[i]) + } else if value.Valid { + cs.StartLine = int(value.Int64) + } + case codesnippet.FieldEndLine: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field end_line", values[i]) + } else if value.Valid { + cs.EndLine = int(value.Int64) + } + case codesnippet.FieldStartColumn: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field start_column", values[i]) + } else if value.Valid { + cs.StartColumn = int(value.Int64) + } + case codesnippet.FieldEndColumn: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field end_column", values[i]) + } else if value.Valid { + cs.EndColumn = int(value.Int64) + } + case codesnippet.FieldNamespace: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field namespace", values[i]) + } else if value.Valid { + cs.Namespace = value.String + } + case codesnippet.FieldContainerName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field container_name", values[i]) + } else if value.Valid { + cs.ContainerName = value.String + } + case codesnippet.FieldScope: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field scope", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &cs.Scope); err != nil { + return fmt.Errorf("unmarshal field scope: %w", err) + } + } + case codesnippet.FieldDependencies: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field dependencies", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &cs.Dependencies); err != nil { + return fmt.Errorf("unmarshal field dependencies: %w", err) + } + } + case codesnippet.FieldParameters: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field parameters", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &cs.Parameters); err != nil { + return fmt.Errorf("unmarshal field parameters: %w", err) + } + } + case codesnippet.FieldSignature: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field signature", values[i]) + } else if value.Valid { + cs.Signature = value.String + } + case codesnippet.FieldDefinitionText: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field definition_text", values[i]) + } else if value.Valid { + cs.DefinitionText = value.String + } + case codesnippet.FieldStructuredInfo: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field structured_info", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &cs.StructuredInfo); err != nil { + return fmt.Errorf("unmarshal field structured_info: %w", err) + } + } + default: + cs.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the CodeSnippet. +// This includes values selected through modifiers, order, etc. +func (cs *CodeSnippet) Value(name string) (ent.Value, error) { + return cs.selectValues.Get(name) +} + +// QuerySourceFile queries the "source_file" edge of the CodeSnippet entity. +func (cs *CodeSnippet) QuerySourceFile() *WorkspaceFileQuery { + return NewCodeSnippetClient(cs.config).QuerySourceFile(cs) +} + +// Update returns a builder for updating this CodeSnippet. +// Note that you need to call CodeSnippet.Unwrap() before calling this method if this CodeSnippet +// was returned from a transaction, and the transaction was committed or rolled back. +func (cs *CodeSnippet) Update() *CodeSnippetUpdateOne { + return NewCodeSnippetClient(cs.config).UpdateOne(cs) +} + +// Unwrap unwraps the CodeSnippet 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 (cs *CodeSnippet) Unwrap() *CodeSnippet { + _tx, ok := cs.config.driver.(*txDriver) + if !ok { + panic("db: CodeSnippet is not a transactional entity") + } + cs.config.driver = _tx.drv + return cs +} + +// String implements the fmt.Stringer. +func (cs *CodeSnippet) String() string { + var builder strings.Builder + builder.WriteString("CodeSnippet(") + builder.WriteString(fmt.Sprintf("id=%v, ", cs.ID)) + builder.WriteString("workspace_file_id=") + builder.WriteString(fmt.Sprintf("%v", cs.WorkspaceFileID)) + builder.WriteString(", ") + builder.WriteString("name=") + builder.WriteString(cs.Name) + builder.WriteString(", ") + builder.WriteString("snippet_type=") + builder.WriteString(cs.SnippetType) + builder.WriteString(", ") + builder.WriteString("language=") + builder.WriteString(cs.Language) + builder.WriteString(", ") + builder.WriteString("content=") + builder.WriteString(cs.Content) + builder.WriteString(", ") + builder.WriteString("hash=") + builder.WriteString(cs.Hash) + builder.WriteString(", ") + builder.WriteString("start_line=") + builder.WriteString(fmt.Sprintf("%v", cs.StartLine)) + builder.WriteString(", ") + builder.WriteString("end_line=") + builder.WriteString(fmt.Sprintf("%v", cs.EndLine)) + builder.WriteString(", ") + builder.WriteString("start_column=") + builder.WriteString(fmt.Sprintf("%v", cs.StartColumn)) + builder.WriteString(", ") + builder.WriteString("end_column=") + builder.WriteString(fmt.Sprintf("%v", cs.EndColumn)) + builder.WriteString(", ") + builder.WriteString("namespace=") + builder.WriteString(cs.Namespace) + builder.WriteString(", ") + builder.WriteString("container_name=") + builder.WriteString(cs.ContainerName) + builder.WriteString(", ") + builder.WriteString("scope=") + builder.WriteString(fmt.Sprintf("%v", cs.Scope)) + builder.WriteString(", ") + builder.WriteString("dependencies=") + builder.WriteString(fmt.Sprintf("%v", cs.Dependencies)) + builder.WriteString(", ") + builder.WriteString("parameters=") + builder.WriteString(fmt.Sprintf("%v", cs.Parameters)) + builder.WriteString(", ") + builder.WriteString("signature=") + builder.WriteString(cs.Signature) + builder.WriteString(", ") + builder.WriteString("definition_text=") + builder.WriteString(cs.DefinitionText) + builder.WriteString(", ") + builder.WriteString("structured_info=") + builder.WriteString(fmt.Sprintf("%v", cs.StructuredInfo)) + builder.WriteByte(')') + return builder.String() +} + +// CodeSnippets is a parsable slice of CodeSnippet. +type CodeSnippets []*CodeSnippet diff --git a/backend/db/codesnippet/codesnippet.go b/backend/db/codesnippet/codesnippet.go new file mode 100644 index 0000000..95c6ece --- /dev/null +++ b/backend/db/codesnippet/codesnippet.go @@ -0,0 +1,187 @@ +// Code generated by ent, DO NOT EDIT. + +package codesnippet + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the codesnippet type in the database. + Label = "code_snippet" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldWorkspaceFileID holds the string denoting the workspace_file_id field in the database. + FieldWorkspaceFileID = "workspace_file_id" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldSnippetType holds the string denoting the snippet_type field in the database. + FieldSnippetType = "snippet_type" + // FieldLanguage holds the string denoting the language field in the database. + FieldLanguage = "language" + // FieldContent holds the string denoting the content field in the database. + FieldContent = "content" + // FieldHash holds the string denoting the hash field in the database. + FieldHash = "hash" + // FieldStartLine holds the string denoting the start_line field in the database. + FieldStartLine = "start_line" + // FieldEndLine holds the string denoting the end_line field in the database. + FieldEndLine = "end_line" + // FieldStartColumn holds the string denoting the start_column field in the database. + FieldStartColumn = "start_column" + // FieldEndColumn holds the string denoting the end_column field in the database. + FieldEndColumn = "end_column" + // FieldNamespace holds the string denoting the namespace field in the database. + FieldNamespace = "namespace" + // FieldContainerName holds the string denoting the container_name field in the database. + FieldContainerName = "container_name" + // FieldScope holds the string denoting the scope field in the database. + FieldScope = "scope" + // FieldDependencies holds the string denoting the dependencies field in the database. + FieldDependencies = "dependencies" + // FieldParameters holds the string denoting the parameters field in the database. + FieldParameters = "parameters" + // FieldSignature holds the string denoting the signature field in the database. + FieldSignature = "signature" + // FieldDefinitionText holds the string denoting the definition_text field in the database. + FieldDefinitionText = "definition_text" + // FieldStructuredInfo holds the string denoting the structured_info field in the database. + FieldStructuredInfo = "structured_info" + // EdgeSourceFile holds the string denoting the source_file edge name in mutations. + EdgeSourceFile = "source_file" + // Table holds the table name of the codesnippet in the database. + Table = "code_snippets" + // SourceFileTable is the table that holds the source_file relation/edge. + SourceFileTable = "code_snippets" + // SourceFileInverseTable is the table name for the WorkspaceFile entity. + // It exists in this package in order to avoid circular dependency with the "workspacefile" package. + SourceFileInverseTable = "workspace_files" + // SourceFileColumn is the table column denoting the source_file relation/edge. + SourceFileColumn = "workspace_file_id" +) + +// Columns holds all SQL columns for codesnippet fields. +var Columns = []string{ + FieldID, + FieldWorkspaceFileID, + FieldName, + FieldSnippetType, + FieldLanguage, + FieldContent, + FieldHash, + FieldStartLine, + FieldEndLine, + FieldStartColumn, + FieldEndColumn, + FieldNamespace, + FieldContainerName, + FieldScope, + FieldDependencies, + FieldParameters, + FieldSignature, + FieldDefinitionText, + FieldStructuredInfo, +} + +// 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 +} + +// OrderOption defines the ordering options for the CodeSnippet 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() +} + +// ByWorkspaceFileID orders the results by the workspace_file_id field. +func ByWorkspaceFileID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldWorkspaceFileID, opts...).ToFunc() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} + +// BySnippetType orders the results by the snippet_type field. +func BySnippetType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSnippetType, opts...).ToFunc() +} + +// ByLanguage orders the results by the language field. +func ByLanguage(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldLanguage, opts...).ToFunc() +} + +// ByContent orders the results by the content field. +func ByContent(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldContent, opts...).ToFunc() +} + +// ByHash orders the results by the hash field. +func ByHash(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldHash, opts...).ToFunc() +} + +// ByStartLine orders the results by the start_line field. +func ByStartLine(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldStartLine, opts...).ToFunc() +} + +// ByEndLine orders the results by the end_line field. +func ByEndLine(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldEndLine, opts...).ToFunc() +} + +// ByStartColumn orders the results by the start_column field. +func ByStartColumn(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldStartColumn, opts...).ToFunc() +} + +// ByEndColumn orders the results by the end_column field. +func ByEndColumn(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldEndColumn, opts...).ToFunc() +} + +// ByNamespace orders the results by the namespace field. +func ByNamespace(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldNamespace, opts...).ToFunc() +} + +// ByContainerName orders the results by the container_name field. +func ByContainerName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldContainerName, opts...).ToFunc() +} + +// BySignature orders the results by the signature field. +func BySignature(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSignature, opts...).ToFunc() +} + +// ByDefinitionText orders the results by the definition_text field. +func ByDefinitionText(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDefinitionText, opts...).ToFunc() +} + +// BySourceFileField orders the results by source_file field. +func BySourceFileField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newSourceFileStep(), sql.OrderByField(field, opts...)) + } +} +func newSourceFileStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(SourceFileInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SourceFileTable, SourceFileColumn), + ) +} diff --git a/backend/db/codesnippet/where.go b/backend/db/codesnippet/where.go new file mode 100644 index 0000000..cbf2225 --- /dev/null +++ b/backend/db/codesnippet/where.go @@ -0,0 +1,1008 @@ +// Code generated by ent, DO NOT EDIT. + +package codesnippet + +import ( + "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.CodeSnippet { + return predicate.CodeSnippet(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id uuid.UUID) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id uuid.UUID) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...uuid.UUID) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...uuid.UUID) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id uuid.UUID) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id uuid.UUID) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id uuid.UUID) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id uuid.UUID) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldLTE(FieldID, id)) +} + +// WorkspaceFileID applies equality check predicate on the "workspace_file_id" field. It's identical to WorkspaceFileIDEQ. +func WorkspaceFileID(v uuid.UUID) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldEQ(FieldWorkspaceFileID, v)) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldEQ(FieldName, v)) +} + +// SnippetType applies equality check predicate on the "snippet_type" field. It's identical to SnippetTypeEQ. +func SnippetType(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldEQ(FieldSnippetType, v)) +} + +// Language applies equality check predicate on the "language" field. It's identical to LanguageEQ. +func Language(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldEQ(FieldLanguage, v)) +} + +// Content applies equality check predicate on the "content" field. It's identical to ContentEQ. +func Content(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldEQ(FieldContent, v)) +} + +// Hash applies equality check predicate on the "hash" field. It's identical to HashEQ. +func Hash(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldEQ(FieldHash, v)) +} + +// StartLine applies equality check predicate on the "start_line" field. It's identical to StartLineEQ. +func StartLine(v int) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldEQ(FieldStartLine, v)) +} + +// EndLine applies equality check predicate on the "end_line" field. It's identical to EndLineEQ. +func EndLine(v int) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldEQ(FieldEndLine, v)) +} + +// StartColumn applies equality check predicate on the "start_column" field. It's identical to StartColumnEQ. +func StartColumn(v int) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldEQ(FieldStartColumn, v)) +} + +// EndColumn applies equality check predicate on the "end_column" field. It's identical to EndColumnEQ. +func EndColumn(v int) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldEQ(FieldEndColumn, v)) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldEQ(FieldNamespace, v)) +} + +// ContainerName applies equality check predicate on the "container_name" field. It's identical to ContainerNameEQ. +func ContainerName(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldEQ(FieldContainerName, v)) +} + +// Signature applies equality check predicate on the "signature" field. It's identical to SignatureEQ. +func Signature(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldEQ(FieldSignature, v)) +} + +// DefinitionText applies equality check predicate on the "definition_text" field. It's identical to DefinitionTextEQ. +func DefinitionText(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldEQ(FieldDefinitionText, v)) +} + +// WorkspaceFileIDEQ applies the EQ predicate on the "workspace_file_id" field. +func WorkspaceFileIDEQ(v uuid.UUID) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldEQ(FieldWorkspaceFileID, v)) +} + +// WorkspaceFileIDNEQ applies the NEQ predicate on the "workspace_file_id" field. +func WorkspaceFileIDNEQ(v uuid.UUID) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldNEQ(FieldWorkspaceFileID, v)) +} + +// WorkspaceFileIDIn applies the In predicate on the "workspace_file_id" field. +func WorkspaceFileIDIn(vs ...uuid.UUID) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldIn(FieldWorkspaceFileID, vs...)) +} + +// WorkspaceFileIDNotIn applies the NotIn predicate on the "workspace_file_id" field. +func WorkspaceFileIDNotIn(vs ...uuid.UUID) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldNotIn(FieldWorkspaceFileID, vs...)) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldEQ(FieldName, v)) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldNEQ(FieldName, v)) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldIn(FieldName, vs...)) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldNotIn(FieldName, vs...)) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldGT(FieldName, v)) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldGTE(FieldName, v)) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldLT(FieldName, v)) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldLTE(FieldName, v)) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldContains(FieldName, v)) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldHasPrefix(FieldName, v)) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldHasSuffix(FieldName, v)) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldEqualFold(FieldName, v)) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldContainsFold(FieldName, v)) +} + +// SnippetTypeEQ applies the EQ predicate on the "snippet_type" field. +func SnippetTypeEQ(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldEQ(FieldSnippetType, v)) +} + +// SnippetTypeNEQ applies the NEQ predicate on the "snippet_type" field. +func SnippetTypeNEQ(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldNEQ(FieldSnippetType, v)) +} + +// SnippetTypeIn applies the In predicate on the "snippet_type" field. +func SnippetTypeIn(vs ...string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldIn(FieldSnippetType, vs...)) +} + +// SnippetTypeNotIn applies the NotIn predicate on the "snippet_type" field. +func SnippetTypeNotIn(vs ...string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldNotIn(FieldSnippetType, vs...)) +} + +// SnippetTypeGT applies the GT predicate on the "snippet_type" field. +func SnippetTypeGT(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldGT(FieldSnippetType, v)) +} + +// SnippetTypeGTE applies the GTE predicate on the "snippet_type" field. +func SnippetTypeGTE(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldGTE(FieldSnippetType, v)) +} + +// SnippetTypeLT applies the LT predicate on the "snippet_type" field. +func SnippetTypeLT(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldLT(FieldSnippetType, v)) +} + +// SnippetTypeLTE applies the LTE predicate on the "snippet_type" field. +func SnippetTypeLTE(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldLTE(FieldSnippetType, v)) +} + +// SnippetTypeContains applies the Contains predicate on the "snippet_type" field. +func SnippetTypeContains(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldContains(FieldSnippetType, v)) +} + +// SnippetTypeHasPrefix applies the HasPrefix predicate on the "snippet_type" field. +func SnippetTypeHasPrefix(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldHasPrefix(FieldSnippetType, v)) +} + +// SnippetTypeHasSuffix applies the HasSuffix predicate on the "snippet_type" field. +func SnippetTypeHasSuffix(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldHasSuffix(FieldSnippetType, v)) +} + +// SnippetTypeEqualFold applies the EqualFold predicate on the "snippet_type" field. +func SnippetTypeEqualFold(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldEqualFold(FieldSnippetType, v)) +} + +// SnippetTypeContainsFold applies the ContainsFold predicate on the "snippet_type" field. +func SnippetTypeContainsFold(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldContainsFold(FieldSnippetType, v)) +} + +// LanguageEQ applies the EQ predicate on the "language" field. +func LanguageEQ(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldEQ(FieldLanguage, v)) +} + +// LanguageNEQ applies the NEQ predicate on the "language" field. +func LanguageNEQ(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldNEQ(FieldLanguage, v)) +} + +// LanguageIn applies the In predicate on the "language" field. +func LanguageIn(vs ...string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldIn(FieldLanguage, vs...)) +} + +// LanguageNotIn applies the NotIn predicate on the "language" field. +func LanguageNotIn(vs ...string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldNotIn(FieldLanguage, vs...)) +} + +// LanguageGT applies the GT predicate on the "language" field. +func LanguageGT(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldGT(FieldLanguage, v)) +} + +// LanguageGTE applies the GTE predicate on the "language" field. +func LanguageGTE(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldGTE(FieldLanguage, v)) +} + +// LanguageLT applies the LT predicate on the "language" field. +func LanguageLT(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldLT(FieldLanguage, v)) +} + +// LanguageLTE applies the LTE predicate on the "language" field. +func LanguageLTE(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldLTE(FieldLanguage, v)) +} + +// LanguageContains applies the Contains predicate on the "language" field. +func LanguageContains(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldContains(FieldLanguage, v)) +} + +// LanguageHasPrefix applies the HasPrefix predicate on the "language" field. +func LanguageHasPrefix(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldHasPrefix(FieldLanguage, v)) +} + +// LanguageHasSuffix applies the HasSuffix predicate on the "language" field. +func LanguageHasSuffix(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldHasSuffix(FieldLanguage, v)) +} + +// LanguageEqualFold applies the EqualFold predicate on the "language" field. +func LanguageEqualFold(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldEqualFold(FieldLanguage, v)) +} + +// LanguageContainsFold applies the ContainsFold predicate on the "language" field. +func LanguageContainsFold(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldContainsFold(FieldLanguage, v)) +} + +// ContentEQ applies the EQ predicate on the "content" field. +func ContentEQ(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldEQ(FieldContent, v)) +} + +// ContentNEQ applies the NEQ predicate on the "content" field. +func ContentNEQ(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldNEQ(FieldContent, v)) +} + +// ContentIn applies the In predicate on the "content" field. +func ContentIn(vs ...string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldIn(FieldContent, vs...)) +} + +// ContentNotIn applies the NotIn predicate on the "content" field. +func ContentNotIn(vs ...string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldNotIn(FieldContent, vs...)) +} + +// ContentGT applies the GT predicate on the "content" field. +func ContentGT(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldGT(FieldContent, v)) +} + +// ContentGTE applies the GTE predicate on the "content" field. +func ContentGTE(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldGTE(FieldContent, v)) +} + +// ContentLT applies the LT predicate on the "content" field. +func ContentLT(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldLT(FieldContent, v)) +} + +// ContentLTE applies the LTE predicate on the "content" field. +func ContentLTE(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldLTE(FieldContent, v)) +} + +// ContentContains applies the Contains predicate on the "content" field. +func ContentContains(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldContains(FieldContent, v)) +} + +// ContentHasPrefix applies the HasPrefix predicate on the "content" field. +func ContentHasPrefix(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldHasPrefix(FieldContent, v)) +} + +// ContentHasSuffix applies the HasSuffix predicate on the "content" field. +func ContentHasSuffix(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldHasSuffix(FieldContent, v)) +} + +// ContentEqualFold applies the EqualFold predicate on the "content" field. +func ContentEqualFold(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldEqualFold(FieldContent, v)) +} + +// ContentContainsFold applies the ContainsFold predicate on the "content" field. +func ContentContainsFold(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldContainsFold(FieldContent, v)) +} + +// HashEQ applies the EQ predicate on the "hash" field. +func HashEQ(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldEQ(FieldHash, v)) +} + +// HashNEQ applies the NEQ predicate on the "hash" field. +func HashNEQ(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldNEQ(FieldHash, v)) +} + +// HashIn applies the In predicate on the "hash" field. +func HashIn(vs ...string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldIn(FieldHash, vs...)) +} + +// HashNotIn applies the NotIn predicate on the "hash" field. +func HashNotIn(vs ...string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldNotIn(FieldHash, vs...)) +} + +// HashGT applies the GT predicate on the "hash" field. +func HashGT(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldGT(FieldHash, v)) +} + +// HashGTE applies the GTE predicate on the "hash" field. +func HashGTE(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldGTE(FieldHash, v)) +} + +// HashLT applies the LT predicate on the "hash" field. +func HashLT(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldLT(FieldHash, v)) +} + +// HashLTE applies the LTE predicate on the "hash" field. +func HashLTE(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldLTE(FieldHash, v)) +} + +// HashContains applies the Contains predicate on the "hash" field. +func HashContains(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldContains(FieldHash, v)) +} + +// HashHasPrefix applies the HasPrefix predicate on the "hash" field. +func HashHasPrefix(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldHasPrefix(FieldHash, v)) +} + +// HashHasSuffix applies the HasSuffix predicate on the "hash" field. +func HashHasSuffix(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldHasSuffix(FieldHash, v)) +} + +// HashEqualFold applies the EqualFold predicate on the "hash" field. +func HashEqualFold(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldEqualFold(FieldHash, v)) +} + +// HashContainsFold applies the ContainsFold predicate on the "hash" field. +func HashContainsFold(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldContainsFold(FieldHash, v)) +} + +// StartLineEQ applies the EQ predicate on the "start_line" field. +func StartLineEQ(v int) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldEQ(FieldStartLine, v)) +} + +// StartLineNEQ applies the NEQ predicate on the "start_line" field. +func StartLineNEQ(v int) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldNEQ(FieldStartLine, v)) +} + +// StartLineIn applies the In predicate on the "start_line" field. +func StartLineIn(vs ...int) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldIn(FieldStartLine, vs...)) +} + +// StartLineNotIn applies the NotIn predicate on the "start_line" field. +func StartLineNotIn(vs ...int) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldNotIn(FieldStartLine, vs...)) +} + +// StartLineGT applies the GT predicate on the "start_line" field. +func StartLineGT(v int) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldGT(FieldStartLine, v)) +} + +// StartLineGTE applies the GTE predicate on the "start_line" field. +func StartLineGTE(v int) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldGTE(FieldStartLine, v)) +} + +// StartLineLT applies the LT predicate on the "start_line" field. +func StartLineLT(v int) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldLT(FieldStartLine, v)) +} + +// StartLineLTE applies the LTE predicate on the "start_line" field. +func StartLineLTE(v int) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldLTE(FieldStartLine, v)) +} + +// EndLineEQ applies the EQ predicate on the "end_line" field. +func EndLineEQ(v int) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldEQ(FieldEndLine, v)) +} + +// EndLineNEQ applies the NEQ predicate on the "end_line" field. +func EndLineNEQ(v int) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldNEQ(FieldEndLine, v)) +} + +// EndLineIn applies the In predicate on the "end_line" field. +func EndLineIn(vs ...int) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldIn(FieldEndLine, vs...)) +} + +// EndLineNotIn applies the NotIn predicate on the "end_line" field. +func EndLineNotIn(vs ...int) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldNotIn(FieldEndLine, vs...)) +} + +// EndLineGT applies the GT predicate on the "end_line" field. +func EndLineGT(v int) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldGT(FieldEndLine, v)) +} + +// EndLineGTE applies the GTE predicate on the "end_line" field. +func EndLineGTE(v int) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldGTE(FieldEndLine, v)) +} + +// EndLineLT applies the LT predicate on the "end_line" field. +func EndLineLT(v int) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldLT(FieldEndLine, v)) +} + +// EndLineLTE applies the LTE predicate on the "end_line" field. +func EndLineLTE(v int) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldLTE(FieldEndLine, v)) +} + +// StartColumnEQ applies the EQ predicate on the "start_column" field. +func StartColumnEQ(v int) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldEQ(FieldStartColumn, v)) +} + +// StartColumnNEQ applies the NEQ predicate on the "start_column" field. +func StartColumnNEQ(v int) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldNEQ(FieldStartColumn, v)) +} + +// StartColumnIn applies the In predicate on the "start_column" field. +func StartColumnIn(vs ...int) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldIn(FieldStartColumn, vs...)) +} + +// StartColumnNotIn applies the NotIn predicate on the "start_column" field. +func StartColumnNotIn(vs ...int) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldNotIn(FieldStartColumn, vs...)) +} + +// StartColumnGT applies the GT predicate on the "start_column" field. +func StartColumnGT(v int) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldGT(FieldStartColumn, v)) +} + +// StartColumnGTE applies the GTE predicate on the "start_column" field. +func StartColumnGTE(v int) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldGTE(FieldStartColumn, v)) +} + +// StartColumnLT applies the LT predicate on the "start_column" field. +func StartColumnLT(v int) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldLT(FieldStartColumn, v)) +} + +// StartColumnLTE applies the LTE predicate on the "start_column" field. +func StartColumnLTE(v int) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldLTE(FieldStartColumn, v)) +} + +// EndColumnEQ applies the EQ predicate on the "end_column" field. +func EndColumnEQ(v int) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldEQ(FieldEndColumn, v)) +} + +// EndColumnNEQ applies the NEQ predicate on the "end_column" field. +func EndColumnNEQ(v int) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldNEQ(FieldEndColumn, v)) +} + +// EndColumnIn applies the In predicate on the "end_column" field. +func EndColumnIn(vs ...int) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldIn(FieldEndColumn, vs...)) +} + +// EndColumnNotIn applies the NotIn predicate on the "end_column" field. +func EndColumnNotIn(vs ...int) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldNotIn(FieldEndColumn, vs...)) +} + +// EndColumnGT applies the GT predicate on the "end_column" field. +func EndColumnGT(v int) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldGT(FieldEndColumn, v)) +} + +// EndColumnGTE applies the GTE predicate on the "end_column" field. +func EndColumnGTE(v int) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldGTE(FieldEndColumn, v)) +} + +// EndColumnLT applies the LT predicate on the "end_column" field. +func EndColumnLT(v int) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldLT(FieldEndColumn, v)) +} + +// EndColumnLTE applies the LTE predicate on the "end_column" field. +func EndColumnLTE(v int) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldLTE(FieldEndColumn, v)) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldEQ(FieldNamespace, v)) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldNEQ(FieldNamespace, v)) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldIn(FieldNamespace, vs...)) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldNotIn(FieldNamespace, vs...)) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldGT(FieldNamespace, v)) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldGTE(FieldNamespace, v)) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldLT(FieldNamespace, v)) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldLTE(FieldNamespace, v)) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldContains(FieldNamespace, v)) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldHasPrefix(FieldNamespace, v)) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldHasSuffix(FieldNamespace, v)) +} + +// NamespaceIsNil applies the IsNil predicate on the "namespace" field. +func NamespaceIsNil() predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldIsNull(FieldNamespace)) +} + +// NamespaceNotNil applies the NotNil predicate on the "namespace" field. +func NamespaceNotNil() predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldNotNull(FieldNamespace)) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldEqualFold(FieldNamespace, v)) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldContainsFold(FieldNamespace, v)) +} + +// ContainerNameEQ applies the EQ predicate on the "container_name" field. +func ContainerNameEQ(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldEQ(FieldContainerName, v)) +} + +// ContainerNameNEQ applies the NEQ predicate on the "container_name" field. +func ContainerNameNEQ(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldNEQ(FieldContainerName, v)) +} + +// ContainerNameIn applies the In predicate on the "container_name" field. +func ContainerNameIn(vs ...string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldIn(FieldContainerName, vs...)) +} + +// ContainerNameNotIn applies the NotIn predicate on the "container_name" field. +func ContainerNameNotIn(vs ...string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldNotIn(FieldContainerName, vs...)) +} + +// ContainerNameGT applies the GT predicate on the "container_name" field. +func ContainerNameGT(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldGT(FieldContainerName, v)) +} + +// ContainerNameGTE applies the GTE predicate on the "container_name" field. +func ContainerNameGTE(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldGTE(FieldContainerName, v)) +} + +// ContainerNameLT applies the LT predicate on the "container_name" field. +func ContainerNameLT(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldLT(FieldContainerName, v)) +} + +// ContainerNameLTE applies the LTE predicate on the "container_name" field. +func ContainerNameLTE(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldLTE(FieldContainerName, v)) +} + +// ContainerNameContains applies the Contains predicate on the "container_name" field. +func ContainerNameContains(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldContains(FieldContainerName, v)) +} + +// ContainerNameHasPrefix applies the HasPrefix predicate on the "container_name" field. +func ContainerNameHasPrefix(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldHasPrefix(FieldContainerName, v)) +} + +// ContainerNameHasSuffix applies the HasSuffix predicate on the "container_name" field. +func ContainerNameHasSuffix(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldHasSuffix(FieldContainerName, v)) +} + +// ContainerNameIsNil applies the IsNil predicate on the "container_name" field. +func ContainerNameIsNil() predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldIsNull(FieldContainerName)) +} + +// ContainerNameNotNil applies the NotNil predicate on the "container_name" field. +func ContainerNameNotNil() predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldNotNull(FieldContainerName)) +} + +// ContainerNameEqualFold applies the EqualFold predicate on the "container_name" field. +func ContainerNameEqualFold(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldEqualFold(FieldContainerName, v)) +} + +// ContainerNameContainsFold applies the ContainsFold predicate on the "container_name" field. +func ContainerNameContainsFold(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldContainsFold(FieldContainerName, v)) +} + +// ScopeIsNil applies the IsNil predicate on the "scope" field. +func ScopeIsNil() predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldIsNull(FieldScope)) +} + +// ScopeNotNil applies the NotNil predicate on the "scope" field. +func ScopeNotNil() predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldNotNull(FieldScope)) +} + +// DependenciesIsNil applies the IsNil predicate on the "dependencies" field. +func DependenciesIsNil() predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldIsNull(FieldDependencies)) +} + +// DependenciesNotNil applies the NotNil predicate on the "dependencies" field. +func DependenciesNotNil() predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldNotNull(FieldDependencies)) +} + +// ParametersIsNil applies the IsNil predicate on the "parameters" field. +func ParametersIsNil() predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldIsNull(FieldParameters)) +} + +// ParametersNotNil applies the NotNil predicate on the "parameters" field. +func ParametersNotNil() predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldNotNull(FieldParameters)) +} + +// SignatureEQ applies the EQ predicate on the "signature" field. +func SignatureEQ(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldEQ(FieldSignature, v)) +} + +// SignatureNEQ applies the NEQ predicate on the "signature" field. +func SignatureNEQ(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldNEQ(FieldSignature, v)) +} + +// SignatureIn applies the In predicate on the "signature" field. +func SignatureIn(vs ...string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldIn(FieldSignature, vs...)) +} + +// SignatureNotIn applies the NotIn predicate on the "signature" field. +func SignatureNotIn(vs ...string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldNotIn(FieldSignature, vs...)) +} + +// SignatureGT applies the GT predicate on the "signature" field. +func SignatureGT(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldGT(FieldSignature, v)) +} + +// SignatureGTE applies the GTE predicate on the "signature" field. +func SignatureGTE(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldGTE(FieldSignature, v)) +} + +// SignatureLT applies the LT predicate on the "signature" field. +func SignatureLT(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldLT(FieldSignature, v)) +} + +// SignatureLTE applies the LTE predicate on the "signature" field. +func SignatureLTE(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldLTE(FieldSignature, v)) +} + +// SignatureContains applies the Contains predicate on the "signature" field. +func SignatureContains(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldContains(FieldSignature, v)) +} + +// SignatureHasPrefix applies the HasPrefix predicate on the "signature" field. +func SignatureHasPrefix(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldHasPrefix(FieldSignature, v)) +} + +// SignatureHasSuffix applies the HasSuffix predicate on the "signature" field. +func SignatureHasSuffix(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldHasSuffix(FieldSignature, v)) +} + +// SignatureIsNil applies the IsNil predicate on the "signature" field. +func SignatureIsNil() predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldIsNull(FieldSignature)) +} + +// SignatureNotNil applies the NotNil predicate on the "signature" field. +func SignatureNotNil() predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldNotNull(FieldSignature)) +} + +// SignatureEqualFold applies the EqualFold predicate on the "signature" field. +func SignatureEqualFold(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldEqualFold(FieldSignature, v)) +} + +// SignatureContainsFold applies the ContainsFold predicate on the "signature" field. +func SignatureContainsFold(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldContainsFold(FieldSignature, v)) +} + +// DefinitionTextEQ applies the EQ predicate on the "definition_text" field. +func DefinitionTextEQ(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldEQ(FieldDefinitionText, v)) +} + +// DefinitionTextNEQ applies the NEQ predicate on the "definition_text" field. +func DefinitionTextNEQ(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldNEQ(FieldDefinitionText, v)) +} + +// DefinitionTextIn applies the In predicate on the "definition_text" field. +func DefinitionTextIn(vs ...string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldIn(FieldDefinitionText, vs...)) +} + +// DefinitionTextNotIn applies the NotIn predicate on the "definition_text" field. +func DefinitionTextNotIn(vs ...string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldNotIn(FieldDefinitionText, vs...)) +} + +// DefinitionTextGT applies the GT predicate on the "definition_text" field. +func DefinitionTextGT(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldGT(FieldDefinitionText, v)) +} + +// DefinitionTextGTE applies the GTE predicate on the "definition_text" field. +func DefinitionTextGTE(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldGTE(FieldDefinitionText, v)) +} + +// DefinitionTextLT applies the LT predicate on the "definition_text" field. +func DefinitionTextLT(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldLT(FieldDefinitionText, v)) +} + +// DefinitionTextLTE applies the LTE predicate on the "definition_text" field. +func DefinitionTextLTE(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldLTE(FieldDefinitionText, v)) +} + +// DefinitionTextContains applies the Contains predicate on the "definition_text" field. +func DefinitionTextContains(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldContains(FieldDefinitionText, v)) +} + +// DefinitionTextHasPrefix applies the HasPrefix predicate on the "definition_text" field. +func DefinitionTextHasPrefix(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldHasPrefix(FieldDefinitionText, v)) +} + +// DefinitionTextHasSuffix applies the HasSuffix predicate on the "definition_text" field. +func DefinitionTextHasSuffix(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldHasSuffix(FieldDefinitionText, v)) +} + +// DefinitionTextIsNil applies the IsNil predicate on the "definition_text" field. +func DefinitionTextIsNil() predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldIsNull(FieldDefinitionText)) +} + +// DefinitionTextNotNil applies the NotNil predicate on the "definition_text" field. +func DefinitionTextNotNil() predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldNotNull(FieldDefinitionText)) +} + +// DefinitionTextEqualFold applies the EqualFold predicate on the "definition_text" field. +func DefinitionTextEqualFold(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldEqualFold(FieldDefinitionText, v)) +} + +// DefinitionTextContainsFold applies the ContainsFold predicate on the "definition_text" field. +func DefinitionTextContainsFold(v string) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldContainsFold(FieldDefinitionText, v)) +} + +// StructuredInfoIsNil applies the IsNil predicate on the "structured_info" field. +func StructuredInfoIsNil() predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldIsNull(FieldStructuredInfo)) +} + +// StructuredInfoNotNil applies the NotNil predicate on the "structured_info" field. +func StructuredInfoNotNil() predicate.CodeSnippet { + return predicate.CodeSnippet(sql.FieldNotNull(FieldStructuredInfo)) +} + +// HasSourceFile applies the HasEdge predicate on the "source_file" edge. +func HasSourceFile() predicate.CodeSnippet { + return predicate.CodeSnippet(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SourceFileTable, SourceFileColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasSourceFileWith applies the HasEdge predicate on the "source_file" edge with a given conditions (other predicates). +func HasSourceFileWith(preds ...predicate.WorkspaceFile) predicate.CodeSnippet { + return predicate.CodeSnippet(func(s *sql.Selector) { + step := newSourceFileStep() + 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.CodeSnippet) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.CodeSnippet) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.CodeSnippet) predicate.CodeSnippet { + return predicate.CodeSnippet(sql.NotPredicates(p)) +} diff --git a/backend/db/codesnippet_create.go b/backend/db/codesnippet_create.go new file mode 100644 index 0000000..6368ca7 --- /dev/null +++ b/backend/db/codesnippet_create.go @@ -0,0 +1,1667 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + + "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/codesnippet" + "github.com/chaitin/MonkeyCode/backend/db/workspacefile" + "github.com/google/uuid" +) + +// CodeSnippetCreate is the builder for creating a CodeSnippet entity. +type CodeSnippetCreate struct { + config + mutation *CodeSnippetMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetWorkspaceFileID sets the "workspace_file_id" field. +func (csc *CodeSnippetCreate) SetWorkspaceFileID(u uuid.UUID) *CodeSnippetCreate { + csc.mutation.SetWorkspaceFileID(u) + return csc +} + +// SetName sets the "name" field. +func (csc *CodeSnippetCreate) SetName(s string) *CodeSnippetCreate { + csc.mutation.SetName(s) + return csc +} + +// SetSnippetType sets the "snippet_type" field. +func (csc *CodeSnippetCreate) SetSnippetType(s string) *CodeSnippetCreate { + csc.mutation.SetSnippetType(s) + return csc +} + +// SetLanguage sets the "language" field. +func (csc *CodeSnippetCreate) SetLanguage(s string) *CodeSnippetCreate { + csc.mutation.SetLanguage(s) + return csc +} + +// SetContent sets the "content" field. +func (csc *CodeSnippetCreate) SetContent(s string) *CodeSnippetCreate { + csc.mutation.SetContent(s) + return csc +} + +// SetHash sets the "hash" field. +func (csc *CodeSnippetCreate) SetHash(s string) *CodeSnippetCreate { + csc.mutation.SetHash(s) + return csc +} + +// SetStartLine sets the "start_line" field. +func (csc *CodeSnippetCreate) SetStartLine(i int) *CodeSnippetCreate { + csc.mutation.SetStartLine(i) + return csc +} + +// SetEndLine sets the "end_line" field. +func (csc *CodeSnippetCreate) SetEndLine(i int) *CodeSnippetCreate { + csc.mutation.SetEndLine(i) + return csc +} + +// SetStartColumn sets the "start_column" field. +func (csc *CodeSnippetCreate) SetStartColumn(i int) *CodeSnippetCreate { + csc.mutation.SetStartColumn(i) + return csc +} + +// SetEndColumn sets the "end_column" field. +func (csc *CodeSnippetCreate) SetEndColumn(i int) *CodeSnippetCreate { + csc.mutation.SetEndColumn(i) + return csc +} + +// SetNamespace sets the "namespace" field. +func (csc *CodeSnippetCreate) SetNamespace(s string) *CodeSnippetCreate { + csc.mutation.SetNamespace(s) + return csc +} + +// SetNillableNamespace sets the "namespace" field if the given value is not nil. +func (csc *CodeSnippetCreate) SetNillableNamespace(s *string) *CodeSnippetCreate { + if s != nil { + csc.SetNamespace(*s) + } + return csc +} + +// SetContainerName sets the "container_name" field. +func (csc *CodeSnippetCreate) SetContainerName(s string) *CodeSnippetCreate { + csc.mutation.SetContainerName(s) + return csc +} + +// SetNillableContainerName sets the "container_name" field if the given value is not nil. +func (csc *CodeSnippetCreate) SetNillableContainerName(s *string) *CodeSnippetCreate { + if s != nil { + csc.SetContainerName(*s) + } + return csc +} + +// SetScope sets the "scope" field. +func (csc *CodeSnippetCreate) SetScope(s []string) *CodeSnippetCreate { + csc.mutation.SetScope(s) + return csc +} + +// SetDependencies sets the "dependencies" field. +func (csc *CodeSnippetCreate) SetDependencies(s []string) *CodeSnippetCreate { + csc.mutation.SetDependencies(s) + return csc +} + +// SetParameters sets the "parameters" field. +func (csc *CodeSnippetCreate) SetParameters(m []map[string]interface{}) *CodeSnippetCreate { + csc.mutation.SetParameters(m) + return csc +} + +// SetSignature sets the "signature" field. +func (csc *CodeSnippetCreate) SetSignature(s string) *CodeSnippetCreate { + csc.mutation.SetSignature(s) + return csc +} + +// SetNillableSignature sets the "signature" field if the given value is not nil. +func (csc *CodeSnippetCreate) SetNillableSignature(s *string) *CodeSnippetCreate { + if s != nil { + csc.SetSignature(*s) + } + return csc +} + +// SetDefinitionText sets the "definition_text" field. +func (csc *CodeSnippetCreate) SetDefinitionText(s string) *CodeSnippetCreate { + csc.mutation.SetDefinitionText(s) + return csc +} + +// SetNillableDefinitionText sets the "definition_text" field if the given value is not nil. +func (csc *CodeSnippetCreate) SetNillableDefinitionText(s *string) *CodeSnippetCreate { + if s != nil { + csc.SetDefinitionText(*s) + } + return csc +} + +// SetStructuredInfo sets the "structured_info" field. +func (csc *CodeSnippetCreate) SetStructuredInfo(m map[string]interface{}) *CodeSnippetCreate { + csc.mutation.SetStructuredInfo(m) + return csc +} + +// SetID sets the "id" field. +func (csc *CodeSnippetCreate) SetID(u uuid.UUID) *CodeSnippetCreate { + csc.mutation.SetID(u) + return csc +} + +// SetSourceFileID sets the "source_file" edge to the WorkspaceFile entity by ID. +func (csc *CodeSnippetCreate) SetSourceFileID(id uuid.UUID) *CodeSnippetCreate { + csc.mutation.SetSourceFileID(id) + return csc +} + +// SetSourceFile sets the "source_file" edge to the WorkspaceFile entity. +func (csc *CodeSnippetCreate) SetSourceFile(w *WorkspaceFile) *CodeSnippetCreate { + return csc.SetSourceFileID(w.ID) +} + +// Mutation returns the CodeSnippetMutation object of the builder. +func (csc *CodeSnippetCreate) Mutation() *CodeSnippetMutation { + return csc.mutation +} + +// Save creates the CodeSnippet in the database. +func (csc *CodeSnippetCreate) Save(ctx context.Context) (*CodeSnippet, error) { + return withHooks(ctx, csc.sqlSave, csc.mutation, csc.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (csc *CodeSnippetCreate) SaveX(ctx context.Context) *CodeSnippet { + v, err := csc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (csc *CodeSnippetCreate) Exec(ctx context.Context) error { + _, err := csc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (csc *CodeSnippetCreate) ExecX(ctx context.Context) { + if err := csc.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (csc *CodeSnippetCreate) check() error { + if _, ok := csc.mutation.WorkspaceFileID(); !ok { + return &ValidationError{Name: "workspace_file_id", err: errors.New(`db: missing required field "CodeSnippet.workspace_file_id"`)} + } + if _, ok := csc.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`db: missing required field "CodeSnippet.name"`)} + } + if _, ok := csc.mutation.SnippetType(); !ok { + return &ValidationError{Name: "snippet_type", err: errors.New(`db: missing required field "CodeSnippet.snippet_type"`)} + } + if _, ok := csc.mutation.Language(); !ok { + return &ValidationError{Name: "language", err: errors.New(`db: missing required field "CodeSnippet.language"`)} + } + if _, ok := csc.mutation.Content(); !ok { + return &ValidationError{Name: "content", err: errors.New(`db: missing required field "CodeSnippet.content"`)} + } + if _, ok := csc.mutation.Hash(); !ok { + return &ValidationError{Name: "hash", err: errors.New(`db: missing required field "CodeSnippet.hash"`)} + } + if _, ok := csc.mutation.StartLine(); !ok { + return &ValidationError{Name: "start_line", err: errors.New(`db: missing required field "CodeSnippet.start_line"`)} + } + if _, ok := csc.mutation.EndLine(); !ok { + return &ValidationError{Name: "end_line", err: errors.New(`db: missing required field "CodeSnippet.end_line"`)} + } + if _, ok := csc.mutation.StartColumn(); !ok { + return &ValidationError{Name: "start_column", err: errors.New(`db: missing required field "CodeSnippet.start_column"`)} + } + if _, ok := csc.mutation.EndColumn(); !ok { + return &ValidationError{Name: "end_column", err: errors.New(`db: missing required field "CodeSnippet.end_column"`)} + } + if len(csc.mutation.SourceFileIDs()) == 0 { + return &ValidationError{Name: "source_file", err: errors.New(`db: missing required edge "CodeSnippet.source_file"`)} + } + return nil +} + +func (csc *CodeSnippetCreate) sqlSave(ctx context.Context) (*CodeSnippet, error) { + if err := csc.check(); err != nil { + return nil, err + } + _node, _spec := csc.createSpec() + if err := sqlgraph.CreateNode(ctx, csc.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 + } + } + csc.mutation.id = &_node.ID + csc.mutation.done = true + return _node, nil +} + +func (csc *CodeSnippetCreate) createSpec() (*CodeSnippet, *sqlgraph.CreateSpec) { + var ( + _node = &CodeSnippet{config: csc.config} + _spec = sqlgraph.NewCreateSpec(codesnippet.Table, sqlgraph.NewFieldSpec(codesnippet.FieldID, field.TypeUUID)) + ) + _spec.OnConflict = csc.conflict + if id, ok := csc.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = &id + } + if value, ok := csc.mutation.Name(); ok { + _spec.SetField(codesnippet.FieldName, field.TypeString, value) + _node.Name = value + } + if value, ok := csc.mutation.SnippetType(); ok { + _spec.SetField(codesnippet.FieldSnippetType, field.TypeString, value) + _node.SnippetType = value + } + if value, ok := csc.mutation.Language(); ok { + _spec.SetField(codesnippet.FieldLanguage, field.TypeString, value) + _node.Language = value + } + if value, ok := csc.mutation.Content(); ok { + _spec.SetField(codesnippet.FieldContent, field.TypeString, value) + _node.Content = value + } + if value, ok := csc.mutation.Hash(); ok { + _spec.SetField(codesnippet.FieldHash, field.TypeString, value) + _node.Hash = value + } + if value, ok := csc.mutation.StartLine(); ok { + _spec.SetField(codesnippet.FieldStartLine, field.TypeInt, value) + _node.StartLine = value + } + if value, ok := csc.mutation.EndLine(); ok { + _spec.SetField(codesnippet.FieldEndLine, field.TypeInt, value) + _node.EndLine = value + } + if value, ok := csc.mutation.StartColumn(); ok { + _spec.SetField(codesnippet.FieldStartColumn, field.TypeInt, value) + _node.StartColumn = value + } + if value, ok := csc.mutation.EndColumn(); ok { + _spec.SetField(codesnippet.FieldEndColumn, field.TypeInt, value) + _node.EndColumn = value + } + if value, ok := csc.mutation.Namespace(); ok { + _spec.SetField(codesnippet.FieldNamespace, field.TypeString, value) + _node.Namespace = value + } + if value, ok := csc.mutation.ContainerName(); ok { + _spec.SetField(codesnippet.FieldContainerName, field.TypeString, value) + _node.ContainerName = value + } + if value, ok := csc.mutation.Scope(); ok { + _spec.SetField(codesnippet.FieldScope, field.TypeJSON, value) + _node.Scope = value + } + if value, ok := csc.mutation.Dependencies(); ok { + _spec.SetField(codesnippet.FieldDependencies, field.TypeJSON, value) + _node.Dependencies = value + } + if value, ok := csc.mutation.Parameters(); ok { + _spec.SetField(codesnippet.FieldParameters, field.TypeJSON, value) + _node.Parameters = value + } + if value, ok := csc.mutation.Signature(); ok { + _spec.SetField(codesnippet.FieldSignature, field.TypeString, value) + _node.Signature = value + } + if value, ok := csc.mutation.DefinitionText(); ok { + _spec.SetField(codesnippet.FieldDefinitionText, field.TypeString, value) + _node.DefinitionText = value + } + if value, ok := csc.mutation.StructuredInfo(); ok { + _spec.SetField(codesnippet.FieldStructuredInfo, field.TypeJSON, value) + _node.StructuredInfo = value + } + if nodes := csc.mutation.SourceFileIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: codesnippet.SourceFileTable, + Columns: []string{codesnippet.SourceFileColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(workspacefile.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.WorkspaceFileID = 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.CodeSnippet.Create(). +// SetWorkspaceFileID(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.CodeSnippetUpsert) { +// SetWorkspaceFileID(v+v). +// }). +// Exec(ctx) +func (csc *CodeSnippetCreate) OnConflict(opts ...sql.ConflictOption) *CodeSnippetUpsertOne { + csc.conflict = opts + return &CodeSnippetUpsertOne{ + create: csc, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.CodeSnippet.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (csc *CodeSnippetCreate) OnConflictColumns(columns ...string) *CodeSnippetUpsertOne { + csc.conflict = append(csc.conflict, sql.ConflictColumns(columns...)) + return &CodeSnippetUpsertOne{ + create: csc, + } +} + +type ( + // CodeSnippetUpsertOne is the builder for "upsert"-ing + // one CodeSnippet node. + CodeSnippetUpsertOne struct { + create *CodeSnippetCreate + } + + // CodeSnippetUpsert is the "OnConflict" setter. + CodeSnippetUpsert struct { + *sql.UpdateSet + } +) + +// SetWorkspaceFileID sets the "workspace_file_id" field. +func (u *CodeSnippetUpsert) SetWorkspaceFileID(v uuid.UUID) *CodeSnippetUpsert { + u.Set(codesnippet.FieldWorkspaceFileID, v) + return u +} + +// UpdateWorkspaceFileID sets the "workspace_file_id" field to the value that was provided on create. +func (u *CodeSnippetUpsert) UpdateWorkspaceFileID() *CodeSnippetUpsert { + u.SetExcluded(codesnippet.FieldWorkspaceFileID) + return u +} + +// SetName sets the "name" field. +func (u *CodeSnippetUpsert) SetName(v string) *CodeSnippetUpsert { + u.Set(codesnippet.FieldName, v) + return u +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *CodeSnippetUpsert) UpdateName() *CodeSnippetUpsert { + u.SetExcluded(codesnippet.FieldName) + return u +} + +// SetSnippetType sets the "snippet_type" field. +func (u *CodeSnippetUpsert) SetSnippetType(v string) *CodeSnippetUpsert { + u.Set(codesnippet.FieldSnippetType, v) + return u +} + +// UpdateSnippetType sets the "snippet_type" field to the value that was provided on create. +func (u *CodeSnippetUpsert) UpdateSnippetType() *CodeSnippetUpsert { + u.SetExcluded(codesnippet.FieldSnippetType) + return u +} + +// SetLanguage sets the "language" field. +func (u *CodeSnippetUpsert) SetLanguage(v string) *CodeSnippetUpsert { + u.Set(codesnippet.FieldLanguage, v) + return u +} + +// UpdateLanguage sets the "language" field to the value that was provided on create. +func (u *CodeSnippetUpsert) UpdateLanguage() *CodeSnippetUpsert { + u.SetExcluded(codesnippet.FieldLanguage) + return u +} + +// SetContent sets the "content" field. +func (u *CodeSnippetUpsert) SetContent(v string) *CodeSnippetUpsert { + u.Set(codesnippet.FieldContent, v) + return u +} + +// UpdateContent sets the "content" field to the value that was provided on create. +func (u *CodeSnippetUpsert) UpdateContent() *CodeSnippetUpsert { + u.SetExcluded(codesnippet.FieldContent) + return u +} + +// SetHash sets the "hash" field. +func (u *CodeSnippetUpsert) SetHash(v string) *CodeSnippetUpsert { + u.Set(codesnippet.FieldHash, v) + return u +} + +// UpdateHash sets the "hash" field to the value that was provided on create. +func (u *CodeSnippetUpsert) UpdateHash() *CodeSnippetUpsert { + u.SetExcluded(codesnippet.FieldHash) + return u +} + +// SetStartLine sets the "start_line" field. +func (u *CodeSnippetUpsert) SetStartLine(v int) *CodeSnippetUpsert { + u.Set(codesnippet.FieldStartLine, v) + return u +} + +// UpdateStartLine sets the "start_line" field to the value that was provided on create. +func (u *CodeSnippetUpsert) UpdateStartLine() *CodeSnippetUpsert { + u.SetExcluded(codesnippet.FieldStartLine) + return u +} + +// AddStartLine adds v to the "start_line" field. +func (u *CodeSnippetUpsert) AddStartLine(v int) *CodeSnippetUpsert { + u.Add(codesnippet.FieldStartLine, v) + return u +} + +// SetEndLine sets the "end_line" field. +func (u *CodeSnippetUpsert) SetEndLine(v int) *CodeSnippetUpsert { + u.Set(codesnippet.FieldEndLine, v) + return u +} + +// UpdateEndLine sets the "end_line" field to the value that was provided on create. +func (u *CodeSnippetUpsert) UpdateEndLine() *CodeSnippetUpsert { + u.SetExcluded(codesnippet.FieldEndLine) + return u +} + +// AddEndLine adds v to the "end_line" field. +func (u *CodeSnippetUpsert) AddEndLine(v int) *CodeSnippetUpsert { + u.Add(codesnippet.FieldEndLine, v) + return u +} + +// SetStartColumn sets the "start_column" field. +func (u *CodeSnippetUpsert) SetStartColumn(v int) *CodeSnippetUpsert { + u.Set(codesnippet.FieldStartColumn, v) + return u +} + +// UpdateStartColumn sets the "start_column" field to the value that was provided on create. +func (u *CodeSnippetUpsert) UpdateStartColumn() *CodeSnippetUpsert { + u.SetExcluded(codesnippet.FieldStartColumn) + return u +} + +// AddStartColumn adds v to the "start_column" field. +func (u *CodeSnippetUpsert) AddStartColumn(v int) *CodeSnippetUpsert { + u.Add(codesnippet.FieldStartColumn, v) + return u +} + +// SetEndColumn sets the "end_column" field. +func (u *CodeSnippetUpsert) SetEndColumn(v int) *CodeSnippetUpsert { + u.Set(codesnippet.FieldEndColumn, v) + return u +} + +// UpdateEndColumn sets the "end_column" field to the value that was provided on create. +func (u *CodeSnippetUpsert) UpdateEndColumn() *CodeSnippetUpsert { + u.SetExcluded(codesnippet.FieldEndColumn) + return u +} + +// AddEndColumn adds v to the "end_column" field. +func (u *CodeSnippetUpsert) AddEndColumn(v int) *CodeSnippetUpsert { + u.Add(codesnippet.FieldEndColumn, v) + return u +} + +// SetNamespace sets the "namespace" field. +func (u *CodeSnippetUpsert) SetNamespace(v string) *CodeSnippetUpsert { + u.Set(codesnippet.FieldNamespace, v) + return u +} + +// UpdateNamespace sets the "namespace" field to the value that was provided on create. +func (u *CodeSnippetUpsert) UpdateNamespace() *CodeSnippetUpsert { + u.SetExcluded(codesnippet.FieldNamespace) + return u +} + +// ClearNamespace clears the value of the "namespace" field. +func (u *CodeSnippetUpsert) ClearNamespace() *CodeSnippetUpsert { + u.SetNull(codesnippet.FieldNamespace) + return u +} + +// SetContainerName sets the "container_name" field. +func (u *CodeSnippetUpsert) SetContainerName(v string) *CodeSnippetUpsert { + u.Set(codesnippet.FieldContainerName, v) + return u +} + +// UpdateContainerName sets the "container_name" field to the value that was provided on create. +func (u *CodeSnippetUpsert) UpdateContainerName() *CodeSnippetUpsert { + u.SetExcluded(codesnippet.FieldContainerName) + return u +} + +// ClearContainerName clears the value of the "container_name" field. +func (u *CodeSnippetUpsert) ClearContainerName() *CodeSnippetUpsert { + u.SetNull(codesnippet.FieldContainerName) + return u +} + +// SetScope sets the "scope" field. +func (u *CodeSnippetUpsert) SetScope(v []string) *CodeSnippetUpsert { + u.Set(codesnippet.FieldScope, v) + return u +} + +// UpdateScope sets the "scope" field to the value that was provided on create. +func (u *CodeSnippetUpsert) UpdateScope() *CodeSnippetUpsert { + u.SetExcluded(codesnippet.FieldScope) + return u +} + +// ClearScope clears the value of the "scope" field. +func (u *CodeSnippetUpsert) ClearScope() *CodeSnippetUpsert { + u.SetNull(codesnippet.FieldScope) + return u +} + +// SetDependencies sets the "dependencies" field. +func (u *CodeSnippetUpsert) SetDependencies(v []string) *CodeSnippetUpsert { + u.Set(codesnippet.FieldDependencies, v) + return u +} + +// UpdateDependencies sets the "dependencies" field to the value that was provided on create. +func (u *CodeSnippetUpsert) UpdateDependencies() *CodeSnippetUpsert { + u.SetExcluded(codesnippet.FieldDependencies) + return u +} + +// ClearDependencies clears the value of the "dependencies" field. +func (u *CodeSnippetUpsert) ClearDependencies() *CodeSnippetUpsert { + u.SetNull(codesnippet.FieldDependencies) + return u +} + +// SetParameters sets the "parameters" field. +func (u *CodeSnippetUpsert) SetParameters(v []map[string]interface{}) *CodeSnippetUpsert { + u.Set(codesnippet.FieldParameters, v) + return u +} + +// UpdateParameters sets the "parameters" field to the value that was provided on create. +func (u *CodeSnippetUpsert) UpdateParameters() *CodeSnippetUpsert { + u.SetExcluded(codesnippet.FieldParameters) + return u +} + +// ClearParameters clears the value of the "parameters" field. +func (u *CodeSnippetUpsert) ClearParameters() *CodeSnippetUpsert { + u.SetNull(codesnippet.FieldParameters) + return u +} + +// SetSignature sets the "signature" field. +func (u *CodeSnippetUpsert) SetSignature(v string) *CodeSnippetUpsert { + u.Set(codesnippet.FieldSignature, v) + return u +} + +// UpdateSignature sets the "signature" field to the value that was provided on create. +func (u *CodeSnippetUpsert) UpdateSignature() *CodeSnippetUpsert { + u.SetExcluded(codesnippet.FieldSignature) + return u +} + +// ClearSignature clears the value of the "signature" field. +func (u *CodeSnippetUpsert) ClearSignature() *CodeSnippetUpsert { + u.SetNull(codesnippet.FieldSignature) + return u +} + +// SetDefinitionText sets the "definition_text" field. +func (u *CodeSnippetUpsert) SetDefinitionText(v string) *CodeSnippetUpsert { + u.Set(codesnippet.FieldDefinitionText, v) + return u +} + +// UpdateDefinitionText sets the "definition_text" field to the value that was provided on create. +func (u *CodeSnippetUpsert) UpdateDefinitionText() *CodeSnippetUpsert { + u.SetExcluded(codesnippet.FieldDefinitionText) + return u +} + +// ClearDefinitionText clears the value of the "definition_text" field. +func (u *CodeSnippetUpsert) ClearDefinitionText() *CodeSnippetUpsert { + u.SetNull(codesnippet.FieldDefinitionText) + return u +} + +// SetStructuredInfo sets the "structured_info" field. +func (u *CodeSnippetUpsert) SetStructuredInfo(v map[string]interface{}) *CodeSnippetUpsert { + u.Set(codesnippet.FieldStructuredInfo, v) + return u +} + +// UpdateStructuredInfo sets the "structured_info" field to the value that was provided on create. +func (u *CodeSnippetUpsert) UpdateStructuredInfo() *CodeSnippetUpsert { + u.SetExcluded(codesnippet.FieldStructuredInfo) + return u +} + +// ClearStructuredInfo clears the value of the "structured_info" field. +func (u *CodeSnippetUpsert) ClearStructuredInfo() *CodeSnippetUpsert { + u.SetNull(codesnippet.FieldStructuredInfo) + 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.CodeSnippet.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(codesnippet.FieldID) +// }), +// ). +// Exec(ctx) +func (u *CodeSnippetUpsertOne) UpdateNewValues() *CodeSnippetUpsertOne { + 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(codesnippet.FieldID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.CodeSnippet.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *CodeSnippetUpsertOne) Ignore() *CodeSnippetUpsertOne { + 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 *CodeSnippetUpsertOne) DoNothing() *CodeSnippetUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the CodeSnippetCreate.OnConflict +// documentation for more info. +func (u *CodeSnippetUpsertOne) Update(set func(*CodeSnippetUpsert)) *CodeSnippetUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&CodeSnippetUpsert{UpdateSet: update}) + })) + return u +} + +// SetWorkspaceFileID sets the "workspace_file_id" field. +func (u *CodeSnippetUpsertOne) SetWorkspaceFileID(v uuid.UUID) *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.SetWorkspaceFileID(v) + }) +} + +// UpdateWorkspaceFileID sets the "workspace_file_id" field to the value that was provided on create. +func (u *CodeSnippetUpsertOne) UpdateWorkspaceFileID() *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.UpdateWorkspaceFileID() + }) +} + +// SetName sets the "name" field. +func (u *CodeSnippetUpsertOne) SetName(v string) *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *CodeSnippetUpsertOne) UpdateName() *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.UpdateName() + }) +} + +// SetSnippetType sets the "snippet_type" field. +func (u *CodeSnippetUpsertOne) SetSnippetType(v string) *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.SetSnippetType(v) + }) +} + +// UpdateSnippetType sets the "snippet_type" field to the value that was provided on create. +func (u *CodeSnippetUpsertOne) UpdateSnippetType() *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.UpdateSnippetType() + }) +} + +// SetLanguage sets the "language" field. +func (u *CodeSnippetUpsertOne) SetLanguage(v string) *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.SetLanguage(v) + }) +} + +// UpdateLanguage sets the "language" field to the value that was provided on create. +func (u *CodeSnippetUpsertOne) UpdateLanguage() *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.UpdateLanguage() + }) +} + +// SetContent sets the "content" field. +func (u *CodeSnippetUpsertOne) SetContent(v string) *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.SetContent(v) + }) +} + +// UpdateContent sets the "content" field to the value that was provided on create. +func (u *CodeSnippetUpsertOne) UpdateContent() *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.UpdateContent() + }) +} + +// SetHash sets the "hash" field. +func (u *CodeSnippetUpsertOne) SetHash(v string) *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.SetHash(v) + }) +} + +// UpdateHash sets the "hash" field to the value that was provided on create. +func (u *CodeSnippetUpsertOne) UpdateHash() *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.UpdateHash() + }) +} + +// SetStartLine sets the "start_line" field. +func (u *CodeSnippetUpsertOne) SetStartLine(v int) *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.SetStartLine(v) + }) +} + +// AddStartLine adds v to the "start_line" field. +func (u *CodeSnippetUpsertOne) AddStartLine(v int) *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.AddStartLine(v) + }) +} + +// UpdateStartLine sets the "start_line" field to the value that was provided on create. +func (u *CodeSnippetUpsertOne) UpdateStartLine() *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.UpdateStartLine() + }) +} + +// SetEndLine sets the "end_line" field. +func (u *CodeSnippetUpsertOne) SetEndLine(v int) *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.SetEndLine(v) + }) +} + +// AddEndLine adds v to the "end_line" field. +func (u *CodeSnippetUpsertOne) AddEndLine(v int) *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.AddEndLine(v) + }) +} + +// UpdateEndLine sets the "end_line" field to the value that was provided on create. +func (u *CodeSnippetUpsertOne) UpdateEndLine() *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.UpdateEndLine() + }) +} + +// SetStartColumn sets the "start_column" field. +func (u *CodeSnippetUpsertOne) SetStartColumn(v int) *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.SetStartColumn(v) + }) +} + +// AddStartColumn adds v to the "start_column" field. +func (u *CodeSnippetUpsertOne) AddStartColumn(v int) *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.AddStartColumn(v) + }) +} + +// UpdateStartColumn sets the "start_column" field to the value that was provided on create. +func (u *CodeSnippetUpsertOne) UpdateStartColumn() *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.UpdateStartColumn() + }) +} + +// SetEndColumn sets the "end_column" field. +func (u *CodeSnippetUpsertOne) SetEndColumn(v int) *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.SetEndColumn(v) + }) +} + +// AddEndColumn adds v to the "end_column" field. +func (u *CodeSnippetUpsertOne) AddEndColumn(v int) *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.AddEndColumn(v) + }) +} + +// UpdateEndColumn sets the "end_column" field to the value that was provided on create. +func (u *CodeSnippetUpsertOne) UpdateEndColumn() *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.UpdateEndColumn() + }) +} + +// SetNamespace sets the "namespace" field. +func (u *CodeSnippetUpsertOne) SetNamespace(v string) *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.SetNamespace(v) + }) +} + +// UpdateNamespace sets the "namespace" field to the value that was provided on create. +func (u *CodeSnippetUpsertOne) UpdateNamespace() *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.UpdateNamespace() + }) +} + +// ClearNamespace clears the value of the "namespace" field. +func (u *CodeSnippetUpsertOne) ClearNamespace() *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.ClearNamespace() + }) +} + +// SetContainerName sets the "container_name" field. +func (u *CodeSnippetUpsertOne) SetContainerName(v string) *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.SetContainerName(v) + }) +} + +// UpdateContainerName sets the "container_name" field to the value that was provided on create. +func (u *CodeSnippetUpsertOne) UpdateContainerName() *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.UpdateContainerName() + }) +} + +// ClearContainerName clears the value of the "container_name" field. +func (u *CodeSnippetUpsertOne) ClearContainerName() *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.ClearContainerName() + }) +} + +// SetScope sets the "scope" field. +func (u *CodeSnippetUpsertOne) SetScope(v []string) *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.SetScope(v) + }) +} + +// UpdateScope sets the "scope" field to the value that was provided on create. +func (u *CodeSnippetUpsertOne) UpdateScope() *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.UpdateScope() + }) +} + +// ClearScope clears the value of the "scope" field. +func (u *CodeSnippetUpsertOne) ClearScope() *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.ClearScope() + }) +} + +// SetDependencies sets the "dependencies" field. +func (u *CodeSnippetUpsertOne) SetDependencies(v []string) *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.SetDependencies(v) + }) +} + +// UpdateDependencies sets the "dependencies" field to the value that was provided on create. +func (u *CodeSnippetUpsertOne) UpdateDependencies() *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.UpdateDependencies() + }) +} + +// ClearDependencies clears the value of the "dependencies" field. +func (u *CodeSnippetUpsertOne) ClearDependencies() *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.ClearDependencies() + }) +} + +// SetParameters sets the "parameters" field. +func (u *CodeSnippetUpsertOne) SetParameters(v []map[string]interface{}) *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.SetParameters(v) + }) +} + +// UpdateParameters sets the "parameters" field to the value that was provided on create. +func (u *CodeSnippetUpsertOne) UpdateParameters() *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.UpdateParameters() + }) +} + +// ClearParameters clears the value of the "parameters" field. +func (u *CodeSnippetUpsertOne) ClearParameters() *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.ClearParameters() + }) +} + +// SetSignature sets the "signature" field. +func (u *CodeSnippetUpsertOne) SetSignature(v string) *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.SetSignature(v) + }) +} + +// UpdateSignature sets the "signature" field to the value that was provided on create. +func (u *CodeSnippetUpsertOne) UpdateSignature() *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.UpdateSignature() + }) +} + +// ClearSignature clears the value of the "signature" field. +func (u *CodeSnippetUpsertOne) ClearSignature() *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.ClearSignature() + }) +} + +// SetDefinitionText sets the "definition_text" field. +func (u *CodeSnippetUpsertOne) SetDefinitionText(v string) *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.SetDefinitionText(v) + }) +} + +// UpdateDefinitionText sets the "definition_text" field to the value that was provided on create. +func (u *CodeSnippetUpsertOne) UpdateDefinitionText() *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.UpdateDefinitionText() + }) +} + +// ClearDefinitionText clears the value of the "definition_text" field. +func (u *CodeSnippetUpsertOne) ClearDefinitionText() *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.ClearDefinitionText() + }) +} + +// SetStructuredInfo sets the "structured_info" field. +func (u *CodeSnippetUpsertOne) SetStructuredInfo(v map[string]interface{}) *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.SetStructuredInfo(v) + }) +} + +// UpdateStructuredInfo sets the "structured_info" field to the value that was provided on create. +func (u *CodeSnippetUpsertOne) UpdateStructuredInfo() *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.UpdateStructuredInfo() + }) +} + +// ClearStructuredInfo clears the value of the "structured_info" field. +func (u *CodeSnippetUpsertOne) ClearStructuredInfo() *CodeSnippetUpsertOne { + return u.Update(func(s *CodeSnippetUpsert) { + s.ClearStructuredInfo() + }) +} + +// Exec executes the query. +func (u *CodeSnippetUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for CodeSnippetCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *CodeSnippetUpsertOne) 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 *CodeSnippetUpsertOne) 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: CodeSnippetUpsertOne.ID is not supported by MySQL driver. Use CodeSnippetUpsertOne.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 *CodeSnippetUpsertOne) IDX(ctx context.Context) uuid.UUID { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// CodeSnippetCreateBulk is the builder for creating many CodeSnippet entities in bulk. +type CodeSnippetCreateBulk struct { + config + err error + builders []*CodeSnippetCreate + conflict []sql.ConflictOption +} + +// Save creates the CodeSnippet entities in the database. +func (cscb *CodeSnippetCreateBulk) Save(ctx context.Context) ([]*CodeSnippet, error) { + if cscb.err != nil { + return nil, cscb.err + } + specs := make([]*sqlgraph.CreateSpec, len(cscb.builders)) + nodes := make([]*CodeSnippet, len(cscb.builders)) + mutators := make([]Mutator, len(cscb.builders)) + for i := range cscb.builders { + func(i int, root context.Context) { + builder := cscb.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*CodeSnippetMutation) + 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, cscb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = cscb.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, cscb.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, cscb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (cscb *CodeSnippetCreateBulk) SaveX(ctx context.Context) []*CodeSnippet { + v, err := cscb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (cscb *CodeSnippetCreateBulk) Exec(ctx context.Context) error { + _, err := cscb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (cscb *CodeSnippetCreateBulk) ExecX(ctx context.Context) { + if err := cscb.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.CodeSnippet.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.CodeSnippetUpsert) { +// SetWorkspaceFileID(v+v). +// }). +// Exec(ctx) +func (cscb *CodeSnippetCreateBulk) OnConflict(opts ...sql.ConflictOption) *CodeSnippetUpsertBulk { + cscb.conflict = opts + return &CodeSnippetUpsertBulk{ + create: cscb, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.CodeSnippet.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (cscb *CodeSnippetCreateBulk) OnConflictColumns(columns ...string) *CodeSnippetUpsertBulk { + cscb.conflict = append(cscb.conflict, sql.ConflictColumns(columns...)) + return &CodeSnippetUpsertBulk{ + create: cscb, + } +} + +// CodeSnippetUpsertBulk is the builder for "upsert"-ing +// a bulk of CodeSnippet nodes. +type CodeSnippetUpsertBulk struct { + create *CodeSnippetCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.CodeSnippet.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(codesnippet.FieldID) +// }), +// ). +// Exec(ctx) +func (u *CodeSnippetUpsertBulk) UpdateNewValues() *CodeSnippetUpsertBulk { + 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(codesnippet.FieldID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.CodeSnippet.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *CodeSnippetUpsertBulk) Ignore() *CodeSnippetUpsertBulk { + 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 *CodeSnippetUpsertBulk) DoNothing() *CodeSnippetUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the CodeSnippetCreateBulk.OnConflict +// documentation for more info. +func (u *CodeSnippetUpsertBulk) Update(set func(*CodeSnippetUpsert)) *CodeSnippetUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&CodeSnippetUpsert{UpdateSet: update}) + })) + return u +} + +// SetWorkspaceFileID sets the "workspace_file_id" field. +func (u *CodeSnippetUpsertBulk) SetWorkspaceFileID(v uuid.UUID) *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.SetWorkspaceFileID(v) + }) +} + +// UpdateWorkspaceFileID sets the "workspace_file_id" field to the value that was provided on create. +func (u *CodeSnippetUpsertBulk) UpdateWorkspaceFileID() *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.UpdateWorkspaceFileID() + }) +} + +// SetName sets the "name" field. +func (u *CodeSnippetUpsertBulk) SetName(v string) *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *CodeSnippetUpsertBulk) UpdateName() *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.UpdateName() + }) +} + +// SetSnippetType sets the "snippet_type" field. +func (u *CodeSnippetUpsertBulk) SetSnippetType(v string) *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.SetSnippetType(v) + }) +} + +// UpdateSnippetType sets the "snippet_type" field to the value that was provided on create. +func (u *CodeSnippetUpsertBulk) UpdateSnippetType() *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.UpdateSnippetType() + }) +} + +// SetLanguage sets the "language" field. +func (u *CodeSnippetUpsertBulk) SetLanguage(v string) *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.SetLanguage(v) + }) +} + +// UpdateLanguage sets the "language" field to the value that was provided on create. +func (u *CodeSnippetUpsertBulk) UpdateLanguage() *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.UpdateLanguage() + }) +} + +// SetContent sets the "content" field. +func (u *CodeSnippetUpsertBulk) SetContent(v string) *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.SetContent(v) + }) +} + +// UpdateContent sets the "content" field to the value that was provided on create. +func (u *CodeSnippetUpsertBulk) UpdateContent() *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.UpdateContent() + }) +} + +// SetHash sets the "hash" field. +func (u *CodeSnippetUpsertBulk) SetHash(v string) *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.SetHash(v) + }) +} + +// UpdateHash sets the "hash" field to the value that was provided on create. +func (u *CodeSnippetUpsertBulk) UpdateHash() *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.UpdateHash() + }) +} + +// SetStartLine sets the "start_line" field. +func (u *CodeSnippetUpsertBulk) SetStartLine(v int) *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.SetStartLine(v) + }) +} + +// AddStartLine adds v to the "start_line" field. +func (u *CodeSnippetUpsertBulk) AddStartLine(v int) *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.AddStartLine(v) + }) +} + +// UpdateStartLine sets the "start_line" field to the value that was provided on create. +func (u *CodeSnippetUpsertBulk) UpdateStartLine() *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.UpdateStartLine() + }) +} + +// SetEndLine sets the "end_line" field. +func (u *CodeSnippetUpsertBulk) SetEndLine(v int) *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.SetEndLine(v) + }) +} + +// AddEndLine adds v to the "end_line" field. +func (u *CodeSnippetUpsertBulk) AddEndLine(v int) *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.AddEndLine(v) + }) +} + +// UpdateEndLine sets the "end_line" field to the value that was provided on create. +func (u *CodeSnippetUpsertBulk) UpdateEndLine() *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.UpdateEndLine() + }) +} + +// SetStartColumn sets the "start_column" field. +func (u *CodeSnippetUpsertBulk) SetStartColumn(v int) *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.SetStartColumn(v) + }) +} + +// AddStartColumn adds v to the "start_column" field. +func (u *CodeSnippetUpsertBulk) AddStartColumn(v int) *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.AddStartColumn(v) + }) +} + +// UpdateStartColumn sets the "start_column" field to the value that was provided on create. +func (u *CodeSnippetUpsertBulk) UpdateStartColumn() *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.UpdateStartColumn() + }) +} + +// SetEndColumn sets the "end_column" field. +func (u *CodeSnippetUpsertBulk) SetEndColumn(v int) *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.SetEndColumn(v) + }) +} + +// AddEndColumn adds v to the "end_column" field. +func (u *CodeSnippetUpsertBulk) AddEndColumn(v int) *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.AddEndColumn(v) + }) +} + +// UpdateEndColumn sets the "end_column" field to the value that was provided on create. +func (u *CodeSnippetUpsertBulk) UpdateEndColumn() *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.UpdateEndColumn() + }) +} + +// SetNamespace sets the "namespace" field. +func (u *CodeSnippetUpsertBulk) SetNamespace(v string) *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.SetNamespace(v) + }) +} + +// UpdateNamespace sets the "namespace" field to the value that was provided on create. +func (u *CodeSnippetUpsertBulk) UpdateNamespace() *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.UpdateNamespace() + }) +} + +// ClearNamespace clears the value of the "namespace" field. +func (u *CodeSnippetUpsertBulk) ClearNamespace() *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.ClearNamespace() + }) +} + +// SetContainerName sets the "container_name" field. +func (u *CodeSnippetUpsertBulk) SetContainerName(v string) *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.SetContainerName(v) + }) +} + +// UpdateContainerName sets the "container_name" field to the value that was provided on create. +func (u *CodeSnippetUpsertBulk) UpdateContainerName() *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.UpdateContainerName() + }) +} + +// ClearContainerName clears the value of the "container_name" field. +func (u *CodeSnippetUpsertBulk) ClearContainerName() *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.ClearContainerName() + }) +} + +// SetScope sets the "scope" field. +func (u *CodeSnippetUpsertBulk) SetScope(v []string) *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.SetScope(v) + }) +} + +// UpdateScope sets the "scope" field to the value that was provided on create. +func (u *CodeSnippetUpsertBulk) UpdateScope() *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.UpdateScope() + }) +} + +// ClearScope clears the value of the "scope" field. +func (u *CodeSnippetUpsertBulk) ClearScope() *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.ClearScope() + }) +} + +// SetDependencies sets the "dependencies" field. +func (u *CodeSnippetUpsertBulk) SetDependencies(v []string) *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.SetDependencies(v) + }) +} + +// UpdateDependencies sets the "dependencies" field to the value that was provided on create. +func (u *CodeSnippetUpsertBulk) UpdateDependencies() *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.UpdateDependencies() + }) +} + +// ClearDependencies clears the value of the "dependencies" field. +func (u *CodeSnippetUpsertBulk) ClearDependencies() *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.ClearDependencies() + }) +} + +// SetParameters sets the "parameters" field. +func (u *CodeSnippetUpsertBulk) SetParameters(v []map[string]interface{}) *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.SetParameters(v) + }) +} + +// UpdateParameters sets the "parameters" field to the value that was provided on create. +func (u *CodeSnippetUpsertBulk) UpdateParameters() *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.UpdateParameters() + }) +} + +// ClearParameters clears the value of the "parameters" field. +func (u *CodeSnippetUpsertBulk) ClearParameters() *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.ClearParameters() + }) +} + +// SetSignature sets the "signature" field. +func (u *CodeSnippetUpsertBulk) SetSignature(v string) *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.SetSignature(v) + }) +} + +// UpdateSignature sets the "signature" field to the value that was provided on create. +func (u *CodeSnippetUpsertBulk) UpdateSignature() *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.UpdateSignature() + }) +} + +// ClearSignature clears the value of the "signature" field. +func (u *CodeSnippetUpsertBulk) ClearSignature() *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.ClearSignature() + }) +} + +// SetDefinitionText sets the "definition_text" field. +func (u *CodeSnippetUpsertBulk) SetDefinitionText(v string) *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.SetDefinitionText(v) + }) +} + +// UpdateDefinitionText sets the "definition_text" field to the value that was provided on create. +func (u *CodeSnippetUpsertBulk) UpdateDefinitionText() *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.UpdateDefinitionText() + }) +} + +// ClearDefinitionText clears the value of the "definition_text" field. +func (u *CodeSnippetUpsertBulk) ClearDefinitionText() *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.ClearDefinitionText() + }) +} + +// SetStructuredInfo sets the "structured_info" field. +func (u *CodeSnippetUpsertBulk) SetStructuredInfo(v map[string]interface{}) *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.SetStructuredInfo(v) + }) +} + +// UpdateStructuredInfo sets the "structured_info" field to the value that was provided on create. +func (u *CodeSnippetUpsertBulk) UpdateStructuredInfo() *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.UpdateStructuredInfo() + }) +} + +// ClearStructuredInfo clears the value of the "structured_info" field. +func (u *CodeSnippetUpsertBulk) ClearStructuredInfo() *CodeSnippetUpsertBulk { + return u.Update(func(s *CodeSnippetUpsert) { + s.ClearStructuredInfo() + }) +} + +// Exec executes the query. +func (u *CodeSnippetUpsertBulk) 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 CodeSnippetCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for CodeSnippetCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *CodeSnippetUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/codesnippet_delete.go b/backend/db/codesnippet_delete.go new file mode 100644 index 0000000..4006460 --- /dev/null +++ b/backend/db/codesnippet_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/codesnippet" + "github.com/chaitin/MonkeyCode/backend/db/predicate" +) + +// CodeSnippetDelete is the builder for deleting a CodeSnippet entity. +type CodeSnippetDelete struct { + config + hooks []Hook + mutation *CodeSnippetMutation +} + +// Where appends a list predicates to the CodeSnippetDelete builder. +func (csd *CodeSnippetDelete) Where(ps ...predicate.CodeSnippet) *CodeSnippetDelete { + csd.mutation.Where(ps...) + return csd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (csd *CodeSnippetDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, csd.sqlExec, csd.mutation, csd.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (csd *CodeSnippetDelete) ExecX(ctx context.Context) int { + n, err := csd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (csd *CodeSnippetDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(codesnippet.Table, sqlgraph.NewFieldSpec(codesnippet.FieldID, field.TypeUUID)) + if ps := csd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, csd.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + csd.mutation.done = true + return affected, err +} + +// CodeSnippetDeleteOne is the builder for deleting a single CodeSnippet entity. +type CodeSnippetDeleteOne struct { + csd *CodeSnippetDelete +} + +// Where appends a list predicates to the CodeSnippetDelete builder. +func (csdo *CodeSnippetDeleteOne) Where(ps ...predicate.CodeSnippet) *CodeSnippetDeleteOne { + csdo.csd.mutation.Where(ps...) + return csdo +} + +// Exec executes the deletion query. +func (csdo *CodeSnippetDeleteOne) Exec(ctx context.Context) error { + n, err := csdo.csd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{codesnippet.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (csdo *CodeSnippetDeleteOne) ExecX(ctx context.Context) { + if err := csdo.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/codesnippet_query.go b/backend/db/codesnippet_query.go new file mode 100644 index 0000000..6c54661 --- /dev/null +++ b/backend/db/codesnippet_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/codesnippet" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/workspacefile" + "github.com/google/uuid" +) + +// CodeSnippetQuery is the builder for querying CodeSnippet entities. +type CodeSnippetQuery struct { + config + ctx *QueryContext + order []codesnippet.OrderOption + inters []Interceptor + predicates []predicate.CodeSnippet + withSourceFile *WorkspaceFileQuery + 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 CodeSnippetQuery builder. +func (csq *CodeSnippetQuery) Where(ps ...predicate.CodeSnippet) *CodeSnippetQuery { + csq.predicates = append(csq.predicates, ps...) + return csq +} + +// Limit the number of records to be returned by this query. +func (csq *CodeSnippetQuery) Limit(limit int) *CodeSnippetQuery { + csq.ctx.Limit = &limit + return csq +} + +// Offset to start from. +func (csq *CodeSnippetQuery) Offset(offset int) *CodeSnippetQuery { + csq.ctx.Offset = &offset + return csq +} + +// 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 (csq *CodeSnippetQuery) Unique(unique bool) *CodeSnippetQuery { + csq.ctx.Unique = &unique + return csq +} + +// Order specifies how the records should be ordered. +func (csq *CodeSnippetQuery) Order(o ...codesnippet.OrderOption) *CodeSnippetQuery { + csq.order = append(csq.order, o...) + return csq +} + +// QuerySourceFile chains the current query on the "source_file" edge. +func (csq *CodeSnippetQuery) QuerySourceFile() *WorkspaceFileQuery { + query := (&WorkspaceFileClient{config: csq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := csq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := csq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(codesnippet.Table, codesnippet.FieldID, selector), + sqlgraph.To(workspacefile.Table, workspacefile.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, codesnippet.SourceFileTable, codesnippet.SourceFileColumn), + ) + fromU = sqlgraph.SetNeighbors(csq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first CodeSnippet entity from the query. +// Returns a *NotFoundError when no CodeSnippet was found. +func (csq *CodeSnippetQuery) First(ctx context.Context) (*CodeSnippet, error) { + nodes, err := csq.Limit(1).All(setContextOp(ctx, csq.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{codesnippet.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (csq *CodeSnippetQuery) FirstX(ctx context.Context) *CodeSnippet { + node, err := csq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first CodeSnippet ID from the query. +// Returns a *NotFoundError when no CodeSnippet ID was found. +func (csq *CodeSnippetQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = csq.Limit(1).IDs(setContextOp(ctx, csq.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{codesnippet.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (csq *CodeSnippetQuery) FirstIDX(ctx context.Context) uuid.UUID { + id, err := csq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single CodeSnippet entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one CodeSnippet entity is found. +// Returns a *NotFoundError when no CodeSnippet entities are found. +func (csq *CodeSnippetQuery) Only(ctx context.Context) (*CodeSnippet, error) { + nodes, err := csq.Limit(2).All(setContextOp(ctx, csq.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{codesnippet.Label} + default: + return nil, &NotSingularError{codesnippet.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (csq *CodeSnippetQuery) OnlyX(ctx context.Context) *CodeSnippet { + node, err := csq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only CodeSnippet ID in the query. +// Returns a *NotSingularError when more than one CodeSnippet ID is found. +// Returns a *NotFoundError when no entities are found. +func (csq *CodeSnippetQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = csq.Limit(2).IDs(setContextOp(ctx, csq.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{codesnippet.Label} + default: + err = &NotSingularError{codesnippet.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (csq *CodeSnippetQuery) OnlyIDX(ctx context.Context) uuid.UUID { + id, err := csq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of CodeSnippets. +func (csq *CodeSnippetQuery) All(ctx context.Context) ([]*CodeSnippet, error) { + ctx = setContextOp(ctx, csq.ctx, ent.OpQueryAll) + if err := csq.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*CodeSnippet, *CodeSnippetQuery]() + return withInterceptors[[]*CodeSnippet](ctx, csq, qr, csq.inters) +} + +// AllX is like All, but panics if an error occurs. +func (csq *CodeSnippetQuery) AllX(ctx context.Context) []*CodeSnippet { + nodes, err := csq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of CodeSnippet IDs. +func (csq *CodeSnippetQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) { + if csq.ctx.Unique == nil && csq.path != nil { + csq.Unique(true) + } + ctx = setContextOp(ctx, csq.ctx, ent.OpQueryIDs) + if err = csq.Select(codesnippet.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (csq *CodeSnippetQuery) IDsX(ctx context.Context) []uuid.UUID { + ids, err := csq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (csq *CodeSnippetQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, csq.ctx, ent.OpQueryCount) + if err := csq.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, csq, querierCount[*CodeSnippetQuery](), csq.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (csq *CodeSnippetQuery) CountX(ctx context.Context) int { + count, err := csq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (csq *CodeSnippetQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, csq.ctx, ent.OpQueryExist) + switch _, err := csq.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 (csq *CodeSnippetQuery) ExistX(ctx context.Context) bool { + exist, err := csq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the CodeSnippetQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (csq *CodeSnippetQuery) Clone() *CodeSnippetQuery { + if csq == nil { + return nil + } + return &CodeSnippetQuery{ + config: csq.config, + ctx: csq.ctx.Clone(), + order: append([]codesnippet.OrderOption{}, csq.order...), + inters: append([]Interceptor{}, csq.inters...), + predicates: append([]predicate.CodeSnippet{}, csq.predicates...), + withSourceFile: csq.withSourceFile.Clone(), + // clone intermediate query. + sql: csq.sql.Clone(), + path: csq.path, + modifiers: append([]func(*sql.Selector){}, csq.modifiers...), + } +} + +// WithSourceFile tells the query-builder to eager-load the nodes that are connected to +// the "source_file" edge. The optional arguments are used to configure the query builder of the edge. +func (csq *CodeSnippetQuery) WithSourceFile(opts ...func(*WorkspaceFileQuery)) *CodeSnippetQuery { + query := (&WorkspaceFileClient{config: csq.config}).Query() + for _, opt := range opts { + opt(query) + } + csq.withSourceFile = query + return csq +} + +// 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 { +// WorkspaceFileID uuid.UUID `json:"workspace_file_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.CodeSnippet.Query(). +// GroupBy(codesnippet.FieldWorkspaceFileID). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (csq *CodeSnippetQuery) GroupBy(field string, fields ...string) *CodeSnippetGroupBy { + csq.ctx.Fields = append([]string{field}, fields...) + grbuild := &CodeSnippetGroupBy{build: csq} + grbuild.flds = &csq.ctx.Fields + grbuild.label = codesnippet.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 { +// WorkspaceFileID uuid.UUID `json:"workspace_file_id,omitempty"` +// } +// +// client.CodeSnippet.Query(). +// Select(codesnippet.FieldWorkspaceFileID). +// Scan(ctx, &v) +func (csq *CodeSnippetQuery) Select(fields ...string) *CodeSnippetSelect { + csq.ctx.Fields = append(csq.ctx.Fields, fields...) + sbuild := &CodeSnippetSelect{CodeSnippetQuery: csq} + sbuild.label = codesnippet.Label + sbuild.flds, sbuild.scan = &csq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a CodeSnippetSelect configured with the given aggregations. +func (csq *CodeSnippetQuery) Aggregate(fns ...AggregateFunc) *CodeSnippetSelect { + return csq.Select().Aggregate(fns...) +} + +func (csq *CodeSnippetQuery) prepareQuery(ctx context.Context) error { + for _, inter := range csq.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, csq); err != nil { + return err + } + } + } + for _, f := range csq.ctx.Fields { + if !codesnippet.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + } + if csq.path != nil { + prev, err := csq.path(ctx) + if err != nil { + return err + } + csq.sql = prev + } + return nil +} + +func (csq *CodeSnippetQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*CodeSnippet, error) { + var ( + nodes = []*CodeSnippet{} + _spec = csq.querySpec() + loadedTypes = [1]bool{ + csq.withSourceFile != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*CodeSnippet).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &CodeSnippet{config: csq.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(csq.modifiers) > 0 { + _spec.Modifiers = csq.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, csq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := csq.withSourceFile; query != nil { + if err := csq.loadSourceFile(ctx, query, nodes, nil, + func(n *CodeSnippet, e *WorkspaceFile) { n.Edges.SourceFile = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (csq *CodeSnippetQuery) loadSourceFile(ctx context.Context, query *WorkspaceFileQuery, nodes []*CodeSnippet, init func(*CodeSnippet), assign func(*CodeSnippet, *WorkspaceFile)) error { + ids := make([]uuid.UUID, 0, len(nodes)) + nodeids := make(map[uuid.UUID][]*CodeSnippet) + for i := range nodes { + fk := nodes[i].WorkspaceFileID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(workspacefile.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_file_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (csq *CodeSnippetQuery) sqlCount(ctx context.Context) (int, error) { + _spec := csq.querySpec() + if len(csq.modifiers) > 0 { + _spec.Modifiers = csq.modifiers + } + _spec.Node.Columns = csq.ctx.Fields + if len(csq.ctx.Fields) > 0 { + _spec.Unique = csq.ctx.Unique != nil && *csq.ctx.Unique + } + return sqlgraph.CountNodes(ctx, csq.driver, _spec) +} + +func (csq *CodeSnippetQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(codesnippet.Table, codesnippet.Columns, sqlgraph.NewFieldSpec(codesnippet.FieldID, field.TypeUUID)) + _spec.From = csq.sql + if unique := csq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if csq.path != nil { + _spec.Unique = true + } + if fields := csq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, codesnippet.FieldID) + for i := range fields { + if fields[i] != codesnippet.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if csq.withSourceFile != nil { + _spec.Node.AddColumnOnce(codesnippet.FieldWorkspaceFileID) + } + } + if ps := csq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := csq.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := csq.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := csq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (csq *CodeSnippetQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(csq.driver.Dialect()) + t1 := builder.Table(codesnippet.Table) + columns := csq.ctx.Fields + if len(columns) == 0 { + columns = codesnippet.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if csq.sql != nil { + selector = csq.sql + selector.Select(selector.Columns(columns...)...) + } + if csq.ctx.Unique != nil && *csq.ctx.Unique { + selector.Distinct() + } + for _, m := range csq.modifiers { + m(selector) + } + for _, p := range csq.predicates { + p(selector) + } + for _, p := range csq.order { + p(selector) + } + if offset := csq.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 := csq.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 (csq *CodeSnippetQuery) ForUpdate(opts ...sql.LockOption) *CodeSnippetQuery { + if csq.driver.Dialect() == dialect.Postgres { + csq.Unique(false) + } + csq.modifiers = append(csq.modifiers, func(s *sql.Selector) { + s.ForUpdate(opts...) + }) + return csq +} + +// 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 (csq *CodeSnippetQuery) ForShare(opts ...sql.LockOption) *CodeSnippetQuery { + if csq.driver.Dialect() == dialect.Postgres { + csq.Unique(false) + } + csq.modifiers = append(csq.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return csq +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (csq *CodeSnippetQuery) Modify(modifiers ...func(s *sql.Selector)) *CodeSnippetSelect { + csq.modifiers = append(csq.modifiers, modifiers...) + return csq.Select() +} + +// CodeSnippetGroupBy is the group-by builder for CodeSnippet entities. +type CodeSnippetGroupBy struct { + selector + build *CodeSnippetQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (csgb *CodeSnippetGroupBy) Aggregate(fns ...AggregateFunc) *CodeSnippetGroupBy { + csgb.fns = append(csgb.fns, fns...) + return csgb +} + +// Scan applies the selector query and scans the result into the given value. +func (csgb *CodeSnippetGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, csgb.build.ctx, ent.OpQueryGroupBy) + if err := csgb.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*CodeSnippetQuery, *CodeSnippetGroupBy](ctx, csgb.build, csgb, csgb.build.inters, v) +} + +func (csgb *CodeSnippetGroupBy) sqlScan(ctx context.Context, root *CodeSnippetQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(csgb.fns)) + for _, fn := range csgb.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*csgb.flds)+len(csgb.fns)) + for _, f := range *csgb.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*csgb.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := csgb.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// CodeSnippetSelect is the builder for selecting fields of CodeSnippet entities. +type CodeSnippetSelect struct { + *CodeSnippetQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (css *CodeSnippetSelect) Aggregate(fns ...AggregateFunc) *CodeSnippetSelect { + css.fns = append(css.fns, fns...) + return css +} + +// Scan applies the selector query and scans the result into the given value. +func (css *CodeSnippetSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, css.ctx, ent.OpQuerySelect) + if err := css.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*CodeSnippetQuery, *CodeSnippetSelect](ctx, css.CodeSnippetQuery, css, css.inters, v) +} + +func (css *CodeSnippetSelect) sqlScan(ctx context.Context, root *CodeSnippetQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(css.fns)) + for _, fn := range css.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*css.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 := css.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 (css *CodeSnippetSelect) Modify(modifiers ...func(s *sql.Selector)) *CodeSnippetSelect { + css.modifiers = append(css.modifiers, modifiers...) + return css +} diff --git a/backend/db/codesnippet_update.go b/backend/db/codesnippet_update.go new file mode 100644 index 0000000..32594d7 --- /dev/null +++ b/backend/db/codesnippet_update.go @@ -0,0 +1,1140 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + + "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/codesnippet" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/workspacefile" + "github.com/google/uuid" +) + +// CodeSnippetUpdate is the builder for updating CodeSnippet entities. +type CodeSnippetUpdate struct { + config + hooks []Hook + mutation *CodeSnippetMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the CodeSnippetUpdate builder. +func (csu *CodeSnippetUpdate) Where(ps ...predicate.CodeSnippet) *CodeSnippetUpdate { + csu.mutation.Where(ps...) + return csu +} + +// SetWorkspaceFileID sets the "workspace_file_id" field. +func (csu *CodeSnippetUpdate) SetWorkspaceFileID(u uuid.UUID) *CodeSnippetUpdate { + csu.mutation.SetWorkspaceFileID(u) + return csu +} + +// SetNillableWorkspaceFileID sets the "workspace_file_id" field if the given value is not nil. +func (csu *CodeSnippetUpdate) SetNillableWorkspaceFileID(u *uuid.UUID) *CodeSnippetUpdate { + if u != nil { + csu.SetWorkspaceFileID(*u) + } + return csu +} + +// SetName sets the "name" field. +func (csu *CodeSnippetUpdate) SetName(s string) *CodeSnippetUpdate { + csu.mutation.SetName(s) + return csu +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (csu *CodeSnippetUpdate) SetNillableName(s *string) *CodeSnippetUpdate { + if s != nil { + csu.SetName(*s) + } + return csu +} + +// SetSnippetType sets the "snippet_type" field. +func (csu *CodeSnippetUpdate) SetSnippetType(s string) *CodeSnippetUpdate { + csu.mutation.SetSnippetType(s) + return csu +} + +// SetNillableSnippetType sets the "snippet_type" field if the given value is not nil. +func (csu *CodeSnippetUpdate) SetNillableSnippetType(s *string) *CodeSnippetUpdate { + if s != nil { + csu.SetSnippetType(*s) + } + return csu +} + +// SetLanguage sets the "language" field. +func (csu *CodeSnippetUpdate) SetLanguage(s string) *CodeSnippetUpdate { + csu.mutation.SetLanguage(s) + return csu +} + +// SetNillableLanguage sets the "language" field if the given value is not nil. +func (csu *CodeSnippetUpdate) SetNillableLanguage(s *string) *CodeSnippetUpdate { + if s != nil { + csu.SetLanguage(*s) + } + return csu +} + +// SetContent sets the "content" field. +func (csu *CodeSnippetUpdate) SetContent(s string) *CodeSnippetUpdate { + csu.mutation.SetContent(s) + return csu +} + +// SetNillableContent sets the "content" field if the given value is not nil. +func (csu *CodeSnippetUpdate) SetNillableContent(s *string) *CodeSnippetUpdate { + if s != nil { + csu.SetContent(*s) + } + return csu +} + +// SetHash sets the "hash" field. +func (csu *CodeSnippetUpdate) SetHash(s string) *CodeSnippetUpdate { + csu.mutation.SetHash(s) + return csu +} + +// SetNillableHash sets the "hash" field if the given value is not nil. +func (csu *CodeSnippetUpdate) SetNillableHash(s *string) *CodeSnippetUpdate { + if s != nil { + csu.SetHash(*s) + } + return csu +} + +// SetStartLine sets the "start_line" field. +func (csu *CodeSnippetUpdate) SetStartLine(i int) *CodeSnippetUpdate { + csu.mutation.ResetStartLine() + csu.mutation.SetStartLine(i) + return csu +} + +// SetNillableStartLine sets the "start_line" field if the given value is not nil. +func (csu *CodeSnippetUpdate) SetNillableStartLine(i *int) *CodeSnippetUpdate { + if i != nil { + csu.SetStartLine(*i) + } + return csu +} + +// AddStartLine adds i to the "start_line" field. +func (csu *CodeSnippetUpdate) AddStartLine(i int) *CodeSnippetUpdate { + csu.mutation.AddStartLine(i) + return csu +} + +// SetEndLine sets the "end_line" field. +func (csu *CodeSnippetUpdate) SetEndLine(i int) *CodeSnippetUpdate { + csu.mutation.ResetEndLine() + csu.mutation.SetEndLine(i) + return csu +} + +// SetNillableEndLine sets the "end_line" field if the given value is not nil. +func (csu *CodeSnippetUpdate) SetNillableEndLine(i *int) *CodeSnippetUpdate { + if i != nil { + csu.SetEndLine(*i) + } + return csu +} + +// AddEndLine adds i to the "end_line" field. +func (csu *CodeSnippetUpdate) AddEndLine(i int) *CodeSnippetUpdate { + csu.mutation.AddEndLine(i) + return csu +} + +// SetStartColumn sets the "start_column" field. +func (csu *CodeSnippetUpdate) SetStartColumn(i int) *CodeSnippetUpdate { + csu.mutation.ResetStartColumn() + csu.mutation.SetStartColumn(i) + return csu +} + +// SetNillableStartColumn sets the "start_column" field if the given value is not nil. +func (csu *CodeSnippetUpdate) SetNillableStartColumn(i *int) *CodeSnippetUpdate { + if i != nil { + csu.SetStartColumn(*i) + } + return csu +} + +// AddStartColumn adds i to the "start_column" field. +func (csu *CodeSnippetUpdate) AddStartColumn(i int) *CodeSnippetUpdate { + csu.mutation.AddStartColumn(i) + return csu +} + +// SetEndColumn sets the "end_column" field. +func (csu *CodeSnippetUpdate) SetEndColumn(i int) *CodeSnippetUpdate { + csu.mutation.ResetEndColumn() + csu.mutation.SetEndColumn(i) + return csu +} + +// SetNillableEndColumn sets the "end_column" field if the given value is not nil. +func (csu *CodeSnippetUpdate) SetNillableEndColumn(i *int) *CodeSnippetUpdate { + if i != nil { + csu.SetEndColumn(*i) + } + return csu +} + +// AddEndColumn adds i to the "end_column" field. +func (csu *CodeSnippetUpdate) AddEndColumn(i int) *CodeSnippetUpdate { + csu.mutation.AddEndColumn(i) + return csu +} + +// SetNamespace sets the "namespace" field. +func (csu *CodeSnippetUpdate) SetNamespace(s string) *CodeSnippetUpdate { + csu.mutation.SetNamespace(s) + return csu +} + +// SetNillableNamespace sets the "namespace" field if the given value is not nil. +func (csu *CodeSnippetUpdate) SetNillableNamespace(s *string) *CodeSnippetUpdate { + if s != nil { + csu.SetNamespace(*s) + } + return csu +} + +// ClearNamespace clears the value of the "namespace" field. +func (csu *CodeSnippetUpdate) ClearNamespace() *CodeSnippetUpdate { + csu.mutation.ClearNamespace() + return csu +} + +// SetContainerName sets the "container_name" field. +func (csu *CodeSnippetUpdate) SetContainerName(s string) *CodeSnippetUpdate { + csu.mutation.SetContainerName(s) + return csu +} + +// SetNillableContainerName sets the "container_name" field if the given value is not nil. +func (csu *CodeSnippetUpdate) SetNillableContainerName(s *string) *CodeSnippetUpdate { + if s != nil { + csu.SetContainerName(*s) + } + return csu +} + +// ClearContainerName clears the value of the "container_name" field. +func (csu *CodeSnippetUpdate) ClearContainerName() *CodeSnippetUpdate { + csu.mutation.ClearContainerName() + return csu +} + +// SetScope sets the "scope" field. +func (csu *CodeSnippetUpdate) SetScope(s []string) *CodeSnippetUpdate { + csu.mutation.SetScope(s) + return csu +} + +// AppendScope appends s to the "scope" field. +func (csu *CodeSnippetUpdate) AppendScope(s []string) *CodeSnippetUpdate { + csu.mutation.AppendScope(s) + return csu +} + +// ClearScope clears the value of the "scope" field. +func (csu *CodeSnippetUpdate) ClearScope() *CodeSnippetUpdate { + csu.mutation.ClearScope() + return csu +} + +// SetDependencies sets the "dependencies" field. +func (csu *CodeSnippetUpdate) SetDependencies(s []string) *CodeSnippetUpdate { + csu.mutation.SetDependencies(s) + return csu +} + +// AppendDependencies appends s to the "dependencies" field. +func (csu *CodeSnippetUpdate) AppendDependencies(s []string) *CodeSnippetUpdate { + csu.mutation.AppendDependencies(s) + return csu +} + +// ClearDependencies clears the value of the "dependencies" field. +func (csu *CodeSnippetUpdate) ClearDependencies() *CodeSnippetUpdate { + csu.mutation.ClearDependencies() + return csu +} + +// SetParameters sets the "parameters" field. +func (csu *CodeSnippetUpdate) SetParameters(m []map[string]interface{}) *CodeSnippetUpdate { + csu.mutation.SetParameters(m) + return csu +} + +// AppendParameters appends m to the "parameters" field. +func (csu *CodeSnippetUpdate) AppendParameters(m []map[string]interface{}) *CodeSnippetUpdate { + csu.mutation.AppendParameters(m) + return csu +} + +// ClearParameters clears the value of the "parameters" field. +func (csu *CodeSnippetUpdate) ClearParameters() *CodeSnippetUpdate { + csu.mutation.ClearParameters() + return csu +} + +// SetSignature sets the "signature" field. +func (csu *CodeSnippetUpdate) SetSignature(s string) *CodeSnippetUpdate { + csu.mutation.SetSignature(s) + return csu +} + +// SetNillableSignature sets the "signature" field if the given value is not nil. +func (csu *CodeSnippetUpdate) SetNillableSignature(s *string) *CodeSnippetUpdate { + if s != nil { + csu.SetSignature(*s) + } + return csu +} + +// ClearSignature clears the value of the "signature" field. +func (csu *CodeSnippetUpdate) ClearSignature() *CodeSnippetUpdate { + csu.mutation.ClearSignature() + return csu +} + +// SetDefinitionText sets the "definition_text" field. +func (csu *CodeSnippetUpdate) SetDefinitionText(s string) *CodeSnippetUpdate { + csu.mutation.SetDefinitionText(s) + return csu +} + +// SetNillableDefinitionText sets the "definition_text" field if the given value is not nil. +func (csu *CodeSnippetUpdate) SetNillableDefinitionText(s *string) *CodeSnippetUpdate { + if s != nil { + csu.SetDefinitionText(*s) + } + return csu +} + +// ClearDefinitionText clears the value of the "definition_text" field. +func (csu *CodeSnippetUpdate) ClearDefinitionText() *CodeSnippetUpdate { + csu.mutation.ClearDefinitionText() + return csu +} + +// SetStructuredInfo sets the "structured_info" field. +func (csu *CodeSnippetUpdate) SetStructuredInfo(m map[string]interface{}) *CodeSnippetUpdate { + csu.mutation.SetStructuredInfo(m) + return csu +} + +// ClearStructuredInfo clears the value of the "structured_info" field. +func (csu *CodeSnippetUpdate) ClearStructuredInfo() *CodeSnippetUpdate { + csu.mutation.ClearStructuredInfo() + return csu +} + +// SetSourceFileID sets the "source_file" edge to the WorkspaceFile entity by ID. +func (csu *CodeSnippetUpdate) SetSourceFileID(id uuid.UUID) *CodeSnippetUpdate { + csu.mutation.SetSourceFileID(id) + return csu +} + +// SetSourceFile sets the "source_file" edge to the WorkspaceFile entity. +func (csu *CodeSnippetUpdate) SetSourceFile(w *WorkspaceFile) *CodeSnippetUpdate { + return csu.SetSourceFileID(w.ID) +} + +// Mutation returns the CodeSnippetMutation object of the builder. +func (csu *CodeSnippetUpdate) Mutation() *CodeSnippetMutation { + return csu.mutation +} + +// ClearSourceFile clears the "source_file" edge to the WorkspaceFile entity. +func (csu *CodeSnippetUpdate) ClearSourceFile() *CodeSnippetUpdate { + csu.mutation.ClearSourceFile() + return csu +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (csu *CodeSnippetUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, csu.sqlSave, csu.mutation, csu.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (csu *CodeSnippetUpdate) SaveX(ctx context.Context) int { + affected, err := csu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (csu *CodeSnippetUpdate) Exec(ctx context.Context) error { + _, err := csu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (csu *CodeSnippetUpdate) ExecX(ctx context.Context) { + if err := csu.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (csu *CodeSnippetUpdate) check() error { + if csu.mutation.SourceFileCleared() && len(csu.mutation.SourceFileIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "CodeSnippet.source_file"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (csu *CodeSnippetUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *CodeSnippetUpdate { + csu.modifiers = append(csu.modifiers, modifiers...) + return csu +} + +func (csu *CodeSnippetUpdate) sqlSave(ctx context.Context) (n int, err error) { + if err := csu.check(); err != nil { + return n, err + } + _spec := sqlgraph.NewUpdateSpec(codesnippet.Table, codesnippet.Columns, sqlgraph.NewFieldSpec(codesnippet.FieldID, field.TypeUUID)) + if ps := csu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := csu.mutation.Name(); ok { + _spec.SetField(codesnippet.FieldName, field.TypeString, value) + } + if value, ok := csu.mutation.SnippetType(); ok { + _spec.SetField(codesnippet.FieldSnippetType, field.TypeString, value) + } + if value, ok := csu.mutation.Language(); ok { + _spec.SetField(codesnippet.FieldLanguage, field.TypeString, value) + } + if value, ok := csu.mutation.Content(); ok { + _spec.SetField(codesnippet.FieldContent, field.TypeString, value) + } + if value, ok := csu.mutation.Hash(); ok { + _spec.SetField(codesnippet.FieldHash, field.TypeString, value) + } + if value, ok := csu.mutation.StartLine(); ok { + _spec.SetField(codesnippet.FieldStartLine, field.TypeInt, value) + } + if value, ok := csu.mutation.AddedStartLine(); ok { + _spec.AddField(codesnippet.FieldStartLine, field.TypeInt, value) + } + if value, ok := csu.mutation.EndLine(); ok { + _spec.SetField(codesnippet.FieldEndLine, field.TypeInt, value) + } + if value, ok := csu.mutation.AddedEndLine(); ok { + _spec.AddField(codesnippet.FieldEndLine, field.TypeInt, value) + } + if value, ok := csu.mutation.StartColumn(); ok { + _spec.SetField(codesnippet.FieldStartColumn, field.TypeInt, value) + } + if value, ok := csu.mutation.AddedStartColumn(); ok { + _spec.AddField(codesnippet.FieldStartColumn, field.TypeInt, value) + } + if value, ok := csu.mutation.EndColumn(); ok { + _spec.SetField(codesnippet.FieldEndColumn, field.TypeInt, value) + } + if value, ok := csu.mutation.AddedEndColumn(); ok { + _spec.AddField(codesnippet.FieldEndColumn, field.TypeInt, value) + } + if value, ok := csu.mutation.Namespace(); ok { + _spec.SetField(codesnippet.FieldNamespace, field.TypeString, value) + } + if csu.mutation.NamespaceCleared() { + _spec.ClearField(codesnippet.FieldNamespace, field.TypeString) + } + if value, ok := csu.mutation.ContainerName(); ok { + _spec.SetField(codesnippet.FieldContainerName, field.TypeString, value) + } + if csu.mutation.ContainerNameCleared() { + _spec.ClearField(codesnippet.FieldContainerName, field.TypeString) + } + if value, ok := csu.mutation.Scope(); ok { + _spec.SetField(codesnippet.FieldScope, field.TypeJSON, value) + } + if value, ok := csu.mutation.AppendedScope(); ok { + _spec.AddModifier(func(u *sql.UpdateBuilder) { + sqljson.Append(u, codesnippet.FieldScope, value) + }) + } + if csu.mutation.ScopeCleared() { + _spec.ClearField(codesnippet.FieldScope, field.TypeJSON) + } + if value, ok := csu.mutation.Dependencies(); ok { + _spec.SetField(codesnippet.FieldDependencies, field.TypeJSON, value) + } + if value, ok := csu.mutation.AppendedDependencies(); ok { + _spec.AddModifier(func(u *sql.UpdateBuilder) { + sqljson.Append(u, codesnippet.FieldDependencies, value) + }) + } + if csu.mutation.DependenciesCleared() { + _spec.ClearField(codesnippet.FieldDependencies, field.TypeJSON) + } + if value, ok := csu.mutation.Parameters(); ok { + _spec.SetField(codesnippet.FieldParameters, field.TypeJSON, value) + } + if value, ok := csu.mutation.AppendedParameters(); ok { + _spec.AddModifier(func(u *sql.UpdateBuilder) { + sqljson.Append(u, codesnippet.FieldParameters, value) + }) + } + if csu.mutation.ParametersCleared() { + _spec.ClearField(codesnippet.FieldParameters, field.TypeJSON) + } + if value, ok := csu.mutation.Signature(); ok { + _spec.SetField(codesnippet.FieldSignature, field.TypeString, value) + } + if csu.mutation.SignatureCleared() { + _spec.ClearField(codesnippet.FieldSignature, field.TypeString) + } + if value, ok := csu.mutation.DefinitionText(); ok { + _spec.SetField(codesnippet.FieldDefinitionText, field.TypeString, value) + } + if csu.mutation.DefinitionTextCleared() { + _spec.ClearField(codesnippet.FieldDefinitionText, field.TypeString) + } + if value, ok := csu.mutation.StructuredInfo(); ok { + _spec.SetField(codesnippet.FieldStructuredInfo, field.TypeJSON, value) + } + if csu.mutation.StructuredInfoCleared() { + _spec.ClearField(codesnippet.FieldStructuredInfo, field.TypeJSON) + } + if csu.mutation.SourceFileCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: codesnippet.SourceFileTable, + Columns: []string{codesnippet.SourceFileColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(workspacefile.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := csu.mutation.SourceFileIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: codesnippet.SourceFileTable, + Columns: []string{codesnippet.SourceFileColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(workspacefile.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(csu.modifiers...) + if n, err = sqlgraph.UpdateNodes(ctx, csu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{codesnippet.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + csu.mutation.done = true + return n, nil +} + +// CodeSnippetUpdateOne is the builder for updating a single CodeSnippet entity. +type CodeSnippetUpdateOne struct { + config + fields []string + hooks []Hook + mutation *CodeSnippetMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetWorkspaceFileID sets the "workspace_file_id" field. +func (csuo *CodeSnippetUpdateOne) SetWorkspaceFileID(u uuid.UUID) *CodeSnippetUpdateOne { + csuo.mutation.SetWorkspaceFileID(u) + return csuo +} + +// SetNillableWorkspaceFileID sets the "workspace_file_id" field if the given value is not nil. +func (csuo *CodeSnippetUpdateOne) SetNillableWorkspaceFileID(u *uuid.UUID) *CodeSnippetUpdateOne { + if u != nil { + csuo.SetWorkspaceFileID(*u) + } + return csuo +} + +// SetName sets the "name" field. +func (csuo *CodeSnippetUpdateOne) SetName(s string) *CodeSnippetUpdateOne { + csuo.mutation.SetName(s) + return csuo +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (csuo *CodeSnippetUpdateOne) SetNillableName(s *string) *CodeSnippetUpdateOne { + if s != nil { + csuo.SetName(*s) + } + return csuo +} + +// SetSnippetType sets the "snippet_type" field. +func (csuo *CodeSnippetUpdateOne) SetSnippetType(s string) *CodeSnippetUpdateOne { + csuo.mutation.SetSnippetType(s) + return csuo +} + +// SetNillableSnippetType sets the "snippet_type" field if the given value is not nil. +func (csuo *CodeSnippetUpdateOne) SetNillableSnippetType(s *string) *CodeSnippetUpdateOne { + if s != nil { + csuo.SetSnippetType(*s) + } + return csuo +} + +// SetLanguage sets the "language" field. +func (csuo *CodeSnippetUpdateOne) SetLanguage(s string) *CodeSnippetUpdateOne { + csuo.mutation.SetLanguage(s) + return csuo +} + +// SetNillableLanguage sets the "language" field if the given value is not nil. +func (csuo *CodeSnippetUpdateOne) SetNillableLanguage(s *string) *CodeSnippetUpdateOne { + if s != nil { + csuo.SetLanguage(*s) + } + return csuo +} + +// SetContent sets the "content" field. +func (csuo *CodeSnippetUpdateOne) SetContent(s string) *CodeSnippetUpdateOne { + csuo.mutation.SetContent(s) + return csuo +} + +// SetNillableContent sets the "content" field if the given value is not nil. +func (csuo *CodeSnippetUpdateOne) SetNillableContent(s *string) *CodeSnippetUpdateOne { + if s != nil { + csuo.SetContent(*s) + } + return csuo +} + +// SetHash sets the "hash" field. +func (csuo *CodeSnippetUpdateOne) SetHash(s string) *CodeSnippetUpdateOne { + csuo.mutation.SetHash(s) + return csuo +} + +// SetNillableHash sets the "hash" field if the given value is not nil. +func (csuo *CodeSnippetUpdateOne) SetNillableHash(s *string) *CodeSnippetUpdateOne { + if s != nil { + csuo.SetHash(*s) + } + return csuo +} + +// SetStartLine sets the "start_line" field. +func (csuo *CodeSnippetUpdateOne) SetStartLine(i int) *CodeSnippetUpdateOne { + csuo.mutation.ResetStartLine() + csuo.mutation.SetStartLine(i) + return csuo +} + +// SetNillableStartLine sets the "start_line" field if the given value is not nil. +func (csuo *CodeSnippetUpdateOne) SetNillableStartLine(i *int) *CodeSnippetUpdateOne { + if i != nil { + csuo.SetStartLine(*i) + } + return csuo +} + +// AddStartLine adds i to the "start_line" field. +func (csuo *CodeSnippetUpdateOne) AddStartLine(i int) *CodeSnippetUpdateOne { + csuo.mutation.AddStartLine(i) + return csuo +} + +// SetEndLine sets the "end_line" field. +func (csuo *CodeSnippetUpdateOne) SetEndLine(i int) *CodeSnippetUpdateOne { + csuo.mutation.ResetEndLine() + csuo.mutation.SetEndLine(i) + return csuo +} + +// SetNillableEndLine sets the "end_line" field if the given value is not nil. +func (csuo *CodeSnippetUpdateOne) SetNillableEndLine(i *int) *CodeSnippetUpdateOne { + if i != nil { + csuo.SetEndLine(*i) + } + return csuo +} + +// AddEndLine adds i to the "end_line" field. +func (csuo *CodeSnippetUpdateOne) AddEndLine(i int) *CodeSnippetUpdateOne { + csuo.mutation.AddEndLine(i) + return csuo +} + +// SetStartColumn sets the "start_column" field. +func (csuo *CodeSnippetUpdateOne) SetStartColumn(i int) *CodeSnippetUpdateOne { + csuo.mutation.ResetStartColumn() + csuo.mutation.SetStartColumn(i) + return csuo +} + +// SetNillableStartColumn sets the "start_column" field if the given value is not nil. +func (csuo *CodeSnippetUpdateOne) SetNillableStartColumn(i *int) *CodeSnippetUpdateOne { + if i != nil { + csuo.SetStartColumn(*i) + } + return csuo +} + +// AddStartColumn adds i to the "start_column" field. +func (csuo *CodeSnippetUpdateOne) AddStartColumn(i int) *CodeSnippetUpdateOne { + csuo.mutation.AddStartColumn(i) + return csuo +} + +// SetEndColumn sets the "end_column" field. +func (csuo *CodeSnippetUpdateOne) SetEndColumn(i int) *CodeSnippetUpdateOne { + csuo.mutation.ResetEndColumn() + csuo.mutation.SetEndColumn(i) + return csuo +} + +// SetNillableEndColumn sets the "end_column" field if the given value is not nil. +func (csuo *CodeSnippetUpdateOne) SetNillableEndColumn(i *int) *CodeSnippetUpdateOne { + if i != nil { + csuo.SetEndColumn(*i) + } + return csuo +} + +// AddEndColumn adds i to the "end_column" field. +func (csuo *CodeSnippetUpdateOne) AddEndColumn(i int) *CodeSnippetUpdateOne { + csuo.mutation.AddEndColumn(i) + return csuo +} + +// SetNamespace sets the "namespace" field. +func (csuo *CodeSnippetUpdateOne) SetNamespace(s string) *CodeSnippetUpdateOne { + csuo.mutation.SetNamespace(s) + return csuo +} + +// SetNillableNamespace sets the "namespace" field if the given value is not nil. +func (csuo *CodeSnippetUpdateOne) SetNillableNamespace(s *string) *CodeSnippetUpdateOne { + if s != nil { + csuo.SetNamespace(*s) + } + return csuo +} + +// ClearNamespace clears the value of the "namespace" field. +func (csuo *CodeSnippetUpdateOne) ClearNamespace() *CodeSnippetUpdateOne { + csuo.mutation.ClearNamespace() + return csuo +} + +// SetContainerName sets the "container_name" field. +func (csuo *CodeSnippetUpdateOne) SetContainerName(s string) *CodeSnippetUpdateOne { + csuo.mutation.SetContainerName(s) + return csuo +} + +// SetNillableContainerName sets the "container_name" field if the given value is not nil. +func (csuo *CodeSnippetUpdateOne) SetNillableContainerName(s *string) *CodeSnippetUpdateOne { + if s != nil { + csuo.SetContainerName(*s) + } + return csuo +} + +// ClearContainerName clears the value of the "container_name" field. +func (csuo *CodeSnippetUpdateOne) ClearContainerName() *CodeSnippetUpdateOne { + csuo.mutation.ClearContainerName() + return csuo +} + +// SetScope sets the "scope" field. +func (csuo *CodeSnippetUpdateOne) SetScope(s []string) *CodeSnippetUpdateOne { + csuo.mutation.SetScope(s) + return csuo +} + +// AppendScope appends s to the "scope" field. +func (csuo *CodeSnippetUpdateOne) AppendScope(s []string) *CodeSnippetUpdateOne { + csuo.mutation.AppendScope(s) + return csuo +} + +// ClearScope clears the value of the "scope" field. +func (csuo *CodeSnippetUpdateOne) ClearScope() *CodeSnippetUpdateOne { + csuo.mutation.ClearScope() + return csuo +} + +// SetDependencies sets the "dependencies" field. +func (csuo *CodeSnippetUpdateOne) SetDependencies(s []string) *CodeSnippetUpdateOne { + csuo.mutation.SetDependencies(s) + return csuo +} + +// AppendDependencies appends s to the "dependencies" field. +func (csuo *CodeSnippetUpdateOne) AppendDependencies(s []string) *CodeSnippetUpdateOne { + csuo.mutation.AppendDependencies(s) + return csuo +} + +// ClearDependencies clears the value of the "dependencies" field. +func (csuo *CodeSnippetUpdateOne) ClearDependencies() *CodeSnippetUpdateOne { + csuo.mutation.ClearDependencies() + return csuo +} + +// SetParameters sets the "parameters" field. +func (csuo *CodeSnippetUpdateOne) SetParameters(m []map[string]interface{}) *CodeSnippetUpdateOne { + csuo.mutation.SetParameters(m) + return csuo +} + +// AppendParameters appends m to the "parameters" field. +func (csuo *CodeSnippetUpdateOne) AppendParameters(m []map[string]interface{}) *CodeSnippetUpdateOne { + csuo.mutation.AppendParameters(m) + return csuo +} + +// ClearParameters clears the value of the "parameters" field. +func (csuo *CodeSnippetUpdateOne) ClearParameters() *CodeSnippetUpdateOne { + csuo.mutation.ClearParameters() + return csuo +} + +// SetSignature sets the "signature" field. +func (csuo *CodeSnippetUpdateOne) SetSignature(s string) *CodeSnippetUpdateOne { + csuo.mutation.SetSignature(s) + return csuo +} + +// SetNillableSignature sets the "signature" field if the given value is not nil. +func (csuo *CodeSnippetUpdateOne) SetNillableSignature(s *string) *CodeSnippetUpdateOne { + if s != nil { + csuo.SetSignature(*s) + } + return csuo +} + +// ClearSignature clears the value of the "signature" field. +func (csuo *CodeSnippetUpdateOne) ClearSignature() *CodeSnippetUpdateOne { + csuo.mutation.ClearSignature() + return csuo +} + +// SetDefinitionText sets the "definition_text" field. +func (csuo *CodeSnippetUpdateOne) SetDefinitionText(s string) *CodeSnippetUpdateOne { + csuo.mutation.SetDefinitionText(s) + return csuo +} + +// SetNillableDefinitionText sets the "definition_text" field if the given value is not nil. +func (csuo *CodeSnippetUpdateOne) SetNillableDefinitionText(s *string) *CodeSnippetUpdateOne { + if s != nil { + csuo.SetDefinitionText(*s) + } + return csuo +} + +// ClearDefinitionText clears the value of the "definition_text" field. +func (csuo *CodeSnippetUpdateOne) ClearDefinitionText() *CodeSnippetUpdateOne { + csuo.mutation.ClearDefinitionText() + return csuo +} + +// SetStructuredInfo sets the "structured_info" field. +func (csuo *CodeSnippetUpdateOne) SetStructuredInfo(m map[string]interface{}) *CodeSnippetUpdateOne { + csuo.mutation.SetStructuredInfo(m) + return csuo +} + +// ClearStructuredInfo clears the value of the "structured_info" field. +func (csuo *CodeSnippetUpdateOne) ClearStructuredInfo() *CodeSnippetUpdateOne { + csuo.mutation.ClearStructuredInfo() + return csuo +} + +// SetSourceFileID sets the "source_file" edge to the WorkspaceFile entity by ID. +func (csuo *CodeSnippetUpdateOne) SetSourceFileID(id uuid.UUID) *CodeSnippetUpdateOne { + csuo.mutation.SetSourceFileID(id) + return csuo +} + +// SetSourceFile sets the "source_file" edge to the WorkspaceFile entity. +func (csuo *CodeSnippetUpdateOne) SetSourceFile(w *WorkspaceFile) *CodeSnippetUpdateOne { + return csuo.SetSourceFileID(w.ID) +} + +// Mutation returns the CodeSnippetMutation object of the builder. +func (csuo *CodeSnippetUpdateOne) Mutation() *CodeSnippetMutation { + return csuo.mutation +} + +// ClearSourceFile clears the "source_file" edge to the WorkspaceFile entity. +func (csuo *CodeSnippetUpdateOne) ClearSourceFile() *CodeSnippetUpdateOne { + csuo.mutation.ClearSourceFile() + return csuo +} + +// Where appends a list predicates to the CodeSnippetUpdate builder. +func (csuo *CodeSnippetUpdateOne) Where(ps ...predicate.CodeSnippet) *CodeSnippetUpdateOne { + csuo.mutation.Where(ps...) + return csuo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (csuo *CodeSnippetUpdateOne) Select(field string, fields ...string) *CodeSnippetUpdateOne { + csuo.fields = append([]string{field}, fields...) + return csuo +} + +// Save executes the query and returns the updated CodeSnippet entity. +func (csuo *CodeSnippetUpdateOne) Save(ctx context.Context) (*CodeSnippet, error) { + return withHooks(ctx, csuo.sqlSave, csuo.mutation, csuo.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (csuo *CodeSnippetUpdateOne) SaveX(ctx context.Context) *CodeSnippet { + node, err := csuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (csuo *CodeSnippetUpdateOne) Exec(ctx context.Context) error { + _, err := csuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (csuo *CodeSnippetUpdateOne) ExecX(ctx context.Context) { + if err := csuo.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (csuo *CodeSnippetUpdateOne) check() error { + if csuo.mutation.SourceFileCleared() && len(csuo.mutation.SourceFileIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "CodeSnippet.source_file"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (csuo *CodeSnippetUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *CodeSnippetUpdateOne { + csuo.modifiers = append(csuo.modifiers, modifiers...) + return csuo +} + +func (csuo *CodeSnippetUpdateOne) sqlSave(ctx context.Context) (_node *CodeSnippet, err error) { + if err := csuo.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(codesnippet.Table, codesnippet.Columns, sqlgraph.NewFieldSpec(codesnippet.FieldID, field.TypeUUID)) + id, ok := csuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "CodeSnippet.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := csuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, codesnippet.FieldID) + for _, f := range fields { + if !codesnippet.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != codesnippet.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := csuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := csuo.mutation.Name(); ok { + _spec.SetField(codesnippet.FieldName, field.TypeString, value) + } + if value, ok := csuo.mutation.SnippetType(); ok { + _spec.SetField(codesnippet.FieldSnippetType, field.TypeString, value) + } + if value, ok := csuo.mutation.Language(); ok { + _spec.SetField(codesnippet.FieldLanguage, field.TypeString, value) + } + if value, ok := csuo.mutation.Content(); ok { + _spec.SetField(codesnippet.FieldContent, field.TypeString, value) + } + if value, ok := csuo.mutation.Hash(); ok { + _spec.SetField(codesnippet.FieldHash, field.TypeString, value) + } + if value, ok := csuo.mutation.StartLine(); ok { + _spec.SetField(codesnippet.FieldStartLine, field.TypeInt, value) + } + if value, ok := csuo.mutation.AddedStartLine(); ok { + _spec.AddField(codesnippet.FieldStartLine, field.TypeInt, value) + } + if value, ok := csuo.mutation.EndLine(); ok { + _spec.SetField(codesnippet.FieldEndLine, field.TypeInt, value) + } + if value, ok := csuo.mutation.AddedEndLine(); ok { + _spec.AddField(codesnippet.FieldEndLine, field.TypeInt, value) + } + if value, ok := csuo.mutation.StartColumn(); ok { + _spec.SetField(codesnippet.FieldStartColumn, field.TypeInt, value) + } + if value, ok := csuo.mutation.AddedStartColumn(); ok { + _spec.AddField(codesnippet.FieldStartColumn, field.TypeInt, value) + } + if value, ok := csuo.mutation.EndColumn(); ok { + _spec.SetField(codesnippet.FieldEndColumn, field.TypeInt, value) + } + if value, ok := csuo.mutation.AddedEndColumn(); ok { + _spec.AddField(codesnippet.FieldEndColumn, field.TypeInt, value) + } + if value, ok := csuo.mutation.Namespace(); ok { + _spec.SetField(codesnippet.FieldNamespace, field.TypeString, value) + } + if csuo.mutation.NamespaceCleared() { + _spec.ClearField(codesnippet.FieldNamespace, field.TypeString) + } + if value, ok := csuo.mutation.ContainerName(); ok { + _spec.SetField(codesnippet.FieldContainerName, field.TypeString, value) + } + if csuo.mutation.ContainerNameCleared() { + _spec.ClearField(codesnippet.FieldContainerName, field.TypeString) + } + if value, ok := csuo.mutation.Scope(); ok { + _spec.SetField(codesnippet.FieldScope, field.TypeJSON, value) + } + if value, ok := csuo.mutation.AppendedScope(); ok { + _spec.AddModifier(func(u *sql.UpdateBuilder) { + sqljson.Append(u, codesnippet.FieldScope, value) + }) + } + if csuo.mutation.ScopeCleared() { + _spec.ClearField(codesnippet.FieldScope, field.TypeJSON) + } + if value, ok := csuo.mutation.Dependencies(); ok { + _spec.SetField(codesnippet.FieldDependencies, field.TypeJSON, value) + } + if value, ok := csuo.mutation.AppendedDependencies(); ok { + _spec.AddModifier(func(u *sql.UpdateBuilder) { + sqljson.Append(u, codesnippet.FieldDependencies, value) + }) + } + if csuo.mutation.DependenciesCleared() { + _spec.ClearField(codesnippet.FieldDependencies, field.TypeJSON) + } + if value, ok := csuo.mutation.Parameters(); ok { + _spec.SetField(codesnippet.FieldParameters, field.TypeJSON, value) + } + if value, ok := csuo.mutation.AppendedParameters(); ok { + _spec.AddModifier(func(u *sql.UpdateBuilder) { + sqljson.Append(u, codesnippet.FieldParameters, value) + }) + } + if csuo.mutation.ParametersCleared() { + _spec.ClearField(codesnippet.FieldParameters, field.TypeJSON) + } + if value, ok := csuo.mutation.Signature(); ok { + _spec.SetField(codesnippet.FieldSignature, field.TypeString, value) + } + if csuo.mutation.SignatureCleared() { + _spec.ClearField(codesnippet.FieldSignature, field.TypeString) + } + if value, ok := csuo.mutation.DefinitionText(); ok { + _spec.SetField(codesnippet.FieldDefinitionText, field.TypeString, value) + } + if csuo.mutation.DefinitionTextCleared() { + _spec.ClearField(codesnippet.FieldDefinitionText, field.TypeString) + } + if value, ok := csuo.mutation.StructuredInfo(); ok { + _spec.SetField(codesnippet.FieldStructuredInfo, field.TypeJSON, value) + } + if csuo.mutation.StructuredInfoCleared() { + _spec.ClearField(codesnippet.FieldStructuredInfo, field.TypeJSON) + } + if csuo.mutation.SourceFileCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: codesnippet.SourceFileTable, + Columns: []string{codesnippet.SourceFileColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(workspacefile.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := csuo.mutation.SourceFileIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: codesnippet.SourceFileTable, + Columns: []string{codesnippet.SourceFileColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(workspacefile.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(csuo.modifiers...) + _node = &CodeSnippet{config: csuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, csuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{codesnippet.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + csuo.mutation.done = true + return _node, nil +} diff --git a/backend/db/ent.go b/backend/db/ent.go index 2edc263..a43c63b 100644 --- a/backend/db/ent.go +++ b/backend/db/ent.go @@ -19,6 +19,7 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/billingquota" "github.com/chaitin/MonkeyCode/backend/db/billingrecord" "github.com/chaitin/MonkeyCode/backend/db/billingusage" + "github.com/chaitin/MonkeyCode/backend/db/codesnippet" "github.com/chaitin/MonkeyCode/backend/db/extension" "github.com/chaitin/MonkeyCode/backend/db/invitecode" "github.com/chaitin/MonkeyCode/backend/db/model" @@ -99,6 +100,7 @@ func checkColumn(table, column string) error { billingquota.Table: billingquota.ValidColumn, billingrecord.Table: billingrecord.ValidColumn, billingusage.Table: billingusage.ValidColumn, + codesnippet.Table: codesnippet.ValidColumn, extension.Table: extension.ValidColumn, invitecode.Table: invitecode.ValidColumn, model.Table: model.ValidColumn, diff --git a/backend/db/hook/hook.go b/backend/db/hook/hook.go index cfd3a38..38f4170 100644 --- a/backend/db/hook/hook.go +++ b/backend/db/hook/hook.go @@ -93,6 +93,18 @@ func (f BillingUsageFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, return nil, fmt.Errorf("unexpected mutation type %T. expect *db.BillingUsageMutation", m) } +// The CodeSnippetFunc type is an adapter to allow the use of ordinary +// function as CodeSnippet mutator. +type CodeSnippetFunc func(context.Context, *db.CodeSnippetMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f CodeSnippetFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.CodeSnippetMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.CodeSnippetMutation", m) +} + // The ExtensionFunc type is an adapter to allow the use of ordinary // function as Extension mutator. type ExtensionFunc func(context.Context, *db.ExtensionMutation) (db.Value, error) diff --git a/backend/db/intercept/intercept.go b/backend/db/intercept/intercept.go index f9612bb..155fd85 100644 --- a/backend/db/intercept/intercept.go +++ b/backend/db/intercept/intercept.go @@ -15,6 +15,7 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/billingquota" "github.com/chaitin/MonkeyCode/backend/db/billingrecord" "github.com/chaitin/MonkeyCode/backend/db/billingusage" + "github.com/chaitin/MonkeyCode/backend/db/codesnippet" "github.com/chaitin/MonkeyCode/backend/db/extension" "github.com/chaitin/MonkeyCode/backend/db/invitecode" "github.com/chaitin/MonkeyCode/backend/db/model" @@ -276,6 +277,33 @@ func (f TraverseBillingUsage) Traverse(ctx context.Context, q db.Query) error { return fmt.Errorf("unexpected query type %T. expect *db.BillingUsageQuery", q) } +// The CodeSnippetFunc type is an adapter to allow the use of ordinary function as a Querier. +type CodeSnippetFunc func(context.Context, *db.CodeSnippetQuery) (db.Value, error) + +// Query calls f(ctx, q). +func (f CodeSnippetFunc) Query(ctx context.Context, q db.Query) (db.Value, error) { + if q, ok := q.(*db.CodeSnippetQuery); ok { + return f(ctx, q) + } + return nil, fmt.Errorf("unexpected query type %T. expect *db.CodeSnippetQuery", q) +} + +// The TraverseCodeSnippet type is an adapter to allow the use of ordinary function as Traverser. +type TraverseCodeSnippet func(context.Context, *db.CodeSnippetQuery) error + +// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline. +func (f TraverseCodeSnippet) Intercept(next db.Querier) db.Querier { + return next +} + +// Traverse calls f(ctx, q). +func (f TraverseCodeSnippet) Traverse(ctx context.Context, q db.Query) error { + if q, ok := q.(*db.CodeSnippetQuery); ok { + return f(ctx, q) + } + return fmt.Errorf("unexpected query type %T. expect *db.CodeSnippetQuery", q) +} + // The ExtensionFunc type is an adapter to allow the use of ordinary function as a Querier. type ExtensionFunc func(context.Context, *db.ExtensionQuery) (db.Value, error) @@ -644,6 +672,8 @@ func NewQuery(q db.Query) (Query, error) { return &query[*db.BillingRecordQuery, predicate.BillingRecord, billingrecord.OrderOption]{typ: db.TypeBillingRecord, tq: q}, nil case *db.BillingUsageQuery: return &query[*db.BillingUsageQuery, predicate.BillingUsage, billingusage.OrderOption]{typ: db.TypeBillingUsage, tq: q}, nil + case *db.CodeSnippetQuery: + return &query[*db.CodeSnippetQuery, predicate.CodeSnippet, codesnippet.OrderOption]{typ: db.TypeCodeSnippet, tq: q}, nil case *db.ExtensionQuery: return &query[*db.ExtensionQuery, predicate.Extension, extension.OrderOption]{typ: db.TypeExtension, tq: q}, nil case *db.InviteCodeQuery: diff --git a/backend/db/migrate/schema.go b/backend/db/migrate/schema.go index 50a7558..4086130 100644 --- a/backend/db/migrate/schema.go +++ b/backend/db/migrate/schema.go @@ -148,6 +148,64 @@ var ( Columns: BillingUsagesColumns, PrimaryKey: []*schema.Column{BillingUsagesColumns[0]}, } + // CodeSnippetsColumns holds the columns for the "code_snippets" table. + CodeSnippetsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeUUID}, + {Name: "name", Type: field.TypeString}, + {Name: "snippet_type", Type: field.TypeString}, + {Name: "language", Type: field.TypeString}, + {Name: "content", Type: field.TypeString, Size: 2147483647}, + {Name: "hash", Type: field.TypeString}, + {Name: "start_line", Type: field.TypeInt}, + {Name: "end_line", Type: field.TypeInt}, + {Name: "start_column", Type: field.TypeInt}, + {Name: "end_column", Type: field.TypeInt}, + {Name: "namespace", Type: field.TypeString, Nullable: true}, + {Name: "container_name", Type: field.TypeString, Nullable: true}, + {Name: "scope", Type: field.TypeJSON, Nullable: true}, + {Name: "dependencies", Type: field.TypeJSON, Nullable: true}, + {Name: "parameters", Type: field.TypeJSON, Nullable: true}, + {Name: "signature", Type: field.TypeString, Nullable: true, Size: 2147483647}, + {Name: "definition_text", Type: field.TypeString, Nullable: true, Size: 2147483647}, + {Name: "structured_info", Type: field.TypeJSON, Nullable: true}, + {Name: "workspace_file_id", Type: field.TypeUUID}, + } + // CodeSnippetsTable holds the schema information for the "code_snippets" table. + CodeSnippetsTable = &schema.Table{ + Name: "code_snippets", + Columns: CodeSnippetsColumns, + PrimaryKey: []*schema.Column{CodeSnippetsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "code_snippets_workspace_files_snippets", + Columns: []*schema.Column{CodeSnippetsColumns[18]}, + RefColumns: []*schema.Column{WorkspaceFilesColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + Indexes: []*schema.Index{ + { + Name: "codesnippet_hash", + Unique: false, + Columns: []*schema.Column{CodeSnippetsColumns[5]}, + }, + { + Name: "codesnippet_workspace_file_id", + Unique: false, + Columns: []*schema.Column{CodeSnippetsColumns[18]}, + }, + { + Name: "codesnippet_language_snippet_type", + Unique: false, + Columns: []*schema.Column{CodeSnippetsColumns[3], CodeSnippetsColumns[2]}, + }, + { + Name: "codesnippet_language_name", + Unique: false, + Columns: []*schema.Column{CodeSnippetsColumns[3], CodeSnippetsColumns[1]}, + }, + }, + } // ExtensionsColumns holds the columns for the "extensions" table. ExtensionsColumns = []*schema.Column{ {Name: "id", Type: field.TypeUUID}, @@ -544,6 +602,7 @@ var ( BillingQuotasTable, BillingRecordsTable, BillingUsagesTable, + CodeSnippetsTable, ExtensionsTable, InviteCodesTable, ModelsTable, @@ -584,6 +643,10 @@ func init() { BillingUsagesTable.Annotation = &entsql.Annotation{ Table: "billing_usages", } + CodeSnippetsTable.ForeignKeys[0].RefTable = WorkspaceFilesTable + CodeSnippetsTable.Annotation = &entsql.Annotation{ + Table: "code_snippets", + } ExtensionsTable.Annotation = &entsql.Annotation{ Table: "extensions", } diff --git a/backend/db/mutation.go b/backend/db/mutation.go index 3a56c34..912b57b 100644 --- a/backend/db/mutation.go +++ b/backend/db/mutation.go @@ -19,6 +19,7 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/billingquota" "github.com/chaitin/MonkeyCode/backend/db/billingrecord" "github.com/chaitin/MonkeyCode/backend/db/billingusage" + "github.com/chaitin/MonkeyCode/backend/db/codesnippet" "github.com/chaitin/MonkeyCode/backend/db/extension" "github.com/chaitin/MonkeyCode/backend/db/invitecode" "github.com/chaitin/MonkeyCode/backend/db/model" @@ -53,6 +54,7 @@ const ( TypeBillingQuota = "BillingQuota" TypeBillingRecord = "BillingRecord" TypeBillingUsage = "BillingUsage" + TypeCodeSnippet = "CodeSnippet" TypeExtension = "Extension" TypeInviteCode = "InviteCode" TypeModel = "Model" @@ -5494,6 +5496,1664 @@ func (m *BillingUsageMutation) ResetEdge(name string) error { return fmt.Errorf("unknown BillingUsage edge %s", name) } +// CodeSnippetMutation represents an operation that mutates the CodeSnippet nodes in the graph. +type CodeSnippetMutation struct { + config + op Op + typ string + id *uuid.UUID + name *string + snippet_type *string + language *string + content *string + hash *string + start_line *int + addstart_line *int + end_line *int + addend_line *int + start_column *int + addstart_column *int + end_column *int + addend_column *int + namespace *string + container_name *string + scope *[]string + appendscope []string + dependencies *[]string + appenddependencies []string + parameters *[]map[string]interface{} + appendparameters []map[string]interface{} + signature *string + definition_text *string + structured_info *map[string]interface{} + clearedFields map[string]struct{} + source_file *uuid.UUID + clearedsource_file bool + done bool + oldValue func(context.Context) (*CodeSnippet, error) + predicates []predicate.CodeSnippet +} + +var _ ent.Mutation = (*CodeSnippetMutation)(nil) + +// codesnippetOption allows management of the mutation configuration using functional options. +type codesnippetOption func(*CodeSnippetMutation) + +// newCodeSnippetMutation creates new mutation for the CodeSnippet entity. +func newCodeSnippetMutation(c config, op Op, opts ...codesnippetOption) *CodeSnippetMutation { + m := &CodeSnippetMutation{ + config: c, + op: op, + typ: TypeCodeSnippet, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withCodeSnippetID sets the ID field of the mutation. +func withCodeSnippetID(id uuid.UUID) codesnippetOption { + return func(m *CodeSnippetMutation) { + var ( + err error + once sync.Once + value *CodeSnippet + ) + m.oldValue = func(ctx context.Context) (*CodeSnippet, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().CodeSnippet.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withCodeSnippet sets the old CodeSnippet of the mutation. +func withCodeSnippet(node *CodeSnippet) codesnippetOption { + return func(m *CodeSnippetMutation) { + m.oldValue = func(context.Context) (*CodeSnippet, 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 CodeSnippetMutation) 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 CodeSnippetMutation) 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 CodeSnippet entities. +func (m *CodeSnippetMutation) 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 *CodeSnippetMutation) 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 *CodeSnippetMutation) 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().CodeSnippet.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetWorkspaceFileID sets the "workspace_file_id" field. +func (m *CodeSnippetMutation) SetWorkspaceFileID(u uuid.UUID) { + m.source_file = &u +} + +// WorkspaceFileID returns the value of the "workspace_file_id" field in the mutation. +func (m *CodeSnippetMutation) WorkspaceFileID() (r uuid.UUID, exists bool) { + v := m.source_file + if v == nil { + return + } + return *v, true +} + +// OldWorkspaceFileID returns the old "workspace_file_id" field's value of the CodeSnippet entity. +// If the CodeSnippet 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 *CodeSnippetMutation) OldWorkspaceFileID(ctx context.Context) (v uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldWorkspaceFileID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldWorkspaceFileID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldWorkspaceFileID: %w", err) + } + return oldValue.WorkspaceFileID, nil +} + +// ResetWorkspaceFileID resets all changes to the "workspace_file_id" field. +func (m *CodeSnippetMutation) ResetWorkspaceFileID() { + m.source_file = nil +} + +// SetName sets the "name" field. +func (m *CodeSnippetMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *CodeSnippetMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the CodeSnippet entity. +// If the CodeSnippet 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 *CodeSnippetMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *CodeSnippetMutation) ResetName() { + m.name = nil +} + +// SetSnippetType sets the "snippet_type" field. +func (m *CodeSnippetMutation) SetSnippetType(s string) { + m.snippet_type = &s +} + +// SnippetType returns the value of the "snippet_type" field in the mutation. +func (m *CodeSnippetMutation) SnippetType() (r string, exists bool) { + v := m.snippet_type + if v == nil { + return + } + return *v, true +} + +// OldSnippetType returns the old "snippet_type" field's value of the CodeSnippet entity. +// If the CodeSnippet 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 *CodeSnippetMutation) OldSnippetType(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSnippetType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSnippetType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSnippetType: %w", err) + } + return oldValue.SnippetType, nil +} + +// ResetSnippetType resets all changes to the "snippet_type" field. +func (m *CodeSnippetMutation) ResetSnippetType() { + m.snippet_type = nil +} + +// SetLanguage sets the "language" field. +func (m *CodeSnippetMutation) SetLanguage(s string) { + m.language = &s +} + +// Language returns the value of the "language" field in the mutation. +func (m *CodeSnippetMutation) Language() (r string, exists bool) { + v := m.language + if v == nil { + return + } + return *v, true +} + +// OldLanguage returns the old "language" field's value of the CodeSnippet entity. +// If the CodeSnippet 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 *CodeSnippetMutation) OldLanguage(ctx context.Context) (v string, 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 *CodeSnippetMutation) ResetLanguage() { + m.language = nil +} + +// SetContent sets the "content" field. +func (m *CodeSnippetMutation) SetContent(s string) { + m.content = &s +} + +// Content returns the value of the "content" field in the mutation. +func (m *CodeSnippetMutation) Content() (r string, exists bool) { + v := m.content + if v == nil { + return + } + return *v, true +} + +// OldContent returns the old "content" field's value of the CodeSnippet entity. +// If the CodeSnippet 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 *CodeSnippetMutation) OldContent(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldContent is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldContent requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldContent: %w", err) + } + return oldValue.Content, nil +} + +// ResetContent resets all changes to the "content" field. +func (m *CodeSnippetMutation) ResetContent() { + m.content = nil +} + +// SetHash sets the "hash" field. +func (m *CodeSnippetMutation) SetHash(s string) { + m.hash = &s +} + +// Hash returns the value of the "hash" field in the mutation. +func (m *CodeSnippetMutation) Hash() (r string, exists bool) { + v := m.hash + if v == nil { + return + } + return *v, true +} + +// OldHash returns the old "hash" field's value of the CodeSnippet entity. +// If the CodeSnippet 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 *CodeSnippetMutation) OldHash(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldHash is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldHash requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldHash: %w", err) + } + return oldValue.Hash, nil +} + +// ResetHash resets all changes to the "hash" field. +func (m *CodeSnippetMutation) ResetHash() { + m.hash = nil +} + +// SetStartLine sets the "start_line" field. +func (m *CodeSnippetMutation) SetStartLine(i int) { + m.start_line = &i + m.addstart_line = nil +} + +// StartLine returns the value of the "start_line" field in the mutation. +func (m *CodeSnippetMutation) StartLine() (r int, exists bool) { + v := m.start_line + if v == nil { + return + } + return *v, true +} + +// OldStartLine returns the old "start_line" field's value of the CodeSnippet entity. +// If the CodeSnippet 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 *CodeSnippetMutation) OldStartLine(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldStartLine is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldStartLine requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldStartLine: %w", err) + } + return oldValue.StartLine, nil +} + +// AddStartLine adds i to the "start_line" field. +func (m *CodeSnippetMutation) AddStartLine(i int) { + if m.addstart_line != nil { + *m.addstart_line += i + } else { + m.addstart_line = &i + } +} + +// AddedStartLine returns the value that was added to the "start_line" field in this mutation. +func (m *CodeSnippetMutation) AddedStartLine() (r int, exists bool) { + v := m.addstart_line + if v == nil { + return + } + return *v, true +} + +// ResetStartLine resets all changes to the "start_line" field. +func (m *CodeSnippetMutation) ResetStartLine() { + m.start_line = nil + m.addstart_line = nil +} + +// SetEndLine sets the "end_line" field. +func (m *CodeSnippetMutation) SetEndLine(i int) { + m.end_line = &i + m.addend_line = nil +} + +// EndLine returns the value of the "end_line" field in the mutation. +func (m *CodeSnippetMutation) EndLine() (r int, exists bool) { + v := m.end_line + if v == nil { + return + } + return *v, true +} + +// OldEndLine returns the old "end_line" field's value of the CodeSnippet entity. +// If the CodeSnippet 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 *CodeSnippetMutation) OldEndLine(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEndLine is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEndLine requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEndLine: %w", err) + } + return oldValue.EndLine, nil +} + +// AddEndLine adds i to the "end_line" field. +func (m *CodeSnippetMutation) AddEndLine(i int) { + if m.addend_line != nil { + *m.addend_line += i + } else { + m.addend_line = &i + } +} + +// AddedEndLine returns the value that was added to the "end_line" field in this mutation. +func (m *CodeSnippetMutation) AddedEndLine() (r int, exists bool) { + v := m.addend_line + if v == nil { + return + } + return *v, true +} + +// ResetEndLine resets all changes to the "end_line" field. +func (m *CodeSnippetMutation) ResetEndLine() { + m.end_line = nil + m.addend_line = nil +} + +// SetStartColumn sets the "start_column" field. +func (m *CodeSnippetMutation) SetStartColumn(i int) { + m.start_column = &i + m.addstart_column = nil +} + +// StartColumn returns the value of the "start_column" field in the mutation. +func (m *CodeSnippetMutation) StartColumn() (r int, exists bool) { + v := m.start_column + if v == nil { + return + } + return *v, true +} + +// OldStartColumn returns the old "start_column" field's value of the CodeSnippet entity. +// If the CodeSnippet 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 *CodeSnippetMutation) OldStartColumn(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldStartColumn is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldStartColumn requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldStartColumn: %w", err) + } + return oldValue.StartColumn, nil +} + +// AddStartColumn adds i to the "start_column" field. +func (m *CodeSnippetMutation) AddStartColumn(i int) { + if m.addstart_column != nil { + *m.addstart_column += i + } else { + m.addstart_column = &i + } +} + +// AddedStartColumn returns the value that was added to the "start_column" field in this mutation. +func (m *CodeSnippetMutation) AddedStartColumn() (r int, exists bool) { + v := m.addstart_column + if v == nil { + return + } + return *v, true +} + +// ResetStartColumn resets all changes to the "start_column" field. +func (m *CodeSnippetMutation) ResetStartColumn() { + m.start_column = nil + m.addstart_column = nil +} + +// SetEndColumn sets the "end_column" field. +func (m *CodeSnippetMutation) SetEndColumn(i int) { + m.end_column = &i + m.addend_column = nil +} + +// EndColumn returns the value of the "end_column" field in the mutation. +func (m *CodeSnippetMutation) EndColumn() (r int, exists bool) { + v := m.end_column + if v == nil { + return + } + return *v, true +} + +// OldEndColumn returns the old "end_column" field's value of the CodeSnippet entity. +// If the CodeSnippet 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 *CodeSnippetMutation) OldEndColumn(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEndColumn is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEndColumn requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEndColumn: %w", err) + } + return oldValue.EndColumn, nil +} + +// AddEndColumn adds i to the "end_column" field. +func (m *CodeSnippetMutation) AddEndColumn(i int) { + if m.addend_column != nil { + *m.addend_column += i + } else { + m.addend_column = &i + } +} + +// AddedEndColumn returns the value that was added to the "end_column" field in this mutation. +func (m *CodeSnippetMutation) AddedEndColumn() (r int, exists bool) { + v := m.addend_column + if v == nil { + return + } + return *v, true +} + +// ResetEndColumn resets all changes to the "end_column" field. +func (m *CodeSnippetMutation) ResetEndColumn() { + m.end_column = nil + m.addend_column = nil +} + +// SetNamespace sets the "namespace" field. +func (m *CodeSnippetMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *CodeSnippetMutation) Namespace() (r string, exists bool) { + v := m.namespace + if v == nil { + return + } + return *v, true +} + +// OldNamespace returns the old "namespace" field's value of the CodeSnippet entity. +// If the CodeSnippet 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 *CodeSnippetMutation) OldNamespace(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldNamespace is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldNamespace requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldNamespace: %w", err) + } + return oldValue.Namespace, nil +} + +// ClearNamespace clears the value of the "namespace" field. +func (m *CodeSnippetMutation) ClearNamespace() { + m.namespace = nil + m.clearedFields[codesnippet.FieldNamespace] = struct{}{} +} + +// NamespaceCleared returns if the "namespace" field was cleared in this mutation. +func (m *CodeSnippetMutation) NamespaceCleared() bool { + _, ok := m.clearedFields[codesnippet.FieldNamespace] + return ok +} + +// ResetNamespace resets all changes to the "namespace" field. +func (m *CodeSnippetMutation) ResetNamespace() { + m.namespace = nil + delete(m.clearedFields, codesnippet.FieldNamespace) +} + +// SetContainerName sets the "container_name" field. +func (m *CodeSnippetMutation) SetContainerName(s string) { + m.container_name = &s +} + +// ContainerName returns the value of the "container_name" field in the mutation. +func (m *CodeSnippetMutation) ContainerName() (r string, exists bool) { + v := m.container_name + if v == nil { + return + } + return *v, true +} + +// OldContainerName returns the old "container_name" field's value of the CodeSnippet entity. +// If the CodeSnippet 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 *CodeSnippetMutation) OldContainerName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldContainerName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldContainerName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldContainerName: %w", err) + } + return oldValue.ContainerName, nil +} + +// ClearContainerName clears the value of the "container_name" field. +func (m *CodeSnippetMutation) ClearContainerName() { + m.container_name = nil + m.clearedFields[codesnippet.FieldContainerName] = struct{}{} +} + +// ContainerNameCleared returns if the "container_name" field was cleared in this mutation. +func (m *CodeSnippetMutation) ContainerNameCleared() bool { + _, ok := m.clearedFields[codesnippet.FieldContainerName] + return ok +} + +// ResetContainerName resets all changes to the "container_name" field. +func (m *CodeSnippetMutation) ResetContainerName() { + m.container_name = nil + delete(m.clearedFields, codesnippet.FieldContainerName) +} + +// SetScope sets the "scope" field. +func (m *CodeSnippetMutation) SetScope(s []string) { + m.scope = &s + m.appendscope = nil +} + +// Scope returns the value of the "scope" field in the mutation. +func (m *CodeSnippetMutation) Scope() (r []string, exists bool) { + v := m.scope + if v == nil { + return + } + return *v, true +} + +// OldScope returns the old "scope" field's value of the CodeSnippet entity. +// If the CodeSnippet 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 *CodeSnippetMutation) OldScope(ctx context.Context) (v []string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldScope is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldScope requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldScope: %w", err) + } + return oldValue.Scope, nil +} + +// AppendScope adds s to the "scope" field. +func (m *CodeSnippetMutation) AppendScope(s []string) { + m.appendscope = append(m.appendscope, s...) +} + +// AppendedScope returns the list of values that were appended to the "scope" field in this mutation. +func (m *CodeSnippetMutation) AppendedScope() ([]string, bool) { + if len(m.appendscope) == 0 { + return nil, false + } + return m.appendscope, true +} + +// ClearScope clears the value of the "scope" field. +func (m *CodeSnippetMutation) ClearScope() { + m.scope = nil + m.appendscope = nil + m.clearedFields[codesnippet.FieldScope] = struct{}{} +} + +// ScopeCleared returns if the "scope" field was cleared in this mutation. +func (m *CodeSnippetMutation) ScopeCleared() bool { + _, ok := m.clearedFields[codesnippet.FieldScope] + return ok +} + +// ResetScope resets all changes to the "scope" field. +func (m *CodeSnippetMutation) ResetScope() { + m.scope = nil + m.appendscope = nil + delete(m.clearedFields, codesnippet.FieldScope) +} + +// SetDependencies sets the "dependencies" field. +func (m *CodeSnippetMutation) SetDependencies(s []string) { + m.dependencies = &s + m.appenddependencies = nil +} + +// Dependencies returns the value of the "dependencies" field in the mutation. +func (m *CodeSnippetMutation) Dependencies() (r []string, exists bool) { + v := m.dependencies + if v == nil { + return + } + return *v, true +} + +// OldDependencies returns the old "dependencies" field's value of the CodeSnippet entity. +// If the CodeSnippet 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 *CodeSnippetMutation) OldDependencies(ctx context.Context) (v []string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDependencies is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDependencies requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDependencies: %w", err) + } + return oldValue.Dependencies, nil +} + +// AppendDependencies adds s to the "dependencies" field. +func (m *CodeSnippetMutation) AppendDependencies(s []string) { + m.appenddependencies = append(m.appenddependencies, s...) +} + +// AppendedDependencies returns the list of values that were appended to the "dependencies" field in this mutation. +func (m *CodeSnippetMutation) AppendedDependencies() ([]string, bool) { + if len(m.appenddependencies) == 0 { + return nil, false + } + return m.appenddependencies, true +} + +// ClearDependencies clears the value of the "dependencies" field. +func (m *CodeSnippetMutation) ClearDependencies() { + m.dependencies = nil + m.appenddependencies = nil + m.clearedFields[codesnippet.FieldDependencies] = struct{}{} +} + +// DependenciesCleared returns if the "dependencies" field was cleared in this mutation. +func (m *CodeSnippetMutation) DependenciesCleared() bool { + _, ok := m.clearedFields[codesnippet.FieldDependencies] + return ok +} + +// ResetDependencies resets all changes to the "dependencies" field. +func (m *CodeSnippetMutation) ResetDependencies() { + m.dependencies = nil + m.appenddependencies = nil + delete(m.clearedFields, codesnippet.FieldDependencies) +} + +// SetParameters sets the "parameters" field. +func (m *CodeSnippetMutation) SetParameters(value []map[string]interface{}) { + m.parameters = &value + m.appendparameters = nil +} + +// Parameters returns the value of the "parameters" field in the mutation. +func (m *CodeSnippetMutation) Parameters() (r []map[string]interface{}, exists bool) { + v := m.parameters + if v == nil { + return + } + return *v, true +} + +// OldParameters returns the old "parameters" field's value of the CodeSnippet entity. +// If the CodeSnippet 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 *CodeSnippetMutation) OldParameters(ctx context.Context) (v []map[string]interface{}, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldParameters is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldParameters requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldParameters: %w", err) + } + return oldValue.Parameters, nil +} + +// AppendParameters adds value to the "parameters" field. +func (m *CodeSnippetMutation) AppendParameters(value []map[string]interface{}) { + m.appendparameters = append(m.appendparameters, value...) +} + +// AppendedParameters returns the list of values that were appended to the "parameters" field in this mutation. +func (m *CodeSnippetMutation) AppendedParameters() ([]map[string]interface{}, bool) { + if len(m.appendparameters) == 0 { + return nil, false + } + return m.appendparameters, true +} + +// ClearParameters clears the value of the "parameters" field. +func (m *CodeSnippetMutation) ClearParameters() { + m.parameters = nil + m.appendparameters = nil + m.clearedFields[codesnippet.FieldParameters] = struct{}{} +} + +// ParametersCleared returns if the "parameters" field was cleared in this mutation. +func (m *CodeSnippetMutation) ParametersCleared() bool { + _, ok := m.clearedFields[codesnippet.FieldParameters] + return ok +} + +// ResetParameters resets all changes to the "parameters" field. +func (m *CodeSnippetMutation) ResetParameters() { + m.parameters = nil + m.appendparameters = nil + delete(m.clearedFields, codesnippet.FieldParameters) +} + +// SetSignature sets the "signature" field. +func (m *CodeSnippetMutation) SetSignature(s string) { + m.signature = &s +} + +// Signature returns the value of the "signature" field in the mutation. +func (m *CodeSnippetMutation) Signature() (r string, exists bool) { + v := m.signature + if v == nil { + return + } + return *v, true +} + +// OldSignature returns the old "signature" field's value of the CodeSnippet entity. +// If the CodeSnippet 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 *CodeSnippetMutation) OldSignature(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSignature is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSignature requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSignature: %w", err) + } + return oldValue.Signature, nil +} + +// ClearSignature clears the value of the "signature" field. +func (m *CodeSnippetMutation) ClearSignature() { + m.signature = nil + m.clearedFields[codesnippet.FieldSignature] = struct{}{} +} + +// SignatureCleared returns if the "signature" field was cleared in this mutation. +func (m *CodeSnippetMutation) SignatureCleared() bool { + _, ok := m.clearedFields[codesnippet.FieldSignature] + return ok +} + +// ResetSignature resets all changes to the "signature" field. +func (m *CodeSnippetMutation) ResetSignature() { + m.signature = nil + delete(m.clearedFields, codesnippet.FieldSignature) +} + +// SetDefinitionText sets the "definition_text" field. +func (m *CodeSnippetMutation) SetDefinitionText(s string) { + m.definition_text = &s +} + +// DefinitionText returns the value of the "definition_text" field in the mutation. +func (m *CodeSnippetMutation) DefinitionText() (r string, exists bool) { + v := m.definition_text + if v == nil { + return + } + return *v, true +} + +// OldDefinitionText returns the old "definition_text" field's value of the CodeSnippet entity. +// If the CodeSnippet 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 *CodeSnippetMutation) OldDefinitionText(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDefinitionText is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDefinitionText requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDefinitionText: %w", err) + } + return oldValue.DefinitionText, nil +} + +// ClearDefinitionText clears the value of the "definition_text" field. +func (m *CodeSnippetMutation) ClearDefinitionText() { + m.definition_text = nil + m.clearedFields[codesnippet.FieldDefinitionText] = struct{}{} +} + +// DefinitionTextCleared returns if the "definition_text" field was cleared in this mutation. +func (m *CodeSnippetMutation) DefinitionTextCleared() bool { + _, ok := m.clearedFields[codesnippet.FieldDefinitionText] + return ok +} + +// ResetDefinitionText resets all changes to the "definition_text" field. +func (m *CodeSnippetMutation) ResetDefinitionText() { + m.definition_text = nil + delete(m.clearedFields, codesnippet.FieldDefinitionText) +} + +// SetStructuredInfo sets the "structured_info" field. +func (m *CodeSnippetMutation) SetStructuredInfo(value map[string]interface{}) { + m.structured_info = &value +} + +// StructuredInfo returns the value of the "structured_info" field in the mutation. +func (m *CodeSnippetMutation) StructuredInfo() (r map[string]interface{}, exists bool) { + v := m.structured_info + if v == nil { + return + } + return *v, true +} + +// OldStructuredInfo returns the old "structured_info" field's value of the CodeSnippet entity. +// If the CodeSnippet 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 *CodeSnippetMutation) OldStructuredInfo(ctx context.Context) (v map[string]interface{}, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldStructuredInfo is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldStructuredInfo requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldStructuredInfo: %w", err) + } + return oldValue.StructuredInfo, nil +} + +// ClearStructuredInfo clears the value of the "structured_info" field. +func (m *CodeSnippetMutation) ClearStructuredInfo() { + m.structured_info = nil + m.clearedFields[codesnippet.FieldStructuredInfo] = struct{}{} +} + +// StructuredInfoCleared returns if the "structured_info" field was cleared in this mutation. +func (m *CodeSnippetMutation) StructuredInfoCleared() bool { + _, ok := m.clearedFields[codesnippet.FieldStructuredInfo] + return ok +} + +// ResetStructuredInfo resets all changes to the "structured_info" field. +func (m *CodeSnippetMutation) ResetStructuredInfo() { + m.structured_info = nil + delete(m.clearedFields, codesnippet.FieldStructuredInfo) +} + +// SetSourceFileID sets the "source_file" edge to the WorkspaceFile entity by id. +func (m *CodeSnippetMutation) SetSourceFileID(id uuid.UUID) { + m.source_file = &id +} + +// ClearSourceFile clears the "source_file" edge to the WorkspaceFile entity. +func (m *CodeSnippetMutation) ClearSourceFile() { + m.clearedsource_file = true + m.clearedFields[codesnippet.FieldWorkspaceFileID] = struct{}{} +} + +// SourceFileCleared reports if the "source_file" edge to the WorkspaceFile entity was cleared. +func (m *CodeSnippetMutation) SourceFileCleared() bool { + return m.clearedsource_file +} + +// SourceFileID returns the "source_file" edge ID in the mutation. +func (m *CodeSnippetMutation) SourceFileID() (id uuid.UUID, exists bool) { + if m.source_file != nil { + return *m.source_file, true + } + return +} + +// SourceFileIDs returns the "source_file" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// SourceFileID instead. It exists only for internal usage by the builders. +func (m *CodeSnippetMutation) SourceFileIDs() (ids []uuid.UUID) { + if id := m.source_file; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetSourceFile resets all changes to the "source_file" edge. +func (m *CodeSnippetMutation) ResetSourceFile() { + m.source_file = nil + m.clearedsource_file = false +} + +// Where appends a list predicates to the CodeSnippetMutation builder. +func (m *CodeSnippetMutation) Where(ps ...predicate.CodeSnippet) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the CodeSnippetMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *CodeSnippetMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.CodeSnippet, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *CodeSnippetMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *CodeSnippetMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (CodeSnippet). +func (m *CodeSnippetMutation) 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 *CodeSnippetMutation) Fields() []string { + fields := make([]string, 0, 18) + if m.source_file != nil { + fields = append(fields, codesnippet.FieldWorkspaceFileID) + } + if m.name != nil { + fields = append(fields, codesnippet.FieldName) + } + if m.snippet_type != nil { + fields = append(fields, codesnippet.FieldSnippetType) + } + if m.language != nil { + fields = append(fields, codesnippet.FieldLanguage) + } + if m.content != nil { + fields = append(fields, codesnippet.FieldContent) + } + if m.hash != nil { + fields = append(fields, codesnippet.FieldHash) + } + if m.start_line != nil { + fields = append(fields, codesnippet.FieldStartLine) + } + if m.end_line != nil { + fields = append(fields, codesnippet.FieldEndLine) + } + if m.start_column != nil { + fields = append(fields, codesnippet.FieldStartColumn) + } + if m.end_column != nil { + fields = append(fields, codesnippet.FieldEndColumn) + } + if m.namespace != nil { + fields = append(fields, codesnippet.FieldNamespace) + } + if m.container_name != nil { + fields = append(fields, codesnippet.FieldContainerName) + } + if m.scope != nil { + fields = append(fields, codesnippet.FieldScope) + } + if m.dependencies != nil { + fields = append(fields, codesnippet.FieldDependencies) + } + if m.parameters != nil { + fields = append(fields, codesnippet.FieldParameters) + } + if m.signature != nil { + fields = append(fields, codesnippet.FieldSignature) + } + if m.definition_text != nil { + fields = append(fields, codesnippet.FieldDefinitionText) + } + if m.structured_info != nil { + fields = append(fields, codesnippet.FieldStructuredInfo) + } + 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 *CodeSnippetMutation) Field(name string) (ent.Value, bool) { + switch name { + case codesnippet.FieldWorkspaceFileID: + return m.WorkspaceFileID() + case codesnippet.FieldName: + return m.Name() + case codesnippet.FieldSnippetType: + return m.SnippetType() + case codesnippet.FieldLanguage: + return m.Language() + case codesnippet.FieldContent: + return m.Content() + case codesnippet.FieldHash: + return m.Hash() + case codesnippet.FieldStartLine: + return m.StartLine() + case codesnippet.FieldEndLine: + return m.EndLine() + case codesnippet.FieldStartColumn: + return m.StartColumn() + case codesnippet.FieldEndColumn: + return m.EndColumn() + case codesnippet.FieldNamespace: + return m.Namespace() + case codesnippet.FieldContainerName: + return m.ContainerName() + case codesnippet.FieldScope: + return m.Scope() + case codesnippet.FieldDependencies: + return m.Dependencies() + case codesnippet.FieldParameters: + return m.Parameters() + case codesnippet.FieldSignature: + return m.Signature() + case codesnippet.FieldDefinitionText: + return m.DefinitionText() + case codesnippet.FieldStructuredInfo: + return m.StructuredInfo() + } + 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 *CodeSnippetMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case codesnippet.FieldWorkspaceFileID: + return m.OldWorkspaceFileID(ctx) + case codesnippet.FieldName: + return m.OldName(ctx) + case codesnippet.FieldSnippetType: + return m.OldSnippetType(ctx) + case codesnippet.FieldLanguage: + return m.OldLanguage(ctx) + case codesnippet.FieldContent: + return m.OldContent(ctx) + case codesnippet.FieldHash: + return m.OldHash(ctx) + case codesnippet.FieldStartLine: + return m.OldStartLine(ctx) + case codesnippet.FieldEndLine: + return m.OldEndLine(ctx) + case codesnippet.FieldStartColumn: + return m.OldStartColumn(ctx) + case codesnippet.FieldEndColumn: + return m.OldEndColumn(ctx) + case codesnippet.FieldNamespace: + return m.OldNamespace(ctx) + case codesnippet.FieldContainerName: + return m.OldContainerName(ctx) + case codesnippet.FieldScope: + return m.OldScope(ctx) + case codesnippet.FieldDependencies: + return m.OldDependencies(ctx) + case codesnippet.FieldParameters: + return m.OldParameters(ctx) + case codesnippet.FieldSignature: + return m.OldSignature(ctx) + case codesnippet.FieldDefinitionText: + return m.OldDefinitionText(ctx) + case codesnippet.FieldStructuredInfo: + return m.OldStructuredInfo(ctx) + } + return nil, fmt.Errorf("unknown CodeSnippet 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 *CodeSnippetMutation) SetField(name string, value ent.Value) error { + switch name { + case codesnippet.FieldWorkspaceFileID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetWorkspaceFileID(v) + return nil + case codesnippet.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case codesnippet.FieldSnippetType: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSnippetType(v) + return nil + case codesnippet.FieldLanguage: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLanguage(v) + return nil + case codesnippet.FieldContent: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetContent(v) + return nil + case codesnippet.FieldHash: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetHash(v) + return nil + case codesnippet.FieldStartLine: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStartLine(v) + return nil + case codesnippet.FieldEndLine: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEndLine(v) + return nil + case codesnippet.FieldStartColumn: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStartColumn(v) + return nil + case codesnippet.FieldEndColumn: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEndColumn(v) + return nil + case codesnippet.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case codesnippet.FieldContainerName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetContainerName(v) + return nil + case codesnippet.FieldScope: + v, ok := value.([]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetScope(v) + return nil + case codesnippet.FieldDependencies: + v, ok := value.([]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDependencies(v) + return nil + case codesnippet.FieldParameters: + v, ok := value.([]map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetParameters(v) + return nil + case codesnippet.FieldSignature: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSignature(v) + return nil + case codesnippet.FieldDefinitionText: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDefinitionText(v) + return nil + case codesnippet.FieldStructuredInfo: + v, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStructuredInfo(v) + return nil + } + return fmt.Errorf("unknown CodeSnippet field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *CodeSnippetMutation) AddedFields() []string { + var fields []string + if m.addstart_line != nil { + fields = append(fields, codesnippet.FieldStartLine) + } + if m.addend_line != nil { + fields = append(fields, codesnippet.FieldEndLine) + } + if m.addstart_column != nil { + fields = append(fields, codesnippet.FieldStartColumn) + } + if m.addend_column != nil { + fields = append(fields, codesnippet.FieldEndColumn) + } + return fields +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *CodeSnippetMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case codesnippet.FieldStartLine: + return m.AddedStartLine() + case codesnippet.FieldEndLine: + return m.AddedEndLine() + case codesnippet.FieldStartColumn: + return m.AddedStartColumn() + case codesnippet.FieldEndColumn: + return m.AddedEndColumn() + } + 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 *CodeSnippetMutation) AddField(name string, value ent.Value) error { + switch name { + case codesnippet.FieldStartLine: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddStartLine(v) + return nil + case codesnippet.FieldEndLine: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddEndLine(v) + return nil + case codesnippet.FieldStartColumn: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddStartColumn(v) + return nil + case codesnippet.FieldEndColumn: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddEndColumn(v) + return nil + } + return fmt.Errorf("unknown CodeSnippet numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *CodeSnippetMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(codesnippet.FieldNamespace) { + fields = append(fields, codesnippet.FieldNamespace) + } + if m.FieldCleared(codesnippet.FieldContainerName) { + fields = append(fields, codesnippet.FieldContainerName) + } + if m.FieldCleared(codesnippet.FieldScope) { + fields = append(fields, codesnippet.FieldScope) + } + if m.FieldCleared(codesnippet.FieldDependencies) { + fields = append(fields, codesnippet.FieldDependencies) + } + if m.FieldCleared(codesnippet.FieldParameters) { + fields = append(fields, codesnippet.FieldParameters) + } + if m.FieldCleared(codesnippet.FieldSignature) { + fields = append(fields, codesnippet.FieldSignature) + } + if m.FieldCleared(codesnippet.FieldDefinitionText) { + fields = append(fields, codesnippet.FieldDefinitionText) + } + if m.FieldCleared(codesnippet.FieldStructuredInfo) { + fields = append(fields, codesnippet.FieldStructuredInfo) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *CodeSnippetMutation) 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 *CodeSnippetMutation) ClearField(name string) error { + switch name { + case codesnippet.FieldNamespace: + m.ClearNamespace() + return nil + case codesnippet.FieldContainerName: + m.ClearContainerName() + return nil + case codesnippet.FieldScope: + m.ClearScope() + return nil + case codesnippet.FieldDependencies: + m.ClearDependencies() + return nil + case codesnippet.FieldParameters: + m.ClearParameters() + return nil + case codesnippet.FieldSignature: + m.ClearSignature() + return nil + case codesnippet.FieldDefinitionText: + m.ClearDefinitionText() + return nil + case codesnippet.FieldStructuredInfo: + m.ClearStructuredInfo() + return nil + } + return fmt.Errorf("unknown CodeSnippet 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 *CodeSnippetMutation) ResetField(name string) error { + switch name { + case codesnippet.FieldWorkspaceFileID: + m.ResetWorkspaceFileID() + return nil + case codesnippet.FieldName: + m.ResetName() + return nil + case codesnippet.FieldSnippetType: + m.ResetSnippetType() + return nil + case codesnippet.FieldLanguage: + m.ResetLanguage() + return nil + case codesnippet.FieldContent: + m.ResetContent() + return nil + case codesnippet.FieldHash: + m.ResetHash() + return nil + case codesnippet.FieldStartLine: + m.ResetStartLine() + return nil + case codesnippet.FieldEndLine: + m.ResetEndLine() + return nil + case codesnippet.FieldStartColumn: + m.ResetStartColumn() + return nil + case codesnippet.FieldEndColumn: + m.ResetEndColumn() + return nil + case codesnippet.FieldNamespace: + m.ResetNamespace() + return nil + case codesnippet.FieldContainerName: + m.ResetContainerName() + return nil + case codesnippet.FieldScope: + m.ResetScope() + return nil + case codesnippet.FieldDependencies: + m.ResetDependencies() + return nil + case codesnippet.FieldParameters: + m.ResetParameters() + return nil + case codesnippet.FieldSignature: + m.ResetSignature() + return nil + case codesnippet.FieldDefinitionText: + m.ResetDefinitionText() + return nil + case codesnippet.FieldStructuredInfo: + m.ResetStructuredInfo() + return nil + } + return fmt.Errorf("unknown CodeSnippet field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *CodeSnippetMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.source_file != nil { + edges = append(edges, codesnippet.EdgeSourceFile) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *CodeSnippetMutation) AddedIDs(name string) []ent.Value { + switch name { + case codesnippet.EdgeSourceFile: + if id := m.source_file; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *CodeSnippetMutation) 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 *CodeSnippetMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *CodeSnippetMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedsource_file { + edges = append(edges, codesnippet.EdgeSourceFile) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *CodeSnippetMutation) EdgeCleared(name string) bool { + switch name { + case codesnippet.EdgeSourceFile: + return m.clearedsource_file + } + 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 *CodeSnippetMutation) ClearEdge(name string) error { + switch name { + case codesnippet.EdgeSourceFile: + m.ClearSourceFile() + return nil + } + return fmt.Errorf("unknown CodeSnippet 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 *CodeSnippetMutation) ResetEdge(name string) error { + switch name { + case codesnippet.EdgeSourceFile: + m.ResetSourceFile() + return nil + } + return fmt.Errorf("unknown CodeSnippet edge %s", name) +} + // ExtensionMutation represents an operation that mutates the Extension nodes in the graph. type ExtensionMutation struct { config @@ -17237,6 +18897,9 @@ type WorkspaceFileMutation struct { clearedowner bool workspace *uuid.UUID clearedworkspace bool + snippets map[uuid.UUID]struct{} + removedsnippets map[uuid.UUID]struct{} + clearedsnippets bool done bool oldValue func(context.Context) (*WorkspaceFile, error) predicates []predicate.WorkspaceFile @@ -17783,6 +19446,60 @@ func (m *WorkspaceFileMutation) ResetWorkspace() { m.clearedworkspace = false } +// AddSnippetIDs adds the "snippets" edge to the CodeSnippet entity by ids. +func (m *WorkspaceFileMutation) AddSnippetIDs(ids ...uuid.UUID) { + if m.snippets == nil { + m.snippets = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.snippets[ids[i]] = struct{}{} + } +} + +// ClearSnippets clears the "snippets" edge to the CodeSnippet entity. +func (m *WorkspaceFileMutation) ClearSnippets() { + m.clearedsnippets = true +} + +// SnippetsCleared reports if the "snippets" edge to the CodeSnippet entity was cleared. +func (m *WorkspaceFileMutation) SnippetsCleared() bool { + return m.clearedsnippets +} + +// RemoveSnippetIDs removes the "snippets" edge to the CodeSnippet entity by IDs. +func (m *WorkspaceFileMutation) RemoveSnippetIDs(ids ...uuid.UUID) { + if m.removedsnippets == nil { + m.removedsnippets = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.snippets, ids[i]) + m.removedsnippets[ids[i]] = struct{}{} + } +} + +// RemovedSnippets returns the removed IDs of the "snippets" edge to the CodeSnippet entity. +func (m *WorkspaceFileMutation) RemovedSnippetsIDs() (ids []uuid.UUID) { + for id := range m.removedsnippets { + ids = append(ids, id) + } + return +} + +// SnippetsIDs returns the "snippets" edge IDs in the mutation. +func (m *WorkspaceFileMutation) SnippetsIDs() (ids []uuid.UUID) { + for id := range m.snippets { + ids = append(ids, id) + } + return +} + +// ResetSnippets resets all changes to the "snippets" edge. +func (m *WorkspaceFileMutation) ResetSnippets() { + m.snippets = nil + m.clearedsnippets = false + m.removedsnippets = nil +} + // Where appends a list predicates to the WorkspaceFileMutation builder. func (m *WorkspaceFileMutation) Where(ps ...predicate.WorkspaceFile) { m.predicates = append(m.predicates, ps...) @@ -18082,13 +19799,16 @@ func (m *WorkspaceFileMutation) ResetField(name string) error { // AddedEdges returns all edge names that were set/added in this mutation. func (m *WorkspaceFileMutation) AddedEdges() []string { - edges := make([]string, 0, 2) + edges := make([]string, 0, 3) if m.owner != nil { edges = append(edges, workspacefile.EdgeOwner) } if m.workspace != nil { edges = append(edges, workspacefile.EdgeWorkspace) } + if m.snippets != nil { + edges = append(edges, workspacefile.EdgeSnippets) + } return edges } @@ -18104,31 +19824,51 @@ func (m *WorkspaceFileMutation) AddedIDs(name string) []ent.Value { if id := m.workspace; id != nil { return []ent.Value{*id} } + case workspacefile.EdgeSnippets: + ids := make([]ent.Value, 0, len(m.snippets)) + for id := range m.snippets { + ids = append(ids, id) + } + return ids } return nil } // RemovedEdges returns all edge names that were removed in this mutation. func (m *WorkspaceFileMutation) RemovedEdges() []string { - edges := make([]string, 0, 2) + edges := make([]string, 0, 3) + if m.removedsnippets != nil { + edges = append(edges, workspacefile.EdgeSnippets) + } return edges } // RemovedIDs returns all IDs (to other nodes) that were removed for the edge with // the given name in this mutation. func (m *WorkspaceFileMutation) RemovedIDs(name string) []ent.Value { + switch name { + case workspacefile.EdgeSnippets: + ids := make([]ent.Value, 0, len(m.removedsnippets)) + for id := range m.removedsnippets { + ids = append(ids, id) + } + return ids + } return nil } // ClearedEdges returns all edge names that were cleared in this mutation. func (m *WorkspaceFileMutation) ClearedEdges() []string { - edges := make([]string, 0, 2) + edges := make([]string, 0, 3) if m.clearedowner { edges = append(edges, workspacefile.EdgeOwner) } if m.clearedworkspace { edges = append(edges, workspacefile.EdgeWorkspace) } + if m.clearedsnippets { + edges = append(edges, workspacefile.EdgeSnippets) + } return edges } @@ -18140,6 +19880,8 @@ func (m *WorkspaceFileMutation) EdgeCleared(name string) bool { return m.clearedowner case workspacefile.EdgeWorkspace: return m.clearedworkspace + case workspacefile.EdgeSnippets: + return m.clearedsnippets } return false } @@ -18168,6 +19910,9 @@ func (m *WorkspaceFileMutation) ResetEdge(name string) error { case workspacefile.EdgeWorkspace: m.ResetWorkspace() return nil + case workspacefile.EdgeSnippets: + m.ResetSnippets() + return nil } return fmt.Errorf("unknown WorkspaceFile edge %s", name) } diff --git a/backend/db/page.go b/backend/db/page.go index a4f5c38..620ced1 100644 --- a/backend/db/page.go +++ b/backend/db/page.go @@ -109,6 +109,20 @@ func (bu *BillingUsageQuery) Page(ctx context.Context, page, size int) ([]*Billi return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil } +func (cs *CodeSnippetQuery) Page(ctx context.Context, page, size int) ([]*CodeSnippet, *PageInfo, error) { + cnt, err := cs.Count(ctx) + if err != nil { + return nil, nil, err + } + offset := size * (page - 1) + rs, err := cs.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 (e *ExtensionQuery) Page(ctx context.Context, page, size int) ([]*Extension, *PageInfo, error) { cnt, err := e.Count(ctx) if err != nil { diff --git a/backend/db/predicate/predicate.go b/backend/db/predicate/predicate.go index fc98120..f27a35e 100644 --- a/backend/db/predicate/predicate.go +++ b/backend/db/predicate/predicate.go @@ -27,6 +27,9 @@ type BillingRecord func(*sql.Selector) // BillingUsage is the predicate function for billingusage builders. type BillingUsage func(*sql.Selector) +// CodeSnippet is the predicate function for codesnippet builders. +type CodeSnippet func(*sql.Selector) + // Extension is the predicate function for extension builders. type Extension func(*sql.Selector) diff --git a/backend/db/tx.go b/backend/db/tx.go index f041c08..a99cd82 100644 --- a/backend/db/tx.go +++ b/backend/db/tx.go @@ -28,6 +28,8 @@ type Tx struct { BillingRecord *BillingRecordClient // BillingUsage is the client for interacting with the BillingUsage builders. BillingUsage *BillingUsageClient + // CodeSnippet is the client for interacting with the CodeSnippet builders. + CodeSnippet *CodeSnippetClient // Extension is the client for interacting with the Extension builders. Extension *ExtensionClient // InviteCode is the client for interacting with the InviteCode builders. @@ -192,6 +194,7 @@ func (tx *Tx) init() { tx.BillingQuota = NewBillingQuotaClient(tx.config) tx.BillingRecord = NewBillingRecordClient(tx.config) tx.BillingUsage = NewBillingUsageClient(tx.config) + tx.CodeSnippet = NewCodeSnippetClient(tx.config) tx.Extension = NewExtensionClient(tx.config) tx.InviteCode = NewInviteCodeClient(tx.config) tx.Model = NewModelClient(tx.config) diff --git a/backend/db/workspacefile.go b/backend/db/workspacefile.go index e59381a..18465e5 100644 --- a/backend/db/workspacefile.go +++ b/backend/db/workspacefile.go @@ -50,9 +50,11 @@ type WorkspaceFileEdges struct { Owner *User `json:"owner,omitempty"` // Workspace holds the value of the workspace edge. Workspace *Workspace `json:"workspace,omitempty"` + // Snippets holds the value of the snippets edge. + Snippets []*CodeSnippet `json:"snippets,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 @@ -77,6 +79,15 @@ func (e WorkspaceFileEdges) WorkspaceOrErr() (*Workspace, error) { return nil, &NotLoadedError{edge: "workspace"} } +// SnippetsOrErr returns the Snippets value or an error if the edge +// was not loaded in eager-loading. +func (e WorkspaceFileEdges) SnippetsOrErr() ([]*CodeSnippet, error) { + if e.loadedTypes[2] { + return e.Snippets, nil + } + return nil, &NotLoadedError{edge: "snippets"} +} + // scanValues returns the types for scanning values from sql.Rows. func (*WorkspaceFile) scanValues(columns []string) ([]any, error) { values := make([]any, len(columns)) @@ -188,6 +199,11 @@ func (wf *WorkspaceFile) QueryWorkspace() *WorkspaceQuery { return NewWorkspaceFileClient(wf.config).QueryWorkspace(wf) } +// QuerySnippets queries the "snippets" edge of the WorkspaceFile entity. +func (wf *WorkspaceFile) QuerySnippets() *CodeSnippetQuery { + return NewWorkspaceFileClient(wf.config).QuerySnippets(wf) +} + // Update returns a builder for updating this WorkspaceFile. // Note that you need to call WorkspaceFile.Unwrap() before calling this method if this WorkspaceFile // was returned from a transaction, and the transaction was committed or rolled back. diff --git a/backend/db/workspacefile/where.go b/backend/db/workspacefile/where.go index 5d7fead..4187a4c 100644 --- a/backend/db/workspacefile/where.go +++ b/backend/db/workspacefile/where.go @@ -587,6 +587,29 @@ func HasWorkspaceWith(preds ...predicate.Workspace) predicate.WorkspaceFile { }) } +// HasSnippets applies the HasEdge predicate on the "snippets" edge. +func HasSnippets() predicate.WorkspaceFile { + return predicate.WorkspaceFile(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, SnippetsTable, SnippetsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasSnippetsWith applies the HasEdge predicate on the "snippets" edge with a given conditions (other predicates). +func HasSnippetsWith(preds ...predicate.CodeSnippet) predicate.WorkspaceFile { + return predicate.WorkspaceFile(func(s *sql.Selector) { + step := newSnippetsStep() + 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.WorkspaceFile) predicate.WorkspaceFile { return predicate.WorkspaceFile(sql.AndPredicates(predicates...)) diff --git a/backend/db/workspacefile/workspacefile.go b/backend/db/workspacefile/workspacefile.go index 0f6a13f..aa315b8 100644 --- a/backend/db/workspacefile/workspacefile.go +++ b/backend/db/workspacefile/workspacefile.go @@ -36,6 +36,8 @@ const ( EdgeOwner = "owner" // EdgeWorkspace holds the string denoting the workspace edge name in mutations. EdgeWorkspace = "workspace" + // EdgeSnippets holds the string denoting the snippets edge name in mutations. + EdgeSnippets = "snippets" // Table holds the table name of the workspacefile in the database. Table = "workspace_files" // OwnerTable is the table that holds the owner relation/edge. @@ -52,6 +54,13 @@ const ( WorkspaceInverseTable = "workspaces" // WorkspaceColumn is the table column denoting the workspace relation/edge. WorkspaceColumn = "workspace_id" + // SnippetsTable is the table that holds the snippets relation/edge. + SnippetsTable = "code_snippets" + // SnippetsInverseTable is the table name for the CodeSnippet entity. + // It exists in this package in order to avoid circular dependency with the "codesnippet" package. + SnippetsInverseTable = "code_snippets" + // SnippetsColumn is the table column denoting the snippets relation/edge. + SnippetsColumn = "workspace_file_id" ) // Columns holds all SQL columns for workspacefile fields. @@ -159,6 +168,20 @@ func ByWorkspaceField(field string, opts ...sql.OrderTermOption) OrderOption { sqlgraph.OrderByNeighborTerms(s, newWorkspaceStep(), sql.OrderByField(field, opts...)) } } + +// BySnippetsCount orders the results by snippets count. +func BySnippetsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newSnippetsStep(), opts...) + } +} + +// BySnippets orders the results by snippets terms. +func BySnippets(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newSnippetsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} func newOwnerStep() *sqlgraph.Step { return sqlgraph.NewStep( sqlgraph.From(Table, FieldID), @@ -173,3 +196,10 @@ func newWorkspaceStep() *sqlgraph.Step { sqlgraph.Edge(sqlgraph.M2O, true, WorkspaceTable, WorkspaceColumn), ) } +func newSnippetsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(SnippetsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, SnippetsTable, SnippetsColumn), + ) +} diff --git a/backend/db/workspacefile_create.go b/backend/db/workspacefile_create.go index 6291621..3266bca 100644 --- a/backend/db/workspacefile_create.go +++ b/backend/db/workspacefile_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/codesnippet" "github.com/chaitin/MonkeyCode/backend/db/user" "github.com/chaitin/MonkeyCode/backend/db/workspace" "github.com/chaitin/MonkeyCode/backend/db/workspacefile" @@ -142,6 +143,21 @@ func (wfc *WorkspaceFileCreate) SetWorkspace(w *Workspace) *WorkspaceFileCreate return wfc.SetWorkspaceID(w.ID) } +// AddSnippetIDs adds the "snippets" edge to the CodeSnippet entity by IDs. +func (wfc *WorkspaceFileCreate) AddSnippetIDs(ids ...uuid.UUID) *WorkspaceFileCreate { + wfc.mutation.AddSnippetIDs(ids...) + return wfc +} + +// AddSnippets adds the "snippets" edges to the CodeSnippet entity. +func (wfc *WorkspaceFileCreate) AddSnippets(c ...*CodeSnippet) *WorkspaceFileCreate { + ids := make([]uuid.UUID, len(c)) + for i := range c { + ids[i] = c[i].ID + } + return wfc.AddSnippetIDs(ids...) +} + // Mutation returns the WorkspaceFileMutation object of the builder. func (wfc *WorkspaceFileCreate) Mutation() *WorkspaceFileMutation { return wfc.mutation @@ -328,6 +344,22 @@ func (wfc *WorkspaceFileCreate) createSpec() (*WorkspaceFile, *sqlgraph.CreateSp _node.WorkspaceID = nodes[0] _spec.Edges = append(_spec.Edges, edge) } + if nodes := wfc.mutation.SnippetsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: workspacefile.SnippetsTable, + Columns: []string{workspacefile.SnippetsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(codesnippet.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/workspacefile_query.go b/backend/db/workspacefile_query.go index 4b5418c..c0000c1 100644 --- a/backend/db/workspacefile_query.go +++ b/backend/db/workspacefile_query.go @@ -4,6 +4,7 @@ package db import ( "context" + "database/sql/driver" "fmt" "math" @@ -12,6 +13,7 @@ import ( "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/codesnippet" "github.com/chaitin/MonkeyCode/backend/db/predicate" "github.com/chaitin/MonkeyCode/backend/db/user" "github.com/chaitin/MonkeyCode/backend/db/workspace" @@ -28,6 +30,7 @@ type WorkspaceFileQuery struct { predicates []predicate.WorkspaceFile withOwner *UserQuery withWorkspace *WorkspaceQuery + withSnippets *CodeSnippetQuery modifiers []func(*sql.Selector) // intermediate query (i.e. traversal path). sql *sql.Selector @@ -109,6 +112,28 @@ func (wfq *WorkspaceFileQuery) QueryWorkspace() *WorkspaceQuery { return query } +// QuerySnippets chains the current query on the "snippets" edge. +func (wfq *WorkspaceFileQuery) QuerySnippets() *CodeSnippetQuery { + query := (&CodeSnippetClient{config: wfq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := wfq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := wfq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(workspacefile.Table, workspacefile.FieldID, selector), + sqlgraph.To(codesnippet.Table, codesnippet.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, workspacefile.SnippetsTable, workspacefile.SnippetsColumn), + ) + fromU = sqlgraph.SetNeighbors(wfq.driver.Dialect(), step) + return fromU, nil + } + return query +} + // First returns the first WorkspaceFile entity from the query. // Returns a *NotFoundError when no WorkspaceFile was found. func (wfq *WorkspaceFileQuery) First(ctx context.Context) (*WorkspaceFile, error) { @@ -303,6 +328,7 @@ func (wfq *WorkspaceFileQuery) Clone() *WorkspaceFileQuery { predicates: append([]predicate.WorkspaceFile{}, wfq.predicates...), withOwner: wfq.withOwner.Clone(), withWorkspace: wfq.withWorkspace.Clone(), + withSnippets: wfq.withSnippets.Clone(), // clone intermediate query. sql: wfq.sql.Clone(), path: wfq.path, @@ -332,6 +358,17 @@ func (wfq *WorkspaceFileQuery) WithWorkspace(opts ...func(*WorkspaceQuery)) *Wor return wfq } +// WithSnippets tells the query-builder to eager-load the nodes that are connected to +// the "snippets" edge. The optional arguments are used to configure the query builder of the edge. +func (wfq *WorkspaceFileQuery) WithSnippets(opts ...func(*CodeSnippetQuery)) *WorkspaceFileQuery { + query := (&CodeSnippetClient{config: wfq.config}).Query() + for _, opt := range opts { + opt(query) + } + wfq.withSnippets = query + return wfq +} + // 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. // @@ -410,9 +447,10 @@ func (wfq *WorkspaceFileQuery) sqlAll(ctx context.Context, hooks ...queryHook) ( var ( nodes = []*WorkspaceFile{} _spec = wfq.querySpec() - loadedTypes = [2]bool{ + loadedTypes = [3]bool{ wfq.withOwner != nil, wfq.withWorkspace != nil, + wfq.withSnippets != nil, } ) _spec.ScanValues = func(columns []string) ([]any, error) { @@ -448,6 +486,13 @@ func (wfq *WorkspaceFileQuery) sqlAll(ctx context.Context, hooks ...queryHook) ( return nil, err } } + if query := wfq.withSnippets; query != nil { + if err := wfq.loadSnippets(ctx, query, nodes, + func(n *WorkspaceFile) { n.Edges.Snippets = []*CodeSnippet{} }, + func(n *WorkspaceFile, e *CodeSnippet) { n.Edges.Snippets = append(n.Edges.Snippets, e) }); err != nil { + return nil, err + } + } return nodes, nil } @@ -509,6 +554,36 @@ func (wfq *WorkspaceFileQuery) loadWorkspace(ctx context.Context, query *Workspa } return nil } +func (wfq *WorkspaceFileQuery) loadSnippets(ctx context.Context, query *CodeSnippetQuery, nodes []*WorkspaceFile, init func(*WorkspaceFile), assign func(*WorkspaceFile, *CodeSnippet)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[uuid.UUID]*WorkspaceFile) + 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(codesnippet.FieldWorkspaceFileID) + } + query.Where(predicate.CodeSnippet(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(workspacefile.SnippetsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.WorkspaceFileID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "workspace_file_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} func (wfq *WorkspaceFileQuery) sqlCount(ctx context.Context) (int, error) { _spec := wfq.querySpec() diff --git a/backend/db/workspacefile_update.go b/backend/db/workspacefile_update.go index 2cc66d8..2d9131a 100644 --- a/backend/db/workspacefile_update.go +++ b/backend/db/workspacefile_update.go @@ -11,6 +11,7 @@ import ( "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/codesnippet" "github.com/chaitin/MonkeyCode/backend/db/predicate" "github.com/chaitin/MonkeyCode/backend/db/user" "github.com/chaitin/MonkeyCode/backend/db/workspace" @@ -171,6 +172,21 @@ func (wfu *WorkspaceFileUpdate) SetWorkspace(w *Workspace) *WorkspaceFileUpdate return wfu.SetWorkspaceID(w.ID) } +// AddSnippetIDs adds the "snippets" edge to the CodeSnippet entity by IDs. +func (wfu *WorkspaceFileUpdate) AddSnippetIDs(ids ...uuid.UUID) *WorkspaceFileUpdate { + wfu.mutation.AddSnippetIDs(ids...) + return wfu +} + +// AddSnippets adds the "snippets" edges to the CodeSnippet entity. +func (wfu *WorkspaceFileUpdate) AddSnippets(c ...*CodeSnippet) *WorkspaceFileUpdate { + ids := make([]uuid.UUID, len(c)) + for i := range c { + ids[i] = c[i].ID + } + return wfu.AddSnippetIDs(ids...) +} + // Mutation returns the WorkspaceFileMutation object of the builder. func (wfu *WorkspaceFileUpdate) Mutation() *WorkspaceFileMutation { return wfu.mutation @@ -188,6 +204,27 @@ func (wfu *WorkspaceFileUpdate) ClearWorkspace() *WorkspaceFileUpdate { return wfu } +// ClearSnippets clears all "snippets" edges to the CodeSnippet entity. +func (wfu *WorkspaceFileUpdate) ClearSnippets() *WorkspaceFileUpdate { + wfu.mutation.ClearSnippets() + return wfu +} + +// RemoveSnippetIDs removes the "snippets" edge to CodeSnippet entities by IDs. +func (wfu *WorkspaceFileUpdate) RemoveSnippetIDs(ids ...uuid.UUID) *WorkspaceFileUpdate { + wfu.mutation.RemoveSnippetIDs(ids...) + return wfu +} + +// RemoveSnippets removes "snippets" edges to CodeSnippet entities. +func (wfu *WorkspaceFileUpdate) RemoveSnippets(c ...*CodeSnippet) *WorkspaceFileUpdate { + ids := make([]uuid.UUID, len(c)) + for i := range c { + ids[i] = c[i].ID + } + return wfu.RemoveSnippetIDs(ids...) +} + // Save executes the query and returns the number of nodes affected by the update operation. func (wfu *WorkspaceFileUpdate) Save(ctx context.Context) (int, error) { wfu.defaults() @@ -348,6 +385,51 @@ func (wfu *WorkspaceFileUpdate) sqlSave(ctx context.Context) (n int, err error) } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if wfu.mutation.SnippetsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: workspacefile.SnippetsTable, + Columns: []string{workspacefile.SnippetsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(codesnippet.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := wfu.mutation.RemovedSnippetsIDs(); len(nodes) > 0 && !wfu.mutation.SnippetsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: workspacefile.SnippetsTable, + Columns: []string{workspacefile.SnippetsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(codesnippet.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 := wfu.mutation.SnippetsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: workspacefile.SnippetsTable, + Columns: []string{workspacefile.SnippetsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(codesnippet.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(wfu.modifiers...) if n, err = sqlgraph.UpdateNodes(ctx, wfu.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { @@ -509,6 +591,21 @@ func (wfuo *WorkspaceFileUpdateOne) SetWorkspace(w *Workspace) *WorkspaceFileUpd return wfuo.SetWorkspaceID(w.ID) } +// AddSnippetIDs adds the "snippets" edge to the CodeSnippet entity by IDs. +func (wfuo *WorkspaceFileUpdateOne) AddSnippetIDs(ids ...uuid.UUID) *WorkspaceFileUpdateOne { + wfuo.mutation.AddSnippetIDs(ids...) + return wfuo +} + +// AddSnippets adds the "snippets" edges to the CodeSnippet entity. +func (wfuo *WorkspaceFileUpdateOne) AddSnippets(c ...*CodeSnippet) *WorkspaceFileUpdateOne { + ids := make([]uuid.UUID, len(c)) + for i := range c { + ids[i] = c[i].ID + } + return wfuo.AddSnippetIDs(ids...) +} + // Mutation returns the WorkspaceFileMutation object of the builder. func (wfuo *WorkspaceFileUpdateOne) Mutation() *WorkspaceFileMutation { return wfuo.mutation @@ -526,6 +623,27 @@ func (wfuo *WorkspaceFileUpdateOne) ClearWorkspace() *WorkspaceFileUpdateOne { return wfuo } +// ClearSnippets clears all "snippets" edges to the CodeSnippet entity. +func (wfuo *WorkspaceFileUpdateOne) ClearSnippets() *WorkspaceFileUpdateOne { + wfuo.mutation.ClearSnippets() + return wfuo +} + +// RemoveSnippetIDs removes the "snippets" edge to CodeSnippet entities by IDs. +func (wfuo *WorkspaceFileUpdateOne) RemoveSnippetIDs(ids ...uuid.UUID) *WorkspaceFileUpdateOne { + wfuo.mutation.RemoveSnippetIDs(ids...) + return wfuo +} + +// RemoveSnippets removes "snippets" edges to CodeSnippet entities. +func (wfuo *WorkspaceFileUpdateOne) RemoveSnippets(c ...*CodeSnippet) *WorkspaceFileUpdateOne { + ids := make([]uuid.UUID, len(c)) + for i := range c { + ids[i] = c[i].ID + } + return wfuo.RemoveSnippetIDs(ids...) +} + // Where appends a list predicates to the WorkspaceFileUpdate builder. func (wfuo *WorkspaceFileUpdateOne) Where(ps ...predicate.WorkspaceFile) *WorkspaceFileUpdateOne { wfuo.mutation.Where(ps...) @@ -716,6 +834,51 @@ func (wfuo *WorkspaceFileUpdateOne) sqlSave(ctx context.Context) (_node *Workspa } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if wfuo.mutation.SnippetsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: workspacefile.SnippetsTable, + Columns: []string{workspacefile.SnippetsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(codesnippet.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := wfuo.mutation.RemovedSnippetsIDs(); len(nodes) > 0 && !wfuo.mutation.SnippetsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: workspacefile.SnippetsTable, + Columns: []string{workspacefile.SnippetsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(codesnippet.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 := wfuo.mutation.SnippetsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: workspacefile.SnippetsTable, + Columns: []string{workspacefile.SnippetsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(codesnippet.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(wfuo.modifiers...) _node = &WorkspaceFile{config: wfuo.config} _spec.Assign = _node.assignValues diff --git a/backend/docs/swagger.json b/backend/docs/swagger.json index 3b9b9fa..be68c2e 100644 --- a/backend/docs/swagger.json +++ b/backend/docs/swagger.json @@ -689,6 +689,62 @@ } } }, + "/api/v1/cli/{command}": { + "post": { + "description": "运行ctcode-cli命令", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "CLI" + ], + "summary": "运行ctcode-cli命令", + "parameters": [ + { + "type": "string", + "description": "命令", + "name": "command", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "标志", + "name": "flag", + "in": "query" + }, + { + "description": "代码文件信息", + "name": "codeFiles", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.CodeFiles" + } + } + ], + "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": "获取分类统计信息", @@ -2878,6 +2934,39 @@ } } }, + "/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": "同步本地文件到工作区,智能检测新增、修改和删除", @@ -3654,6 +3743,54 @@ } } }, + "domain.CodeFiles": { + "type": "object", + "properties": { + "files": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.FileMeta" + } + } + } + }, + "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.CompletionData": { "type": "object", "properties": { @@ -4061,6 +4198,59 @@ } } }, + "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", + "project_id", + "user_id" + ], + "properties": { + "code_files": { + "description": "代码文件信息", + "allOf": [ + { + "$ref": "#/definitions/domain.CodeFiles" + } + ] + }, + "project_id": { + "description": "项目ID", + "type": "string" + }, + "user_id": { + "description": "用户ID", + "type": "string" + } + } + }, "domain.GetProviderModelListResp": { "type": "object", "properties": { @@ -4101,6 +4291,64 @@ } } }, + "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": { + "type": "array", + "items": { + "type": "object" + } + }, + "signature": { + "type": "string" + }, + "startLine": { + "type": "integer" + }, + "type": { + "type": "string" + } + } + }, "domain.InviteResp": { "type": "object", "properties": { diff --git a/backend/domain/ast.go b/backend/domain/ast.go new file mode 100644 index 0000000..53ed2b5 --- /dev/null +++ b/backend/domain/ast.go @@ -0,0 +1,13 @@ +package domain + +type ParseResult struct { + FilePath string `json:"file_path"` + Definition string `json:"definition"` + Error string `json:"error,omitempty"` + Success bool `json:"success"` +} +type SaveAstReq struct { + UserID string `json:"user_id" validate:"required"` + ProjectID string `json:"project_id" validate:"required"` + Files []string `json:"files" validate:"required"` +} diff --git a/backend/domain/workspace.go b/backend/domain/workspace.go index ec0279d..6419615 100644 --- a/backend/domain/workspace.go +++ b/backend/domain/workspace.go @@ -6,15 +6,35 @@ import ( "github.com/GoYoko/web" "github.com/chaitin/MonkeyCode/backend/db" - "github.com/chaitin/MonkeyCode/backend/pkg/cvt" ) +// WorkspaceUsecase 定义 Workspace 业务逻辑接口 +type WorkspaceUsecase interface { + Create(ctx context.Context, req *CreateWorkspaceReq) (*Workspace, error) + GetByID(ctx context.Context, id string) (*Workspace, error) + GetByUserAndPath(ctx context.Context, userID, rootPath string) (*Workspace, error) + List(ctx context.Context, req *ListWorkspaceReq) (*ListWorkspaceResp, error) + Update(ctx context.Context, req *UpdateWorkspaceReq) (*Workspace, error) + Delete(ctx context.Context, id string) error + EnsureWorkspace(ctx context.Context, userID, rootPath, name string) (*Workspace, error) +} + +// WorkspaceRepo 定义 Workspace 数据访问接口 +type WorkspaceRepo interface { + Create(ctx context.Context, req *CreateWorkspaceReq) (*db.Workspace, error) + GetByID(ctx context.Context, id string) (*db.Workspace, error) + GetByUserAndPath(ctx context.Context, userID, rootPath string) (*db.Workspace, error) + List(ctx context.Context, req *ListWorkspaceReq) ([]*db.Workspace, *db.PageInfo, error) + Update(ctx context.Context, id string, fn func(*db.WorkspaceUpdateOne) error) (*db.Workspace, error) + Delete(ctx context.Context, id string) error +} + // WorkspaceFileUsecase 定义 WorkspaceFile 业务逻辑接口 type WorkspaceFileUsecase interface { Create(ctx context.Context, req *CreateWorkspaceFileReq) (*WorkspaceFile, error) Update(ctx context.Context, req *UpdateWorkspaceFileReq) (*WorkspaceFile, error) Delete(ctx context.Context, id string) error - GetAndSave(ctx context.Context, req *GetAndSaveReq) error + GetAndSave(ctx context.Context, req *GetAndSaveReq) error GetByID(ctx context.Context, id string) (*WorkspaceFile, error) GetByPath(ctx context.Context, userID, workspaceID, path string) (*WorkspaceFile, error) List(ctx context.Context, req *ListWorkspaceFileReq) (*ListWorkspaceFileResp, error) @@ -23,7 +43,6 @@ type WorkspaceFileUsecase interface { Sync(ctx context.Context, req *SyncWorkspaceFileReq) (*SyncWorkspaceFileResp, error) } - // WorkspaceFileRepo 定义 WorkspaceFile 数据访问接口 type WorkspaceFileRepo interface { Create(ctx context.Context, req *CreateWorkspaceFileReq) (*db.WorkspaceFile, error) @@ -40,6 +59,28 @@ type WorkspaceFileRepo interface { // 请求结构体 +type CreateWorkspaceReq struct { + UserID string `json:"user_id" validate:"required"` // 用户ID + Name string `json:"name" validate:"required"` // 工作区名称 + Description string `json:"description"` // 工作区描述 + RootPath string `json:"root_path" validate:"required"` // 工作区根路径 + Settings map[string]interface{} `json:"settings"` // 工作区设置 +} + +type UpdateWorkspaceReq struct { + ID string `json:"id" validate:"required"` // 工作区ID + Name *string `json:"name"` // 工作区名称 + Description *string `json:"description"` // 工作区描述 + Settings map[string]interface{} `json:"settings"` // 工作区设置 +} + +type ListWorkspaceReq struct { + *web.Pagination + UserID string `json:"user_id" query:"user_id"` // 用户ID + Search string `json:"search" query:"search"` // 搜索关键词(工作区名称或描述) + RootPath string `json:"root_path" query:"root_path"` // 根路径筛选 +} + type CreateWorkspaceFileReq struct { UserID string `json:"user_id" validate:"required"` // 用户ID WorkspaceID string `json:"workspace_id" validate:"required"` // 工作区ID @@ -85,11 +126,16 @@ type SyncWorkspaceFileReq struct { type GetAndSaveReq struct { CodeFiles CodeFiles `json:"code_files" validate:"required"` // 代码文件信息 UserID string `json:"user_id" validate:"required"` // 用户ID - ProjectID string `json:"project_id" validate:"required"` // 项目ID + ProjectID string `json:"project_id" validate:"required"` // 项目ID } // 响应结构体 +type ListWorkspaceResp struct { + *db.PageInfo + Workspaces []*Workspace `json:"workspaces"` +} + type ListWorkspaceFileResp struct { *db.PageInfo Files []*WorkspaceFile `json:"files"` @@ -104,6 +150,18 @@ type SyncWorkspaceFileResp struct { // 数据模型 +type Workspace struct { + ID string `json:"id"` // 工作区ID + UserID string `json:"user_id"` // 用户ID + Name string `json:"name"` // 工作区名称 + Description string `json:"description"` // 工作区描述 + RootPath string `json:"root_path"` // 工作区根路径 + Settings map[string]interface{} `json:"settings"` // 工作区设置 + LastAccessedAt int64 `json:"last_accessed_at"` // 最后访问时间 + CreatedAt int64 `json:"created_at"` // 创建时间 + UpdatedAt int64 `json:"updated_at"` // 更新时间 +} + type WorkspaceFile struct { ID string `json:"id"` // 文件ID UserID string `json:"user_id"` // 用户ID @@ -117,7 +175,7 @@ type WorkspaceFile struct { UpdatedAt int64 `json:"updated_at"` // 更新时间 } -type CodeLanguageType string +type CodeLanguageType string const ( CodeLanguageTypeGo CodeLanguageType = "go" @@ -137,34 +195,52 @@ const ( CodeLanguageTypeCpp CodeLanguageType = "cpp" ) -type CodeFiles struct { +type CodeFiles struct { Files []FileMeta `json:"files"` } type FileMeta struct { - FilePath string `json:"filePath"` - FileExtension string `json:"fileExtension"` - Language CodeLanguageType `json:"language"` // 语言类型(可选) - FileHash string `json:"fileHash"` // 文件哈希(可选) - Content string `json:"content"` // 文件内容(可选) + FilePath string `json:"filePath"` + FileExtension string `json:"fileExtension"` + Language CodeLanguageType `json:"language"` // 语言类型(可选) + FileHash string `json:"fileHash"` // 文件哈希(可选) + Content string `json:"content"` // 文件内容(可选) } type IndexResult struct { - Name string `json:"name"` - Type string `json:"type"` - FilePath string `json:"filePath"` - StartLine int `json:"startLine"` - EndLine int `json:"endLine"` - RangeText string `json:"rangeText"` - DefinitionText string `json:"definitionText"` - Scope []struct{} `json:"scope"` - FileHash string `json:"fileHash"` - Definition struct { - Name string `json:"name"` - Type string `json:"type"` - ReturnType string `json:"returnType"` - } `json:"definition"` - Signature string `json:"signature"` - Language string `json:"language"` - ImplementText string `json:"implementText"` + Name string `json:"name"` + Type string `json:"type"` + FilePath string `json:"filePath"` + StartLine int `json:"startLine"` + EndLine int `json:"endLine"` + RangeText string `json:"rangeText"` + DefinitionText string `json:"definitionText"` + Scope []struct{} `json:"scope"` + FileHash string `json:"fileHash"` + Definition struct { + Name string `json:"name"` + Type string `json:"type"` + ReturnType string `json:"returnType"` + } `json:"definition"` + Signature string `json:"signature"` + Language string `json:"language"` + ImplementText string `json:"implementText"` +} + +func (w *Workspace) From(e *db.Workspace) *Workspace { + if e == nil { + return w + } + + w.ID = e.ID.String() + w.UserID = e.UserID.String() + w.Name = e.Name + w.Description = e.Description + w.RootPath = e.RootPath + w.Settings = e.Settings + w.LastAccessedAt = e.LastAccessedAt.Unix() + w.CreatedAt = e.CreatedAt.Unix() + w.UpdatedAt = e.UpdatedAt.Unix() + + return w } func (w *WorkspaceFile) From(e *db.WorkspaceFile) *WorkspaceFile { @@ -187,8 +263,18 @@ func (w *WorkspaceFile) From(e *db.WorkspaceFile) *WorkspaceFile { } // 工具函数 -func FromWorkspaceFiles(files []*db.WorkspaceFile) []*WorkspaceFile { - return cvt.Iter(files, func(_ int, e *db.WorkspaceFile) *WorkspaceFile { - return cvt.From(e, &WorkspaceFile{}) - }) +func FromWorkspaces(workspaces []*db.Workspace) []*Workspace { + result := make([]*Workspace, len(workspaces)) + for i, e := range workspaces { + result[i] = (&Workspace{}).From(e) + } + return result +} + +func FromWorkspaceFiles(files []*db.WorkspaceFile) []*WorkspaceFile { + result := make([]*WorkspaceFile, len(files)) + for i, e := range files { + result[i] = (&WorkspaceFile{}).From(e) + } + return result } diff --git a/backend/ent/schema/codesnippet.go b/backend/ent/schema/codesnippet.go new file mode 100644 index 0000000..2aaaa3f --- /dev/null +++ b/backend/ent/schema/codesnippet.go @@ -0,0 +1,78 @@ +package schema + +import ( + "entgo.io/ent" + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/schema" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/index" + "github.com/google/uuid" +) + +// CodeSnippet holds the schema definition for the CodeSnippet entity. +type CodeSnippet struct { + ent.Schema +} + +func (CodeSnippet) Annotations() []schema.Annotation { + return []schema.Annotation{ + entsql.Annotation{ + Table: "code_snippets", + }, + } +} + +// Fields of the CodeSnippet. +func (CodeSnippet) Fields() []ent.Field { + return []ent.Field{ + field.UUID("id", uuid.UUID{}), + field.UUID("workspace_file_id", uuid.UUID{}).Comment("关联的源文件ID"), + + // Basic Info + field.String("name").Comment("符号名称 (e.g., function name, class name)"), + field.String("snippet_type").Comment("片段类型 (e.g., import_or_include, function_or_method)"), + field.String("language").Comment("代码语言"), + field.Text("content").Comment("代码片段原文 (rangeText)"), + field.String("hash").Comment("代码片段内容的哈希值,用于去重"), + + // Position Info + field.Int("start_line").Comment("在源文件中的起始行号"), + field.Int("end_line").Comment("在源文件中的结束行号"), + field.Int("start_column").Comment("在源文件中的起始列号"), + field.Int("end_column").Comment("在源文件中的结束列号"), + + // Context Info + field.String("namespace").Optional().Comment("所处的namespace名称"), + field.String("container_name").Optional().Comment("所处的class/struct/interface名称"), + field.JSON("scope", []string{}).Optional().Comment("作用域链"), + field.JSON("dependencies", []string{}).Optional().Comment("依赖项"), + + // Structured Info + field.JSON("parameters", []map[string]any{}).Optional().Comment("参数信息列表 (ParameterInfo[])"), + field.Text("signature").Optional().Comment("函数/方法签名"), + field.Text("definition_text").Optional().Comment("定义文本,用于提供定义参考"), + field.JSON("structured_info", map[string]any{}).Optional().Comment("结构化信息 (definition)"), + } +} + +// Edges of the CodeSnippet. +func (CodeSnippet) Edges() []ent.Edge { + return []ent.Edge{ + edge.From("source_file", WorkspaceFile.Type). + Ref("snippets"). + Field("workspace_file_id"). + Unique(). + Required(), + } +} + +// Indexes of the CodeSnippet. +func (CodeSnippet) Indexes() []ent.Index { + return []ent.Index{ + index.Fields("hash"), + index.Fields("workspace_file_id"), + index.Fields("language", "snippet_type"), + index.Fields("language", "name"), + } +} diff --git a/backend/ent/schema/workspacefile.go b/backend/ent/schema/workspacefile.go index 4226c0c..e042c80 100644 --- a/backend/ent/schema/workspacefile.go +++ b/backend/ent/schema/workspacefile.go @@ -57,6 +57,7 @@ func (WorkspaceFile) Edges() []ent.Edge { return []ent.Edge{ edge.From("owner", User.Type).Ref("workspace_files").Field("user_id").Unique().Required(), edge.From("workspace", Workspace.Type).Ref("files").Field("workspace_id").Unique().Required(), + edge.To("snippets", CodeSnippet.Type), } } diff --git a/backend/internal/provider.go b/backend/internal/provider.go index f6e785f..f148fd8 100644 --- a/backend/internal/provider.go +++ b/backend/internal/provider.go @@ -57,7 +57,9 @@ var Provider = wire.NewSet( billingusecase.NewBillingUsecase, erepo.NewExtensionRepo, eusecase.NewExtensionUsecase, + workspacerepo.NewWorkspaceRepo, workspacerepo.NewWorkspaceFileRepo, + workspaceusecase.NewWorkspaceUsecase, workspaceusecase.NewWorkspaceFileUsecase, workspacehandlerv1.NewWorkspaceFileHandler, sockethandler.NewSocketHandler, diff --git a/backend/internal/socket/handler/socket.go b/backend/internal/socket/handler/socket.go index 22c8e09..1f87941 100644 --- a/backend/internal/socket/handler/socket.go +++ b/backend/internal/socket/handler/socket.go @@ -600,18 +600,32 @@ func (h *SocketHandler) generateAST(filePath, content string) string { return "" } - // 创建临时文件来调用ctcode-cli - // 注意:这里是一个简化版本,实际使用时可能需要更复杂的临时文件处理 - // 为了验证功能,我们直接调用cli,假设它能处理内容 - results, err := cli.RunParseCLI("parse", "--successOnly", filePath) + // 准备代码文件信息 + codeFiles := domain.CodeFiles{ + Files: []domain.FileMeta{ + { + FilePath: filePath, + FileExtension: ext, + Content: content, + }, + }, + } + + // 调用CLI工具生成AST + results, err := cli.RunCli("parse", "--successOnly", codeFiles) if err != nil { h.logger.Error("Failed to generate AST", "filePath", filePath, "error", err) return "" } // 如果解析成功,返回第一个结果的definition - if len(results) > 0 && results[0].Success { - return results[0].Definition + if len(results) > 0 { + resultBytes, err := json.Marshal(results[0]) + if err != nil { + h.logger.Error("Failed to marshal AST result", "filePath", filePath, "error", err) + return "" + } + return string(resultBytes) } return "" diff --git a/backend/internal/workspace/handler/http/v1/workspace.go b/backend/internal/workspace/handler/http/v1/workspace.go index d22832c..733a8fd 100644 --- a/backend/internal/workspace/handler/http/v1/workspace.go +++ b/backend/internal/workspace/handler/http/v1/workspace.go @@ -92,17 +92,20 @@ func (h *WorkspaceFileHandler) GetByID(c *web.Context, req struct { return c.Success(file) } -// GetAndSave -// @Tags WorkspaceFile -// @Summary 获取并保存工作区文件 -// @param ctx -// @param req -// @return error +// GetAndSave +// +// @Tags WorkspaceFile +// @Summary 获取并保存工作区文件 +// @Accept json +// @Produce json +// @Param req body domain.GetAndSaveReq true "请求参数" +// @Success 200 {object} web.Resp{} +// @Router /api/v1/workspace/files/get-and-save [post] func (h *WorkspaceFileHandler) GetAndSave(ctx *web.Context, req *domain.GetAndSaveReq) error { - err := h.usecase.GetAndSave(ctx.Request().Context(), req) + err := h.usecase.GetAndSave(ctx.Request().Context(), req) if err != nil { h.logger.Error("failed to get and save workspace files", "error", err, "count", len(req.CodeFiles.Files)) - return err + return err } return ctx.Success(nil) } diff --git a/backend/internal/workspace/usecase/workspace.go b/backend/internal/workspace/usecase/workspace.go index 3b85b15..54398b1 100644 --- a/backend/internal/workspace/usecase/workspace.go +++ b/backend/internal/workspace/usecase/workspace.go @@ -14,7 +14,6 @@ import ( "github.com/chaitin/MonkeyCode/backend/db" "github.com/chaitin/MonkeyCode/backend/domain" "github.com/chaitin/MonkeyCode/backend/pkg/cli" - "github.com/chaitin/MonkeyCode/backend/pkg/cvt" ) type WorkspaceUsecase struct { @@ -66,7 +65,7 @@ func (u *WorkspaceUsecase) Create(ctx context.Context, req *domain.CreateWorkspa } u.logger.Info("workspace created", "id", workspace.ID, "name", req.Name, "root_path", req.RootPath) - return cvt.From(workspace, &domain.Workspace{}), nil + return (&domain.Workspace{}).From(workspace), nil } func (u *WorkspaceUsecase) GetByID(ctx context.Context, id string) (*domain.Workspace, error) { @@ -75,7 +74,7 @@ func (u *WorkspaceUsecase) GetByID(ctx context.Context, id string) (*domain.Work return nil, fmt.Errorf("failed to get workspace: %w", err) } - return cvt.From(workspace, &domain.Workspace{}), nil + return (&domain.Workspace{}).From(workspace), nil } func (u *WorkspaceUsecase) GetByUserAndPath(ctx context.Context, userID, rootPath string) (*domain.Workspace, error) { @@ -84,7 +83,7 @@ func (u *WorkspaceUsecase) GetByUserAndPath(ctx context.Context, userID, rootPat return nil, fmt.Errorf("failed to get workspace by user and path: %w", err) } - return cvt.From(workspace, &domain.Workspace{}), nil + return (&domain.Workspace{}).From(workspace), nil } func (u *WorkspaceUsecase) List(ctx context.Context, req *domain.ListWorkspaceReq) (*domain.ListWorkspaceResp, error) { @@ -118,7 +117,7 @@ func (u *WorkspaceUsecase) Update(ctx context.Context, req *domain.UpdateWorkspa } u.logger.Info("workspace updated", "id", req.ID) - return cvt.From(workspace, &domain.Workspace{}), nil + return (&domain.Workspace{}).From(workspace), nil } func (u *WorkspaceUsecase) Delete(ctx context.Context, id string) error { @@ -144,7 +143,7 @@ func (u *WorkspaceUsecase) EnsureWorkspace(ctx context.Context, userID, rootPath if err != nil { u.logger.Warn("failed to update workspace last accessed time", "error", err, "id", workspace.ID) } - return cvt.From(updated, &domain.Workspace{}), nil + return (&domain.Workspace{}).From(updated), nil } // 如果工作区不存在,创建新的工作区 @@ -206,7 +205,7 @@ func (u *WorkspaceFileUsecase) Create(ctx context.Context, req *domain.CreateWor if err != nil { return nil, fmt.Errorf("failed to get workspace by ID: %w", err) } - + _, err = u.workspaceSvc.EnsureWorkspace(ctx, req.UserID, workspace.RootPath, "") if err != nil { return nil, fmt.Errorf("failed to ensure workspace exists: %w", err) @@ -219,7 +218,7 @@ func (u *WorkspaceFileUsecase) Create(ctx context.Context, req *domain.CreateWor } u.logger.Info("workspace file created", "id", file.ID, "path", req.Path) - return cvt.From(file, &domain.WorkspaceFile{}), nil + return (&domain.WorkspaceFile{}).From(file), nil } func (u *WorkspaceFileUsecase) Update(ctx context.Context, req *domain.UpdateWorkspaceFileReq) (*domain.WorkspaceFile, error) { @@ -262,7 +261,7 @@ func (u *WorkspaceFileUsecase) Update(ctx context.Context, req *domain.UpdateWor } u.logger.Info("workspace file updated", "id", req.ID) - return cvt.From(file, &domain.WorkspaceFile{}), nil + return (&domain.WorkspaceFile{}).From(file), nil } func (u *WorkspaceFileUsecase) Delete(ctx context.Context, id string) error { @@ -282,11 +281,11 @@ func (u *WorkspaceFileUsecase) GetByID(ctx context.Context, id string) (*domain. return nil, fmt.Errorf("failed to get file: %w", err) } - return cvt.From(file, &domain.WorkspaceFile{}), nil + return (&domain.WorkspaceFile{}).From(file), nil } -func (u *WorkspaceFileUsecase) GetAndSave(ctx context.Context, req *domain.GetAndSaveReq) (error) { - results, err := cli.RunCli("index", "", req.CodeFiles) +func (u *WorkspaceFileUsecase) GetAndSave(ctx context.Context, req *domain.GetAndSaveReq) error { + results, err := cli.RunCli("index", "", req.CodeFiles) if err != nil { return err } @@ -296,12 +295,13 @@ func (u *WorkspaceFileUsecase) GetAndSave(ctx context.Context, req *domain.GetAn return err } - resString, err := json.Marshal(res) - if err!= nil { + resString, err := json.Marshal(res) + if err != nil { return err } _, err = u.repo.Update(ctx, file.ID.String(), func(up *db.WorkspaceFileUpdateOne) error { - return up.SetContent(string(resString)).Exec(ctx) + up.SetContent(string(resString)) + return nil }) if err != nil { return err @@ -316,7 +316,7 @@ func (u *WorkspaceFileUsecase) GetByPath(ctx context.Context, userID, workspaceI return nil, fmt.Errorf("failed to get file by path: %w", err) } - return cvt.From(file, &domain.WorkspaceFile{}), nil + return (&domain.WorkspaceFile{}).From(file), nil } func (u *WorkspaceFileUsecase) List(ctx context.Context, req *domain.ListWorkspaceFileReq) (*domain.ListWorkspaceFileResp, error) { @@ -338,7 +338,7 @@ func (u *WorkspaceFileUsecase) BatchCreate(ctx context.Context, req *domain.Batc if err != nil { return nil, fmt.Errorf("failed to get workspace by ID: %w", err) } - + _, err = u.workspaceSvc.EnsureWorkspace(ctx, req.UserID, workspace.RootPath, "") if err != nil { return nil, fmt.Errorf("failed to ensure workspace exists: %w", err) @@ -397,7 +397,7 @@ func (u *WorkspaceFileUsecase) Sync(ctx context.Context, req *domain.SyncWorkspa if err != nil { return nil, fmt.Errorf("failed to get workspace by ID: %w", err) } - + _, err = u.workspaceSvc.EnsureWorkspace(ctx, req.UserID, workspace.RootPath, "") if err != nil { return nil, fmt.Errorf("failed to ensure workspace exists: %w", err) diff --git a/backend/pkg/cli/cli.go b/backend/pkg/cli/cli.go index 2d1e532..fae8264 100644 --- a/backend/pkg/cli/cli.go +++ b/backend/pkg/cli/cli.go @@ -8,30 +8,34 @@ import ( "github.com/chaitin/MonkeyCode/backend/domain" ) -// RunCli -// @Tags WorkspaceFile -// @Description: 运行ctcode-cli命令 -// @param command 命令 -// @param flag [ -m | --maxlines ] 解析时允许的最大 CodeSnippet 行数 -// @param codeFiles 代码文件信息 -// @return string 输出结果 -// @return error +// RunCli 运行ctcode-cli命令 +// +// @Tags CLI +// @Summary 运行ctcode-cli命令 +// @Description 运行ctcode-cli命令 +// @Accept json +// @Produce json +// @Param command path string true "命令" +// @Param flag query string false "标志" +// @Param codeFiles body domain.CodeFiles true "代码文件信息" +// @Success 200 {object} []domain.IndexResult "输出结果" +// @Failure 500 {object} web.Resp "内部错误" +// @Router /api/v1/cli/{command} [post] func RunCli(command string, flag string, codeFiles domain.CodeFiles) ([]domain.IndexResult, error) { - inputJson, err := json.Marshal(codeFiles) + inputJson, err := json.Marshal(codeFiles) if err != nil { - return []domain.IndexResult{}, err - } - cmd := exec.Command("ctcode-cli", command, flag, string(inputJson)) - cmd.Env = os.Environ() - output, err := cmd.CombinedOutput() - - if err != nil { - return []domain.IndexResult{}, err - } - var res []domain.IndexResult - err = json.Unmarshal(output, &res) - if err!= nil { return []domain.IndexResult{}, err - } - return res, nil + } + cmd := exec.Command("ctcode-cli", command, flag, string(inputJson)) + cmd.Env = os.Environ() + output, err := cmd.CombinedOutput() + if err != nil { + return []domain.IndexResult{}, err + } + var res []domain.IndexResult + err = json.Unmarshal(output, &res) + if err != nil { + return []domain.IndexResult{}, err + } + return res, nil }