diff --git a/backend/cmd/server/wire_gen.go b/backend/cmd/server/wire_gen.go index 63960bc..b4e36d8 100644 --- a/backend/cmd/server/wire_gen.go +++ b/backend/cmd/server/wire_gen.go @@ -7,8 +7,6 @@ package main import ( - "log/slog" - "github.com/GoYoko/web" "github.com/chaitin/MonkeyCode/backend/config" "github.com/chaitin/MonkeyCode/backend/db" @@ -23,9 +21,9 @@ import ( v1_2 "github.com/chaitin/MonkeyCode/backend/internal/model/handler/http/v1" repo3 "github.com/chaitin/MonkeyCode/backend/internal/model/repo" usecase2 "github.com/chaitin/MonkeyCode/backend/internal/model/usecase" - v1 "github.com/chaitin/MonkeyCode/backend/internal/openai/handler/v1" + "github.com/chaitin/MonkeyCode/backend/internal/openai/handler/v1" repo2 "github.com/chaitin/MonkeyCode/backend/internal/openai/repo" - openai "github.com/chaitin/MonkeyCode/backend/internal/openai/usecase" + "github.com/chaitin/MonkeyCode/backend/internal/openai/usecase" "github.com/chaitin/MonkeyCode/backend/internal/proxy" "github.com/chaitin/MonkeyCode/backend/internal/proxy/repo" "github.com/chaitin/MonkeyCode/backend/internal/proxy/usecase" @@ -36,6 +34,7 @@ import ( "github.com/chaitin/MonkeyCode/backend/pkg/logger" "github.com/chaitin/MonkeyCode/backend/pkg/session" "github.com/chaitin/MonkeyCode/backend/pkg/store" + "log/slog" ) // Injectors from wire.go: diff --git a/backend/db/client.go b/backend/db/client.go index b617f83..6e3451e 100644 --- a/backend/db/client.go +++ b/backend/db/client.go @@ -25,8 +25,9 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/billingusage" "github.com/chaitin/MonkeyCode/backend/db/invitecode" "github.com/chaitin/MonkeyCode/backend/db/model" - "github.com/chaitin/MonkeyCode/backend/db/record" "github.com/chaitin/MonkeyCode/backend/db/setting" + "github.com/chaitin/MonkeyCode/backend/db/task" + "github.com/chaitin/MonkeyCode/backend/db/taskrecord" "github.com/chaitin/MonkeyCode/backend/db/user" "github.com/chaitin/MonkeyCode/backend/db/userloginhistory" @@ -56,10 +57,12 @@ type Client struct { InviteCode *InviteCodeClient // Model is the client for interacting with the Model builders. Model *ModelClient - // Record is the client for interacting with the Record builders. - Record *RecordClient // Setting is the client for interacting with the Setting builders. Setting *SettingClient + // Task is the client for interacting with the Task builders. + Task *TaskClient + // TaskRecord is the client for interacting with the TaskRecord builders. + TaskRecord *TaskRecordClient // User is the client for interacting with the User builders. User *UserClient // UserLoginHistory is the client for interacting with the UserLoginHistory builders. @@ -84,8 +87,9 @@ func (c *Client) init() { c.BillingUsage = NewBillingUsageClient(c.config) c.InviteCode = NewInviteCodeClient(c.config) c.Model = NewModelClient(c.config) - c.Record = NewRecordClient(c.config) c.Setting = NewSettingClient(c.config) + c.Task = NewTaskClient(c.config) + c.TaskRecord = NewTaskRecordClient(c.config) c.User = NewUserClient(c.config) c.UserLoginHistory = NewUserLoginHistoryClient(c.config) } @@ -189,8 +193,9 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { BillingUsage: NewBillingUsageClient(cfg), InviteCode: NewInviteCodeClient(cfg), Model: NewModelClient(cfg), - Record: NewRecordClient(cfg), Setting: NewSettingClient(cfg), + Task: NewTaskClient(cfg), + TaskRecord: NewTaskRecordClient(cfg), User: NewUserClient(cfg), UserLoginHistory: NewUserLoginHistoryClient(cfg), }, nil @@ -221,8 +226,9 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) BillingUsage: NewBillingUsageClient(cfg), InviteCode: NewInviteCodeClient(cfg), Model: NewModelClient(cfg), - Record: NewRecordClient(cfg), Setting: NewSettingClient(cfg), + Task: NewTaskClient(cfg), + TaskRecord: NewTaskRecordClient(cfg), User: NewUserClient(cfg), UserLoginHistory: NewUserLoginHistoryClient(cfg), }, nil @@ -255,8 +261,8 @@ 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.InviteCode, c.Model, c.Record, c.Setting, - c.User, c.UserLoginHistory, + c.BillingRecord, c.BillingUsage, c.InviteCode, c.Model, c.Setting, c.Task, + c.TaskRecord, c.User, c.UserLoginHistory, } { n.Use(hooks...) } @@ -267,8 +273,8 @@ 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.InviteCode, c.Model, c.Record, c.Setting, - c.User, c.UserLoginHistory, + c.BillingRecord, c.BillingUsage, c.InviteCode, c.Model, c.Setting, c.Task, + c.TaskRecord, c.User, c.UserLoginHistory, } { n.Intercept(interceptors...) } @@ -295,10 +301,12 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { return c.InviteCode.mutate(ctx, m) case *ModelMutation: return c.Model.mutate(ctx, m) - case *RecordMutation: - return c.Record.mutate(ctx, m) case *SettingMutation: return c.Setting.mutate(ctx, m) + case *TaskMutation: + return c.Task.mutate(ctx, m) + case *TaskRecordMutation: + return c.TaskRecord.mutate(ctx, m) case *UserMutation: return c.User.mutate(ctx, m) case *UserLoginHistoryMutation: @@ -1516,15 +1524,15 @@ func (c *ModelClient) GetX(ctx context.Context, id uuid.UUID) *Model { return obj } -// QueryRecords queries the records edge of a Model. -func (c *ModelClient) QueryRecords(m *Model) *RecordQuery { - query := (&RecordClient{config: c.config}).Query() +// QueryTasks queries the tasks edge of a Model. +func (c *ModelClient) QueryTasks(m *Model) *TaskQuery { + query := (&TaskClient{config: c.config}).Query() query.path = func(context.Context) (fromV *sql.Selector, _ error) { id := m.ID step := sqlgraph.NewStep( sqlgraph.From(model.Table, model.FieldID, id), - sqlgraph.To(record.Table, record.FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, model.RecordsTable, model.RecordsColumn), + sqlgraph.To(task.Table, task.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, model.TasksTable, model.TasksColumn), ) fromV = sqlgraph.Neighbors(m.driver.Dialect(), step) return fromV, nil @@ -1573,171 +1581,6 @@ func (c *ModelClient) mutate(ctx context.Context, m *ModelMutation) (Value, erro } } -// RecordClient is a client for the Record schema. -type RecordClient struct { - config -} - -// NewRecordClient returns a client for the Record from the given config. -func NewRecordClient(c config) *RecordClient { - return &RecordClient{config: c} -} - -// Use adds a list of mutation hooks to the hooks stack. -// A call to `Use(f, g, h)` equals to `record.Hooks(f(g(h())))`. -func (c *RecordClient) Use(hooks ...Hook) { - c.hooks.Record = append(c.hooks.Record, hooks...) -} - -// Intercept adds a list of query interceptors to the interceptors stack. -// A call to `Intercept(f, g, h)` equals to `record.Intercept(f(g(h())))`. -func (c *RecordClient) Intercept(interceptors ...Interceptor) { - c.inters.Record = append(c.inters.Record, interceptors...) -} - -// Create returns a builder for creating a Record entity. -func (c *RecordClient) Create() *RecordCreate { - mutation := newRecordMutation(c.config, OpCreate) - return &RecordCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// CreateBulk returns a builder for creating a bulk of Record entities. -func (c *RecordClient) CreateBulk(builders ...*RecordCreate) *RecordCreateBulk { - return &RecordCreateBulk{config: c.config, builders: builders} -} - -// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates -// a builder and applies setFunc on it. -func (c *RecordClient) MapCreateBulk(slice any, setFunc func(*RecordCreate, int)) *RecordCreateBulk { - rv := reflect.ValueOf(slice) - if rv.Kind() != reflect.Slice { - return &RecordCreateBulk{err: fmt.Errorf("calling to RecordClient.MapCreateBulk with wrong type %T, need slice", slice)} - } - builders := make([]*RecordCreate, rv.Len()) - for i := 0; i < rv.Len(); i++ { - builders[i] = c.Create() - setFunc(builders[i], i) - } - return &RecordCreateBulk{config: c.config, builders: builders} -} - -// Update returns an update builder for Record. -func (c *RecordClient) Update() *RecordUpdate { - mutation := newRecordMutation(c.config, OpUpdate) - return &RecordUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOne returns an update builder for the given entity. -func (c *RecordClient) UpdateOne(r *Record) *RecordUpdateOne { - mutation := newRecordMutation(c.config, OpUpdateOne, withRecord(r)) - return &RecordUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOneID returns an update builder for the given id. -func (c *RecordClient) UpdateOneID(id uuid.UUID) *RecordUpdateOne { - mutation := newRecordMutation(c.config, OpUpdateOne, withRecordID(id)) - return &RecordUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// Delete returns a delete builder for Record. -func (c *RecordClient) Delete() *RecordDelete { - mutation := newRecordMutation(c.config, OpDelete) - return &RecordDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// DeleteOne returns a builder for deleting the given entity. -func (c *RecordClient) DeleteOne(r *Record) *RecordDeleteOne { - return c.DeleteOneID(r.ID) -} - -// DeleteOneID returns a builder for deleting the given entity by its id. -func (c *RecordClient) DeleteOneID(id uuid.UUID) *RecordDeleteOne { - builder := c.Delete().Where(record.ID(id)) - builder.mutation.id = &id - builder.mutation.op = OpDeleteOne - return &RecordDeleteOne{builder} -} - -// Query returns a query builder for Record. -func (c *RecordClient) Query() *RecordQuery { - return &RecordQuery{ - config: c.config, - ctx: &QueryContext{Type: TypeRecord}, - inters: c.Interceptors(), - } -} - -// Get returns a Record entity by its id. -func (c *RecordClient) Get(ctx context.Context, id uuid.UUID) (*Record, error) { - return c.Query().Where(record.ID(id)).Only(ctx) -} - -// GetX is like Get, but panics if an error occurs. -func (c *RecordClient) GetX(ctx context.Context, id uuid.UUID) *Record { - obj, err := c.Get(ctx, id) - if err != nil { - panic(err) - } - return obj -} - -// QueryUser queries the user edge of a Record. -func (c *RecordClient) QueryUser(r *Record) *UserQuery { - query := (&UserClient{config: c.config}).Query() - query.path = func(context.Context) (fromV *sql.Selector, _ error) { - id := r.ID - step := sqlgraph.NewStep( - sqlgraph.From(record.Table, record.FieldID, id), - sqlgraph.To(user.Table, user.FieldID), - sqlgraph.Edge(sqlgraph.M2O, true, record.UserTable, record.UserColumn), - ) - fromV = sqlgraph.Neighbors(r.driver.Dialect(), step) - return fromV, nil - } - return query -} - -// QueryModel queries the model edge of a Record. -func (c *RecordClient) QueryModel(r *Record) *ModelQuery { - query := (&ModelClient{config: c.config}).Query() - query.path = func(context.Context) (fromV *sql.Selector, _ error) { - id := r.ID - step := sqlgraph.NewStep( - sqlgraph.From(record.Table, record.FieldID, id), - sqlgraph.To(model.Table, model.FieldID), - sqlgraph.Edge(sqlgraph.M2O, true, record.ModelTable, record.ModelColumn), - ) - fromV = sqlgraph.Neighbors(r.driver.Dialect(), step) - return fromV, nil - } - return query -} - -// Hooks returns the client hooks. -func (c *RecordClient) Hooks() []Hook { - return c.hooks.Record -} - -// Interceptors returns the client interceptors. -func (c *RecordClient) Interceptors() []Interceptor { - return c.inters.Record -} - -func (c *RecordClient) mutate(ctx context.Context, m *RecordMutation) (Value, error) { - switch m.Op() { - case OpCreate: - return (&RecordCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpUpdate: - return (&RecordUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpUpdateOne: - return (&RecordUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpDelete, OpDeleteOne: - return (&RecordDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) - default: - return nil, fmt.Errorf("db: unknown Record mutation op: %q", m.Op()) - } -} - // SettingClient is a client for the Setting schema. type SettingClient struct { config @@ -1871,6 +1714,336 @@ func (c *SettingClient) mutate(ctx context.Context, m *SettingMutation) (Value, } } +// TaskClient is a client for the Task schema. +type TaskClient struct { + config +} + +// NewTaskClient returns a client for the Task from the given config. +func NewTaskClient(c config) *TaskClient { + return &TaskClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `task.Hooks(f(g(h())))`. +func (c *TaskClient) Use(hooks ...Hook) { + c.hooks.Task = append(c.hooks.Task, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `task.Intercept(f(g(h())))`. +func (c *TaskClient) Intercept(interceptors ...Interceptor) { + c.inters.Task = append(c.inters.Task, interceptors...) +} + +// Create returns a builder for creating a Task entity. +func (c *TaskClient) Create() *TaskCreate { + mutation := newTaskMutation(c.config, OpCreate) + return &TaskCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Task entities. +func (c *TaskClient) CreateBulk(builders ...*TaskCreate) *TaskCreateBulk { + return &TaskCreateBulk{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 *TaskClient) MapCreateBulk(slice any, setFunc func(*TaskCreate, int)) *TaskCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &TaskCreateBulk{err: fmt.Errorf("calling to TaskClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*TaskCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &TaskCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Task. +func (c *TaskClient) Update() *TaskUpdate { + mutation := newTaskMutation(c.config, OpUpdate) + return &TaskUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *TaskClient) UpdateOne(t *Task) *TaskUpdateOne { + mutation := newTaskMutation(c.config, OpUpdateOne, withTask(t)) + return &TaskUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *TaskClient) UpdateOneID(id uuid.UUID) *TaskUpdateOne { + mutation := newTaskMutation(c.config, OpUpdateOne, withTaskID(id)) + return &TaskUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Task. +func (c *TaskClient) Delete() *TaskDelete { + mutation := newTaskMutation(c.config, OpDelete) + return &TaskDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *TaskClient) DeleteOne(t *Task) *TaskDeleteOne { + return c.DeleteOneID(t.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *TaskClient) DeleteOneID(id uuid.UUID) *TaskDeleteOne { + builder := c.Delete().Where(task.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &TaskDeleteOne{builder} +} + +// Query returns a query builder for Task. +func (c *TaskClient) Query() *TaskQuery { + return &TaskQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeTask}, + inters: c.Interceptors(), + } +} + +// Get returns a Task entity by its id. +func (c *TaskClient) Get(ctx context.Context, id uuid.UUID) (*Task, error) { + return c.Query().Where(task.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *TaskClient) GetX(ctx context.Context, id uuid.UUID) *Task { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryTaskRecords queries the task_records edge of a Task. +func (c *TaskClient) QueryTaskRecords(t *Task) *TaskRecordQuery { + query := (&TaskRecordClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := t.ID + step := sqlgraph.NewStep( + sqlgraph.From(task.Table, task.FieldID, id), + sqlgraph.To(taskrecord.Table, taskrecord.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, task.TaskRecordsTable, task.TaskRecordsColumn), + ) + fromV = sqlgraph.Neighbors(t.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryUser queries the user edge of a Task. +func (c *TaskClient) QueryUser(t *Task) *UserQuery { + query := (&UserClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := t.ID + step := sqlgraph.NewStep( + sqlgraph.From(task.Table, task.FieldID, id), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, task.UserTable, task.UserColumn), + ) + fromV = sqlgraph.Neighbors(t.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryModel queries the model edge of a Task. +func (c *TaskClient) QueryModel(t *Task) *ModelQuery { + query := (&ModelClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := t.ID + step := sqlgraph.NewStep( + sqlgraph.From(task.Table, task.FieldID, id), + sqlgraph.To(model.Table, model.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, task.ModelTable, task.ModelColumn), + ) + fromV = sqlgraph.Neighbors(t.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *TaskClient) Hooks() []Hook { + return c.hooks.Task +} + +// Interceptors returns the client interceptors. +func (c *TaskClient) Interceptors() []Interceptor { + return c.inters.Task +} + +func (c *TaskClient) mutate(ctx context.Context, m *TaskMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&TaskCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&TaskUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&TaskUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&TaskDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown Task mutation op: %q", m.Op()) + } +} + +// TaskRecordClient is a client for the TaskRecord schema. +type TaskRecordClient struct { + config +} + +// NewTaskRecordClient returns a client for the TaskRecord from the given config. +func NewTaskRecordClient(c config) *TaskRecordClient { + return &TaskRecordClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `taskrecord.Hooks(f(g(h())))`. +func (c *TaskRecordClient) Use(hooks ...Hook) { + c.hooks.TaskRecord = append(c.hooks.TaskRecord, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `taskrecord.Intercept(f(g(h())))`. +func (c *TaskRecordClient) Intercept(interceptors ...Interceptor) { + c.inters.TaskRecord = append(c.inters.TaskRecord, interceptors...) +} + +// Create returns a builder for creating a TaskRecord entity. +func (c *TaskRecordClient) Create() *TaskRecordCreate { + mutation := newTaskRecordMutation(c.config, OpCreate) + return &TaskRecordCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of TaskRecord entities. +func (c *TaskRecordClient) CreateBulk(builders ...*TaskRecordCreate) *TaskRecordCreateBulk { + return &TaskRecordCreateBulk{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 *TaskRecordClient) MapCreateBulk(slice any, setFunc func(*TaskRecordCreate, int)) *TaskRecordCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &TaskRecordCreateBulk{err: fmt.Errorf("calling to TaskRecordClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*TaskRecordCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &TaskRecordCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for TaskRecord. +func (c *TaskRecordClient) Update() *TaskRecordUpdate { + mutation := newTaskRecordMutation(c.config, OpUpdate) + return &TaskRecordUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *TaskRecordClient) UpdateOne(tr *TaskRecord) *TaskRecordUpdateOne { + mutation := newTaskRecordMutation(c.config, OpUpdateOne, withTaskRecord(tr)) + return &TaskRecordUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *TaskRecordClient) UpdateOneID(id uuid.UUID) *TaskRecordUpdateOne { + mutation := newTaskRecordMutation(c.config, OpUpdateOne, withTaskRecordID(id)) + return &TaskRecordUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for TaskRecord. +func (c *TaskRecordClient) Delete() *TaskRecordDelete { + mutation := newTaskRecordMutation(c.config, OpDelete) + return &TaskRecordDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *TaskRecordClient) DeleteOne(tr *TaskRecord) *TaskRecordDeleteOne { + return c.DeleteOneID(tr.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *TaskRecordClient) DeleteOneID(id uuid.UUID) *TaskRecordDeleteOne { + builder := c.Delete().Where(taskrecord.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &TaskRecordDeleteOne{builder} +} + +// Query returns a query builder for TaskRecord. +func (c *TaskRecordClient) Query() *TaskRecordQuery { + return &TaskRecordQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeTaskRecord}, + inters: c.Interceptors(), + } +} + +// Get returns a TaskRecord entity by its id. +func (c *TaskRecordClient) Get(ctx context.Context, id uuid.UUID) (*TaskRecord, error) { + return c.Query().Where(taskrecord.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *TaskRecordClient) GetX(ctx context.Context, id uuid.UUID) *TaskRecord { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryTask queries the task edge of a TaskRecord. +func (c *TaskRecordClient) QueryTask(tr *TaskRecord) *TaskQuery { + query := (&TaskClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := tr.ID + step := sqlgraph.NewStep( + sqlgraph.From(taskrecord.Table, taskrecord.FieldID, id), + sqlgraph.To(task.Table, task.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, taskrecord.TaskTable, taskrecord.TaskColumn), + ) + fromV = sqlgraph.Neighbors(tr.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *TaskRecordClient) Hooks() []Hook { + return c.hooks.TaskRecord +} + +// Interceptors returns the client interceptors. +func (c *TaskRecordClient) Interceptors() []Interceptor { + return c.inters.TaskRecord +} + +func (c *TaskRecordClient) mutate(ctx context.Context, m *TaskRecordMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&TaskRecordCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&TaskRecordUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&TaskRecordUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&TaskRecordDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown TaskRecord mutation op: %q", m.Op()) + } +} + // UserClient is a client for the User schema. type UserClient struct { config @@ -1979,22 +2152,6 @@ func (c *UserClient) GetX(ctx context.Context, id uuid.UUID) *User { return obj } -// QueryRecords queries the records edge of a User. -func (c *UserClient) QueryRecords(u *User) *RecordQuery { - query := (&RecordClient{config: c.config}).Query() - query.path = func(context.Context) (fromV *sql.Selector, _ error) { - id := u.ID - step := sqlgraph.NewStep( - sqlgraph.From(user.Table, user.FieldID, id), - sqlgraph.To(record.Table, record.FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, user.RecordsTable, user.RecordsColumn), - ) - fromV = sqlgraph.Neighbors(u.driver.Dialect(), step) - return fromV, nil - } - return query -} - // QueryLoginHistories queries the login_histories edge of a User. func (c *UserClient) QueryLoginHistories(u *User) *UserLoginHistoryQuery { query := (&UserLoginHistoryClient{config: c.config}).Query() @@ -2027,6 +2184,22 @@ func (c *UserClient) QueryModels(u *User) *ModelQuery { return query } +// QueryTasks queries the tasks edge of a User. +func (c *UserClient) QueryTasks(u *User) *TaskQuery { + query := (&TaskClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := u.ID + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, id), + sqlgraph.To(task.Table, task.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, user.TasksTable, user.TasksColumn), + ) + fromV = sqlgraph.Neighbors(u.driver.Dialect(), step) + return fromV, nil + } + return query +} + // Hooks returns the client hooks. func (c *UserClient) Hooks() []Hook { return c.hooks.User @@ -2205,12 +2378,12 @@ func (c *UserLoginHistoryClient) mutate(ctx context.Context, m *UserLoginHistory type ( hooks struct { Admin, AdminLoginHistory, ApiKey, BillingPlan, BillingQuota, BillingRecord, - BillingUsage, InviteCode, Model, Record, Setting, User, + BillingUsage, InviteCode, Model, Setting, Task, TaskRecord, User, UserLoginHistory []ent.Hook } inters struct { Admin, AdminLoginHistory, ApiKey, BillingPlan, BillingQuota, BillingRecord, - BillingUsage, InviteCode, Model, Record, Setting, User, + BillingUsage, InviteCode, Model, Setting, Task, TaskRecord, User, UserLoginHistory []ent.Interceptor } ) diff --git a/backend/db/ent.go b/backend/db/ent.go index d8ec291..292f941 100644 --- a/backend/db/ent.go +++ b/backend/db/ent.go @@ -21,8 +21,9 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/billingusage" "github.com/chaitin/MonkeyCode/backend/db/invitecode" "github.com/chaitin/MonkeyCode/backend/db/model" - "github.com/chaitin/MonkeyCode/backend/db/record" "github.com/chaitin/MonkeyCode/backend/db/setting" + "github.com/chaitin/MonkeyCode/backend/db/task" + "github.com/chaitin/MonkeyCode/backend/db/taskrecord" "github.com/chaitin/MonkeyCode/backend/db/user" "github.com/chaitin/MonkeyCode/backend/db/userloginhistory" ) @@ -94,8 +95,9 @@ func checkColumn(table, column string) error { billingusage.Table: billingusage.ValidColumn, invitecode.Table: invitecode.ValidColumn, model.Table: model.ValidColumn, - record.Table: record.ValidColumn, setting.Table: setting.ValidColumn, + task.Table: task.ValidColumn, + taskrecord.Table: taskrecord.ValidColumn, user.Table: user.ValidColumn, userloginhistory.Table: userloginhistory.ValidColumn, }) diff --git a/backend/db/hook/hook.go b/backend/db/hook/hook.go index 92d1829..f9630e1 100644 --- a/backend/db/hook/hook.go +++ b/backend/db/hook/hook.go @@ -117,18 +117,6 @@ func (f ModelFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) return nil, fmt.Errorf("unexpected mutation type %T. expect *db.ModelMutation", m) } -// The RecordFunc type is an adapter to allow the use of ordinary -// function as Record mutator. -type RecordFunc func(context.Context, *db.RecordMutation) (db.Value, error) - -// Mutate calls f(ctx, m). -func (f RecordFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { - if mv, ok := m.(*db.RecordMutation); ok { - return f(ctx, mv) - } - return nil, fmt.Errorf("unexpected mutation type %T. expect *db.RecordMutation", m) -} - // The SettingFunc type is an adapter to allow the use of ordinary // function as Setting mutator. type SettingFunc func(context.Context, *db.SettingMutation) (db.Value, error) @@ -141,6 +129,30 @@ func (f SettingFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error return nil, fmt.Errorf("unexpected mutation type %T. expect *db.SettingMutation", m) } +// The TaskFunc type is an adapter to allow the use of ordinary +// function as Task mutator. +type TaskFunc func(context.Context, *db.TaskMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f TaskFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.TaskMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.TaskMutation", m) +} + +// The TaskRecordFunc type is an adapter to allow the use of ordinary +// function as TaskRecord mutator. +type TaskRecordFunc func(context.Context, *db.TaskRecordMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f TaskRecordFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.TaskRecordMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.TaskRecordMutation", m) +} + // The UserFunc type is an adapter to allow the use of ordinary // function as User mutator. type UserFunc func(context.Context, *db.UserMutation) (db.Value, error) diff --git a/backend/db/intercept/intercept.go b/backend/db/intercept/intercept.go index 925b277..d9c7d69 100644 --- a/backend/db/intercept/intercept.go +++ b/backend/db/intercept/intercept.go @@ -18,8 +18,9 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/invitecode" "github.com/chaitin/MonkeyCode/backend/db/model" "github.com/chaitin/MonkeyCode/backend/db/predicate" - "github.com/chaitin/MonkeyCode/backend/db/record" "github.com/chaitin/MonkeyCode/backend/db/setting" + "github.com/chaitin/MonkeyCode/backend/db/task" + "github.com/chaitin/MonkeyCode/backend/db/taskrecord" "github.com/chaitin/MonkeyCode/backend/db/user" "github.com/chaitin/MonkeyCode/backend/db/userloginhistory" ) @@ -323,33 +324,6 @@ func (f TraverseModel) Traverse(ctx context.Context, q db.Query) error { return fmt.Errorf("unexpected query type %T. expect *db.ModelQuery", q) } -// The RecordFunc type is an adapter to allow the use of ordinary function as a Querier. -type RecordFunc func(context.Context, *db.RecordQuery) (db.Value, error) - -// Query calls f(ctx, q). -func (f RecordFunc) Query(ctx context.Context, q db.Query) (db.Value, error) { - if q, ok := q.(*db.RecordQuery); ok { - return f(ctx, q) - } - return nil, fmt.Errorf("unexpected query type %T. expect *db.RecordQuery", q) -} - -// The TraverseRecord type is an adapter to allow the use of ordinary function as Traverser. -type TraverseRecord func(context.Context, *db.RecordQuery) error - -// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline. -func (f TraverseRecord) Intercept(next db.Querier) db.Querier { - return next -} - -// Traverse calls f(ctx, q). -func (f TraverseRecord) Traverse(ctx context.Context, q db.Query) error { - if q, ok := q.(*db.RecordQuery); ok { - return f(ctx, q) - } - return fmt.Errorf("unexpected query type %T. expect *db.RecordQuery", q) -} - // The SettingFunc type is an adapter to allow the use of ordinary function as a Querier. type SettingFunc func(context.Context, *db.SettingQuery) (db.Value, error) @@ -377,6 +351,60 @@ func (f TraverseSetting) Traverse(ctx context.Context, q db.Query) error { return fmt.Errorf("unexpected query type %T. expect *db.SettingQuery", q) } +// The TaskFunc type is an adapter to allow the use of ordinary function as a Querier. +type TaskFunc func(context.Context, *db.TaskQuery) (db.Value, error) + +// Query calls f(ctx, q). +func (f TaskFunc) Query(ctx context.Context, q db.Query) (db.Value, error) { + if q, ok := q.(*db.TaskQuery); ok { + return f(ctx, q) + } + return nil, fmt.Errorf("unexpected query type %T. expect *db.TaskQuery", q) +} + +// The TraverseTask type is an adapter to allow the use of ordinary function as Traverser. +type TraverseTask func(context.Context, *db.TaskQuery) error + +// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline. +func (f TraverseTask) Intercept(next db.Querier) db.Querier { + return next +} + +// Traverse calls f(ctx, q). +func (f TraverseTask) Traverse(ctx context.Context, q db.Query) error { + if q, ok := q.(*db.TaskQuery); ok { + return f(ctx, q) + } + return fmt.Errorf("unexpected query type %T. expect *db.TaskQuery", q) +} + +// The TaskRecordFunc type is an adapter to allow the use of ordinary function as a Querier. +type TaskRecordFunc func(context.Context, *db.TaskRecordQuery) (db.Value, error) + +// Query calls f(ctx, q). +func (f TaskRecordFunc) Query(ctx context.Context, q db.Query) (db.Value, error) { + if q, ok := q.(*db.TaskRecordQuery); ok { + return f(ctx, q) + } + return nil, fmt.Errorf("unexpected query type %T. expect *db.TaskRecordQuery", q) +} + +// The TraverseTaskRecord type is an adapter to allow the use of ordinary function as Traverser. +type TraverseTaskRecord func(context.Context, *db.TaskRecordQuery) error + +// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline. +func (f TraverseTaskRecord) Intercept(next db.Querier) db.Querier { + return next +} + +// Traverse calls f(ctx, q). +func (f TraverseTaskRecord) Traverse(ctx context.Context, q db.Query) error { + if q, ok := q.(*db.TaskRecordQuery); ok { + return f(ctx, q) + } + return fmt.Errorf("unexpected query type %T. expect *db.TaskRecordQuery", q) +} + // The UserFunc type is an adapter to allow the use of ordinary function as a Querier. type UserFunc func(context.Context, *db.UserQuery) (db.Value, error) @@ -452,10 +480,12 @@ func NewQuery(q db.Query) (Query, error) { return &query[*db.InviteCodeQuery, predicate.InviteCode, invitecode.OrderOption]{typ: db.TypeInviteCode, tq: q}, nil case *db.ModelQuery: return &query[*db.ModelQuery, predicate.Model, model.OrderOption]{typ: db.TypeModel, tq: q}, nil - case *db.RecordQuery: - return &query[*db.RecordQuery, predicate.Record, record.OrderOption]{typ: db.TypeRecord, tq: q}, nil case *db.SettingQuery: return &query[*db.SettingQuery, predicate.Setting, setting.OrderOption]{typ: db.TypeSetting, tq: q}, nil + case *db.TaskQuery: + return &query[*db.TaskQuery, predicate.Task, task.OrderOption]{typ: db.TypeTask, tq: q}, nil + case *db.TaskRecordQuery: + return &query[*db.TaskRecordQuery, predicate.TaskRecord, taskrecord.OrderOption]{typ: db.TypeTaskRecord, tq: q}, nil case *db.UserQuery: return &query[*db.UserQuery, predicate.User, user.OrderOption]{typ: db.TypeUser, tq: q}, nil case *db.UserLoginHistoryQuery: diff --git a/backend/db/migrate/schema.go b/backend/db/migrate/schema.go index 42e5bb9..373a0d0 100644 --- a/backend/db/migrate/schema.go +++ b/backend/db/migrate/schema.go @@ -185,44 +185,6 @@ var ( }, }, } - // RecordsColumns holds the columns for the "records" table. - RecordsColumns = []*schema.Column{ - {Name: "id", Type: field.TypeUUID}, - {Name: "task_id", Type: field.TypeString}, - {Name: "model_type", Type: field.TypeString, Nullable: true}, - {Name: "prompt", Type: field.TypeString, Nullable: true}, - {Name: "completion", Type: field.TypeString, Nullable: true}, - {Name: "is_accept", Type: field.TypeBool, Default: false}, - {Name: "program_language", Type: field.TypeString, Nullable: true}, - {Name: "work_mode", Type: field.TypeString, Nullable: true}, - {Name: "code_lines", Type: field.TypeInt64, Nullable: true}, - {Name: "input_tokens", Type: field.TypeInt64}, - {Name: "output_tokens", Type: field.TypeInt64}, - {Name: "created_at", Type: field.TypeTime}, - {Name: "updated_at", Type: field.TypeTime}, - {Name: "model_id", Type: field.TypeUUID, Nullable: true}, - {Name: "user_id", Type: field.TypeUUID, Nullable: true}, - } - // RecordsTable holds the schema information for the "records" table. - RecordsTable = &schema.Table{ - Name: "records", - Columns: RecordsColumns, - PrimaryKey: []*schema.Column{RecordsColumns[0]}, - ForeignKeys: []*schema.ForeignKey{ - { - Symbol: "records_models_records", - Columns: []*schema.Column{RecordsColumns[13]}, - RefColumns: []*schema.Column{ModelsColumns[0]}, - OnDelete: schema.SetNull, - }, - { - Symbol: "records_users_records", - Columns: []*schema.Column{RecordsColumns[14]}, - RefColumns: []*schema.Column{UsersColumns[0]}, - OnDelete: schema.SetNull, - }, - }, - } // SettingsColumns holds the columns for the "settings" table. SettingsColumns = []*schema.Column{ {Name: "id", Type: field.TypeUUID}, @@ -238,6 +200,68 @@ var ( Columns: SettingsColumns, PrimaryKey: []*schema.Column{SettingsColumns[0]}, } + // TasksColumns holds the columns for the "tasks" table. + TasksColumns = []*schema.Column{ + {Name: "id", Type: field.TypeUUID}, + {Name: "task_id", Type: field.TypeString, Unique: true}, + {Name: "request_id", Type: field.TypeString, Nullable: true}, + {Name: "model_type", Type: field.TypeString}, + {Name: "prompt", Type: field.TypeString, Nullable: true}, + {Name: "is_accept", Type: field.TypeBool, Default: false}, + {Name: "program_language", Type: field.TypeString, Nullable: true}, + {Name: "work_mode", Type: field.TypeString, Nullable: true}, + {Name: "completion", Type: field.TypeString, Nullable: true}, + {Name: "code_lines", Type: field.TypeInt64, Nullable: true}, + {Name: "input_tokens", Type: field.TypeInt64, Nullable: true}, + {Name: "output_tokens", Type: field.TypeInt64, Nullable: true}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "model_id", Type: field.TypeUUID, Nullable: true}, + {Name: "user_id", Type: field.TypeUUID, Nullable: true}, + } + // TasksTable holds the schema information for the "tasks" table. + TasksTable = &schema.Table{ + Name: "tasks", + Columns: TasksColumns, + PrimaryKey: []*schema.Column{TasksColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "tasks_models_tasks", + Columns: []*schema.Column{TasksColumns[14]}, + RefColumns: []*schema.Column{ModelsColumns[0]}, + OnDelete: schema.SetNull, + }, + { + Symbol: "tasks_users_tasks", + Columns: []*schema.Column{TasksColumns[15]}, + RefColumns: []*schema.Column{UsersColumns[0]}, + OnDelete: schema.SetNull, + }, + }, + } + // TaskRecordsColumns holds the columns for the "task_records" table. + TaskRecordsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeUUID, Unique: true}, + {Name: "completion", Type: field.TypeString}, + {Name: "output_tokens", Type: field.TypeInt64}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "task_id", Type: field.TypeUUID, Nullable: true}, + } + // TaskRecordsTable holds the schema information for the "task_records" table. + TaskRecordsTable = &schema.Table{ + Name: "task_records", + Columns: TaskRecordsColumns, + PrimaryKey: []*schema.Column{TaskRecordsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "task_records_tasks_task_records", + Columns: []*schema.Column{TaskRecordsColumns[5]}, + RefColumns: []*schema.Column{TasksColumns[0]}, + OnDelete: schema.SetNull, + }, + }, + } // UsersColumns holds the columns for the "users" table. UsersColumns = []*schema.Column{ {Name: "id", Type: field.TypeUUID}, @@ -294,8 +318,9 @@ var ( BillingUsagesTable, InviteCodesTable, ModelsTable, - RecordsTable, SettingsTable, + TasksTable, + TaskRecordsTable, UsersTable, UserLoginHistoriesTable, } @@ -331,14 +356,18 @@ func init() { ModelsTable.Annotation = &entsql.Annotation{ Table: "models", } - RecordsTable.ForeignKeys[0].RefTable = ModelsTable - RecordsTable.ForeignKeys[1].RefTable = UsersTable - RecordsTable.Annotation = &entsql.Annotation{ - Table: "records", - } SettingsTable.Annotation = &entsql.Annotation{ Table: "settings", } + TasksTable.ForeignKeys[0].RefTable = ModelsTable + TasksTable.ForeignKeys[1].RefTable = UsersTable + TasksTable.Annotation = &entsql.Annotation{ + Table: "tasks", + } + TaskRecordsTable.ForeignKeys[0].RefTable = TasksTable + TaskRecordsTable.Annotation = &entsql.Annotation{ + Table: "task_records", + } UsersTable.Annotation = &entsql.Annotation{ Table: "users", } diff --git a/backend/db/model.go b/backend/db/model.go index a25d520..a63a297 100644 --- a/backend/db/model.go +++ b/backend/db/model.go @@ -52,8 +52,8 @@ type Model struct { // ModelEdges holds the relations/edges for other nodes in the graph. type ModelEdges struct { - // Records holds the value of the records edge. - Records []*Record `json:"records,omitempty"` + // Tasks holds the value of the tasks edge. + Tasks []*Task `json:"tasks,omitempty"` // User holds the value of the user edge. User *User `json:"user,omitempty"` // loadedTypes holds the information for reporting if a @@ -61,13 +61,13 @@ type ModelEdges struct { loadedTypes [2]bool } -// RecordsOrErr returns the Records value or an error if the edge +// TasksOrErr returns the Tasks value or an error if the edge // was not loaded in eager-loading. -func (e ModelEdges) RecordsOrErr() ([]*Record, error) { +func (e ModelEdges) TasksOrErr() ([]*Task, error) { if e.loadedTypes[0] { - return e.Records, nil + return e.Tasks, nil } - return nil, &NotLoadedError{edge: "records"} + return nil, &NotLoadedError{edge: "tasks"} } // UserOrErr returns the User value or an error if the edge @@ -200,9 +200,9 @@ func (m *Model) Value(name string) (ent.Value, error) { return m.selectValues.Get(name) } -// QueryRecords queries the "records" edge of the Model entity. -func (m *Model) QueryRecords() *RecordQuery { - return NewModelClient(m.config).QueryRecords(m) +// QueryTasks queries the "tasks" edge of the Model entity. +func (m *Model) QueryTasks() *TaskQuery { + return NewModelClient(m.config).QueryTasks(m) } // QueryUser queries the "user" edge of the Model entity. diff --git a/backend/db/model/model.go b/backend/db/model/model.go index 5aa0e14..c1b6957 100644 --- a/backend/db/model/model.go +++ b/backend/db/model/model.go @@ -39,19 +39,19 @@ const ( FieldCreatedAt = "created_at" // FieldUpdatedAt holds the string denoting the updated_at field in the database. FieldUpdatedAt = "updated_at" - // EdgeRecords holds the string denoting the records edge name in mutations. - EdgeRecords = "records" + // EdgeTasks holds the string denoting the tasks edge name in mutations. + EdgeTasks = "tasks" // EdgeUser holds the string denoting the user edge name in mutations. EdgeUser = "user" // Table holds the table name of the model in the database. Table = "models" - // RecordsTable is the table that holds the records relation/edge. - RecordsTable = "records" - // RecordsInverseTable is the table name for the Record entity. - // It exists in this package in order to avoid circular dependency with the "record" package. - RecordsInverseTable = "records" - // RecordsColumn is the table column denoting the records relation/edge. - RecordsColumn = "model_id" + // TasksTable is the table that holds the tasks relation/edge. + TasksTable = "tasks" + // TasksInverseTable is the table name for the Task entity. + // It exists in this package in order to avoid circular dependency with the "task" package. + TasksInverseTable = "tasks" + // TasksColumn is the table column denoting the tasks relation/edge. + TasksColumn = "model_id" // UserTable is the table that holds the user relation/edge. UserTable = "models" // UserInverseTable is the table name for the User entity. @@ -167,17 +167,17 @@ func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc() } -// ByRecordsCount orders the results by records count. -func ByRecordsCount(opts ...sql.OrderTermOption) OrderOption { +// ByTasksCount orders the results by tasks count. +func ByTasksCount(opts ...sql.OrderTermOption) OrderOption { return func(s *sql.Selector) { - sqlgraph.OrderByNeighborsCount(s, newRecordsStep(), opts...) + sqlgraph.OrderByNeighborsCount(s, newTasksStep(), opts...) } } -// ByRecords orders the results by records terms. -func ByRecords(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { +// ByTasks orders the results by tasks terms. +func ByTasks(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { return func(s *sql.Selector) { - sqlgraph.OrderByNeighborTerms(s, newRecordsStep(), append([]sql.OrderTerm{term}, terms...)...) + sqlgraph.OrderByNeighborTerms(s, newTasksStep(), append([]sql.OrderTerm{term}, terms...)...) } } @@ -187,11 +187,11 @@ func ByUserField(field string, opts ...sql.OrderTermOption) OrderOption { sqlgraph.OrderByNeighborTerms(s, newUserStep(), sql.OrderByField(field, opts...)) } } -func newRecordsStep() *sqlgraph.Step { +func newTasksStep() *sqlgraph.Step { return sqlgraph.NewStep( sqlgraph.From(Table, FieldID), - sqlgraph.To(RecordsInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, RecordsTable, RecordsColumn), + sqlgraph.To(TasksInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, TasksTable, TasksColumn), ) } func newUserStep() *sqlgraph.Step { diff --git a/backend/db/model/where.go b/backend/db/model/where.go index 17d222d..ca7d76a 100644 --- a/backend/db/model/where.go +++ b/backend/db/model/where.go @@ -857,21 +857,21 @@ func UpdatedAtLTE(v time.Time) predicate.Model { return predicate.Model(sql.FieldLTE(FieldUpdatedAt, v)) } -// HasRecords applies the HasEdge predicate on the "records" edge. -func HasRecords() predicate.Model { +// HasTasks applies the HasEdge predicate on the "tasks" edge. +func HasTasks() predicate.Model { return predicate.Model(func(s *sql.Selector) { step := sqlgraph.NewStep( sqlgraph.From(Table, FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, RecordsTable, RecordsColumn), + sqlgraph.Edge(sqlgraph.O2M, false, TasksTable, TasksColumn), ) sqlgraph.HasNeighbors(s, step) }) } -// HasRecordsWith applies the HasEdge predicate on the "records" edge with a given conditions (other predicates). -func HasRecordsWith(preds ...predicate.Record) predicate.Model { +// HasTasksWith applies the HasEdge predicate on the "tasks" edge with a given conditions (other predicates). +func HasTasksWith(preds ...predicate.Task) predicate.Model { return predicate.Model(func(s *sql.Selector) { - step := newRecordsStep() + step := newTasksStep() sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { for _, p := range preds { p(s) diff --git a/backend/db/model_create.go b/backend/db/model_create.go index 035b6e8..e36a0a5 100644 --- a/backend/db/model_create.go +++ b/backend/db/model_create.go @@ -14,7 +14,7 @@ import ( "entgo.io/ent/schema/field" "github.com/chaitin/MonkeyCode/backend/consts" "github.com/chaitin/MonkeyCode/backend/db/model" - "github.com/chaitin/MonkeyCode/backend/db/record" + "github.com/chaitin/MonkeyCode/backend/db/task" "github.com/chaitin/MonkeyCode/backend/db/user" "github.com/google/uuid" ) @@ -161,19 +161,19 @@ func (mc *ModelCreate) SetID(u uuid.UUID) *ModelCreate { return mc } -// AddRecordIDs adds the "records" edge to the Record entity by IDs. -func (mc *ModelCreate) AddRecordIDs(ids ...uuid.UUID) *ModelCreate { - mc.mutation.AddRecordIDs(ids...) +// AddTaskIDs adds the "tasks" edge to the Task entity by IDs. +func (mc *ModelCreate) AddTaskIDs(ids ...uuid.UUID) *ModelCreate { + mc.mutation.AddTaskIDs(ids...) return mc } -// AddRecords adds the "records" edges to the Record entity. -func (mc *ModelCreate) AddRecords(r ...*Record) *ModelCreate { - ids := make([]uuid.UUID, len(r)) - for i := range r { - ids[i] = r[i].ID +// AddTasks adds the "tasks" edges to the Task entity. +func (mc *ModelCreate) AddTasks(t ...*Task) *ModelCreate { + ids := make([]uuid.UUID, len(t)) + for i := range t { + ids[i] = t[i].ID } - return mc.AddRecordIDs(ids...) + return mc.AddTaskIDs(ids...) } // SetUser sets the "user" edge to the User entity. @@ -336,15 +336,15 @@ func (mc *ModelCreate) createSpec() (*Model, *sqlgraph.CreateSpec) { _spec.SetField(model.FieldUpdatedAt, field.TypeTime, value) _node.UpdatedAt = value } - if nodes := mc.mutation.RecordsIDs(); len(nodes) > 0 { + if nodes := mc.mutation.TasksIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, Inverse: false, - Table: model.RecordsTable, - Columns: []string{model.RecordsColumn}, + Table: model.TasksTable, + Columns: []string{model.TasksColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(record.FieldID, field.TypeUUID), + IDSpec: sqlgraph.NewFieldSpec(task.FieldID, field.TypeUUID), }, } for _, k := range nodes { diff --git a/backend/db/model_query.go b/backend/db/model_query.go index e28cb33..b489501 100644 --- a/backend/db/model_query.go +++ b/backend/db/model_query.go @@ -15,7 +15,7 @@ import ( "entgo.io/ent/schema/field" "github.com/chaitin/MonkeyCode/backend/db/model" "github.com/chaitin/MonkeyCode/backend/db/predicate" - "github.com/chaitin/MonkeyCode/backend/db/record" + "github.com/chaitin/MonkeyCode/backend/db/task" "github.com/chaitin/MonkeyCode/backend/db/user" "github.com/google/uuid" ) @@ -23,13 +23,13 @@ import ( // ModelQuery is the builder for querying Model entities. type ModelQuery struct { config - ctx *QueryContext - order []model.OrderOption - inters []Interceptor - predicates []predicate.Model - withRecords *RecordQuery - withUser *UserQuery - modifiers []func(*sql.Selector) + ctx *QueryContext + order []model.OrderOption + inters []Interceptor + predicates []predicate.Model + withTasks *TaskQuery + withUser *UserQuery + modifiers []func(*sql.Selector) // intermediate query (i.e. traversal path). sql *sql.Selector path func(context.Context) (*sql.Selector, error) @@ -66,9 +66,9 @@ func (mq *ModelQuery) Order(o ...model.OrderOption) *ModelQuery { return mq } -// QueryRecords chains the current query on the "records" edge. -func (mq *ModelQuery) QueryRecords() *RecordQuery { - query := (&RecordClient{config: mq.config}).Query() +// QueryTasks chains the current query on the "tasks" edge. +func (mq *ModelQuery) QueryTasks() *TaskQuery { + query := (&TaskClient{config: mq.config}).Query() query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { if err := mq.prepareQuery(ctx); err != nil { return nil, err @@ -79,8 +79,8 @@ func (mq *ModelQuery) QueryRecords() *RecordQuery { } step := sqlgraph.NewStep( sqlgraph.From(model.Table, model.FieldID, selector), - sqlgraph.To(record.Table, record.FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, model.RecordsTable, model.RecordsColumn), + sqlgraph.To(task.Table, task.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, model.TasksTable, model.TasksColumn), ) fromU = sqlgraph.SetNeighbors(mq.driver.Dialect(), step) return fromU, nil @@ -297,13 +297,13 @@ func (mq *ModelQuery) Clone() *ModelQuery { return nil } return &ModelQuery{ - config: mq.config, - ctx: mq.ctx.Clone(), - order: append([]model.OrderOption{}, mq.order...), - inters: append([]Interceptor{}, mq.inters...), - predicates: append([]predicate.Model{}, mq.predicates...), - withRecords: mq.withRecords.Clone(), - withUser: mq.withUser.Clone(), + config: mq.config, + ctx: mq.ctx.Clone(), + order: append([]model.OrderOption{}, mq.order...), + inters: append([]Interceptor{}, mq.inters...), + predicates: append([]predicate.Model{}, mq.predicates...), + withTasks: mq.withTasks.Clone(), + withUser: mq.withUser.Clone(), // clone intermediate query. sql: mq.sql.Clone(), path: mq.path, @@ -311,14 +311,14 @@ func (mq *ModelQuery) Clone() *ModelQuery { } } -// WithRecords tells the query-builder to eager-load the nodes that are connected to -// the "records" edge. The optional arguments are used to configure the query builder of the edge. -func (mq *ModelQuery) WithRecords(opts ...func(*RecordQuery)) *ModelQuery { - query := (&RecordClient{config: mq.config}).Query() +// WithTasks tells the query-builder to eager-load the nodes that are connected to +// the "tasks" edge. The optional arguments are used to configure the query builder of the edge. +func (mq *ModelQuery) WithTasks(opts ...func(*TaskQuery)) *ModelQuery { + query := (&TaskClient{config: mq.config}).Query() for _, opt := range opts { opt(query) } - mq.withRecords = query + mq.withTasks = query return mq } @@ -412,7 +412,7 @@ func (mq *ModelQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Model, nodes = []*Model{} _spec = mq.querySpec() loadedTypes = [2]bool{ - mq.withRecords != nil, + mq.withTasks != nil, mq.withUser != nil, } ) @@ -437,10 +437,10 @@ func (mq *ModelQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Model, if len(nodes) == 0 { return nodes, nil } - if query := mq.withRecords; query != nil { - if err := mq.loadRecords(ctx, query, nodes, - func(n *Model) { n.Edges.Records = []*Record{} }, - func(n *Model, e *Record) { n.Edges.Records = append(n.Edges.Records, e) }); err != nil { + if query := mq.withTasks; query != nil { + if err := mq.loadTasks(ctx, query, nodes, + func(n *Model) { n.Edges.Tasks = []*Task{} }, + func(n *Model, e *Task) { n.Edges.Tasks = append(n.Edges.Tasks, e) }); err != nil { return nil, err } } @@ -453,7 +453,7 @@ func (mq *ModelQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Model, return nodes, nil } -func (mq *ModelQuery) loadRecords(ctx context.Context, query *RecordQuery, nodes []*Model, init func(*Model), assign func(*Model, *Record)) error { +func (mq *ModelQuery) loadTasks(ctx context.Context, query *TaskQuery, nodes []*Model, init func(*Model), assign func(*Model, *Task)) error { fks := make([]driver.Value, 0, len(nodes)) nodeids := make(map[uuid.UUID]*Model) for i := range nodes { @@ -464,10 +464,10 @@ func (mq *ModelQuery) loadRecords(ctx context.Context, query *RecordQuery, nodes } } if len(query.ctx.Fields) > 0 { - query.ctx.AppendFieldOnce(record.FieldModelID) + query.ctx.AppendFieldOnce(task.FieldModelID) } - query.Where(predicate.Record(func(s *sql.Selector) { - s.Where(sql.InValues(s.C(model.RecordsColumn), fks...)) + query.Where(predicate.Task(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(model.TasksColumn), fks...)) })) neighbors, err := query.All(ctx) if err != nil { diff --git a/backend/db/model_update.go b/backend/db/model_update.go index 3f3e0ae..ae211cd 100644 --- a/backend/db/model_update.go +++ b/backend/db/model_update.go @@ -14,7 +14,7 @@ import ( "github.com/chaitin/MonkeyCode/backend/consts" "github.com/chaitin/MonkeyCode/backend/db/model" "github.com/chaitin/MonkeyCode/backend/db/predicate" - "github.com/chaitin/MonkeyCode/backend/db/record" + "github.com/chaitin/MonkeyCode/backend/db/task" "github.com/chaitin/MonkeyCode/backend/db/user" "github.com/google/uuid" ) @@ -224,19 +224,19 @@ func (mu *ModelUpdate) SetUpdatedAt(t time.Time) *ModelUpdate { return mu } -// AddRecordIDs adds the "records" edge to the Record entity by IDs. -func (mu *ModelUpdate) AddRecordIDs(ids ...uuid.UUID) *ModelUpdate { - mu.mutation.AddRecordIDs(ids...) +// AddTaskIDs adds the "tasks" edge to the Task entity by IDs. +func (mu *ModelUpdate) AddTaskIDs(ids ...uuid.UUID) *ModelUpdate { + mu.mutation.AddTaskIDs(ids...) return mu } -// AddRecords adds the "records" edges to the Record entity. -func (mu *ModelUpdate) AddRecords(r ...*Record) *ModelUpdate { - ids := make([]uuid.UUID, len(r)) - for i := range r { - ids[i] = r[i].ID +// AddTasks adds the "tasks" edges to the Task entity. +func (mu *ModelUpdate) AddTasks(t ...*Task) *ModelUpdate { + ids := make([]uuid.UUID, len(t)) + for i := range t { + ids[i] = t[i].ID } - return mu.AddRecordIDs(ids...) + return mu.AddTaskIDs(ids...) } // SetUser sets the "user" edge to the User entity. @@ -249,25 +249,25 @@ func (mu *ModelUpdate) Mutation() *ModelMutation { return mu.mutation } -// ClearRecords clears all "records" edges to the Record entity. -func (mu *ModelUpdate) ClearRecords() *ModelUpdate { - mu.mutation.ClearRecords() +// ClearTasks clears all "tasks" edges to the Task entity. +func (mu *ModelUpdate) ClearTasks() *ModelUpdate { + mu.mutation.ClearTasks() return mu } -// RemoveRecordIDs removes the "records" edge to Record entities by IDs. -func (mu *ModelUpdate) RemoveRecordIDs(ids ...uuid.UUID) *ModelUpdate { - mu.mutation.RemoveRecordIDs(ids...) +// RemoveTaskIDs removes the "tasks" edge to Task entities by IDs. +func (mu *ModelUpdate) RemoveTaskIDs(ids ...uuid.UUID) *ModelUpdate { + mu.mutation.RemoveTaskIDs(ids...) return mu } -// RemoveRecords removes "records" edges to Record entities. -func (mu *ModelUpdate) RemoveRecords(r ...*Record) *ModelUpdate { - ids := make([]uuid.UUID, len(r)) - for i := range r { - ids[i] = r[i].ID +// RemoveTasks removes "tasks" edges to Task entities. +func (mu *ModelUpdate) RemoveTasks(t ...*Task) *ModelUpdate { + ids := make([]uuid.UUID, len(t)) + for i := range t { + ids[i] = t[i].ID } - return mu.RemoveRecordIDs(ids...) + return mu.RemoveTaskIDs(ids...) } // ClearUser clears the "user" edge to the User entity. @@ -372,28 +372,28 @@ func (mu *ModelUpdate) sqlSave(ctx context.Context) (n int, err error) { if value, ok := mu.mutation.UpdatedAt(); ok { _spec.SetField(model.FieldUpdatedAt, field.TypeTime, value) } - if mu.mutation.RecordsCleared() { + if mu.mutation.TasksCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, Inverse: false, - Table: model.RecordsTable, - Columns: []string{model.RecordsColumn}, + Table: model.TasksTable, + Columns: []string{model.TasksColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(record.FieldID, field.TypeUUID), + IDSpec: sqlgraph.NewFieldSpec(task.FieldID, field.TypeUUID), }, } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) } - if nodes := mu.mutation.RemovedRecordsIDs(); len(nodes) > 0 && !mu.mutation.RecordsCleared() { + if nodes := mu.mutation.RemovedTasksIDs(); len(nodes) > 0 && !mu.mutation.TasksCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, Inverse: false, - Table: model.RecordsTable, - Columns: []string{model.RecordsColumn}, + Table: model.TasksTable, + Columns: []string{model.TasksColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(record.FieldID, field.TypeUUID), + IDSpec: sqlgraph.NewFieldSpec(task.FieldID, field.TypeUUID), }, } for _, k := range nodes { @@ -401,15 +401,15 @@ func (mu *ModelUpdate) sqlSave(ctx context.Context) (n int, err error) { } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) } - if nodes := mu.mutation.RecordsIDs(); len(nodes) > 0 { + if nodes := mu.mutation.TasksIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, Inverse: false, - Table: model.RecordsTable, - Columns: []string{model.RecordsColumn}, + Table: model.TasksTable, + Columns: []string{model.TasksColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(record.FieldID, field.TypeUUID), + IDSpec: sqlgraph.NewFieldSpec(task.FieldID, field.TypeUUID), }, } for _, k := range nodes { @@ -659,19 +659,19 @@ func (muo *ModelUpdateOne) SetUpdatedAt(t time.Time) *ModelUpdateOne { return muo } -// AddRecordIDs adds the "records" edge to the Record entity by IDs. -func (muo *ModelUpdateOne) AddRecordIDs(ids ...uuid.UUID) *ModelUpdateOne { - muo.mutation.AddRecordIDs(ids...) +// AddTaskIDs adds the "tasks" edge to the Task entity by IDs. +func (muo *ModelUpdateOne) AddTaskIDs(ids ...uuid.UUID) *ModelUpdateOne { + muo.mutation.AddTaskIDs(ids...) return muo } -// AddRecords adds the "records" edges to the Record entity. -func (muo *ModelUpdateOne) AddRecords(r ...*Record) *ModelUpdateOne { - ids := make([]uuid.UUID, len(r)) - for i := range r { - ids[i] = r[i].ID +// AddTasks adds the "tasks" edges to the Task entity. +func (muo *ModelUpdateOne) AddTasks(t ...*Task) *ModelUpdateOne { + ids := make([]uuid.UUID, len(t)) + for i := range t { + ids[i] = t[i].ID } - return muo.AddRecordIDs(ids...) + return muo.AddTaskIDs(ids...) } // SetUser sets the "user" edge to the User entity. @@ -684,25 +684,25 @@ func (muo *ModelUpdateOne) Mutation() *ModelMutation { return muo.mutation } -// ClearRecords clears all "records" edges to the Record entity. -func (muo *ModelUpdateOne) ClearRecords() *ModelUpdateOne { - muo.mutation.ClearRecords() +// ClearTasks clears all "tasks" edges to the Task entity. +func (muo *ModelUpdateOne) ClearTasks() *ModelUpdateOne { + muo.mutation.ClearTasks() return muo } -// RemoveRecordIDs removes the "records" edge to Record entities by IDs. -func (muo *ModelUpdateOne) RemoveRecordIDs(ids ...uuid.UUID) *ModelUpdateOne { - muo.mutation.RemoveRecordIDs(ids...) +// RemoveTaskIDs removes the "tasks" edge to Task entities by IDs. +func (muo *ModelUpdateOne) RemoveTaskIDs(ids ...uuid.UUID) *ModelUpdateOne { + muo.mutation.RemoveTaskIDs(ids...) return muo } -// RemoveRecords removes "records" edges to Record entities. -func (muo *ModelUpdateOne) RemoveRecords(r ...*Record) *ModelUpdateOne { - ids := make([]uuid.UUID, len(r)) - for i := range r { - ids[i] = r[i].ID +// RemoveTasks removes "tasks" edges to Task entities. +func (muo *ModelUpdateOne) RemoveTasks(t ...*Task) *ModelUpdateOne { + ids := make([]uuid.UUID, len(t)) + for i := range t { + ids[i] = t[i].ID } - return muo.RemoveRecordIDs(ids...) + return muo.RemoveTaskIDs(ids...) } // ClearUser clears the "user" edge to the User entity. @@ -837,28 +837,28 @@ func (muo *ModelUpdateOne) sqlSave(ctx context.Context) (_node *Model, err error if value, ok := muo.mutation.UpdatedAt(); ok { _spec.SetField(model.FieldUpdatedAt, field.TypeTime, value) } - if muo.mutation.RecordsCleared() { + if muo.mutation.TasksCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, Inverse: false, - Table: model.RecordsTable, - Columns: []string{model.RecordsColumn}, + Table: model.TasksTable, + Columns: []string{model.TasksColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(record.FieldID, field.TypeUUID), + IDSpec: sqlgraph.NewFieldSpec(task.FieldID, field.TypeUUID), }, } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) } - if nodes := muo.mutation.RemovedRecordsIDs(); len(nodes) > 0 && !muo.mutation.RecordsCleared() { + if nodes := muo.mutation.RemovedTasksIDs(); len(nodes) > 0 && !muo.mutation.TasksCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, Inverse: false, - Table: model.RecordsTable, - Columns: []string{model.RecordsColumn}, + Table: model.TasksTable, + Columns: []string{model.TasksColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(record.FieldID, field.TypeUUID), + IDSpec: sqlgraph.NewFieldSpec(task.FieldID, field.TypeUUID), }, } for _, k := range nodes { @@ -866,15 +866,15 @@ func (muo *ModelUpdateOne) sqlSave(ctx context.Context) (_node *Model, err error } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) } - if nodes := muo.mutation.RecordsIDs(); len(nodes) > 0 { + if nodes := muo.mutation.TasksIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, Inverse: false, - Table: model.RecordsTable, - Columns: []string{model.RecordsColumn}, + Table: model.TasksTable, + Columns: []string{model.TasksColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(record.FieldID, field.TypeUUID), + IDSpec: sqlgraph.NewFieldSpec(task.FieldID, field.TypeUUID), }, } for _, k := range nodes { diff --git a/backend/db/mutation.go b/backend/db/mutation.go index bc82c28..3f4609c 100644 --- a/backend/db/mutation.go +++ b/backend/db/mutation.go @@ -22,8 +22,9 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/invitecode" "github.com/chaitin/MonkeyCode/backend/db/model" "github.com/chaitin/MonkeyCode/backend/db/predicate" - "github.com/chaitin/MonkeyCode/backend/db/record" "github.com/chaitin/MonkeyCode/backend/db/setting" + "github.com/chaitin/MonkeyCode/backend/db/task" + "github.com/chaitin/MonkeyCode/backend/db/taskrecord" "github.com/chaitin/MonkeyCode/backend/db/user" "github.com/chaitin/MonkeyCode/backend/db/userloginhistory" "github.com/google/uuid" @@ -47,8 +48,9 @@ const ( TypeBillingUsage = "BillingUsage" TypeInviteCode = "InviteCode" TypeModel = "Model" - TypeRecord = "Record" TypeSetting = "Setting" + TypeTask = "Task" + TypeTaskRecord = "TaskRecord" TypeUser = "User" TypeUserLoginHistory = "UserLoginHistory" ) @@ -5840,9 +5842,9 @@ type ModelMutation struct { created_at *time.Time updated_at *time.Time clearedFields map[string]struct{} - records map[uuid.UUID]struct{} - removedrecords map[uuid.UUID]struct{} - clearedrecords bool + tasks map[uuid.UUID]struct{} + removedtasks map[uuid.UUID]struct{} + clearedtasks bool user *uuid.UUID cleareduser bool done bool @@ -6459,58 +6461,58 @@ func (m *ModelMutation) ResetUpdatedAt() { m.updated_at = nil } -// AddRecordIDs adds the "records" edge to the Record entity by ids. -func (m *ModelMutation) AddRecordIDs(ids ...uuid.UUID) { - if m.records == nil { - m.records = make(map[uuid.UUID]struct{}) +// AddTaskIDs adds the "tasks" edge to the Task entity by ids. +func (m *ModelMutation) AddTaskIDs(ids ...uuid.UUID) { + if m.tasks == nil { + m.tasks = make(map[uuid.UUID]struct{}) } for i := range ids { - m.records[ids[i]] = struct{}{} + m.tasks[ids[i]] = struct{}{} } } -// ClearRecords clears the "records" edge to the Record entity. -func (m *ModelMutation) ClearRecords() { - m.clearedrecords = true +// ClearTasks clears the "tasks" edge to the Task entity. +func (m *ModelMutation) ClearTasks() { + m.clearedtasks = true } -// RecordsCleared reports if the "records" edge to the Record entity was cleared. -func (m *ModelMutation) RecordsCleared() bool { - return m.clearedrecords +// TasksCleared reports if the "tasks" edge to the Task entity was cleared. +func (m *ModelMutation) TasksCleared() bool { + return m.clearedtasks } -// RemoveRecordIDs removes the "records" edge to the Record entity by IDs. -func (m *ModelMutation) RemoveRecordIDs(ids ...uuid.UUID) { - if m.removedrecords == nil { - m.removedrecords = make(map[uuid.UUID]struct{}) +// RemoveTaskIDs removes the "tasks" edge to the Task entity by IDs. +func (m *ModelMutation) RemoveTaskIDs(ids ...uuid.UUID) { + if m.removedtasks == nil { + m.removedtasks = make(map[uuid.UUID]struct{}) } for i := range ids { - delete(m.records, ids[i]) - m.removedrecords[ids[i]] = struct{}{} + delete(m.tasks, ids[i]) + m.removedtasks[ids[i]] = struct{}{} } } -// RemovedRecords returns the removed IDs of the "records" edge to the Record entity. -func (m *ModelMutation) RemovedRecordsIDs() (ids []uuid.UUID) { - for id := range m.removedrecords { +// RemovedTasks returns the removed IDs of the "tasks" edge to the Task entity. +func (m *ModelMutation) RemovedTasksIDs() (ids []uuid.UUID) { + for id := range m.removedtasks { ids = append(ids, id) } return } -// RecordsIDs returns the "records" edge IDs in the mutation. -func (m *ModelMutation) RecordsIDs() (ids []uuid.UUID) { - for id := range m.records { +// TasksIDs returns the "tasks" edge IDs in the mutation. +func (m *ModelMutation) TasksIDs() (ids []uuid.UUID) { + for id := range m.tasks { ids = append(ids, id) } return } -// ResetRecords resets all changes to the "records" edge. -func (m *ModelMutation) ResetRecords() { - m.records = nil - m.clearedrecords = false - m.removedrecords = nil +// ResetTasks resets all changes to the "tasks" edge. +func (m *ModelMutation) ResetTasks() { + m.tasks = nil + m.clearedtasks = false + m.removedtasks = nil } // ClearUser clears the "user" edge to the User entity. @@ -6903,8 +6905,8 @@ func (m *ModelMutation) ResetField(name string) error { // AddedEdges returns all edge names that were set/added in this mutation. func (m *ModelMutation) AddedEdges() []string { edges := make([]string, 0, 2) - if m.records != nil { - edges = append(edges, model.EdgeRecords) + if m.tasks != nil { + edges = append(edges, model.EdgeTasks) } if m.user != nil { edges = append(edges, model.EdgeUser) @@ -6916,9 +6918,9 @@ func (m *ModelMutation) AddedEdges() []string { // name in this mutation. func (m *ModelMutation) AddedIDs(name string) []ent.Value { switch name { - case model.EdgeRecords: - ids := make([]ent.Value, 0, len(m.records)) - for id := range m.records { + case model.EdgeTasks: + ids := make([]ent.Value, 0, len(m.tasks)) + for id := range m.tasks { ids = append(ids, id) } return ids @@ -6933,8 +6935,8 @@ func (m *ModelMutation) AddedIDs(name string) []ent.Value { // RemovedEdges returns all edge names that were removed in this mutation. func (m *ModelMutation) RemovedEdges() []string { edges := make([]string, 0, 2) - if m.removedrecords != nil { - edges = append(edges, model.EdgeRecords) + if m.removedtasks != nil { + edges = append(edges, model.EdgeTasks) } return edges } @@ -6943,9 +6945,9 @@ func (m *ModelMutation) RemovedEdges() []string { // the given name in this mutation. func (m *ModelMutation) RemovedIDs(name string) []ent.Value { switch name { - case model.EdgeRecords: - ids := make([]ent.Value, 0, len(m.removedrecords)) - for id := range m.removedrecords { + case model.EdgeTasks: + ids := make([]ent.Value, 0, len(m.removedtasks)) + for id := range m.removedtasks { ids = append(ids, id) } return ids @@ -6956,8 +6958,8 @@ func (m *ModelMutation) RemovedIDs(name string) []ent.Value { // ClearedEdges returns all edge names that were cleared in this mutation. func (m *ModelMutation) ClearedEdges() []string { edges := make([]string, 0, 2) - if m.clearedrecords { - edges = append(edges, model.EdgeRecords) + if m.clearedtasks { + edges = append(edges, model.EdgeTasks) } if m.cleareduser { edges = append(edges, model.EdgeUser) @@ -6969,8 +6971,8 @@ func (m *ModelMutation) ClearedEdges() []string { // was cleared in this mutation. func (m *ModelMutation) EdgeCleared(name string) bool { switch name { - case model.EdgeRecords: - return m.clearedrecords + case model.EdgeTasks: + return m.clearedtasks case model.EdgeUser: return m.cleareduser } @@ -6992,8 +6994,8 @@ func (m *ModelMutation) ClearEdge(name string) error { // It returns an error if the edge is not defined in the schema. func (m *ModelMutation) ResetEdge(name string) error { switch name { - case model.EdgeRecords: - m.ResetRecords() + case model.EdgeTasks: + m.ResetTasks() return nil case model.EdgeUser: m.ResetUser() @@ -7002,1398 +7004,6 @@ func (m *ModelMutation) ResetEdge(name string) error { return fmt.Errorf("unknown Model edge %s", name) } -// RecordMutation represents an operation that mutates the Record nodes in the graph. -type RecordMutation struct { - config - op Op - typ string - id *uuid.UUID - task_id *string - model_type *consts.ModelType - prompt *string - completion *string - is_accept *bool - program_language *string - work_mode *string - code_lines *int64 - addcode_lines *int64 - input_tokens *int64 - addinput_tokens *int64 - output_tokens *int64 - addoutput_tokens *int64 - created_at *time.Time - updated_at *time.Time - clearedFields map[string]struct{} - user *uuid.UUID - cleareduser bool - model *uuid.UUID - clearedmodel bool - done bool - oldValue func(context.Context) (*Record, error) - predicates []predicate.Record -} - -var _ ent.Mutation = (*RecordMutation)(nil) - -// recordOption allows management of the mutation configuration using functional options. -type recordOption func(*RecordMutation) - -// newRecordMutation creates new mutation for the Record entity. -func newRecordMutation(c config, op Op, opts ...recordOption) *RecordMutation { - m := &RecordMutation{ - config: c, - op: op, - typ: TypeRecord, - clearedFields: make(map[string]struct{}), - } - for _, opt := range opts { - opt(m) - } - return m -} - -// withRecordID sets the ID field of the mutation. -func withRecordID(id uuid.UUID) recordOption { - return func(m *RecordMutation) { - var ( - err error - once sync.Once - value *Record - ) - m.oldValue = func(ctx context.Context) (*Record, error) { - once.Do(func() { - if m.done { - err = errors.New("querying old values post mutation is not allowed") - } else { - value, err = m.Client().Record.Get(ctx, id) - } - }) - return value, err - } - m.id = &id - } -} - -// withRecord sets the old Record of the mutation. -func withRecord(node *Record) recordOption { - return func(m *RecordMutation) { - m.oldValue = func(context.Context) (*Record, error) { - return node, nil - } - m.id = &node.ID - } -} - -// Client returns a new `ent.Client` from the mutation. If the mutation was -// executed in a transaction (ent.Tx), a transactional client is returned. -func (m RecordMutation) Client() *Client { - client := &Client{config: m.config} - client.init() - return client -} - -// Tx returns an `ent.Tx` for mutations that were executed in transactions; -// it returns an error otherwise. -func (m RecordMutation) Tx() (*Tx, error) { - if _, ok := m.driver.(*txDriver); !ok { - return nil, errors.New("db: mutation is not running in a transaction") - } - tx := &Tx{config: m.config} - tx.init() - return tx, nil -} - -// SetID sets the value of the id field. Note that this -// operation is only accepted on creation of Record entities. -func (m *RecordMutation) SetID(id uuid.UUID) { - m.id = &id -} - -// ID returns the ID value in the mutation. Note that the ID is only available -// if it was provided to the builder or after it was returned from the database. -func (m *RecordMutation) ID() (id uuid.UUID, exists bool) { - if m.id == nil { - return - } - return *m.id, true -} - -// IDs queries the database and returns the entity ids that match the mutation's predicate. -// That means, if the mutation is applied within a transaction with an isolation level such -// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated -// or updated by the mutation. -func (m *RecordMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { - switch { - case m.op.Is(OpUpdateOne | OpDeleteOne): - id, exists := m.ID() - if exists { - return []uuid.UUID{id}, nil - } - fallthrough - case m.op.Is(OpUpdate | OpDelete): - return m.Client().Record.Query().Where(m.predicates...).IDs(ctx) - default: - return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) - } -} - -// SetUserID sets the "user_id" field. -func (m *RecordMutation) SetUserID(u uuid.UUID) { - m.user = &u -} - -// UserID returns the value of the "user_id" field in the mutation. -func (m *RecordMutation) UserID() (r uuid.UUID, exists bool) { - v := m.user - if v == nil { - return - } - return *v, true -} - -// OldUserID returns the old "user_id" field's value of the Record entity. -// If the Record object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *RecordMutation) OldUserID(ctx context.Context) (v uuid.UUID, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldUserID is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldUserID requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldUserID: %w", err) - } - return oldValue.UserID, nil -} - -// ClearUserID clears the value of the "user_id" field. -func (m *RecordMutation) ClearUserID() { - m.user = nil - m.clearedFields[record.FieldUserID] = struct{}{} -} - -// UserIDCleared returns if the "user_id" field was cleared in this mutation. -func (m *RecordMutation) UserIDCleared() bool { - _, ok := m.clearedFields[record.FieldUserID] - return ok -} - -// ResetUserID resets all changes to the "user_id" field. -func (m *RecordMutation) ResetUserID() { - m.user = nil - delete(m.clearedFields, record.FieldUserID) -} - -// SetModelID sets the "model_id" field. -func (m *RecordMutation) SetModelID(u uuid.UUID) { - m.model = &u -} - -// ModelID returns the value of the "model_id" field in the mutation. -func (m *RecordMutation) ModelID() (r uuid.UUID, exists bool) { - v := m.model - if v == nil { - return - } - return *v, true -} - -// OldModelID returns the old "model_id" field's value of the Record entity. -// If the Record object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *RecordMutation) OldModelID(ctx context.Context) (v uuid.UUID, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldModelID is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldModelID requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldModelID: %w", err) - } - return oldValue.ModelID, nil -} - -// ClearModelID clears the value of the "model_id" field. -func (m *RecordMutation) ClearModelID() { - m.model = nil - m.clearedFields[record.FieldModelID] = struct{}{} -} - -// ModelIDCleared returns if the "model_id" field was cleared in this mutation. -func (m *RecordMutation) ModelIDCleared() bool { - _, ok := m.clearedFields[record.FieldModelID] - return ok -} - -// ResetModelID resets all changes to the "model_id" field. -func (m *RecordMutation) ResetModelID() { - m.model = nil - delete(m.clearedFields, record.FieldModelID) -} - -// SetTaskID sets the "task_id" field. -func (m *RecordMutation) SetTaskID(s string) { - m.task_id = &s -} - -// TaskID returns the value of the "task_id" field in the mutation. -func (m *RecordMutation) TaskID() (r string, exists bool) { - v := m.task_id - if v == nil { - return - } - return *v, true -} - -// OldTaskID returns the old "task_id" field's value of the Record entity. -// If the Record object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *RecordMutation) OldTaskID(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldTaskID is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldTaskID requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldTaskID: %w", err) - } - return oldValue.TaskID, nil -} - -// ResetTaskID resets all changes to the "task_id" field. -func (m *RecordMutation) ResetTaskID() { - m.task_id = nil -} - -// SetModelType sets the "model_type" field. -func (m *RecordMutation) SetModelType(ct consts.ModelType) { - m.model_type = &ct -} - -// ModelType returns the value of the "model_type" field in the mutation. -func (m *RecordMutation) ModelType() (r consts.ModelType, exists bool) { - v := m.model_type - if v == nil { - return - } - return *v, true -} - -// OldModelType returns the old "model_type" field's value of the Record entity. -// If the Record object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *RecordMutation) OldModelType(ctx context.Context) (v consts.ModelType, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldModelType is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldModelType requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldModelType: %w", err) - } - return oldValue.ModelType, nil -} - -// ClearModelType clears the value of the "model_type" field. -func (m *RecordMutation) ClearModelType() { - m.model_type = nil - m.clearedFields[record.FieldModelType] = struct{}{} -} - -// ModelTypeCleared returns if the "model_type" field was cleared in this mutation. -func (m *RecordMutation) ModelTypeCleared() bool { - _, ok := m.clearedFields[record.FieldModelType] - return ok -} - -// ResetModelType resets all changes to the "model_type" field. -func (m *RecordMutation) ResetModelType() { - m.model_type = nil - delete(m.clearedFields, record.FieldModelType) -} - -// SetPrompt sets the "prompt" field. -func (m *RecordMutation) SetPrompt(s string) { - m.prompt = &s -} - -// Prompt returns the value of the "prompt" field in the mutation. -func (m *RecordMutation) Prompt() (r string, exists bool) { - v := m.prompt - if v == nil { - return - } - return *v, true -} - -// OldPrompt returns the old "prompt" field's value of the Record entity. -// If the Record object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *RecordMutation) OldPrompt(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldPrompt is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldPrompt requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldPrompt: %w", err) - } - return oldValue.Prompt, nil -} - -// ClearPrompt clears the value of the "prompt" field. -func (m *RecordMutation) ClearPrompt() { - m.prompt = nil - m.clearedFields[record.FieldPrompt] = struct{}{} -} - -// PromptCleared returns if the "prompt" field was cleared in this mutation. -func (m *RecordMutation) PromptCleared() bool { - _, ok := m.clearedFields[record.FieldPrompt] - return ok -} - -// ResetPrompt resets all changes to the "prompt" field. -func (m *RecordMutation) ResetPrompt() { - m.prompt = nil - delete(m.clearedFields, record.FieldPrompt) -} - -// SetCompletion sets the "completion" field. -func (m *RecordMutation) SetCompletion(s string) { - m.completion = &s -} - -// Completion returns the value of the "completion" field in the mutation. -func (m *RecordMutation) Completion() (r string, exists bool) { - v := m.completion - if v == nil { - return - } - return *v, true -} - -// OldCompletion returns the old "completion" field's value of the Record entity. -// If the Record object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *RecordMutation) OldCompletion(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCompletion is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCompletion requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldCompletion: %w", err) - } - return oldValue.Completion, nil -} - -// ClearCompletion clears the value of the "completion" field. -func (m *RecordMutation) ClearCompletion() { - m.completion = nil - m.clearedFields[record.FieldCompletion] = struct{}{} -} - -// CompletionCleared returns if the "completion" field was cleared in this mutation. -func (m *RecordMutation) CompletionCleared() bool { - _, ok := m.clearedFields[record.FieldCompletion] - return ok -} - -// ResetCompletion resets all changes to the "completion" field. -func (m *RecordMutation) ResetCompletion() { - m.completion = nil - delete(m.clearedFields, record.FieldCompletion) -} - -// SetIsAccept sets the "is_accept" field. -func (m *RecordMutation) SetIsAccept(b bool) { - m.is_accept = &b -} - -// IsAccept returns the value of the "is_accept" field in the mutation. -func (m *RecordMutation) IsAccept() (r bool, exists bool) { - v := m.is_accept - if v == nil { - return - } - return *v, true -} - -// OldIsAccept returns the old "is_accept" field's value of the Record entity. -// If the Record object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *RecordMutation) OldIsAccept(ctx context.Context) (v bool, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldIsAccept is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldIsAccept requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldIsAccept: %w", err) - } - return oldValue.IsAccept, nil -} - -// ResetIsAccept resets all changes to the "is_accept" field. -func (m *RecordMutation) ResetIsAccept() { - m.is_accept = nil -} - -// SetProgramLanguage sets the "program_language" field. -func (m *RecordMutation) SetProgramLanguage(s string) { - m.program_language = &s -} - -// ProgramLanguage returns the value of the "program_language" field in the mutation. -func (m *RecordMutation) ProgramLanguage() (r string, exists bool) { - v := m.program_language - if v == nil { - return - } - return *v, true -} - -// OldProgramLanguage returns the old "program_language" field's value of the Record entity. -// If the Record object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *RecordMutation) OldProgramLanguage(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldProgramLanguage is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldProgramLanguage requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldProgramLanguage: %w", err) - } - return oldValue.ProgramLanguage, nil -} - -// ClearProgramLanguage clears the value of the "program_language" field. -func (m *RecordMutation) ClearProgramLanguage() { - m.program_language = nil - m.clearedFields[record.FieldProgramLanguage] = struct{}{} -} - -// ProgramLanguageCleared returns if the "program_language" field was cleared in this mutation. -func (m *RecordMutation) ProgramLanguageCleared() bool { - _, ok := m.clearedFields[record.FieldProgramLanguage] - return ok -} - -// ResetProgramLanguage resets all changes to the "program_language" field. -func (m *RecordMutation) ResetProgramLanguage() { - m.program_language = nil - delete(m.clearedFields, record.FieldProgramLanguage) -} - -// SetWorkMode sets the "work_mode" field. -func (m *RecordMutation) SetWorkMode(s string) { - m.work_mode = &s -} - -// WorkMode returns the value of the "work_mode" field in the mutation. -func (m *RecordMutation) WorkMode() (r string, exists bool) { - v := m.work_mode - if v == nil { - return - } - return *v, true -} - -// OldWorkMode returns the old "work_mode" field's value of the Record entity. -// If the Record object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *RecordMutation) OldWorkMode(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldWorkMode is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldWorkMode requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldWorkMode: %w", err) - } - return oldValue.WorkMode, nil -} - -// ClearWorkMode clears the value of the "work_mode" field. -func (m *RecordMutation) ClearWorkMode() { - m.work_mode = nil - m.clearedFields[record.FieldWorkMode] = struct{}{} -} - -// WorkModeCleared returns if the "work_mode" field was cleared in this mutation. -func (m *RecordMutation) WorkModeCleared() bool { - _, ok := m.clearedFields[record.FieldWorkMode] - return ok -} - -// ResetWorkMode resets all changes to the "work_mode" field. -func (m *RecordMutation) ResetWorkMode() { - m.work_mode = nil - delete(m.clearedFields, record.FieldWorkMode) -} - -// SetCodeLines sets the "code_lines" field. -func (m *RecordMutation) SetCodeLines(i int64) { - m.code_lines = &i - m.addcode_lines = nil -} - -// CodeLines returns the value of the "code_lines" field in the mutation. -func (m *RecordMutation) CodeLines() (r int64, exists bool) { - v := m.code_lines - if v == nil { - return - } - return *v, true -} - -// OldCodeLines returns the old "code_lines" field's value of the Record entity. -// If the Record object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *RecordMutation) OldCodeLines(ctx context.Context) (v int64, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCodeLines is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCodeLines requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldCodeLines: %w", err) - } - return oldValue.CodeLines, nil -} - -// AddCodeLines adds i to the "code_lines" field. -func (m *RecordMutation) AddCodeLines(i int64) { - if m.addcode_lines != nil { - *m.addcode_lines += i - } else { - m.addcode_lines = &i - } -} - -// AddedCodeLines returns the value that was added to the "code_lines" field in this mutation. -func (m *RecordMutation) AddedCodeLines() (r int64, exists bool) { - v := m.addcode_lines - if v == nil { - return - } - return *v, true -} - -// ClearCodeLines clears the value of the "code_lines" field. -func (m *RecordMutation) ClearCodeLines() { - m.code_lines = nil - m.addcode_lines = nil - m.clearedFields[record.FieldCodeLines] = struct{}{} -} - -// CodeLinesCleared returns if the "code_lines" field was cleared in this mutation. -func (m *RecordMutation) CodeLinesCleared() bool { - _, ok := m.clearedFields[record.FieldCodeLines] - return ok -} - -// ResetCodeLines resets all changes to the "code_lines" field. -func (m *RecordMutation) ResetCodeLines() { - m.code_lines = nil - m.addcode_lines = nil - delete(m.clearedFields, record.FieldCodeLines) -} - -// SetInputTokens sets the "input_tokens" field. -func (m *RecordMutation) SetInputTokens(i int64) { - m.input_tokens = &i - m.addinput_tokens = nil -} - -// InputTokens returns the value of the "input_tokens" field in the mutation. -func (m *RecordMutation) InputTokens() (r int64, exists bool) { - v := m.input_tokens - if v == nil { - return - } - return *v, true -} - -// OldInputTokens returns the old "input_tokens" field's value of the Record entity. -// If the Record object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *RecordMutation) OldInputTokens(ctx context.Context) (v int64, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldInputTokens is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldInputTokens requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldInputTokens: %w", err) - } - return oldValue.InputTokens, nil -} - -// AddInputTokens adds i to the "input_tokens" field. -func (m *RecordMutation) AddInputTokens(i int64) { - if m.addinput_tokens != nil { - *m.addinput_tokens += i - } else { - m.addinput_tokens = &i - } -} - -// AddedInputTokens returns the value that was added to the "input_tokens" field in this mutation. -func (m *RecordMutation) AddedInputTokens() (r int64, exists bool) { - v := m.addinput_tokens - if v == nil { - return - } - return *v, true -} - -// ResetInputTokens resets all changes to the "input_tokens" field. -func (m *RecordMutation) ResetInputTokens() { - m.input_tokens = nil - m.addinput_tokens = nil -} - -// SetOutputTokens sets the "output_tokens" field. -func (m *RecordMutation) SetOutputTokens(i int64) { - m.output_tokens = &i - m.addoutput_tokens = nil -} - -// OutputTokens returns the value of the "output_tokens" field in the mutation. -func (m *RecordMutation) OutputTokens() (r int64, exists bool) { - v := m.output_tokens - if v == nil { - return - } - return *v, true -} - -// OldOutputTokens returns the old "output_tokens" field's value of the Record entity. -// If the Record object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *RecordMutation) OldOutputTokens(ctx context.Context) (v int64, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldOutputTokens is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldOutputTokens requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldOutputTokens: %w", err) - } - return oldValue.OutputTokens, nil -} - -// AddOutputTokens adds i to the "output_tokens" field. -func (m *RecordMutation) AddOutputTokens(i int64) { - if m.addoutput_tokens != nil { - *m.addoutput_tokens += i - } else { - m.addoutput_tokens = &i - } -} - -// AddedOutputTokens returns the value that was added to the "output_tokens" field in this mutation. -func (m *RecordMutation) AddedOutputTokens() (r int64, exists bool) { - v := m.addoutput_tokens - if v == nil { - return - } - return *v, true -} - -// ResetOutputTokens resets all changes to the "output_tokens" field. -func (m *RecordMutation) ResetOutputTokens() { - m.output_tokens = nil - m.addoutput_tokens = nil -} - -// SetCreatedAt sets the "created_at" field. -func (m *RecordMutation) SetCreatedAt(t time.Time) { - m.created_at = &t -} - -// CreatedAt returns the value of the "created_at" field in the mutation. -func (m *RecordMutation) CreatedAt() (r time.Time, exists bool) { - v := m.created_at - if v == nil { - return - } - return *v, true -} - -// OldCreatedAt returns the old "created_at" field's value of the Record entity. -// If the Record object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *RecordMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCreatedAt requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) - } - return oldValue.CreatedAt, nil -} - -// ResetCreatedAt resets all changes to the "created_at" field. -func (m *RecordMutation) ResetCreatedAt() { - m.created_at = nil -} - -// SetUpdatedAt sets the "updated_at" field. -func (m *RecordMutation) SetUpdatedAt(t time.Time) { - m.updated_at = &t -} - -// UpdatedAt returns the value of the "updated_at" field in the mutation. -func (m *RecordMutation) UpdatedAt() (r time.Time, exists bool) { - v := m.updated_at - if v == nil { - return - } - return *v, true -} - -// OldUpdatedAt returns the old "updated_at" field's value of the Record entity. -// If the Record object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *RecordMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldUpdatedAt requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) - } - return oldValue.UpdatedAt, nil -} - -// ResetUpdatedAt resets all changes to the "updated_at" field. -func (m *RecordMutation) ResetUpdatedAt() { - m.updated_at = nil -} - -// ClearUser clears the "user" edge to the User entity. -func (m *RecordMutation) ClearUser() { - m.cleareduser = true - m.clearedFields[record.FieldUserID] = struct{}{} -} - -// UserCleared reports if the "user" edge to the User entity was cleared. -func (m *RecordMutation) UserCleared() bool { - return m.UserIDCleared() || m.cleareduser -} - -// UserIDs returns the "user" edge IDs in the mutation. -// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// UserID instead. It exists only for internal usage by the builders. -func (m *RecordMutation) UserIDs() (ids []uuid.UUID) { - if id := m.user; id != nil { - ids = append(ids, *id) - } - return -} - -// ResetUser resets all changes to the "user" edge. -func (m *RecordMutation) ResetUser() { - m.user = nil - m.cleareduser = false -} - -// ClearModel clears the "model" edge to the Model entity. -func (m *RecordMutation) ClearModel() { - m.clearedmodel = true - m.clearedFields[record.FieldModelID] = struct{}{} -} - -// ModelCleared reports if the "model" edge to the Model entity was cleared. -func (m *RecordMutation) ModelCleared() bool { - return m.ModelIDCleared() || m.clearedmodel -} - -// ModelIDs returns the "model" edge IDs in the mutation. -// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// ModelID instead. It exists only for internal usage by the builders. -func (m *RecordMutation) ModelIDs() (ids []uuid.UUID) { - if id := m.model; id != nil { - ids = append(ids, *id) - } - return -} - -// ResetModel resets all changes to the "model" edge. -func (m *RecordMutation) ResetModel() { - m.model = nil - m.clearedmodel = false -} - -// Where appends a list predicates to the RecordMutation builder. -func (m *RecordMutation) Where(ps ...predicate.Record) { - m.predicates = append(m.predicates, ps...) -} - -// WhereP appends storage-level predicates to the RecordMutation builder. Using this method, -// users can use type-assertion to append predicates that do not depend on any generated package. -func (m *RecordMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.Record, len(ps)) - for i := range ps { - p[i] = ps[i] - } - m.Where(p...) -} - -// Op returns the operation name. -func (m *RecordMutation) Op() Op { - return m.op -} - -// SetOp allows setting the mutation operation. -func (m *RecordMutation) SetOp(op Op) { - m.op = op -} - -// Type returns the node type of this mutation (Record). -func (m *RecordMutation) Type() string { - return m.typ -} - -// Fields returns all fields that were changed during this mutation. Note that in -// order to get all numeric fields that were incremented/decremented, call -// AddedFields(). -func (m *RecordMutation) Fields() []string { - fields := make([]string, 0, 14) - if m.user != nil { - fields = append(fields, record.FieldUserID) - } - if m.model != nil { - fields = append(fields, record.FieldModelID) - } - if m.task_id != nil { - fields = append(fields, record.FieldTaskID) - } - if m.model_type != nil { - fields = append(fields, record.FieldModelType) - } - if m.prompt != nil { - fields = append(fields, record.FieldPrompt) - } - if m.completion != nil { - fields = append(fields, record.FieldCompletion) - } - if m.is_accept != nil { - fields = append(fields, record.FieldIsAccept) - } - if m.program_language != nil { - fields = append(fields, record.FieldProgramLanguage) - } - if m.work_mode != nil { - fields = append(fields, record.FieldWorkMode) - } - if m.code_lines != nil { - fields = append(fields, record.FieldCodeLines) - } - if m.input_tokens != nil { - fields = append(fields, record.FieldInputTokens) - } - if m.output_tokens != nil { - fields = append(fields, record.FieldOutputTokens) - } - if m.created_at != nil { - fields = append(fields, record.FieldCreatedAt) - } - if m.updated_at != nil { - fields = append(fields, record.FieldUpdatedAt) - } - return fields -} - -// Field returns the value of a field with the given name. The second boolean -// return value indicates that this field was not set, or was not defined in the -// schema. -func (m *RecordMutation) Field(name string) (ent.Value, bool) { - switch name { - case record.FieldUserID: - return m.UserID() - case record.FieldModelID: - return m.ModelID() - case record.FieldTaskID: - return m.TaskID() - case record.FieldModelType: - return m.ModelType() - case record.FieldPrompt: - return m.Prompt() - case record.FieldCompletion: - return m.Completion() - case record.FieldIsAccept: - return m.IsAccept() - case record.FieldProgramLanguage: - return m.ProgramLanguage() - case record.FieldWorkMode: - return m.WorkMode() - case record.FieldCodeLines: - return m.CodeLines() - case record.FieldInputTokens: - return m.InputTokens() - case record.FieldOutputTokens: - return m.OutputTokens() - case record.FieldCreatedAt: - return m.CreatedAt() - case record.FieldUpdatedAt: - return m.UpdatedAt() - } - return nil, false -} - -// OldField returns the old value of the field from the database. An error is -// returned if the mutation operation is not UpdateOne, or the query to the -// database failed. -func (m *RecordMutation) OldField(ctx context.Context, name string) (ent.Value, error) { - switch name { - case record.FieldUserID: - return m.OldUserID(ctx) - case record.FieldModelID: - return m.OldModelID(ctx) - case record.FieldTaskID: - return m.OldTaskID(ctx) - case record.FieldModelType: - return m.OldModelType(ctx) - case record.FieldPrompt: - return m.OldPrompt(ctx) - case record.FieldCompletion: - return m.OldCompletion(ctx) - case record.FieldIsAccept: - return m.OldIsAccept(ctx) - case record.FieldProgramLanguage: - return m.OldProgramLanguage(ctx) - case record.FieldWorkMode: - return m.OldWorkMode(ctx) - case record.FieldCodeLines: - return m.OldCodeLines(ctx) - case record.FieldInputTokens: - return m.OldInputTokens(ctx) - case record.FieldOutputTokens: - return m.OldOutputTokens(ctx) - case record.FieldCreatedAt: - return m.OldCreatedAt(ctx) - case record.FieldUpdatedAt: - return m.OldUpdatedAt(ctx) - } - return nil, fmt.Errorf("unknown Record field %s", name) -} - -// SetField sets the value of a field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *RecordMutation) SetField(name string, value ent.Value) error { - switch name { - case record.FieldUserID: - v, ok := value.(uuid.UUID) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetUserID(v) - return nil - case record.FieldModelID: - v, ok := value.(uuid.UUID) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetModelID(v) - return nil - case record.FieldTaskID: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetTaskID(v) - return nil - case record.FieldModelType: - v, ok := value.(consts.ModelType) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetModelType(v) - return nil - case record.FieldPrompt: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetPrompt(v) - return nil - case record.FieldCompletion: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetCompletion(v) - return nil - case record.FieldIsAccept: - v, ok := value.(bool) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetIsAccept(v) - return nil - case record.FieldProgramLanguage: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetProgramLanguage(v) - return nil - case record.FieldWorkMode: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetWorkMode(v) - return nil - case record.FieldCodeLines: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetCodeLines(v) - return nil - case record.FieldInputTokens: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetInputTokens(v) - return nil - case record.FieldOutputTokens: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetOutputTokens(v) - return nil - case record.FieldCreatedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetCreatedAt(v) - return nil - case record.FieldUpdatedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetUpdatedAt(v) - return nil - } - return fmt.Errorf("unknown Record field %s", name) -} - -// AddedFields returns all numeric fields that were incremented/decremented during -// this mutation. -func (m *RecordMutation) AddedFields() []string { - var fields []string - if m.addcode_lines != nil { - fields = append(fields, record.FieldCodeLines) - } - if m.addinput_tokens != nil { - fields = append(fields, record.FieldInputTokens) - } - if m.addoutput_tokens != nil { - fields = append(fields, record.FieldOutputTokens) - } - return fields -} - -// AddedField returns the numeric value that was incremented/decremented on a field -// with the given name. The second boolean return value indicates that this field -// was not set, or was not defined in the schema. -func (m *RecordMutation) AddedField(name string) (ent.Value, bool) { - switch name { - case record.FieldCodeLines: - return m.AddedCodeLines() - case record.FieldInputTokens: - return m.AddedInputTokens() - case record.FieldOutputTokens: - return m.AddedOutputTokens() - } - return nil, false -} - -// AddField adds the value to the field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *RecordMutation) AddField(name string, value ent.Value) error { - switch name { - case record.FieldCodeLines: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddCodeLines(v) - return nil - case record.FieldInputTokens: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddInputTokens(v) - return nil - case record.FieldOutputTokens: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddOutputTokens(v) - return nil - } - return fmt.Errorf("unknown Record numeric field %s", name) -} - -// ClearedFields returns all nullable fields that were cleared during this -// mutation. -func (m *RecordMutation) ClearedFields() []string { - var fields []string - if m.FieldCleared(record.FieldUserID) { - fields = append(fields, record.FieldUserID) - } - if m.FieldCleared(record.FieldModelID) { - fields = append(fields, record.FieldModelID) - } - if m.FieldCleared(record.FieldModelType) { - fields = append(fields, record.FieldModelType) - } - if m.FieldCleared(record.FieldPrompt) { - fields = append(fields, record.FieldPrompt) - } - if m.FieldCleared(record.FieldCompletion) { - fields = append(fields, record.FieldCompletion) - } - if m.FieldCleared(record.FieldProgramLanguage) { - fields = append(fields, record.FieldProgramLanguage) - } - if m.FieldCleared(record.FieldWorkMode) { - fields = append(fields, record.FieldWorkMode) - } - if m.FieldCleared(record.FieldCodeLines) { - fields = append(fields, record.FieldCodeLines) - } - return fields -} - -// FieldCleared returns a boolean indicating if a field with the given name was -// cleared in this mutation. -func (m *RecordMutation) FieldCleared(name string) bool { - _, ok := m.clearedFields[name] - return ok -} - -// ClearField clears the value of the field with the given name. It returns an -// error if the field is not defined in the schema. -func (m *RecordMutation) ClearField(name string) error { - switch name { - case record.FieldUserID: - m.ClearUserID() - return nil - case record.FieldModelID: - m.ClearModelID() - return nil - case record.FieldModelType: - m.ClearModelType() - return nil - case record.FieldPrompt: - m.ClearPrompt() - return nil - case record.FieldCompletion: - m.ClearCompletion() - return nil - case record.FieldProgramLanguage: - m.ClearProgramLanguage() - return nil - case record.FieldWorkMode: - m.ClearWorkMode() - return nil - case record.FieldCodeLines: - m.ClearCodeLines() - return nil - } - return fmt.Errorf("unknown Record nullable field %s", name) -} - -// ResetField resets all changes in the mutation for the field with the given name. -// It returns an error if the field is not defined in the schema. -func (m *RecordMutation) ResetField(name string) error { - switch name { - case record.FieldUserID: - m.ResetUserID() - return nil - case record.FieldModelID: - m.ResetModelID() - return nil - case record.FieldTaskID: - m.ResetTaskID() - return nil - case record.FieldModelType: - m.ResetModelType() - return nil - case record.FieldPrompt: - m.ResetPrompt() - return nil - case record.FieldCompletion: - m.ResetCompletion() - return nil - case record.FieldIsAccept: - m.ResetIsAccept() - return nil - case record.FieldProgramLanguage: - m.ResetProgramLanguage() - return nil - case record.FieldWorkMode: - m.ResetWorkMode() - return nil - case record.FieldCodeLines: - m.ResetCodeLines() - return nil - case record.FieldInputTokens: - m.ResetInputTokens() - return nil - case record.FieldOutputTokens: - m.ResetOutputTokens() - return nil - case record.FieldCreatedAt: - m.ResetCreatedAt() - return nil - case record.FieldUpdatedAt: - m.ResetUpdatedAt() - return nil - } - return fmt.Errorf("unknown Record field %s", name) -} - -// AddedEdges returns all edge names that were set/added in this mutation. -func (m *RecordMutation) AddedEdges() []string { - edges := make([]string, 0, 2) - if m.user != nil { - edges = append(edges, record.EdgeUser) - } - if m.model != nil { - edges = append(edges, record.EdgeModel) - } - return edges -} - -// AddedIDs returns all IDs (to other nodes) that were added for the given edge -// name in this mutation. -func (m *RecordMutation) AddedIDs(name string) []ent.Value { - switch name { - case record.EdgeUser: - if id := m.user; id != nil { - return []ent.Value{*id} - } - case record.EdgeModel: - if id := m.model; id != nil { - return []ent.Value{*id} - } - } - return nil -} - -// RemovedEdges returns all edge names that were removed in this mutation. -func (m *RecordMutation) RemovedEdges() []string { - edges := make([]string, 0, 2) - return edges -} - -// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with -// the given name in this mutation. -func (m *RecordMutation) RemovedIDs(name string) []ent.Value { - return nil -} - -// ClearedEdges returns all edge names that were cleared in this mutation. -func (m *RecordMutation) ClearedEdges() []string { - edges := make([]string, 0, 2) - if m.cleareduser { - edges = append(edges, record.EdgeUser) - } - if m.clearedmodel { - edges = append(edges, record.EdgeModel) - } - return edges -} - -// EdgeCleared returns a boolean which indicates if the edge with the given name -// was cleared in this mutation. -func (m *RecordMutation) EdgeCleared(name string) bool { - switch name { - case record.EdgeUser: - return m.cleareduser - case record.EdgeModel: - return m.clearedmodel - } - return false -} - -// ClearEdge clears the value of the edge with the given name. It returns an error -// if that edge is not defined in the schema. -func (m *RecordMutation) ClearEdge(name string) error { - switch name { - case record.EdgeUser: - m.ClearUser() - return nil - case record.EdgeModel: - m.ClearModel() - return nil - } - return fmt.Errorf("unknown Record unique edge %s", name) -} - -// ResetEdge resets all changes to the edge with the given name in this mutation. -// It returns an error if the edge is not defined in the schema. -func (m *RecordMutation) ResetEdge(name string) error { - switch name { - case record.EdgeUser: - m.ResetUser() - return nil - case record.EdgeModel: - m.ResetModel() - return nil - } - return fmt.Errorf("unknown Record edge %s", name) -} - // SettingMutation represents an operation that mutates the Setting nodes in the graph. type SettingMutation struct { config @@ -8942,6 +7552,2237 @@ func (m *SettingMutation) ResetEdge(name string) error { return fmt.Errorf("unknown Setting edge %s", name) } +// TaskMutation represents an operation that mutates the Task nodes in the graph. +type TaskMutation struct { + config + op Op + typ string + id *uuid.UUID + task_id *string + request_id *string + model_type *consts.ModelType + prompt *string + is_accept *bool + program_language *string + work_mode *string + completion *string + code_lines *int64 + addcode_lines *int64 + input_tokens *int64 + addinput_tokens *int64 + output_tokens *int64 + addoutput_tokens *int64 + created_at *time.Time + updated_at *time.Time + clearedFields map[string]struct{} + task_records map[uuid.UUID]struct{} + removedtask_records map[uuid.UUID]struct{} + clearedtask_records bool + user *uuid.UUID + cleareduser bool + model *uuid.UUID + clearedmodel bool + done bool + oldValue func(context.Context) (*Task, error) + predicates []predicate.Task +} + +var _ ent.Mutation = (*TaskMutation)(nil) + +// taskOption allows management of the mutation configuration using functional options. +type taskOption func(*TaskMutation) + +// newTaskMutation creates new mutation for the Task entity. +func newTaskMutation(c config, op Op, opts ...taskOption) *TaskMutation { + m := &TaskMutation{ + config: c, + op: op, + typ: TypeTask, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withTaskID sets the ID field of the mutation. +func withTaskID(id uuid.UUID) taskOption { + return func(m *TaskMutation) { + var ( + err error + once sync.Once + value *Task + ) + m.oldValue = func(ctx context.Context) (*Task, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Task.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withTask sets the old Task of the mutation. +func withTask(node *Task) taskOption { + return func(m *TaskMutation) { + m.oldValue = func(context.Context) (*Task, 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 TaskMutation) 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 TaskMutation) 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 Task entities. +func (m *TaskMutation) 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 *TaskMutation) 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 *TaskMutation) 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().Task.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetTaskID sets the "task_id" field. +func (m *TaskMutation) SetTaskID(s string) { + m.task_id = &s +} + +// TaskID returns the value of the "task_id" field in the mutation. +func (m *TaskMutation) TaskID() (r string, exists bool) { + v := m.task_id + if v == nil { + return + } + return *v, true +} + +// OldTaskID returns the old "task_id" field's value of the Task entity. +// If the Task 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 *TaskMutation) OldTaskID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTaskID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTaskID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTaskID: %w", err) + } + return oldValue.TaskID, nil +} + +// ResetTaskID resets all changes to the "task_id" field. +func (m *TaskMutation) ResetTaskID() { + m.task_id = nil +} + +// SetUserID sets the "user_id" field. +func (m *TaskMutation) SetUserID(u uuid.UUID) { + m.user = &u +} + +// UserID returns the value of the "user_id" field in the mutation. +func (m *TaskMutation) UserID() (r uuid.UUID, exists bool) { + v := m.user + if v == nil { + return + } + return *v, true +} + +// OldUserID returns the old "user_id" field's value of the Task entity. +// If the Task 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 *TaskMutation) OldUserID(ctx context.Context) (v uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUserID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUserID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUserID: %w", err) + } + return oldValue.UserID, nil +} + +// ClearUserID clears the value of the "user_id" field. +func (m *TaskMutation) ClearUserID() { + m.user = nil + m.clearedFields[task.FieldUserID] = struct{}{} +} + +// UserIDCleared returns if the "user_id" field was cleared in this mutation. +func (m *TaskMutation) UserIDCleared() bool { + _, ok := m.clearedFields[task.FieldUserID] + return ok +} + +// ResetUserID resets all changes to the "user_id" field. +func (m *TaskMutation) ResetUserID() { + m.user = nil + delete(m.clearedFields, task.FieldUserID) +} + +// SetModelID sets the "model_id" field. +func (m *TaskMutation) SetModelID(u uuid.UUID) { + m.model = &u +} + +// ModelID returns the value of the "model_id" field in the mutation. +func (m *TaskMutation) ModelID() (r uuid.UUID, exists bool) { + v := m.model + if v == nil { + return + } + return *v, true +} + +// OldModelID returns the old "model_id" field's value of the Task entity. +// If the Task 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 *TaskMutation) OldModelID(ctx context.Context) (v uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldModelID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldModelID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldModelID: %w", err) + } + return oldValue.ModelID, nil +} + +// ClearModelID clears the value of the "model_id" field. +func (m *TaskMutation) ClearModelID() { + m.model = nil + m.clearedFields[task.FieldModelID] = struct{}{} +} + +// ModelIDCleared returns if the "model_id" field was cleared in this mutation. +func (m *TaskMutation) ModelIDCleared() bool { + _, ok := m.clearedFields[task.FieldModelID] + return ok +} + +// ResetModelID resets all changes to the "model_id" field. +func (m *TaskMutation) ResetModelID() { + m.model = nil + delete(m.clearedFields, task.FieldModelID) +} + +// SetRequestID sets the "request_id" field. +func (m *TaskMutation) SetRequestID(s string) { + m.request_id = &s +} + +// RequestID returns the value of the "request_id" field in the mutation. +func (m *TaskMutation) RequestID() (r string, exists bool) { + v := m.request_id + if v == nil { + return + } + return *v, true +} + +// OldRequestID returns the old "request_id" field's value of the Task entity. +// If the Task 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 *TaskMutation) OldRequestID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRequestID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRequestID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRequestID: %w", err) + } + return oldValue.RequestID, nil +} + +// ClearRequestID clears the value of the "request_id" field. +func (m *TaskMutation) ClearRequestID() { + m.request_id = nil + m.clearedFields[task.FieldRequestID] = struct{}{} +} + +// RequestIDCleared returns if the "request_id" field was cleared in this mutation. +func (m *TaskMutation) RequestIDCleared() bool { + _, ok := m.clearedFields[task.FieldRequestID] + return ok +} + +// ResetRequestID resets all changes to the "request_id" field. +func (m *TaskMutation) ResetRequestID() { + m.request_id = nil + delete(m.clearedFields, task.FieldRequestID) +} + +// SetModelType sets the "model_type" field. +func (m *TaskMutation) SetModelType(ct consts.ModelType) { + m.model_type = &ct +} + +// ModelType returns the value of the "model_type" field in the mutation. +func (m *TaskMutation) ModelType() (r consts.ModelType, exists bool) { + v := m.model_type + if v == nil { + return + } + return *v, true +} + +// OldModelType returns the old "model_type" field's value of the Task entity. +// If the Task 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 *TaskMutation) OldModelType(ctx context.Context) (v consts.ModelType, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldModelType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldModelType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldModelType: %w", err) + } + return oldValue.ModelType, nil +} + +// ResetModelType resets all changes to the "model_type" field. +func (m *TaskMutation) ResetModelType() { + m.model_type = nil +} + +// SetPrompt sets the "prompt" field. +func (m *TaskMutation) SetPrompt(s string) { + m.prompt = &s +} + +// Prompt returns the value of the "prompt" field in the mutation. +func (m *TaskMutation) Prompt() (r string, exists bool) { + v := m.prompt + if v == nil { + return + } + return *v, true +} + +// OldPrompt returns the old "prompt" field's value of the Task entity. +// If the Task 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 *TaskMutation) OldPrompt(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPrompt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPrompt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPrompt: %w", err) + } + return oldValue.Prompt, nil +} + +// ClearPrompt clears the value of the "prompt" field. +func (m *TaskMutation) ClearPrompt() { + m.prompt = nil + m.clearedFields[task.FieldPrompt] = struct{}{} +} + +// PromptCleared returns if the "prompt" field was cleared in this mutation. +func (m *TaskMutation) PromptCleared() bool { + _, ok := m.clearedFields[task.FieldPrompt] + return ok +} + +// ResetPrompt resets all changes to the "prompt" field. +func (m *TaskMutation) ResetPrompt() { + m.prompt = nil + delete(m.clearedFields, task.FieldPrompt) +} + +// SetIsAccept sets the "is_accept" field. +func (m *TaskMutation) SetIsAccept(b bool) { + m.is_accept = &b +} + +// IsAccept returns the value of the "is_accept" field in the mutation. +func (m *TaskMutation) IsAccept() (r bool, exists bool) { + v := m.is_accept + if v == nil { + return + } + return *v, true +} + +// OldIsAccept returns the old "is_accept" field's value of the Task entity. +// If the Task 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 *TaskMutation) OldIsAccept(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldIsAccept is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldIsAccept requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldIsAccept: %w", err) + } + return oldValue.IsAccept, nil +} + +// ResetIsAccept resets all changes to the "is_accept" field. +func (m *TaskMutation) ResetIsAccept() { + m.is_accept = nil +} + +// SetProgramLanguage sets the "program_language" field. +func (m *TaskMutation) SetProgramLanguage(s string) { + m.program_language = &s +} + +// ProgramLanguage returns the value of the "program_language" field in the mutation. +func (m *TaskMutation) ProgramLanguage() (r string, exists bool) { + v := m.program_language + if v == nil { + return + } + return *v, true +} + +// OldProgramLanguage returns the old "program_language" field's value of the Task entity. +// If the Task 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 *TaskMutation) OldProgramLanguage(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldProgramLanguage is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldProgramLanguage requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldProgramLanguage: %w", err) + } + return oldValue.ProgramLanguage, nil +} + +// ClearProgramLanguage clears the value of the "program_language" field. +func (m *TaskMutation) ClearProgramLanguage() { + m.program_language = nil + m.clearedFields[task.FieldProgramLanguage] = struct{}{} +} + +// ProgramLanguageCleared returns if the "program_language" field was cleared in this mutation. +func (m *TaskMutation) ProgramLanguageCleared() bool { + _, ok := m.clearedFields[task.FieldProgramLanguage] + return ok +} + +// ResetProgramLanguage resets all changes to the "program_language" field. +func (m *TaskMutation) ResetProgramLanguage() { + m.program_language = nil + delete(m.clearedFields, task.FieldProgramLanguage) +} + +// SetWorkMode sets the "work_mode" field. +func (m *TaskMutation) SetWorkMode(s string) { + m.work_mode = &s +} + +// WorkMode returns the value of the "work_mode" field in the mutation. +func (m *TaskMutation) WorkMode() (r string, exists bool) { + v := m.work_mode + if v == nil { + return + } + return *v, true +} + +// OldWorkMode returns the old "work_mode" field's value of the Task entity. +// If the Task 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 *TaskMutation) OldWorkMode(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldWorkMode is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldWorkMode requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldWorkMode: %w", err) + } + return oldValue.WorkMode, nil +} + +// ClearWorkMode clears the value of the "work_mode" field. +func (m *TaskMutation) ClearWorkMode() { + m.work_mode = nil + m.clearedFields[task.FieldWorkMode] = struct{}{} +} + +// WorkModeCleared returns if the "work_mode" field was cleared in this mutation. +func (m *TaskMutation) WorkModeCleared() bool { + _, ok := m.clearedFields[task.FieldWorkMode] + return ok +} + +// ResetWorkMode resets all changes to the "work_mode" field. +func (m *TaskMutation) ResetWorkMode() { + m.work_mode = nil + delete(m.clearedFields, task.FieldWorkMode) +} + +// SetCompletion sets the "completion" field. +func (m *TaskMutation) SetCompletion(s string) { + m.completion = &s +} + +// Completion returns the value of the "completion" field in the mutation. +func (m *TaskMutation) Completion() (r string, exists bool) { + v := m.completion + if v == nil { + return + } + return *v, true +} + +// OldCompletion returns the old "completion" field's value of the Task entity. +// If the Task 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 *TaskMutation) OldCompletion(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCompletion is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCompletion requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCompletion: %w", err) + } + return oldValue.Completion, nil +} + +// ClearCompletion clears the value of the "completion" field. +func (m *TaskMutation) ClearCompletion() { + m.completion = nil + m.clearedFields[task.FieldCompletion] = struct{}{} +} + +// CompletionCleared returns if the "completion" field was cleared in this mutation. +func (m *TaskMutation) CompletionCleared() bool { + _, ok := m.clearedFields[task.FieldCompletion] + return ok +} + +// ResetCompletion resets all changes to the "completion" field. +func (m *TaskMutation) ResetCompletion() { + m.completion = nil + delete(m.clearedFields, task.FieldCompletion) +} + +// SetCodeLines sets the "code_lines" field. +func (m *TaskMutation) SetCodeLines(i int64) { + m.code_lines = &i + m.addcode_lines = nil +} + +// CodeLines returns the value of the "code_lines" field in the mutation. +func (m *TaskMutation) CodeLines() (r int64, exists bool) { + v := m.code_lines + if v == nil { + return + } + return *v, true +} + +// OldCodeLines returns the old "code_lines" field's value of the Task entity. +// If the Task 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 *TaskMutation) OldCodeLines(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCodeLines is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCodeLines requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCodeLines: %w", err) + } + return oldValue.CodeLines, nil +} + +// AddCodeLines adds i to the "code_lines" field. +func (m *TaskMutation) AddCodeLines(i int64) { + if m.addcode_lines != nil { + *m.addcode_lines += i + } else { + m.addcode_lines = &i + } +} + +// AddedCodeLines returns the value that was added to the "code_lines" field in this mutation. +func (m *TaskMutation) AddedCodeLines() (r int64, exists bool) { + v := m.addcode_lines + if v == nil { + return + } + return *v, true +} + +// ClearCodeLines clears the value of the "code_lines" field. +func (m *TaskMutation) ClearCodeLines() { + m.code_lines = nil + m.addcode_lines = nil + m.clearedFields[task.FieldCodeLines] = struct{}{} +} + +// CodeLinesCleared returns if the "code_lines" field was cleared in this mutation. +func (m *TaskMutation) CodeLinesCleared() bool { + _, ok := m.clearedFields[task.FieldCodeLines] + return ok +} + +// ResetCodeLines resets all changes to the "code_lines" field. +func (m *TaskMutation) ResetCodeLines() { + m.code_lines = nil + m.addcode_lines = nil + delete(m.clearedFields, task.FieldCodeLines) +} + +// SetInputTokens sets the "input_tokens" field. +func (m *TaskMutation) SetInputTokens(i int64) { + m.input_tokens = &i + m.addinput_tokens = nil +} + +// InputTokens returns the value of the "input_tokens" field in the mutation. +func (m *TaskMutation) InputTokens() (r int64, exists bool) { + v := m.input_tokens + if v == nil { + return + } + return *v, true +} + +// OldInputTokens returns the old "input_tokens" field's value of the Task entity. +// If the Task 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 *TaskMutation) OldInputTokens(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInputTokens is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInputTokens requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInputTokens: %w", err) + } + return oldValue.InputTokens, nil +} + +// AddInputTokens adds i to the "input_tokens" field. +func (m *TaskMutation) AddInputTokens(i int64) { + if m.addinput_tokens != nil { + *m.addinput_tokens += i + } else { + m.addinput_tokens = &i + } +} + +// AddedInputTokens returns the value that was added to the "input_tokens" field in this mutation. +func (m *TaskMutation) AddedInputTokens() (r int64, exists bool) { + v := m.addinput_tokens + if v == nil { + return + } + return *v, true +} + +// ClearInputTokens clears the value of the "input_tokens" field. +func (m *TaskMutation) ClearInputTokens() { + m.input_tokens = nil + m.addinput_tokens = nil + m.clearedFields[task.FieldInputTokens] = struct{}{} +} + +// InputTokensCleared returns if the "input_tokens" field was cleared in this mutation. +func (m *TaskMutation) InputTokensCleared() bool { + _, ok := m.clearedFields[task.FieldInputTokens] + return ok +} + +// ResetInputTokens resets all changes to the "input_tokens" field. +func (m *TaskMutation) ResetInputTokens() { + m.input_tokens = nil + m.addinput_tokens = nil + delete(m.clearedFields, task.FieldInputTokens) +} + +// SetOutputTokens sets the "output_tokens" field. +func (m *TaskMutation) SetOutputTokens(i int64) { + m.output_tokens = &i + m.addoutput_tokens = nil +} + +// OutputTokens returns the value of the "output_tokens" field in the mutation. +func (m *TaskMutation) OutputTokens() (r int64, exists bool) { + v := m.output_tokens + if v == nil { + return + } + return *v, true +} + +// OldOutputTokens returns the old "output_tokens" field's value of the Task entity. +// If the Task 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 *TaskMutation) OldOutputTokens(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldOutputTokens is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldOutputTokens requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldOutputTokens: %w", err) + } + return oldValue.OutputTokens, nil +} + +// AddOutputTokens adds i to the "output_tokens" field. +func (m *TaskMutation) AddOutputTokens(i int64) { + if m.addoutput_tokens != nil { + *m.addoutput_tokens += i + } else { + m.addoutput_tokens = &i + } +} + +// AddedOutputTokens returns the value that was added to the "output_tokens" field in this mutation. +func (m *TaskMutation) AddedOutputTokens() (r int64, exists bool) { + v := m.addoutput_tokens + if v == nil { + return + } + return *v, true +} + +// ClearOutputTokens clears the value of the "output_tokens" field. +func (m *TaskMutation) ClearOutputTokens() { + m.output_tokens = nil + m.addoutput_tokens = nil + m.clearedFields[task.FieldOutputTokens] = struct{}{} +} + +// OutputTokensCleared returns if the "output_tokens" field was cleared in this mutation. +func (m *TaskMutation) OutputTokensCleared() bool { + _, ok := m.clearedFields[task.FieldOutputTokens] + return ok +} + +// ResetOutputTokens resets all changes to the "output_tokens" field. +func (m *TaskMutation) ResetOutputTokens() { + m.output_tokens = nil + m.addoutput_tokens = nil + delete(m.clearedFields, task.FieldOutputTokens) +} + +// SetCreatedAt sets the "created_at" field. +func (m *TaskMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *TaskMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at + if v == nil { + return + } + return *v, true +} + +// OldCreatedAt returns the old "created_at" field's value of the Task entity. +// If the Task 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 *TaskMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) + } + return oldValue.CreatedAt, nil +} + +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *TaskMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *TaskMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *TaskMutation) UpdatedAt() (r time.Time, exists bool) { + v := m.updated_at + if v == nil { + return + } + return *v, true +} + +// OldUpdatedAt returns the old "updated_at" field's value of the Task entity. +// If the Task 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 *TaskMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUpdatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) + } + return oldValue.UpdatedAt, nil +} + +// ResetUpdatedAt resets all changes to the "updated_at" field. +func (m *TaskMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// AddTaskRecordIDs adds the "task_records" edge to the TaskRecord entity by ids. +func (m *TaskMutation) AddTaskRecordIDs(ids ...uuid.UUID) { + if m.task_records == nil { + m.task_records = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.task_records[ids[i]] = struct{}{} + } +} + +// ClearTaskRecords clears the "task_records" edge to the TaskRecord entity. +func (m *TaskMutation) ClearTaskRecords() { + m.clearedtask_records = true +} + +// TaskRecordsCleared reports if the "task_records" edge to the TaskRecord entity was cleared. +func (m *TaskMutation) TaskRecordsCleared() bool { + return m.clearedtask_records +} + +// RemoveTaskRecordIDs removes the "task_records" edge to the TaskRecord entity by IDs. +func (m *TaskMutation) RemoveTaskRecordIDs(ids ...uuid.UUID) { + if m.removedtask_records == nil { + m.removedtask_records = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.task_records, ids[i]) + m.removedtask_records[ids[i]] = struct{}{} + } +} + +// RemovedTaskRecords returns the removed IDs of the "task_records" edge to the TaskRecord entity. +func (m *TaskMutation) RemovedTaskRecordsIDs() (ids []uuid.UUID) { + for id := range m.removedtask_records { + ids = append(ids, id) + } + return +} + +// TaskRecordsIDs returns the "task_records" edge IDs in the mutation. +func (m *TaskMutation) TaskRecordsIDs() (ids []uuid.UUID) { + for id := range m.task_records { + ids = append(ids, id) + } + return +} + +// ResetTaskRecords resets all changes to the "task_records" edge. +func (m *TaskMutation) ResetTaskRecords() { + m.task_records = nil + m.clearedtask_records = false + m.removedtask_records = nil +} + +// ClearUser clears the "user" edge to the User entity. +func (m *TaskMutation) ClearUser() { + m.cleareduser = true + m.clearedFields[task.FieldUserID] = struct{}{} +} + +// UserCleared reports if the "user" edge to the User entity was cleared. +func (m *TaskMutation) UserCleared() bool { + return m.UserIDCleared() || m.cleareduser +} + +// UserIDs returns the "user" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// UserID instead. It exists only for internal usage by the builders. +func (m *TaskMutation) UserIDs() (ids []uuid.UUID) { + if id := m.user; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetUser resets all changes to the "user" edge. +func (m *TaskMutation) ResetUser() { + m.user = nil + m.cleareduser = false +} + +// ClearModel clears the "model" edge to the Model entity. +func (m *TaskMutation) ClearModel() { + m.clearedmodel = true + m.clearedFields[task.FieldModelID] = struct{}{} +} + +// ModelCleared reports if the "model" edge to the Model entity was cleared. +func (m *TaskMutation) ModelCleared() bool { + return m.ModelIDCleared() || m.clearedmodel +} + +// ModelIDs returns the "model" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// ModelID instead. It exists only for internal usage by the builders. +func (m *TaskMutation) ModelIDs() (ids []uuid.UUID) { + if id := m.model; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetModel resets all changes to the "model" edge. +func (m *TaskMutation) ResetModel() { + m.model = nil + m.clearedmodel = false +} + +// Where appends a list predicates to the TaskMutation builder. +func (m *TaskMutation) Where(ps ...predicate.Task) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the TaskMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *TaskMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Task, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *TaskMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *TaskMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Task). +func (m *TaskMutation) 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 *TaskMutation) Fields() []string { + fields := make([]string, 0, 15) + if m.task_id != nil { + fields = append(fields, task.FieldTaskID) + } + if m.user != nil { + fields = append(fields, task.FieldUserID) + } + if m.model != nil { + fields = append(fields, task.FieldModelID) + } + if m.request_id != nil { + fields = append(fields, task.FieldRequestID) + } + if m.model_type != nil { + fields = append(fields, task.FieldModelType) + } + if m.prompt != nil { + fields = append(fields, task.FieldPrompt) + } + if m.is_accept != nil { + fields = append(fields, task.FieldIsAccept) + } + if m.program_language != nil { + fields = append(fields, task.FieldProgramLanguage) + } + if m.work_mode != nil { + fields = append(fields, task.FieldWorkMode) + } + if m.completion != nil { + fields = append(fields, task.FieldCompletion) + } + if m.code_lines != nil { + fields = append(fields, task.FieldCodeLines) + } + if m.input_tokens != nil { + fields = append(fields, task.FieldInputTokens) + } + if m.output_tokens != nil { + fields = append(fields, task.FieldOutputTokens) + } + if m.created_at != nil { + fields = append(fields, task.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, task.FieldUpdatedAt) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *TaskMutation) Field(name string) (ent.Value, bool) { + switch name { + case task.FieldTaskID: + return m.TaskID() + case task.FieldUserID: + return m.UserID() + case task.FieldModelID: + return m.ModelID() + case task.FieldRequestID: + return m.RequestID() + case task.FieldModelType: + return m.ModelType() + case task.FieldPrompt: + return m.Prompt() + case task.FieldIsAccept: + return m.IsAccept() + case task.FieldProgramLanguage: + return m.ProgramLanguage() + case task.FieldWorkMode: + return m.WorkMode() + case task.FieldCompletion: + return m.Completion() + case task.FieldCodeLines: + return m.CodeLines() + case task.FieldInputTokens: + return m.InputTokens() + case task.FieldOutputTokens: + return m.OutputTokens() + case task.FieldCreatedAt: + return m.CreatedAt() + case task.FieldUpdatedAt: + return m.UpdatedAt() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *TaskMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case task.FieldTaskID: + return m.OldTaskID(ctx) + case task.FieldUserID: + return m.OldUserID(ctx) + case task.FieldModelID: + return m.OldModelID(ctx) + case task.FieldRequestID: + return m.OldRequestID(ctx) + case task.FieldModelType: + return m.OldModelType(ctx) + case task.FieldPrompt: + return m.OldPrompt(ctx) + case task.FieldIsAccept: + return m.OldIsAccept(ctx) + case task.FieldProgramLanguage: + return m.OldProgramLanguage(ctx) + case task.FieldWorkMode: + return m.OldWorkMode(ctx) + case task.FieldCompletion: + return m.OldCompletion(ctx) + case task.FieldCodeLines: + return m.OldCodeLines(ctx) + case task.FieldInputTokens: + return m.OldInputTokens(ctx) + case task.FieldOutputTokens: + return m.OldOutputTokens(ctx) + case task.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case task.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + } + return nil, fmt.Errorf("unknown Task 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 *TaskMutation) SetField(name string, value ent.Value) error { + switch name { + case task.FieldTaskID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTaskID(v) + return nil + case task.FieldUserID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUserID(v) + return nil + case task.FieldModelID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetModelID(v) + return nil + case task.FieldRequestID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRequestID(v) + return nil + case task.FieldModelType: + v, ok := value.(consts.ModelType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetModelType(v) + return nil + case task.FieldPrompt: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPrompt(v) + return nil + case task.FieldIsAccept: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIsAccept(v) + return nil + case task.FieldProgramLanguage: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetProgramLanguage(v) + return nil + case task.FieldWorkMode: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetWorkMode(v) + return nil + case task.FieldCompletion: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCompletion(v) + return nil + case task.FieldCodeLines: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCodeLines(v) + return nil + case task.FieldInputTokens: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInputTokens(v) + return nil + case task.FieldOutputTokens: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetOutputTokens(v) + return nil + case task.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + case task.FieldUpdatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdatedAt(v) + return nil + } + return fmt.Errorf("unknown Task field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *TaskMutation) AddedFields() []string { + var fields []string + if m.addcode_lines != nil { + fields = append(fields, task.FieldCodeLines) + } + if m.addinput_tokens != nil { + fields = append(fields, task.FieldInputTokens) + } + if m.addoutput_tokens != nil { + fields = append(fields, task.FieldOutputTokens) + } + return fields +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *TaskMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case task.FieldCodeLines: + return m.AddedCodeLines() + case task.FieldInputTokens: + return m.AddedInputTokens() + case task.FieldOutputTokens: + return m.AddedOutputTokens() + } + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *TaskMutation) AddField(name string, value ent.Value) error { + switch name { + case task.FieldCodeLines: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddCodeLines(v) + return nil + case task.FieldInputTokens: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddInputTokens(v) + return nil + case task.FieldOutputTokens: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddOutputTokens(v) + return nil + } + return fmt.Errorf("unknown Task numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *TaskMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(task.FieldUserID) { + fields = append(fields, task.FieldUserID) + } + if m.FieldCleared(task.FieldModelID) { + fields = append(fields, task.FieldModelID) + } + if m.FieldCleared(task.FieldRequestID) { + fields = append(fields, task.FieldRequestID) + } + if m.FieldCleared(task.FieldPrompt) { + fields = append(fields, task.FieldPrompt) + } + if m.FieldCleared(task.FieldProgramLanguage) { + fields = append(fields, task.FieldProgramLanguage) + } + if m.FieldCleared(task.FieldWorkMode) { + fields = append(fields, task.FieldWorkMode) + } + if m.FieldCleared(task.FieldCompletion) { + fields = append(fields, task.FieldCompletion) + } + if m.FieldCleared(task.FieldCodeLines) { + fields = append(fields, task.FieldCodeLines) + } + if m.FieldCleared(task.FieldInputTokens) { + fields = append(fields, task.FieldInputTokens) + } + if m.FieldCleared(task.FieldOutputTokens) { + fields = append(fields, task.FieldOutputTokens) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *TaskMutation) 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 *TaskMutation) ClearField(name string) error { + switch name { + case task.FieldUserID: + m.ClearUserID() + return nil + case task.FieldModelID: + m.ClearModelID() + return nil + case task.FieldRequestID: + m.ClearRequestID() + return nil + case task.FieldPrompt: + m.ClearPrompt() + return nil + case task.FieldProgramLanguage: + m.ClearProgramLanguage() + return nil + case task.FieldWorkMode: + m.ClearWorkMode() + return nil + case task.FieldCompletion: + m.ClearCompletion() + return nil + case task.FieldCodeLines: + m.ClearCodeLines() + return nil + case task.FieldInputTokens: + m.ClearInputTokens() + return nil + case task.FieldOutputTokens: + m.ClearOutputTokens() + return nil + } + return fmt.Errorf("unknown Task 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 *TaskMutation) ResetField(name string) error { + switch name { + case task.FieldTaskID: + m.ResetTaskID() + return nil + case task.FieldUserID: + m.ResetUserID() + return nil + case task.FieldModelID: + m.ResetModelID() + return nil + case task.FieldRequestID: + m.ResetRequestID() + return nil + case task.FieldModelType: + m.ResetModelType() + return nil + case task.FieldPrompt: + m.ResetPrompt() + return nil + case task.FieldIsAccept: + m.ResetIsAccept() + return nil + case task.FieldProgramLanguage: + m.ResetProgramLanguage() + return nil + case task.FieldWorkMode: + m.ResetWorkMode() + return nil + case task.FieldCompletion: + m.ResetCompletion() + return nil + case task.FieldCodeLines: + m.ResetCodeLines() + return nil + case task.FieldInputTokens: + m.ResetInputTokens() + return nil + case task.FieldOutputTokens: + m.ResetOutputTokens() + return nil + case task.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case task.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + } + return fmt.Errorf("unknown Task field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *TaskMutation) AddedEdges() []string { + edges := make([]string, 0, 3) + if m.task_records != nil { + edges = append(edges, task.EdgeTaskRecords) + } + if m.user != nil { + edges = append(edges, task.EdgeUser) + } + if m.model != nil { + edges = append(edges, task.EdgeModel) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *TaskMutation) AddedIDs(name string) []ent.Value { + switch name { + case task.EdgeTaskRecords: + ids := make([]ent.Value, 0, len(m.task_records)) + for id := range m.task_records { + ids = append(ids, id) + } + return ids + case task.EdgeUser: + if id := m.user; id != nil { + return []ent.Value{*id} + } + case task.EdgeModel: + if id := m.model; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *TaskMutation) RemovedEdges() []string { + edges := make([]string, 0, 3) + if m.removedtask_records != nil { + edges = append(edges, task.EdgeTaskRecords) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *TaskMutation) RemovedIDs(name string) []ent.Value { + switch name { + case task.EdgeTaskRecords: + ids := make([]ent.Value, 0, len(m.removedtask_records)) + for id := range m.removedtask_records { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *TaskMutation) ClearedEdges() []string { + edges := make([]string, 0, 3) + if m.clearedtask_records { + edges = append(edges, task.EdgeTaskRecords) + } + if m.cleareduser { + edges = append(edges, task.EdgeUser) + } + if m.clearedmodel { + edges = append(edges, task.EdgeModel) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *TaskMutation) EdgeCleared(name string) bool { + switch name { + case task.EdgeTaskRecords: + return m.clearedtask_records + case task.EdgeUser: + return m.cleareduser + case task.EdgeModel: + return m.clearedmodel + } + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *TaskMutation) ClearEdge(name string) error { + switch name { + case task.EdgeUser: + m.ClearUser() + return nil + case task.EdgeModel: + m.ClearModel() + return nil + } + return fmt.Errorf("unknown Task 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 *TaskMutation) ResetEdge(name string) error { + switch name { + case task.EdgeTaskRecords: + m.ResetTaskRecords() + return nil + case task.EdgeUser: + m.ResetUser() + return nil + case task.EdgeModel: + m.ResetModel() + return nil + } + return fmt.Errorf("unknown Task edge %s", name) +} + +// TaskRecordMutation represents an operation that mutates the TaskRecord nodes in the graph. +type TaskRecordMutation struct { + config + op Op + typ string + id *uuid.UUID + completion *string + output_tokens *int64 + addoutput_tokens *int64 + created_at *time.Time + updated_at *time.Time + clearedFields map[string]struct{} + task *uuid.UUID + clearedtask bool + done bool + oldValue func(context.Context) (*TaskRecord, error) + predicates []predicate.TaskRecord +} + +var _ ent.Mutation = (*TaskRecordMutation)(nil) + +// taskrecordOption allows management of the mutation configuration using functional options. +type taskrecordOption func(*TaskRecordMutation) + +// newTaskRecordMutation creates new mutation for the TaskRecord entity. +func newTaskRecordMutation(c config, op Op, opts ...taskrecordOption) *TaskRecordMutation { + m := &TaskRecordMutation{ + config: c, + op: op, + typ: TypeTaskRecord, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withTaskRecordID sets the ID field of the mutation. +func withTaskRecordID(id uuid.UUID) taskrecordOption { + return func(m *TaskRecordMutation) { + var ( + err error + once sync.Once + value *TaskRecord + ) + m.oldValue = func(ctx context.Context) (*TaskRecord, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().TaskRecord.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withTaskRecord sets the old TaskRecord of the mutation. +func withTaskRecord(node *TaskRecord) taskrecordOption { + return func(m *TaskRecordMutation) { + m.oldValue = func(context.Context) (*TaskRecord, 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 TaskRecordMutation) 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 TaskRecordMutation) 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 TaskRecord entities. +func (m *TaskRecordMutation) 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 *TaskRecordMutation) 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 *TaskRecordMutation) 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().TaskRecord.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetTaskID sets the "task_id" field. +func (m *TaskRecordMutation) SetTaskID(u uuid.UUID) { + m.task = &u +} + +// TaskID returns the value of the "task_id" field in the mutation. +func (m *TaskRecordMutation) TaskID() (r uuid.UUID, exists bool) { + v := m.task + if v == nil { + return + } + return *v, true +} + +// OldTaskID returns the old "task_id" field's value of the TaskRecord entity. +// If the TaskRecord 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 *TaskRecordMutation) OldTaskID(ctx context.Context) (v uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTaskID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTaskID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTaskID: %w", err) + } + return oldValue.TaskID, nil +} + +// ClearTaskID clears the value of the "task_id" field. +func (m *TaskRecordMutation) ClearTaskID() { + m.task = nil + m.clearedFields[taskrecord.FieldTaskID] = struct{}{} +} + +// TaskIDCleared returns if the "task_id" field was cleared in this mutation. +func (m *TaskRecordMutation) TaskIDCleared() bool { + _, ok := m.clearedFields[taskrecord.FieldTaskID] + return ok +} + +// ResetTaskID resets all changes to the "task_id" field. +func (m *TaskRecordMutation) ResetTaskID() { + m.task = nil + delete(m.clearedFields, taskrecord.FieldTaskID) +} + +// SetCompletion sets the "completion" field. +func (m *TaskRecordMutation) SetCompletion(s string) { + m.completion = &s +} + +// Completion returns the value of the "completion" field in the mutation. +func (m *TaskRecordMutation) Completion() (r string, exists bool) { + v := m.completion + if v == nil { + return + } + return *v, true +} + +// OldCompletion returns the old "completion" field's value of the TaskRecord entity. +// If the TaskRecord 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 *TaskRecordMutation) OldCompletion(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCompletion is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCompletion requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCompletion: %w", err) + } + return oldValue.Completion, nil +} + +// ResetCompletion resets all changes to the "completion" field. +func (m *TaskRecordMutation) ResetCompletion() { + m.completion = nil +} + +// SetOutputTokens sets the "output_tokens" field. +func (m *TaskRecordMutation) SetOutputTokens(i int64) { + m.output_tokens = &i + m.addoutput_tokens = nil +} + +// OutputTokens returns the value of the "output_tokens" field in the mutation. +func (m *TaskRecordMutation) OutputTokens() (r int64, exists bool) { + v := m.output_tokens + if v == nil { + return + } + return *v, true +} + +// OldOutputTokens returns the old "output_tokens" field's value of the TaskRecord entity. +// If the TaskRecord 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 *TaskRecordMutation) OldOutputTokens(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldOutputTokens is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldOutputTokens requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldOutputTokens: %w", err) + } + return oldValue.OutputTokens, nil +} + +// AddOutputTokens adds i to the "output_tokens" field. +func (m *TaskRecordMutation) AddOutputTokens(i int64) { + if m.addoutput_tokens != nil { + *m.addoutput_tokens += i + } else { + m.addoutput_tokens = &i + } +} + +// AddedOutputTokens returns the value that was added to the "output_tokens" field in this mutation. +func (m *TaskRecordMutation) AddedOutputTokens() (r int64, exists bool) { + v := m.addoutput_tokens + if v == nil { + return + } + return *v, true +} + +// ResetOutputTokens resets all changes to the "output_tokens" field. +func (m *TaskRecordMutation) ResetOutputTokens() { + m.output_tokens = nil + m.addoutput_tokens = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *TaskRecordMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *TaskRecordMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at + if v == nil { + return + } + return *v, true +} + +// OldCreatedAt returns the old "created_at" field's value of the TaskRecord entity. +// If the TaskRecord 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 *TaskRecordMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) + } + return oldValue.CreatedAt, nil +} + +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *TaskRecordMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *TaskRecordMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *TaskRecordMutation) UpdatedAt() (r time.Time, exists bool) { + v := m.updated_at + if v == nil { + return + } + return *v, true +} + +// OldUpdatedAt returns the old "updated_at" field's value of the TaskRecord entity. +// If the TaskRecord 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 *TaskRecordMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUpdatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) + } + return oldValue.UpdatedAt, nil +} + +// ResetUpdatedAt resets all changes to the "updated_at" field. +func (m *TaskRecordMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// ClearTask clears the "task" edge to the Task entity. +func (m *TaskRecordMutation) ClearTask() { + m.clearedtask = true + m.clearedFields[taskrecord.FieldTaskID] = struct{}{} +} + +// TaskCleared reports if the "task" edge to the Task entity was cleared. +func (m *TaskRecordMutation) TaskCleared() bool { + return m.TaskIDCleared() || m.clearedtask +} + +// TaskIDs returns the "task" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// TaskID instead. It exists only for internal usage by the builders. +func (m *TaskRecordMutation) TaskIDs() (ids []uuid.UUID) { + if id := m.task; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetTask resets all changes to the "task" edge. +func (m *TaskRecordMutation) ResetTask() { + m.task = nil + m.clearedtask = false +} + +// Where appends a list predicates to the TaskRecordMutation builder. +func (m *TaskRecordMutation) Where(ps ...predicate.TaskRecord) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the TaskRecordMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *TaskRecordMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.TaskRecord, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *TaskRecordMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *TaskRecordMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (TaskRecord). +func (m *TaskRecordMutation) 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 *TaskRecordMutation) Fields() []string { + fields := make([]string, 0, 5) + if m.task != nil { + fields = append(fields, taskrecord.FieldTaskID) + } + if m.completion != nil { + fields = append(fields, taskrecord.FieldCompletion) + } + if m.output_tokens != nil { + fields = append(fields, taskrecord.FieldOutputTokens) + } + if m.created_at != nil { + fields = append(fields, taskrecord.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, taskrecord.FieldUpdatedAt) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *TaskRecordMutation) Field(name string) (ent.Value, bool) { + switch name { + case taskrecord.FieldTaskID: + return m.TaskID() + case taskrecord.FieldCompletion: + return m.Completion() + case taskrecord.FieldOutputTokens: + return m.OutputTokens() + case taskrecord.FieldCreatedAt: + return m.CreatedAt() + case taskrecord.FieldUpdatedAt: + return m.UpdatedAt() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *TaskRecordMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case taskrecord.FieldTaskID: + return m.OldTaskID(ctx) + case taskrecord.FieldCompletion: + return m.OldCompletion(ctx) + case taskrecord.FieldOutputTokens: + return m.OldOutputTokens(ctx) + case taskrecord.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case taskrecord.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + } + return nil, fmt.Errorf("unknown TaskRecord 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 *TaskRecordMutation) SetField(name string, value ent.Value) error { + switch name { + case taskrecord.FieldTaskID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTaskID(v) + return nil + case taskrecord.FieldCompletion: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCompletion(v) + return nil + case taskrecord.FieldOutputTokens: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetOutputTokens(v) + return nil + case taskrecord.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + case taskrecord.FieldUpdatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdatedAt(v) + return nil + } + return fmt.Errorf("unknown TaskRecord field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *TaskRecordMutation) AddedFields() []string { + var fields []string + if m.addoutput_tokens != nil { + fields = append(fields, taskrecord.FieldOutputTokens) + } + return fields +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *TaskRecordMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case taskrecord.FieldOutputTokens: + return m.AddedOutputTokens() + } + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *TaskRecordMutation) AddField(name string, value ent.Value) error { + switch name { + case taskrecord.FieldOutputTokens: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddOutputTokens(v) + return nil + } + return fmt.Errorf("unknown TaskRecord numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *TaskRecordMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(taskrecord.FieldTaskID) { + fields = append(fields, taskrecord.FieldTaskID) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *TaskRecordMutation) 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 *TaskRecordMutation) ClearField(name string) error { + switch name { + case taskrecord.FieldTaskID: + m.ClearTaskID() + return nil + } + return fmt.Errorf("unknown TaskRecord 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 *TaskRecordMutation) ResetField(name string) error { + switch name { + case taskrecord.FieldTaskID: + m.ResetTaskID() + return nil + case taskrecord.FieldCompletion: + m.ResetCompletion() + return nil + case taskrecord.FieldOutputTokens: + m.ResetOutputTokens() + return nil + case taskrecord.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case taskrecord.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + } + return fmt.Errorf("unknown TaskRecord field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *TaskRecordMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.task != nil { + edges = append(edges, taskrecord.EdgeTask) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *TaskRecordMutation) AddedIDs(name string) []ent.Value { + switch name { + case taskrecord.EdgeTask: + if id := m.task; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *TaskRecordMutation) 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 *TaskRecordMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *TaskRecordMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedtask { + edges = append(edges, taskrecord.EdgeTask) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *TaskRecordMutation) EdgeCleared(name string) bool { + switch name { + case taskrecord.EdgeTask: + return m.clearedtask + } + 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 *TaskRecordMutation) ClearEdge(name string) error { + switch name { + case taskrecord.EdgeTask: + m.ClearTask() + return nil + } + return fmt.Errorf("unknown TaskRecord 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 *TaskRecordMutation) ResetEdge(name string) error { + switch name { + case taskrecord.EdgeTask: + m.ResetTask() + return nil + } + return fmt.Errorf("unknown TaskRecord edge %s", name) +} + // UserMutation represents an operation that mutates the User nodes in the graph. type UserMutation struct { config @@ -8955,15 +9796,15 @@ type UserMutation struct { created_at *time.Time updated_at *time.Time clearedFields map[string]struct{} - records map[uuid.UUID]struct{} - removedrecords map[uuid.UUID]struct{} - clearedrecords bool login_histories map[uuid.UUID]struct{} removedlogin_histories map[uuid.UUID]struct{} clearedlogin_histories bool models map[uuid.UUID]struct{} removedmodels map[uuid.UUID]struct{} clearedmodels bool + tasks map[uuid.UUID]struct{} + removedtasks map[uuid.UUID]struct{} + clearedtasks bool done bool oldValue func(context.Context) (*User, error) predicates []predicate.User @@ -9289,60 +10130,6 @@ func (m *UserMutation) ResetUpdatedAt() { m.updated_at = nil } -// AddRecordIDs adds the "records" edge to the Record entity by ids. -func (m *UserMutation) AddRecordIDs(ids ...uuid.UUID) { - if m.records == nil { - m.records = make(map[uuid.UUID]struct{}) - } - for i := range ids { - m.records[ids[i]] = struct{}{} - } -} - -// ClearRecords clears the "records" edge to the Record entity. -func (m *UserMutation) ClearRecords() { - m.clearedrecords = true -} - -// RecordsCleared reports if the "records" edge to the Record entity was cleared. -func (m *UserMutation) RecordsCleared() bool { - return m.clearedrecords -} - -// RemoveRecordIDs removes the "records" edge to the Record entity by IDs. -func (m *UserMutation) RemoveRecordIDs(ids ...uuid.UUID) { - if m.removedrecords == nil { - m.removedrecords = make(map[uuid.UUID]struct{}) - } - for i := range ids { - delete(m.records, ids[i]) - m.removedrecords[ids[i]] = struct{}{} - } -} - -// RemovedRecords returns the removed IDs of the "records" edge to the Record entity. -func (m *UserMutation) RemovedRecordsIDs() (ids []uuid.UUID) { - for id := range m.removedrecords { - ids = append(ids, id) - } - return -} - -// RecordsIDs returns the "records" edge IDs in the mutation. -func (m *UserMutation) RecordsIDs() (ids []uuid.UUID) { - for id := range m.records { - ids = append(ids, id) - } - return -} - -// ResetRecords resets all changes to the "records" edge. -func (m *UserMutation) ResetRecords() { - m.records = nil - m.clearedrecords = false - m.removedrecords = nil -} - // AddLoginHistoryIDs adds the "login_histories" edge to the UserLoginHistory entity by ids. func (m *UserMutation) AddLoginHistoryIDs(ids ...uuid.UUID) { if m.login_histories == nil { @@ -9451,6 +10238,60 @@ func (m *UserMutation) ResetModels() { m.removedmodels = nil } +// AddTaskIDs adds the "tasks" edge to the Task entity by ids. +func (m *UserMutation) AddTaskIDs(ids ...uuid.UUID) { + if m.tasks == nil { + m.tasks = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.tasks[ids[i]] = struct{}{} + } +} + +// ClearTasks clears the "tasks" edge to the Task entity. +func (m *UserMutation) ClearTasks() { + m.clearedtasks = true +} + +// TasksCleared reports if the "tasks" edge to the Task entity was cleared. +func (m *UserMutation) TasksCleared() bool { + return m.clearedtasks +} + +// RemoveTaskIDs removes the "tasks" edge to the Task entity by IDs. +func (m *UserMutation) RemoveTaskIDs(ids ...uuid.UUID) { + if m.removedtasks == nil { + m.removedtasks = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.tasks, ids[i]) + m.removedtasks[ids[i]] = struct{}{} + } +} + +// RemovedTasks returns the removed IDs of the "tasks" edge to the Task entity. +func (m *UserMutation) RemovedTasksIDs() (ids []uuid.UUID) { + for id := range m.removedtasks { + ids = append(ids, id) + } + return +} + +// TasksIDs returns the "tasks" edge IDs in the mutation. +func (m *UserMutation) TasksIDs() (ids []uuid.UUID) { + for id := range m.tasks { + ids = append(ids, id) + } + return +} + +// ResetTasks resets all changes to the "tasks" edge. +func (m *UserMutation) ResetTasks() { + m.tasks = nil + m.clearedtasks = false + m.removedtasks = nil +} + // Where appends a list predicates to the UserMutation builder. func (m *UserMutation) Where(ps ...predicate.User) { m.predicates = append(m.predicates, ps...) @@ -9670,15 +10511,15 @@ func (m *UserMutation) ResetField(name string) error { // AddedEdges returns all edge names that were set/added in this mutation. func (m *UserMutation) AddedEdges() []string { edges := make([]string, 0, 3) - if m.records != nil { - edges = append(edges, user.EdgeRecords) - } if m.login_histories != nil { edges = append(edges, user.EdgeLoginHistories) } if m.models != nil { edges = append(edges, user.EdgeModels) } + if m.tasks != nil { + edges = append(edges, user.EdgeTasks) + } return edges } @@ -9686,12 +10527,6 @@ func (m *UserMutation) AddedEdges() []string { // name in this mutation. func (m *UserMutation) AddedIDs(name string) []ent.Value { switch name { - case user.EdgeRecords: - ids := make([]ent.Value, 0, len(m.records)) - for id := range m.records { - ids = append(ids, id) - } - return ids case user.EdgeLoginHistories: ids := make([]ent.Value, 0, len(m.login_histories)) for id := range m.login_histories { @@ -9704,6 +10539,12 @@ func (m *UserMutation) AddedIDs(name string) []ent.Value { ids = append(ids, id) } return ids + case user.EdgeTasks: + ids := make([]ent.Value, 0, len(m.tasks)) + for id := range m.tasks { + ids = append(ids, id) + } + return ids } return nil } @@ -9711,15 +10552,15 @@ func (m *UserMutation) AddedIDs(name string) []ent.Value { // RemovedEdges returns all edge names that were removed in this mutation. func (m *UserMutation) RemovedEdges() []string { edges := make([]string, 0, 3) - if m.removedrecords != nil { - edges = append(edges, user.EdgeRecords) - } if m.removedlogin_histories != nil { edges = append(edges, user.EdgeLoginHistories) } if m.removedmodels != nil { edges = append(edges, user.EdgeModels) } + if m.removedtasks != nil { + edges = append(edges, user.EdgeTasks) + } return edges } @@ -9727,12 +10568,6 @@ func (m *UserMutation) RemovedEdges() []string { // the given name in this mutation. func (m *UserMutation) RemovedIDs(name string) []ent.Value { switch name { - case user.EdgeRecords: - ids := make([]ent.Value, 0, len(m.removedrecords)) - for id := range m.removedrecords { - ids = append(ids, id) - } - return ids case user.EdgeLoginHistories: ids := make([]ent.Value, 0, len(m.removedlogin_histories)) for id := range m.removedlogin_histories { @@ -9745,6 +10580,12 @@ func (m *UserMutation) RemovedIDs(name string) []ent.Value { ids = append(ids, id) } return ids + case user.EdgeTasks: + ids := make([]ent.Value, 0, len(m.removedtasks)) + for id := range m.removedtasks { + ids = append(ids, id) + } + return ids } return nil } @@ -9752,15 +10593,15 @@ func (m *UserMutation) RemovedIDs(name string) []ent.Value { // ClearedEdges returns all edge names that were cleared in this mutation. func (m *UserMutation) ClearedEdges() []string { edges := make([]string, 0, 3) - if m.clearedrecords { - edges = append(edges, user.EdgeRecords) - } if m.clearedlogin_histories { edges = append(edges, user.EdgeLoginHistories) } if m.clearedmodels { edges = append(edges, user.EdgeModels) } + if m.clearedtasks { + edges = append(edges, user.EdgeTasks) + } return edges } @@ -9768,12 +10609,12 @@ func (m *UserMutation) ClearedEdges() []string { // was cleared in this mutation. func (m *UserMutation) EdgeCleared(name string) bool { switch name { - case user.EdgeRecords: - return m.clearedrecords case user.EdgeLoginHistories: return m.clearedlogin_histories case user.EdgeModels: return m.clearedmodels + case user.EdgeTasks: + return m.clearedtasks } return false } @@ -9790,15 +10631,15 @@ func (m *UserMutation) ClearEdge(name string) error { // It returns an error if the edge is not defined in the schema. func (m *UserMutation) ResetEdge(name string) error { switch name { - case user.EdgeRecords: - m.ResetRecords() - return nil case user.EdgeLoginHistories: m.ResetLoginHistories() return nil case user.EdgeModels: m.ResetModels() return nil + case user.EdgeTasks: + m.ResetTasks() + return nil } return fmt.Errorf("unknown User edge %s", name) } diff --git a/backend/db/page.go b/backend/db/page.go index 345a744..02856ec 100644 --- a/backend/db/page.go +++ b/backend/db/page.go @@ -137,20 +137,6 @@ func (m *ModelQuery) Page(ctx context.Context, page, size int) ([]*Model, *PageI return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil } -func (r *RecordQuery) Page(ctx context.Context, page, size int) ([]*Record, *PageInfo, error) { - cnt, err := r.Count(ctx) - if err != nil { - return nil, nil, err - } - offset := size * (page - 1) - rs, err := r.Offset(offset).Limit(size).All(ctx) - if err != nil { - return nil, nil, err - } - has := (page * size) < cnt - return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil -} - func (s *SettingQuery) Page(ctx context.Context, page, size int) ([]*Setting, *PageInfo, error) { cnt, err := s.Count(ctx) if err != nil { @@ -165,6 +151,34 @@ func (s *SettingQuery) Page(ctx context.Context, page, size int) ([]*Setting, *P return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil } +func (t *TaskQuery) Page(ctx context.Context, page, size int) ([]*Task, *PageInfo, error) { + cnt, err := t.Count(ctx) + if err != nil { + return nil, nil, err + } + offset := size * (page - 1) + rs, err := t.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 (tr *TaskRecordQuery) Page(ctx context.Context, page, size int) ([]*TaskRecord, *PageInfo, error) { + cnt, err := tr.Count(ctx) + if err != nil { + return nil, nil, err + } + offset := size * (page - 1) + rs, err := tr.Offset(offset).Limit(size).All(ctx) + if err != nil { + return nil, nil, err + } + has := (page * size) < cnt + return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil +} + func (u *UserQuery) Page(ctx context.Context, page, size int) ([]*User, *PageInfo, error) { cnt, err := u.Count(ctx) if err != nil { diff --git a/backend/db/predicate/predicate.go b/backend/db/predicate/predicate.go index 82b46a8..fa194b4 100644 --- a/backend/db/predicate/predicate.go +++ b/backend/db/predicate/predicate.go @@ -33,12 +33,15 @@ type InviteCode func(*sql.Selector) // Model is the predicate function for model builders. type Model func(*sql.Selector) -// Record is the predicate function for record builders. -type Record func(*sql.Selector) - // Setting is the predicate function for setting builders. type Setting func(*sql.Selector) +// Task is the predicate function for task builders. +type Task func(*sql.Selector) + +// TaskRecord is the predicate function for taskrecord builders. +type TaskRecord func(*sql.Selector) + // User is the predicate function for user builders. type User func(*sql.Selector) diff --git a/backend/db/record/where.go b/backend/db/record/where.go deleted file mode 100644 index 0ee915e..0000000 --- a/backend/db/record/where.go +++ /dev/null @@ -1,929 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package record - -import ( - "time" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "github.com/chaitin/MonkeyCode/backend/consts" - "github.com/chaitin/MonkeyCode/backend/db/predicate" - "github.com/google/uuid" -) - -// ID filters vertices based on their ID field. -func ID(id uuid.UUID) predicate.Record { - return predicate.Record(sql.FieldEQ(FieldID, id)) -} - -// IDEQ applies the EQ predicate on the ID field. -func IDEQ(id uuid.UUID) predicate.Record { - return predicate.Record(sql.FieldEQ(FieldID, id)) -} - -// IDNEQ applies the NEQ predicate on the ID field. -func IDNEQ(id uuid.UUID) predicate.Record { - return predicate.Record(sql.FieldNEQ(FieldID, id)) -} - -// IDIn applies the In predicate on the ID field. -func IDIn(ids ...uuid.UUID) predicate.Record { - return predicate.Record(sql.FieldIn(FieldID, ids...)) -} - -// IDNotIn applies the NotIn predicate on the ID field. -func IDNotIn(ids ...uuid.UUID) predicate.Record { - return predicate.Record(sql.FieldNotIn(FieldID, ids...)) -} - -// IDGT applies the GT predicate on the ID field. -func IDGT(id uuid.UUID) predicate.Record { - return predicate.Record(sql.FieldGT(FieldID, id)) -} - -// IDGTE applies the GTE predicate on the ID field. -func IDGTE(id uuid.UUID) predicate.Record { - return predicate.Record(sql.FieldGTE(FieldID, id)) -} - -// IDLT applies the LT predicate on the ID field. -func IDLT(id uuid.UUID) predicate.Record { - return predicate.Record(sql.FieldLT(FieldID, id)) -} - -// IDLTE applies the LTE predicate on the ID field. -func IDLTE(id uuid.UUID) predicate.Record { - return predicate.Record(sql.FieldLTE(FieldID, id)) -} - -// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ. -func UserID(v uuid.UUID) predicate.Record { - return predicate.Record(sql.FieldEQ(FieldUserID, v)) -} - -// ModelID applies equality check predicate on the "model_id" field. It's identical to ModelIDEQ. -func ModelID(v uuid.UUID) predicate.Record { - return predicate.Record(sql.FieldEQ(FieldModelID, v)) -} - -// TaskID applies equality check predicate on the "task_id" field. It's identical to TaskIDEQ. -func TaskID(v string) predicate.Record { - return predicate.Record(sql.FieldEQ(FieldTaskID, v)) -} - -// ModelType applies equality check predicate on the "model_type" field. It's identical to ModelTypeEQ. -func ModelType(v consts.ModelType) predicate.Record { - vc := string(v) - return predicate.Record(sql.FieldEQ(FieldModelType, vc)) -} - -// Prompt applies equality check predicate on the "prompt" field. It's identical to PromptEQ. -func Prompt(v string) predicate.Record { - return predicate.Record(sql.FieldEQ(FieldPrompt, v)) -} - -// Completion applies equality check predicate on the "completion" field. It's identical to CompletionEQ. -func Completion(v string) predicate.Record { - return predicate.Record(sql.FieldEQ(FieldCompletion, v)) -} - -// IsAccept applies equality check predicate on the "is_accept" field. It's identical to IsAcceptEQ. -func IsAccept(v bool) predicate.Record { - return predicate.Record(sql.FieldEQ(FieldIsAccept, v)) -} - -// ProgramLanguage applies equality check predicate on the "program_language" field. It's identical to ProgramLanguageEQ. -func ProgramLanguage(v string) predicate.Record { - return predicate.Record(sql.FieldEQ(FieldProgramLanguage, v)) -} - -// WorkMode applies equality check predicate on the "work_mode" field. It's identical to WorkModeEQ. -func WorkMode(v string) predicate.Record { - return predicate.Record(sql.FieldEQ(FieldWorkMode, v)) -} - -// CodeLines applies equality check predicate on the "code_lines" field. It's identical to CodeLinesEQ. -func CodeLines(v int64) predicate.Record { - return predicate.Record(sql.FieldEQ(FieldCodeLines, v)) -} - -// InputTokens applies equality check predicate on the "input_tokens" field. It's identical to InputTokensEQ. -func InputTokens(v int64) predicate.Record { - return predicate.Record(sql.FieldEQ(FieldInputTokens, v)) -} - -// OutputTokens applies equality check predicate on the "output_tokens" field. It's identical to OutputTokensEQ. -func OutputTokens(v int64) predicate.Record { - return predicate.Record(sql.FieldEQ(FieldOutputTokens, v)) -} - -// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. -func CreatedAt(v time.Time) predicate.Record { - return predicate.Record(sql.FieldEQ(FieldCreatedAt, v)) -} - -// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ. -func UpdatedAt(v time.Time) predicate.Record { - return predicate.Record(sql.FieldEQ(FieldUpdatedAt, v)) -} - -// UserIDEQ applies the EQ predicate on the "user_id" field. -func UserIDEQ(v uuid.UUID) predicate.Record { - return predicate.Record(sql.FieldEQ(FieldUserID, v)) -} - -// UserIDNEQ applies the NEQ predicate on the "user_id" field. -func UserIDNEQ(v uuid.UUID) predicate.Record { - return predicate.Record(sql.FieldNEQ(FieldUserID, v)) -} - -// UserIDIn applies the In predicate on the "user_id" field. -func UserIDIn(vs ...uuid.UUID) predicate.Record { - return predicate.Record(sql.FieldIn(FieldUserID, vs...)) -} - -// UserIDNotIn applies the NotIn predicate on the "user_id" field. -func UserIDNotIn(vs ...uuid.UUID) predicate.Record { - return predicate.Record(sql.FieldNotIn(FieldUserID, vs...)) -} - -// UserIDIsNil applies the IsNil predicate on the "user_id" field. -func UserIDIsNil() predicate.Record { - return predicate.Record(sql.FieldIsNull(FieldUserID)) -} - -// UserIDNotNil applies the NotNil predicate on the "user_id" field. -func UserIDNotNil() predicate.Record { - return predicate.Record(sql.FieldNotNull(FieldUserID)) -} - -// ModelIDEQ applies the EQ predicate on the "model_id" field. -func ModelIDEQ(v uuid.UUID) predicate.Record { - return predicate.Record(sql.FieldEQ(FieldModelID, v)) -} - -// ModelIDNEQ applies the NEQ predicate on the "model_id" field. -func ModelIDNEQ(v uuid.UUID) predicate.Record { - return predicate.Record(sql.FieldNEQ(FieldModelID, v)) -} - -// ModelIDIn applies the In predicate on the "model_id" field. -func ModelIDIn(vs ...uuid.UUID) predicate.Record { - return predicate.Record(sql.FieldIn(FieldModelID, vs...)) -} - -// ModelIDNotIn applies the NotIn predicate on the "model_id" field. -func ModelIDNotIn(vs ...uuid.UUID) predicate.Record { - return predicate.Record(sql.FieldNotIn(FieldModelID, vs...)) -} - -// ModelIDIsNil applies the IsNil predicate on the "model_id" field. -func ModelIDIsNil() predicate.Record { - return predicate.Record(sql.FieldIsNull(FieldModelID)) -} - -// ModelIDNotNil applies the NotNil predicate on the "model_id" field. -func ModelIDNotNil() predicate.Record { - return predicate.Record(sql.FieldNotNull(FieldModelID)) -} - -// TaskIDEQ applies the EQ predicate on the "task_id" field. -func TaskIDEQ(v string) predicate.Record { - return predicate.Record(sql.FieldEQ(FieldTaskID, v)) -} - -// TaskIDNEQ applies the NEQ predicate on the "task_id" field. -func TaskIDNEQ(v string) predicate.Record { - return predicate.Record(sql.FieldNEQ(FieldTaskID, v)) -} - -// TaskIDIn applies the In predicate on the "task_id" field. -func TaskIDIn(vs ...string) predicate.Record { - return predicate.Record(sql.FieldIn(FieldTaskID, vs...)) -} - -// TaskIDNotIn applies the NotIn predicate on the "task_id" field. -func TaskIDNotIn(vs ...string) predicate.Record { - return predicate.Record(sql.FieldNotIn(FieldTaskID, vs...)) -} - -// TaskIDGT applies the GT predicate on the "task_id" field. -func TaskIDGT(v string) predicate.Record { - return predicate.Record(sql.FieldGT(FieldTaskID, v)) -} - -// TaskIDGTE applies the GTE predicate on the "task_id" field. -func TaskIDGTE(v string) predicate.Record { - return predicate.Record(sql.FieldGTE(FieldTaskID, v)) -} - -// TaskIDLT applies the LT predicate on the "task_id" field. -func TaskIDLT(v string) predicate.Record { - return predicate.Record(sql.FieldLT(FieldTaskID, v)) -} - -// TaskIDLTE applies the LTE predicate on the "task_id" field. -func TaskIDLTE(v string) predicate.Record { - return predicate.Record(sql.FieldLTE(FieldTaskID, v)) -} - -// TaskIDContains applies the Contains predicate on the "task_id" field. -func TaskIDContains(v string) predicate.Record { - return predicate.Record(sql.FieldContains(FieldTaskID, v)) -} - -// TaskIDHasPrefix applies the HasPrefix predicate on the "task_id" field. -func TaskIDHasPrefix(v string) predicate.Record { - return predicate.Record(sql.FieldHasPrefix(FieldTaskID, v)) -} - -// TaskIDHasSuffix applies the HasSuffix predicate on the "task_id" field. -func TaskIDHasSuffix(v string) predicate.Record { - return predicate.Record(sql.FieldHasSuffix(FieldTaskID, v)) -} - -// TaskIDEqualFold applies the EqualFold predicate on the "task_id" field. -func TaskIDEqualFold(v string) predicate.Record { - return predicate.Record(sql.FieldEqualFold(FieldTaskID, v)) -} - -// TaskIDContainsFold applies the ContainsFold predicate on the "task_id" field. -func TaskIDContainsFold(v string) predicate.Record { - return predicate.Record(sql.FieldContainsFold(FieldTaskID, v)) -} - -// ModelTypeEQ applies the EQ predicate on the "model_type" field. -func ModelTypeEQ(v consts.ModelType) predicate.Record { - vc := string(v) - return predicate.Record(sql.FieldEQ(FieldModelType, vc)) -} - -// ModelTypeNEQ applies the NEQ predicate on the "model_type" field. -func ModelTypeNEQ(v consts.ModelType) predicate.Record { - vc := string(v) - return predicate.Record(sql.FieldNEQ(FieldModelType, vc)) -} - -// ModelTypeIn applies the In predicate on the "model_type" field. -func ModelTypeIn(vs ...consts.ModelType) predicate.Record { - v := make([]any, len(vs)) - for i := range v { - v[i] = string(vs[i]) - } - return predicate.Record(sql.FieldIn(FieldModelType, v...)) -} - -// ModelTypeNotIn applies the NotIn predicate on the "model_type" field. -func ModelTypeNotIn(vs ...consts.ModelType) predicate.Record { - v := make([]any, len(vs)) - for i := range v { - v[i] = string(vs[i]) - } - return predicate.Record(sql.FieldNotIn(FieldModelType, v...)) -} - -// ModelTypeGT applies the GT predicate on the "model_type" field. -func ModelTypeGT(v consts.ModelType) predicate.Record { - vc := string(v) - return predicate.Record(sql.FieldGT(FieldModelType, vc)) -} - -// ModelTypeGTE applies the GTE predicate on the "model_type" field. -func ModelTypeGTE(v consts.ModelType) predicate.Record { - vc := string(v) - return predicate.Record(sql.FieldGTE(FieldModelType, vc)) -} - -// ModelTypeLT applies the LT predicate on the "model_type" field. -func ModelTypeLT(v consts.ModelType) predicate.Record { - vc := string(v) - return predicate.Record(sql.FieldLT(FieldModelType, vc)) -} - -// ModelTypeLTE applies the LTE predicate on the "model_type" field. -func ModelTypeLTE(v consts.ModelType) predicate.Record { - vc := string(v) - return predicate.Record(sql.FieldLTE(FieldModelType, vc)) -} - -// ModelTypeContains applies the Contains predicate on the "model_type" field. -func ModelTypeContains(v consts.ModelType) predicate.Record { - vc := string(v) - return predicate.Record(sql.FieldContains(FieldModelType, vc)) -} - -// ModelTypeHasPrefix applies the HasPrefix predicate on the "model_type" field. -func ModelTypeHasPrefix(v consts.ModelType) predicate.Record { - vc := string(v) - return predicate.Record(sql.FieldHasPrefix(FieldModelType, vc)) -} - -// ModelTypeHasSuffix applies the HasSuffix predicate on the "model_type" field. -func ModelTypeHasSuffix(v consts.ModelType) predicate.Record { - vc := string(v) - return predicate.Record(sql.FieldHasSuffix(FieldModelType, vc)) -} - -// ModelTypeIsNil applies the IsNil predicate on the "model_type" field. -func ModelTypeIsNil() predicate.Record { - return predicate.Record(sql.FieldIsNull(FieldModelType)) -} - -// ModelTypeNotNil applies the NotNil predicate on the "model_type" field. -func ModelTypeNotNil() predicate.Record { - return predicate.Record(sql.FieldNotNull(FieldModelType)) -} - -// ModelTypeEqualFold applies the EqualFold predicate on the "model_type" field. -func ModelTypeEqualFold(v consts.ModelType) predicate.Record { - vc := string(v) - return predicate.Record(sql.FieldEqualFold(FieldModelType, vc)) -} - -// ModelTypeContainsFold applies the ContainsFold predicate on the "model_type" field. -func ModelTypeContainsFold(v consts.ModelType) predicate.Record { - vc := string(v) - return predicate.Record(sql.FieldContainsFold(FieldModelType, vc)) -} - -// PromptEQ applies the EQ predicate on the "prompt" field. -func PromptEQ(v string) predicate.Record { - return predicate.Record(sql.FieldEQ(FieldPrompt, v)) -} - -// PromptNEQ applies the NEQ predicate on the "prompt" field. -func PromptNEQ(v string) predicate.Record { - return predicate.Record(sql.FieldNEQ(FieldPrompt, v)) -} - -// PromptIn applies the In predicate on the "prompt" field. -func PromptIn(vs ...string) predicate.Record { - return predicate.Record(sql.FieldIn(FieldPrompt, vs...)) -} - -// PromptNotIn applies the NotIn predicate on the "prompt" field. -func PromptNotIn(vs ...string) predicate.Record { - return predicate.Record(sql.FieldNotIn(FieldPrompt, vs...)) -} - -// PromptGT applies the GT predicate on the "prompt" field. -func PromptGT(v string) predicate.Record { - return predicate.Record(sql.FieldGT(FieldPrompt, v)) -} - -// PromptGTE applies the GTE predicate on the "prompt" field. -func PromptGTE(v string) predicate.Record { - return predicate.Record(sql.FieldGTE(FieldPrompt, v)) -} - -// PromptLT applies the LT predicate on the "prompt" field. -func PromptLT(v string) predicate.Record { - return predicate.Record(sql.FieldLT(FieldPrompt, v)) -} - -// PromptLTE applies the LTE predicate on the "prompt" field. -func PromptLTE(v string) predicate.Record { - return predicate.Record(sql.FieldLTE(FieldPrompt, v)) -} - -// PromptContains applies the Contains predicate on the "prompt" field. -func PromptContains(v string) predicate.Record { - return predicate.Record(sql.FieldContains(FieldPrompt, v)) -} - -// PromptHasPrefix applies the HasPrefix predicate on the "prompt" field. -func PromptHasPrefix(v string) predicate.Record { - return predicate.Record(sql.FieldHasPrefix(FieldPrompt, v)) -} - -// PromptHasSuffix applies the HasSuffix predicate on the "prompt" field. -func PromptHasSuffix(v string) predicate.Record { - return predicate.Record(sql.FieldHasSuffix(FieldPrompt, v)) -} - -// PromptIsNil applies the IsNil predicate on the "prompt" field. -func PromptIsNil() predicate.Record { - return predicate.Record(sql.FieldIsNull(FieldPrompt)) -} - -// PromptNotNil applies the NotNil predicate on the "prompt" field. -func PromptNotNil() predicate.Record { - return predicate.Record(sql.FieldNotNull(FieldPrompt)) -} - -// PromptEqualFold applies the EqualFold predicate on the "prompt" field. -func PromptEqualFold(v string) predicate.Record { - return predicate.Record(sql.FieldEqualFold(FieldPrompt, v)) -} - -// PromptContainsFold applies the ContainsFold predicate on the "prompt" field. -func PromptContainsFold(v string) predicate.Record { - return predicate.Record(sql.FieldContainsFold(FieldPrompt, v)) -} - -// CompletionEQ applies the EQ predicate on the "completion" field. -func CompletionEQ(v string) predicate.Record { - return predicate.Record(sql.FieldEQ(FieldCompletion, v)) -} - -// CompletionNEQ applies the NEQ predicate on the "completion" field. -func CompletionNEQ(v string) predicate.Record { - return predicate.Record(sql.FieldNEQ(FieldCompletion, v)) -} - -// CompletionIn applies the In predicate on the "completion" field. -func CompletionIn(vs ...string) predicate.Record { - return predicate.Record(sql.FieldIn(FieldCompletion, vs...)) -} - -// CompletionNotIn applies the NotIn predicate on the "completion" field. -func CompletionNotIn(vs ...string) predicate.Record { - return predicate.Record(sql.FieldNotIn(FieldCompletion, vs...)) -} - -// CompletionGT applies the GT predicate on the "completion" field. -func CompletionGT(v string) predicate.Record { - return predicate.Record(sql.FieldGT(FieldCompletion, v)) -} - -// CompletionGTE applies the GTE predicate on the "completion" field. -func CompletionGTE(v string) predicate.Record { - return predicate.Record(sql.FieldGTE(FieldCompletion, v)) -} - -// CompletionLT applies the LT predicate on the "completion" field. -func CompletionLT(v string) predicate.Record { - return predicate.Record(sql.FieldLT(FieldCompletion, v)) -} - -// CompletionLTE applies the LTE predicate on the "completion" field. -func CompletionLTE(v string) predicate.Record { - return predicate.Record(sql.FieldLTE(FieldCompletion, v)) -} - -// CompletionContains applies the Contains predicate on the "completion" field. -func CompletionContains(v string) predicate.Record { - return predicate.Record(sql.FieldContains(FieldCompletion, v)) -} - -// CompletionHasPrefix applies the HasPrefix predicate on the "completion" field. -func CompletionHasPrefix(v string) predicate.Record { - return predicate.Record(sql.FieldHasPrefix(FieldCompletion, v)) -} - -// CompletionHasSuffix applies the HasSuffix predicate on the "completion" field. -func CompletionHasSuffix(v string) predicate.Record { - return predicate.Record(sql.FieldHasSuffix(FieldCompletion, v)) -} - -// CompletionIsNil applies the IsNil predicate on the "completion" field. -func CompletionIsNil() predicate.Record { - return predicate.Record(sql.FieldIsNull(FieldCompletion)) -} - -// CompletionNotNil applies the NotNil predicate on the "completion" field. -func CompletionNotNil() predicate.Record { - return predicate.Record(sql.FieldNotNull(FieldCompletion)) -} - -// CompletionEqualFold applies the EqualFold predicate on the "completion" field. -func CompletionEqualFold(v string) predicate.Record { - return predicate.Record(sql.FieldEqualFold(FieldCompletion, v)) -} - -// CompletionContainsFold applies the ContainsFold predicate on the "completion" field. -func CompletionContainsFold(v string) predicate.Record { - return predicate.Record(sql.FieldContainsFold(FieldCompletion, v)) -} - -// IsAcceptEQ applies the EQ predicate on the "is_accept" field. -func IsAcceptEQ(v bool) predicate.Record { - return predicate.Record(sql.FieldEQ(FieldIsAccept, v)) -} - -// IsAcceptNEQ applies the NEQ predicate on the "is_accept" field. -func IsAcceptNEQ(v bool) predicate.Record { - return predicate.Record(sql.FieldNEQ(FieldIsAccept, v)) -} - -// ProgramLanguageEQ applies the EQ predicate on the "program_language" field. -func ProgramLanguageEQ(v string) predicate.Record { - return predicate.Record(sql.FieldEQ(FieldProgramLanguage, v)) -} - -// ProgramLanguageNEQ applies the NEQ predicate on the "program_language" field. -func ProgramLanguageNEQ(v string) predicate.Record { - return predicate.Record(sql.FieldNEQ(FieldProgramLanguage, v)) -} - -// ProgramLanguageIn applies the In predicate on the "program_language" field. -func ProgramLanguageIn(vs ...string) predicate.Record { - return predicate.Record(sql.FieldIn(FieldProgramLanguage, vs...)) -} - -// ProgramLanguageNotIn applies the NotIn predicate on the "program_language" field. -func ProgramLanguageNotIn(vs ...string) predicate.Record { - return predicate.Record(sql.FieldNotIn(FieldProgramLanguage, vs...)) -} - -// ProgramLanguageGT applies the GT predicate on the "program_language" field. -func ProgramLanguageGT(v string) predicate.Record { - return predicate.Record(sql.FieldGT(FieldProgramLanguage, v)) -} - -// ProgramLanguageGTE applies the GTE predicate on the "program_language" field. -func ProgramLanguageGTE(v string) predicate.Record { - return predicate.Record(sql.FieldGTE(FieldProgramLanguage, v)) -} - -// ProgramLanguageLT applies the LT predicate on the "program_language" field. -func ProgramLanguageLT(v string) predicate.Record { - return predicate.Record(sql.FieldLT(FieldProgramLanguage, v)) -} - -// ProgramLanguageLTE applies the LTE predicate on the "program_language" field. -func ProgramLanguageLTE(v string) predicate.Record { - return predicate.Record(sql.FieldLTE(FieldProgramLanguage, v)) -} - -// ProgramLanguageContains applies the Contains predicate on the "program_language" field. -func ProgramLanguageContains(v string) predicate.Record { - return predicate.Record(sql.FieldContains(FieldProgramLanguage, v)) -} - -// ProgramLanguageHasPrefix applies the HasPrefix predicate on the "program_language" field. -func ProgramLanguageHasPrefix(v string) predicate.Record { - return predicate.Record(sql.FieldHasPrefix(FieldProgramLanguage, v)) -} - -// ProgramLanguageHasSuffix applies the HasSuffix predicate on the "program_language" field. -func ProgramLanguageHasSuffix(v string) predicate.Record { - return predicate.Record(sql.FieldHasSuffix(FieldProgramLanguage, v)) -} - -// ProgramLanguageIsNil applies the IsNil predicate on the "program_language" field. -func ProgramLanguageIsNil() predicate.Record { - return predicate.Record(sql.FieldIsNull(FieldProgramLanguage)) -} - -// ProgramLanguageNotNil applies the NotNil predicate on the "program_language" field. -func ProgramLanguageNotNil() predicate.Record { - return predicate.Record(sql.FieldNotNull(FieldProgramLanguage)) -} - -// ProgramLanguageEqualFold applies the EqualFold predicate on the "program_language" field. -func ProgramLanguageEqualFold(v string) predicate.Record { - return predicate.Record(sql.FieldEqualFold(FieldProgramLanguage, v)) -} - -// ProgramLanguageContainsFold applies the ContainsFold predicate on the "program_language" field. -func ProgramLanguageContainsFold(v string) predicate.Record { - return predicate.Record(sql.FieldContainsFold(FieldProgramLanguage, v)) -} - -// WorkModeEQ applies the EQ predicate on the "work_mode" field. -func WorkModeEQ(v string) predicate.Record { - return predicate.Record(sql.FieldEQ(FieldWorkMode, v)) -} - -// WorkModeNEQ applies the NEQ predicate on the "work_mode" field. -func WorkModeNEQ(v string) predicate.Record { - return predicate.Record(sql.FieldNEQ(FieldWorkMode, v)) -} - -// WorkModeIn applies the In predicate on the "work_mode" field. -func WorkModeIn(vs ...string) predicate.Record { - return predicate.Record(sql.FieldIn(FieldWorkMode, vs...)) -} - -// WorkModeNotIn applies the NotIn predicate on the "work_mode" field. -func WorkModeNotIn(vs ...string) predicate.Record { - return predicate.Record(sql.FieldNotIn(FieldWorkMode, vs...)) -} - -// WorkModeGT applies the GT predicate on the "work_mode" field. -func WorkModeGT(v string) predicate.Record { - return predicate.Record(sql.FieldGT(FieldWorkMode, v)) -} - -// WorkModeGTE applies the GTE predicate on the "work_mode" field. -func WorkModeGTE(v string) predicate.Record { - return predicate.Record(sql.FieldGTE(FieldWorkMode, v)) -} - -// WorkModeLT applies the LT predicate on the "work_mode" field. -func WorkModeLT(v string) predicate.Record { - return predicate.Record(sql.FieldLT(FieldWorkMode, v)) -} - -// WorkModeLTE applies the LTE predicate on the "work_mode" field. -func WorkModeLTE(v string) predicate.Record { - return predicate.Record(sql.FieldLTE(FieldWorkMode, v)) -} - -// WorkModeContains applies the Contains predicate on the "work_mode" field. -func WorkModeContains(v string) predicate.Record { - return predicate.Record(sql.FieldContains(FieldWorkMode, v)) -} - -// WorkModeHasPrefix applies the HasPrefix predicate on the "work_mode" field. -func WorkModeHasPrefix(v string) predicate.Record { - return predicate.Record(sql.FieldHasPrefix(FieldWorkMode, v)) -} - -// WorkModeHasSuffix applies the HasSuffix predicate on the "work_mode" field. -func WorkModeHasSuffix(v string) predicate.Record { - return predicate.Record(sql.FieldHasSuffix(FieldWorkMode, v)) -} - -// WorkModeIsNil applies the IsNil predicate on the "work_mode" field. -func WorkModeIsNil() predicate.Record { - return predicate.Record(sql.FieldIsNull(FieldWorkMode)) -} - -// WorkModeNotNil applies the NotNil predicate on the "work_mode" field. -func WorkModeNotNil() predicate.Record { - return predicate.Record(sql.FieldNotNull(FieldWorkMode)) -} - -// WorkModeEqualFold applies the EqualFold predicate on the "work_mode" field. -func WorkModeEqualFold(v string) predicate.Record { - return predicate.Record(sql.FieldEqualFold(FieldWorkMode, v)) -} - -// WorkModeContainsFold applies the ContainsFold predicate on the "work_mode" field. -func WorkModeContainsFold(v string) predicate.Record { - return predicate.Record(sql.FieldContainsFold(FieldWorkMode, v)) -} - -// CodeLinesEQ applies the EQ predicate on the "code_lines" field. -func CodeLinesEQ(v int64) predicate.Record { - return predicate.Record(sql.FieldEQ(FieldCodeLines, v)) -} - -// CodeLinesNEQ applies the NEQ predicate on the "code_lines" field. -func CodeLinesNEQ(v int64) predicate.Record { - return predicate.Record(sql.FieldNEQ(FieldCodeLines, v)) -} - -// CodeLinesIn applies the In predicate on the "code_lines" field. -func CodeLinesIn(vs ...int64) predicate.Record { - return predicate.Record(sql.FieldIn(FieldCodeLines, vs...)) -} - -// CodeLinesNotIn applies the NotIn predicate on the "code_lines" field. -func CodeLinesNotIn(vs ...int64) predicate.Record { - return predicate.Record(sql.FieldNotIn(FieldCodeLines, vs...)) -} - -// CodeLinesGT applies the GT predicate on the "code_lines" field. -func CodeLinesGT(v int64) predicate.Record { - return predicate.Record(sql.FieldGT(FieldCodeLines, v)) -} - -// CodeLinesGTE applies the GTE predicate on the "code_lines" field. -func CodeLinesGTE(v int64) predicate.Record { - return predicate.Record(sql.FieldGTE(FieldCodeLines, v)) -} - -// CodeLinesLT applies the LT predicate on the "code_lines" field. -func CodeLinesLT(v int64) predicate.Record { - return predicate.Record(sql.FieldLT(FieldCodeLines, v)) -} - -// CodeLinesLTE applies the LTE predicate on the "code_lines" field. -func CodeLinesLTE(v int64) predicate.Record { - return predicate.Record(sql.FieldLTE(FieldCodeLines, v)) -} - -// CodeLinesIsNil applies the IsNil predicate on the "code_lines" field. -func CodeLinesIsNil() predicate.Record { - return predicate.Record(sql.FieldIsNull(FieldCodeLines)) -} - -// CodeLinesNotNil applies the NotNil predicate on the "code_lines" field. -func CodeLinesNotNil() predicate.Record { - return predicate.Record(sql.FieldNotNull(FieldCodeLines)) -} - -// InputTokensEQ applies the EQ predicate on the "input_tokens" field. -func InputTokensEQ(v int64) predicate.Record { - return predicate.Record(sql.FieldEQ(FieldInputTokens, v)) -} - -// InputTokensNEQ applies the NEQ predicate on the "input_tokens" field. -func InputTokensNEQ(v int64) predicate.Record { - return predicate.Record(sql.FieldNEQ(FieldInputTokens, v)) -} - -// InputTokensIn applies the In predicate on the "input_tokens" field. -func InputTokensIn(vs ...int64) predicate.Record { - return predicate.Record(sql.FieldIn(FieldInputTokens, vs...)) -} - -// InputTokensNotIn applies the NotIn predicate on the "input_tokens" field. -func InputTokensNotIn(vs ...int64) predicate.Record { - return predicate.Record(sql.FieldNotIn(FieldInputTokens, vs...)) -} - -// InputTokensGT applies the GT predicate on the "input_tokens" field. -func InputTokensGT(v int64) predicate.Record { - return predicate.Record(sql.FieldGT(FieldInputTokens, v)) -} - -// InputTokensGTE applies the GTE predicate on the "input_tokens" field. -func InputTokensGTE(v int64) predicate.Record { - return predicate.Record(sql.FieldGTE(FieldInputTokens, v)) -} - -// InputTokensLT applies the LT predicate on the "input_tokens" field. -func InputTokensLT(v int64) predicate.Record { - return predicate.Record(sql.FieldLT(FieldInputTokens, v)) -} - -// InputTokensLTE applies the LTE predicate on the "input_tokens" field. -func InputTokensLTE(v int64) predicate.Record { - return predicate.Record(sql.FieldLTE(FieldInputTokens, v)) -} - -// OutputTokensEQ applies the EQ predicate on the "output_tokens" field. -func OutputTokensEQ(v int64) predicate.Record { - return predicate.Record(sql.FieldEQ(FieldOutputTokens, v)) -} - -// OutputTokensNEQ applies the NEQ predicate on the "output_tokens" field. -func OutputTokensNEQ(v int64) predicate.Record { - return predicate.Record(sql.FieldNEQ(FieldOutputTokens, v)) -} - -// OutputTokensIn applies the In predicate on the "output_tokens" field. -func OutputTokensIn(vs ...int64) predicate.Record { - return predicate.Record(sql.FieldIn(FieldOutputTokens, vs...)) -} - -// OutputTokensNotIn applies the NotIn predicate on the "output_tokens" field. -func OutputTokensNotIn(vs ...int64) predicate.Record { - return predicate.Record(sql.FieldNotIn(FieldOutputTokens, vs...)) -} - -// OutputTokensGT applies the GT predicate on the "output_tokens" field. -func OutputTokensGT(v int64) predicate.Record { - return predicate.Record(sql.FieldGT(FieldOutputTokens, v)) -} - -// OutputTokensGTE applies the GTE predicate on the "output_tokens" field. -func OutputTokensGTE(v int64) predicate.Record { - return predicate.Record(sql.FieldGTE(FieldOutputTokens, v)) -} - -// OutputTokensLT applies the LT predicate on the "output_tokens" field. -func OutputTokensLT(v int64) predicate.Record { - return predicate.Record(sql.FieldLT(FieldOutputTokens, v)) -} - -// OutputTokensLTE applies the LTE predicate on the "output_tokens" field. -func OutputTokensLTE(v int64) predicate.Record { - return predicate.Record(sql.FieldLTE(FieldOutputTokens, v)) -} - -// CreatedAtEQ applies the EQ predicate on the "created_at" field. -func CreatedAtEQ(v time.Time) predicate.Record { - return predicate.Record(sql.FieldEQ(FieldCreatedAt, v)) -} - -// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. -func CreatedAtNEQ(v time.Time) predicate.Record { - return predicate.Record(sql.FieldNEQ(FieldCreatedAt, v)) -} - -// CreatedAtIn applies the In predicate on the "created_at" field. -func CreatedAtIn(vs ...time.Time) predicate.Record { - return predicate.Record(sql.FieldIn(FieldCreatedAt, vs...)) -} - -// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. -func CreatedAtNotIn(vs ...time.Time) predicate.Record { - return predicate.Record(sql.FieldNotIn(FieldCreatedAt, vs...)) -} - -// CreatedAtGT applies the GT predicate on the "created_at" field. -func CreatedAtGT(v time.Time) predicate.Record { - return predicate.Record(sql.FieldGT(FieldCreatedAt, v)) -} - -// CreatedAtGTE applies the GTE predicate on the "created_at" field. -func CreatedAtGTE(v time.Time) predicate.Record { - return predicate.Record(sql.FieldGTE(FieldCreatedAt, v)) -} - -// CreatedAtLT applies the LT predicate on the "created_at" field. -func CreatedAtLT(v time.Time) predicate.Record { - return predicate.Record(sql.FieldLT(FieldCreatedAt, v)) -} - -// CreatedAtLTE applies the LTE predicate on the "created_at" field. -func CreatedAtLTE(v time.Time) predicate.Record { - return predicate.Record(sql.FieldLTE(FieldCreatedAt, v)) -} - -// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. -func UpdatedAtEQ(v time.Time) predicate.Record { - return predicate.Record(sql.FieldEQ(FieldUpdatedAt, v)) -} - -// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. -func UpdatedAtNEQ(v time.Time) predicate.Record { - return predicate.Record(sql.FieldNEQ(FieldUpdatedAt, v)) -} - -// UpdatedAtIn applies the In predicate on the "updated_at" field. -func UpdatedAtIn(vs ...time.Time) predicate.Record { - return predicate.Record(sql.FieldIn(FieldUpdatedAt, vs...)) -} - -// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. -func UpdatedAtNotIn(vs ...time.Time) predicate.Record { - return predicate.Record(sql.FieldNotIn(FieldUpdatedAt, vs...)) -} - -// UpdatedAtGT applies the GT predicate on the "updated_at" field. -func UpdatedAtGT(v time.Time) predicate.Record { - return predicate.Record(sql.FieldGT(FieldUpdatedAt, v)) -} - -// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. -func UpdatedAtGTE(v time.Time) predicate.Record { - return predicate.Record(sql.FieldGTE(FieldUpdatedAt, v)) -} - -// UpdatedAtLT applies the LT predicate on the "updated_at" field. -func UpdatedAtLT(v time.Time) predicate.Record { - return predicate.Record(sql.FieldLT(FieldUpdatedAt, v)) -} - -// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. -func UpdatedAtLTE(v time.Time) predicate.Record { - return predicate.Record(sql.FieldLTE(FieldUpdatedAt, v)) -} - -// HasUser applies the HasEdge predicate on the "user" edge. -func HasUser() predicate.Record { - return predicate.Record(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.Edge(sqlgraph.M2O, true, UserTable, UserColumn), - ) - sqlgraph.HasNeighbors(s, step) - }) -} - -// HasUserWith applies the HasEdge predicate on the "user" edge with a given conditions (other predicates). -func HasUserWith(preds ...predicate.User) predicate.Record { - return predicate.Record(func(s *sql.Selector) { - step := newUserStep() - sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { - for _, p := range preds { - p(s) - } - }) - }) -} - -// HasModel applies the HasEdge predicate on the "model" edge. -func HasModel() predicate.Record { - return predicate.Record(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.Edge(sqlgraph.M2O, true, ModelTable, ModelColumn), - ) - sqlgraph.HasNeighbors(s, step) - }) -} - -// HasModelWith applies the HasEdge predicate on the "model" edge with a given conditions (other predicates). -func HasModelWith(preds ...predicate.Model) predicate.Record { - return predicate.Record(func(s *sql.Selector) { - step := newModelStep() - sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { - for _, p := range preds { - p(s) - } - }) - }) -} - -// And groups predicates with the AND operator between them. -func And(predicates ...predicate.Record) predicate.Record { - return predicate.Record(sql.AndPredicates(predicates...)) -} - -// Or groups predicates with the OR operator between them. -func Or(predicates ...predicate.Record) predicate.Record { - return predicate.Record(sql.OrPredicates(predicates...)) -} - -// Not applies the not operator on the given predicate. -func Not(p predicate.Record) predicate.Record { - return predicate.Record(sql.NotPredicates(p)) -} diff --git a/backend/db/record_create.go b/backend/db/record_create.go deleted file mode 100644 index cbb8421..0000000 --- a/backend/db/record_create.go +++ /dev/null @@ -1,1521 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package db - -import ( - "context" - "errors" - "fmt" - "time" - - "entgo.io/ent/dialect" - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "github.com/chaitin/MonkeyCode/backend/consts" - "github.com/chaitin/MonkeyCode/backend/db/model" - "github.com/chaitin/MonkeyCode/backend/db/record" - "github.com/chaitin/MonkeyCode/backend/db/user" - "github.com/google/uuid" -) - -// RecordCreate is the builder for creating a Record entity. -type RecordCreate struct { - config - mutation *RecordMutation - hooks []Hook - conflict []sql.ConflictOption -} - -// SetUserID sets the "user_id" field. -func (rc *RecordCreate) SetUserID(u uuid.UUID) *RecordCreate { - rc.mutation.SetUserID(u) - return rc -} - -// SetNillableUserID sets the "user_id" field if the given value is not nil. -func (rc *RecordCreate) SetNillableUserID(u *uuid.UUID) *RecordCreate { - if u != nil { - rc.SetUserID(*u) - } - return rc -} - -// SetModelID sets the "model_id" field. -func (rc *RecordCreate) SetModelID(u uuid.UUID) *RecordCreate { - rc.mutation.SetModelID(u) - return rc -} - -// SetNillableModelID sets the "model_id" field if the given value is not nil. -func (rc *RecordCreate) SetNillableModelID(u *uuid.UUID) *RecordCreate { - if u != nil { - rc.SetModelID(*u) - } - return rc -} - -// SetTaskID sets the "task_id" field. -func (rc *RecordCreate) SetTaskID(s string) *RecordCreate { - rc.mutation.SetTaskID(s) - return rc -} - -// SetModelType sets the "model_type" field. -func (rc *RecordCreate) SetModelType(ct consts.ModelType) *RecordCreate { - rc.mutation.SetModelType(ct) - return rc -} - -// SetNillableModelType sets the "model_type" field if the given value is not nil. -func (rc *RecordCreate) SetNillableModelType(ct *consts.ModelType) *RecordCreate { - if ct != nil { - rc.SetModelType(*ct) - } - return rc -} - -// SetPrompt sets the "prompt" field. -func (rc *RecordCreate) SetPrompt(s string) *RecordCreate { - rc.mutation.SetPrompt(s) - return rc -} - -// SetNillablePrompt sets the "prompt" field if the given value is not nil. -func (rc *RecordCreate) SetNillablePrompt(s *string) *RecordCreate { - if s != nil { - rc.SetPrompt(*s) - } - return rc -} - -// SetCompletion sets the "completion" field. -func (rc *RecordCreate) SetCompletion(s string) *RecordCreate { - rc.mutation.SetCompletion(s) - return rc -} - -// SetNillableCompletion sets the "completion" field if the given value is not nil. -func (rc *RecordCreate) SetNillableCompletion(s *string) *RecordCreate { - if s != nil { - rc.SetCompletion(*s) - } - return rc -} - -// SetIsAccept sets the "is_accept" field. -func (rc *RecordCreate) SetIsAccept(b bool) *RecordCreate { - rc.mutation.SetIsAccept(b) - return rc -} - -// SetNillableIsAccept sets the "is_accept" field if the given value is not nil. -func (rc *RecordCreate) SetNillableIsAccept(b *bool) *RecordCreate { - if b != nil { - rc.SetIsAccept(*b) - } - return rc -} - -// SetProgramLanguage sets the "program_language" field. -func (rc *RecordCreate) SetProgramLanguage(s string) *RecordCreate { - rc.mutation.SetProgramLanguage(s) - return rc -} - -// SetNillableProgramLanguage sets the "program_language" field if the given value is not nil. -func (rc *RecordCreate) SetNillableProgramLanguage(s *string) *RecordCreate { - if s != nil { - rc.SetProgramLanguage(*s) - } - return rc -} - -// SetWorkMode sets the "work_mode" field. -func (rc *RecordCreate) SetWorkMode(s string) *RecordCreate { - rc.mutation.SetWorkMode(s) - return rc -} - -// SetNillableWorkMode sets the "work_mode" field if the given value is not nil. -func (rc *RecordCreate) SetNillableWorkMode(s *string) *RecordCreate { - if s != nil { - rc.SetWorkMode(*s) - } - return rc -} - -// SetCodeLines sets the "code_lines" field. -func (rc *RecordCreate) SetCodeLines(i int64) *RecordCreate { - rc.mutation.SetCodeLines(i) - return rc -} - -// SetNillableCodeLines sets the "code_lines" field if the given value is not nil. -func (rc *RecordCreate) SetNillableCodeLines(i *int64) *RecordCreate { - if i != nil { - rc.SetCodeLines(*i) - } - return rc -} - -// SetInputTokens sets the "input_tokens" field. -func (rc *RecordCreate) SetInputTokens(i int64) *RecordCreate { - rc.mutation.SetInputTokens(i) - return rc -} - -// SetOutputTokens sets the "output_tokens" field. -func (rc *RecordCreate) SetOutputTokens(i int64) *RecordCreate { - rc.mutation.SetOutputTokens(i) - return rc -} - -// SetCreatedAt sets the "created_at" field. -func (rc *RecordCreate) SetCreatedAt(t time.Time) *RecordCreate { - rc.mutation.SetCreatedAt(t) - return rc -} - -// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. -func (rc *RecordCreate) SetNillableCreatedAt(t *time.Time) *RecordCreate { - if t != nil { - rc.SetCreatedAt(*t) - } - return rc -} - -// SetUpdatedAt sets the "updated_at" field. -func (rc *RecordCreate) SetUpdatedAt(t time.Time) *RecordCreate { - rc.mutation.SetUpdatedAt(t) - return rc -} - -// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. -func (rc *RecordCreate) SetNillableUpdatedAt(t *time.Time) *RecordCreate { - if t != nil { - rc.SetUpdatedAt(*t) - } - return rc -} - -// SetID sets the "id" field. -func (rc *RecordCreate) SetID(u uuid.UUID) *RecordCreate { - rc.mutation.SetID(u) - return rc -} - -// SetUser sets the "user" edge to the User entity. -func (rc *RecordCreate) SetUser(u *User) *RecordCreate { - return rc.SetUserID(u.ID) -} - -// SetModel sets the "model" edge to the Model entity. -func (rc *RecordCreate) SetModel(m *Model) *RecordCreate { - return rc.SetModelID(m.ID) -} - -// Mutation returns the RecordMutation object of the builder. -func (rc *RecordCreate) Mutation() *RecordMutation { - return rc.mutation -} - -// Save creates the Record in the database. -func (rc *RecordCreate) Save(ctx context.Context) (*Record, error) { - rc.defaults() - return withHooks(ctx, rc.sqlSave, rc.mutation, rc.hooks) -} - -// SaveX calls Save and panics if Save returns an error. -func (rc *RecordCreate) SaveX(ctx context.Context) *Record { - v, err := rc.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (rc *RecordCreate) Exec(ctx context.Context) error { - _, err := rc.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (rc *RecordCreate) ExecX(ctx context.Context) { - if err := rc.Exec(ctx); err != nil { - panic(err) - } -} - -// defaults sets the default values of the builder before save. -func (rc *RecordCreate) defaults() { - if _, ok := rc.mutation.IsAccept(); !ok { - v := record.DefaultIsAccept - rc.mutation.SetIsAccept(v) - } - if _, ok := rc.mutation.CreatedAt(); !ok { - v := record.DefaultCreatedAt() - rc.mutation.SetCreatedAt(v) - } - if _, ok := rc.mutation.UpdatedAt(); !ok { - v := record.DefaultUpdatedAt() - rc.mutation.SetUpdatedAt(v) - } -} - -// check runs all checks and user-defined validators on the builder. -func (rc *RecordCreate) check() error { - if _, ok := rc.mutation.TaskID(); !ok { - return &ValidationError{Name: "task_id", err: errors.New(`db: missing required field "Record.task_id"`)} - } - if _, ok := rc.mutation.IsAccept(); !ok { - return &ValidationError{Name: "is_accept", err: errors.New(`db: missing required field "Record.is_accept"`)} - } - if _, ok := rc.mutation.InputTokens(); !ok { - return &ValidationError{Name: "input_tokens", err: errors.New(`db: missing required field "Record.input_tokens"`)} - } - if _, ok := rc.mutation.OutputTokens(); !ok { - return &ValidationError{Name: "output_tokens", err: errors.New(`db: missing required field "Record.output_tokens"`)} - } - if _, ok := rc.mutation.CreatedAt(); !ok { - return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "Record.created_at"`)} - } - if _, ok := rc.mutation.UpdatedAt(); !ok { - return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "Record.updated_at"`)} - } - return nil -} - -func (rc *RecordCreate) sqlSave(ctx context.Context) (*Record, error) { - if err := rc.check(); err != nil { - return nil, err - } - _node, _spec := rc.createSpec() - if err := sqlgraph.CreateNode(ctx, rc.driver, _spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return nil, err - } - if _spec.ID.Value != nil { - if id, ok := _spec.ID.Value.(*uuid.UUID); ok { - _node.ID = *id - } else if err := _node.ID.Scan(_spec.ID.Value); err != nil { - return nil, err - } - } - rc.mutation.id = &_node.ID - rc.mutation.done = true - return _node, nil -} - -func (rc *RecordCreate) createSpec() (*Record, *sqlgraph.CreateSpec) { - var ( - _node = &Record{config: rc.config} - _spec = sqlgraph.NewCreateSpec(record.Table, sqlgraph.NewFieldSpec(record.FieldID, field.TypeUUID)) - ) - _spec.OnConflict = rc.conflict - if id, ok := rc.mutation.ID(); ok { - _node.ID = id - _spec.ID.Value = &id - } - if value, ok := rc.mutation.TaskID(); ok { - _spec.SetField(record.FieldTaskID, field.TypeString, value) - _node.TaskID = value - } - if value, ok := rc.mutation.ModelType(); ok { - _spec.SetField(record.FieldModelType, field.TypeString, value) - _node.ModelType = value - } - if value, ok := rc.mutation.Prompt(); ok { - _spec.SetField(record.FieldPrompt, field.TypeString, value) - _node.Prompt = value - } - if value, ok := rc.mutation.Completion(); ok { - _spec.SetField(record.FieldCompletion, field.TypeString, value) - _node.Completion = value - } - if value, ok := rc.mutation.IsAccept(); ok { - _spec.SetField(record.FieldIsAccept, field.TypeBool, value) - _node.IsAccept = value - } - if value, ok := rc.mutation.ProgramLanguage(); ok { - _spec.SetField(record.FieldProgramLanguage, field.TypeString, value) - _node.ProgramLanguage = value - } - if value, ok := rc.mutation.WorkMode(); ok { - _spec.SetField(record.FieldWorkMode, field.TypeString, value) - _node.WorkMode = value - } - if value, ok := rc.mutation.CodeLines(); ok { - _spec.SetField(record.FieldCodeLines, field.TypeInt64, value) - _node.CodeLines = value - } - if value, ok := rc.mutation.InputTokens(); ok { - _spec.SetField(record.FieldInputTokens, field.TypeInt64, value) - _node.InputTokens = value - } - if value, ok := rc.mutation.OutputTokens(); ok { - _spec.SetField(record.FieldOutputTokens, field.TypeInt64, value) - _node.OutputTokens = value - } - if value, ok := rc.mutation.CreatedAt(); ok { - _spec.SetField(record.FieldCreatedAt, field.TypeTime, value) - _node.CreatedAt = value - } - if value, ok := rc.mutation.UpdatedAt(); ok { - _spec.SetField(record.FieldUpdatedAt, field.TypeTime, value) - _node.UpdatedAt = value - } - if nodes := rc.mutation.UserIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: true, - Table: record.UserTable, - Columns: []string{record.UserColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _node.UserID = nodes[0] - _spec.Edges = append(_spec.Edges, edge) - } - if nodes := rc.mutation.ModelIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: true, - Table: record.ModelTable, - Columns: []string{record.ModelColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(model.FieldID, field.TypeUUID), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _node.ModelID = nodes[0] - _spec.Edges = append(_spec.Edges, edge) - } - return _node, _spec -} - -// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause -// of the `INSERT` statement. For example: -// -// client.Record.Create(). -// SetUserID(v). -// OnConflict( -// // Update the row with the new values -// // the was proposed for insertion. -// sql.ResolveWithNewValues(), -// ). -// // Override some of the fields with custom -// // update values. -// Update(func(u *ent.RecordUpsert) { -// SetUserID(v+v). -// }). -// Exec(ctx) -func (rc *RecordCreate) OnConflict(opts ...sql.ConflictOption) *RecordUpsertOne { - rc.conflict = opts - return &RecordUpsertOne{ - create: rc, - } -} - -// OnConflictColumns calls `OnConflict` and configures the columns -// as conflict target. Using this option is equivalent to using: -// -// client.Record.Create(). -// OnConflict(sql.ConflictColumns(columns...)). -// Exec(ctx) -func (rc *RecordCreate) OnConflictColumns(columns ...string) *RecordUpsertOne { - rc.conflict = append(rc.conflict, sql.ConflictColumns(columns...)) - return &RecordUpsertOne{ - create: rc, - } -} - -type ( - // RecordUpsertOne is the builder for "upsert"-ing - // one Record node. - RecordUpsertOne struct { - create *RecordCreate - } - - // RecordUpsert is the "OnConflict" setter. - RecordUpsert struct { - *sql.UpdateSet - } -) - -// SetUserID sets the "user_id" field. -func (u *RecordUpsert) SetUserID(v uuid.UUID) *RecordUpsert { - u.Set(record.FieldUserID, v) - return u -} - -// UpdateUserID sets the "user_id" field to the value that was provided on create. -func (u *RecordUpsert) UpdateUserID() *RecordUpsert { - u.SetExcluded(record.FieldUserID) - return u -} - -// ClearUserID clears the value of the "user_id" field. -func (u *RecordUpsert) ClearUserID() *RecordUpsert { - u.SetNull(record.FieldUserID) - return u -} - -// SetModelID sets the "model_id" field. -func (u *RecordUpsert) SetModelID(v uuid.UUID) *RecordUpsert { - u.Set(record.FieldModelID, v) - return u -} - -// UpdateModelID sets the "model_id" field to the value that was provided on create. -func (u *RecordUpsert) UpdateModelID() *RecordUpsert { - u.SetExcluded(record.FieldModelID) - return u -} - -// ClearModelID clears the value of the "model_id" field. -func (u *RecordUpsert) ClearModelID() *RecordUpsert { - u.SetNull(record.FieldModelID) - return u -} - -// SetTaskID sets the "task_id" field. -func (u *RecordUpsert) SetTaskID(v string) *RecordUpsert { - u.Set(record.FieldTaskID, v) - return u -} - -// UpdateTaskID sets the "task_id" field to the value that was provided on create. -func (u *RecordUpsert) UpdateTaskID() *RecordUpsert { - u.SetExcluded(record.FieldTaskID) - return u -} - -// SetModelType sets the "model_type" field. -func (u *RecordUpsert) SetModelType(v consts.ModelType) *RecordUpsert { - u.Set(record.FieldModelType, v) - return u -} - -// UpdateModelType sets the "model_type" field to the value that was provided on create. -func (u *RecordUpsert) UpdateModelType() *RecordUpsert { - u.SetExcluded(record.FieldModelType) - return u -} - -// ClearModelType clears the value of the "model_type" field. -func (u *RecordUpsert) ClearModelType() *RecordUpsert { - u.SetNull(record.FieldModelType) - return u -} - -// SetPrompt sets the "prompt" field. -func (u *RecordUpsert) SetPrompt(v string) *RecordUpsert { - u.Set(record.FieldPrompt, v) - return u -} - -// UpdatePrompt sets the "prompt" field to the value that was provided on create. -func (u *RecordUpsert) UpdatePrompt() *RecordUpsert { - u.SetExcluded(record.FieldPrompt) - return u -} - -// ClearPrompt clears the value of the "prompt" field. -func (u *RecordUpsert) ClearPrompt() *RecordUpsert { - u.SetNull(record.FieldPrompt) - return u -} - -// SetCompletion sets the "completion" field. -func (u *RecordUpsert) SetCompletion(v string) *RecordUpsert { - u.Set(record.FieldCompletion, v) - return u -} - -// UpdateCompletion sets the "completion" field to the value that was provided on create. -func (u *RecordUpsert) UpdateCompletion() *RecordUpsert { - u.SetExcluded(record.FieldCompletion) - return u -} - -// ClearCompletion clears the value of the "completion" field. -func (u *RecordUpsert) ClearCompletion() *RecordUpsert { - u.SetNull(record.FieldCompletion) - return u -} - -// SetIsAccept sets the "is_accept" field. -func (u *RecordUpsert) SetIsAccept(v bool) *RecordUpsert { - u.Set(record.FieldIsAccept, v) - return u -} - -// UpdateIsAccept sets the "is_accept" field to the value that was provided on create. -func (u *RecordUpsert) UpdateIsAccept() *RecordUpsert { - u.SetExcluded(record.FieldIsAccept) - return u -} - -// SetProgramLanguage sets the "program_language" field. -func (u *RecordUpsert) SetProgramLanguage(v string) *RecordUpsert { - u.Set(record.FieldProgramLanguage, v) - return u -} - -// UpdateProgramLanguage sets the "program_language" field to the value that was provided on create. -func (u *RecordUpsert) UpdateProgramLanguage() *RecordUpsert { - u.SetExcluded(record.FieldProgramLanguage) - return u -} - -// ClearProgramLanguage clears the value of the "program_language" field. -func (u *RecordUpsert) ClearProgramLanguage() *RecordUpsert { - u.SetNull(record.FieldProgramLanguage) - return u -} - -// SetWorkMode sets the "work_mode" field. -func (u *RecordUpsert) SetWorkMode(v string) *RecordUpsert { - u.Set(record.FieldWorkMode, v) - return u -} - -// UpdateWorkMode sets the "work_mode" field to the value that was provided on create. -func (u *RecordUpsert) UpdateWorkMode() *RecordUpsert { - u.SetExcluded(record.FieldWorkMode) - return u -} - -// ClearWorkMode clears the value of the "work_mode" field. -func (u *RecordUpsert) ClearWorkMode() *RecordUpsert { - u.SetNull(record.FieldWorkMode) - return u -} - -// SetCodeLines sets the "code_lines" field. -func (u *RecordUpsert) SetCodeLines(v int64) *RecordUpsert { - u.Set(record.FieldCodeLines, v) - return u -} - -// UpdateCodeLines sets the "code_lines" field to the value that was provided on create. -func (u *RecordUpsert) UpdateCodeLines() *RecordUpsert { - u.SetExcluded(record.FieldCodeLines) - return u -} - -// AddCodeLines adds v to the "code_lines" field. -func (u *RecordUpsert) AddCodeLines(v int64) *RecordUpsert { - u.Add(record.FieldCodeLines, v) - return u -} - -// ClearCodeLines clears the value of the "code_lines" field. -func (u *RecordUpsert) ClearCodeLines() *RecordUpsert { - u.SetNull(record.FieldCodeLines) - return u -} - -// SetInputTokens sets the "input_tokens" field. -func (u *RecordUpsert) SetInputTokens(v int64) *RecordUpsert { - u.Set(record.FieldInputTokens, v) - return u -} - -// UpdateInputTokens sets the "input_tokens" field to the value that was provided on create. -func (u *RecordUpsert) UpdateInputTokens() *RecordUpsert { - u.SetExcluded(record.FieldInputTokens) - return u -} - -// AddInputTokens adds v to the "input_tokens" field. -func (u *RecordUpsert) AddInputTokens(v int64) *RecordUpsert { - u.Add(record.FieldInputTokens, v) - return u -} - -// SetOutputTokens sets the "output_tokens" field. -func (u *RecordUpsert) SetOutputTokens(v int64) *RecordUpsert { - u.Set(record.FieldOutputTokens, v) - return u -} - -// UpdateOutputTokens sets the "output_tokens" field to the value that was provided on create. -func (u *RecordUpsert) UpdateOutputTokens() *RecordUpsert { - u.SetExcluded(record.FieldOutputTokens) - return u -} - -// AddOutputTokens adds v to the "output_tokens" field. -func (u *RecordUpsert) AddOutputTokens(v int64) *RecordUpsert { - u.Add(record.FieldOutputTokens, v) - return u -} - -// SetCreatedAt sets the "created_at" field. -func (u *RecordUpsert) SetCreatedAt(v time.Time) *RecordUpsert { - u.Set(record.FieldCreatedAt, v) - return u -} - -// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. -func (u *RecordUpsert) UpdateCreatedAt() *RecordUpsert { - u.SetExcluded(record.FieldCreatedAt) - return u -} - -// SetUpdatedAt sets the "updated_at" field. -func (u *RecordUpsert) SetUpdatedAt(v time.Time) *RecordUpsert { - u.Set(record.FieldUpdatedAt, v) - return u -} - -// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. -func (u *RecordUpsert) UpdateUpdatedAt() *RecordUpsert { - u.SetExcluded(record.FieldUpdatedAt) - return u -} - -// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field. -// Using this option is equivalent to using: -// -// client.Record.Create(). -// OnConflict( -// sql.ResolveWithNewValues(), -// sql.ResolveWith(func(u *sql.UpdateSet) { -// u.SetIgnore(record.FieldID) -// }), -// ). -// Exec(ctx) -func (u *RecordUpsertOne) UpdateNewValues() *RecordUpsertOne { - u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) - u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { - if _, exists := u.create.mutation.ID(); exists { - s.SetIgnore(record.FieldID) - } - })) - return u -} - -// Ignore sets each column to itself in case of conflict. -// Using this option is equivalent to using: -// -// client.Record.Create(). -// OnConflict(sql.ResolveWithIgnore()). -// Exec(ctx) -func (u *RecordUpsertOne) Ignore() *RecordUpsertOne { - u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) - return u -} - -// DoNothing configures the conflict_action to `DO NOTHING`. -// Supported only by SQLite and PostgreSQL. -func (u *RecordUpsertOne) DoNothing() *RecordUpsertOne { - u.create.conflict = append(u.create.conflict, sql.DoNothing()) - return u -} - -// Update allows overriding fields `UPDATE` values. See the RecordCreate.OnConflict -// documentation for more info. -func (u *RecordUpsertOne) Update(set func(*RecordUpsert)) *RecordUpsertOne { - u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { - set(&RecordUpsert{UpdateSet: update}) - })) - return u -} - -// SetUserID sets the "user_id" field. -func (u *RecordUpsertOne) SetUserID(v uuid.UUID) *RecordUpsertOne { - return u.Update(func(s *RecordUpsert) { - s.SetUserID(v) - }) -} - -// UpdateUserID sets the "user_id" field to the value that was provided on create. -func (u *RecordUpsertOne) UpdateUserID() *RecordUpsertOne { - return u.Update(func(s *RecordUpsert) { - s.UpdateUserID() - }) -} - -// ClearUserID clears the value of the "user_id" field. -func (u *RecordUpsertOne) ClearUserID() *RecordUpsertOne { - return u.Update(func(s *RecordUpsert) { - s.ClearUserID() - }) -} - -// SetModelID sets the "model_id" field. -func (u *RecordUpsertOne) SetModelID(v uuid.UUID) *RecordUpsertOne { - return u.Update(func(s *RecordUpsert) { - s.SetModelID(v) - }) -} - -// UpdateModelID sets the "model_id" field to the value that was provided on create. -func (u *RecordUpsertOne) UpdateModelID() *RecordUpsertOne { - return u.Update(func(s *RecordUpsert) { - s.UpdateModelID() - }) -} - -// ClearModelID clears the value of the "model_id" field. -func (u *RecordUpsertOne) ClearModelID() *RecordUpsertOne { - return u.Update(func(s *RecordUpsert) { - s.ClearModelID() - }) -} - -// SetTaskID sets the "task_id" field. -func (u *RecordUpsertOne) SetTaskID(v string) *RecordUpsertOne { - return u.Update(func(s *RecordUpsert) { - s.SetTaskID(v) - }) -} - -// UpdateTaskID sets the "task_id" field to the value that was provided on create. -func (u *RecordUpsertOne) UpdateTaskID() *RecordUpsertOne { - return u.Update(func(s *RecordUpsert) { - s.UpdateTaskID() - }) -} - -// SetModelType sets the "model_type" field. -func (u *RecordUpsertOne) SetModelType(v consts.ModelType) *RecordUpsertOne { - return u.Update(func(s *RecordUpsert) { - s.SetModelType(v) - }) -} - -// UpdateModelType sets the "model_type" field to the value that was provided on create. -func (u *RecordUpsertOne) UpdateModelType() *RecordUpsertOne { - return u.Update(func(s *RecordUpsert) { - s.UpdateModelType() - }) -} - -// ClearModelType clears the value of the "model_type" field. -func (u *RecordUpsertOne) ClearModelType() *RecordUpsertOne { - return u.Update(func(s *RecordUpsert) { - s.ClearModelType() - }) -} - -// SetPrompt sets the "prompt" field. -func (u *RecordUpsertOne) SetPrompt(v string) *RecordUpsertOne { - return u.Update(func(s *RecordUpsert) { - s.SetPrompt(v) - }) -} - -// UpdatePrompt sets the "prompt" field to the value that was provided on create. -func (u *RecordUpsertOne) UpdatePrompt() *RecordUpsertOne { - return u.Update(func(s *RecordUpsert) { - s.UpdatePrompt() - }) -} - -// ClearPrompt clears the value of the "prompt" field. -func (u *RecordUpsertOne) ClearPrompt() *RecordUpsertOne { - return u.Update(func(s *RecordUpsert) { - s.ClearPrompt() - }) -} - -// SetCompletion sets the "completion" field. -func (u *RecordUpsertOne) SetCompletion(v string) *RecordUpsertOne { - return u.Update(func(s *RecordUpsert) { - s.SetCompletion(v) - }) -} - -// UpdateCompletion sets the "completion" field to the value that was provided on create. -func (u *RecordUpsertOne) UpdateCompletion() *RecordUpsertOne { - return u.Update(func(s *RecordUpsert) { - s.UpdateCompletion() - }) -} - -// ClearCompletion clears the value of the "completion" field. -func (u *RecordUpsertOne) ClearCompletion() *RecordUpsertOne { - return u.Update(func(s *RecordUpsert) { - s.ClearCompletion() - }) -} - -// SetIsAccept sets the "is_accept" field. -func (u *RecordUpsertOne) SetIsAccept(v bool) *RecordUpsertOne { - return u.Update(func(s *RecordUpsert) { - s.SetIsAccept(v) - }) -} - -// UpdateIsAccept sets the "is_accept" field to the value that was provided on create. -func (u *RecordUpsertOne) UpdateIsAccept() *RecordUpsertOne { - return u.Update(func(s *RecordUpsert) { - s.UpdateIsAccept() - }) -} - -// SetProgramLanguage sets the "program_language" field. -func (u *RecordUpsertOne) SetProgramLanguage(v string) *RecordUpsertOne { - return u.Update(func(s *RecordUpsert) { - s.SetProgramLanguage(v) - }) -} - -// UpdateProgramLanguage sets the "program_language" field to the value that was provided on create. -func (u *RecordUpsertOne) UpdateProgramLanguage() *RecordUpsertOne { - return u.Update(func(s *RecordUpsert) { - s.UpdateProgramLanguage() - }) -} - -// ClearProgramLanguage clears the value of the "program_language" field. -func (u *RecordUpsertOne) ClearProgramLanguage() *RecordUpsertOne { - return u.Update(func(s *RecordUpsert) { - s.ClearProgramLanguage() - }) -} - -// SetWorkMode sets the "work_mode" field. -func (u *RecordUpsertOne) SetWorkMode(v string) *RecordUpsertOne { - return u.Update(func(s *RecordUpsert) { - s.SetWorkMode(v) - }) -} - -// UpdateWorkMode sets the "work_mode" field to the value that was provided on create. -func (u *RecordUpsertOne) UpdateWorkMode() *RecordUpsertOne { - return u.Update(func(s *RecordUpsert) { - s.UpdateWorkMode() - }) -} - -// ClearWorkMode clears the value of the "work_mode" field. -func (u *RecordUpsertOne) ClearWorkMode() *RecordUpsertOne { - return u.Update(func(s *RecordUpsert) { - s.ClearWorkMode() - }) -} - -// SetCodeLines sets the "code_lines" field. -func (u *RecordUpsertOne) SetCodeLines(v int64) *RecordUpsertOne { - return u.Update(func(s *RecordUpsert) { - s.SetCodeLines(v) - }) -} - -// AddCodeLines adds v to the "code_lines" field. -func (u *RecordUpsertOne) AddCodeLines(v int64) *RecordUpsertOne { - return u.Update(func(s *RecordUpsert) { - s.AddCodeLines(v) - }) -} - -// UpdateCodeLines sets the "code_lines" field to the value that was provided on create. -func (u *RecordUpsertOne) UpdateCodeLines() *RecordUpsertOne { - return u.Update(func(s *RecordUpsert) { - s.UpdateCodeLines() - }) -} - -// ClearCodeLines clears the value of the "code_lines" field. -func (u *RecordUpsertOne) ClearCodeLines() *RecordUpsertOne { - return u.Update(func(s *RecordUpsert) { - s.ClearCodeLines() - }) -} - -// SetInputTokens sets the "input_tokens" field. -func (u *RecordUpsertOne) SetInputTokens(v int64) *RecordUpsertOne { - return u.Update(func(s *RecordUpsert) { - s.SetInputTokens(v) - }) -} - -// AddInputTokens adds v to the "input_tokens" field. -func (u *RecordUpsertOne) AddInputTokens(v int64) *RecordUpsertOne { - return u.Update(func(s *RecordUpsert) { - s.AddInputTokens(v) - }) -} - -// UpdateInputTokens sets the "input_tokens" field to the value that was provided on create. -func (u *RecordUpsertOne) UpdateInputTokens() *RecordUpsertOne { - return u.Update(func(s *RecordUpsert) { - s.UpdateInputTokens() - }) -} - -// SetOutputTokens sets the "output_tokens" field. -func (u *RecordUpsertOne) SetOutputTokens(v int64) *RecordUpsertOne { - return u.Update(func(s *RecordUpsert) { - s.SetOutputTokens(v) - }) -} - -// AddOutputTokens adds v to the "output_tokens" field. -func (u *RecordUpsertOne) AddOutputTokens(v int64) *RecordUpsertOne { - return u.Update(func(s *RecordUpsert) { - s.AddOutputTokens(v) - }) -} - -// UpdateOutputTokens sets the "output_tokens" field to the value that was provided on create. -func (u *RecordUpsertOne) UpdateOutputTokens() *RecordUpsertOne { - return u.Update(func(s *RecordUpsert) { - s.UpdateOutputTokens() - }) -} - -// SetCreatedAt sets the "created_at" field. -func (u *RecordUpsertOne) SetCreatedAt(v time.Time) *RecordUpsertOne { - return u.Update(func(s *RecordUpsert) { - s.SetCreatedAt(v) - }) -} - -// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. -func (u *RecordUpsertOne) UpdateCreatedAt() *RecordUpsertOne { - return u.Update(func(s *RecordUpsert) { - s.UpdateCreatedAt() - }) -} - -// SetUpdatedAt sets the "updated_at" field. -func (u *RecordUpsertOne) SetUpdatedAt(v time.Time) *RecordUpsertOne { - return u.Update(func(s *RecordUpsert) { - s.SetUpdatedAt(v) - }) -} - -// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. -func (u *RecordUpsertOne) UpdateUpdatedAt() *RecordUpsertOne { - return u.Update(func(s *RecordUpsert) { - s.UpdateUpdatedAt() - }) -} - -// Exec executes the query. -func (u *RecordUpsertOne) Exec(ctx context.Context) error { - if len(u.create.conflict) == 0 { - return errors.New("db: missing options for RecordCreate.OnConflict") - } - return u.create.Exec(ctx) -} - -// ExecX is like Exec, but panics if an error occurs. -func (u *RecordUpsertOne) ExecX(ctx context.Context) { - if err := u.create.Exec(ctx); err != nil { - panic(err) - } -} - -// Exec executes the UPSERT query and returns the inserted/updated ID. -func (u *RecordUpsertOne) ID(ctx context.Context) (id uuid.UUID, err error) { - if u.create.driver.Dialect() == dialect.MySQL { - // In case of "ON CONFLICT", there is no way to get back non-numeric ID - // fields from the database since MySQL does not support the RETURNING clause. - return id, errors.New("db: RecordUpsertOne.ID is not supported by MySQL driver. Use RecordUpsertOne.Exec instead") - } - node, err := u.create.Save(ctx) - if err != nil { - return id, err - } - return node.ID, nil -} - -// IDX is like ID, but panics if an error occurs. -func (u *RecordUpsertOne) IDX(ctx context.Context) uuid.UUID { - id, err := u.ID(ctx) - if err != nil { - panic(err) - } - return id -} - -// RecordCreateBulk is the builder for creating many Record entities in bulk. -type RecordCreateBulk struct { - config - err error - builders []*RecordCreate - conflict []sql.ConflictOption -} - -// Save creates the Record entities in the database. -func (rcb *RecordCreateBulk) Save(ctx context.Context) ([]*Record, error) { - if rcb.err != nil { - return nil, rcb.err - } - specs := make([]*sqlgraph.CreateSpec, len(rcb.builders)) - nodes := make([]*Record, len(rcb.builders)) - mutators := make([]Mutator, len(rcb.builders)) - for i := range rcb.builders { - func(i int, root context.Context) { - builder := rcb.builders[i] - builder.defaults() - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*RecordMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - if err := builder.check(); err != nil { - return nil, err - } - builder.mutation = mutation - var err error - nodes[i], specs[i] = builder.createSpec() - if i < len(mutators)-1 { - _, err = mutators[i+1].Mutate(root, rcb.builders[i+1].mutation) - } else { - spec := &sqlgraph.BatchCreateSpec{Nodes: specs} - spec.OnConflict = rcb.conflict - // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, rcb.driver, spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - } - } - if err != nil { - return nil, err - } - mutation.id = &nodes[i].ID - mutation.done = true - return nodes[i], nil - }) - for i := len(builder.hooks) - 1; i >= 0; i-- { - mut = builder.hooks[i](mut) - } - mutators[i] = mut - }(i, ctx) - } - if len(mutators) > 0 { - if _, err := mutators[0].Mutate(ctx, rcb.builders[0].mutation); err != nil { - return nil, err - } - } - return nodes, nil -} - -// SaveX is like Save, but panics if an error occurs. -func (rcb *RecordCreateBulk) SaveX(ctx context.Context) []*Record { - v, err := rcb.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (rcb *RecordCreateBulk) Exec(ctx context.Context) error { - _, err := rcb.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (rcb *RecordCreateBulk) ExecX(ctx context.Context) { - if err := rcb.Exec(ctx); err != nil { - panic(err) - } -} - -// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause -// of the `INSERT` statement. For example: -// -// client.Record.CreateBulk(builders...). -// OnConflict( -// // Update the row with the new values -// // the was proposed for insertion. -// sql.ResolveWithNewValues(), -// ). -// // Override some of the fields with custom -// // update values. -// Update(func(u *ent.RecordUpsert) { -// SetUserID(v+v). -// }). -// Exec(ctx) -func (rcb *RecordCreateBulk) OnConflict(opts ...sql.ConflictOption) *RecordUpsertBulk { - rcb.conflict = opts - return &RecordUpsertBulk{ - create: rcb, - } -} - -// OnConflictColumns calls `OnConflict` and configures the columns -// as conflict target. Using this option is equivalent to using: -// -// client.Record.Create(). -// OnConflict(sql.ConflictColumns(columns...)). -// Exec(ctx) -func (rcb *RecordCreateBulk) OnConflictColumns(columns ...string) *RecordUpsertBulk { - rcb.conflict = append(rcb.conflict, sql.ConflictColumns(columns...)) - return &RecordUpsertBulk{ - create: rcb, - } -} - -// RecordUpsertBulk is the builder for "upsert"-ing -// a bulk of Record nodes. -type RecordUpsertBulk struct { - create *RecordCreateBulk -} - -// UpdateNewValues updates the mutable fields using the new values that -// were set on create. Using this option is equivalent to using: -// -// client.Record.Create(). -// OnConflict( -// sql.ResolveWithNewValues(), -// sql.ResolveWith(func(u *sql.UpdateSet) { -// u.SetIgnore(record.FieldID) -// }), -// ). -// Exec(ctx) -func (u *RecordUpsertBulk) UpdateNewValues() *RecordUpsertBulk { - u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) - u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { - for _, b := range u.create.builders { - if _, exists := b.mutation.ID(); exists { - s.SetIgnore(record.FieldID) - } - } - })) - return u -} - -// Ignore sets each column to itself in case of conflict. -// Using this option is equivalent to using: -// -// client.Record.Create(). -// OnConflict(sql.ResolveWithIgnore()). -// Exec(ctx) -func (u *RecordUpsertBulk) Ignore() *RecordUpsertBulk { - u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) - return u -} - -// DoNothing configures the conflict_action to `DO NOTHING`. -// Supported only by SQLite and PostgreSQL. -func (u *RecordUpsertBulk) DoNothing() *RecordUpsertBulk { - u.create.conflict = append(u.create.conflict, sql.DoNothing()) - return u -} - -// Update allows overriding fields `UPDATE` values. See the RecordCreateBulk.OnConflict -// documentation for more info. -func (u *RecordUpsertBulk) Update(set func(*RecordUpsert)) *RecordUpsertBulk { - u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { - set(&RecordUpsert{UpdateSet: update}) - })) - return u -} - -// SetUserID sets the "user_id" field. -func (u *RecordUpsertBulk) SetUserID(v uuid.UUID) *RecordUpsertBulk { - return u.Update(func(s *RecordUpsert) { - s.SetUserID(v) - }) -} - -// UpdateUserID sets the "user_id" field to the value that was provided on create. -func (u *RecordUpsertBulk) UpdateUserID() *RecordUpsertBulk { - return u.Update(func(s *RecordUpsert) { - s.UpdateUserID() - }) -} - -// ClearUserID clears the value of the "user_id" field. -func (u *RecordUpsertBulk) ClearUserID() *RecordUpsertBulk { - return u.Update(func(s *RecordUpsert) { - s.ClearUserID() - }) -} - -// SetModelID sets the "model_id" field. -func (u *RecordUpsertBulk) SetModelID(v uuid.UUID) *RecordUpsertBulk { - return u.Update(func(s *RecordUpsert) { - s.SetModelID(v) - }) -} - -// UpdateModelID sets the "model_id" field to the value that was provided on create. -func (u *RecordUpsertBulk) UpdateModelID() *RecordUpsertBulk { - return u.Update(func(s *RecordUpsert) { - s.UpdateModelID() - }) -} - -// ClearModelID clears the value of the "model_id" field. -func (u *RecordUpsertBulk) ClearModelID() *RecordUpsertBulk { - return u.Update(func(s *RecordUpsert) { - s.ClearModelID() - }) -} - -// SetTaskID sets the "task_id" field. -func (u *RecordUpsertBulk) SetTaskID(v string) *RecordUpsertBulk { - return u.Update(func(s *RecordUpsert) { - s.SetTaskID(v) - }) -} - -// UpdateTaskID sets the "task_id" field to the value that was provided on create. -func (u *RecordUpsertBulk) UpdateTaskID() *RecordUpsertBulk { - return u.Update(func(s *RecordUpsert) { - s.UpdateTaskID() - }) -} - -// SetModelType sets the "model_type" field. -func (u *RecordUpsertBulk) SetModelType(v consts.ModelType) *RecordUpsertBulk { - return u.Update(func(s *RecordUpsert) { - s.SetModelType(v) - }) -} - -// UpdateModelType sets the "model_type" field to the value that was provided on create. -func (u *RecordUpsertBulk) UpdateModelType() *RecordUpsertBulk { - return u.Update(func(s *RecordUpsert) { - s.UpdateModelType() - }) -} - -// ClearModelType clears the value of the "model_type" field. -func (u *RecordUpsertBulk) ClearModelType() *RecordUpsertBulk { - return u.Update(func(s *RecordUpsert) { - s.ClearModelType() - }) -} - -// SetPrompt sets the "prompt" field. -func (u *RecordUpsertBulk) SetPrompt(v string) *RecordUpsertBulk { - return u.Update(func(s *RecordUpsert) { - s.SetPrompt(v) - }) -} - -// UpdatePrompt sets the "prompt" field to the value that was provided on create. -func (u *RecordUpsertBulk) UpdatePrompt() *RecordUpsertBulk { - return u.Update(func(s *RecordUpsert) { - s.UpdatePrompt() - }) -} - -// ClearPrompt clears the value of the "prompt" field. -func (u *RecordUpsertBulk) ClearPrompt() *RecordUpsertBulk { - return u.Update(func(s *RecordUpsert) { - s.ClearPrompt() - }) -} - -// SetCompletion sets the "completion" field. -func (u *RecordUpsertBulk) SetCompletion(v string) *RecordUpsertBulk { - return u.Update(func(s *RecordUpsert) { - s.SetCompletion(v) - }) -} - -// UpdateCompletion sets the "completion" field to the value that was provided on create. -func (u *RecordUpsertBulk) UpdateCompletion() *RecordUpsertBulk { - return u.Update(func(s *RecordUpsert) { - s.UpdateCompletion() - }) -} - -// ClearCompletion clears the value of the "completion" field. -func (u *RecordUpsertBulk) ClearCompletion() *RecordUpsertBulk { - return u.Update(func(s *RecordUpsert) { - s.ClearCompletion() - }) -} - -// SetIsAccept sets the "is_accept" field. -func (u *RecordUpsertBulk) SetIsAccept(v bool) *RecordUpsertBulk { - return u.Update(func(s *RecordUpsert) { - s.SetIsAccept(v) - }) -} - -// UpdateIsAccept sets the "is_accept" field to the value that was provided on create. -func (u *RecordUpsertBulk) UpdateIsAccept() *RecordUpsertBulk { - return u.Update(func(s *RecordUpsert) { - s.UpdateIsAccept() - }) -} - -// SetProgramLanguage sets the "program_language" field. -func (u *RecordUpsertBulk) SetProgramLanguage(v string) *RecordUpsertBulk { - return u.Update(func(s *RecordUpsert) { - s.SetProgramLanguage(v) - }) -} - -// UpdateProgramLanguage sets the "program_language" field to the value that was provided on create. -func (u *RecordUpsertBulk) UpdateProgramLanguage() *RecordUpsertBulk { - return u.Update(func(s *RecordUpsert) { - s.UpdateProgramLanguage() - }) -} - -// ClearProgramLanguage clears the value of the "program_language" field. -func (u *RecordUpsertBulk) ClearProgramLanguage() *RecordUpsertBulk { - return u.Update(func(s *RecordUpsert) { - s.ClearProgramLanguage() - }) -} - -// SetWorkMode sets the "work_mode" field. -func (u *RecordUpsertBulk) SetWorkMode(v string) *RecordUpsertBulk { - return u.Update(func(s *RecordUpsert) { - s.SetWorkMode(v) - }) -} - -// UpdateWorkMode sets the "work_mode" field to the value that was provided on create. -func (u *RecordUpsertBulk) UpdateWorkMode() *RecordUpsertBulk { - return u.Update(func(s *RecordUpsert) { - s.UpdateWorkMode() - }) -} - -// ClearWorkMode clears the value of the "work_mode" field. -func (u *RecordUpsertBulk) ClearWorkMode() *RecordUpsertBulk { - return u.Update(func(s *RecordUpsert) { - s.ClearWorkMode() - }) -} - -// SetCodeLines sets the "code_lines" field. -func (u *RecordUpsertBulk) SetCodeLines(v int64) *RecordUpsertBulk { - return u.Update(func(s *RecordUpsert) { - s.SetCodeLines(v) - }) -} - -// AddCodeLines adds v to the "code_lines" field. -func (u *RecordUpsertBulk) AddCodeLines(v int64) *RecordUpsertBulk { - return u.Update(func(s *RecordUpsert) { - s.AddCodeLines(v) - }) -} - -// UpdateCodeLines sets the "code_lines" field to the value that was provided on create. -func (u *RecordUpsertBulk) UpdateCodeLines() *RecordUpsertBulk { - return u.Update(func(s *RecordUpsert) { - s.UpdateCodeLines() - }) -} - -// ClearCodeLines clears the value of the "code_lines" field. -func (u *RecordUpsertBulk) ClearCodeLines() *RecordUpsertBulk { - return u.Update(func(s *RecordUpsert) { - s.ClearCodeLines() - }) -} - -// SetInputTokens sets the "input_tokens" field. -func (u *RecordUpsertBulk) SetInputTokens(v int64) *RecordUpsertBulk { - return u.Update(func(s *RecordUpsert) { - s.SetInputTokens(v) - }) -} - -// AddInputTokens adds v to the "input_tokens" field. -func (u *RecordUpsertBulk) AddInputTokens(v int64) *RecordUpsertBulk { - return u.Update(func(s *RecordUpsert) { - s.AddInputTokens(v) - }) -} - -// UpdateInputTokens sets the "input_tokens" field to the value that was provided on create. -func (u *RecordUpsertBulk) UpdateInputTokens() *RecordUpsertBulk { - return u.Update(func(s *RecordUpsert) { - s.UpdateInputTokens() - }) -} - -// SetOutputTokens sets the "output_tokens" field. -func (u *RecordUpsertBulk) SetOutputTokens(v int64) *RecordUpsertBulk { - return u.Update(func(s *RecordUpsert) { - s.SetOutputTokens(v) - }) -} - -// AddOutputTokens adds v to the "output_tokens" field. -func (u *RecordUpsertBulk) AddOutputTokens(v int64) *RecordUpsertBulk { - return u.Update(func(s *RecordUpsert) { - s.AddOutputTokens(v) - }) -} - -// UpdateOutputTokens sets the "output_tokens" field to the value that was provided on create. -func (u *RecordUpsertBulk) UpdateOutputTokens() *RecordUpsertBulk { - return u.Update(func(s *RecordUpsert) { - s.UpdateOutputTokens() - }) -} - -// SetCreatedAt sets the "created_at" field. -func (u *RecordUpsertBulk) SetCreatedAt(v time.Time) *RecordUpsertBulk { - return u.Update(func(s *RecordUpsert) { - s.SetCreatedAt(v) - }) -} - -// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. -func (u *RecordUpsertBulk) UpdateCreatedAt() *RecordUpsertBulk { - return u.Update(func(s *RecordUpsert) { - s.UpdateCreatedAt() - }) -} - -// SetUpdatedAt sets the "updated_at" field. -func (u *RecordUpsertBulk) SetUpdatedAt(v time.Time) *RecordUpsertBulk { - return u.Update(func(s *RecordUpsert) { - s.SetUpdatedAt(v) - }) -} - -// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. -func (u *RecordUpsertBulk) UpdateUpdatedAt() *RecordUpsertBulk { - return u.Update(func(s *RecordUpsert) { - s.UpdateUpdatedAt() - }) -} - -// Exec executes the query. -func (u *RecordUpsertBulk) Exec(ctx context.Context) error { - if u.create.err != nil { - return u.create.err - } - for i, b := range u.create.builders { - if len(b.conflict) != 0 { - return fmt.Errorf("db: OnConflict was set for builder %d. Set it on the RecordCreateBulk instead", i) - } - } - if len(u.create.conflict) == 0 { - return errors.New("db: missing options for RecordCreateBulk.OnConflict") - } - return u.create.Exec(ctx) -} - -// ExecX is like Exec, but panics if an error occurs. -func (u *RecordUpsertBulk) ExecX(ctx context.Context) { - if err := u.create.Exec(ctx); err != nil { - panic(err) - } -} diff --git a/backend/db/record_delete.go b/backend/db/record_delete.go deleted file mode 100644 index 06aa28b..0000000 --- a/backend/db/record_delete.go +++ /dev/null @@ -1,88 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package db - -import ( - "context" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "github.com/chaitin/MonkeyCode/backend/db/predicate" - "github.com/chaitin/MonkeyCode/backend/db/record" -) - -// RecordDelete is the builder for deleting a Record entity. -type RecordDelete struct { - config - hooks []Hook - mutation *RecordMutation -} - -// Where appends a list predicates to the RecordDelete builder. -func (rd *RecordDelete) Where(ps ...predicate.Record) *RecordDelete { - rd.mutation.Where(ps...) - return rd -} - -// Exec executes the deletion query and returns how many vertices were deleted. -func (rd *RecordDelete) Exec(ctx context.Context) (int, error) { - return withHooks(ctx, rd.sqlExec, rd.mutation, rd.hooks) -} - -// ExecX is like Exec, but panics if an error occurs. -func (rd *RecordDelete) ExecX(ctx context.Context) int { - n, err := rd.Exec(ctx) - if err != nil { - panic(err) - } - return n -} - -func (rd *RecordDelete) sqlExec(ctx context.Context) (int, error) { - _spec := sqlgraph.NewDeleteSpec(record.Table, sqlgraph.NewFieldSpec(record.FieldID, field.TypeUUID)) - if ps := rd.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - affected, err := sqlgraph.DeleteNodes(ctx, rd.driver, _spec) - if err != nil && sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - rd.mutation.done = true - return affected, err -} - -// RecordDeleteOne is the builder for deleting a single Record entity. -type RecordDeleteOne struct { - rd *RecordDelete -} - -// Where appends a list predicates to the RecordDelete builder. -func (rdo *RecordDeleteOne) Where(ps ...predicate.Record) *RecordDeleteOne { - rdo.rd.mutation.Where(ps...) - return rdo -} - -// Exec executes the deletion query. -func (rdo *RecordDeleteOne) Exec(ctx context.Context) error { - n, err := rdo.rd.Exec(ctx) - switch { - case err != nil: - return err - case n == 0: - return &NotFoundError{record.Label} - default: - return nil - } -} - -// ExecX is like Exec, but panics if an error occurs. -func (rdo *RecordDeleteOne) ExecX(ctx context.Context) { - if err := rdo.Exec(ctx); err != nil { - panic(err) - } -} diff --git a/backend/db/record_query.go b/backend/db/record_query.go deleted file mode 100644 index efb8284..0000000 --- a/backend/db/record_query.go +++ /dev/null @@ -1,732 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package db - -import ( - "context" - "fmt" - "math" - - "entgo.io/ent" - "entgo.io/ent/dialect" - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "github.com/chaitin/MonkeyCode/backend/db/model" - "github.com/chaitin/MonkeyCode/backend/db/predicate" - "github.com/chaitin/MonkeyCode/backend/db/record" - "github.com/chaitin/MonkeyCode/backend/db/user" - "github.com/google/uuid" -) - -// RecordQuery is the builder for querying Record entities. -type RecordQuery struct { - config - ctx *QueryContext - order []record.OrderOption - inters []Interceptor - predicates []predicate.Record - withUser *UserQuery - withModel *ModelQuery - modifiers []func(*sql.Selector) - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) -} - -// Where adds a new predicate for the RecordQuery builder. -func (rq *RecordQuery) Where(ps ...predicate.Record) *RecordQuery { - rq.predicates = append(rq.predicates, ps...) - return rq -} - -// Limit the number of records to be returned by this query. -func (rq *RecordQuery) Limit(limit int) *RecordQuery { - rq.ctx.Limit = &limit - return rq -} - -// Offset to start from. -func (rq *RecordQuery) Offset(offset int) *RecordQuery { - rq.ctx.Offset = &offset - return rq -} - -// Unique configures the query builder to filter duplicate records on query. -// By default, unique is set to true, and can be disabled using this method. -func (rq *RecordQuery) Unique(unique bool) *RecordQuery { - rq.ctx.Unique = &unique - return rq -} - -// Order specifies how the records should be ordered. -func (rq *RecordQuery) Order(o ...record.OrderOption) *RecordQuery { - rq.order = append(rq.order, o...) - return rq -} - -// QueryUser chains the current query on the "user" edge. -func (rq *RecordQuery) QueryUser() *UserQuery { - query := (&UserClient{config: rq.config}).Query() - query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { - if err := rq.prepareQuery(ctx); err != nil { - return nil, err - } - selector := rq.sqlQuery(ctx) - if err := selector.Err(); err != nil { - return nil, err - } - step := sqlgraph.NewStep( - sqlgraph.From(record.Table, record.FieldID, selector), - sqlgraph.To(user.Table, user.FieldID), - sqlgraph.Edge(sqlgraph.M2O, true, record.UserTable, record.UserColumn), - ) - fromU = sqlgraph.SetNeighbors(rq.driver.Dialect(), step) - return fromU, nil - } - return query -} - -// QueryModel chains the current query on the "model" edge. -func (rq *RecordQuery) QueryModel() *ModelQuery { - query := (&ModelClient{config: rq.config}).Query() - query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { - if err := rq.prepareQuery(ctx); err != nil { - return nil, err - } - selector := rq.sqlQuery(ctx) - if err := selector.Err(); err != nil { - return nil, err - } - step := sqlgraph.NewStep( - sqlgraph.From(record.Table, record.FieldID, selector), - sqlgraph.To(model.Table, model.FieldID), - sqlgraph.Edge(sqlgraph.M2O, true, record.ModelTable, record.ModelColumn), - ) - fromU = sqlgraph.SetNeighbors(rq.driver.Dialect(), step) - return fromU, nil - } - return query -} - -// First returns the first Record entity from the query. -// Returns a *NotFoundError when no Record was found. -func (rq *RecordQuery) First(ctx context.Context) (*Record, error) { - nodes, err := rq.Limit(1).All(setContextOp(ctx, rq.ctx, ent.OpQueryFirst)) - if err != nil { - return nil, err - } - if len(nodes) == 0 { - return nil, &NotFoundError{record.Label} - } - return nodes[0], nil -} - -// FirstX is like First, but panics if an error occurs. -func (rq *RecordQuery) FirstX(ctx context.Context) *Record { - node, err := rq.First(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return node -} - -// FirstID returns the first Record ID from the query. -// Returns a *NotFoundError when no Record ID was found. -func (rq *RecordQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) { - var ids []uuid.UUID - if ids, err = rq.Limit(1).IDs(setContextOp(ctx, rq.ctx, ent.OpQueryFirstID)); err != nil { - return - } - if len(ids) == 0 { - err = &NotFoundError{record.Label} - return - } - return ids[0], nil -} - -// FirstIDX is like FirstID, but panics if an error occurs. -func (rq *RecordQuery) FirstIDX(ctx context.Context) uuid.UUID { - id, err := rq.FirstID(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return id -} - -// Only returns a single Record entity found by the query, ensuring it only returns one. -// Returns a *NotSingularError when more than one Record entity is found. -// Returns a *NotFoundError when no Record entities are found. -func (rq *RecordQuery) Only(ctx context.Context) (*Record, error) { - nodes, err := rq.Limit(2).All(setContextOp(ctx, rq.ctx, ent.OpQueryOnly)) - if err != nil { - return nil, err - } - switch len(nodes) { - case 1: - return nodes[0], nil - case 0: - return nil, &NotFoundError{record.Label} - default: - return nil, &NotSingularError{record.Label} - } -} - -// OnlyX is like Only, but panics if an error occurs. -func (rq *RecordQuery) OnlyX(ctx context.Context) *Record { - node, err := rq.Only(ctx) - if err != nil { - panic(err) - } - return node -} - -// OnlyID is like Only, but returns the only Record ID in the query. -// Returns a *NotSingularError when more than one Record ID is found. -// Returns a *NotFoundError when no entities are found. -func (rq *RecordQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) { - var ids []uuid.UUID - if ids, err = rq.Limit(2).IDs(setContextOp(ctx, rq.ctx, ent.OpQueryOnlyID)); err != nil { - return - } - switch len(ids) { - case 1: - id = ids[0] - case 0: - err = &NotFoundError{record.Label} - default: - err = &NotSingularError{record.Label} - } - return -} - -// OnlyIDX is like OnlyID, but panics if an error occurs. -func (rq *RecordQuery) OnlyIDX(ctx context.Context) uuid.UUID { - id, err := rq.OnlyID(ctx) - if err != nil { - panic(err) - } - return id -} - -// All executes the query and returns a list of Records. -func (rq *RecordQuery) All(ctx context.Context) ([]*Record, error) { - ctx = setContextOp(ctx, rq.ctx, ent.OpQueryAll) - if err := rq.prepareQuery(ctx); err != nil { - return nil, err - } - qr := querierAll[[]*Record, *RecordQuery]() - return withInterceptors[[]*Record](ctx, rq, qr, rq.inters) -} - -// AllX is like All, but panics if an error occurs. -func (rq *RecordQuery) AllX(ctx context.Context) []*Record { - nodes, err := rq.All(ctx) - if err != nil { - panic(err) - } - return nodes -} - -// IDs executes the query and returns a list of Record IDs. -func (rq *RecordQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) { - if rq.ctx.Unique == nil && rq.path != nil { - rq.Unique(true) - } - ctx = setContextOp(ctx, rq.ctx, ent.OpQueryIDs) - if err = rq.Select(record.FieldID).Scan(ctx, &ids); err != nil { - return nil, err - } - return ids, nil -} - -// IDsX is like IDs, but panics if an error occurs. -func (rq *RecordQuery) IDsX(ctx context.Context) []uuid.UUID { - ids, err := rq.IDs(ctx) - if err != nil { - panic(err) - } - return ids -} - -// Count returns the count of the given query. -func (rq *RecordQuery) Count(ctx context.Context) (int, error) { - ctx = setContextOp(ctx, rq.ctx, ent.OpQueryCount) - if err := rq.prepareQuery(ctx); err != nil { - return 0, err - } - return withInterceptors[int](ctx, rq, querierCount[*RecordQuery](), rq.inters) -} - -// CountX is like Count, but panics if an error occurs. -func (rq *RecordQuery) CountX(ctx context.Context) int { - count, err := rq.Count(ctx) - if err != nil { - panic(err) - } - return count -} - -// Exist returns true if the query has elements in the graph. -func (rq *RecordQuery) Exist(ctx context.Context) (bool, error) { - ctx = setContextOp(ctx, rq.ctx, ent.OpQueryExist) - switch _, err := rq.FirstID(ctx); { - case IsNotFound(err): - return false, nil - case err != nil: - return false, fmt.Errorf("db: check existence: %w", err) - default: - return true, nil - } -} - -// ExistX is like Exist, but panics if an error occurs. -func (rq *RecordQuery) ExistX(ctx context.Context) bool { - exist, err := rq.Exist(ctx) - if err != nil { - panic(err) - } - return exist -} - -// Clone returns a duplicate of the RecordQuery builder, including all associated steps. It can be -// used to prepare common query builders and use them differently after the clone is made. -func (rq *RecordQuery) Clone() *RecordQuery { - if rq == nil { - return nil - } - return &RecordQuery{ - config: rq.config, - ctx: rq.ctx.Clone(), - order: append([]record.OrderOption{}, rq.order...), - inters: append([]Interceptor{}, rq.inters...), - predicates: append([]predicate.Record{}, rq.predicates...), - withUser: rq.withUser.Clone(), - withModel: rq.withModel.Clone(), - // clone intermediate query. - sql: rq.sql.Clone(), - path: rq.path, - modifiers: append([]func(*sql.Selector){}, rq.modifiers...), - } -} - -// WithUser tells the query-builder to eager-load the nodes that are connected to -// the "user" edge. The optional arguments are used to configure the query builder of the edge. -func (rq *RecordQuery) WithUser(opts ...func(*UserQuery)) *RecordQuery { - query := (&UserClient{config: rq.config}).Query() - for _, opt := range opts { - opt(query) - } - rq.withUser = query - return rq -} - -// WithModel tells the query-builder to eager-load the nodes that are connected to -// the "model" edge. The optional arguments are used to configure the query builder of the edge. -func (rq *RecordQuery) WithModel(opts ...func(*ModelQuery)) *RecordQuery { - query := (&ModelClient{config: rq.config}).Query() - for _, opt := range opts { - opt(query) - } - rq.withModel = query - return rq -} - -// GroupBy is used to group vertices by one or more fields/columns. -// It is often used with aggregate functions, like: count, max, mean, min, sum. -// -// Example: -// -// var v []struct { -// UserID uuid.UUID `json:"user_id,omitempty"` -// Count int `json:"count,omitempty"` -// } -// -// client.Record.Query(). -// GroupBy(record.FieldUserID). -// Aggregate(db.Count()). -// Scan(ctx, &v) -func (rq *RecordQuery) GroupBy(field string, fields ...string) *RecordGroupBy { - rq.ctx.Fields = append([]string{field}, fields...) - grbuild := &RecordGroupBy{build: rq} - grbuild.flds = &rq.ctx.Fields - grbuild.label = record.Label - grbuild.scan = grbuild.Scan - return grbuild -} - -// Select allows the selection one or more fields/columns for the given query, -// instead of selecting all fields in the entity. -// -// Example: -// -// var v []struct { -// UserID uuid.UUID `json:"user_id,omitempty"` -// } -// -// client.Record.Query(). -// Select(record.FieldUserID). -// Scan(ctx, &v) -func (rq *RecordQuery) Select(fields ...string) *RecordSelect { - rq.ctx.Fields = append(rq.ctx.Fields, fields...) - sbuild := &RecordSelect{RecordQuery: rq} - sbuild.label = record.Label - sbuild.flds, sbuild.scan = &rq.ctx.Fields, sbuild.Scan - return sbuild -} - -// Aggregate returns a RecordSelect configured with the given aggregations. -func (rq *RecordQuery) Aggregate(fns ...AggregateFunc) *RecordSelect { - return rq.Select().Aggregate(fns...) -} - -func (rq *RecordQuery) prepareQuery(ctx context.Context) error { - for _, inter := range rq.inters { - if inter == nil { - return fmt.Errorf("db: uninitialized interceptor (forgotten import db/runtime?)") - } - if trv, ok := inter.(Traverser); ok { - if err := trv.Traverse(ctx, rq); err != nil { - return err - } - } - } - for _, f := range rq.ctx.Fields { - if !record.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} - } - } - if rq.path != nil { - prev, err := rq.path(ctx) - if err != nil { - return err - } - rq.sql = prev - } - return nil -} - -func (rq *RecordQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Record, error) { - var ( - nodes = []*Record{} - _spec = rq.querySpec() - loadedTypes = [2]bool{ - rq.withUser != nil, - rq.withModel != nil, - } - ) - _spec.ScanValues = func(columns []string) ([]any, error) { - return (*Record).scanValues(nil, columns) - } - _spec.Assign = func(columns []string, values []any) error { - node := &Record{config: rq.config} - nodes = append(nodes, node) - node.Edges.loadedTypes = loadedTypes - return node.assignValues(columns, values) - } - if len(rq.modifiers) > 0 { - _spec.Modifiers = rq.modifiers - } - for i := range hooks { - hooks[i](ctx, _spec) - } - if err := sqlgraph.QueryNodes(ctx, rq.driver, _spec); err != nil { - return nil, err - } - if len(nodes) == 0 { - return nodes, nil - } - if query := rq.withUser; query != nil { - if err := rq.loadUser(ctx, query, nodes, nil, - func(n *Record, e *User) { n.Edges.User = e }); err != nil { - return nil, err - } - } - if query := rq.withModel; query != nil { - if err := rq.loadModel(ctx, query, nodes, nil, - func(n *Record, e *Model) { n.Edges.Model = e }); err != nil { - return nil, err - } - } - return nodes, nil -} - -func (rq *RecordQuery) loadUser(ctx context.Context, query *UserQuery, nodes []*Record, init func(*Record), assign func(*Record, *User)) error { - ids := make([]uuid.UUID, 0, len(nodes)) - nodeids := make(map[uuid.UUID][]*Record) - for i := range nodes { - fk := nodes[i].UserID - if _, ok := nodeids[fk]; !ok { - ids = append(ids, fk) - } - nodeids[fk] = append(nodeids[fk], nodes[i]) - } - if len(ids) == 0 { - return nil - } - query.Where(user.IDIn(ids...)) - neighbors, err := query.All(ctx) - if err != nil { - return err - } - for _, n := range neighbors { - nodes, ok := nodeids[n.ID] - if !ok { - return fmt.Errorf(`unexpected foreign-key "user_id" returned %v`, n.ID) - } - for i := range nodes { - assign(nodes[i], n) - } - } - return nil -} -func (rq *RecordQuery) loadModel(ctx context.Context, query *ModelQuery, nodes []*Record, init func(*Record), assign func(*Record, *Model)) error { - ids := make([]uuid.UUID, 0, len(nodes)) - nodeids := make(map[uuid.UUID][]*Record) - for i := range nodes { - fk := nodes[i].ModelID - if _, ok := nodeids[fk]; !ok { - ids = append(ids, fk) - } - nodeids[fk] = append(nodeids[fk], nodes[i]) - } - if len(ids) == 0 { - return nil - } - query.Where(model.IDIn(ids...)) - neighbors, err := query.All(ctx) - if err != nil { - return err - } - for _, n := range neighbors { - nodes, ok := nodeids[n.ID] - if !ok { - return fmt.Errorf(`unexpected foreign-key "model_id" returned %v`, n.ID) - } - for i := range nodes { - assign(nodes[i], n) - } - } - return nil -} - -func (rq *RecordQuery) sqlCount(ctx context.Context) (int, error) { - _spec := rq.querySpec() - if len(rq.modifiers) > 0 { - _spec.Modifiers = rq.modifiers - } - _spec.Node.Columns = rq.ctx.Fields - if len(rq.ctx.Fields) > 0 { - _spec.Unique = rq.ctx.Unique != nil && *rq.ctx.Unique - } - return sqlgraph.CountNodes(ctx, rq.driver, _spec) -} - -func (rq *RecordQuery) querySpec() *sqlgraph.QuerySpec { - _spec := sqlgraph.NewQuerySpec(record.Table, record.Columns, sqlgraph.NewFieldSpec(record.FieldID, field.TypeUUID)) - _spec.From = rq.sql - if unique := rq.ctx.Unique; unique != nil { - _spec.Unique = *unique - } else if rq.path != nil { - _spec.Unique = true - } - if fields := rq.ctx.Fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, record.FieldID) - for i := range fields { - if fields[i] != record.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) - } - } - if rq.withUser != nil { - _spec.Node.AddColumnOnce(record.FieldUserID) - } - if rq.withModel != nil { - _spec.Node.AddColumnOnce(record.FieldModelID) - } - } - if ps := rq.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if limit := rq.ctx.Limit; limit != nil { - _spec.Limit = *limit - } - if offset := rq.ctx.Offset; offset != nil { - _spec.Offset = *offset - } - if ps := rq.order; len(ps) > 0 { - _spec.Order = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - return _spec -} - -func (rq *RecordQuery) sqlQuery(ctx context.Context) *sql.Selector { - builder := sql.Dialect(rq.driver.Dialect()) - t1 := builder.Table(record.Table) - columns := rq.ctx.Fields - if len(columns) == 0 { - columns = record.Columns - } - selector := builder.Select(t1.Columns(columns...)...).From(t1) - if rq.sql != nil { - selector = rq.sql - selector.Select(selector.Columns(columns...)...) - } - if rq.ctx.Unique != nil && *rq.ctx.Unique { - selector.Distinct() - } - for _, m := range rq.modifiers { - m(selector) - } - for _, p := range rq.predicates { - p(selector) - } - for _, p := range rq.order { - p(selector) - } - if offset := rq.ctx.Offset; offset != nil { - // limit is mandatory for offset clause. We start - // with default value, and override it below if needed. - selector.Offset(*offset).Limit(math.MaxInt32) - } - if limit := rq.ctx.Limit; limit != nil { - selector.Limit(*limit) - } - return selector -} - -// ForUpdate locks the selected rows against concurrent updates, and prevent them from being -// updated, deleted or "selected ... for update" by other sessions, until the transaction is -// either committed or rolled-back. -func (rq *RecordQuery) ForUpdate(opts ...sql.LockOption) *RecordQuery { - if rq.driver.Dialect() == dialect.Postgres { - rq.Unique(false) - } - rq.modifiers = append(rq.modifiers, func(s *sql.Selector) { - s.ForUpdate(opts...) - }) - return rq -} - -// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock -// on any rows that are read. Other sessions can read the rows, but cannot modify them -// until your transaction commits. -func (rq *RecordQuery) ForShare(opts ...sql.LockOption) *RecordQuery { - if rq.driver.Dialect() == dialect.Postgres { - rq.Unique(false) - } - rq.modifiers = append(rq.modifiers, func(s *sql.Selector) { - s.ForShare(opts...) - }) - return rq -} - -// Modify adds a query modifier for attaching custom logic to queries. -func (rq *RecordQuery) Modify(modifiers ...func(s *sql.Selector)) *RecordSelect { - rq.modifiers = append(rq.modifiers, modifiers...) - return rq.Select() -} - -// RecordGroupBy is the group-by builder for Record entities. -type RecordGroupBy struct { - selector - build *RecordQuery -} - -// Aggregate adds the given aggregation functions to the group-by query. -func (rgb *RecordGroupBy) Aggregate(fns ...AggregateFunc) *RecordGroupBy { - rgb.fns = append(rgb.fns, fns...) - return rgb -} - -// Scan applies the selector query and scans the result into the given value. -func (rgb *RecordGroupBy) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, rgb.build.ctx, ent.OpQueryGroupBy) - if err := rgb.build.prepareQuery(ctx); err != nil { - return err - } - return scanWithInterceptors[*RecordQuery, *RecordGroupBy](ctx, rgb.build, rgb, rgb.build.inters, v) -} - -func (rgb *RecordGroupBy) sqlScan(ctx context.Context, root *RecordQuery, v any) error { - selector := root.sqlQuery(ctx).Select() - aggregation := make([]string, 0, len(rgb.fns)) - for _, fn := range rgb.fns { - aggregation = append(aggregation, fn(selector)) - } - if len(selector.SelectedColumns()) == 0 { - columns := make([]string, 0, len(*rgb.flds)+len(rgb.fns)) - for _, f := range *rgb.flds { - columns = append(columns, selector.C(f)) - } - columns = append(columns, aggregation...) - selector.Select(columns...) - } - selector.GroupBy(selector.Columns(*rgb.flds...)...) - if err := selector.Err(); err != nil { - return err - } - rows := &sql.Rows{} - query, args := selector.Query() - if err := rgb.build.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} - -// RecordSelect is the builder for selecting fields of Record entities. -type RecordSelect struct { - *RecordQuery - selector -} - -// Aggregate adds the given aggregation functions to the selector query. -func (rs *RecordSelect) Aggregate(fns ...AggregateFunc) *RecordSelect { - rs.fns = append(rs.fns, fns...) - return rs -} - -// Scan applies the selector query and scans the result into the given value. -func (rs *RecordSelect) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, rs.ctx, ent.OpQuerySelect) - if err := rs.prepareQuery(ctx); err != nil { - return err - } - return scanWithInterceptors[*RecordQuery, *RecordSelect](ctx, rs.RecordQuery, rs, rs.inters, v) -} - -func (rs *RecordSelect) sqlScan(ctx context.Context, root *RecordQuery, v any) error { - selector := root.sqlQuery(ctx) - aggregation := make([]string, 0, len(rs.fns)) - for _, fn := range rs.fns { - aggregation = append(aggregation, fn(selector)) - } - switch n := len(*rs.selector.flds); { - case n == 0 && len(aggregation) > 0: - selector.Select(aggregation...) - case n != 0 && len(aggregation) > 0: - selector.AppendSelect(aggregation...) - } - rows := &sql.Rows{} - query, args := selector.Query() - if err := rs.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} - -// Modify adds a query modifier for attaching custom logic to queries. -func (rs *RecordSelect) Modify(modifiers ...func(s *sql.Selector)) *RecordSelect { - rs.modifiers = append(rs.modifiers, modifiers...) - return rs -} diff --git a/backend/db/record_update.go b/backend/db/record_update.go deleted file mode 100644 index edbbbf1..0000000 --- a/backend/db/record_update.go +++ /dev/null @@ -1,1014 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package db - -import ( - "context" - "errors" - "fmt" - "time" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "github.com/chaitin/MonkeyCode/backend/consts" - "github.com/chaitin/MonkeyCode/backend/db/model" - "github.com/chaitin/MonkeyCode/backend/db/predicate" - "github.com/chaitin/MonkeyCode/backend/db/record" - "github.com/chaitin/MonkeyCode/backend/db/user" - "github.com/google/uuid" -) - -// RecordUpdate is the builder for updating Record entities. -type RecordUpdate struct { - config - hooks []Hook - mutation *RecordMutation - modifiers []func(*sql.UpdateBuilder) -} - -// Where appends a list predicates to the RecordUpdate builder. -func (ru *RecordUpdate) Where(ps ...predicate.Record) *RecordUpdate { - ru.mutation.Where(ps...) - return ru -} - -// SetUserID sets the "user_id" field. -func (ru *RecordUpdate) SetUserID(u uuid.UUID) *RecordUpdate { - ru.mutation.SetUserID(u) - return ru -} - -// SetNillableUserID sets the "user_id" field if the given value is not nil. -func (ru *RecordUpdate) SetNillableUserID(u *uuid.UUID) *RecordUpdate { - if u != nil { - ru.SetUserID(*u) - } - return ru -} - -// ClearUserID clears the value of the "user_id" field. -func (ru *RecordUpdate) ClearUserID() *RecordUpdate { - ru.mutation.ClearUserID() - return ru -} - -// SetModelID sets the "model_id" field. -func (ru *RecordUpdate) SetModelID(u uuid.UUID) *RecordUpdate { - ru.mutation.SetModelID(u) - return ru -} - -// SetNillableModelID sets the "model_id" field if the given value is not nil. -func (ru *RecordUpdate) SetNillableModelID(u *uuid.UUID) *RecordUpdate { - if u != nil { - ru.SetModelID(*u) - } - return ru -} - -// ClearModelID clears the value of the "model_id" field. -func (ru *RecordUpdate) ClearModelID() *RecordUpdate { - ru.mutation.ClearModelID() - return ru -} - -// SetTaskID sets the "task_id" field. -func (ru *RecordUpdate) SetTaskID(s string) *RecordUpdate { - ru.mutation.SetTaskID(s) - return ru -} - -// SetNillableTaskID sets the "task_id" field if the given value is not nil. -func (ru *RecordUpdate) SetNillableTaskID(s *string) *RecordUpdate { - if s != nil { - ru.SetTaskID(*s) - } - return ru -} - -// SetModelType sets the "model_type" field. -func (ru *RecordUpdate) SetModelType(ct consts.ModelType) *RecordUpdate { - ru.mutation.SetModelType(ct) - return ru -} - -// SetNillableModelType sets the "model_type" field if the given value is not nil. -func (ru *RecordUpdate) SetNillableModelType(ct *consts.ModelType) *RecordUpdate { - if ct != nil { - ru.SetModelType(*ct) - } - return ru -} - -// ClearModelType clears the value of the "model_type" field. -func (ru *RecordUpdate) ClearModelType() *RecordUpdate { - ru.mutation.ClearModelType() - return ru -} - -// SetPrompt sets the "prompt" field. -func (ru *RecordUpdate) SetPrompt(s string) *RecordUpdate { - ru.mutation.SetPrompt(s) - return ru -} - -// SetNillablePrompt sets the "prompt" field if the given value is not nil. -func (ru *RecordUpdate) SetNillablePrompt(s *string) *RecordUpdate { - if s != nil { - ru.SetPrompt(*s) - } - return ru -} - -// ClearPrompt clears the value of the "prompt" field. -func (ru *RecordUpdate) ClearPrompt() *RecordUpdate { - ru.mutation.ClearPrompt() - return ru -} - -// SetCompletion sets the "completion" field. -func (ru *RecordUpdate) SetCompletion(s string) *RecordUpdate { - ru.mutation.SetCompletion(s) - return ru -} - -// SetNillableCompletion sets the "completion" field if the given value is not nil. -func (ru *RecordUpdate) SetNillableCompletion(s *string) *RecordUpdate { - if s != nil { - ru.SetCompletion(*s) - } - return ru -} - -// ClearCompletion clears the value of the "completion" field. -func (ru *RecordUpdate) ClearCompletion() *RecordUpdate { - ru.mutation.ClearCompletion() - return ru -} - -// SetIsAccept sets the "is_accept" field. -func (ru *RecordUpdate) SetIsAccept(b bool) *RecordUpdate { - ru.mutation.SetIsAccept(b) - return ru -} - -// SetNillableIsAccept sets the "is_accept" field if the given value is not nil. -func (ru *RecordUpdate) SetNillableIsAccept(b *bool) *RecordUpdate { - if b != nil { - ru.SetIsAccept(*b) - } - return ru -} - -// SetProgramLanguage sets the "program_language" field. -func (ru *RecordUpdate) SetProgramLanguage(s string) *RecordUpdate { - ru.mutation.SetProgramLanguage(s) - return ru -} - -// SetNillableProgramLanguage sets the "program_language" field if the given value is not nil. -func (ru *RecordUpdate) SetNillableProgramLanguage(s *string) *RecordUpdate { - if s != nil { - ru.SetProgramLanguage(*s) - } - return ru -} - -// ClearProgramLanguage clears the value of the "program_language" field. -func (ru *RecordUpdate) ClearProgramLanguage() *RecordUpdate { - ru.mutation.ClearProgramLanguage() - return ru -} - -// SetWorkMode sets the "work_mode" field. -func (ru *RecordUpdate) SetWorkMode(s string) *RecordUpdate { - ru.mutation.SetWorkMode(s) - return ru -} - -// SetNillableWorkMode sets the "work_mode" field if the given value is not nil. -func (ru *RecordUpdate) SetNillableWorkMode(s *string) *RecordUpdate { - if s != nil { - ru.SetWorkMode(*s) - } - return ru -} - -// ClearWorkMode clears the value of the "work_mode" field. -func (ru *RecordUpdate) ClearWorkMode() *RecordUpdate { - ru.mutation.ClearWorkMode() - return ru -} - -// SetCodeLines sets the "code_lines" field. -func (ru *RecordUpdate) SetCodeLines(i int64) *RecordUpdate { - ru.mutation.ResetCodeLines() - ru.mutation.SetCodeLines(i) - return ru -} - -// SetNillableCodeLines sets the "code_lines" field if the given value is not nil. -func (ru *RecordUpdate) SetNillableCodeLines(i *int64) *RecordUpdate { - if i != nil { - ru.SetCodeLines(*i) - } - return ru -} - -// AddCodeLines adds i to the "code_lines" field. -func (ru *RecordUpdate) AddCodeLines(i int64) *RecordUpdate { - ru.mutation.AddCodeLines(i) - return ru -} - -// ClearCodeLines clears the value of the "code_lines" field. -func (ru *RecordUpdate) ClearCodeLines() *RecordUpdate { - ru.mutation.ClearCodeLines() - return ru -} - -// SetInputTokens sets the "input_tokens" field. -func (ru *RecordUpdate) SetInputTokens(i int64) *RecordUpdate { - ru.mutation.ResetInputTokens() - ru.mutation.SetInputTokens(i) - return ru -} - -// SetNillableInputTokens sets the "input_tokens" field if the given value is not nil. -func (ru *RecordUpdate) SetNillableInputTokens(i *int64) *RecordUpdate { - if i != nil { - ru.SetInputTokens(*i) - } - return ru -} - -// AddInputTokens adds i to the "input_tokens" field. -func (ru *RecordUpdate) AddInputTokens(i int64) *RecordUpdate { - ru.mutation.AddInputTokens(i) - return ru -} - -// SetOutputTokens sets the "output_tokens" field. -func (ru *RecordUpdate) SetOutputTokens(i int64) *RecordUpdate { - ru.mutation.ResetOutputTokens() - ru.mutation.SetOutputTokens(i) - return ru -} - -// SetNillableOutputTokens sets the "output_tokens" field if the given value is not nil. -func (ru *RecordUpdate) SetNillableOutputTokens(i *int64) *RecordUpdate { - if i != nil { - ru.SetOutputTokens(*i) - } - return ru -} - -// AddOutputTokens adds i to the "output_tokens" field. -func (ru *RecordUpdate) AddOutputTokens(i int64) *RecordUpdate { - ru.mutation.AddOutputTokens(i) - return ru -} - -// SetCreatedAt sets the "created_at" field. -func (ru *RecordUpdate) SetCreatedAt(t time.Time) *RecordUpdate { - ru.mutation.SetCreatedAt(t) - return ru -} - -// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. -func (ru *RecordUpdate) SetNillableCreatedAt(t *time.Time) *RecordUpdate { - if t != nil { - ru.SetCreatedAt(*t) - } - return ru -} - -// SetUpdatedAt sets the "updated_at" field. -func (ru *RecordUpdate) SetUpdatedAt(t time.Time) *RecordUpdate { - ru.mutation.SetUpdatedAt(t) - return ru -} - -// SetUser sets the "user" edge to the User entity. -func (ru *RecordUpdate) SetUser(u *User) *RecordUpdate { - return ru.SetUserID(u.ID) -} - -// SetModel sets the "model" edge to the Model entity. -func (ru *RecordUpdate) SetModel(m *Model) *RecordUpdate { - return ru.SetModelID(m.ID) -} - -// Mutation returns the RecordMutation object of the builder. -func (ru *RecordUpdate) Mutation() *RecordMutation { - return ru.mutation -} - -// ClearUser clears the "user" edge to the User entity. -func (ru *RecordUpdate) ClearUser() *RecordUpdate { - ru.mutation.ClearUser() - return ru -} - -// ClearModel clears the "model" edge to the Model entity. -func (ru *RecordUpdate) ClearModel() *RecordUpdate { - ru.mutation.ClearModel() - return ru -} - -// Save executes the query and returns the number of nodes affected by the update operation. -func (ru *RecordUpdate) Save(ctx context.Context) (int, error) { - ru.defaults() - return withHooks(ctx, ru.sqlSave, ru.mutation, ru.hooks) -} - -// SaveX is like Save, but panics if an error occurs. -func (ru *RecordUpdate) SaveX(ctx context.Context) int { - affected, err := ru.Save(ctx) - if err != nil { - panic(err) - } - return affected -} - -// Exec executes the query. -func (ru *RecordUpdate) Exec(ctx context.Context) error { - _, err := ru.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (ru *RecordUpdate) ExecX(ctx context.Context) { - if err := ru.Exec(ctx); err != nil { - panic(err) - } -} - -// defaults sets the default values of the builder before save. -func (ru *RecordUpdate) defaults() { - if _, ok := ru.mutation.UpdatedAt(); !ok { - v := record.UpdateDefaultUpdatedAt() - ru.mutation.SetUpdatedAt(v) - } -} - -// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. -func (ru *RecordUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *RecordUpdate { - ru.modifiers = append(ru.modifiers, modifiers...) - return ru -} - -func (ru *RecordUpdate) sqlSave(ctx context.Context) (n int, err error) { - _spec := sqlgraph.NewUpdateSpec(record.Table, record.Columns, sqlgraph.NewFieldSpec(record.FieldID, field.TypeUUID)) - if ps := ru.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if value, ok := ru.mutation.TaskID(); ok { - _spec.SetField(record.FieldTaskID, field.TypeString, value) - } - if value, ok := ru.mutation.ModelType(); ok { - _spec.SetField(record.FieldModelType, field.TypeString, value) - } - if ru.mutation.ModelTypeCleared() { - _spec.ClearField(record.FieldModelType, field.TypeString) - } - if value, ok := ru.mutation.Prompt(); ok { - _spec.SetField(record.FieldPrompt, field.TypeString, value) - } - if ru.mutation.PromptCleared() { - _spec.ClearField(record.FieldPrompt, field.TypeString) - } - if value, ok := ru.mutation.Completion(); ok { - _spec.SetField(record.FieldCompletion, field.TypeString, value) - } - if ru.mutation.CompletionCleared() { - _spec.ClearField(record.FieldCompletion, field.TypeString) - } - if value, ok := ru.mutation.IsAccept(); ok { - _spec.SetField(record.FieldIsAccept, field.TypeBool, value) - } - if value, ok := ru.mutation.ProgramLanguage(); ok { - _spec.SetField(record.FieldProgramLanguage, field.TypeString, value) - } - if ru.mutation.ProgramLanguageCleared() { - _spec.ClearField(record.FieldProgramLanguage, field.TypeString) - } - if value, ok := ru.mutation.WorkMode(); ok { - _spec.SetField(record.FieldWorkMode, field.TypeString, value) - } - if ru.mutation.WorkModeCleared() { - _spec.ClearField(record.FieldWorkMode, field.TypeString) - } - if value, ok := ru.mutation.CodeLines(); ok { - _spec.SetField(record.FieldCodeLines, field.TypeInt64, value) - } - if value, ok := ru.mutation.AddedCodeLines(); ok { - _spec.AddField(record.FieldCodeLines, field.TypeInt64, value) - } - if ru.mutation.CodeLinesCleared() { - _spec.ClearField(record.FieldCodeLines, field.TypeInt64) - } - if value, ok := ru.mutation.InputTokens(); ok { - _spec.SetField(record.FieldInputTokens, field.TypeInt64, value) - } - if value, ok := ru.mutation.AddedInputTokens(); ok { - _spec.AddField(record.FieldInputTokens, field.TypeInt64, value) - } - if value, ok := ru.mutation.OutputTokens(); ok { - _spec.SetField(record.FieldOutputTokens, field.TypeInt64, value) - } - if value, ok := ru.mutation.AddedOutputTokens(); ok { - _spec.AddField(record.FieldOutputTokens, field.TypeInt64, value) - } - if value, ok := ru.mutation.CreatedAt(); ok { - _spec.SetField(record.FieldCreatedAt, field.TypeTime, value) - } - if value, ok := ru.mutation.UpdatedAt(); ok { - _spec.SetField(record.FieldUpdatedAt, field.TypeTime, value) - } - if ru.mutation.UserCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: true, - Table: record.UserTable, - Columns: []string{record.UserColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := ru.mutation.UserIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: true, - Table: record.UserTable, - Columns: []string{record.UserColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } - if ru.mutation.ModelCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: true, - Table: record.ModelTable, - Columns: []string{record.ModelColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(model.FieldID, field.TypeUUID), - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := ru.mutation.ModelIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: true, - Table: record.ModelTable, - Columns: []string{record.ModelColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(model.FieldID, field.TypeUUID), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } - _spec.AddModifiers(ru.modifiers...) - if n, err = sqlgraph.UpdateNodes(ctx, ru.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{record.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return 0, err - } - ru.mutation.done = true - return n, nil -} - -// RecordUpdateOne is the builder for updating a single Record entity. -type RecordUpdateOne struct { - config - fields []string - hooks []Hook - mutation *RecordMutation - modifiers []func(*sql.UpdateBuilder) -} - -// SetUserID sets the "user_id" field. -func (ruo *RecordUpdateOne) SetUserID(u uuid.UUID) *RecordUpdateOne { - ruo.mutation.SetUserID(u) - return ruo -} - -// SetNillableUserID sets the "user_id" field if the given value is not nil. -func (ruo *RecordUpdateOne) SetNillableUserID(u *uuid.UUID) *RecordUpdateOne { - if u != nil { - ruo.SetUserID(*u) - } - return ruo -} - -// ClearUserID clears the value of the "user_id" field. -func (ruo *RecordUpdateOne) ClearUserID() *RecordUpdateOne { - ruo.mutation.ClearUserID() - return ruo -} - -// SetModelID sets the "model_id" field. -func (ruo *RecordUpdateOne) SetModelID(u uuid.UUID) *RecordUpdateOne { - ruo.mutation.SetModelID(u) - return ruo -} - -// SetNillableModelID sets the "model_id" field if the given value is not nil. -func (ruo *RecordUpdateOne) SetNillableModelID(u *uuid.UUID) *RecordUpdateOne { - if u != nil { - ruo.SetModelID(*u) - } - return ruo -} - -// ClearModelID clears the value of the "model_id" field. -func (ruo *RecordUpdateOne) ClearModelID() *RecordUpdateOne { - ruo.mutation.ClearModelID() - return ruo -} - -// SetTaskID sets the "task_id" field. -func (ruo *RecordUpdateOne) SetTaskID(s string) *RecordUpdateOne { - ruo.mutation.SetTaskID(s) - return ruo -} - -// SetNillableTaskID sets the "task_id" field if the given value is not nil. -func (ruo *RecordUpdateOne) SetNillableTaskID(s *string) *RecordUpdateOne { - if s != nil { - ruo.SetTaskID(*s) - } - return ruo -} - -// SetModelType sets the "model_type" field. -func (ruo *RecordUpdateOne) SetModelType(ct consts.ModelType) *RecordUpdateOne { - ruo.mutation.SetModelType(ct) - return ruo -} - -// SetNillableModelType sets the "model_type" field if the given value is not nil. -func (ruo *RecordUpdateOne) SetNillableModelType(ct *consts.ModelType) *RecordUpdateOne { - if ct != nil { - ruo.SetModelType(*ct) - } - return ruo -} - -// ClearModelType clears the value of the "model_type" field. -func (ruo *RecordUpdateOne) ClearModelType() *RecordUpdateOne { - ruo.mutation.ClearModelType() - return ruo -} - -// SetPrompt sets the "prompt" field. -func (ruo *RecordUpdateOne) SetPrompt(s string) *RecordUpdateOne { - ruo.mutation.SetPrompt(s) - return ruo -} - -// SetNillablePrompt sets the "prompt" field if the given value is not nil. -func (ruo *RecordUpdateOne) SetNillablePrompt(s *string) *RecordUpdateOne { - if s != nil { - ruo.SetPrompt(*s) - } - return ruo -} - -// ClearPrompt clears the value of the "prompt" field. -func (ruo *RecordUpdateOne) ClearPrompt() *RecordUpdateOne { - ruo.mutation.ClearPrompt() - return ruo -} - -// SetCompletion sets the "completion" field. -func (ruo *RecordUpdateOne) SetCompletion(s string) *RecordUpdateOne { - ruo.mutation.SetCompletion(s) - return ruo -} - -// SetNillableCompletion sets the "completion" field if the given value is not nil. -func (ruo *RecordUpdateOne) SetNillableCompletion(s *string) *RecordUpdateOne { - if s != nil { - ruo.SetCompletion(*s) - } - return ruo -} - -// ClearCompletion clears the value of the "completion" field. -func (ruo *RecordUpdateOne) ClearCompletion() *RecordUpdateOne { - ruo.mutation.ClearCompletion() - return ruo -} - -// SetIsAccept sets the "is_accept" field. -func (ruo *RecordUpdateOne) SetIsAccept(b bool) *RecordUpdateOne { - ruo.mutation.SetIsAccept(b) - return ruo -} - -// SetNillableIsAccept sets the "is_accept" field if the given value is not nil. -func (ruo *RecordUpdateOne) SetNillableIsAccept(b *bool) *RecordUpdateOne { - if b != nil { - ruo.SetIsAccept(*b) - } - return ruo -} - -// SetProgramLanguage sets the "program_language" field. -func (ruo *RecordUpdateOne) SetProgramLanguage(s string) *RecordUpdateOne { - ruo.mutation.SetProgramLanguage(s) - return ruo -} - -// SetNillableProgramLanguage sets the "program_language" field if the given value is not nil. -func (ruo *RecordUpdateOne) SetNillableProgramLanguage(s *string) *RecordUpdateOne { - if s != nil { - ruo.SetProgramLanguage(*s) - } - return ruo -} - -// ClearProgramLanguage clears the value of the "program_language" field. -func (ruo *RecordUpdateOne) ClearProgramLanguage() *RecordUpdateOne { - ruo.mutation.ClearProgramLanguage() - return ruo -} - -// SetWorkMode sets the "work_mode" field. -func (ruo *RecordUpdateOne) SetWorkMode(s string) *RecordUpdateOne { - ruo.mutation.SetWorkMode(s) - return ruo -} - -// SetNillableWorkMode sets the "work_mode" field if the given value is not nil. -func (ruo *RecordUpdateOne) SetNillableWorkMode(s *string) *RecordUpdateOne { - if s != nil { - ruo.SetWorkMode(*s) - } - return ruo -} - -// ClearWorkMode clears the value of the "work_mode" field. -func (ruo *RecordUpdateOne) ClearWorkMode() *RecordUpdateOne { - ruo.mutation.ClearWorkMode() - return ruo -} - -// SetCodeLines sets the "code_lines" field. -func (ruo *RecordUpdateOne) SetCodeLines(i int64) *RecordUpdateOne { - ruo.mutation.ResetCodeLines() - ruo.mutation.SetCodeLines(i) - return ruo -} - -// SetNillableCodeLines sets the "code_lines" field if the given value is not nil. -func (ruo *RecordUpdateOne) SetNillableCodeLines(i *int64) *RecordUpdateOne { - if i != nil { - ruo.SetCodeLines(*i) - } - return ruo -} - -// AddCodeLines adds i to the "code_lines" field. -func (ruo *RecordUpdateOne) AddCodeLines(i int64) *RecordUpdateOne { - ruo.mutation.AddCodeLines(i) - return ruo -} - -// ClearCodeLines clears the value of the "code_lines" field. -func (ruo *RecordUpdateOne) ClearCodeLines() *RecordUpdateOne { - ruo.mutation.ClearCodeLines() - return ruo -} - -// SetInputTokens sets the "input_tokens" field. -func (ruo *RecordUpdateOne) SetInputTokens(i int64) *RecordUpdateOne { - ruo.mutation.ResetInputTokens() - ruo.mutation.SetInputTokens(i) - return ruo -} - -// SetNillableInputTokens sets the "input_tokens" field if the given value is not nil. -func (ruo *RecordUpdateOne) SetNillableInputTokens(i *int64) *RecordUpdateOne { - if i != nil { - ruo.SetInputTokens(*i) - } - return ruo -} - -// AddInputTokens adds i to the "input_tokens" field. -func (ruo *RecordUpdateOne) AddInputTokens(i int64) *RecordUpdateOne { - ruo.mutation.AddInputTokens(i) - return ruo -} - -// SetOutputTokens sets the "output_tokens" field. -func (ruo *RecordUpdateOne) SetOutputTokens(i int64) *RecordUpdateOne { - ruo.mutation.ResetOutputTokens() - ruo.mutation.SetOutputTokens(i) - return ruo -} - -// SetNillableOutputTokens sets the "output_tokens" field if the given value is not nil. -func (ruo *RecordUpdateOne) SetNillableOutputTokens(i *int64) *RecordUpdateOne { - if i != nil { - ruo.SetOutputTokens(*i) - } - return ruo -} - -// AddOutputTokens adds i to the "output_tokens" field. -func (ruo *RecordUpdateOne) AddOutputTokens(i int64) *RecordUpdateOne { - ruo.mutation.AddOutputTokens(i) - return ruo -} - -// SetCreatedAt sets the "created_at" field. -func (ruo *RecordUpdateOne) SetCreatedAt(t time.Time) *RecordUpdateOne { - ruo.mutation.SetCreatedAt(t) - return ruo -} - -// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. -func (ruo *RecordUpdateOne) SetNillableCreatedAt(t *time.Time) *RecordUpdateOne { - if t != nil { - ruo.SetCreatedAt(*t) - } - return ruo -} - -// SetUpdatedAt sets the "updated_at" field. -func (ruo *RecordUpdateOne) SetUpdatedAt(t time.Time) *RecordUpdateOne { - ruo.mutation.SetUpdatedAt(t) - return ruo -} - -// SetUser sets the "user" edge to the User entity. -func (ruo *RecordUpdateOne) SetUser(u *User) *RecordUpdateOne { - return ruo.SetUserID(u.ID) -} - -// SetModel sets the "model" edge to the Model entity. -func (ruo *RecordUpdateOne) SetModel(m *Model) *RecordUpdateOne { - return ruo.SetModelID(m.ID) -} - -// Mutation returns the RecordMutation object of the builder. -func (ruo *RecordUpdateOne) Mutation() *RecordMutation { - return ruo.mutation -} - -// ClearUser clears the "user" edge to the User entity. -func (ruo *RecordUpdateOne) ClearUser() *RecordUpdateOne { - ruo.mutation.ClearUser() - return ruo -} - -// ClearModel clears the "model" edge to the Model entity. -func (ruo *RecordUpdateOne) ClearModel() *RecordUpdateOne { - ruo.mutation.ClearModel() - return ruo -} - -// Where appends a list predicates to the RecordUpdate builder. -func (ruo *RecordUpdateOne) Where(ps ...predicate.Record) *RecordUpdateOne { - ruo.mutation.Where(ps...) - return ruo -} - -// Select allows selecting one or more fields (columns) of the returned entity. -// The default is selecting all fields defined in the entity schema. -func (ruo *RecordUpdateOne) Select(field string, fields ...string) *RecordUpdateOne { - ruo.fields = append([]string{field}, fields...) - return ruo -} - -// Save executes the query and returns the updated Record entity. -func (ruo *RecordUpdateOne) Save(ctx context.Context) (*Record, error) { - ruo.defaults() - return withHooks(ctx, ruo.sqlSave, ruo.mutation, ruo.hooks) -} - -// SaveX is like Save, but panics if an error occurs. -func (ruo *RecordUpdateOne) SaveX(ctx context.Context) *Record { - node, err := ruo.Save(ctx) - if err != nil { - panic(err) - } - return node -} - -// Exec executes the query on the entity. -func (ruo *RecordUpdateOne) Exec(ctx context.Context) error { - _, err := ruo.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (ruo *RecordUpdateOne) ExecX(ctx context.Context) { - if err := ruo.Exec(ctx); err != nil { - panic(err) - } -} - -// defaults sets the default values of the builder before save. -func (ruo *RecordUpdateOne) defaults() { - if _, ok := ruo.mutation.UpdatedAt(); !ok { - v := record.UpdateDefaultUpdatedAt() - ruo.mutation.SetUpdatedAt(v) - } -} - -// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. -func (ruo *RecordUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *RecordUpdateOne { - ruo.modifiers = append(ruo.modifiers, modifiers...) - return ruo -} - -func (ruo *RecordUpdateOne) sqlSave(ctx context.Context) (_node *Record, err error) { - _spec := sqlgraph.NewUpdateSpec(record.Table, record.Columns, sqlgraph.NewFieldSpec(record.FieldID, field.TypeUUID)) - id, ok := ruo.mutation.ID() - if !ok { - return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "Record.id" for update`)} - } - _spec.Node.ID.Value = id - if fields := ruo.fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, record.FieldID) - for _, f := range fields { - if !record.ValidColumn(f) { - return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} - } - if f != record.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, f) - } - } - } - if ps := ruo.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if value, ok := ruo.mutation.TaskID(); ok { - _spec.SetField(record.FieldTaskID, field.TypeString, value) - } - if value, ok := ruo.mutation.ModelType(); ok { - _spec.SetField(record.FieldModelType, field.TypeString, value) - } - if ruo.mutation.ModelTypeCleared() { - _spec.ClearField(record.FieldModelType, field.TypeString) - } - if value, ok := ruo.mutation.Prompt(); ok { - _spec.SetField(record.FieldPrompt, field.TypeString, value) - } - if ruo.mutation.PromptCleared() { - _spec.ClearField(record.FieldPrompt, field.TypeString) - } - if value, ok := ruo.mutation.Completion(); ok { - _spec.SetField(record.FieldCompletion, field.TypeString, value) - } - if ruo.mutation.CompletionCleared() { - _spec.ClearField(record.FieldCompletion, field.TypeString) - } - if value, ok := ruo.mutation.IsAccept(); ok { - _spec.SetField(record.FieldIsAccept, field.TypeBool, value) - } - if value, ok := ruo.mutation.ProgramLanguage(); ok { - _spec.SetField(record.FieldProgramLanguage, field.TypeString, value) - } - if ruo.mutation.ProgramLanguageCleared() { - _spec.ClearField(record.FieldProgramLanguage, field.TypeString) - } - if value, ok := ruo.mutation.WorkMode(); ok { - _spec.SetField(record.FieldWorkMode, field.TypeString, value) - } - if ruo.mutation.WorkModeCleared() { - _spec.ClearField(record.FieldWorkMode, field.TypeString) - } - if value, ok := ruo.mutation.CodeLines(); ok { - _spec.SetField(record.FieldCodeLines, field.TypeInt64, value) - } - if value, ok := ruo.mutation.AddedCodeLines(); ok { - _spec.AddField(record.FieldCodeLines, field.TypeInt64, value) - } - if ruo.mutation.CodeLinesCleared() { - _spec.ClearField(record.FieldCodeLines, field.TypeInt64) - } - if value, ok := ruo.mutation.InputTokens(); ok { - _spec.SetField(record.FieldInputTokens, field.TypeInt64, value) - } - if value, ok := ruo.mutation.AddedInputTokens(); ok { - _spec.AddField(record.FieldInputTokens, field.TypeInt64, value) - } - if value, ok := ruo.mutation.OutputTokens(); ok { - _spec.SetField(record.FieldOutputTokens, field.TypeInt64, value) - } - if value, ok := ruo.mutation.AddedOutputTokens(); ok { - _spec.AddField(record.FieldOutputTokens, field.TypeInt64, value) - } - if value, ok := ruo.mutation.CreatedAt(); ok { - _spec.SetField(record.FieldCreatedAt, field.TypeTime, value) - } - if value, ok := ruo.mutation.UpdatedAt(); ok { - _spec.SetField(record.FieldUpdatedAt, field.TypeTime, value) - } - if ruo.mutation.UserCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: true, - Table: record.UserTable, - Columns: []string{record.UserColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := ruo.mutation.UserIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: true, - Table: record.UserTable, - Columns: []string{record.UserColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } - if ruo.mutation.ModelCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: true, - Table: record.ModelTable, - Columns: []string{record.ModelColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(model.FieldID, field.TypeUUID), - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := ruo.mutation.ModelIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: true, - Table: record.ModelTable, - Columns: []string{record.ModelColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(model.FieldID, field.TypeUUID), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } - _spec.AddModifiers(ruo.modifiers...) - _node = &Record{config: ruo.config} - _spec.Assign = _node.assignValues - _spec.ScanValues = _node.scanValues - if err = sqlgraph.UpdateNode(ctx, ruo.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{record.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return nil, err - } - ruo.mutation.done = true - return _node, nil -} diff --git a/backend/db/runtime/runtime.go b/backend/db/runtime/runtime.go index 9d628bc..36513d6 100644 --- a/backend/db/runtime/runtime.go +++ b/backend/db/runtime/runtime.go @@ -15,8 +15,9 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/billingusage" "github.com/chaitin/MonkeyCode/backend/db/invitecode" "github.com/chaitin/MonkeyCode/backend/db/model" - "github.com/chaitin/MonkeyCode/backend/db/record" "github.com/chaitin/MonkeyCode/backend/db/setting" + "github.com/chaitin/MonkeyCode/backend/db/task" + "github.com/chaitin/MonkeyCode/backend/db/taskrecord" "github.com/chaitin/MonkeyCode/backend/db/user" "github.com/chaitin/MonkeyCode/backend/db/userloginhistory" "github.com/chaitin/MonkeyCode/backend/ent/schema" @@ -154,22 +155,6 @@ func init() { model.DefaultUpdatedAt = modelDescUpdatedAt.Default.(func() time.Time) // model.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. model.UpdateDefaultUpdatedAt = modelDescUpdatedAt.UpdateDefault.(func() time.Time) - recordFields := schema.Record{}.Fields() - _ = recordFields - // recordDescIsAccept is the schema descriptor for is_accept field. - recordDescIsAccept := recordFields[7].Descriptor() - // record.DefaultIsAccept holds the default value on creation for the is_accept field. - record.DefaultIsAccept = recordDescIsAccept.Default.(bool) - // recordDescCreatedAt is the schema descriptor for created_at field. - recordDescCreatedAt := recordFields[13].Descriptor() - // record.DefaultCreatedAt holds the default value on creation for the created_at field. - record.DefaultCreatedAt = recordDescCreatedAt.Default.(func() time.Time) - // recordDescUpdatedAt is the schema descriptor for updated_at field. - recordDescUpdatedAt := recordFields[14].Descriptor() - // record.DefaultUpdatedAt holds the default value on creation for the updated_at field. - record.DefaultUpdatedAt = recordDescUpdatedAt.Default.(func() time.Time) - // record.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. - record.UpdateDefaultUpdatedAt = recordDescUpdatedAt.UpdateDefault.(func() time.Time) settingFields := schema.Setting{}.Fields() _ = settingFields // settingDescEnableSSO is the schema descriptor for enable_sso field. @@ -194,6 +179,34 @@ func init() { setting.DefaultUpdatedAt = settingDescUpdatedAt.Default.(func() time.Time) // setting.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. setting.UpdateDefaultUpdatedAt = settingDescUpdatedAt.UpdateDefault.(func() time.Time) + taskFields := schema.Task{}.Fields() + _ = taskFields + // taskDescIsAccept is the schema descriptor for is_accept field. + taskDescIsAccept := taskFields[7].Descriptor() + // task.DefaultIsAccept holds the default value on creation for the is_accept field. + task.DefaultIsAccept = taskDescIsAccept.Default.(bool) + // taskDescCreatedAt is the schema descriptor for created_at field. + taskDescCreatedAt := taskFields[14].Descriptor() + // task.DefaultCreatedAt holds the default value on creation for the created_at field. + task.DefaultCreatedAt = taskDescCreatedAt.Default.(func() time.Time) + // taskDescUpdatedAt is the schema descriptor for updated_at field. + taskDescUpdatedAt := taskFields[15].Descriptor() + // task.DefaultUpdatedAt holds the default value on creation for the updated_at field. + task.DefaultUpdatedAt = taskDescUpdatedAt.Default.(func() time.Time) + // task.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. + task.UpdateDefaultUpdatedAt = taskDescUpdatedAt.UpdateDefault.(func() time.Time) + taskrecordFields := schema.TaskRecord{}.Fields() + _ = taskrecordFields + // taskrecordDescCreatedAt is the schema descriptor for created_at field. + taskrecordDescCreatedAt := taskrecordFields[4].Descriptor() + // taskrecord.DefaultCreatedAt holds the default value on creation for the created_at field. + taskrecord.DefaultCreatedAt = taskrecordDescCreatedAt.Default.(func() time.Time) + // taskrecordDescUpdatedAt is the schema descriptor for updated_at field. + taskrecordDescUpdatedAt := taskrecordFields[5].Descriptor() + // taskrecord.DefaultUpdatedAt holds the default value on creation for the updated_at field. + taskrecord.DefaultUpdatedAt = taskrecordDescUpdatedAt.Default.(func() time.Time) + // taskrecord.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. + taskrecord.UpdateDefaultUpdatedAt = taskrecordDescUpdatedAt.UpdateDefault.(func() time.Time) userFields := schema.User{}.Fields() _ = userFields // userDescStatus is the schema descriptor for status field. diff --git a/backend/db/record.go b/backend/db/task.go similarity index 61% rename from backend/db/record.go rename to backend/db/task.go index b296370..3c86a41 100644 --- a/backend/db/record.go +++ b/backend/db/task.go @@ -11,34 +11,36 @@ import ( "entgo.io/ent/dialect/sql" "github.com/chaitin/MonkeyCode/backend/consts" "github.com/chaitin/MonkeyCode/backend/db/model" - "github.com/chaitin/MonkeyCode/backend/db/record" + "github.com/chaitin/MonkeyCode/backend/db/task" "github.com/chaitin/MonkeyCode/backend/db/user" "github.com/google/uuid" ) -// Record is the model entity for the Record schema. -type Record struct { +// Task is the model entity for the Task schema. +type Task struct { config `json:"-"` // ID of the ent. ID uuid.UUID `json:"id,omitempty"` + // TaskID holds the value of the "task_id" field. + TaskID string `json:"task_id,omitempty"` // UserID holds the value of the "user_id" field. UserID uuid.UUID `json:"user_id,omitempty"` // ModelID holds the value of the "model_id" field. ModelID uuid.UUID `json:"model_id,omitempty"` - // TaskID holds the value of the "task_id" field. - TaskID string `json:"task_id,omitempty"` + // RequestID holds the value of the "request_id" field. + RequestID string `json:"request_id,omitempty"` // ModelType holds the value of the "model_type" field. ModelType consts.ModelType `json:"model_type,omitempty"` // Prompt holds the value of the "prompt" field. Prompt string `json:"prompt,omitempty"` - // Completion holds the value of the "completion" field. - Completion string `json:"completion,omitempty"` // IsAccept holds the value of the "is_accept" field. IsAccept bool `json:"is_accept,omitempty"` // ProgramLanguage holds the value of the "program_language" field. ProgramLanguage string `json:"program_language,omitempty"` // WorkMode holds the value of the "work_mode" field. WorkMode string `json:"work_mode,omitempty"` + // Completion holds the value of the "completion" field. + Completion string `json:"completion,omitempty"` // CodeLines holds the value of the "code_lines" field. CodeLines int64 `json:"code_lines,omitempty"` // InputTokens holds the value of the "input_tokens" field. @@ -50,28 +52,39 @@ type Record struct { // UpdatedAt holds the value of the "updated_at" field. UpdatedAt time.Time `json:"updated_at,omitempty"` // Edges holds the relations/edges for other nodes in the graph. - // The values are being populated by the RecordQuery when eager-loading is set. - Edges RecordEdges `json:"edges"` + // The values are being populated by the TaskQuery when eager-loading is set. + Edges TaskEdges `json:"edges"` selectValues sql.SelectValues } -// RecordEdges holds the relations/edges for other nodes in the graph. -type RecordEdges struct { +// TaskEdges holds the relations/edges for other nodes in the graph. +type TaskEdges struct { + // TaskRecords holds the value of the task_records edge. + TaskRecords []*TaskRecord `json:"task_records,omitempty"` // User holds the value of the user edge. User *User `json:"user,omitempty"` // Model holds the value of the model edge. Model *Model `json:"model,omitempty"` // loadedTypes holds the information for reporting if a // type was loaded (or requested) in eager-loading or not. - loadedTypes [2]bool + loadedTypes [3]bool +} + +// TaskRecordsOrErr returns the TaskRecords value or an error if the edge +// was not loaded in eager-loading. +func (e TaskEdges) TaskRecordsOrErr() ([]*TaskRecord, error) { + if e.loadedTypes[0] { + return e.TaskRecords, nil + } + return nil, &NotLoadedError{edge: "task_records"} } // UserOrErr returns the User value or an error if the edge // was not loaded in eager-loading, or loaded but was not found. -func (e RecordEdges) UserOrErr() (*User, error) { +func (e TaskEdges) UserOrErr() (*User, error) { if e.User != nil { return e.User, nil - } else if e.loadedTypes[0] { + } else if e.loadedTypes[1] { return nil, &NotFoundError{label: user.Label} } return nil, &NotLoadedError{edge: "user"} @@ -79,29 +92,29 @@ func (e RecordEdges) UserOrErr() (*User, error) { // ModelOrErr returns the Model value or an error if the edge // was not loaded in eager-loading, or loaded but was not found. -func (e RecordEdges) ModelOrErr() (*Model, error) { +func (e TaskEdges) ModelOrErr() (*Model, error) { if e.Model != nil { return e.Model, nil - } else if e.loadedTypes[1] { + } else if e.loadedTypes[2] { return nil, &NotFoundError{label: model.Label} } return nil, &NotLoadedError{edge: "model"} } // scanValues returns the types for scanning values from sql.Rows. -func (*Record) scanValues(columns []string) ([]any, error) { +func (*Task) scanValues(columns []string) ([]any, error) { values := make([]any, len(columns)) for i := range columns { switch columns[i] { - case record.FieldIsAccept: + case task.FieldIsAccept: values[i] = new(sql.NullBool) - case record.FieldCodeLines, record.FieldInputTokens, record.FieldOutputTokens: + case task.FieldCodeLines, task.FieldInputTokens, task.FieldOutputTokens: values[i] = new(sql.NullInt64) - case record.FieldTaskID, record.FieldModelType, record.FieldPrompt, record.FieldCompletion, record.FieldProgramLanguage, record.FieldWorkMode: + case task.FieldTaskID, task.FieldRequestID, task.FieldModelType, task.FieldPrompt, task.FieldProgramLanguage, task.FieldWorkMode, task.FieldCompletion: values[i] = new(sql.NullString) - case record.FieldCreatedAt, record.FieldUpdatedAt: + case task.FieldCreatedAt, task.FieldUpdatedAt: values[i] = new(sql.NullTime) - case record.FieldID, record.FieldUserID, record.FieldModelID: + case task.FieldID, task.FieldUserID, task.FieldModelID: values[i] = new(uuid.UUID) default: values[i] = new(sql.UnknownType) @@ -111,193 +124,207 @@ func (*Record) scanValues(columns []string) ([]any, error) { } // assignValues assigns the values that were returned from sql.Rows (after scanning) -// to the Record fields. -func (r *Record) assignValues(columns []string, values []any) error { +// to the Task fields. +func (t *Task) assignValues(columns []string, values []any) error { if m, n := len(values), len(columns); m < n { return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) } for i := range columns { switch columns[i] { - case record.FieldID: + case task.FieldID: if value, ok := values[i].(*uuid.UUID); !ok { return fmt.Errorf("unexpected type %T for field id", values[i]) } else if value != nil { - r.ID = *value + t.ID = *value } - case record.FieldUserID: - if value, ok := values[i].(*uuid.UUID); !ok { - return fmt.Errorf("unexpected type %T for field user_id", values[i]) - } else if value != nil { - r.UserID = *value - } - case record.FieldModelID: - if value, ok := values[i].(*uuid.UUID); !ok { - return fmt.Errorf("unexpected type %T for field model_id", values[i]) - } else if value != nil { - r.ModelID = *value - } - case record.FieldTaskID: + case task.FieldTaskID: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field task_id", values[i]) } else if value.Valid { - r.TaskID = value.String + t.TaskID = value.String } - case record.FieldModelType: + case task.FieldUserID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field user_id", values[i]) + } else if value != nil { + t.UserID = *value + } + case task.FieldModelID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field model_id", values[i]) + } else if value != nil { + t.ModelID = *value + } + case task.FieldRequestID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field request_id", values[i]) + } else if value.Valid { + t.RequestID = value.String + } + case task.FieldModelType: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field model_type", values[i]) } else if value.Valid { - r.ModelType = consts.ModelType(value.String) + t.ModelType = consts.ModelType(value.String) } - case record.FieldPrompt: + case task.FieldPrompt: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field prompt", values[i]) } else if value.Valid { - r.Prompt = value.String + t.Prompt = value.String } - case record.FieldCompletion: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field completion", values[i]) - } else if value.Valid { - r.Completion = value.String - } - case record.FieldIsAccept: + case task.FieldIsAccept: if value, ok := values[i].(*sql.NullBool); !ok { return fmt.Errorf("unexpected type %T for field is_accept", values[i]) } else if value.Valid { - r.IsAccept = value.Bool + t.IsAccept = value.Bool } - case record.FieldProgramLanguage: + case task.FieldProgramLanguage: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field program_language", values[i]) } else if value.Valid { - r.ProgramLanguage = value.String + t.ProgramLanguage = value.String } - case record.FieldWorkMode: + case task.FieldWorkMode: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field work_mode", values[i]) } else if value.Valid { - r.WorkMode = value.String + t.WorkMode = value.String } - case record.FieldCodeLines: + case task.FieldCompletion: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field completion", values[i]) + } else if value.Valid { + t.Completion = value.String + } + case task.FieldCodeLines: if value, ok := values[i].(*sql.NullInt64); !ok { return fmt.Errorf("unexpected type %T for field code_lines", values[i]) } else if value.Valid { - r.CodeLines = value.Int64 + t.CodeLines = value.Int64 } - case record.FieldInputTokens: + case task.FieldInputTokens: if value, ok := values[i].(*sql.NullInt64); !ok { return fmt.Errorf("unexpected type %T for field input_tokens", values[i]) } else if value.Valid { - r.InputTokens = value.Int64 + t.InputTokens = value.Int64 } - case record.FieldOutputTokens: + case task.FieldOutputTokens: if value, ok := values[i].(*sql.NullInt64); !ok { return fmt.Errorf("unexpected type %T for field output_tokens", values[i]) } else if value.Valid { - r.OutputTokens = value.Int64 + t.OutputTokens = value.Int64 } - case record.FieldCreatedAt: + case task.FieldCreatedAt: if value, ok := values[i].(*sql.NullTime); !ok { return fmt.Errorf("unexpected type %T for field created_at", values[i]) } else if value.Valid { - r.CreatedAt = value.Time + t.CreatedAt = value.Time } - case record.FieldUpdatedAt: + case task.FieldUpdatedAt: if value, ok := values[i].(*sql.NullTime); !ok { return fmt.Errorf("unexpected type %T for field updated_at", values[i]) } else if value.Valid { - r.UpdatedAt = value.Time + t.UpdatedAt = value.Time } default: - r.selectValues.Set(columns[i], values[i]) + t.selectValues.Set(columns[i], values[i]) } } return nil } -// Value returns the ent.Value that was dynamically selected and assigned to the Record. +// Value returns the ent.Value that was dynamically selected and assigned to the Task. // This includes values selected through modifiers, order, etc. -func (r *Record) Value(name string) (ent.Value, error) { - return r.selectValues.Get(name) +func (t *Task) Value(name string) (ent.Value, error) { + return t.selectValues.Get(name) } -// QueryUser queries the "user" edge of the Record entity. -func (r *Record) QueryUser() *UserQuery { - return NewRecordClient(r.config).QueryUser(r) +// QueryTaskRecords queries the "task_records" edge of the Task entity. +func (t *Task) QueryTaskRecords() *TaskRecordQuery { + return NewTaskClient(t.config).QueryTaskRecords(t) } -// QueryModel queries the "model" edge of the Record entity. -func (r *Record) QueryModel() *ModelQuery { - return NewRecordClient(r.config).QueryModel(r) +// QueryUser queries the "user" edge of the Task entity. +func (t *Task) QueryUser() *UserQuery { + return NewTaskClient(t.config).QueryUser(t) } -// Update returns a builder for updating this Record. -// Note that you need to call Record.Unwrap() before calling this method if this Record +// QueryModel queries the "model" edge of the Task entity. +func (t *Task) QueryModel() *ModelQuery { + return NewTaskClient(t.config).QueryModel(t) +} + +// Update returns a builder for updating this Task. +// Note that you need to call Task.Unwrap() before calling this method if this Task // was returned from a transaction, and the transaction was committed or rolled back. -func (r *Record) Update() *RecordUpdateOne { - return NewRecordClient(r.config).UpdateOne(r) +func (t *Task) Update() *TaskUpdateOne { + return NewTaskClient(t.config).UpdateOne(t) } -// Unwrap unwraps the Record entity that was returned from a transaction after it was closed, +// Unwrap unwraps the Task entity that was returned from a transaction after it was closed, // so that all future queries will be executed through the driver which created the transaction. -func (r *Record) Unwrap() *Record { - _tx, ok := r.config.driver.(*txDriver) +func (t *Task) Unwrap() *Task { + _tx, ok := t.config.driver.(*txDriver) if !ok { - panic("db: Record is not a transactional entity") + panic("db: Task is not a transactional entity") } - r.config.driver = _tx.drv - return r + t.config.driver = _tx.drv + return t } // String implements the fmt.Stringer. -func (r *Record) String() string { +func (t *Task) String() string { var builder strings.Builder - builder.WriteString("Record(") - builder.WriteString(fmt.Sprintf("id=%v, ", r.ID)) + builder.WriteString("Task(") + builder.WriteString(fmt.Sprintf("id=%v, ", t.ID)) + builder.WriteString("task_id=") + builder.WriteString(t.TaskID) + builder.WriteString(", ") builder.WriteString("user_id=") - builder.WriteString(fmt.Sprintf("%v", r.UserID)) + builder.WriteString(fmt.Sprintf("%v", t.UserID)) builder.WriteString(", ") builder.WriteString("model_id=") - builder.WriteString(fmt.Sprintf("%v", r.ModelID)) + builder.WriteString(fmt.Sprintf("%v", t.ModelID)) builder.WriteString(", ") - builder.WriteString("task_id=") - builder.WriteString(r.TaskID) + builder.WriteString("request_id=") + builder.WriteString(t.RequestID) builder.WriteString(", ") builder.WriteString("model_type=") - builder.WriteString(fmt.Sprintf("%v", r.ModelType)) + builder.WriteString(fmt.Sprintf("%v", t.ModelType)) builder.WriteString(", ") builder.WriteString("prompt=") - builder.WriteString(r.Prompt) - builder.WriteString(", ") - builder.WriteString("completion=") - builder.WriteString(r.Completion) + builder.WriteString(t.Prompt) builder.WriteString(", ") builder.WriteString("is_accept=") - builder.WriteString(fmt.Sprintf("%v", r.IsAccept)) + builder.WriteString(fmt.Sprintf("%v", t.IsAccept)) builder.WriteString(", ") builder.WriteString("program_language=") - builder.WriteString(r.ProgramLanguage) + builder.WriteString(t.ProgramLanguage) builder.WriteString(", ") builder.WriteString("work_mode=") - builder.WriteString(r.WorkMode) + builder.WriteString(t.WorkMode) + builder.WriteString(", ") + builder.WriteString("completion=") + builder.WriteString(t.Completion) builder.WriteString(", ") builder.WriteString("code_lines=") - builder.WriteString(fmt.Sprintf("%v", r.CodeLines)) + builder.WriteString(fmt.Sprintf("%v", t.CodeLines)) builder.WriteString(", ") builder.WriteString("input_tokens=") - builder.WriteString(fmt.Sprintf("%v", r.InputTokens)) + builder.WriteString(fmt.Sprintf("%v", t.InputTokens)) builder.WriteString(", ") builder.WriteString("output_tokens=") - builder.WriteString(fmt.Sprintf("%v", r.OutputTokens)) + builder.WriteString(fmt.Sprintf("%v", t.OutputTokens)) builder.WriteString(", ") builder.WriteString("created_at=") - builder.WriteString(r.CreatedAt.Format(time.ANSIC)) + builder.WriteString(t.CreatedAt.Format(time.ANSIC)) builder.WriteString(", ") builder.WriteString("updated_at=") - builder.WriteString(r.UpdatedAt.Format(time.ANSIC)) + builder.WriteString(t.UpdatedAt.Format(time.ANSIC)) builder.WriteByte(')') return builder.String() } -// Records is a parsable slice of Record. -type Records []*Record +// Tasks is a parsable slice of Task. +type Tasks []*Task diff --git a/backend/db/record/record.go b/backend/db/task/task.go similarity index 78% rename from backend/db/record/record.go rename to backend/db/task/task.go index 4797926..ef9b130 100644 --- a/backend/db/record/record.go +++ b/backend/db/task/task.go @@ -1,6 +1,6 @@ // Code generated by ent, DO NOT EDIT. -package record +package task import ( "time" @@ -10,28 +10,30 @@ import ( ) const ( - // Label holds the string label denoting the record type in the database. - Label = "record" + // Label holds the string label denoting the task type in the database. + Label = "task" // FieldID holds the string denoting the id field in the database. FieldID = "id" + // FieldTaskID holds the string denoting the task_id field in the database. + FieldTaskID = "task_id" // FieldUserID holds the string denoting the user_id field in the database. FieldUserID = "user_id" // FieldModelID holds the string denoting the model_id field in the database. FieldModelID = "model_id" - // FieldTaskID holds the string denoting the task_id field in the database. - FieldTaskID = "task_id" + // FieldRequestID holds the string denoting the request_id field in the database. + FieldRequestID = "request_id" // FieldModelType holds the string denoting the model_type field in the database. FieldModelType = "model_type" // FieldPrompt holds the string denoting the prompt field in the database. FieldPrompt = "prompt" - // FieldCompletion holds the string denoting the completion field in the database. - FieldCompletion = "completion" // FieldIsAccept holds the string denoting the is_accept field in the database. FieldIsAccept = "is_accept" // FieldProgramLanguage holds the string denoting the program_language field in the database. FieldProgramLanguage = "program_language" // FieldWorkMode holds the string denoting the work_mode field in the database. FieldWorkMode = "work_mode" + // FieldCompletion holds the string denoting the completion field in the database. + FieldCompletion = "completion" // FieldCodeLines holds the string denoting the code_lines field in the database. FieldCodeLines = "code_lines" // FieldInputTokens holds the string denoting the input_tokens field in the database. @@ -42,21 +44,30 @@ const ( FieldCreatedAt = "created_at" // FieldUpdatedAt holds the string denoting the updated_at field in the database. FieldUpdatedAt = "updated_at" + // EdgeTaskRecords holds the string denoting the task_records edge name in mutations. + EdgeTaskRecords = "task_records" // EdgeUser holds the string denoting the user edge name in mutations. EdgeUser = "user" // EdgeModel holds the string denoting the model edge name in mutations. EdgeModel = "model" - // Table holds the table name of the record in the database. - Table = "records" + // Table holds the table name of the task in the database. + Table = "tasks" + // TaskRecordsTable is the table that holds the task_records relation/edge. + TaskRecordsTable = "task_records" + // TaskRecordsInverseTable is the table name for the TaskRecord entity. + // It exists in this package in order to avoid circular dependency with the "taskrecord" package. + TaskRecordsInverseTable = "task_records" + // TaskRecordsColumn is the table column denoting the task_records relation/edge. + TaskRecordsColumn = "task_id" // UserTable is the table that holds the user relation/edge. - UserTable = "records" + UserTable = "tasks" // UserInverseTable is the table name for the User entity. // It exists in this package in order to avoid circular dependency with the "user" package. UserInverseTable = "users" // UserColumn is the table column denoting the user relation/edge. UserColumn = "user_id" // ModelTable is the table that holds the model relation/edge. - ModelTable = "records" + ModelTable = "tasks" // ModelInverseTable is the table name for the Model entity. // It exists in this package in order to avoid circular dependency with the "model" package. ModelInverseTable = "models" @@ -64,18 +75,19 @@ const ( ModelColumn = "model_id" ) -// Columns holds all SQL columns for record fields. +// Columns holds all SQL columns for task fields. var Columns = []string{ FieldID, + FieldTaskID, FieldUserID, FieldModelID, - FieldTaskID, + FieldRequestID, FieldModelType, FieldPrompt, - FieldCompletion, FieldIsAccept, FieldProgramLanguage, FieldWorkMode, + FieldCompletion, FieldCodeLines, FieldInputTokens, FieldOutputTokens, @@ -104,7 +116,7 @@ var ( UpdateDefaultUpdatedAt func() time.Time ) -// OrderOption defines the ordering options for the Record queries. +// OrderOption defines the ordering options for the Task queries. type OrderOption func(*sql.Selector) // ByID orders the results by the id field. @@ -112,6 +124,11 @@ func ByID(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldID, opts...).ToFunc() } +// ByTaskID orders the results by the task_id field. +func ByTaskID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTaskID, opts...).ToFunc() +} + // ByUserID orders the results by the user_id field. func ByUserID(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldUserID, opts...).ToFunc() @@ -122,9 +139,9 @@ func ByModelID(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldModelID, opts...).ToFunc() } -// ByTaskID orders the results by the task_id field. -func ByTaskID(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldTaskID, opts...).ToFunc() +// ByRequestID orders the results by the request_id field. +func ByRequestID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRequestID, opts...).ToFunc() } // ByModelType orders the results by the model_type field. @@ -137,11 +154,6 @@ func ByPrompt(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldPrompt, opts...).ToFunc() } -// ByCompletion orders the results by the completion field. -func ByCompletion(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldCompletion, opts...).ToFunc() -} - // ByIsAccept orders the results by the is_accept field. func ByIsAccept(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldIsAccept, opts...).ToFunc() @@ -157,6 +169,11 @@ func ByWorkMode(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldWorkMode, opts...).ToFunc() } +// ByCompletion orders the results by the completion field. +func ByCompletion(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCompletion, opts...).ToFunc() +} + // ByCodeLines orders the results by the code_lines field. func ByCodeLines(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldCodeLines, opts...).ToFunc() @@ -182,6 +199,20 @@ func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc() } +// ByTaskRecordsCount orders the results by task_records count. +func ByTaskRecordsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newTaskRecordsStep(), opts...) + } +} + +// ByTaskRecords orders the results by task_records terms. +func ByTaskRecords(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newTaskRecordsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + // ByUserField orders the results by user field. func ByUserField(field string, opts ...sql.OrderTermOption) OrderOption { return func(s *sql.Selector) { @@ -195,6 +226,13 @@ func ByModelField(field string, opts ...sql.OrderTermOption) OrderOption { sqlgraph.OrderByNeighborTerms(s, newModelStep(), sql.OrderByField(field, opts...)) } } +func newTaskRecordsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(TaskRecordsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, TaskRecordsTable, TaskRecordsColumn), + ) +} func newUserStep() *sqlgraph.Step { return sqlgraph.NewStep( sqlgraph.From(Table, FieldID), diff --git a/backend/db/task/where.go b/backend/db/task/where.go new file mode 100644 index 0000000..6675562 --- /dev/null +++ b/backend/db/task/where.go @@ -0,0 +1,1042 @@ +// Code generated by ent, DO NOT EDIT. + +package task + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/chaitin/MonkeyCode/backend/consts" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/google/uuid" +) + +// ID filters vertices based on their ID field. +func ID(id uuid.UUID) predicate.Task { + return predicate.Task(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id uuid.UUID) predicate.Task { + return predicate.Task(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id uuid.UUID) predicate.Task { + return predicate.Task(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...uuid.UUID) predicate.Task { + return predicate.Task(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...uuid.UUID) predicate.Task { + return predicate.Task(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id uuid.UUID) predicate.Task { + return predicate.Task(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id uuid.UUID) predicate.Task { + return predicate.Task(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id uuid.UUID) predicate.Task { + return predicate.Task(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id uuid.UUID) predicate.Task { + return predicate.Task(sql.FieldLTE(FieldID, id)) +} + +// TaskID applies equality check predicate on the "task_id" field. It's identical to TaskIDEQ. +func TaskID(v string) predicate.Task { + return predicate.Task(sql.FieldEQ(FieldTaskID, v)) +} + +// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ. +func UserID(v uuid.UUID) predicate.Task { + return predicate.Task(sql.FieldEQ(FieldUserID, v)) +} + +// ModelID applies equality check predicate on the "model_id" field. It's identical to ModelIDEQ. +func ModelID(v uuid.UUID) predicate.Task { + return predicate.Task(sql.FieldEQ(FieldModelID, v)) +} + +// RequestID applies equality check predicate on the "request_id" field. It's identical to RequestIDEQ. +func RequestID(v string) predicate.Task { + return predicate.Task(sql.FieldEQ(FieldRequestID, v)) +} + +// ModelType applies equality check predicate on the "model_type" field. It's identical to ModelTypeEQ. +func ModelType(v consts.ModelType) predicate.Task { + vc := string(v) + return predicate.Task(sql.FieldEQ(FieldModelType, vc)) +} + +// Prompt applies equality check predicate on the "prompt" field. It's identical to PromptEQ. +func Prompt(v string) predicate.Task { + return predicate.Task(sql.FieldEQ(FieldPrompt, v)) +} + +// IsAccept applies equality check predicate on the "is_accept" field. It's identical to IsAcceptEQ. +func IsAccept(v bool) predicate.Task { + return predicate.Task(sql.FieldEQ(FieldIsAccept, v)) +} + +// ProgramLanguage applies equality check predicate on the "program_language" field. It's identical to ProgramLanguageEQ. +func ProgramLanguage(v string) predicate.Task { + return predicate.Task(sql.FieldEQ(FieldProgramLanguage, v)) +} + +// WorkMode applies equality check predicate on the "work_mode" field. It's identical to WorkModeEQ. +func WorkMode(v string) predicate.Task { + return predicate.Task(sql.FieldEQ(FieldWorkMode, v)) +} + +// Completion applies equality check predicate on the "completion" field. It's identical to CompletionEQ. +func Completion(v string) predicate.Task { + return predicate.Task(sql.FieldEQ(FieldCompletion, v)) +} + +// CodeLines applies equality check predicate on the "code_lines" field. It's identical to CodeLinesEQ. +func CodeLines(v int64) predicate.Task { + return predicate.Task(sql.FieldEQ(FieldCodeLines, v)) +} + +// InputTokens applies equality check predicate on the "input_tokens" field. It's identical to InputTokensEQ. +func InputTokens(v int64) predicate.Task { + return predicate.Task(sql.FieldEQ(FieldInputTokens, v)) +} + +// OutputTokens applies equality check predicate on the "output_tokens" field. It's identical to OutputTokensEQ. +func OutputTokens(v int64) predicate.Task { + return predicate.Task(sql.FieldEQ(FieldOutputTokens, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.Task { + return predicate.Task(sql.FieldEQ(FieldCreatedAt, v)) +} + +// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ. +func UpdatedAt(v time.Time) predicate.Task { + return predicate.Task(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// TaskIDEQ applies the EQ predicate on the "task_id" field. +func TaskIDEQ(v string) predicate.Task { + return predicate.Task(sql.FieldEQ(FieldTaskID, v)) +} + +// TaskIDNEQ applies the NEQ predicate on the "task_id" field. +func TaskIDNEQ(v string) predicate.Task { + return predicate.Task(sql.FieldNEQ(FieldTaskID, v)) +} + +// TaskIDIn applies the In predicate on the "task_id" field. +func TaskIDIn(vs ...string) predicate.Task { + return predicate.Task(sql.FieldIn(FieldTaskID, vs...)) +} + +// TaskIDNotIn applies the NotIn predicate on the "task_id" field. +func TaskIDNotIn(vs ...string) predicate.Task { + return predicate.Task(sql.FieldNotIn(FieldTaskID, vs...)) +} + +// TaskIDGT applies the GT predicate on the "task_id" field. +func TaskIDGT(v string) predicate.Task { + return predicate.Task(sql.FieldGT(FieldTaskID, v)) +} + +// TaskIDGTE applies the GTE predicate on the "task_id" field. +func TaskIDGTE(v string) predicate.Task { + return predicate.Task(sql.FieldGTE(FieldTaskID, v)) +} + +// TaskIDLT applies the LT predicate on the "task_id" field. +func TaskIDLT(v string) predicate.Task { + return predicate.Task(sql.FieldLT(FieldTaskID, v)) +} + +// TaskIDLTE applies the LTE predicate on the "task_id" field. +func TaskIDLTE(v string) predicate.Task { + return predicate.Task(sql.FieldLTE(FieldTaskID, v)) +} + +// TaskIDContains applies the Contains predicate on the "task_id" field. +func TaskIDContains(v string) predicate.Task { + return predicate.Task(sql.FieldContains(FieldTaskID, v)) +} + +// TaskIDHasPrefix applies the HasPrefix predicate on the "task_id" field. +func TaskIDHasPrefix(v string) predicate.Task { + return predicate.Task(sql.FieldHasPrefix(FieldTaskID, v)) +} + +// TaskIDHasSuffix applies the HasSuffix predicate on the "task_id" field. +func TaskIDHasSuffix(v string) predicate.Task { + return predicate.Task(sql.FieldHasSuffix(FieldTaskID, v)) +} + +// TaskIDEqualFold applies the EqualFold predicate on the "task_id" field. +func TaskIDEqualFold(v string) predicate.Task { + return predicate.Task(sql.FieldEqualFold(FieldTaskID, v)) +} + +// TaskIDContainsFold applies the ContainsFold predicate on the "task_id" field. +func TaskIDContainsFold(v string) predicate.Task { + return predicate.Task(sql.FieldContainsFold(FieldTaskID, v)) +} + +// UserIDEQ applies the EQ predicate on the "user_id" field. +func UserIDEQ(v uuid.UUID) predicate.Task { + return predicate.Task(sql.FieldEQ(FieldUserID, v)) +} + +// UserIDNEQ applies the NEQ predicate on the "user_id" field. +func UserIDNEQ(v uuid.UUID) predicate.Task { + return predicate.Task(sql.FieldNEQ(FieldUserID, v)) +} + +// UserIDIn applies the In predicate on the "user_id" field. +func UserIDIn(vs ...uuid.UUID) predicate.Task { + return predicate.Task(sql.FieldIn(FieldUserID, vs...)) +} + +// UserIDNotIn applies the NotIn predicate on the "user_id" field. +func UserIDNotIn(vs ...uuid.UUID) predicate.Task { + return predicate.Task(sql.FieldNotIn(FieldUserID, vs...)) +} + +// UserIDIsNil applies the IsNil predicate on the "user_id" field. +func UserIDIsNil() predicate.Task { + return predicate.Task(sql.FieldIsNull(FieldUserID)) +} + +// UserIDNotNil applies the NotNil predicate on the "user_id" field. +func UserIDNotNil() predicate.Task { + return predicate.Task(sql.FieldNotNull(FieldUserID)) +} + +// ModelIDEQ applies the EQ predicate on the "model_id" field. +func ModelIDEQ(v uuid.UUID) predicate.Task { + return predicate.Task(sql.FieldEQ(FieldModelID, v)) +} + +// ModelIDNEQ applies the NEQ predicate on the "model_id" field. +func ModelIDNEQ(v uuid.UUID) predicate.Task { + return predicate.Task(sql.FieldNEQ(FieldModelID, v)) +} + +// ModelIDIn applies the In predicate on the "model_id" field. +func ModelIDIn(vs ...uuid.UUID) predicate.Task { + return predicate.Task(sql.FieldIn(FieldModelID, vs...)) +} + +// ModelIDNotIn applies the NotIn predicate on the "model_id" field. +func ModelIDNotIn(vs ...uuid.UUID) predicate.Task { + return predicate.Task(sql.FieldNotIn(FieldModelID, vs...)) +} + +// ModelIDIsNil applies the IsNil predicate on the "model_id" field. +func ModelIDIsNil() predicate.Task { + return predicate.Task(sql.FieldIsNull(FieldModelID)) +} + +// ModelIDNotNil applies the NotNil predicate on the "model_id" field. +func ModelIDNotNil() predicate.Task { + return predicate.Task(sql.FieldNotNull(FieldModelID)) +} + +// RequestIDEQ applies the EQ predicate on the "request_id" field. +func RequestIDEQ(v string) predicate.Task { + return predicate.Task(sql.FieldEQ(FieldRequestID, v)) +} + +// RequestIDNEQ applies the NEQ predicate on the "request_id" field. +func RequestIDNEQ(v string) predicate.Task { + return predicate.Task(sql.FieldNEQ(FieldRequestID, v)) +} + +// RequestIDIn applies the In predicate on the "request_id" field. +func RequestIDIn(vs ...string) predicate.Task { + return predicate.Task(sql.FieldIn(FieldRequestID, vs...)) +} + +// RequestIDNotIn applies the NotIn predicate on the "request_id" field. +func RequestIDNotIn(vs ...string) predicate.Task { + return predicate.Task(sql.FieldNotIn(FieldRequestID, vs...)) +} + +// RequestIDGT applies the GT predicate on the "request_id" field. +func RequestIDGT(v string) predicate.Task { + return predicate.Task(sql.FieldGT(FieldRequestID, v)) +} + +// RequestIDGTE applies the GTE predicate on the "request_id" field. +func RequestIDGTE(v string) predicate.Task { + return predicate.Task(sql.FieldGTE(FieldRequestID, v)) +} + +// RequestIDLT applies the LT predicate on the "request_id" field. +func RequestIDLT(v string) predicate.Task { + return predicate.Task(sql.FieldLT(FieldRequestID, v)) +} + +// RequestIDLTE applies the LTE predicate on the "request_id" field. +func RequestIDLTE(v string) predicate.Task { + return predicate.Task(sql.FieldLTE(FieldRequestID, v)) +} + +// RequestIDContains applies the Contains predicate on the "request_id" field. +func RequestIDContains(v string) predicate.Task { + return predicate.Task(sql.FieldContains(FieldRequestID, v)) +} + +// RequestIDHasPrefix applies the HasPrefix predicate on the "request_id" field. +func RequestIDHasPrefix(v string) predicate.Task { + return predicate.Task(sql.FieldHasPrefix(FieldRequestID, v)) +} + +// RequestIDHasSuffix applies the HasSuffix predicate on the "request_id" field. +func RequestIDHasSuffix(v string) predicate.Task { + return predicate.Task(sql.FieldHasSuffix(FieldRequestID, v)) +} + +// RequestIDIsNil applies the IsNil predicate on the "request_id" field. +func RequestIDIsNil() predicate.Task { + return predicate.Task(sql.FieldIsNull(FieldRequestID)) +} + +// RequestIDNotNil applies the NotNil predicate on the "request_id" field. +func RequestIDNotNil() predicate.Task { + return predicate.Task(sql.FieldNotNull(FieldRequestID)) +} + +// RequestIDEqualFold applies the EqualFold predicate on the "request_id" field. +func RequestIDEqualFold(v string) predicate.Task { + return predicate.Task(sql.FieldEqualFold(FieldRequestID, v)) +} + +// RequestIDContainsFold applies the ContainsFold predicate on the "request_id" field. +func RequestIDContainsFold(v string) predicate.Task { + return predicate.Task(sql.FieldContainsFold(FieldRequestID, v)) +} + +// ModelTypeEQ applies the EQ predicate on the "model_type" field. +func ModelTypeEQ(v consts.ModelType) predicate.Task { + vc := string(v) + return predicate.Task(sql.FieldEQ(FieldModelType, vc)) +} + +// ModelTypeNEQ applies the NEQ predicate on the "model_type" field. +func ModelTypeNEQ(v consts.ModelType) predicate.Task { + vc := string(v) + return predicate.Task(sql.FieldNEQ(FieldModelType, vc)) +} + +// ModelTypeIn applies the In predicate on the "model_type" field. +func ModelTypeIn(vs ...consts.ModelType) predicate.Task { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.Task(sql.FieldIn(FieldModelType, v...)) +} + +// ModelTypeNotIn applies the NotIn predicate on the "model_type" field. +func ModelTypeNotIn(vs ...consts.ModelType) predicate.Task { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.Task(sql.FieldNotIn(FieldModelType, v...)) +} + +// ModelTypeGT applies the GT predicate on the "model_type" field. +func ModelTypeGT(v consts.ModelType) predicate.Task { + vc := string(v) + return predicate.Task(sql.FieldGT(FieldModelType, vc)) +} + +// ModelTypeGTE applies the GTE predicate on the "model_type" field. +func ModelTypeGTE(v consts.ModelType) predicate.Task { + vc := string(v) + return predicate.Task(sql.FieldGTE(FieldModelType, vc)) +} + +// ModelTypeLT applies the LT predicate on the "model_type" field. +func ModelTypeLT(v consts.ModelType) predicate.Task { + vc := string(v) + return predicate.Task(sql.FieldLT(FieldModelType, vc)) +} + +// ModelTypeLTE applies the LTE predicate on the "model_type" field. +func ModelTypeLTE(v consts.ModelType) predicate.Task { + vc := string(v) + return predicate.Task(sql.FieldLTE(FieldModelType, vc)) +} + +// ModelTypeContains applies the Contains predicate on the "model_type" field. +func ModelTypeContains(v consts.ModelType) predicate.Task { + vc := string(v) + return predicate.Task(sql.FieldContains(FieldModelType, vc)) +} + +// ModelTypeHasPrefix applies the HasPrefix predicate on the "model_type" field. +func ModelTypeHasPrefix(v consts.ModelType) predicate.Task { + vc := string(v) + return predicate.Task(sql.FieldHasPrefix(FieldModelType, vc)) +} + +// ModelTypeHasSuffix applies the HasSuffix predicate on the "model_type" field. +func ModelTypeHasSuffix(v consts.ModelType) predicate.Task { + vc := string(v) + return predicate.Task(sql.FieldHasSuffix(FieldModelType, vc)) +} + +// ModelTypeEqualFold applies the EqualFold predicate on the "model_type" field. +func ModelTypeEqualFold(v consts.ModelType) predicate.Task { + vc := string(v) + return predicate.Task(sql.FieldEqualFold(FieldModelType, vc)) +} + +// ModelTypeContainsFold applies the ContainsFold predicate on the "model_type" field. +func ModelTypeContainsFold(v consts.ModelType) predicate.Task { + vc := string(v) + return predicate.Task(sql.FieldContainsFold(FieldModelType, vc)) +} + +// PromptEQ applies the EQ predicate on the "prompt" field. +func PromptEQ(v string) predicate.Task { + return predicate.Task(sql.FieldEQ(FieldPrompt, v)) +} + +// PromptNEQ applies the NEQ predicate on the "prompt" field. +func PromptNEQ(v string) predicate.Task { + return predicate.Task(sql.FieldNEQ(FieldPrompt, v)) +} + +// PromptIn applies the In predicate on the "prompt" field. +func PromptIn(vs ...string) predicate.Task { + return predicate.Task(sql.FieldIn(FieldPrompt, vs...)) +} + +// PromptNotIn applies the NotIn predicate on the "prompt" field. +func PromptNotIn(vs ...string) predicate.Task { + return predicate.Task(sql.FieldNotIn(FieldPrompt, vs...)) +} + +// PromptGT applies the GT predicate on the "prompt" field. +func PromptGT(v string) predicate.Task { + return predicate.Task(sql.FieldGT(FieldPrompt, v)) +} + +// PromptGTE applies the GTE predicate on the "prompt" field. +func PromptGTE(v string) predicate.Task { + return predicate.Task(sql.FieldGTE(FieldPrompt, v)) +} + +// PromptLT applies the LT predicate on the "prompt" field. +func PromptLT(v string) predicate.Task { + return predicate.Task(sql.FieldLT(FieldPrompt, v)) +} + +// PromptLTE applies the LTE predicate on the "prompt" field. +func PromptLTE(v string) predicate.Task { + return predicate.Task(sql.FieldLTE(FieldPrompt, v)) +} + +// PromptContains applies the Contains predicate on the "prompt" field. +func PromptContains(v string) predicate.Task { + return predicate.Task(sql.FieldContains(FieldPrompt, v)) +} + +// PromptHasPrefix applies the HasPrefix predicate on the "prompt" field. +func PromptHasPrefix(v string) predicate.Task { + return predicate.Task(sql.FieldHasPrefix(FieldPrompt, v)) +} + +// PromptHasSuffix applies the HasSuffix predicate on the "prompt" field. +func PromptHasSuffix(v string) predicate.Task { + return predicate.Task(sql.FieldHasSuffix(FieldPrompt, v)) +} + +// PromptIsNil applies the IsNil predicate on the "prompt" field. +func PromptIsNil() predicate.Task { + return predicate.Task(sql.FieldIsNull(FieldPrompt)) +} + +// PromptNotNil applies the NotNil predicate on the "prompt" field. +func PromptNotNil() predicate.Task { + return predicate.Task(sql.FieldNotNull(FieldPrompt)) +} + +// PromptEqualFold applies the EqualFold predicate on the "prompt" field. +func PromptEqualFold(v string) predicate.Task { + return predicate.Task(sql.FieldEqualFold(FieldPrompt, v)) +} + +// PromptContainsFold applies the ContainsFold predicate on the "prompt" field. +func PromptContainsFold(v string) predicate.Task { + return predicate.Task(sql.FieldContainsFold(FieldPrompt, v)) +} + +// IsAcceptEQ applies the EQ predicate on the "is_accept" field. +func IsAcceptEQ(v bool) predicate.Task { + return predicate.Task(sql.FieldEQ(FieldIsAccept, v)) +} + +// IsAcceptNEQ applies the NEQ predicate on the "is_accept" field. +func IsAcceptNEQ(v bool) predicate.Task { + return predicate.Task(sql.FieldNEQ(FieldIsAccept, v)) +} + +// ProgramLanguageEQ applies the EQ predicate on the "program_language" field. +func ProgramLanguageEQ(v string) predicate.Task { + return predicate.Task(sql.FieldEQ(FieldProgramLanguage, v)) +} + +// ProgramLanguageNEQ applies the NEQ predicate on the "program_language" field. +func ProgramLanguageNEQ(v string) predicate.Task { + return predicate.Task(sql.FieldNEQ(FieldProgramLanguage, v)) +} + +// ProgramLanguageIn applies the In predicate on the "program_language" field. +func ProgramLanguageIn(vs ...string) predicate.Task { + return predicate.Task(sql.FieldIn(FieldProgramLanguage, vs...)) +} + +// ProgramLanguageNotIn applies the NotIn predicate on the "program_language" field. +func ProgramLanguageNotIn(vs ...string) predicate.Task { + return predicate.Task(sql.FieldNotIn(FieldProgramLanguage, vs...)) +} + +// ProgramLanguageGT applies the GT predicate on the "program_language" field. +func ProgramLanguageGT(v string) predicate.Task { + return predicate.Task(sql.FieldGT(FieldProgramLanguage, v)) +} + +// ProgramLanguageGTE applies the GTE predicate on the "program_language" field. +func ProgramLanguageGTE(v string) predicate.Task { + return predicate.Task(sql.FieldGTE(FieldProgramLanguage, v)) +} + +// ProgramLanguageLT applies the LT predicate on the "program_language" field. +func ProgramLanguageLT(v string) predicate.Task { + return predicate.Task(sql.FieldLT(FieldProgramLanguage, v)) +} + +// ProgramLanguageLTE applies the LTE predicate on the "program_language" field. +func ProgramLanguageLTE(v string) predicate.Task { + return predicate.Task(sql.FieldLTE(FieldProgramLanguage, v)) +} + +// ProgramLanguageContains applies the Contains predicate on the "program_language" field. +func ProgramLanguageContains(v string) predicate.Task { + return predicate.Task(sql.FieldContains(FieldProgramLanguage, v)) +} + +// ProgramLanguageHasPrefix applies the HasPrefix predicate on the "program_language" field. +func ProgramLanguageHasPrefix(v string) predicate.Task { + return predicate.Task(sql.FieldHasPrefix(FieldProgramLanguage, v)) +} + +// ProgramLanguageHasSuffix applies the HasSuffix predicate on the "program_language" field. +func ProgramLanguageHasSuffix(v string) predicate.Task { + return predicate.Task(sql.FieldHasSuffix(FieldProgramLanguage, v)) +} + +// ProgramLanguageIsNil applies the IsNil predicate on the "program_language" field. +func ProgramLanguageIsNil() predicate.Task { + return predicate.Task(sql.FieldIsNull(FieldProgramLanguage)) +} + +// ProgramLanguageNotNil applies the NotNil predicate on the "program_language" field. +func ProgramLanguageNotNil() predicate.Task { + return predicate.Task(sql.FieldNotNull(FieldProgramLanguage)) +} + +// ProgramLanguageEqualFold applies the EqualFold predicate on the "program_language" field. +func ProgramLanguageEqualFold(v string) predicate.Task { + return predicate.Task(sql.FieldEqualFold(FieldProgramLanguage, v)) +} + +// ProgramLanguageContainsFold applies the ContainsFold predicate on the "program_language" field. +func ProgramLanguageContainsFold(v string) predicate.Task { + return predicate.Task(sql.FieldContainsFold(FieldProgramLanguage, v)) +} + +// WorkModeEQ applies the EQ predicate on the "work_mode" field. +func WorkModeEQ(v string) predicate.Task { + return predicate.Task(sql.FieldEQ(FieldWorkMode, v)) +} + +// WorkModeNEQ applies the NEQ predicate on the "work_mode" field. +func WorkModeNEQ(v string) predicate.Task { + return predicate.Task(sql.FieldNEQ(FieldWorkMode, v)) +} + +// WorkModeIn applies the In predicate on the "work_mode" field. +func WorkModeIn(vs ...string) predicate.Task { + return predicate.Task(sql.FieldIn(FieldWorkMode, vs...)) +} + +// WorkModeNotIn applies the NotIn predicate on the "work_mode" field. +func WorkModeNotIn(vs ...string) predicate.Task { + return predicate.Task(sql.FieldNotIn(FieldWorkMode, vs...)) +} + +// WorkModeGT applies the GT predicate on the "work_mode" field. +func WorkModeGT(v string) predicate.Task { + return predicate.Task(sql.FieldGT(FieldWorkMode, v)) +} + +// WorkModeGTE applies the GTE predicate on the "work_mode" field. +func WorkModeGTE(v string) predicate.Task { + return predicate.Task(sql.FieldGTE(FieldWorkMode, v)) +} + +// WorkModeLT applies the LT predicate on the "work_mode" field. +func WorkModeLT(v string) predicate.Task { + return predicate.Task(sql.FieldLT(FieldWorkMode, v)) +} + +// WorkModeLTE applies the LTE predicate on the "work_mode" field. +func WorkModeLTE(v string) predicate.Task { + return predicate.Task(sql.FieldLTE(FieldWorkMode, v)) +} + +// WorkModeContains applies the Contains predicate on the "work_mode" field. +func WorkModeContains(v string) predicate.Task { + return predicate.Task(sql.FieldContains(FieldWorkMode, v)) +} + +// WorkModeHasPrefix applies the HasPrefix predicate on the "work_mode" field. +func WorkModeHasPrefix(v string) predicate.Task { + return predicate.Task(sql.FieldHasPrefix(FieldWorkMode, v)) +} + +// WorkModeHasSuffix applies the HasSuffix predicate on the "work_mode" field. +func WorkModeHasSuffix(v string) predicate.Task { + return predicate.Task(sql.FieldHasSuffix(FieldWorkMode, v)) +} + +// WorkModeIsNil applies the IsNil predicate on the "work_mode" field. +func WorkModeIsNil() predicate.Task { + return predicate.Task(sql.FieldIsNull(FieldWorkMode)) +} + +// WorkModeNotNil applies the NotNil predicate on the "work_mode" field. +func WorkModeNotNil() predicate.Task { + return predicate.Task(sql.FieldNotNull(FieldWorkMode)) +} + +// WorkModeEqualFold applies the EqualFold predicate on the "work_mode" field. +func WorkModeEqualFold(v string) predicate.Task { + return predicate.Task(sql.FieldEqualFold(FieldWorkMode, v)) +} + +// WorkModeContainsFold applies the ContainsFold predicate on the "work_mode" field. +func WorkModeContainsFold(v string) predicate.Task { + return predicate.Task(sql.FieldContainsFold(FieldWorkMode, v)) +} + +// CompletionEQ applies the EQ predicate on the "completion" field. +func CompletionEQ(v string) predicate.Task { + return predicate.Task(sql.FieldEQ(FieldCompletion, v)) +} + +// CompletionNEQ applies the NEQ predicate on the "completion" field. +func CompletionNEQ(v string) predicate.Task { + return predicate.Task(sql.FieldNEQ(FieldCompletion, v)) +} + +// CompletionIn applies the In predicate on the "completion" field. +func CompletionIn(vs ...string) predicate.Task { + return predicate.Task(sql.FieldIn(FieldCompletion, vs...)) +} + +// CompletionNotIn applies the NotIn predicate on the "completion" field. +func CompletionNotIn(vs ...string) predicate.Task { + return predicate.Task(sql.FieldNotIn(FieldCompletion, vs...)) +} + +// CompletionGT applies the GT predicate on the "completion" field. +func CompletionGT(v string) predicate.Task { + return predicate.Task(sql.FieldGT(FieldCompletion, v)) +} + +// CompletionGTE applies the GTE predicate on the "completion" field. +func CompletionGTE(v string) predicate.Task { + return predicate.Task(sql.FieldGTE(FieldCompletion, v)) +} + +// CompletionLT applies the LT predicate on the "completion" field. +func CompletionLT(v string) predicate.Task { + return predicate.Task(sql.FieldLT(FieldCompletion, v)) +} + +// CompletionLTE applies the LTE predicate on the "completion" field. +func CompletionLTE(v string) predicate.Task { + return predicate.Task(sql.FieldLTE(FieldCompletion, v)) +} + +// CompletionContains applies the Contains predicate on the "completion" field. +func CompletionContains(v string) predicate.Task { + return predicate.Task(sql.FieldContains(FieldCompletion, v)) +} + +// CompletionHasPrefix applies the HasPrefix predicate on the "completion" field. +func CompletionHasPrefix(v string) predicate.Task { + return predicate.Task(sql.FieldHasPrefix(FieldCompletion, v)) +} + +// CompletionHasSuffix applies the HasSuffix predicate on the "completion" field. +func CompletionHasSuffix(v string) predicate.Task { + return predicate.Task(sql.FieldHasSuffix(FieldCompletion, v)) +} + +// CompletionIsNil applies the IsNil predicate on the "completion" field. +func CompletionIsNil() predicate.Task { + return predicate.Task(sql.FieldIsNull(FieldCompletion)) +} + +// CompletionNotNil applies the NotNil predicate on the "completion" field. +func CompletionNotNil() predicate.Task { + return predicate.Task(sql.FieldNotNull(FieldCompletion)) +} + +// CompletionEqualFold applies the EqualFold predicate on the "completion" field. +func CompletionEqualFold(v string) predicate.Task { + return predicate.Task(sql.FieldEqualFold(FieldCompletion, v)) +} + +// CompletionContainsFold applies the ContainsFold predicate on the "completion" field. +func CompletionContainsFold(v string) predicate.Task { + return predicate.Task(sql.FieldContainsFold(FieldCompletion, v)) +} + +// CodeLinesEQ applies the EQ predicate on the "code_lines" field. +func CodeLinesEQ(v int64) predicate.Task { + return predicate.Task(sql.FieldEQ(FieldCodeLines, v)) +} + +// CodeLinesNEQ applies the NEQ predicate on the "code_lines" field. +func CodeLinesNEQ(v int64) predicate.Task { + return predicate.Task(sql.FieldNEQ(FieldCodeLines, v)) +} + +// CodeLinesIn applies the In predicate on the "code_lines" field. +func CodeLinesIn(vs ...int64) predicate.Task { + return predicate.Task(sql.FieldIn(FieldCodeLines, vs...)) +} + +// CodeLinesNotIn applies the NotIn predicate on the "code_lines" field. +func CodeLinesNotIn(vs ...int64) predicate.Task { + return predicate.Task(sql.FieldNotIn(FieldCodeLines, vs...)) +} + +// CodeLinesGT applies the GT predicate on the "code_lines" field. +func CodeLinesGT(v int64) predicate.Task { + return predicate.Task(sql.FieldGT(FieldCodeLines, v)) +} + +// CodeLinesGTE applies the GTE predicate on the "code_lines" field. +func CodeLinesGTE(v int64) predicate.Task { + return predicate.Task(sql.FieldGTE(FieldCodeLines, v)) +} + +// CodeLinesLT applies the LT predicate on the "code_lines" field. +func CodeLinesLT(v int64) predicate.Task { + return predicate.Task(sql.FieldLT(FieldCodeLines, v)) +} + +// CodeLinesLTE applies the LTE predicate on the "code_lines" field. +func CodeLinesLTE(v int64) predicate.Task { + return predicate.Task(sql.FieldLTE(FieldCodeLines, v)) +} + +// CodeLinesIsNil applies the IsNil predicate on the "code_lines" field. +func CodeLinesIsNil() predicate.Task { + return predicate.Task(sql.FieldIsNull(FieldCodeLines)) +} + +// CodeLinesNotNil applies the NotNil predicate on the "code_lines" field. +func CodeLinesNotNil() predicate.Task { + return predicate.Task(sql.FieldNotNull(FieldCodeLines)) +} + +// InputTokensEQ applies the EQ predicate on the "input_tokens" field. +func InputTokensEQ(v int64) predicate.Task { + return predicate.Task(sql.FieldEQ(FieldInputTokens, v)) +} + +// InputTokensNEQ applies the NEQ predicate on the "input_tokens" field. +func InputTokensNEQ(v int64) predicate.Task { + return predicate.Task(sql.FieldNEQ(FieldInputTokens, v)) +} + +// InputTokensIn applies the In predicate on the "input_tokens" field. +func InputTokensIn(vs ...int64) predicate.Task { + return predicate.Task(sql.FieldIn(FieldInputTokens, vs...)) +} + +// InputTokensNotIn applies the NotIn predicate on the "input_tokens" field. +func InputTokensNotIn(vs ...int64) predicate.Task { + return predicate.Task(sql.FieldNotIn(FieldInputTokens, vs...)) +} + +// InputTokensGT applies the GT predicate on the "input_tokens" field. +func InputTokensGT(v int64) predicate.Task { + return predicate.Task(sql.FieldGT(FieldInputTokens, v)) +} + +// InputTokensGTE applies the GTE predicate on the "input_tokens" field. +func InputTokensGTE(v int64) predicate.Task { + return predicate.Task(sql.FieldGTE(FieldInputTokens, v)) +} + +// InputTokensLT applies the LT predicate on the "input_tokens" field. +func InputTokensLT(v int64) predicate.Task { + return predicate.Task(sql.FieldLT(FieldInputTokens, v)) +} + +// InputTokensLTE applies the LTE predicate on the "input_tokens" field. +func InputTokensLTE(v int64) predicate.Task { + return predicate.Task(sql.FieldLTE(FieldInputTokens, v)) +} + +// InputTokensIsNil applies the IsNil predicate on the "input_tokens" field. +func InputTokensIsNil() predicate.Task { + return predicate.Task(sql.FieldIsNull(FieldInputTokens)) +} + +// InputTokensNotNil applies the NotNil predicate on the "input_tokens" field. +func InputTokensNotNil() predicate.Task { + return predicate.Task(sql.FieldNotNull(FieldInputTokens)) +} + +// OutputTokensEQ applies the EQ predicate on the "output_tokens" field. +func OutputTokensEQ(v int64) predicate.Task { + return predicate.Task(sql.FieldEQ(FieldOutputTokens, v)) +} + +// OutputTokensNEQ applies the NEQ predicate on the "output_tokens" field. +func OutputTokensNEQ(v int64) predicate.Task { + return predicate.Task(sql.FieldNEQ(FieldOutputTokens, v)) +} + +// OutputTokensIn applies the In predicate on the "output_tokens" field. +func OutputTokensIn(vs ...int64) predicate.Task { + return predicate.Task(sql.FieldIn(FieldOutputTokens, vs...)) +} + +// OutputTokensNotIn applies the NotIn predicate on the "output_tokens" field. +func OutputTokensNotIn(vs ...int64) predicate.Task { + return predicate.Task(sql.FieldNotIn(FieldOutputTokens, vs...)) +} + +// OutputTokensGT applies the GT predicate on the "output_tokens" field. +func OutputTokensGT(v int64) predicate.Task { + return predicate.Task(sql.FieldGT(FieldOutputTokens, v)) +} + +// OutputTokensGTE applies the GTE predicate on the "output_tokens" field. +func OutputTokensGTE(v int64) predicate.Task { + return predicate.Task(sql.FieldGTE(FieldOutputTokens, v)) +} + +// OutputTokensLT applies the LT predicate on the "output_tokens" field. +func OutputTokensLT(v int64) predicate.Task { + return predicate.Task(sql.FieldLT(FieldOutputTokens, v)) +} + +// OutputTokensLTE applies the LTE predicate on the "output_tokens" field. +func OutputTokensLTE(v int64) predicate.Task { + return predicate.Task(sql.FieldLTE(FieldOutputTokens, v)) +} + +// OutputTokensIsNil applies the IsNil predicate on the "output_tokens" field. +func OutputTokensIsNil() predicate.Task { + return predicate.Task(sql.FieldIsNull(FieldOutputTokens)) +} + +// OutputTokensNotNil applies the NotNil predicate on the "output_tokens" field. +func OutputTokensNotNil() predicate.Task { + return predicate.Task(sql.FieldNotNull(FieldOutputTokens)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.Task { + return predicate.Task(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.Task { + return predicate.Task(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.Task { + return predicate.Task(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.Task { + return predicate.Task(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.Task { + return predicate.Task(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.Task { + return predicate.Task(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.Task { + return predicate.Task(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.Task { + return predicate.Task(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.Task { + return predicate.Task(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.Task { + return predicate.Task(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.Task { + return predicate.Task(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.Task { + return predicate.Task(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.Task { + return predicate.Task(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.Task { + return predicate.Task(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.Task { + return predicate.Task(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.Task { + return predicate.Task(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// HasTaskRecords applies the HasEdge predicate on the "task_records" edge. +func HasTaskRecords() predicate.Task { + return predicate.Task(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, TaskRecordsTable, TaskRecordsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasTaskRecordsWith applies the HasEdge predicate on the "task_records" edge with a given conditions (other predicates). +func HasTaskRecordsWith(preds ...predicate.TaskRecord) predicate.Task { + return predicate.Task(func(s *sql.Selector) { + step := newTaskRecordsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasUser applies the HasEdge predicate on the "user" edge. +func HasUser() predicate.Task { + return predicate.Task(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, UserTable, UserColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasUserWith applies the HasEdge predicate on the "user" edge with a given conditions (other predicates). +func HasUserWith(preds ...predicate.User) predicate.Task { + return predicate.Task(func(s *sql.Selector) { + step := newUserStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasModel applies the HasEdge predicate on the "model" edge. +func HasModel() predicate.Task { + return predicate.Task(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ModelTable, ModelColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasModelWith applies the HasEdge predicate on the "model" edge with a given conditions (other predicates). +func HasModelWith(preds ...predicate.Model) predicate.Task { + return predicate.Task(func(s *sql.Selector) { + step := newModelStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.Task) predicate.Task { + return predicate.Task(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Task) predicate.Task { + return predicate.Task(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Task) predicate.Task { + return predicate.Task(sql.NotPredicates(p)) +} diff --git a/backend/db/task_create.go b/backend/db/task_create.go new file mode 100644 index 0000000..f6ada06 --- /dev/null +++ b/backend/db/task_create.go @@ -0,0 +1,1656 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/consts" + "github.com/chaitin/MonkeyCode/backend/db/model" + "github.com/chaitin/MonkeyCode/backend/db/task" + "github.com/chaitin/MonkeyCode/backend/db/taskrecord" + "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/google/uuid" +) + +// TaskCreate is the builder for creating a Task entity. +type TaskCreate struct { + config + mutation *TaskMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetTaskID sets the "task_id" field. +func (tc *TaskCreate) SetTaskID(s string) *TaskCreate { + tc.mutation.SetTaskID(s) + return tc +} + +// SetUserID sets the "user_id" field. +func (tc *TaskCreate) SetUserID(u uuid.UUID) *TaskCreate { + tc.mutation.SetUserID(u) + return tc +} + +// SetNillableUserID sets the "user_id" field if the given value is not nil. +func (tc *TaskCreate) SetNillableUserID(u *uuid.UUID) *TaskCreate { + if u != nil { + tc.SetUserID(*u) + } + return tc +} + +// SetModelID sets the "model_id" field. +func (tc *TaskCreate) SetModelID(u uuid.UUID) *TaskCreate { + tc.mutation.SetModelID(u) + return tc +} + +// SetNillableModelID sets the "model_id" field if the given value is not nil. +func (tc *TaskCreate) SetNillableModelID(u *uuid.UUID) *TaskCreate { + if u != nil { + tc.SetModelID(*u) + } + return tc +} + +// SetRequestID sets the "request_id" field. +func (tc *TaskCreate) SetRequestID(s string) *TaskCreate { + tc.mutation.SetRequestID(s) + return tc +} + +// SetNillableRequestID sets the "request_id" field if the given value is not nil. +func (tc *TaskCreate) SetNillableRequestID(s *string) *TaskCreate { + if s != nil { + tc.SetRequestID(*s) + } + return tc +} + +// SetModelType sets the "model_type" field. +func (tc *TaskCreate) SetModelType(ct consts.ModelType) *TaskCreate { + tc.mutation.SetModelType(ct) + return tc +} + +// SetPrompt sets the "prompt" field. +func (tc *TaskCreate) SetPrompt(s string) *TaskCreate { + tc.mutation.SetPrompt(s) + return tc +} + +// SetNillablePrompt sets the "prompt" field if the given value is not nil. +func (tc *TaskCreate) SetNillablePrompt(s *string) *TaskCreate { + if s != nil { + tc.SetPrompt(*s) + } + return tc +} + +// SetIsAccept sets the "is_accept" field. +func (tc *TaskCreate) SetIsAccept(b bool) *TaskCreate { + tc.mutation.SetIsAccept(b) + return tc +} + +// SetNillableIsAccept sets the "is_accept" field if the given value is not nil. +func (tc *TaskCreate) SetNillableIsAccept(b *bool) *TaskCreate { + if b != nil { + tc.SetIsAccept(*b) + } + return tc +} + +// SetProgramLanguage sets the "program_language" field. +func (tc *TaskCreate) SetProgramLanguage(s string) *TaskCreate { + tc.mutation.SetProgramLanguage(s) + return tc +} + +// SetNillableProgramLanguage sets the "program_language" field if the given value is not nil. +func (tc *TaskCreate) SetNillableProgramLanguage(s *string) *TaskCreate { + if s != nil { + tc.SetProgramLanguage(*s) + } + return tc +} + +// SetWorkMode sets the "work_mode" field. +func (tc *TaskCreate) SetWorkMode(s string) *TaskCreate { + tc.mutation.SetWorkMode(s) + return tc +} + +// SetNillableWorkMode sets the "work_mode" field if the given value is not nil. +func (tc *TaskCreate) SetNillableWorkMode(s *string) *TaskCreate { + if s != nil { + tc.SetWorkMode(*s) + } + return tc +} + +// SetCompletion sets the "completion" field. +func (tc *TaskCreate) SetCompletion(s string) *TaskCreate { + tc.mutation.SetCompletion(s) + return tc +} + +// SetNillableCompletion sets the "completion" field if the given value is not nil. +func (tc *TaskCreate) SetNillableCompletion(s *string) *TaskCreate { + if s != nil { + tc.SetCompletion(*s) + } + return tc +} + +// SetCodeLines sets the "code_lines" field. +func (tc *TaskCreate) SetCodeLines(i int64) *TaskCreate { + tc.mutation.SetCodeLines(i) + return tc +} + +// SetNillableCodeLines sets the "code_lines" field if the given value is not nil. +func (tc *TaskCreate) SetNillableCodeLines(i *int64) *TaskCreate { + if i != nil { + tc.SetCodeLines(*i) + } + return tc +} + +// SetInputTokens sets the "input_tokens" field. +func (tc *TaskCreate) SetInputTokens(i int64) *TaskCreate { + tc.mutation.SetInputTokens(i) + return tc +} + +// SetNillableInputTokens sets the "input_tokens" field if the given value is not nil. +func (tc *TaskCreate) SetNillableInputTokens(i *int64) *TaskCreate { + if i != nil { + tc.SetInputTokens(*i) + } + return tc +} + +// SetOutputTokens sets the "output_tokens" field. +func (tc *TaskCreate) SetOutputTokens(i int64) *TaskCreate { + tc.mutation.SetOutputTokens(i) + return tc +} + +// SetNillableOutputTokens sets the "output_tokens" field if the given value is not nil. +func (tc *TaskCreate) SetNillableOutputTokens(i *int64) *TaskCreate { + if i != nil { + tc.SetOutputTokens(*i) + } + return tc +} + +// SetCreatedAt sets the "created_at" field. +func (tc *TaskCreate) SetCreatedAt(t time.Time) *TaskCreate { + tc.mutation.SetCreatedAt(t) + return tc +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (tc *TaskCreate) SetNillableCreatedAt(t *time.Time) *TaskCreate { + if t != nil { + tc.SetCreatedAt(*t) + } + return tc +} + +// SetUpdatedAt sets the "updated_at" field. +func (tc *TaskCreate) SetUpdatedAt(t time.Time) *TaskCreate { + tc.mutation.SetUpdatedAt(t) + return tc +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (tc *TaskCreate) SetNillableUpdatedAt(t *time.Time) *TaskCreate { + if t != nil { + tc.SetUpdatedAt(*t) + } + return tc +} + +// SetID sets the "id" field. +func (tc *TaskCreate) SetID(u uuid.UUID) *TaskCreate { + tc.mutation.SetID(u) + return tc +} + +// AddTaskRecordIDs adds the "task_records" edge to the TaskRecord entity by IDs. +func (tc *TaskCreate) AddTaskRecordIDs(ids ...uuid.UUID) *TaskCreate { + tc.mutation.AddTaskRecordIDs(ids...) + return tc +} + +// AddTaskRecords adds the "task_records" edges to the TaskRecord entity. +func (tc *TaskCreate) AddTaskRecords(t ...*TaskRecord) *TaskCreate { + ids := make([]uuid.UUID, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return tc.AddTaskRecordIDs(ids...) +} + +// SetUser sets the "user" edge to the User entity. +func (tc *TaskCreate) SetUser(u *User) *TaskCreate { + return tc.SetUserID(u.ID) +} + +// SetModel sets the "model" edge to the Model entity. +func (tc *TaskCreate) SetModel(m *Model) *TaskCreate { + return tc.SetModelID(m.ID) +} + +// Mutation returns the TaskMutation object of the builder. +func (tc *TaskCreate) Mutation() *TaskMutation { + return tc.mutation +} + +// Save creates the Task in the database. +func (tc *TaskCreate) Save(ctx context.Context) (*Task, error) { + tc.defaults() + return withHooks(ctx, tc.sqlSave, tc.mutation, tc.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (tc *TaskCreate) SaveX(ctx context.Context) *Task { + v, err := tc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (tc *TaskCreate) Exec(ctx context.Context) error { + _, err := tc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (tc *TaskCreate) ExecX(ctx context.Context) { + if err := tc.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (tc *TaskCreate) defaults() { + if _, ok := tc.mutation.IsAccept(); !ok { + v := task.DefaultIsAccept + tc.mutation.SetIsAccept(v) + } + if _, ok := tc.mutation.CreatedAt(); !ok { + v := task.DefaultCreatedAt() + tc.mutation.SetCreatedAt(v) + } + if _, ok := tc.mutation.UpdatedAt(); !ok { + v := task.DefaultUpdatedAt() + tc.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (tc *TaskCreate) check() error { + if _, ok := tc.mutation.TaskID(); !ok { + return &ValidationError{Name: "task_id", err: errors.New(`db: missing required field "Task.task_id"`)} + } + if _, ok := tc.mutation.ModelType(); !ok { + return &ValidationError{Name: "model_type", err: errors.New(`db: missing required field "Task.model_type"`)} + } + if _, ok := tc.mutation.IsAccept(); !ok { + return &ValidationError{Name: "is_accept", err: errors.New(`db: missing required field "Task.is_accept"`)} + } + if _, ok := tc.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "Task.created_at"`)} + } + if _, ok := tc.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "Task.updated_at"`)} + } + return nil +} + +func (tc *TaskCreate) sqlSave(ctx context.Context) (*Task, error) { + if err := tc.check(); err != nil { + return nil, err + } + _node, _spec := tc.createSpec() + if err := sqlgraph.CreateNode(ctx, tc.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 + } + } + tc.mutation.id = &_node.ID + tc.mutation.done = true + return _node, nil +} + +func (tc *TaskCreate) createSpec() (*Task, *sqlgraph.CreateSpec) { + var ( + _node = &Task{config: tc.config} + _spec = sqlgraph.NewCreateSpec(task.Table, sqlgraph.NewFieldSpec(task.FieldID, field.TypeUUID)) + ) + _spec.OnConflict = tc.conflict + if id, ok := tc.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = &id + } + if value, ok := tc.mutation.TaskID(); ok { + _spec.SetField(task.FieldTaskID, field.TypeString, value) + _node.TaskID = value + } + if value, ok := tc.mutation.RequestID(); ok { + _spec.SetField(task.FieldRequestID, field.TypeString, value) + _node.RequestID = value + } + if value, ok := tc.mutation.ModelType(); ok { + _spec.SetField(task.FieldModelType, field.TypeString, value) + _node.ModelType = value + } + if value, ok := tc.mutation.Prompt(); ok { + _spec.SetField(task.FieldPrompt, field.TypeString, value) + _node.Prompt = value + } + if value, ok := tc.mutation.IsAccept(); ok { + _spec.SetField(task.FieldIsAccept, field.TypeBool, value) + _node.IsAccept = value + } + if value, ok := tc.mutation.ProgramLanguage(); ok { + _spec.SetField(task.FieldProgramLanguage, field.TypeString, value) + _node.ProgramLanguage = value + } + if value, ok := tc.mutation.WorkMode(); ok { + _spec.SetField(task.FieldWorkMode, field.TypeString, value) + _node.WorkMode = value + } + if value, ok := tc.mutation.Completion(); ok { + _spec.SetField(task.FieldCompletion, field.TypeString, value) + _node.Completion = value + } + if value, ok := tc.mutation.CodeLines(); ok { + _spec.SetField(task.FieldCodeLines, field.TypeInt64, value) + _node.CodeLines = value + } + if value, ok := tc.mutation.InputTokens(); ok { + _spec.SetField(task.FieldInputTokens, field.TypeInt64, value) + _node.InputTokens = value + } + if value, ok := tc.mutation.OutputTokens(); ok { + _spec.SetField(task.FieldOutputTokens, field.TypeInt64, value) + _node.OutputTokens = value + } + if value, ok := tc.mutation.CreatedAt(); ok { + _spec.SetField(task.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := tc.mutation.UpdatedAt(); ok { + _spec.SetField(task.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if nodes := tc.mutation.TaskRecordsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: task.TaskRecordsTable, + Columns: []string{task.TaskRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(taskrecord.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := tc.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: task.UserTable, + Columns: []string{task.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.UserID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := tc.mutation.ModelIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: task.ModelTable, + Columns: []string{task.ModelColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(model.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.ModelID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.Task.Create(). +// SetTaskID(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.TaskUpsert) { +// SetTaskID(v+v). +// }). +// Exec(ctx) +func (tc *TaskCreate) OnConflict(opts ...sql.ConflictOption) *TaskUpsertOne { + tc.conflict = opts + return &TaskUpsertOne{ + create: tc, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.Task.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (tc *TaskCreate) OnConflictColumns(columns ...string) *TaskUpsertOne { + tc.conflict = append(tc.conflict, sql.ConflictColumns(columns...)) + return &TaskUpsertOne{ + create: tc, + } +} + +type ( + // TaskUpsertOne is the builder for "upsert"-ing + // one Task node. + TaskUpsertOne struct { + create *TaskCreate + } + + // TaskUpsert is the "OnConflict" setter. + TaskUpsert struct { + *sql.UpdateSet + } +) + +// SetTaskID sets the "task_id" field. +func (u *TaskUpsert) SetTaskID(v string) *TaskUpsert { + u.Set(task.FieldTaskID, v) + return u +} + +// UpdateTaskID sets the "task_id" field to the value that was provided on create. +func (u *TaskUpsert) UpdateTaskID() *TaskUpsert { + u.SetExcluded(task.FieldTaskID) + return u +} + +// SetUserID sets the "user_id" field. +func (u *TaskUpsert) SetUserID(v uuid.UUID) *TaskUpsert { + u.Set(task.FieldUserID, v) + return u +} + +// UpdateUserID sets the "user_id" field to the value that was provided on create. +func (u *TaskUpsert) UpdateUserID() *TaskUpsert { + u.SetExcluded(task.FieldUserID) + return u +} + +// ClearUserID clears the value of the "user_id" field. +func (u *TaskUpsert) ClearUserID() *TaskUpsert { + u.SetNull(task.FieldUserID) + return u +} + +// SetModelID sets the "model_id" field. +func (u *TaskUpsert) SetModelID(v uuid.UUID) *TaskUpsert { + u.Set(task.FieldModelID, v) + return u +} + +// UpdateModelID sets the "model_id" field to the value that was provided on create. +func (u *TaskUpsert) UpdateModelID() *TaskUpsert { + u.SetExcluded(task.FieldModelID) + return u +} + +// ClearModelID clears the value of the "model_id" field. +func (u *TaskUpsert) ClearModelID() *TaskUpsert { + u.SetNull(task.FieldModelID) + return u +} + +// SetRequestID sets the "request_id" field. +func (u *TaskUpsert) SetRequestID(v string) *TaskUpsert { + u.Set(task.FieldRequestID, v) + return u +} + +// UpdateRequestID sets the "request_id" field to the value that was provided on create. +func (u *TaskUpsert) UpdateRequestID() *TaskUpsert { + u.SetExcluded(task.FieldRequestID) + return u +} + +// ClearRequestID clears the value of the "request_id" field. +func (u *TaskUpsert) ClearRequestID() *TaskUpsert { + u.SetNull(task.FieldRequestID) + return u +} + +// SetModelType sets the "model_type" field. +func (u *TaskUpsert) SetModelType(v consts.ModelType) *TaskUpsert { + u.Set(task.FieldModelType, v) + return u +} + +// UpdateModelType sets the "model_type" field to the value that was provided on create. +func (u *TaskUpsert) UpdateModelType() *TaskUpsert { + u.SetExcluded(task.FieldModelType) + return u +} + +// SetPrompt sets the "prompt" field. +func (u *TaskUpsert) SetPrompt(v string) *TaskUpsert { + u.Set(task.FieldPrompt, v) + return u +} + +// UpdatePrompt sets the "prompt" field to the value that was provided on create. +func (u *TaskUpsert) UpdatePrompt() *TaskUpsert { + u.SetExcluded(task.FieldPrompt) + return u +} + +// ClearPrompt clears the value of the "prompt" field. +func (u *TaskUpsert) ClearPrompt() *TaskUpsert { + u.SetNull(task.FieldPrompt) + return u +} + +// SetIsAccept sets the "is_accept" field. +func (u *TaskUpsert) SetIsAccept(v bool) *TaskUpsert { + u.Set(task.FieldIsAccept, v) + return u +} + +// UpdateIsAccept sets the "is_accept" field to the value that was provided on create. +func (u *TaskUpsert) UpdateIsAccept() *TaskUpsert { + u.SetExcluded(task.FieldIsAccept) + return u +} + +// SetProgramLanguage sets the "program_language" field. +func (u *TaskUpsert) SetProgramLanguage(v string) *TaskUpsert { + u.Set(task.FieldProgramLanguage, v) + return u +} + +// UpdateProgramLanguage sets the "program_language" field to the value that was provided on create. +func (u *TaskUpsert) UpdateProgramLanguage() *TaskUpsert { + u.SetExcluded(task.FieldProgramLanguage) + return u +} + +// ClearProgramLanguage clears the value of the "program_language" field. +func (u *TaskUpsert) ClearProgramLanguage() *TaskUpsert { + u.SetNull(task.FieldProgramLanguage) + return u +} + +// SetWorkMode sets the "work_mode" field. +func (u *TaskUpsert) SetWorkMode(v string) *TaskUpsert { + u.Set(task.FieldWorkMode, v) + return u +} + +// UpdateWorkMode sets the "work_mode" field to the value that was provided on create. +func (u *TaskUpsert) UpdateWorkMode() *TaskUpsert { + u.SetExcluded(task.FieldWorkMode) + return u +} + +// ClearWorkMode clears the value of the "work_mode" field. +func (u *TaskUpsert) ClearWorkMode() *TaskUpsert { + u.SetNull(task.FieldWorkMode) + return u +} + +// SetCompletion sets the "completion" field. +func (u *TaskUpsert) SetCompletion(v string) *TaskUpsert { + u.Set(task.FieldCompletion, v) + return u +} + +// UpdateCompletion sets the "completion" field to the value that was provided on create. +func (u *TaskUpsert) UpdateCompletion() *TaskUpsert { + u.SetExcluded(task.FieldCompletion) + return u +} + +// ClearCompletion clears the value of the "completion" field. +func (u *TaskUpsert) ClearCompletion() *TaskUpsert { + u.SetNull(task.FieldCompletion) + return u +} + +// SetCodeLines sets the "code_lines" field. +func (u *TaskUpsert) SetCodeLines(v int64) *TaskUpsert { + u.Set(task.FieldCodeLines, v) + return u +} + +// UpdateCodeLines sets the "code_lines" field to the value that was provided on create. +func (u *TaskUpsert) UpdateCodeLines() *TaskUpsert { + u.SetExcluded(task.FieldCodeLines) + return u +} + +// AddCodeLines adds v to the "code_lines" field. +func (u *TaskUpsert) AddCodeLines(v int64) *TaskUpsert { + u.Add(task.FieldCodeLines, v) + return u +} + +// ClearCodeLines clears the value of the "code_lines" field. +func (u *TaskUpsert) ClearCodeLines() *TaskUpsert { + u.SetNull(task.FieldCodeLines) + return u +} + +// SetInputTokens sets the "input_tokens" field. +func (u *TaskUpsert) SetInputTokens(v int64) *TaskUpsert { + u.Set(task.FieldInputTokens, v) + return u +} + +// UpdateInputTokens sets the "input_tokens" field to the value that was provided on create. +func (u *TaskUpsert) UpdateInputTokens() *TaskUpsert { + u.SetExcluded(task.FieldInputTokens) + return u +} + +// AddInputTokens adds v to the "input_tokens" field. +func (u *TaskUpsert) AddInputTokens(v int64) *TaskUpsert { + u.Add(task.FieldInputTokens, v) + return u +} + +// ClearInputTokens clears the value of the "input_tokens" field. +func (u *TaskUpsert) ClearInputTokens() *TaskUpsert { + u.SetNull(task.FieldInputTokens) + return u +} + +// SetOutputTokens sets the "output_tokens" field. +func (u *TaskUpsert) SetOutputTokens(v int64) *TaskUpsert { + u.Set(task.FieldOutputTokens, v) + return u +} + +// UpdateOutputTokens sets the "output_tokens" field to the value that was provided on create. +func (u *TaskUpsert) UpdateOutputTokens() *TaskUpsert { + u.SetExcluded(task.FieldOutputTokens) + return u +} + +// AddOutputTokens adds v to the "output_tokens" field. +func (u *TaskUpsert) AddOutputTokens(v int64) *TaskUpsert { + u.Add(task.FieldOutputTokens, v) + return u +} + +// ClearOutputTokens clears the value of the "output_tokens" field. +func (u *TaskUpsert) ClearOutputTokens() *TaskUpsert { + u.SetNull(task.FieldOutputTokens) + return u +} + +// SetCreatedAt sets the "created_at" field. +func (u *TaskUpsert) SetCreatedAt(v time.Time) *TaskUpsert { + u.Set(task.FieldCreatedAt, v) + return u +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *TaskUpsert) UpdateCreatedAt() *TaskUpsert { + u.SetExcluded(task.FieldCreatedAt) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *TaskUpsert) SetUpdatedAt(v time.Time) *TaskUpsert { + u.Set(task.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *TaskUpsert) UpdateUpdatedAt() *TaskUpsert { + u.SetExcluded(task.FieldUpdatedAt) + return u +} + +// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field. +// Using this option is equivalent to using: +// +// client.Task.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(task.FieldID) +// }), +// ). +// Exec(ctx) +func (u *TaskUpsertOne) UpdateNewValues() *TaskUpsertOne { + 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(task.FieldID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.Task.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *TaskUpsertOne) Ignore() *TaskUpsertOne { + 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 *TaskUpsertOne) DoNothing() *TaskUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the TaskCreate.OnConflict +// documentation for more info. +func (u *TaskUpsertOne) Update(set func(*TaskUpsert)) *TaskUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&TaskUpsert{UpdateSet: update}) + })) + return u +} + +// SetTaskID sets the "task_id" field. +func (u *TaskUpsertOne) SetTaskID(v string) *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.SetTaskID(v) + }) +} + +// UpdateTaskID sets the "task_id" field to the value that was provided on create. +func (u *TaskUpsertOne) UpdateTaskID() *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.UpdateTaskID() + }) +} + +// SetUserID sets the "user_id" field. +func (u *TaskUpsertOne) SetUserID(v uuid.UUID) *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.SetUserID(v) + }) +} + +// UpdateUserID sets the "user_id" field to the value that was provided on create. +func (u *TaskUpsertOne) UpdateUserID() *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.UpdateUserID() + }) +} + +// ClearUserID clears the value of the "user_id" field. +func (u *TaskUpsertOne) ClearUserID() *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.ClearUserID() + }) +} + +// SetModelID sets the "model_id" field. +func (u *TaskUpsertOne) SetModelID(v uuid.UUID) *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.SetModelID(v) + }) +} + +// UpdateModelID sets the "model_id" field to the value that was provided on create. +func (u *TaskUpsertOne) UpdateModelID() *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.UpdateModelID() + }) +} + +// ClearModelID clears the value of the "model_id" field. +func (u *TaskUpsertOne) ClearModelID() *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.ClearModelID() + }) +} + +// SetRequestID sets the "request_id" field. +func (u *TaskUpsertOne) SetRequestID(v string) *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.SetRequestID(v) + }) +} + +// UpdateRequestID sets the "request_id" field to the value that was provided on create. +func (u *TaskUpsertOne) UpdateRequestID() *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.UpdateRequestID() + }) +} + +// ClearRequestID clears the value of the "request_id" field. +func (u *TaskUpsertOne) ClearRequestID() *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.ClearRequestID() + }) +} + +// SetModelType sets the "model_type" field. +func (u *TaskUpsertOne) SetModelType(v consts.ModelType) *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.SetModelType(v) + }) +} + +// UpdateModelType sets the "model_type" field to the value that was provided on create. +func (u *TaskUpsertOne) UpdateModelType() *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.UpdateModelType() + }) +} + +// SetPrompt sets the "prompt" field. +func (u *TaskUpsertOne) SetPrompt(v string) *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.SetPrompt(v) + }) +} + +// UpdatePrompt sets the "prompt" field to the value that was provided on create. +func (u *TaskUpsertOne) UpdatePrompt() *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.UpdatePrompt() + }) +} + +// ClearPrompt clears the value of the "prompt" field. +func (u *TaskUpsertOne) ClearPrompt() *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.ClearPrompt() + }) +} + +// SetIsAccept sets the "is_accept" field. +func (u *TaskUpsertOne) SetIsAccept(v bool) *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.SetIsAccept(v) + }) +} + +// UpdateIsAccept sets the "is_accept" field to the value that was provided on create. +func (u *TaskUpsertOne) UpdateIsAccept() *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.UpdateIsAccept() + }) +} + +// SetProgramLanguage sets the "program_language" field. +func (u *TaskUpsertOne) SetProgramLanguage(v string) *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.SetProgramLanguage(v) + }) +} + +// UpdateProgramLanguage sets the "program_language" field to the value that was provided on create. +func (u *TaskUpsertOne) UpdateProgramLanguage() *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.UpdateProgramLanguage() + }) +} + +// ClearProgramLanguage clears the value of the "program_language" field. +func (u *TaskUpsertOne) ClearProgramLanguage() *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.ClearProgramLanguage() + }) +} + +// SetWorkMode sets the "work_mode" field. +func (u *TaskUpsertOne) SetWorkMode(v string) *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.SetWorkMode(v) + }) +} + +// UpdateWorkMode sets the "work_mode" field to the value that was provided on create. +func (u *TaskUpsertOne) UpdateWorkMode() *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.UpdateWorkMode() + }) +} + +// ClearWorkMode clears the value of the "work_mode" field. +func (u *TaskUpsertOne) ClearWorkMode() *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.ClearWorkMode() + }) +} + +// SetCompletion sets the "completion" field. +func (u *TaskUpsertOne) SetCompletion(v string) *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.SetCompletion(v) + }) +} + +// UpdateCompletion sets the "completion" field to the value that was provided on create. +func (u *TaskUpsertOne) UpdateCompletion() *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.UpdateCompletion() + }) +} + +// ClearCompletion clears the value of the "completion" field. +func (u *TaskUpsertOne) ClearCompletion() *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.ClearCompletion() + }) +} + +// SetCodeLines sets the "code_lines" field. +func (u *TaskUpsertOne) SetCodeLines(v int64) *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.SetCodeLines(v) + }) +} + +// AddCodeLines adds v to the "code_lines" field. +func (u *TaskUpsertOne) AddCodeLines(v int64) *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.AddCodeLines(v) + }) +} + +// UpdateCodeLines sets the "code_lines" field to the value that was provided on create. +func (u *TaskUpsertOne) UpdateCodeLines() *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.UpdateCodeLines() + }) +} + +// ClearCodeLines clears the value of the "code_lines" field. +func (u *TaskUpsertOne) ClearCodeLines() *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.ClearCodeLines() + }) +} + +// SetInputTokens sets the "input_tokens" field. +func (u *TaskUpsertOne) SetInputTokens(v int64) *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.SetInputTokens(v) + }) +} + +// AddInputTokens adds v to the "input_tokens" field. +func (u *TaskUpsertOne) AddInputTokens(v int64) *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.AddInputTokens(v) + }) +} + +// UpdateInputTokens sets the "input_tokens" field to the value that was provided on create. +func (u *TaskUpsertOne) UpdateInputTokens() *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.UpdateInputTokens() + }) +} + +// ClearInputTokens clears the value of the "input_tokens" field. +func (u *TaskUpsertOne) ClearInputTokens() *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.ClearInputTokens() + }) +} + +// SetOutputTokens sets the "output_tokens" field. +func (u *TaskUpsertOne) SetOutputTokens(v int64) *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.SetOutputTokens(v) + }) +} + +// AddOutputTokens adds v to the "output_tokens" field. +func (u *TaskUpsertOne) AddOutputTokens(v int64) *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.AddOutputTokens(v) + }) +} + +// UpdateOutputTokens sets the "output_tokens" field to the value that was provided on create. +func (u *TaskUpsertOne) UpdateOutputTokens() *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.UpdateOutputTokens() + }) +} + +// ClearOutputTokens clears the value of the "output_tokens" field. +func (u *TaskUpsertOne) ClearOutputTokens() *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.ClearOutputTokens() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *TaskUpsertOne) SetCreatedAt(v time.Time) *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *TaskUpsertOne) UpdateCreatedAt() *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.UpdateCreatedAt() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *TaskUpsertOne) SetUpdatedAt(v time.Time) *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *TaskUpsertOne) UpdateUpdatedAt() *TaskUpsertOne { + return u.Update(func(s *TaskUpsert) { + s.UpdateUpdatedAt() + }) +} + +// Exec executes the query. +func (u *TaskUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for TaskCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *TaskUpsertOne) 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 *TaskUpsertOne) 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: TaskUpsertOne.ID is not supported by MySQL driver. Use TaskUpsertOne.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 *TaskUpsertOne) IDX(ctx context.Context) uuid.UUID { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// TaskCreateBulk is the builder for creating many Task entities in bulk. +type TaskCreateBulk struct { + config + err error + builders []*TaskCreate + conflict []sql.ConflictOption +} + +// Save creates the Task entities in the database. +func (tcb *TaskCreateBulk) Save(ctx context.Context) ([]*Task, error) { + if tcb.err != nil { + return nil, tcb.err + } + specs := make([]*sqlgraph.CreateSpec, len(tcb.builders)) + nodes := make([]*Task, len(tcb.builders)) + mutators := make([]Mutator, len(tcb.builders)) + for i := range tcb.builders { + func(i int, root context.Context) { + builder := tcb.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*TaskMutation) + 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, tcb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = tcb.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, tcb.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, tcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (tcb *TaskCreateBulk) SaveX(ctx context.Context) []*Task { + v, err := tcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (tcb *TaskCreateBulk) Exec(ctx context.Context) error { + _, err := tcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (tcb *TaskCreateBulk) ExecX(ctx context.Context) { + if err := tcb.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.Task.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.TaskUpsert) { +// SetTaskID(v+v). +// }). +// Exec(ctx) +func (tcb *TaskCreateBulk) OnConflict(opts ...sql.ConflictOption) *TaskUpsertBulk { + tcb.conflict = opts + return &TaskUpsertBulk{ + create: tcb, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.Task.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (tcb *TaskCreateBulk) OnConflictColumns(columns ...string) *TaskUpsertBulk { + tcb.conflict = append(tcb.conflict, sql.ConflictColumns(columns...)) + return &TaskUpsertBulk{ + create: tcb, + } +} + +// TaskUpsertBulk is the builder for "upsert"-ing +// a bulk of Task nodes. +type TaskUpsertBulk struct { + create *TaskCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.Task.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(task.FieldID) +// }), +// ). +// Exec(ctx) +func (u *TaskUpsertBulk) UpdateNewValues() *TaskUpsertBulk { + 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(task.FieldID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.Task.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *TaskUpsertBulk) Ignore() *TaskUpsertBulk { + 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 *TaskUpsertBulk) DoNothing() *TaskUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the TaskCreateBulk.OnConflict +// documentation for more info. +func (u *TaskUpsertBulk) Update(set func(*TaskUpsert)) *TaskUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&TaskUpsert{UpdateSet: update}) + })) + return u +} + +// SetTaskID sets the "task_id" field. +func (u *TaskUpsertBulk) SetTaskID(v string) *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.SetTaskID(v) + }) +} + +// UpdateTaskID sets the "task_id" field to the value that was provided on create. +func (u *TaskUpsertBulk) UpdateTaskID() *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.UpdateTaskID() + }) +} + +// SetUserID sets the "user_id" field. +func (u *TaskUpsertBulk) SetUserID(v uuid.UUID) *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.SetUserID(v) + }) +} + +// UpdateUserID sets the "user_id" field to the value that was provided on create. +func (u *TaskUpsertBulk) UpdateUserID() *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.UpdateUserID() + }) +} + +// ClearUserID clears the value of the "user_id" field. +func (u *TaskUpsertBulk) ClearUserID() *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.ClearUserID() + }) +} + +// SetModelID sets the "model_id" field. +func (u *TaskUpsertBulk) SetModelID(v uuid.UUID) *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.SetModelID(v) + }) +} + +// UpdateModelID sets the "model_id" field to the value that was provided on create. +func (u *TaskUpsertBulk) UpdateModelID() *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.UpdateModelID() + }) +} + +// ClearModelID clears the value of the "model_id" field. +func (u *TaskUpsertBulk) ClearModelID() *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.ClearModelID() + }) +} + +// SetRequestID sets the "request_id" field. +func (u *TaskUpsertBulk) SetRequestID(v string) *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.SetRequestID(v) + }) +} + +// UpdateRequestID sets the "request_id" field to the value that was provided on create. +func (u *TaskUpsertBulk) UpdateRequestID() *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.UpdateRequestID() + }) +} + +// ClearRequestID clears the value of the "request_id" field. +func (u *TaskUpsertBulk) ClearRequestID() *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.ClearRequestID() + }) +} + +// SetModelType sets the "model_type" field. +func (u *TaskUpsertBulk) SetModelType(v consts.ModelType) *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.SetModelType(v) + }) +} + +// UpdateModelType sets the "model_type" field to the value that was provided on create. +func (u *TaskUpsertBulk) UpdateModelType() *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.UpdateModelType() + }) +} + +// SetPrompt sets the "prompt" field. +func (u *TaskUpsertBulk) SetPrompt(v string) *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.SetPrompt(v) + }) +} + +// UpdatePrompt sets the "prompt" field to the value that was provided on create. +func (u *TaskUpsertBulk) UpdatePrompt() *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.UpdatePrompt() + }) +} + +// ClearPrompt clears the value of the "prompt" field. +func (u *TaskUpsertBulk) ClearPrompt() *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.ClearPrompt() + }) +} + +// SetIsAccept sets the "is_accept" field. +func (u *TaskUpsertBulk) SetIsAccept(v bool) *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.SetIsAccept(v) + }) +} + +// UpdateIsAccept sets the "is_accept" field to the value that was provided on create. +func (u *TaskUpsertBulk) UpdateIsAccept() *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.UpdateIsAccept() + }) +} + +// SetProgramLanguage sets the "program_language" field. +func (u *TaskUpsertBulk) SetProgramLanguage(v string) *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.SetProgramLanguage(v) + }) +} + +// UpdateProgramLanguage sets the "program_language" field to the value that was provided on create. +func (u *TaskUpsertBulk) UpdateProgramLanguage() *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.UpdateProgramLanguage() + }) +} + +// ClearProgramLanguage clears the value of the "program_language" field. +func (u *TaskUpsertBulk) ClearProgramLanguage() *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.ClearProgramLanguage() + }) +} + +// SetWorkMode sets the "work_mode" field. +func (u *TaskUpsertBulk) SetWorkMode(v string) *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.SetWorkMode(v) + }) +} + +// UpdateWorkMode sets the "work_mode" field to the value that was provided on create. +func (u *TaskUpsertBulk) UpdateWorkMode() *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.UpdateWorkMode() + }) +} + +// ClearWorkMode clears the value of the "work_mode" field. +func (u *TaskUpsertBulk) ClearWorkMode() *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.ClearWorkMode() + }) +} + +// SetCompletion sets the "completion" field. +func (u *TaskUpsertBulk) SetCompletion(v string) *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.SetCompletion(v) + }) +} + +// UpdateCompletion sets the "completion" field to the value that was provided on create. +func (u *TaskUpsertBulk) UpdateCompletion() *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.UpdateCompletion() + }) +} + +// ClearCompletion clears the value of the "completion" field. +func (u *TaskUpsertBulk) ClearCompletion() *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.ClearCompletion() + }) +} + +// SetCodeLines sets the "code_lines" field. +func (u *TaskUpsertBulk) SetCodeLines(v int64) *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.SetCodeLines(v) + }) +} + +// AddCodeLines adds v to the "code_lines" field. +func (u *TaskUpsertBulk) AddCodeLines(v int64) *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.AddCodeLines(v) + }) +} + +// UpdateCodeLines sets the "code_lines" field to the value that was provided on create. +func (u *TaskUpsertBulk) UpdateCodeLines() *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.UpdateCodeLines() + }) +} + +// ClearCodeLines clears the value of the "code_lines" field. +func (u *TaskUpsertBulk) ClearCodeLines() *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.ClearCodeLines() + }) +} + +// SetInputTokens sets the "input_tokens" field. +func (u *TaskUpsertBulk) SetInputTokens(v int64) *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.SetInputTokens(v) + }) +} + +// AddInputTokens adds v to the "input_tokens" field. +func (u *TaskUpsertBulk) AddInputTokens(v int64) *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.AddInputTokens(v) + }) +} + +// UpdateInputTokens sets the "input_tokens" field to the value that was provided on create. +func (u *TaskUpsertBulk) UpdateInputTokens() *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.UpdateInputTokens() + }) +} + +// ClearInputTokens clears the value of the "input_tokens" field. +func (u *TaskUpsertBulk) ClearInputTokens() *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.ClearInputTokens() + }) +} + +// SetOutputTokens sets the "output_tokens" field. +func (u *TaskUpsertBulk) SetOutputTokens(v int64) *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.SetOutputTokens(v) + }) +} + +// AddOutputTokens adds v to the "output_tokens" field. +func (u *TaskUpsertBulk) AddOutputTokens(v int64) *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.AddOutputTokens(v) + }) +} + +// UpdateOutputTokens sets the "output_tokens" field to the value that was provided on create. +func (u *TaskUpsertBulk) UpdateOutputTokens() *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.UpdateOutputTokens() + }) +} + +// ClearOutputTokens clears the value of the "output_tokens" field. +func (u *TaskUpsertBulk) ClearOutputTokens() *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.ClearOutputTokens() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *TaskUpsertBulk) SetCreatedAt(v time.Time) *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *TaskUpsertBulk) UpdateCreatedAt() *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.UpdateCreatedAt() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *TaskUpsertBulk) SetUpdatedAt(v time.Time) *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *TaskUpsertBulk) UpdateUpdatedAt() *TaskUpsertBulk { + return u.Update(func(s *TaskUpsert) { + s.UpdateUpdatedAt() + }) +} + +// Exec executes the query. +func (u *TaskUpsertBulk) 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 TaskCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for TaskCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *TaskUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/task_delete.go b/backend/db/task_delete.go new file mode 100644 index 0000000..692fc4d --- /dev/null +++ b/backend/db/task_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/task" +) + +// TaskDelete is the builder for deleting a Task entity. +type TaskDelete struct { + config + hooks []Hook + mutation *TaskMutation +} + +// Where appends a list predicates to the TaskDelete builder. +func (td *TaskDelete) Where(ps ...predicate.Task) *TaskDelete { + td.mutation.Where(ps...) + return td +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (td *TaskDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, td.sqlExec, td.mutation, td.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (td *TaskDelete) ExecX(ctx context.Context) int { + n, err := td.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (td *TaskDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(task.Table, sqlgraph.NewFieldSpec(task.FieldID, field.TypeUUID)) + if ps := td.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, td.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + td.mutation.done = true + return affected, err +} + +// TaskDeleteOne is the builder for deleting a single Task entity. +type TaskDeleteOne struct { + td *TaskDelete +} + +// Where appends a list predicates to the TaskDelete builder. +func (tdo *TaskDeleteOne) Where(ps ...predicate.Task) *TaskDeleteOne { + tdo.td.mutation.Where(ps...) + return tdo +} + +// Exec executes the deletion query. +func (tdo *TaskDeleteOne) Exec(ctx context.Context) error { + n, err := tdo.td.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{task.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (tdo *TaskDeleteOne) ExecX(ctx context.Context) { + if err := tdo.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/task_query.go b/backend/db/task_query.go new file mode 100644 index 0000000..f4a086e --- /dev/null +++ b/backend/db/task_query.go @@ -0,0 +1,807 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "database/sql/driver" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/model" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/task" + "github.com/chaitin/MonkeyCode/backend/db/taskrecord" + "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/google/uuid" +) + +// TaskQuery is the builder for querying Task entities. +type TaskQuery struct { + config + ctx *QueryContext + order []task.OrderOption + inters []Interceptor + predicates []predicate.Task + withTaskRecords *TaskRecordQuery + withUser *UserQuery + withModel *ModelQuery + modifiers []func(*sql.Selector) + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the TaskQuery builder. +func (tq *TaskQuery) Where(ps ...predicate.Task) *TaskQuery { + tq.predicates = append(tq.predicates, ps...) + return tq +} + +// Limit the number of records to be returned by this query. +func (tq *TaskQuery) Limit(limit int) *TaskQuery { + tq.ctx.Limit = &limit + return tq +} + +// Offset to start from. +func (tq *TaskQuery) Offset(offset int) *TaskQuery { + tq.ctx.Offset = &offset + return tq +} + +// 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 (tq *TaskQuery) Unique(unique bool) *TaskQuery { + tq.ctx.Unique = &unique + return tq +} + +// Order specifies how the records should be ordered. +func (tq *TaskQuery) Order(o ...task.OrderOption) *TaskQuery { + tq.order = append(tq.order, o...) + return tq +} + +// QueryTaskRecords chains the current query on the "task_records" edge. +func (tq *TaskQuery) QueryTaskRecords() *TaskRecordQuery { + query := (&TaskRecordClient{config: tq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := tq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := tq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(task.Table, task.FieldID, selector), + sqlgraph.To(taskrecord.Table, taskrecord.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, task.TaskRecordsTable, task.TaskRecordsColumn), + ) + fromU = sqlgraph.SetNeighbors(tq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryUser chains the current query on the "user" edge. +func (tq *TaskQuery) QueryUser() *UserQuery { + query := (&UserClient{config: tq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := tq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := tq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(task.Table, task.FieldID, selector), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, task.UserTable, task.UserColumn), + ) + fromU = sqlgraph.SetNeighbors(tq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryModel chains the current query on the "model" edge. +func (tq *TaskQuery) QueryModel() *ModelQuery { + query := (&ModelClient{config: tq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := tq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := tq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(task.Table, task.FieldID, selector), + sqlgraph.To(model.Table, model.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, task.ModelTable, task.ModelColumn), + ) + fromU = sqlgraph.SetNeighbors(tq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first Task entity from the query. +// Returns a *NotFoundError when no Task was found. +func (tq *TaskQuery) First(ctx context.Context) (*Task, error) { + nodes, err := tq.Limit(1).All(setContextOp(ctx, tq.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{task.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (tq *TaskQuery) FirstX(ctx context.Context) *Task { + node, err := tq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Task ID from the query. +// Returns a *NotFoundError when no Task ID was found. +func (tq *TaskQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = tq.Limit(1).IDs(setContextOp(ctx, tq.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{task.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (tq *TaskQuery) FirstIDX(ctx context.Context) uuid.UUID { + id, err := tq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Task entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Task entity is found. +// Returns a *NotFoundError when no Task entities are found. +func (tq *TaskQuery) Only(ctx context.Context) (*Task, error) { + nodes, err := tq.Limit(2).All(setContextOp(ctx, tq.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{task.Label} + default: + return nil, &NotSingularError{task.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (tq *TaskQuery) OnlyX(ctx context.Context) *Task { + node, err := tq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Task ID in the query. +// Returns a *NotSingularError when more than one Task ID is found. +// Returns a *NotFoundError when no entities are found. +func (tq *TaskQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = tq.Limit(2).IDs(setContextOp(ctx, tq.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{task.Label} + default: + err = &NotSingularError{task.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (tq *TaskQuery) OnlyIDX(ctx context.Context) uuid.UUID { + id, err := tq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Tasks. +func (tq *TaskQuery) All(ctx context.Context) ([]*Task, error) { + ctx = setContextOp(ctx, tq.ctx, ent.OpQueryAll) + if err := tq.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Task, *TaskQuery]() + return withInterceptors[[]*Task](ctx, tq, qr, tq.inters) +} + +// AllX is like All, but panics if an error occurs. +func (tq *TaskQuery) AllX(ctx context.Context) []*Task { + nodes, err := tq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Task IDs. +func (tq *TaskQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) { + if tq.ctx.Unique == nil && tq.path != nil { + tq.Unique(true) + } + ctx = setContextOp(ctx, tq.ctx, ent.OpQueryIDs) + if err = tq.Select(task.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (tq *TaskQuery) IDsX(ctx context.Context) []uuid.UUID { + ids, err := tq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (tq *TaskQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, tq.ctx, ent.OpQueryCount) + if err := tq.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, tq, querierCount[*TaskQuery](), tq.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (tq *TaskQuery) CountX(ctx context.Context) int { + count, err := tq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (tq *TaskQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, tq.ctx, ent.OpQueryExist) + switch _, err := tq.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 (tq *TaskQuery) ExistX(ctx context.Context) bool { + exist, err := tq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the TaskQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (tq *TaskQuery) Clone() *TaskQuery { + if tq == nil { + return nil + } + return &TaskQuery{ + config: tq.config, + ctx: tq.ctx.Clone(), + order: append([]task.OrderOption{}, tq.order...), + inters: append([]Interceptor{}, tq.inters...), + predicates: append([]predicate.Task{}, tq.predicates...), + withTaskRecords: tq.withTaskRecords.Clone(), + withUser: tq.withUser.Clone(), + withModel: tq.withModel.Clone(), + // clone intermediate query. + sql: tq.sql.Clone(), + path: tq.path, + modifiers: append([]func(*sql.Selector){}, tq.modifiers...), + } +} + +// WithTaskRecords tells the query-builder to eager-load the nodes that are connected to +// the "task_records" edge. The optional arguments are used to configure the query builder of the edge. +func (tq *TaskQuery) WithTaskRecords(opts ...func(*TaskRecordQuery)) *TaskQuery { + query := (&TaskRecordClient{config: tq.config}).Query() + for _, opt := range opts { + opt(query) + } + tq.withTaskRecords = query + return tq +} + +// WithUser tells the query-builder to eager-load the nodes that are connected to +// the "user" edge. The optional arguments are used to configure the query builder of the edge. +func (tq *TaskQuery) WithUser(opts ...func(*UserQuery)) *TaskQuery { + query := (&UserClient{config: tq.config}).Query() + for _, opt := range opts { + opt(query) + } + tq.withUser = query + return tq +} + +// WithModel tells the query-builder to eager-load the nodes that are connected to +// the "model" edge. The optional arguments are used to configure the query builder of the edge. +func (tq *TaskQuery) WithModel(opts ...func(*ModelQuery)) *TaskQuery { + query := (&ModelClient{config: tq.config}).Query() + for _, opt := range opts { + opt(query) + } + tq.withModel = query + return tq +} + +// 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 { +// TaskID string `json:"task_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Task.Query(). +// GroupBy(task.FieldTaskID). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (tq *TaskQuery) GroupBy(field string, fields ...string) *TaskGroupBy { + tq.ctx.Fields = append([]string{field}, fields...) + grbuild := &TaskGroupBy{build: tq} + grbuild.flds = &tq.ctx.Fields + grbuild.label = task.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 { +// TaskID string `json:"task_id,omitempty"` +// } +// +// client.Task.Query(). +// Select(task.FieldTaskID). +// Scan(ctx, &v) +func (tq *TaskQuery) Select(fields ...string) *TaskSelect { + tq.ctx.Fields = append(tq.ctx.Fields, fields...) + sbuild := &TaskSelect{TaskQuery: tq} + sbuild.label = task.Label + sbuild.flds, sbuild.scan = &tq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a TaskSelect configured with the given aggregations. +func (tq *TaskQuery) Aggregate(fns ...AggregateFunc) *TaskSelect { + return tq.Select().Aggregate(fns...) +} + +func (tq *TaskQuery) prepareQuery(ctx context.Context) error { + for _, inter := range tq.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, tq); err != nil { + return err + } + } + } + for _, f := range tq.ctx.Fields { + if !task.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + } + if tq.path != nil { + prev, err := tq.path(ctx) + if err != nil { + return err + } + tq.sql = prev + } + return nil +} + +func (tq *TaskQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Task, error) { + var ( + nodes = []*Task{} + _spec = tq.querySpec() + loadedTypes = [3]bool{ + tq.withTaskRecords != nil, + tq.withUser != nil, + tq.withModel != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Task).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Task{config: tq.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(tq.modifiers) > 0 { + _spec.Modifiers = tq.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, tq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := tq.withTaskRecords; query != nil { + if err := tq.loadTaskRecords(ctx, query, nodes, + func(n *Task) { n.Edges.TaskRecords = []*TaskRecord{} }, + func(n *Task, e *TaskRecord) { n.Edges.TaskRecords = append(n.Edges.TaskRecords, e) }); err != nil { + return nil, err + } + } + if query := tq.withUser; query != nil { + if err := tq.loadUser(ctx, query, nodes, nil, + func(n *Task, e *User) { n.Edges.User = e }); err != nil { + return nil, err + } + } + if query := tq.withModel; query != nil { + if err := tq.loadModel(ctx, query, nodes, nil, + func(n *Task, e *Model) { n.Edges.Model = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (tq *TaskQuery) loadTaskRecords(ctx context.Context, query *TaskRecordQuery, nodes []*Task, init func(*Task), assign func(*Task, *TaskRecord)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[uuid.UUID]*Task) + 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(taskrecord.FieldTaskID) + } + query.Where(predicate.TaskRecord(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(task.TaskRecordsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.TaskID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "task_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} +func (tq *TaskQuery) loadUser(ctx context.Context, query *UserQuery, nodes []*Task, init func(*Task), assign func(*Task, *User)) error { + ids := make([]uuid.UUID, 0, len(nodes)) + nodeids := make(map[uuid.UUID][]*Task) + for i := range nodes { + fk := nodes[i].UserID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(user.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return fmt.Errorf(`unexpected foreign-key "user_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (tq *TaskQuery) loadModel(ctx context.Context, query *ModelQuery, nodes []*Task, init func(*Task), assign func(*Task, *Model)) error { + ids := make([]uuid.UUID, 0, len(nodes)) + nodeids := make(map[uuid.UUID][]*Task) + for i := range nodes { + fk := nodes[i].ModelID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(model.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return fmt.Errorf(`unexpected foreign-key "model_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (tq *TaskQuery) sqlCount(ctx context.Context) (int, error) { + _spec := tq.querySpec() + if len(tq.modifiers) > 0 { + _spec.Modifiers = tq.modifiers + } + _spec.Node.Columns = tq.ctx.Fields + if len(tq.ctx.Fields) > 0 { + _spec.Unique = tq.ctx.Unique != nil && *tq.ctx.Unique + } + return sqlgraph.CountNodes(ctx, tq.driver, _spec) +} + +func (tq *TaskQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(task.Table, task.Columns, sqlgraph.NewFieldSpec(task.FieldID, field.TypeUUID)) + _spec.From = tq.sql + if unique := tq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if tq.path != nil { + _spec.Unique = true + } + if fields := tq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, task.FieldID) + for i := range fields { + if fields[i] != task.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if tq.withUser != nil { + _spec.Node.AddColumnOnce(task.FieldUserID) + } + if tq.withModel != nil { + _spec.Node.AddColumnOnce(task.FieldModelID) + } + } + if ps := tq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := tq.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := tq.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := tq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (tq *TaskQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(tq.driver.Dialect()) + t1 := builder.Table(task.Table) + columns := tq.ctx.Fields + if len(columns) == 0 { + columns = task.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if tq.sql != nil { + selector = tq.sql + selector.Select(selector.Columns(columns...)...) + } + if tq.ctx.Unique != nil && *tq.ctx.Unique { + selector.Distinct() + } + for _, m := range tq.modifiers { + m(selector) + } + for _, p := range tq.predicates { + p(selector) + } + for _, p := range tq.order { + p(selector) + } + if offset := tq.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 := tq.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 (tq *TaskQuery) ForUpdate(opts ...sql.LockOption) *TaskQuery { + if tq.driver.Dialect() == dialect.Postgres { + tq.Unique(false) + } + tq.modifiers = append(tq.modifiers, func(s *sql.Selector) { + s.ForUpdate(opts...) + }) + return tq +} + +// 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 (tq *TaskQuery) ForShare(opts ...sql.LockOption) *TaskQuery { + if tq.driver.Dialect() == dialect.Postgres { + tq.Unique(false) + } + tq.modifiers = append(tq.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return tq +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (tq *TaskQuery) Modify(modifiers ...func(s *sql.Selector)) *TaskSelect { + tq.modifiers = append(tq.modifiers, modifiers...) + return tq.Select() +} + +// TaskGroupBy is the group-by builder for Task entities. +type TaskGroupBy struct { + selector + build *TaskQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (tgb *TaskGroupBy) Aggregate(fns ...AggregateFunc) *TaskGroupBy { + tgb.fns = append(tgb.fns, fns...) + return tgb +} + +// Scan applies the selector query and scans the result into the given value. +func (tgb *TaskGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, tgb.build.ctx, ent.OpQueryGroupBy) + if err := tgb.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*TaskQuery, *TaskGroupBy](ctx, tgb.build, tgb, tgb.build.inters, v) +} + +func (tgb *TaskGroupBy) sqlScan(ctx context.Context, root *TaskQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(tgb.fns)) + for _, fn := range tgb.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*tgb.flds)+len(tgb.fns)) + for _, f := range *tgb.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*tgb.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := tgb.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// TaskSelect is the builder for selecting fields of Task entities. +type TaskSelect struct { + *TaskQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (ts *TaskSelect) Aggregate(fns ...AggregateFunc) *TaskSelect { + ts.fns = append(ts.fns, fns...) + return ts +} + +// Scan applies the selector query and scans the result into the given value. +func (ts *TaskSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, ts.ctx, ent.OpQuerySelect) + if err := ts.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*TaskQuery, *TaskSelect](ctx, ts.TaskQuery, ts, ts.inters, v) +} + +func (ts *TaskSelect) sqlScan(ctx context.Context, root *TaskQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(ts.fns)) + for _, fn := range ts.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*ts.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 := ts.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 (ts *TaskSelect) Modify(modifiers ...func(s *sql.Selector)) *TaskSelect { + ts.modifiers = append(ts.modifiers, modifiers...) + return ts +} diff --git a/backend/db/task_update.go b/backend/db/task_update.go new file mode 100644 index 0000000..87a1453 --- /dev/null +++ b/backend/db/task_update.go @@ -0,0 +1,1247 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/consts" + "github.com/chaitin/MonkeyCode/backend/db/model" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/task" + "github.com/chaitin/MonkeyCode/backend/db/taskrecord" + "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/google/uuid" +) + +// TaskUpdate is the builder for updating Task entities. +type TaskUpdate struct { + config + hooks []Hook + mutation *TaskMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the TaskUpdate builder. +func (tu *TaskUpdate) Where(ps ...predicate.Task) *TaskUpdate { + tu.mutation.Where(ps...) + return tu +} + +// SetTaskID sets the "task_id" field. +func (tu *TaskUpdate) SetTaskID(s string) *TaskUpdate { + tu.mutation.SetTaskID(s) + return tu +} + +// SetNillableTaskID sets the "task_id" field if the given value is not nil. +func (tu *TaskUpdate) SetNillableTaskID(s *string) *TaskUpdate { + if s != nil { + tu.SetTaskID(*s) + } + return tu +} + +// SetUserID sets the "user_id" field. +func (tu *TaskUpdate) SetUserID(u uuid.UUID) *TaskUpdate { + tu.mutation.SetUserID(u) + return tu +} + +// SetNillableUserID sets the "user_id" field if the given value is not nil. +func (tu *TaskUpdate) SetNillableUserID(u *uuid.UUID) *TaskUpdate { + if u != nil { + tu.SetUserID(*u) + } + return tu +} + +// ClearUserID clears the value of the "user_id" field. +func (tu *TaskUpdate) ClearUserID() *TaskUpdate { + tu.mutation.ClearUserID() + return tu +} + +// SetModelID sets the "model_id" field. +func (tu *TaskUpdate) SetModelID(u uuid.UUID) *TaskUpdate { + tu.mutation.SetModelID(u) + return tu +} + +// SetNillableModelID sets the "model_id" field if the given value is not nil. +func (tu *TaskUpdate) SetNillableModelID(u *uuid.UUID) *TaskUpdate { + if u != nil { + tu.SetModelID(*u) + } + return tu +} + +// ClearModelID clears the value of the "model_id" field. +func (tu *TaskUpdate) ClearModelID() *TaskUpdate { + tu.mutation.ClearModelID() + return tu +} + +// SetRequestID sets the "request_id" field. +func (tu *TaskUpdate) SetRequestID(s string) *TaskUpdate { + tu.mutation.SetRequestID(s) + return tu +} + +// SetNillableRequestID sets the "request_id" field if the given value is not nil. +func (tu *TaskUpdate) SetNillableRequestID(s *string) *TaskUpdate { + if s != nil { + tu.SetRequestID(*s) + } + return tu +} + +// ClearRequestID clears the value of the "request_id" field. +func (tu *TaskUpdate) ClearRequestID() *TaskUpdate { + tu.mutation.ClearRequestID() + return tu +} + +// SetModelType sets the "model_type" field. +func (tu *TaskUpdate) SetModelType(ct consts.ModelType) *TaskUpdate { + tu.mutation.SetModelType(ct) + return tu +} + +// SetNillableModelType sets the "model_type" field if the given value is not nil. +func (tu *TaskUpdate) SetNillableModelType(ct *consts.ModelType) *TaskUpdate { + if ct != nil { + tu.SetModelType(*ct) + } + return tu +} + +// SetPrompt sets the "prompt" field. +func (tu *TaskUpdate) SetPrompt(s string) *TaskUpdate { + tu.mutation.SetPrompt(s) + return tu +} + +// SetNillablePrompt sets the "prompt" field if the given value is not nil. +func (tu *TaskUpdate) SetNillablePrompt(s *string) *TaskUpdate { + if s != nil { + tu.SetPrompt(*s) + } + return tu +} + +// ClearPrompt clears the value of the "prompt" field. +func (tu *TaskUpdate) ClearPrompt() *TaskUpdate { + tu.mutation.ClearPrompt() + return tu +} + +// SetIsAccept sets the "is_accept" field. +func (tu *TaskUpdate) SetIsAccept(b bool) *TaskUpdate { + tu.mutation.SetIsAccept(b) + return tu +} + +// SetNillableIsAccept sets the "is_accept" field if the given value is not nil. +func (tu *TaskUpdate) SetNillableIsAccept(b *bool) *TaskUpdate { + if b != nil { + tu.SetIsAccept(*b) + } + return tu +} + +// SetProgramLanguage sets the "program_language" field. +func (tu *TaskUpdate) SetProgramLanguage(s string) *TaskUpdate { + tu.mutation.SetProgramLanguage(s) + return tu +} + +// SetNillableProgramLanguage sets the "program_language" field if the given value is not nil. +func (tu *TaskUpdate) SetNillableProgramLanguage(s *string) *TaskUpdate { + if s != nil { + tu.SetProgramLanguage(*s) + } + return tu +} + +// ClearProgramLanguage clears the value of the "program_language" field. +func (tu *TaskUpdate) ClearProgramLanguage() *TaskUpdate { + tu.mutation.ClearProgramLanguage() + return tu +} + +// SetWorkMode sets the "work_mode" field. +func (tu *TaskUpdate) SetWorkMode(s string) *TaskUpdate { + tu.mutation.SetWorkMode(s) + return tu +} + +// SetNillableWorkMode sets the "work_mode" field if the given value is not nil. +func (tu *TaskUpdate) SetNillableWorkMode(s *string) *TaskUpdate { + if s != nil { + tu.SetWorkMode(*s) + } + return tu +} + +// ClearWorkMode clears the value of the "work_mode" field. +func (tu *TaskUpdate) ClearWorkMode() *TaskUpdate { + tu.mutation.ClearWorkMode() + return tu +} + +// SetCompletion sets the "completion" field. +func (tu *TaskUpdate) SetCompletion(s string) *TaskUpdate { + tu.mutation.SetCompletion(s) + return tu +} + +// SetNillableCompletion sets the "completion" field if the given value is not nil. +func (tu *TaskUpdate) SetNillableCompletion(s *string) *TaskUpdate { + if s != nil { + tu.SetCompletion(*s) + } + return tu +} + +// ClearCompletion clears the value of the "completion" field. +func (tu *TaskUpdate) ClearCompletion() *TaskUpdate { + tu.mutation.ClearCompletion() + return tu +} + +// SetCodeLines sets the "code_lines" field. +func (tu *TaskUpdate) SetCodeLines(i int64) *TaskUpdate { + tu.mutation.ResetCodeLines() + tu.mutation.SetCodeLines(i) + return tu +} + +// SetNillableCodeLines sets the "code_lines" field if the given value is not nil. +func (tu *TaskUpdate) SetNillableCodeLines(i *int64) *TaskUpdate { + if i != nil { + tu.SetCodeLines(*i) + } + return tu +} + +// AddCodeLines adds i to the "code_lines" field. +func (tu *TaskUpdate) AddCodeLines(i int64) *TaskUpdate { + tu.mutation.AddCodeLines(i) + return tu +} + +// ClearCodeLines clears the value of the "code_lines" field. +func (tu *TaskUpdate) ClearCodeLines() *TaskUpdate { + tu.mutation.ClearCodeLines() + return tu +} + +// SetInputTokens sets the "input_tokens" field. +func (tu *TaskUpdate) SetInputTokens(i int64) *TaskUpdate { + tu.mutation.ResetInputTokens() + tu.mutation.SetInputTokens(i) + return tu +} + +// SetNillableInputTokens sets the "input_tokens" field if the given value is not nil. +func (tu *TaskUpdate) SetNillableInputTokens(i *int64) *TaskUpdate { + if i != nil { + tu.SetInputTokens(*i) + } + return tu +} + +// AddInputTokens adds i to the "input_tokens" field. +func (tu *TaskUpdate) AddInputTokens(i int64) *TaskUpdate { + tu.mutation.AddInputTokens(i) + return tu +} + +// ClearInputTokens clears the value of the "input_tokens" field. +func (tu *TaskUpdate) ClearInputTokens() *TaskUpdate { + tu.mutation.ClearInputTokens() + return tu +} + +// SetOutputTokens sets the "output_tokens" field. +func (tu *TaskUpdate) SetOutputTokens(i int64) *TaskUpdate { + tu.mutation.ResetOutputTokens() + tu.mutation.SetOutputTokens(i) + return tu +} + +// SetNillableOutputTokens sets the "output_tokens" field if the given value is not nil. +func (tu *TaskUpdate) SetNillableOutputTokens(i *int64) *TaskUpdate { + if i != nil { + tu.SetOutputTokens(*i) + } + return tu +} + +// AddOutputTokens adds i to the "output_tokens" field. +func (tu *TaskUpdate) AddOutputTokens(i int64) *TaskUpdate { + tu.mutation.AddOutputTokens(i) + return tu +} + +// ClearOutputTokens clears the value of the "output_tokens" field. +func (tu *TaskUpdate) ClearOutputTokens() *TaskUpdate { + tu.mutation.ClearOutputTokens() + return tu +} + +// SetCreatedAt sets the "created_at" field. +func (tu *TaskUpdate) SetCreatedAt(t time.Time) *TaskUpdate { + tu.mutation.SetCreatedAt(t) + return tu +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (tu *TaskUpdate) SetNillableCreatedAt(t *time.Time) *TaskUpdate { + if t != nil { + tu.SetCreatedAt(*t) + } + return tu +} + +// SetUpdatedAt sets the "updated_at" field. +func (tu *TaskUpdate) SetUpdatedAt(t time.Time) *TaskUpdate { + tu.mutation.SetUpdatedAt(t) + return tu +} + +// AddTaskRecordIDs adds the "task_records" edge to the TaskRecord entity by IDs. +func (tu *TaskUpdate) AddTaskRecordIDs(ids ...uuid.UUID) *TaskUpdate { + tu.mutation.AddTaskRecordIDs(ids...) + return tu +} + +// AddTaskRecords adds the "task_records" edges to the TaskRecord entity. +func (tu *TaskUpdate) AddTaskRecords(t ...*TaskRecord) *TaskUpdate { + ids := make([]uuid.UUID, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return tu.AddTaskRecordIDs(ids...) +} + +// SetUser sets the "user" edge to the User entity. +func (tu *TaskUpdate) SetUser(u *User) *TaskUpdate { + return tu.SetUserID(u.ID) +} + +// SetModel sets the "model" edge to the Model entity. +func (tu *TaskUpdate) SetModel(m *Model) *TaskUpdate { + return tu.SetModelID(m.ID) +} + +// Mutation returns the TaskMutation object of the builder. +func (tu *TaskUpdate) Mutation() *TaskMutation { + return tu.mutation +} + +// ClearTaskRecords clears all "task_records" edges to the TaskRecord entity. +func (tu *TaskUpdate) ClearTaskRecords() *TaskUpdate { + tu.mutation.ClearTaskRecords() + return tu +} + +// RemoveTaskRecordIDs removes the "task_records" edge to TaskRecord entities by IDs. +func (tu *TaskUpdate) RemoveTaskRecordIDs(ids ...uuid.UUID) *TaskUpdate { + tu.mutation.RemoveTaskRecordIDs(ids...) + return tu +} + +// RemoveTaskRecords removes "task_records" edges to TaskRecord entities. +func (tu *TaskUpdate) RemoveTaskRecords(t ...*TaskRecord) *TaskUpdate { + ids := make([]uuid.UUID, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return tu.RemoveTaskRecordIDs(ids...) +} + +// ClearUser clears the "user" edge to the User entity. +func (tu *TaskUpdate) ClearUser() *TaskUpdate { + tu.mutation.ClearUser() + return tu +} + +// ClearModel clears the "model" edge to the Model entity. +func (tu *TaskUpdate) ClearModel() *TaskUpdate { + tu.mutation.ClearModel() + return tu +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (tu *TaskUpdate) Save(ctx context.Context) (int, error) { + tu.defaults() + return withHooks(ctx, tu.sqlSave, tu.mutation, tu.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (tu *TaskUpdate) SaveX(ctx context.Context) int { + affected, err := tu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (tu *TaskUpdate) Exec(ctx context.Context) error { + _, err := tu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (tu *TaskUpdate) ExecX(ctx context.Context) { + if err := tu.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (tu *TaskUpdate) defaults() { + if _, ok := tu.mutation.UpdatedAt(); !ok { + v := task.UpdateDefaultUpdatedAt() + tu.mutation.SetUpdatedAt(v) + } +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (tu *TaskUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *TaskUpdate { + tu.modifiers = append(tu.modifiers, modifiers...) + return tu +} + +func (tu *TaskUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := sqlgraph.NewUpdateSpec(task.Table, task.Columns, sqlgraph.NewFieldSpec(task.FieldID, field.TypeUUID)) + if ps := tu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := tu.mutation.TaskID(); ok { + _spec.SetField(task.FieldTaskID, field.TypeString, value) + } + if value, ok := tu.mutation.RequestID(); ok { + _spec.SetField(task.FieldRequestID, field.TypeString, value) + } + if tu.mutation.RequestIDCleared() { + _spec.ClearField(task.FieldRequestID, field.TypeString) + } + if value, ok := tu.mutation.ModelType(); ok { + _spec.SetField(task.FieldModelType, field.TypeString, value) + } + if value, ok := tu.mutation.Prompt(); ok { + _spec.SetField(task.FieldPrompt, field.TypeString, value) + } + if tu.mutation.PromptCleared() { + _spec.ClearField(task.FieldPrompt, field.TypeString) + } + if value, ok := tu.mutation.IsAccept(); ok { + _spec.SetField(task.FieldIsAccept, field.TypeBool, value) + } + if value, ok := tu.mutation.ProgramLanguage(); ok { + _spec.SetField(task.FieldProgramLanguage, field.TypeString, value) + } + if tu.mutation.ProgramLanguageCleared() { + _spec.ClearField(task.FieldProgramLanguage, field.TypeString) + } + if value, ok := tu.mutation.WorkMode(); ok { + _spec.SetField(task.FieldWorkMode, field.TypeString, value) + } + if tu.mutation.WorkModeCleared() { + _spec.ClearField(task.FieldWorkMode, field.TypeString) + } + if value, ok := tu.mutation.Completion(); ok { + _spec.SetField(task.FieldCompletion, field.TypeString, value) + } + if tu.mutation.CompletionCleared() { + _spec.ClearField(task.FieldCompletion, field.TypeString) + } + if value, ok := tu.mutation.CodeLines(); ok { + _spec.SetField(task.FieldCodeLines, field.TypeInt64, value) + } + if value, ok := tu.mutation.AddedCodeLines(); ok { + _spec.AddField(task.FieldCodeLines, field.TypeInt64, value) + } + if tu.mutation.CodeLinesCleared() { + _spec.ClearField(task.FieldCodeLines, field.TypeInt64) + } + if value, ok := tu.mutation.InputTokens(); ok { + _spec.SetField(task.FieldInputTokens, field.TypeInt64, value) + } + if value, ok := tu.mutation.AddedInputTokens(); ok { + _spec.AddField(task.FieldInputTokens, field.TypeInt64, value) + } + if tu.mutation.InputTokensCleared() { + _spec.ClearField(task.FieldInputTokens, field.TypeInt64) + } + if value, ok := tu.mutation.OutputTokens(); ok { + _spec.SetField(task.FieldOutputTokens, field.TypeInt64, value) + } + if value, ok := tu.mutation.AddedOutputTokens(); ok { + _spec.AddField(task.FieldOutputTokens, field.TypeInt64, value) + } + if tu.mutation.OutputTokensCleared() { + _spec.ClearField(task.FieldOutputTokens, field.TypeInt64) + } + if value, ok := tu.mutation.CreatedAt(); ok { + _spec.SetField(task.FieldCreatedAt, field.TypeTime, value) + } + if value, ok := tu.mutation.UpdatedAt(); ok { + _spec.SetField(task.FieldUpdatedAt, field.TypeTime, value) + } + if tu.mutation.TaskRecordsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: task.TaskRecordsTable, + Columns: []string{task.TaskRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(taskrecord.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tu.mutation.RemovedTaskRecordsIDs(); len(nodes) > 0 && !tu.mutation.TaskRecordsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: task.TaskRecordsTable, + Columns: []string{task.TaskRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(taskrecord.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 := tu.mutation.TaskRecordsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: task.TaskRecordsTable, + Columns: []string{task.TaskRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(taskrecord.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if tu.mutation.UserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: task.UserTable, + Columns: []string{task.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tu.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: task.UserTable, + Columns: []string{task.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if tu.mutation.ModelCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: task.ModelTable, + Columns: []string{task.ModelColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(model.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tu.mutation.ModelIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: task.ModelTable, + Columns: []string{task.ModelColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(model.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(tu.modifiers...) + if n, err = sqlgraph.UpdateNodes(ctx, tu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{task.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + tu.mutation.done = true + return n, nil +} + +// TaskUpdateOne is the builder for updating a single Task entity. +type TaskUpdateOne struct { + config + fields []string + hooks []Hook + mutation *TaskMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetTaskID sets the "task_id" field. +func (tuo *TaskUpdateOne) SetTaskID(s string) *TaskUpdateOne { + tuo.mutation.SetTaskID(s) + return tuo +} + +// SetNillableTaskID sets the "task_id" field if the given value is not nil. +func (tuo *TaskUpdateOne) SetNillableTaskID(s *string) *TaskUpdateOne { + if s != nil { + tuo.SetTaskID(*s) + } + return tuo +} + +// SetUserID sets the "user_id" field. +func (tuo *TaskUpdateOne) SetUserID(u uuid.UUID) *TaskUpdateOne { + tuo.mutation.SetUserID(u) + return tuo +} + +// SetNillableUserID sets the "user_id" field if the given value is not nil. +func (tuo *TaskUpdateOne) SetNillableUserID(u *uuid.UUID) *TaskUpdateOne { + if u != nil { + tuo.SetUserID(*u) + } + return tuo +} + +// ClearUserID clears the value of the "user_id" field. +func (tuo *TaskUpdateOne) ClearUserID() *TaskUpdateOne { + tuo.mutation.ClearUserID() + return tuo +} + +// SetModelID sets the "model_id" field. +func (tuo *TaskUpdateOne) SetModelID(u uuid.UUID) *TaskUpdateOne { + tuo.mutation.SetModelID(u) + return tuo +} + +// SetNillableModelID sets the "model_id" field if the given value is not nil. +func (tuo *TaskUpdateOne) SetNillableModelID(u *uuid.UUID) *TaskUpdateOne { + if u != nil { + tuo.SetModelID(*u) + } + return tuo +} + +// ClearModelID clears the value of the "model_id" field. +func (tuo *TaskUpdateOne) ClearModelID() *TaskUpdateOne { + tuo.mutation.ClearModelID() + return tuo +} + +// SetRequestID sets the "request_id" field. +func (tuo *TaskUpdateOne) SetRequestID(s string) *TaskUpdateOne { + tuo.mutation.SetRequestID(s) + return tuo +} + +// SetNillableRequestID sets the "request_id" field if the given value is not nil. +func (tuo *TaskUpdateOne) SetNillableRequestID(s *string) *TaskUpdateOne { + if s != nil { + tuo.SetRequestID(*s) + } + return tuo +} + +// ClearRequestID clears the value of the "request_id" field. +func (tuo *TaskUpdateOne) ClearRequestID() *TaskUpdateOne { + tuo.mutation.ClearRequestID() + return tuo +} + +// SetModelType sets the "model_type" field. +func (tuo *TaskUpdateOne) SetModelType(ct consts.ModelType) *TaskUpdateOne { + tuo.mutation.SetModelType(ct) + return tuo +} + +// SetNillableModelType sets the "model_type" field if the given value is not nil. +func (tuo *TaskUpdateOne) SetNillableModelType(ct *consts.ModelType) *TaskUpdateOne { + if ct != nil { + tuo.SetModelType(*ct) + } + return tuo +} + +// SetPrompt sets the "prompt" field. +func (tuo *TaskUpdateOne) SetPrompt(s string) *TaskUpdateOne { + tuo.mutation.SetPrompt(s) + return tuo +} + +// SetNillablePrompt sets the "prompt" field if the given value is not nil. +func (tuo *TaskUpdateOne) SetNillablePrompt(s *string) *TaskUpdateOne { + if s != nil { + tuo.SetPrompt(*s) + } + return tuo +} + +// ClearPrompt clears the value of the "prompt" field. +func (tuo *TaskUpdateOne) ClearPrompt() *TaskUpdateOne { + tuo.mutation.ClearPrompt() + return tuo +} + +// SetIsAccept sets the "is_accept" field. +func (tuo *TaskUpdateOne) SetIsAccept(b bool) *TaskUpdateOne { + tuo.mutation.SetIsAccept(b) + return tuo +} + +// SetNillableIsAccept sets the "is_accept" field if the given value is not nil. +func (tuo *TaskUpdateOne) SetNillableIsAccept(b *bool) *TaskUpdateOne { + if b != nil { + tuo.SetIsAccept(*b) + } + return tuo +} + +// SetProgramLanguage sets the "program_language" field. +func (tuo *TaskUpdateOne) SetProgramLanguage(s string) *TaskUpdateOne { + tuo.mutation.SetProgramLanguage(s) + return tuo +} + +// SetNillableProgramLanguage sets the "program_language" field if the given value is not nil. +func (tuo *TaskUpdateOne) SetNillableProgramLanguage(s *string) *TaskUpdateOne { + if s != nil { + tuo.SetProgramLanguage(*s) + } + return tuo +} + +// ClearProgramLanguage clears the value of the "program_language" field. +func (tuo *TaskUpdateOne) ClearProgramLanguage() *TaskUpdateOne { + tuo.mutation.ClearProgramLanguage() + return tuo +} + +// SetWorkMode sets the "work_mode" field. +func (tuo *TaskUpdateOne) SetWorkMode(s string) *TaskUpdateOne { + tuo.mutation.SetWorkMode(s) + return tuo +} + +// SetNillableWorkMode sets the "work_mode" field if the given value is not nil. +func (tuo *TaskUpdateOne) SetNillableWorkMode(s *string) *TaskUpdateOne { + if s != nil { + tuo.SetWorkMode(*s) + } + return tuo +} + +// ClearWorkMode clears the value of the "work_mode" field. +func (tuo *TaskUpdateOne) ClearWorkMode() *TaskUpdateOne { + tuo.mutation.ClearWorkMode() + return tuo +} + +// SetCompletion sets the "completion" field. +func (tuo *TaskUpdateOne) SetCompletion(s string) *TaskUpdateOne { + tuo.mutation.SetCompletion(s) + return tuo +} + +// SetNillableCompletion sets the "completion" field if the given value is not nil. +func (tuo *TaskUpdateOne) SetNillableCompletion(s *string) *TaskUpdateOne { + if s != nil { + tuo.SetCompletion(*s) + } + return tuo +} + +// ClearCompletion clears the value of the "completion" field. +func (tuo *TaskUpdateOne) ClearCompletion() *TaskUpdateOne { + tuo.mutation.ClearCompletion() + return tuo +} + +// SetCodeLines sets the "code_lines" field. +func (tuo *TaskUpdateOne) SetCodeLines(i int64) *TaskUpdateOne { + tuo.mutation.ResetCodeLines() + tuo.mutation.SetCodeLines(i) + return tuo +} + +// SetNillableCodeLines sets the "code_lines" field if the given value is not nil. +func (tuo *TaskUpdateOne) SetNillableCodeLines(i *int64) *TaskUpdateOne { + if i != nil { + tuo.SetCodeLines(*i) + } + return tuo +} + +// AddCodeLines adds i to the "code_lines" field. +func (tuo *TaskUpdateOne) AddCodeLines(i int64) *TaskUpdateOne { + tuo.mutation.AddCodeLines(i) + return tuo +} + +// ClearCodeLines clears the value of the "code_lines" field. +func (tuo *TaskUpdateOne) ClearCodeLines() *TaskUpdateOne { + tuo.mutation.ClearCodeLines() + return tuo +} + +// SetInputTokens sets the "input_tokens" field. +func (tuo *TaskUpdateOne) SetInputTokens(i int64) *TaskUpdateOne { + tuo.mutation.ResetInputTokens() + tuo.mutation.SetInputTokens(i) + return tuo +} + +// SetNillableInputTokens sets the "input_tokens" field if the given value is not nil. +func (tuo *TaskUpdateOne) SetNillableInputTokens(i *int64) *TaskUpdateOne { + if i != nil { + tuo.SetInputTokens(*i) + } + return tuo +} + +// AddInputTokens adds i to the "input_tokens" field. +func (tuo *TaskUpdateOne) AddInputTokens(i int64) *TaskUpdateOne { + tuo.mutation.AddInputTokens(i) + return tuo +} + +// ClearInputTokens clears the value of the "input_tokens" field. +func (tuo *TaskUpdateOne) ClearInputTokens() *TaskUpdateOne { + tuo.mutation.ClearInputTokens() + return tuo +} + +// SetOutputTokens sets the "output_tokens" field. +func (tuo *TaskUpdateOne) SetOutputTokens(i int64) *TaskUpdateOne { + tuo.mutation.ResetOutputTokens() + tuo.mutation.SetOutputTokens(i) + return tuo +} + +// SetNillableOutputTokens sets the "output_tokens" field if the given value is not nil. +func (tuo *TaskUpdateOne) SetNillableOutputTokens(i *int64) *TaskUpdateOne { + if i != nil { + tuo.SetOutputTokens(*i) + } + return tuo +} + +// AddOutputTokens adds i to the "output_tokens" field. +func (tuo *TaskUpdateOne) AddOutputTokens(i int64) *TaskUpdateOne { + tuo.mutation.AddOutputTokens(i) + return tuo +} + +// ClearOutputTokens clears the value of the "output_tokens" field. +func (tuo *TaskUpdateOne) ClearOutputTokens() *TaskUpdateOne { + tuo.mutation.ClearOutputTokens() + return tuo +} + +// SetCreatedAt sets the "created_at" field. +func (tuo *TaskUpdateOne) SetCreatedAt(t time.Time) *TaskUpdateOne { + tuo.mutation.SetCreatedAt(t) + return tuo +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (tuo *TaskUpdateOne) SetNillableCreatedAt(t *time.Time) *TaskUpdateOne { + if t != nil { + tuo.SetCreatedAt(*t) + } + return tuo +} + +// SetUpdatedAt sets the "updated_at" field. +func (tuo *TaskUpdateOne) SetUpdatedAt(t time.Time) *TaskUpdateOne { + tuo.mutation.SetUpdatedAt(t) + return tuo +} + +// AddTaskRecordIDs adds the "task_records" edge to the TaskRecord entity by IDs. +func (tuo *TaskUpdateOne) AddTaskRecordIDs(ids ...uuid.UUID) *TaskUpdateOne { + tuo.mutation.AddTaskRecordIDs(ids...) + return tuo +} + +// AddTaskRecords adds the "task_records" edges to the TaskRecord entity. +func (tuo *TaskUpdateOne) AddTaskRecords(t ...*TaskRecord) *TaskUpdateOne { + ids := make([]uuid.UUID, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return tuo.AddTaskRecordIDs(ids...) +} + +// SetUser sets the "user" edge to the User entity. +func (tuo *TaskUpdateOne) SetUser(u *User) *TaskUpdateOne { + return tuo.SetUserID(u.ID) +} + +// SetModel sets the "model" edge to the Model entity. +func (tuo *TaskUpdateOne) SetModel(m *Model) *TaskUpdateOne { + return tuo.SetModelID(m.ID) +} + +// Mutation returns the TaskMutation object of the builder. +func (tuo *TaskUpdateOne) Mutation() *TaskMutation { + return tuo.mutation +} + +// ClearTaskRecords clears all "task_records" edges to the TaskRecord entity. +func (tuo *TaskUpdateOne) ClearTaskRecords() *TaskUpdateOne { + tuo.mutation.ClearTaskRecords() + return tuo +} + +// RemoveTaskRecordIDs removes the "task_records" edge to TaskRecord entities by IDs. +func (tuo *TaskUpdateOne) RemoveTaskRecordIDs(ids ...uuid.UUID) *TaskUpdateOne { + tuo.mutation.RemoveTaskRecordIDs(ids...) + return tuo +} + +// RemoveTaskRecords removes "task_records" edges to TaskRecord entities. +func (tuo *TaskUpdateOne) RemoveTaskRecords(t ...*TaskRecord) *TaskUpdateOne { + ids := make([]uuid.UUID, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return tuo.RemoveTaskRecordIDs(ids...) +} + +// ClearUser clears the "user" edge to the User entity. +func (tuo *TaskUpdateOne) ClearUser() *TaskUpdateOne { + tuo.mutation.ClearUser() + return tuo +} + +// ClearModel clears the "model" edge to the Model entity. +func (tuo *TaskUpdateOne) ClearModel() *TaskUpdateOne { + tuo.mutation.ClearModel() + return tuo +} + +// Where appends a list predicates to the TaskUpdate builder. +func (tuo *TaskUpdateOne) Where(ps ...predicate.Task) *TaskUpdateOne { + tuo.mutation.Where(ps...) + return tuo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (tuo *TaskUpdateOne) Select(field string, fields ...string) *TaskUpdateOne { + tuo.fields = append([]string{field}, fields...) + return tuo +} + +// Save executes the query and returns the updated Task entity. +func (tuo *TaskUpdateOne) Save(ctx context.Context) (*Task, error) { + tuo.defaults() + return withHooks(ctx, tuo.sqlSave, tuo.mutation, tuo.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (tuo *TaskUpdateOne) SaveX(ctx context.Context) *Task { + node, err := tuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (tuo *TaskUpdateOne) Exec(ctx context.Context) error { + _, err := tuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (tuo *TaskUpdateOne) ExecX(ctx context.Context) { + if err := tuo.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (tuo *TaskUpdateOne) defaults() { + if _, ok := tuo.mutation.UpdatedAt(); !ok { + v := task.UpdateDefaultUpdatedAt() + tuo.mutation.SetUpdatedAt(v) + } +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (tuo *TaskUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *TaskUpdateOne { + tuo.modifiers = append(tuo.modifiers, modifiers...) + return tuo +} + +func (tuo *TaskUpdateOne) sqlSave(ctx context.Context) (_node *Task, err error) { + _spec := sqlgraph.NewUpdateSpec(task.Table, task.Columns, sqlgraph.NewFieldSpec(task.FieldID, field.TypeUUID)) + id, ok := tuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "Task.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := tuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, task.FieldID) + for _, f := range fields { + if !task.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != task.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := tuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := tuo.mutation.TaskID(); ok { + _spec.SetField(task.FieldTaskID, field.TypeString, value) + } + if value, ok := tuo.mutation.RequestID(); ok { + _spec.SetField(task.FieldRequestID, field.TypeString, value) + } + if tuo.mutation.RequestIDCleared() { + _spec.ClearField(task.FieldRequestID, field.TypeString) + } + if value, ok := tuo.mutation.ModelType(); ok { + _spec.SetField(task.FieldModelType, field.TypeString, value) + } + if value, ok := tuo.mutation.Prompt(); ok { + _spec.SetField(task.FieldPrompt, field.TypeString, value) + } + if tuo.mutation.PromptCleared() { + _spec.ClearField(task.FieldPrompt, field.TypeString) + } + if value, ok := tuo.mutation.IsAccept(); ok { + _spec.SetField(task.FieldIsAccept, field.TypeBool, value) + } + if value, ok := tuo.mutation.ProgramLanguage(); ok { + _spec.SetField(task.FieldProgramLanguage, field.TypeString, value) + } + if tuo.mutation.ProgramLanguageCleared() { + _spec.ClearField(task.FieldProgramLanguage, field.TypeString) + } + if value, ok := tuo.mutation.WorkMode(); ok { + _spec.SetField(task.FieldWorkMode, field.TypeString, value) + } + if tuo.mutation.WorkModeCleared() { + _spec.ClearField(task.FieldWorkMode, field.TypeString) + } + if value, ok := tuo.mutation.Completion(); ok { + _spec.SetField(task.FieldCompletion, field.TypeString, value) + } + if tuo.mutation.CompletionCleared() { + _spec.ClearField(task.FieldCompletion, field.TypeString) + } + if value, ok := tuo.mutation.CodeLines(); ok { + _spec.SetField(task.FieldCodeLines, field.TypeInt64, value) + } + if value, ok := tuo.mutation.AddedCodeLines(); ok { + _spec.AddField(task.FieldCodeLines, field.TypeInt64, value) + } + if tuo.mutation.CodeLinesCleared() { + _spec.ClearField(task.FieldCodeLines, field.TypeInt64) + } + if value, ok := tuo.mutation.InputTokens(); ok { + _spec.SetField(task.FieldInputTokens, field.TypeInt64, value) + } + if value, ok := tuo.mutation.AddedInputTokens(); ok { + _spec.AddField(task.FieldInputTokens, field.TypeInt64, value) + } + if tuo.mutation.InputTokensCleared() { + _spec.ClearField(task.FieldInputTokens, field.TypeInt64) + } + if value, ok := tuo.mutation.OutputTokens(); ok { + _spec.SetField(task.FieldOutputTokens, field.TypeInt64, value) + } + if value, ok := tuo.mutation.AddedOutputTokens(); ok { + _spec.AddField(task.FieldOutputTokens, field.TypeInt64, value) + } + if tuo.mutation.OutputTokensCleared() { + _spec.ClearField(task.FieldOutputTokens, field.TypeInt64) + } + if value, ok := tuo.mutation.CreatedAt(); ok { + _spec.SetField(task.FieldCreatedAt, field.TypeTime, value) + } + if value, ok := tuo.mutation.UpdatedAt(); ok { + _spec.SetField(task.FieldUpdatedAt, field.TypeTime, value) + } + if tuo.mutation.TaskRecordsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: task.TaskRecordsTable, + Columns: []string{task.TaskRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(taskrecord.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tuo.mutation.RemovedTaskRecordsIDs(); len(nodes) > 0 && !tuo.mutation.TaskRecordsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: task.TaskRecordsTable, + Columns: []string{task.TaskRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(taskrecord.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 := tuo.mutation.TaskRecordsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: task.TaskRecordsTable, + Columns: []string{task.TaskRecordsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(taskrecord.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if tuo.mutation.UserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: task.UserTable, + Columns: []string{task.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tuo.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: task.UserTable, + Columns: []string{task.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if tuo.mutation.ModelCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: task.ModelTable, + Columns: []string{task.ModelColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(model.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tuo.mutation.ModelIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: task.ModelTable, + Columns: []string{task.ModelColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(model.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(tuo.modifiers...) + _node = &Task{config: tuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, tuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{task.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + tuo.mutation.done = true + return _node, nil +} diff --git a/backend/db/taskrecord.go b/backend/db/taskrecord.go new file mode 100644 index 0000000..44f5271 --- /dev/null +++ b/backend/db/taskrecord.go @@ -0,0 +1,182 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "fmt" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/chaitin/MonkeyCode/backend/db/task" + "github.com/chaitin/MonkeyCode/backend/db/taskrecord" + "github.com/google/uuid" +) + +// TaskRecord is the model entity for the TaskRecord schema. +type TaskRecord struct { + config `json:"-"` + // ID of the ent. + ID uuid.UUID `json:"id,omitempty"` + // TaskID holds the value of the "task_id" field. + TaskID uuid.UUID `json:"task_id,omitempty"` + // Completion holds the value of the "completion" field. + Completion string `json:"completion,omitempty"` + // OutputTokens holds the value of the "output_tokens" field. + OutputTokens int64 `json:"output_tokens,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + // UpdatedAt holds the value of the "updated_at" field. + UpdatedAt time.Time `json:"updated_at,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the TaskRecordQuery when eager-loading is set. + Edges TaskRecordEdges `json:"edges"` + selectValues sql.SelectValues +} + +// TaskRecordEdges holds the relations/edges for other nodes in the graph. +type TaskRecordEdges struct { + // Task holds the value of the task edge. + Task *Task `json:"task,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// TaskOrErr returns the Task value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e TaskRecordEdges) TaskOrErr() (*Task, error) { + if e.Task != nil { + return e.Task, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: task.Label} + } + return nil, &NotLoadedError{edge: "task"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*TaskRecord) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case taskrecord.FieldOutputTokens: + values[i] = new(sql.NullInt64) + case taskrecord.FieldCompletion: + values[i] = new(sql.NullString) + case taskrecord.FieldCreatedAt, taskrecord.FieldUpdatedAt: + values[i] = new(sql.NullTime) + case taskrecord.FieldID, taskrecord.FieldTaskID: + 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 TaskRecord fields. +func (tr *TaskRecord) 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 taskrecord.FieldID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value != nil { + tr.ID = *value + } + case taskrecord.FieldTaskID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field task_id", values[i]) + } else if value != nil { + tr.TaskID = *value + } + case taskrecord.FieldCompletion: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field completion", values[i]) + } else if value.Valid { + tr.Completion = value.String + } + case taskrecord.FieldOutputTokens: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field output_tokens", values[i]) + } else if value.Valid { + tr.OutputTokens = value.Int64 + } + case taskrecord.FieldCreatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field created_at", values[i]) + } else if value.Valid { + tr.CreatedAt = value.Time + } + case taskrecord.FieldUpdatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field updated_at", values[i]) + } else if value.Valid { + tr.UpdatedAt = value.Time + } + default: + tr.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the TaskRecord. +// This includes values selected through modifiers, order, etc. +func (tr *TaskRecord) Value(name string) (ent.Value, error) { + return tr.selectValues.Get(name) +} + +// QueryTask queries the "task" edge of the TaskRecord entity. +func (tr *TaskRecord) QueryTask() *TaskQuery { + return NewTaskRecordClient(tr.config).QueryTask(tr) +} + +// Update returns a builder for updating this TaskRecord. +// Note that you need to call TaskRecord.Unwrap() before calling this method if this TaskRecord +// was returned from a transaction, and the transaction was committed or rolled back. +func (tr *TaskRecord) Update() *TaskRecordUpdateOne { + return NewTaskRecordClient(tr.config).UpdateOne(tr) +} + +// Unwrap unwraps the TaskRecord 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 (tr *TaskRecord) Unwrap() *TaskRecord { + _tx, ok := tr.config.driver.(*txDriver) + if !ok { + panic("db: TaskRecord is not a transactional entity") + } + tr.config.driver = _tx.drv + return tr +} + +// String implements the fmt.Stringer. +func (tr *TaskRecord) String() string { + var builder strings.Builder + builder.WriteString("TaskRecord(") + builder.WriteString(fmt.Sprintf("id=%v, ", tr.ID)) + builder.WriteString("task_id=") + builder.WriteString(fmt.Sprintf("%v", tr.TaskID)) + builder.WriteString(", ") + builder.WriteString("completion=") + builder.WriteString(tr.Completion) + builder.WriteString(", ") + builder.WriteString("output_tokens=") + builder.WriteString(fmt.Sprintf("%v", tr.OutputTokens)) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(tr.CreatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("updated_at=") + builder.WriteString(tr.UpdatedAt.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// TaskRecords is a parsable slice of TaskRecord. +type TaskRecords []*TaskRecord diff --git a/backend/db/taskrecord/taskrecord.go b/backend/db/taskrecord/taskrecord.go new file mode 100644 index 0000000..bfb5ce2 --- /dev/null +++ b/backend/db/taskrecord/taskrecord.go @@ -0,0 +1,114 @@ +// Code generated by ent, DO NOT EDIT. + +package taskrecord + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the taskrecord type in the database. + Label = "task_record" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldTaskID holds the string denoting the task_id field in the database. + FieldTaskID = "task_id" + // FieldCompletion holds the string denoting the completion field in the database. + FieldCompletion = "completion" + // FieldOutputTokens holds the string denoting the output_tokens field in the database. + FieldOutputTokens = "output_tokens" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // FieldUpdatedAt holds the string denoting the updated_at field in the database. + FieldUpdatedAt = "updated_at" + // EdgeTask holds the string denoting the task edge name in mutations. + EdgeTask = "task" + // Table holds the table name of the taskrecord in the database. + Table = "task_records" + // TaskTable is the table that holds the task relation/edge. + TaskTable = "task_records" + // TaskInverseTable is the table name for the Task entity. + // It exists in this package in order to avoid circular dependency with the "task" package. + TaskInverseTable = "tasks" + // TaskColumn is the table column denoting the task relation/edge. + TaskColumn = "task_id" +) + +// Columns holds all SQL columns for taskrecord fields. +var Columns = []string{ + FieldID, + FieldTaskID, + FieldCompletion, + FieldOutputTokens, + FieldCreatedAt, + FieldUpdatedAt, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time + // DefaultUpdatedAt holds the default value on creation for the "updated_at" field. + DefaultUpdatedAt func() time.Time + // UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field. + UpdateDefaultUpdatedAt func() time.Time +) + +// OrderOption defines the ordering options for the TaskRecord 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() +} + +// ByTaskID orders the results by the task_id field. +func ByTaskID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTaskID, opts...).ToFunc() +} + +// ByCompletion orders the results by the completion field. +func ByCompletion(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCompletion, opts...).ToFunc() +} + +// ByOutputTokens orders the results by the output_tokens field. +func ByOutputTokens(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldOutputTokens, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// ByUpdatedAt orders the results by the updated_at field. +func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc() +} + +// ByTaskField orders the results by task field. +func ByTaskField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newTaskStep(), sql.OrderByField(field, opts...)) + } +} +func newTaskStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(TaskInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, TaskTable, TaskColumn), + ) +} diff --git a/backend/db/taskrecord/where.go b/backend/db/taskrecord/where.go new file mode 100644 index 0000000..a53a3e2 --- /dev/null +++ b/backend/db/taskrecord/where.go @@ -0,0 +1,335 @@ +// Code generated by ent, DO NOT EDIT. + +package taskrecord + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/google/uuid" +) + +// ID filters vertices based on their ID field. +func ID(id uuid.UUID) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id uuid.UUID) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id uuid.UUID) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...uuid.UUID) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...uuid.UUID) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id uuid.UUID) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id uuid.UUID) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id uuid.UUID) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id uuid.UUID) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldLTE(FieldID, id)) +} + +// TaskID applies equality check predicate on the "task_id" field. It's identical to TaskIDEQ. +func TaskID(v uuid.UUID) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldEQ(FieldTaskID, v)) +} + +// Completion applies equality check predicate on the "completion" field. It's identical to CompletionEQ. +func Completion(v string) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldEQ(FieldCompletion, v)) +} + +// OutputTokens applies equality check predicate on the "output_tokens" field. It's identical to OutputTokensEQ. +func OutputTokens(v int64) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldEQ(FieldOutputTokens, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldEQ(FieldCreatedAt, v)) +} + +// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ. +func UpdatedAt(v time.Time) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// TaskIDEQ applies the EQ predicate on the "task_id" field. +func TaskIDEQ(v uuid.UUID) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldEQ(FieldTaskID, v)) +} + +// TaskIDNEQ applies the NEQ predicate on the "task_id" field. +func TaskIDNEQ(v uuid.UUID) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldNEQ(FieldTaskID, v)) +} + +// TaskIDIn applies the In predicate on the "task_id" field. +func TaskIDIn(vs ...uuid.UUID) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldIn(FieldTaskID, vs...)) +} + +// TaskIDNotIn applies the NotIn predicate on the "task_id" field. +func TaskIDNotIn(vs ...uuid.UUID) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldNotIn(FieldTaskID, vs...)) +} + +// TaskIDIsNil applies the IsNil predicate on the "task_id" field. +func TaskIDIsNil() predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldIsNull(FieldTaskID)) +} + +// TaskIDNotNil applies the NotNil predicate on the "task_id" field. +func TaskIDNotNil() predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldNotNull(FieldTaskID)) +} + +// CompletionEQ applies the EQ predicate on the "completion" field. +func CompletionEQ(v string) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldEQ(FieldCompletion, v)) +} + +// CompletionNEQ applies the NEQ predicate on the "completion" field. +func CompletionNEQ(v string) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldNEQ(FieldCompletion, v)) +} + +// CompletionIn applies the In predicate on the "completion" field. +func CompletionIn(vs ...string) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldIn(FieldCompletion, vs...)) +} + +// CompletionNotIn applies the NotIn predicate on the "completion" field. +func CompletionNotIn(vs ...string) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldNotIn(FieldCompletion, vs...)) +} + +// CompletionGT applies the GT predicate on the "completion" field. +func CompletionGT(v string) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldGT(FieldCompletion, v)) +} + +// CompletionGTE applies the GTE predicate on the "completion" field. +func CompletionGTE(v string) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldGTE(FieldCompletion, v)) +} + +// CompletionLT applies the LT predicate on the "completion" field. +func CompletionLT(v string) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldLT(FieldCompletion, v)) +} + +// CompletionLTE applies the LTE predicate on the "completion" field. +func CompletionLTE(v string) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldLTE(FieldCompletion, v)) +} + +// CompletionContains applies the Contains predicate on the "completion" field. +func CompletionContains(v string) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldContains(FieldCompletion, v)) +} + +// CompletionHasPrefix applies the HasPrefix predicate on the "completion" field. +func CompletionHasPrefix(v string) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldHasPrefix(FieldCompletion, v)) +} + +// CompletionHasSuffix applies the HasSuffix predicate on the "completion" field. +func CompletionHasSuffix(v string) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldHasSuffix(FieldCompletion, v)) +} + +// CompletionEqualFold applies the EqualFold predicate on the "completion" field. +func CompletionEqualFold(v string) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldEqualFold(FieldCompletion, v)) +} + +// CompletionContainsFold applies the ContainsFold predicate on the "completion" field. +func CompletionContainsFold(v string) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldContainsFold(FieldCompletion, v)) +} + +// OutputTokensEQ applies the EQ predicate on the "output_tokens" field. +func OutputTokensEQ(v int64) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldEQ(FieldOutputTokens, v)) +} + +// OutputTokensNEQ applies the NEQ predicate on the "output_tokens" field. +func OutputTokensNEQ(v int64) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldNEQ(FieldOutputTokens, v)) +} + +// OutputTokensIn applies the In predicate on the "output_tokens" field. +func OutputTokensIn(vs ...int64) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldIn(FieldOutputTokens, vs...)) +} + +// OutputTokensNotIn applies the NotIn predicate on the "output_tokens" field. +func OutputTokensNotIn(vs ...int64) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldNotIn(FieldOutputTokens, vs...)) +} + +// OutputTokensGT applies the GT predicate on the "output_tokens" field. +func OutputTokensGT(v int64) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldGT(FieldOutputTokens, v)) +} + +// OutputTokensGTE applies the GTE predicate on the "output_tokens" field. +func OutputTokensGTE(v int64) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldGTE(FieldOutputTokens, v)) +} + +// OutputTokensLT applies the LT predicate on the "output_tokens" field. +func OutputTokensLT(v int64) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldLT(FieldOutputTokens, v)) +} + +// OutputTokensLTE applies the LTE predicate on the "output_tokens" field. +func OutputTokensLTE(v int64) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldLTE(FieldOutputTokens, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.TaskRecord { + return predicate.TaskRecord(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// HasTask applies the HasEdge predicate on the "task" edge. +func HasTask() predicate.TaskRecord { + return predicate.TaskRecord(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, TaskTable, TaskColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasTaskWith applies the HasEdge predicate on the "task" edge with a given conditions (other predicates). +func HasTaskWith(preds ...predicate.Task) predicate.TaskRecord { + return predicate.TaskRecord(func(s *sql.Selector) { + step := newTaskStep() + 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.TaskRecord) predicate.TaskRecord { + return predicate.TaskRecord(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.TaskRecord) predicate.TaskRecord { + return predicate.TaskRecord(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.TaskRecord) predicate.TaskRecord { + return predicate.TaskRecord(sql.NotPredicates(p)) +} diff --git a/backend/db/taskrecord_create.go b/backend/db/taskrecord_create.go new file mode 100644 index 0000000..078eab5 --- /dev/null +++ b/backend/db/taskrecord_create.go @@ -0,0 +1,797 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/task" + "github.com/chaitin/MonkeyCode/backend/db/taskrecord" + "github.com/google/uuid" +) + +// TaskRecordCreate is the builder for creating a TaskRecord entity. +type TaskRecordCreate struct { + config + mutation *TaskRecordMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetTaskID sets the "task_id" field. +func (trc *TaskRecordCreate) SetTaskID(u uuid.UUID) *TaskRecordCreate { + trc.mutation.SetTaskID(u) + return trc +} + +// SetNillableTaskID sets the "task_id" field if the given value is not nil. +func (trc *TaskRecordCreate) SetNillableTaskID(u *uuid.UUID) *TaskRecordCreate { + if u != nil { + trc.SetTaskID(*u) + } + return trc +} + +// SetCompletion sets the "completion" field. +func (trc *TaskRecordCreate) SetCompletion(s string) *TaskRecordCreate { + trc.mutation.SetCompletion(s) + return trc +} + +// SetOutputTokens sets the "output_tokens" field. +func (trc *TaskRecordCreate) SetOutputTokens(i int64) *TaskRecordCreate { + trc.mutation.SetOutputTokens(i) + return trc +} + +// SetCreatedAt sets the "created_at" field. +func (trc *TaskRecordCreate) SetCreatedAt(t time.Time) *TaskRecordCreate { + trc.mutation.SetCreatedAt(t) + return trc +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (trc *TaskRecordCreate) SetNillableCreatedAt(t *time.Time) *TaskRecordCreate { + if t != nil { + trc.SetCreatedAt(*t) + } + return trc +} + +// SetUpdatedAt sets the "updated_at" field. +func (trc *TaskRecordCreate) SetUpdatedAt(t time.Time) *TaskRecordCreate { + trc.mutation.SetUpdatedAt(t) + return trc +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (trc *TaskRecordCreate) SetNillableUpdatedAt(t *time.Time) *TaskRecordCreate { + if t != nil { + trc.SetUpdatedAt(*t) + } + return trc +} + +// SetID sets the "id" field. +func (trc *TaskRecordCreate) SetID(u uuid.UUID) *TaskRecordCreate { + trc.mutation.SetID(u) + return trc +} + +// SetTask sets the "task" edge to the Task entity. +func (trc *TaskRecordCreate) SetTask(t *Task) *TaskRecordCreate { + return trc.SetTaskID(t.ID) +} + +// Mutation returns the TaskRecordMutation object of the builder. +func (trc *TaskRecordCreate) Mutation() *TaskRecordMutation { + return trc.mutation +} + +// Save creates the TaskRecord in the database. +func (trc *TaskRecordCreate) Save(ctx context.Context) (*TaskRecord, error) { + trc.defaults() + return withHooks(ctx, trc.sqlSave, trc.mutation, trc.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (trc *TaskRecordCreate) SaveX(ctx context.Context) *TaskRecord { + v, err := trc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (trc *TaskRecordCreate) Exec(ctx context.Context) error { + _, err := trc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (trc *TaskRecordCreate) ExecX(ctx context.Context) { + if err := trc.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (trc *TaskRecordCreate) defaults() { + if _, ok := trc.mutation.CreatedAt(); !ok { + v := taskrecord.DefaultCreatedAt() + trc.mutation.SetCreatedAt(v) + } + if _, ok := trc.mutation.UpdatedAt(); !ok { + v := taskrecord.DefaultUpdatedAt() + trc.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (trc *TaskRecordCreate) check() error { + if _, ok := trc.mutation.Completion(); !ok { + return &ValidationError{Name: "completion", err: errors.New(`db: missing required field "TaskRecord.completion"`)} + } + if _, ok := trc.mutation.OutputTokens(); !ok { + return &ValidationError{Name: "output_tokens", err: errors.New(`db: missing required field "TaskRecord.output_tokens"`)} + } + if _, ok := trc.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "TaskRecord.created_at"`)} + } + if _, ok := trc.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "TaskRecord.updated_at"`)} + } + return nil +} + +func (trc *TaskRecordCreate) sqlSave(ctx context.Context) (*TaskRecord, error) { + if err := trc.check(); err != nil { + return nil, err + } + _node, _spec := trc.createSpec() + if err := sqlgraph.CreateNode(ctx, trc.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 + } + } + trc.mutation.id = &_node.ID + trc.mutation.done = true + return _node, nil +} + +func (trc *TaskRecordCreate) createSpec() (*TaskRecord, *sqlgraph.CreateSpec) { + var ( + _node = &TaskRecord{config: trc.config} + _spec = sqlgraph.NewCreateSpec(taskrecord.Table, sqlgraph.NewFieldSpec(taskrecord.FieldID, field.TypeUUID)) + ) + _spec.OnConflict = trc.conflict + if id, ok := trc.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = &id + } + if value, ok := trc.mutation.Completion(); ok { + _spec.SetField(taskrecord.FieldCompletion, field.TypeString, value) + _node.Completion = value + } + if value, ok := trc.mutation.OutputTokens(); ok { + _spec.SetField(taskrecord.FieldOutputTokens, field.TypeInt64, value) + _node.OutputTokens = value + } + if value, ok := trc.mutation.CreatedAt(); ok { + _spec.SetField(taskrecord.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := trc.mutation.UpdatedAt(); ok { + _spec.SetField(taskrecord.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if nodes := trc.mutation.TaskIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: taskrecord.TaskTable, + Columns: []string{taskrecord.TaskColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(task.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.TaskID = 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.TaskRecord.Create(). +// SetTaskID(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.TaskRecordUpsert) { +// SetTaskID(v+v). +// }). +// Exec(ctx) +func (trc *TaskRecordCreate) OnConflict(opts ...sql.ConflictOption) *TaskRecordUpsertOne { + trc.conflict = opts + return &TaskRecordUpsertOne{ + create: trc, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.TaskRecord.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (trc *TaskRecordCreate) OnConflictColumns(columns ...string) *TaskRecordUpsertOne { + trc.conflict = append(trc.conflict, sql.ConflictColumns(columns...)) + return &TaskRecordUpsertOne{ + create: trc, + } +} + +type ( + // TaskRecordUpsertOne is the builder for "upsert"-ing + // one TaskRecord node. + TaskRecordUpsertOne struct { + create *TaskRecordCreate + } + + // TaskRecordUpsert is the "OnConflict" setter. + TaskRecordUpsert struct { + *sql.UpdateSet + } +) + +// SetTaskID sets the "task_id" field. +func (u *TaskRecordUpsert) SetTaskID(v uuid.UUID) *TaskRecordUpsert { + u.Set(taskrecord.FieldTaskID, v) + return u +} + +// UpdateTaskID sets the "task_id" field to the value that was provided on create. +func (u *TaskRecordUpsert) UpdateTaskID() *TaskRecordUpsert { + u.SetExcluded(taskrecord.FieldTaskID) + return u +} + +// ClearTaskID clears the value of the "task_id" field. +func (u *TaskRecordUpsert) ClearTaskID() *TaskRecordUpsert { + u.SetNull(taskrecord.FieldTaskID) + return u +} + +// SetCompletion sets the "completion" field. +func (u *TaskRecordUpsert) SetCompletion(v string) *TaskRecordUpsert { + u.Set(taskrecord.FieldCompletion, v) + return u +} + +// UpdateCompletion sets the "completion" field to the value that was provided on create. +func (u *TaskRecordUpsert) UpdateCompletion() *TaskRecordUpsert { + u.SetExcluded(taskrecord.FieldCompletion) + return u +} + +// SetOutputTokens sets the "output_tokens" field. +func (u *TaskRecordUpsert) SetOutputTokens(v int64) *TaskRecordUpsert { + u.Set(taskrecord.FieldOutputTokens, v) + return u +} + +// UpdateOutputTokens sets the "output_tokens" field to the value that was provided on create. +func (u *TaskRecordUpsert) UpdateOutputTokens() *TaskRecordUpsert { + u.SetExcluded(taskrecord.FieldOutputTokens) + return u +} + +// AddOutputTokens adds v to the "output_tokens" field. +func (u *TaskRecordUpsert) AddOutputTokens(v int64) *TaskRecordUpsert { + u.Add(taskrecord.FieldOutputTokens, v) + return u +} + +// SetCreatedAt sets the "created_at" field. +func (u *TaskRecordUpsert) SetCreatedAt(v time.Time) *TaskRecordUpsert { + u.Set(taskrecord.FieldCreatedAt, v) + return u +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *TaskRecordUpsert) UpdateCreatedAt() *TaskRecordUpsert { + u.SetExcluded(taskrecord.FieldCreatedAt) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *TaskRecordUpsert) SetUpdatedAt(v time.Time) *TaskRecordUpsert { + u.Set(taskrecord.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *TaskRecordUpsert) UpdateUpdatedAt() *TaskRecordUpsert { + u.SetExcluded(taskrecord.FieldUpdatedAt) + return u +} + +// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field. +// Using this option is equivalent to using: +// +// client.TaskRecord.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(taskrecord.FieldID) +// }), +// ). +// Exec(ctx) +func (u *TaskRecordUpsertOne) UpdateNewValues() *TaskRecordUpsertOne { + 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(taskrecord.FieldID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.TaskRecord.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *TaskRecordUpsertOne) Ignore() *TaskRecordUpsertOne { + 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 *TaskRecordUpsertOne) DoNothing() *TaskRecordUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the TaskRecordCreate.OnConflict +// documentation for more info. +func (u *TaskRecordUpsertOne) Update(set func(*TaskRecordUpsert)) *TaskRecordUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&TaskRecordUpsert{UpdateSet: update}) + })) + return u +} + +// SetTaskID sets the "task_id" field. +func (u *TaskRecordUpsertOne) SetTaskID(v uuid.UUID) *TaskRecordUpsertOne { + return u.Update(func(s *TaskRecordUpsert) { + s.SetTaskID(v) + }) +} + +// UpdateTaskID sets the "task_id" field to the value that was provided on create. +func (u *TaskRecordUpsertOne) UpdateTaskID() *TaskRecordUpsertOne { + return u.Update(func(s *TaskRecordUpsert) { + s.UpdateTaskID() + }) +} + +// ClearTaskID clears the value of the "task_id" field. +func (u *TaskRecordUpsertOne) ClearTaskID() *TaskRecordUpsertOne { + return u.Update(func(s *TaskRecordUpsert) { + s.ClearTaskID() + }) +} + +// SetCompletion sets the "completion" field. +func (u *TaskRecordUpsertOne) SetCompletion(v string) *TaskRecordUpsertOne { + return u.Update(func(s *TaskRecordUpsert) { + s.SetCompletion(v) + }) +} + +// UpdateCompletion sets the "completion" field to the value that was provided on create. +func (u *TaskRecordUpsertOne) UpdateCompletion() *TaskRecordUpsertOne { + return u.Update(func(s *TaskRecordUpsert) { + s.UpdateCompletion() + }) +} + +// SetOutputTokens sets the "output_tokens" field. +func (u *TaskRecordUpsertOne) SetOutputTokens(v int64) *TaskRecordUpsertOne { + return u.Update(func(s *TaskRecordUpsert) { + s.SetOutputTokens(v) + }) +} + +// AddOutputTokens adds v to the "output_tokens" field. +func (u *TaskRecordUpsertOne) AddOutputTokens(v int64) *TaskRecordUpsertOne { + return u.Update(func(s *TaskRecordUpsert) { + s.AddOutputTokens(v) + }) +} + +// UpdateOutputTokens sets the "output_tokens" field to the value that was provided on create. +func (u *TaskRecordUpsertOne) UpdateOutputTokens() *TaskRecordUpsertOne { + return u.Update(func(s *TaskRecordUpsert) { + s.UpdateOutputTokens() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *TaskRecordUpsertOne) SetCreatedAt(v time.Time) *TaskRecordUpsertOne { + return u.Update(func(s *TaskRecordUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *TaskRecordUpsertOne) UpdateCreatedAt() *TaskRecordUpsertOne { + return u.Update(func(s *TaskRecordUpsert) { + s.UpdateCreatedAt() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *TaskRecordUpsertOne) SetUpdatedAt(v time.Time) *TaskRecordUpsertOne { + return u.Update(func(s *TaskRecordUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *TaskRecordUpsertOne) UpdateUpdatedAt() *TaskRecordUpsertOne { + return u.Update(func(s *TaskRecordUpsert) { + s.UpdateUpdatedAt() + }) +} + +// Exec executes the query. +func (u *TaskRecordUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for TaskRecordCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *TaskRecordUpsertOne) 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 *TaskRecordUpsertOne) 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: TaskRecordUpsertOne.ID is not supported by MySQL driver. Use TaskRecordUpsertOne.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 *TaskRecordUpsertOne) IDX(ctx context.Context) uuid.UUID { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// TaskRecordCreateBulk is the builder for creating many TaskRecord entities in bulk. +type TaskRecordCreateBulk struct { + config + err error + builders []*TaskRecordCreate + conflict []sql.ConflictOption +} + +// Save creates the TaskRecord entities in the database. +func (trcb *TaskRecordCreateBulk) Save(ctx context.Context) ([]*TaskRecord, error) { + if trcb.err != nil { + return nil, trcb.err + } + specs := make([]*sqlgraph.CreateSpec, len(trcb.builders)) + nodes := make([]*TaskRecord, len(trcb.builders)) + mutators := make([]Mutator, len(trcb.builders)) + for i := range trcb.builders { + func(i int, root context.Context) { + builder := trcb.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*TaskRecordMutation) + 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, trcb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = trcb.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, trcb.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, trcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (trcb *TaskRecordCreateBulk) SaveX(ctx context.Context) []*TaskRecord { + v, err := trcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (trcb *TaskRecordCreateBulk) Exec(ctx context.Context) error { + _, err := trcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (trcb *TaskRecordCreateBulk) ExecX(ctx context.Context) { + if err := trcb.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.TaskRecord.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.TaskRecordUpsert) { +// SetTaskID(v+v). +// }). +// Exec(ctx) +func (trcb *TaskRecordCreateBulk) OnConflict(opts ...sql.ConflictOption) *TaskRecordUpsertBulk { + trcb.conflict = opts + return &TaskRecordUpsertBulk{ + create: trcb, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.TaskRecord.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (trcb *TaskRecordCreateBulk) OnConflictColumns(columns ...string) *TaskRecordUpsertBulk { + trcb.conflict = append(trcb.conflict, sql.ConflictColumns(columns...)) + return &TaskRecordUpsertBulk{ + create: trcb, + } +} + +// TaskRecordUpsertBulk is the builder for "upsert"-ing +// a bulk of TaskRecord nodes. +type TaskRecordUpsertBulk struct { + create *TaskRecordCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.TaskRecord.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(taskrecord.FieldID) +// }), +// ). +// Exec(ctx) +func (u *TaskRecordUpsertBulk) UpdateNewValues() *TaskRecordUpsertBulk { + 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(taskrecord.FieldID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.TaskRecord.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *TaskRecordUpsertBulk) Ignore() *TaskRecordUpsertBulk { + 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 *TaskRecordUpsertBulk) DoNothing() *TaskRecordUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the TaskRecordCreateBulk.OnConflict +// documentation for more info. +func (u *TaskRecordUpsertBulk) Update(set func(*TaskRecordUpsert)) *TaskRecordUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&TaskRecordUpsert{UpdateSet: update}) + })) + return u +} + +// SetTaskID sets the "task_id" field. +func (u *TaskRecordUpsertBulk) SetTaskID(v uuid.UUID) *TaskRecordUpsertBulk { + return u.Update(func(s *TaskRecordUpsert) { + s.SetTaskID(v) + }) +} + +// UpdateTaskID sets the "task_id" field to the value that was provided on create. +func (u *TaskRecordUpsertBulk) UpdateTaskID() *TaskRecordUpsertBulk { + return u.Update(func(s *TaskRecordUpsert) { + s.UpdateTaskID() + }) +} + +// ClearTaskID clears the value of the "task_id" field. +func (u *TaskRecordUpsertBulk) ClearTaskID() *TaskRecordUpsertBulk { + return u.Update(func(s *TaskRecordUpsert) { + s.ClearTaskID() + }) +} + +// SetCompletion sets the "completion" field. +func (u *TaskRecordUpsertBulk) SetCompletion(v string) *TaskRecordUpsertBulk { + return u.Update(func(s *TaskRecordUpsert) { + s.SetCompletion(v) + }) +} + +// UpdateCompletion sets the "completion" field to the value that was provided on create. +func (u *TaskRecordUpsertBulk) UpdateCompletion() *TaskRecordUpsertBulk { + return u.Update(func(s *TaskRecordUpsert) { + s.UpdateCompletion() + }) +} + +// SetOutputTokens sets the "output_tokens" field. +func (u *TaskRecordUpsertBulk) SetOutputTokens(v int64) *TaskRecordUpsertBulk { + return u.Update(func(s *TaskRecordUpsert) { + s.SetOutputTokens(v) + }) +} + +// AddOutputTokens adds v to the "output_tokens" field. +func (u *TaskRecordUpsertBulk) AddOutputTokens(v int64) *TaskRecordUpsertBulk { + return u.Update(func(s *TaskRecordUpsert) { + s.AddOutputTokens(v) + }) +} + +// UpdateOutputTokens sets the "output_tokens" field to the value that was provided on create. +func (u *TaskRecordUpsertBulk) UpdateOutputTokens() *TaskRecordUpsertBulk { + return u.Update(func(s *TaskRecordUpsert) { + s.UpdateOutputTokens() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *TaskRecordUpsertBulk) SetCreatedAt(v time.Time) *TaskRecordUpsertBulk { + return u.Update(func(s *TaskRecordUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *TaskRecordUpsertBulk) UpdateCreatedAt() *TaskRecordUpsertBulk { + return u.Update(func(s *TaskRecordUpsert) { + s.UpdateCreatedAt() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *TaskRecordUpsertBulk) SetUpdatedAt(v time.Time) *TaskRecordUpsertBulk { + return u.Update(func(s *TaskRecordUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *TaskRecordUpsertBulk) UpdateUpdatedAt() *TaskRecordUpsertBulk { + return u.Update(func(s *TaskRecordUpsert) { + s.UpdateUpdatedAt() + }) +} + +// Exec executes the query. +func (u *TaskRecordUpsertBulk) 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 TaskRecordCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for TaskRecordCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *TaskRecordUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/taskrecord_delete.go b/backend/db/taskrecord_delete.go new file mode 100644 index 0000000..8721b95 --- /dev/null +++ b/backend/db/taskrecord_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/taskrecord" +) + +// TaskRecordDelete is the builder for deleting a TaskRecord entity. +type TaskRecordDelete struct { + config + hooks []Hook + mutation *TaskRecordMutation +} + +// Where appends a list predicates to the TaskRecordDelete builder. +func (trd *TaskRecordDelete) Where(ps ...predicate.TaskRecord) *TaskRecordDelete { + trd.mutation.Where(ps...) + return trd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (trd *TaskRecordDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, trd.sqlExec, trd.mutation, trd.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (trd *TaskRecordDelete) ExecX(ctx context.Context) int { + n, err := trd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (trd *TaskRecordDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(taskrecord.Table, sqlgraph.NewFieldSpec(taskrecord.FieldID, field.TypeUUID)) + if ps := trd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, trd.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + trd.mutation.done = true + return affected, err +} + +// TaskRecordDeleteOne is the builder for deleting a single TaskRecord entity. +type TaskRecordDeleteOne struct { + trd *TaskRecordDelete +} + +// Where appends a list predicates to the TaskRecordDelete builder. +func (trdo *TaskRecordDeleteOne) Where(ps ...predicate.TaskRecord) *TaskRecordDeleteOne { + trdo.trd.mutation.Where(ps...) + return trdo +} + +// Exec executes the deletion query. +func (trdo *TaskRecordDeleteOne) Exec(ctx context.Context) error { + n, err := trdo.trd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{taskrecord.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (trdo *TaskRecordDeleteOne) ExecX(ctx context.Context) { + if err := trdo.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/taskrecord_query.go b/backend/db/taskrecord_query.go new file mode 100644 index 0000000..8570373 --- /dev/null +++ b/backend/db/taskrecord_query.go @@ -0,0 +1,657 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/task" + "github.com/chaitin/MonkeyCode/backend/db/taskrecord" + "github.com/google/uuid" +) + +// TaskRecordQuery is the builder for querying TaskRecord entities. +type TaskRecordQuery struct { + config + ctx *QueryContext + order []taskrecord.OrderOption + inters []Interceptor + predicates []predicate.TaskRecord + withTask *TaskQuery + 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 TaskRecordQuery builder. +func (trq *TaskRecordQuery) Where(ps ...predicate.TaskRecord) *TaskRecordQuery { + trq.predicates = append(trq.predicates, ps...) + return trq +} + +// Limit the number of records to be returned by this query. +func (trq *TaskRecordQuery) Limit(limit int) *TaskRecordQuery { + trq.ctx.Limit = &limit + return trq +} + +// Offset to start from. +func (trq *TaskRecordQuery) Offset(offset int) *TaskRecordQuery { + trq.ctx.Offset = &offset + return trq +} + +// 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 (trq *TaskRecordQuery) Unique(unique bool) *TaskRecordQuery { + trq.ctx.Unique = &unique + return trq +} + +// Order specifies how the records should be ordered. +func (trq *TaskRecordQuery) Order(o ...taskrecord.OrderOption) *TaskRecordQuery { + trq.order = append(trq.order, o...) + return trq +} + +// QueryTask chains the current query on the "task" edge. +func (trq *TaskRecordQuery) QueryTask() *TaskQuery { + query := (&TaskClient{config: trq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := trq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := trq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(taskrecord.Table, taskrecord.FieldID, selector), + sqlgraph.To(task.Table, task.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, taskrecord.TaskTable, taskrecord.TaskColumn), + ) + fromU = sqlgraph.SetNeighbors(trq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first TaskRecord entity from the query. +// Returns a *NotFoundError when no TaskRecord was found. +func (trq *TaskRecordQuery) First(ctx context.Context) (*TaskRecord, error) { + nodes, err := trq.Limit(1).All(setContextOp(ctx, trq.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{taskrecord.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (trq *TaskRecordQuery) FirstX(ctx context.Context) *TaskRecord { + node, err := trq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first TaskRecord ID from the query. +// Returns a *NotFoundError when no TaskRecord ID was found. +func (trq *TaskRecordQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = trq.Limit(1).IDs(setContextOp(ctx, trq.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{taskrecord.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (trq *TaskRecordQuery) FirstIDX(ctx context.Context) uuid.UUID { + id, err := trq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single TaskRecord entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one TaskRecord entity is found. +// Returns a *NotFoundError when no TaskRecord entities are found. +func (trq *TaskRecordQuery) Only(ctx context.Context) (*TaskRecord, error) { + nodes, err := trq.Limit(2).All(setContextOp(ctx, trq.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{taskrecord.Label} + default: + return nil, &NotSingularError{taskrecord.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (trq *TaskRecordQuery) OnlyX(ctx context.Context) *TaskRecord { + node, err := trq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only TaskRecord ID in the query. +// Returns a *NotSingularError when more than one TaskRecord ID is found. +// Returns a *NotFoundError when no entities are found. +func (trq *TaskRecordQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = trq.Limit(2).IDs(setContextOp(ctx, trq.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{taskrecord.Label} + default: + err = &NotSingularError{taskrecord.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (trq *TaskRecordQuery) OnlyIDX(ctx context.Context) uuid.UUID { + id, err := trq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of TaskRecords. +func (trq *TaskRecordQuery) All(ctx context.Context) ([]*TaskRecord, error) { + ctx = setContextOp(ctx, trq.ctx, ent.OpQueryAll) + if err := trq.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*TaskRecord, *TaskRecordQuery]() + return withInterceptors[[]*TaskRecord](ctx, trq, qr, trq.inters) +} + +// AllX is like All, but panics if an error occurs. +func (trq *TaskRecordQuery) AllX(ctx context.Context) []*TaskRecord { + nodes, err := trq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of TaskRecord IDs. +func (trq *TaskRecordQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) { + if trq.ctx.Unique == nil && trq.path != nil { + trq.Unique(true) + } + ctx = setContextOp(ctx, trq.ctx, ent.OpQueryIDs) + if err = trq.Select(taskrecord.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (trq *TaskRecordQuery) IDsX(ctx context.Context) []uuid.UUID { + ids, err := trq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (trq *TaskRecordQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, trq.ctx, ent.OpQueryCount) + if err := trq.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, trq, querierCount[*TaskRecordQuery](), trq.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (trq *TaskRecordQuery) CountX(ctx context.Context) int { + count, err := trq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (trq *TaskRecordQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, trq.ctx, ent.OpQueryExist) + switch _, err := trq.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 (trq *TaskRecordQuery) ExistX(ctx context.Context) bool { + exist, err := trq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the TaskRecordQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (trq *TaskRecordQuery) Clone() *TaskRecordQuery { + if trq == nil { + return nil + } + return &TaskRecordQuery{ + config: trq.config, + ctx: trq.ctx.Clone(), + order: append([]taskrecord.OrderOption{}, trq.order...), + inters: append([]Interceptor{}, trq.inters...), + predicates: append([]predicate.TaskRecord{}, trq.predicates...), + withTask: trq.withTask.Clone(), + // clone intermediate query. + sql: trq.sql.Clone(), + path: trq.path, + modifiers: append([]func(*sql.Selector){}, trq.modifiers...), + } +} + +// WithTask tells the query-builder to eager-load the nodes that are connected to +// the "task" edge. The optional arguments are used to configure the query builder of the edge. +func (trq *TaskRecordQuery) WithTask(opts ...func(*TaskQuery)) *TaskRecordQuery { + query := (&TaskClient{config: trq.config}).Query() + for _, opt := range opts { + opt(query) + } + trq.withTask = query + return trq +} + +// 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 { +// TaskID uuid.UUID `json:"task_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.TaskRecord.Query(). +// GroupBy(taskrecord.FieldTaskID). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (trq *TaskRecordQuery) GroupBy(field string, fields ...string) *TaskRecordGroupBy { + trq.ctx.Fields = append([]string{field}, fields...) + grbuild := &TaskRecordGroupBy{build: trq} + grbuild.flds = &trq.ctx.Fields + grbuild.label = taskrecord.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 { +// TaskID uuid.UUID `json:"task_id,omitempty"` +// } +// +// client.TaskRecord.Query(). +// Select(taskrecord.FieldTaskID). +// Scan(ctx, &v) +func (trq *TaskRecordQuery) Select(fields ...string) *TaskRecordSelect { + trq.ctx.Fields = append(trq.ctx.Fields, fields...) + sbuild := &TaskRecordSelect{TaskRecordQuery: trq} + sbuild.label = taskrecord.Label + sbuild.flds, sbuild.scan = &trq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a TaskRecordSelect configured with the given aggregations. +func (trq *TaskRecordQuery) Aggregate(fns ...AggregateFunc) *TaskRecordSelect { + return trq.Select().Aggregate(fns...) +} + +func (trq *TaskRecordQuery) prepareQuery(ctx context.Context) error { + for _, inter := range trq.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, trq); err != nil { + return err + } + } + } + for _, f := range trq.ctx.Fields { + if !taskrecord.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + } + if trq.path != nil { + prev, err := trq.path(ctx) + if err != nil { + return err + } + trq.sql = prev + } + return nil +} + +func (trq *TaskRecordQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*TaskRecord, error) { + var ( + nodes = []*TaskRecord{} + _spec = trq.querySpec() + loadedTypes = [1]bool{ + trq.withTask != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*TaskRecord).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &TaskRecord{config: trq.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(trq.modifiers) > 0 { + _spec.Modifiers = trq.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, trq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := trq.withTask; query != nil { + if err := trq.loadTask(ctx, query, nodes, nil, + func(n *TaskRecord, e *Task) { n.Edges.Task = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (trq *TaskRecordQuery) loadTask(ctx context.Context, query *TaskQuery, nodes []*TaskRecord, init func(*TaskRecord), assign func(*TaskRecord, *Task)) error { + ids := make([]uuid.UUID, 0, len(nodes)) + nodeids := make(map[uuid.UUID][]*TaskRecord) + for i := range nodes { + fk := nodes[i].TaskID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(task.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 "task_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (trq *TaskRecordQuery) sqlCount(ctx context.Context) (int, error) { + _spec := trq.querySpec() + if len(trq.modifiers) > 0 { + _spec.Modifiers = trq.modifiers + } + _spec.Node.Columns = trq.ctx.Fields + if len(trq.ctx.Fields) > 0 { + _spec.Unique = trq.ctx.Unique != nil && *trq.ctx.Unique + } + return sqlgraph.CountNodes(ctx, trq.driver, _spec) +} + +func (trq *TaskRecordQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(taskrecord.Table, taskrecord.Columns, sqlgraph.NewFieldSpec(taskrecord.FieldID, field.TypeUUID)) + _spec.From = trq.sql + if unique := trq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if trq.path != nil { + _spec.Unique = true + } + if fields := trq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, taskrecord.FieldID) + for i := range fields { + if fields[i] != taskrecord.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if trq.withTask != nil { + _spec.Node.AddColumnOnce(taskrecord.FieldTaskID) + } + } + if ps := trq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := trq.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := trq.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := trq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (trq *TaskRecordQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(trq.driver.Dialect()) + t1 := builder.Table(taskrecord.Table) + columns := trq.ctx.Fields + if len(columns) == 0 { + columns = taskrecord.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if trq.sql != nil { + selector = trq.sql + selector.Select(selector.Columns(columns...)...) + } + if trq.ctx.Unique != nil && *trq.ctx.Unique { + selector.Distinct() + } + for _, m := range trq.modifiers { + m(selector) + } + for _, p := range trq.predicates { + p(selector) + } + for _, p := range trq.order { + p(selector) + } + if offset := trq.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 := trq.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 (trq *TaskRecordQuery) ForUpdate(opts ...sql.LockOption) *TaskRecordQuery { + if trq.driver.Dialect() == dialect.Postgres { + trq.Unique(false) + } + trq.modifiers = append(trq.modifiers, func(s *sql.Selector) { + s.ForUpdate(opts...) + }) + return trq +} + +// 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 (trq *TaskRecordQuery) ForShare(opts ...sql.LockOption) *TaskRecordQuery { + if trq.driver.Dialect() == dialect.Postgres { + trq.Unique(false) + } + trq.modifiers = append(trq.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return trq +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (trq *TaskRecordQuery) Modify(modifiers ...func(s *sql.Selector)) *TaskRecordSelect { + trq.modifiers = append(trq.modifiers, modifiers...) + return trq.Select() +} + +// TaskRecordGroupBy is the group-by builder for TaskRecord entities. +type TaskRecordGroupBy struct { + selector + build *TaskRecordQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (trgb *TaskRecordGroupBy) Aggregate(fns ...AggregateFunc) *TaskRecordGroupBy { + trgb.fns = append(trgb.fns, fns...) + return trgb +} + +// Scan applies the selector query and scans the result into the given value. +func (trgb *TaskRecordGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, trgb.build.ctx, ent.OpQueryGroupBy) + if err := trgb.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*TaskRecordQuery, *TaskRecordGroupBy](ctx, trgb.build, trgb, trgb.build.inters, v) +} + +func (trgb *TaskRecordGroupBy) sqlScan(ctx context.Context, root *TaskRecordQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(trgb.fns)) + for _, fn := range trgb.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*trgb.flds)+len(trgb.fns)) + for _, f := range *trgb.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*trgb.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := trgb.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// TaskRecordSelect is the builder for selecting fields of TaskRecord entities. +type TaskRecordSelect struct { + *TaskRecordQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (trs *TaskRecordSelect) Aggregate(fns ...AggregateFunc) *TaskRecordSelect { + trs.fns = append(trs.fns, fns...) + return trs +} + +// Scan applies the selector query and scans the result into the given value. +func (trs *TaskRecordSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, trs.ctx, ent.OpQuerySelect) + if err := trs.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*TaskRecordQuery, *TaskRecordSelect](ctx, trs.TaskRecordQuery, trs, trs.inters, v) +} + +func (trs *TaskRecordSelect) sqlScan(ctx context.Context, root *TaskRecordQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(trs.fns)) + for _, fn := range trs.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*trs.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 := trs.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 (trs *TaskRecordSelect) Modify(modifiers ...func(s *sql.Selector)) *TaskRecordSelect { + trs.modifiers = append(trs.modifiers, modifiers...) + return trs +} diff --git a/backend/db/taskrecord_update.go b/backend/db/taskrecord_update.go new file mode 100644 index 0000000..2576fc9 --- /dev/null +++ b/backend/db/taskrecord_update.go @@ -0,0 +1,472 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/task" + "github.com/chaitin/MonkeyCode/backend/db/taskrecord" + "github.com/google/uuid" +) + +// TaskRecordUpdate is the builder for updating TaskRecord entities. +type TaskRecordUpdate struct { + config + hooks []Hook + mutation *TaskRecordMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the TaskRecordUpdate builder. +func (tru *TaskRecordUpdate) Where(ps ...predicate.TaskRecord) *TaskRecordUpdate { + tru.mutation.Where(ps...) + return tru +} + +// SetTaskID sets the "task_id" field. +func (tru *TaskRecordUpdate) SetTaskID(u uuid.UUID) *TaskRecordUpdate { + tru.mutation.SetTaskID(u) + return tru +} + +// SetNillableTaskID sets the "task_id" field if the given value is not nil. +func (tru *TaskRecordUpdate) SetNillableTaskID(u *uuid.UUID) *TaskRecordUpdate { + if u != nil { + tru.SetTaskID(*u) + } + return tru +} + +// ClearTaskID clears the value of the "task_id" field. +func (tru *TaskRecordUpdate) ClearTaskID() *TaskRecordUpdate { + tru.mutation.ClearTaskID() + return tru +} + +// SetCompletion sets the "completion" field. +func (tru *TaskRecordUpdate) SetCompletion(s string) *TaskRecordUpdate { + tru.mutation.SetCompletion(s) + return tru +} + +// SetNillableCompletion sets the "completion" field if the given value is not nil. +func (tru *TaskRecordUpdate) SetNillableCompletion(s *string) *TaskRecordUpdate { + if s != nil { + tru.SetCompletion(*s) + } + return tru +} + +// SetOutputTokens sets the "output_tokens" field. +func (tru *TaskRecordUpdate) SetOutputTokens(i int64) *TaskRecordUpdate { + tru.mutation.ResetOutputTokens() + tru.mutation.SetOutputTokens(i) + return tru +} + +// SetNillableOutputTokens sets the "output_tokens" field if the given value is not nil. +func (tru *TaskRecordUpdate) SetNillableOutputTokens(i *int64) *TaskRecordUpdate { + if i != nil { + tru.SetOutputTokens(*i) + } + return tru +} + +// AddOutputTokens adds i to the "output_tokens" field. +func (tru *TaskRecordUpdate) AddOutputTokens(i int64) *TaskRecordUpdate { + tru.mutation.AddOutputTokens(i) + return tru +} + +// SetCreatedAt sets the "created_at" field. +func (tru *TaskRecordUpdate) SetCreatedAt(t time.Time) *TaskRecordUpdate { + tru.mutation.SetCreatedAt(t) + return tru +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (tru *TaskRecordUpdate) SetNillableCreatedAt(t *time.Time) *TaskRecordUpdate { + if t != nil { + tru.SetCreatedAt(*t) + } + return tru +} + +// SetUpdatedAt sets the "updated_at" field. +func (tru *TaskRecordUpdate) SetUpdatedAt(t time.Time) *TaskRecordUpdate { + tru.mutation.SetUpdatedAt(t) + return tru +} + +// SetTask sets the "task" edge to the Task entity. +func (tru *TaskRecordUpdate) SetTask(t *Task) *TaskRecordUpdate { + return tru.SetTaskID(t.ID) +} + +// Mutation returns the TaskRecordMutation object of the builder. +func (tru *TaskRecordUpdate) Mutation() *TaskRecordMutation { + return tru.mutation +} + +// ClearTask clears the "task" edge to the Task entity. +func (tru *TaskRecordUpdate) ClearTask() *TaskRecordUpdate { + tru.mutation.ClearTask() + return tru +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (tru *TaskRecordUpdate) Save(ctx context.Context) (int, error) { + tru.defaults() + return withHooks(ctx, tru.sqlSave, tru.mutation, tru.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (tru *TaskRecordUpdate) SaveX(ctx context.Context) int { + affected, err := tru.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (tru *TaskRecordUpdate) Exec(ctx context.Context) error { + _, err := tru.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (tru *TaskRecordUpdate) ExecX(ctx context.Context) { + if err := tru.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (tru *TaskRecordUpdate) defaults() { + if _, ok := tru.mutation.UpdatedAt(); !ok { + v := taskrecord.UpdateDefaultUpdatedAt() + tru.mutation.SetUpdatedAt(v) + } +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (tru *TaskRecordUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *TaskRecordUpdate { + tru.modifiers = append(tru.modifiers, modifiers...) + return tru +} + +func (tru *TaskRecordUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := sqlgraph.NewUpdateSpec(taskrecord.Table, taskrecord.Columns, sqlgraph.NewFieldSpec(taskrecord.FieldID, field.TypeUUID)) + if ps := tru.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := tru.mutation.Completion(); ok { + _spec.SetField(taskrecord.FieldCompletion, field.TypeString, value) + } + if value, ok := tru.mutation.OutputTokens(); ok { + _spec.SetField(taskrecord.FieldOutputTokens, field.TypeInt64, value) + } + if value, ok := tru.mutation.AddedOutputTokens(); ok { + _spec.AddField(taskrecord.FieldOutputTokens, field.TypeInt64, value) + } + if value, ok := tru.mutation.CreatedAt(); ok { + _spec.SetField(taskrecord.FieldCreatedAt, field.TypeTime, value) + } + if value, ok := tru.mutation.UpdatedAt(); ok { + _spec.SetField(taskrecord.FieldUpdatedAt, field.TypeTime, value) + } + if tru.mutation.TaskCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: taskrecord.TaskTable, + Columns: []string{taskrecord.TaskColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(task.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tru.mutation.TaskIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: taskrecord.TaskTable, + Columns: []string{taskrecord.TaskColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(task.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(tru.modifiers...) + if n, err = sqlgraph.UpdateNodes(ctx, tru.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{taskrecord.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + tru.mutation.done = true + return n, nil +} + +// TaskRecordUpdateOne is the builder for updating a single TaskRecord entity. +type TaskRecordUpdateOne struct { + config + fields []string + hooks []Hook + mutation *TaskRecordMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetTaskID sets the "task_id" field. +func (truo *TaskRecordUpdateOne) SetTaskID(u uuid.UUID) *TaskRecordUpdateOne { + truo.mutation.SetTaskID(u) + return truo +} + +// SetNillableTaskID sets the "task_id" field if the given value is not nil. +func (truo *TaskRecordUpdateOne) SetNillableTaskID(u *uuid.UUID) *TaskRecordUpdateOne { + if u != nil { + truo.SetTaskID(*u) + } + return truo +} + +// ClearTaskID clears the value of the "task_id" field. +func (truo *TaskRecordUpdateOne) ClearTaskID() *TaskRecordUpdateOne { + truo.mutation.ClearTaskID() + return truo +} + +// SetCompletion sets the "completion" field. +func (truo *TaskRecordUpdateOne) SetCompletion(s string) *TaskRecordUpdateOne { + truo.mutation.SetCompletion(s) + return truo +} + +// SetNillableCompletion sets the "completion" field if the given value is not nil. +func (truo *TaskRecordUpdateOne) SetNillableCompletion(s *string) *TaskRecordUpdateOne { + if s != nil { + truo.SetCompletion(*s) + } + return truo +} + +// SetOutputTokens sets the "output_tokens" field. +func (truo *TaskRecordUpdateOne) SetOutputTokens(i int64) *TaskRecordUpdateOne { + truo.mutation.ResetOutputTokens() + truo.mutation.SetOutputTokens(i) + return truo +} + +// SetNillableOutputTokens sets the "output_tokens" field if the given value is not nil. +func (truo *TaskRecordUpdateOne) SetNillableOutputTokens(i *int64) *TaskRecordUpdateOne { + if i != nil { + truo.SetOutputTokens(*i) + } + return truo +} + +// AddOutputTokens adds i to the "output_tokens" field. +func (truo *TaskRecordUpdateOne) AddOutputTokens(i int64) *TaskRecordUpdateOne { + truo.mutation.AddOutputTokens(i) + return truo +} + +// SetCreatedAt sets the "created_at" field. +func (truo *TaskRecordUpdateOne) SetCreatedAt(t time.Time) *TaskRecordUpdateOne { + truo.mutation.SetCreatedAt(t) + return truo +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (truo *TaskRecordUpdateOne) SetNillableCreatedAt(t *time.Time) *TaskRecordUpdateOne { + if t != nil { + truo.SetCreatedAt(*t) + } + return truo +} + +// SetUpdatedAt sets the "updated_at" field. +func (truo *TaskRecordUpdateOne) SetUpdatedAt(t time.Time) *TaskRecordUpdateOne { + truo.mutation.SetUpdatedAt(t) + return truo +} + +// SetTask sets the "task" edge to the Task entity. +func (truo *TaskRecordUpdateOne) SetTask(t *Task) *TaskRecordUpdateOne { + return truo.SetTaskID(t.ID) +} + +// Mutation returns the TaskRecordMutation object of the builder. +func (truo *TaskRecordUpdateOne) Mutation() *TaskRecordMutation { + return truo.mutation +} + +// ClearTask clears the "task" edge to the Task entity. +func (truo *TaskRecordUpdateOne) ClearTask() *TaskRecordUpdateOne { + truo.mutation.ClearTask() + return truo +} + +// Where appends a list predicates to the TaskRecordUpdate builder. +func (truo *TaskRecordUpdateOne) Where(ps ...predicate.TaskRecord) *TaskRecordUpdateOne { + truo.mutation.Where(ps...) + return truo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (truo *TaskRecordUpdateOne) Select(field string, fields ...string) *TaskRecordUpdateOne { + truo.fields = append([]string{field}, fields...) + return truo +} + +// Save executes the query and returns the updated TaskRecord entity. +func (truo *TaskRecordUpdateOne) Save(ctx context.Context) (*TaskRecord, error) { + truo.defaults() + return withHooks(ctx, truo.sqlSave, truo.mutation, truo.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (truo *TaskRecordUpdateOne) SaveX(ctx context.Context) *TaskRecord { + node, err := truo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (truo *TaskRecordUpdateOne) Exec(ctx context.Context) error { + _, err := truo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (truo *TaskRecordUpdateOne) ExecX(ctx context.Context) { + if err := truo.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (truo *TaskRecordUpdateOne) defaults() { + if _, ok := truo.mutation.UpdatedAt(); !ok { + v := taskrecord.UpdateDefaultUpdatedAt() + truo.mutation.SetUpdatedAt(v) + } +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (truo *TaskRecordUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *TaskRecordUpdateOne { + truo.modifiers = append(truo.modifiers, modifiers...) + return truo +} + +func (truo *TaskRecordUpdateOne) sqlSave(ctx context.Context) (_node *TaskRecord, err error) { + _spec := sqlgraph.NewUpdateSpec(taskrecord.Table, taskrecord.Columns, sqlgraph.NewFieldSpec(taskrecord.FieldID, field.TypeUUID)) + id, ok := truo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "TaskRecord.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := truo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, taskrecord.FieldID) + for _, f := range fields { + if !taskrecord.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != taskrecord.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := truo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := truo.mutation.Completion(); ok { + _spec.SetField(taskrecord.FieldCompletion, field.TypeString, value) + } + if value, ok := truo.mutation.OutputTokens(); ok { + _spec.SetField(taskrecord.FieldOutputTokens, field.TypeInt64, value) + } + if value, ok := truo.mutation.AddedOutputTokens(); ok { + _spec.AddField(taskrecord.FieldOutputTokens, field.TypeInt64, value) + } + if value, ok := truo.mutation.CreatedAt(); ok { + _spec.SetField(taskrecord.FieldCreatedAt, field.TypeTime, value) + } + if value, ok := truo.mutation.UpdatedAt(); ok { + _spec.SetField(taskrecord.FieldUpdatedAt, field.TypeTime, value) + } + if truo.mutation.TaskCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: taskrecord.TaskTable, + Columns: []string{taskrecord.TaskColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(task.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := truo.mutation.TaskIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: taskrecord.TaskTable, + Columns: []string{taskrecord.TaskColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(task.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(truo.modifiers...) + _node = &TaskRecord{config: truo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, truo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{taskrecord.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + truo.mutation.done = true + return _node, nil +} diff --git a/backend/db/tx.go b/backend/db/tx.go index 7d53b1f..d0914d3 100644 --- a/backend/db/tx.go +++ b/backend/db/tx.go @@ -32,10 +32,12 @@ type Tx struct { InviteCode *InviteCodeClient // Model is the client for interacting with the Model builders. Model *ModelClient - // Record is the client for interacting with the Record builders. - Record *RecordClient // Setting is the client for interacting with the Setting builders. Setting *SettingClient + // Task is the client for interacting with the Task builders. + Task *TaskClient + // TaskRecord is the client for interacting with the TaskRecord builders. + TaskRecord *TaskRecordClient // User is the client for interacting with the User builders. User *UserClient // UserLoginHistory is the client for interacting with the UserLoginHistory builders. @@ -180,8 +182,9 @@ func (tx *Tx) init() { tx.BillingUsage = NewBillingUsageClient(tx.config) tx.InviteCode = NewInviteCodeClient(tx.config) tx.Model = NewModelClient(tx.config) - tx.Record = NewRecordClient(tx.config) tx.Setting = NewSettingClient(tx.config) + tx.Task = NewTaskClient(tx.config) + tx.TaskRecord = NewTaskRecordClient(tx.config) tx.User = NewUserClient(tx.config) tx.UserLoginHistory = NewUserLoginHistoryClient(tx.config) } diff --git a/backend/db/user.go b/backend/db/user.go index 17c1c2a..667fd02 100644 --- a/backend/db/user.go +++ b/backend/db/user.go @@ -39,30 +39,21 @@ type User struct { // UserEdges holds the relations/edges for other nodes in the graph. type UserEdges struct { - // Records holds the value of the records edge. - Records []*Record `json:"records,omitempty"` // LoginHistories holds the value of the login_histories edge. LoginHistories []*UserLoginHistory `json:"login_histories,omitempty"` // Models holds the value of the models edge. Models []*Model `json:"models,omitempty"` + // Tasks holds the value of the tasks edge. + Tasks []*Task `json:"tasks,omitempty"` // loadedTypes holds the information for reporting if a // type was loaded (or requested) in eager-loading or not. loadedTypes [3]bool } -// RecordsOrErr returns the Records value or an error if the edge -// was not loaded in eager-loading. -func (e UserEdges) RecordsOrErr() ([]*Record, error) { - if e.loadedTypes[0] { - return e.Records, nil - } - return nil, &NotLoadedError{edge: "records"} -} - // LoginHistoriesOrErr returns the LoginHistories value or an error if the edge // was not loaded in eager-loading. func (e UserEdges) LoginHistoriesOrErr() ([]*UserLoginHistory, error) { - if e.loadedTypes[1] { + if e.loadedTypes[0] { return e.LoginHistories, nil } return nil, &NotLoadedError{edge: "login_histories"} @@ -71,12 +62,21 @@ func (e UserEdges) LoginHistoriesOrErr() ([]*UserLoginHistory, error) { // ModelsOrErr returns the Models value or an error if the edge // was not loaded in eager-loading. func (e UserEdges) ModelsOrErr() ([]*Model, error) { - if e.loadedTypes[2] { + if e.loadedTypes[1] { return e.Models, nil } return nil, &NotLoadedError{edge: "models"} } +// TasksOrErr returns the Tasks value or an error if the edge +// was not loaded in eager-loading. +func (e UserEdges) TasksOrErr() ([]*Task, error) { + if e.loadedTypes[2] { + return e.Tasks, nil + } + return nil, &NotLoadedError{edge: "tasks"} +} + // scanValues returns the types for scanning values from sql.Rows. func (*User) scanValues(columns []string) ([]any, error) { values := make([]any, len(columns)) @@ -158,11 +158,6 @@ func (u *User) Value(name string) (ent.Value, error) { return u.selectValues.Get(name) } -// QueryRecords queries the "records" edge of the User entity. -func (u *User) QueryRecords() *RecordQuery { - return NewUserClient(u.config).QueryRecords(u) -} - // QueryLoginHistories queries the "login_histories" edge of the User entity. func (u *User) QueryLoginHistories() *UserLoginHistoryQuery { return NewUserClient(u.config).QueryLoginHistories(u) @@ -173,6 +168,11 @@ func (u *User) QueryModels() *ModelQuery { return NewUserClient(u.config).QueryModels(u) } +// QueryTasks queries the "tasks" edge of the User entity. +func (u *User) QueryTasks() *TaskQuery { + return NewUserClient(u.config).QueryTasks(u) +} + // Update returns a builder for updating this User. // Note that you need to call User.Unwrap() before calling this method if this User // was returned from a transaction, and the transaction was committed or rolled back. diff --git a/backend/db/user/user.go b/backend/db/user/user.go index 794ea11..5ddbc56 100644 --- a/backend/db/user/user.go +++ b/backend/db/user/user.go @@ -27,21 +27,14 @@ const ( FieldCreatedAt = "created_at" // FieldUpdatedAt holds the string denoting the updated_at field in the database. FieldUpdatedAt = "updated_at" - // EdgeRecords holds the string denoting the records edge name in mutations. - EdgeRecords = "records" // EdgeLoginHistories holds the string denoting the login_histories edge name in mutations. EdgeLoginHistories = "login_histories" // EdgeModels holds the string denoting the models edge name in mutations. EdgeModels = "models" + // EdgeTasks holds the string denoting the tasks edge name in mutations. + EdgeTasks = "tasks" // Table holds the table name of the user in the database. Table = "users" - // RecordsTable is the table that holds the records relation/edge. - RecordsTable = "records" - // RecordsInverseTable is the table name for the Record entity. - // It exists in this package in order to avoid circular dependency with the "record" package. - RecordsInverseTable = "records" - // RecordsColumn is the table column denoting the records relation/edge. - RecordsColumn = "user_id" // LoginHistoriesTable is the table that holds the login_histories relation/edge. LoginHistoriesTable = "user_login_histories" // LoginHistoriesInverseTable is the table name for the UserLoginHistory entity. @@ -56,6 +49,13 @@ const ( ModelsInverseTable = "models" // ModelsColumn is the table column denoting the models relation/edge. ModelsColumn = "user_id" + // TasksTable is the table that holds the tasks relation/edge. + TasksTable = "tasks" + // TasksInverseTable is the table name for the Task entity. + // It exists in this package in order to avoid circular dependency with the "task" package. + TasksInverseTable = "tasks" + // TasksColumn is the table column denoting the tasks relation/edge. + TasksColumn = "user_id" ) // Columns holds all SQL columns for user fields. @@ -126,20 +126,6 @@ func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc() } -// ByRecordsCount orders the results by records count. -func ByRecordsCount(opts ...sql.OrderTermOption) OrderOption { - return func(s *sql.Selector) { - sqlgraph.OrderByNeighborsCount(s, newRecordsStep(), opts...) - } -} - -// ByRecords orders the results by records terms. -func ByRecords(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { - return func(s *sql.Selector) { - sqlgraph.OrderByNeighborTerms(s, newRecordsStep(), append([]sql.OrderTerm{term}, terms...)...) - } -} - // ByLoginHistoriesCount orders the results by login_histories count. func ByLoginHistoriesCount(opts ...sql.OrderTermOption) OrderOption { return func(s *sql.Selector) { @@ -167,12 +153,19 @@ func ByModels(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { sqlgraph.OrderByNeighborTerms(s, newModelsStep(), append([]sql.OrderTerm{term}, terms...)...) } } -func newRecordsStep() *sqlgraph.Step { - return sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(RecordsInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, RecordsTable, RecordsColumn), - ) + +// ByTasksCount orders the results by tasks count. +func ByTasksCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newTasksStep(), opts...) + } +} + +// ByTasks orders the results by tasks terms. +func ByTasks(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newTasksStep(), append([]sql.OrderTerm{term}, terms...)...) + } } func newLoginHistoriesStep() *sqlgraph.Step { return sqlgraph.NewStep( @@ -188,3 +181,10 @@ func newModelsStep() *sqlgraph.Step { sqlgraph.Edge(sqlgraph.O2M, false, ModelsTable, ModelsColumn), ) } +func newTasksStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(TasksInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, TasksTable, TasksColumn), + ) +} diff --git a/backend/db/user/where.go b/backend/db/user/where.go index 792403f..25e0816 100644 --- a/backend/db/user/where.go +++ b/backend/db/user/where.go @@ -447,29 +447,6 @@ func UpdatedAtLTE(v time.Time) predicate.User { return predicate.User(sql.FieldLTE(FieldUpdatedAt, v)) } -// HasRecords applies the HasEdge predicate on the "records" edge. -func HasRecords() predicate.User { - return predicate.User(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, RecordsTable, RecordsColumn), - ) - sqlgraph.HasNeighbors(s, step) - }) -} - -// HasRecordsWith applies the HasEdge predicate on the "records" edge with a given conditions (other predicates). -func HasRecordsWith(preds ...predicate.Record) predicate.User { - return predicate.User(func(s *sql.Selector) { - step := newRecordsStep() - sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { - for _, p := range preds { - p(s) - } - }) - }) -} - // HasLoginHistories applies the HasEdge predicate on the "login_histories" edge. func HasLoginHistories() predicate.User { return predicate.User(func(s *sql.Selector) { @@ -516,6 +493,29 @@ func HasModelsWith(preds ...predicate.Model) predicate.User { }) } +// HasTasks applies the HasEdge predicate on the "tasks" edge. +func HasTasks() predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, TasksTable, TasksColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasTasksWith applies the HasEdge predicate on the "tasks" edge with a given conditions (other predicates). +func HasTasksWith(preds ...predicate.Task) predicate.User { + return predicate.User(func(s *sql.Selector) { + step := newTasksStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + // And groups predicates with the AND operator between them. func And(predicates ...predicate.User) predicate.User { return predicate.User(sql.AndPredicates(predicates...)) diff --git a/backend/db/user_create.go b/backend/db/user_create.go index eeee021..269ee34 100644 --- a/backend/db/user_create.go +++ b/backend/db/user_create.go @@ -14,7 +14,7 @@ import ( "entgo.io/ent/schema/field" "github.com/chaitin/MonkeyCode/backend/consts" "github.com/chaitin/MonkeyCode/backend/db/model" - "github.com/chaitin/MonkeyCode/backend/db/record" + "github.com/chaitin/MonkeyCode/backend/db/task" "github.com/chaitin/MonkeyCode/backend/db/user" "github.com/chaitin/MonkeyCode/backend/db/userloginhistory" "github.com/google/uuid" @@ -94,21 +94,6 @@ func (uc *UserCreate) SetID(u uuid.UUID) *UserCreate { return uc } -// AddRecordIDs adds the "records" edge to the Record entity by IDs. -func (uc *UserCreate) AddRecordIDs(ids ...uuid.UUID) *UserCreate { - uc.mutation.AddRecordIDs(ids...) - return uc -} - -// AddRecords adds the "records" edges to the Record entity. -func (uc *UserCreate) AddRecords(r ...*Record) *UserCreate { - ids := make([]uuid.UUID, len(r)) - for i := range r { - ids[i] = r[i].ID - } - return uc.AddRecordIDs(ids...) -} - // AddLoginHistoryIDs adds the "login_histories" edge to the UserLoginHistory entity by IDs. func (uc *UserCreate) AddLoginHistoryIDs(ids ...uuid.UUID) *UserCreate { uc.mutation.AddLoginHistoryIDs(ids...) @@ -139,6 +124,21 @@ func (uc *UserCreate) AddModels(m ...*Model) *UserCreate { return uc.AddModelIDs(ids...) } +// AddTaskIDs adds the "tasks" edge to the Task entity by IDs. +func (uc *UserCreate) AddTaskIDs(ids ...uuid.UUID) *UserCreate { + uc.mutation.AddTaskIDs(ids...) + return uc +} + +// AddTasks adds the "tasks" edges to the Task entity. +func (uc *UserCreate) AddTasks(t ...*Task) *UserCreate { + ids := make([]uuid.UUID, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return uc.AddTaskIDs(ids...) +} + // Mutation returns the UserMutation object of the builder. func (uc *UserCreate) Mutation() *UserMutation { return uc.mutation @@ -268,22 +268,6 @@ func (uc *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) { _spec.SetField(user.FieldUpdatedAt, field.TypeTime, value) _node.UpdatedAt = value } - if nodes := uc.mutation.RecordsIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: user.RecordsTable, - Columns: []string{user.RecordsColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(record.FieldID, field.TypeUUID), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges = append(_spec.Edges, edge) - } if nodes := uc.mutation.LoginHistoriesIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, @@ -316,6 +300,22 @@ func (uc *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) { } _spec.Edges = append(_spec.Edges, edge) } + if nodes := uc.mutation.TasksIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.TasksTable, + Columns: []string{user.TasksColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(task.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } return _node, _spec } diff --git a/backend/db/user_query.go b/backend/db/user_query.go index 170b753..c9d6609 100644 --- a/backend/db/user_query.go +++ b/backend/db/user_query.go @@ -15,7 +15,7 @@ import ( "entgo.io/ent/schema/field" "github.com/chaitin/MonkeyCode/backend/db/model" "github.com/chaitin/MonkeyCode/backend/db/predicate" - "github.com/chaitin/MonkeyCode/backend/db/record" + "github.com/chaitin/MonkeyCode/backend/db/task" "github.com/chaitin/MonkeyCode/backend/db/user" "github.com/chaitin/MonkeyCode/backend/db/userloginhistory" "github.com/google/uuid" @@ -28,9 +28,9 @@ type UserQuery struct { order []user.OrderOption inters []Interceptor predicates []predicate.User - withRecords *RecordQuery withLoginHistories *UserLoginHistoryQuery withModels *ModelQuery + withTasks *TaskQuery modifiers []func(*sql.Selector) // intermediate query (i.e. traversal path). sql *sql.Selector @@ -68,28 +68,6 @@ func (uq *UserQuery) Order(o ...user.OrderOption) *UserQuery { return uq } -// QueryRecords chains the current query on the "records" edge. -func (uq *UserQuery) QueryRecords() *RecordQuery { - query := (&RecordClient{config: uq.config}).Query() - query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { - if err := uq.prepareQuery(ctx); err != nil { - return nil, err - } - selector := uq.sqlQuery(ctx) - if err := selector.Err(); err != nil { - return nil, err - } - step := sqlgraph.NewStep( - sqlgraph.From(user.Table, user.FieldID, selector), - sqlgraph.To(record.Table, record.FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, user.RecordsTable, user.RecordsColumn), - ) - fromU = sqlgraph.SetNeighbors(uq.driver.Dialect(), step) - return fromU, nil - } - return query -} - // QueryLoginHistories chains the current query on the "login_histories" edge. func (uq *UserQuery) QueryLoginHistories() *UserLoginHistoryQuery { query := (&UserLoginHistoryClient{config: uq.config}).Query() @@ -134,6 +112,28 @@ func (uq *UserQuery) QueryModels() *ModelQuery { return query } +// QueryTasks chains the current query on the "tasks" edge. +func (uq *UserQuery) QueryTasks() *TaskQuery { + query := (&TaskClient{config: uq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := uq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := uq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, selector), + sqlgraph.To(task.Table, task.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, user.TasksTable, user.TasksColumn), + ) + fromU = sqlgraph.SetNeighbors(uq.driver.Dialect(), step) + return fromU, nil + } + return query +} + // First returns the first User entity from the query. // Returns a *NotFoundError when no User was found. func (uq *UserQuery) First(ctx context.Context) (*User, error) { @@ -326,9 +326,9 @@ func (uq *UserQuery) Clone() *UserQuery { order: append([]user.OrderOption{}, uq.order...), inters: append([]Interceptor{}, uq.inters...), predicates: append([]predicate.User{}, uq.predicates...), - withRecords: uq.withRecords.Clone(), withLoginHistories: uq.withLoginHistories.Clone(), withModels: uq.withModels.Clone(), + withTasks: uq.withTasks.Clone(), // clone intermediate query. sql: uq.sql.Clone(), path: uq.path, @@ -336,17 +336,6 @@ func (uq *UserQuery) Clone() *UserQuery { } } -// WithRecords tells the query-builder to eager-load the nodes that are connected to -// the "records" edge. The optional arguments are used to configure the query builder of the edge. -func (uq *UserQuery) WithRecords(opts ...func(*RecordQuery)) *UserQuery { - query := (&RecordClient{config: uq.config}).Query() - for _, opt := range opts { - opt(query) - } - uq.withRecords = query - return uq -} - // WithLoginHistories tells the query-builder to eager-load the nodes that are connected to // the "login_histories" edge. The optional arguments are used to configure the query builder of the edge. func (uq *UserQuery) WithLoginHistories(opts ...func(*UserLoginHistoryQuery)) *UserQuery { @@ -369,6 +358,17 @@ func (uq *UserQuery) WithModels(opts ...func(*ModelQuery)) *UserQuery { return uq } +// WithTasks tells the query-builder to eager-load the nodes that are connected to +// the "tasks" edge. The optional arguments are used to configure the query builder of the edge. +func (uq *UserQuery) WithTasks(opts ...func(*TaskQuery)) *UserQuery { + query := (&TaskClient{config: uq.config}).Query() + for _, opt := range opts { + opt(query) + } + uq.withTasks = query + return uq +} + // GroupBy is used to group vertices by one or more fields/columns. // It is often used with aggregate functions, like: count, max, mean, min, sum. // @@ -448,9 +448,9 @@ func (uq *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, e nodes = []*User{} _spec = uq.querySpec() loadedTypes = [3]bool{ - uq.withRecords != nil, uq.withLoginHistories != nil, uq.withModels != nil, + uq.withTasks != nil, } ) _spec.ScanValues = func(columns []string) ([]any, error) { @@ -474,13 +474,6 @@ func (uq *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, e if len(nodes) == 0 { return nodes, nil } - if query := uq.withRecords; query != nil { - if err := uq.loadRecords(ctx, query, nodes, - func(n *User) { n.Edges.Records = []*Record{} }, - func(n *User, e *Record) { n.Edges.Records = append(n.Edges.Records, e) }); err != nil { - return nil, err - } - } if query := uq.withLoginHistories; query != nil { if err := uq.loadLoginHistories(ctx, query, nodes, func(n *User) { n.Edges.LoginHistories = []*UserLoginHistory{} }, @@ -495,39 +488,16 @@ func (uq *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, e return nil, err } } + if query := uq.withTasks; query != nil { + if err := uq.loadTasks(ctx, query, nodes, + func(n *User) { n.Edges.Tasks = []*Task{} }, + func(n *User, e *Task) { n.Edges.Tasks = append(n.Edges.Tasks, e) }); err != nil { + return nil, err + } + } return nodes, nil } -func (uq *UserQuery) loadRecords(ctx context.Context, query *RecordQuery, nodes []*User, init func(*User), assign func(*User, *Record)) error { - fks := make([]driver.Value, 0, len(nodes)) - nodeids := make(map[uuid.UUID]*User) - for i := range nodes { - fks = append(fks, nodes[i].ID) - nodeids[nodes[i].ID] = nodes[i] - if init != nil { - init(nodes[i]) - } - } - if len(query.ctx.Fields) > 0 { - query.ctx.AppendFieldOnce(record.FieldUserID) - } - query.Where(predicate.Record(func(s *sql.Selector) { - s.Where(sql.InValues(s.C(user.RecordsColumn), fks...)) - })) - neighbors, err := query.All(ctx) - if err != nil { - return err - } - for _, n := range neighbors { - fk := n.UserID - node, ok := nodeids[fk] - if !ok { - return fmt.Errorf(`unexpected referenced foreign-key "user_id" returned %v for node %v`, fk, n.ID) - } - assign(node, n) - } - return nil -} func (uq *UserQuery) loadLoginHistories(ctx context.Context, query *UserLoginHistoryQuery, nodes []*User, init func(*User), assign func(*User, *UserLoginHistory)) error { fks := make([]driver.Value, 0, len(nodes)) nodeids := make(map[uuid.UUID]*User) @@ -589,6 +559,36 @@ func (uq *UserQuery) loadModels(ctx context.Context, query *ModelQuery, nodes [] } return nil } +func (uq *UserQuery) loadTasks(ctx context.Context, query *TaskQuery, nodes []*User, init func(*User), assign func(*User, *Task)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[uuid.UUID]*User) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) + } + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(task.FieldUserID) + } + query.Where(predicate.Task(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(user.TasksColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.UserID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "user_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} func (uq *UserQuery) sqlCount(ctx context.Context) (int, error) { _spec := uq.querySpec() diff --git a/backend/db/user_update.go b/backend/db/user_update.go index f5d15d5..a6ffc8f 100644 --- a/backend/db/user_update.go +++ b/backend/db/user_update.go @@ -14,7 +14,7 @@ import ( "github.com/chaitin/MonkeyCode/backend/consts" "github.com/chaitin/MonkeyCode/backend/db/model" "github.com/chaitin/MonkeyCode/backend/db/predicate" - "github.com/chaitin/MonkeyCode/backend/db/record" + "github.com/chaitin/MonkeyCode/backend/db/task" "github.com/chaitin/MonkeyCode/backend/db/user" "github.com/chaitin/MonkeyCode/backend/db/userloginhistory" "github.com/google/uuid" @@ -118,21 +118,6 @@ func (uu *UserUpdate) SetNillableUpdatedAt(t *time.Time) *UserUpdate { return uu } -// AddRecordIDs adds the "records" edge to the Record entity by IDs. -func (uu *UserUpdate) AddRecordIDs(ids ...uuid.UUID) *UserUpdate { - uu.mutation.AddRecordIDs(ids...) - return uu -} - -// AddRecords adds the "records" edges to the Record entity. -func (uu *UserUpdate) AddRecords(r ...*Record) *UserUpdate { - ids := make([]uuid.UUID, len(r)) - for i := range r { - ids[i] = r[i].ID - } - return uu.AddRecordIDs(ids...) -} - // AddLoginHistoryIDs adds the "login_histories" edge to the UserLoginHistory entity by IDs. func (uu *UserUpdate) AddLoginHistoryIDs(ids ...uuid.UUID) *UserUpdate { uu.mutation.AddLoginHistoryIDs(ids...) @@ -163,32 +148,26 @@ func (uu *UserUpdate) AddModels(m ...*Model) *UserUpdate { return uu.AddModelIDs(ids...) } +// AddTaskIDs adds the "tasks" edge to the Task entity by IDs. +func (uu *UserUpdate) AddTaskIDs(ids ...uuid.UUID) *UserUpdate { + uu.mutation.AddTaskIDs(ids...) + return uu +} + +// AddTasks adds the "tasks" edges to the Task entity. +func (uu *UserUpdate) AddTasks(t ...*Task) *UserUpdate { + ids := make([]uuid.UUID, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return uu.AddTaskIDs(ids...) +} + // Mutation returns the UserMutation object of the builder. func (uu *UserUpdate) Mutation() *UserMutation { return uu.mutation } -// ClearRecords clears all "records" edges to the Record entity. -func (uu *UserUpdate) ClearRecords() *UserUpdate { - uu.mutation.ClearRecords() - return uu -} - -// RemoveRecordIDs removes the "records" edge to Record entities by IDs. -func (uu *UserUpdate) RemoveRecordIDs(ids ...uuid.UUID) *UserUpdate { - uu.mutation.RemoveRecordIDs(ids...) - return uu -} - -// RemoveRecords removes "records" edges to Record entities. -func (uu *UserUpdate) RemoveRecords(r ...*Record) *UserUpdate { - ids := make([]uuid.UUID, len(r)) - for i := range r { - ids[i] = r[i].ID - } - return uu.RemoveRecordIDs(ids...) -} - // ClearLoginHistories clears all "login_histories" edges to the UserLoginHistory entity. func (uu *UserUpdate) ClearLoginHistories() *UserUpdate { uu.mutation.ClearLoginHistories() @@ -231,6 +210,27 @@ func (uu *UserUpdate) RemoveModels(m ...*Model) *UserUpdate { return uu.RemoveModelIDs(ids...) } +// ClearTasks clears all "tasks" edges to the Task entity. +func (uu *UserUpdate) ClearTasks() *UserUpdate { + uu.mutation.ClearTasks() + return uu +} + +// RemoveTaskIDs removes the "tasks" edge to Task entities by IDs. +func (uu *UserUpdate) RemoveTaskIDs(ids ...uuid.UUID) *UserUpdate { + uu.mutation.RemoveTaskIDs(ids...) + return uu +} + +// RemoveTasks removes "tasks" edges to Task entities. +func (uu *UserUpdate) RemoveTasks(t ...*Task) *UserUpdate { + ids := make([]uuid.UUID, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return uu.RemoveTaskIDs(ids...) +} + // Save executes the query and returns the number of nodes affected by the update operation. func (uu *UserUpdate) Save(ctx context.Context) (int, error) { return withHooks(ctx, uu.sqlSave, uu.mutation, uu.hooks) @@ -291,51 +291,6 @@ func (uu *UserUpdate) sqlSave(ctx context.Context) (n int, err error) { if value, ok := uu.mutation.UpdatedAt(); ok { _spec.SetField(user.FieldUpdatedAt, field.TypeTime, value) } - if uu.mutation.RecordsCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: user.RecordsTable, - Columns: []string{user.RecordsColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(record.FieldID, field.TypeUUID), - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := uu.mutation.RemovedRecordsIDs(); len(nodes) > 0 && !uu.mutation.RecordsCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: user.RecordsTable, - Columns: []string{user.RecordsColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(record.FieldID, field.TypeUUID), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := uu.mutation.RecordsIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: user.RecordsTable, - Columns: []string{user.RecordsColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(record.FieldID, field.TypeUUID), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } if uu.mutation.LoginHistoriesCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, @@ -426,6 +381,51 @@ func (uu *UserUpdate) sqlSave(ctx context.Context) (n int, err error) { } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if uu.mutation.TasksCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.TasksTable, + Columns: []string{user.TasksColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(task.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uu.mutation.RemovedTasksIDs(); len(nodes) > 0 && !uu.mutation.TasksCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.TasksTable, + Columns: []string{user.TasksColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(task.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uu.mutation.TasksIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.TasksTable, + Columns: []string{user.TasksColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(task.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } _spec.AddModifiers(uu.modifiers...) if n, err = sqlgraph.UpdateNodes(ctx, uu.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { @@ -532,21 +532,6 @@ func (uuo *UserUpdateOne) SetNillableUpdatedAt(t *time.Time) *UserUpdateOne { return uuo } -// AddRecordIDs adds the "records" edge to the Record entity by IDs. -func (uuo *UserUpdateOne) AddRecordIDs(ids ...uuid.UUID) *UserUpdateOne { - uuo.mutation.AddRecordIDs(ids...) - return uuo -} - -// AddRecords adds the "records" edges to the Record entity. -func (uuo *UserUpdateOne) AddRecords(r ...*Record) *UserUpdateOne { - ids := make([]uuid.UUID, len(r)) - for i := range r { - ids[i] = r[i].ID - } - return uuo.AddRecordIDs(ids...) -} - // AddLoginHistoryIDs adds the "login_histories" edge to the UserLoginHistory entity by IDs. func (uuo *UserUpdateOne) AddLoginHistoryIDs(ids ...uuid.UUID) *UserUpdateOne { uuo.mutation.AddLoginHistoryIDs(ids...) @@ -577,32 +562,26 @@ func (uuo *UserUpdateOne) AddModels(m ...*Model) *UserUpdateOne { return uuo.AddModelIDs(ids...) } +// AddTaskIDs adds the "tasks" edge to the Task entity by IDs. +func (uuo *UserUpdateOne) AddTaskIDs(ids ...uuid.UUID) *UserUpdateOne { + uuo.mutation.AddTaskIDs(ids...) + return uuo +} + +// AddTasks adds the "tasks" edges to the Task entity. +func (uuo *UserUpdateOne) AddTasks(t ...*Task) *UserUpdateOne { + ids := make([]uuid.UUID, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return uuo.AddTaskIDs(ids...) +} + // Mutation returns the UserMutation object of the builder. func (uuo *UserUpdateOne) Mutation() *UserMutation { return uuo.mutation } -// ClearRecords clears all "records" edges to the Record entity. -func (uuo *UserUpdateOne) ClearRecords() *UserUpdateOne { - uuo.mutation.ClearRecords() - return uuo -} - -// RemoveRecordIDs removes the "records" edge to Record entities by IDs. -func (uuo *UserUpdateOne) RemoveRecordIDs(ids ...uuid.UUID) *UserUpdateOne { - uuo.mutation.RemoveRecordIDs(ids...) - return uuo -} - -// RemoveRecords removes "records" edges to Record entities. -func (uuo *UserUpdateOne) RemoveRecords(r ...*Record) *UserUpdateOne { - ids := make([]uuid.UUID, len(r)) - for i := range r { - ids[i] = r[i].ID - } - return uuo.RemoveRecordIDs(ids...) -} - // ClearLoginHistories clears all "login_histories" edges to the UserLoginHistory entity. func (uuo *UserUpdateOne) ClearLoginHistories() *UserUpdateOne { uuo.mutation.ClearLoginHistories() @@ -645,6 +624,27 @@ func (uuo *UserUpdateOne) RemoveModels(m ...*Model) *UserUpdateOne { return uuo.RemoveModelIDs(ids...) } +// ClearTasks clears all "tasks" edges to the Task entity. +func (uuo *UserUpdateOne) ClearTasks() *UserUpdateOne { + uuo.mutation.ClearTasks() + return uuo +} + +// RemoveTaskIDs removes the "tasks" edge to Task entities by IDs. +func (uuo *UserUpdateOne) RemoveTaskIDs(ids ...uuid.UUID) *UserUpdateOne { + uuo.mutation.RemoveTaskIDs(ids...) + return uuo +} + +// RemoveTasks removes "tasks" edges to Task entities. +func (uuo *UserUpdateOne) RemoveTasks(t ...*Task) *UserUpdateOne { + ids := make([]uuid.UUID, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return uuo.RemoveTaskIDs(ids...) +} + // Where appends a list predicates to the UserUpdate builder. func (uuo *UserUpdateOne) Where(ps ...predicate.User) *UserUpdateOne { uuo.mutation.Where(ps...) @@ -735,51 +735,6 @@ func (uuo *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) if value, ok := uuo.mutation.UpdatedAt(); ok { _spec.SetField(user.FieldUpdatedAt, field.TypeTime, value) } - if uuo.mutation.RecordsCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: user.RecordsTable, - Columns: []string{user.RecordsColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(record.FieldID, field.TypeUUID), - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := uuo.mutation.RemovedRecordsIDs(); len(nodes) > 0 && !uuo.mutation.RecordsCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: user.RecordsTable, - Columns: []string{user.RecordsColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(record.FieldID, field.TypeUUID), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := uuo.mutation.RecordsIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: user.RecordsTable, - Columns: []string{user.RecordsColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(record.FieldID, field.TypeUUID), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } if uuo.mutation.LoginHistoriesCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, @@ -870,6 +825,51 @@ func (uuo *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if uuo.mutation.TasksCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.TasksTable, + Columns: []string{user.TasksColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(task.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uuo.mutation.RemovedTasksIDs(); len(nodes) > 0 && !uuo.mutation.TasksCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.TasksTable, + Columns: []string{user.TasksColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(task.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uuo.mutation.TasksIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.TasksTable, + Columns: []string{user.TasksColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(task.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } _spec.AddModifiers(uuo.modifiers...) _node = &User{config: uuo.config} _spec.Assign = _node.assignValues diff --git a/backend/domain/billing.go b/backend/domain/billing.go index 8674a9c..64bee84 100644 --- a/backend/domain/billing.go +++ b/backend/domain/billing.go @@ -46,11 +46,11 @@ type ChatRecord struct { CreatedAt int64 `json:"created_at"` // 创建时间 } -func (c *ChatRecord) From(e *db.Record) *ChatRecord { +func (c *ChatRecord) From(e *db.Task) *ChatRecord { if e == nil { return c } - c.ID = e.ID.String() + c.ID = e.TaskID c.Question = e.Prompt c.User = cvt.From(e.Edges.User, &User{}) c.Model = cvt.From(e.Edges.Model, &Model{}) @@ -71,11 +71,11 @@ type CompletionRecord struct { CreatedAt int64 `json:"created_at"` // 创建时间 } -func (c *CompletionRecord) From(e *db.Record) *CompletionRecord { +func (c *CompletionRecord) From(e *db.Task) *CompletionRecord { if e == nil { return c } - c.ID = e.ID.String() + c.ID = e.TaskID c.IsAccept = e.IsAccept c.User = cvt.From(e.Edges.User, &User{}) c.ProgramLanguage = e.ProgramLanguage @@ -91,11 +91,11 @@ type CompletionInfo struct { CreatedAt int64 `json:"created_at"` } -func (c *CompletionInfo) From(e *db.Record) *CompletionInfo { +func (c *CompletionInfo) From(e *db.Task) *CompletionInfo { if e == nil { return c } - c.ID = e.ID.String() + c.ID = e.TaskID c.Content = e.Completion c.CreatedAt = e.CreatedAt.Unix() return c @@ -107,12 +107,14 @@ type ChatInfo struct { CreatedAt int64 `json:"created_at"` } -func (c *ChatInfo) From(e *db.Record) *ChatInfo { +func (c *ChatInfo) From(e *db.Task) *ChatInfo { if e == nil { return c } - c.ID = e.ID.String() - c.Content = e.Completion + c.ID = e.TaskID + for _, tr := range e.Edges.TaskRecords { + c.Content += tr.Completion + "\n" + } c.CreatedAt = e.CreatedAt.Unix() return c } diff --git a/backend/domain/dashboard.go b/backend/domain/dashboard.go index 6547259..8baec21 100644 --- a/backend/domain/dashboard.go +++ b/backend/domain/dashboard.go @@ -46,7 +46,7 @@ type UserCodeRank struct { Lines int64 `json:"lines"` // 代码行数 } -func (u *UserCodeRank) From(d *db.Record) *UserCodeRank { +func (u *UserCodeRank) From(d *db.Task) *UserCodeRank { if d == nil { return u } diff --git a/backend/domain/proxy.go b/backend/domain/proxy.go index 55652b4..554a880 100644 --- a/backend/domain/proxy.go +++ b/backend/domain/proxy.go @@ -26,8 +26,8 @@ type ProxyUsecase interface { } type ProxyRepo interface { - Record(ctx context.Context, record *db.Record) error - UpdateByTaskID(ctx context.Context, taskID string, fn func(*db.RecordUpdateOne)) error + Record(ctx context.Context, record *RecordParam) error + UpdateByTaskID(ctx context.Context, taskID string, fn func(*db.TaskUpdateOne)) error SelectModelWithLoadBalancing(modelName string, modelType consts.ModelType) (*db.Model, error) ValidateApiKey(ctx context.Context, key string) (*db.ApiKey, error) } @@ -38,6 +38,7 @@ type AcceptCompletionReq struct { } type RecordParam struct { + RequestID string TaskID string UserID string ModelID string diff --git a/backend/ent/schema/model.go b/backend/ent/schema/model.go index 3037a92..b8176ba 100644 --- a/backend/ent/schema/model.go +++ b/backend/ent/schema/model.go @@ -48,7 +48,7 @@ func (Model) Fields() []ent.Field { // Edges of the Model. func (Model) Edges() []ent.Edge { return []ent.Edge{ - edge.To("records", Record.Type), + edge.To("tasks", Task.Type), edge.From("user", User.Type).Ref("models").Field("user_id").Unique(), } } diff --git a/backend/ent/schema/record.go b/backend/ent/schema/task.go similarity index 56% rename from backend/ent/schema/record.go rename to backend/ent/schema/task.go index f743f3c..33d7047 100644 --- a/backend/ent/schema/record.go +++ b/backend/ent/schema/task.go @@ -8,49 +8,50 @@ import ( "entgo.io/ent/schema" "entgo.io/ent/schema/edge" "entgo.io/ent/schema/field" - "github.com/google/uuid" - "github.com/chaitin/MonkeyCode/backend/consts" + "github.com/google/uuid" ) -// Record holds the schema definition for the Record entity. -type Record struct { +// Task holds the schema definition for the Task entity. +type Task struct { ent.Schema } -func (Record) Annotations() []schema.Annotation { +func (Task) Annotations() []schema.Annotation { return []schema.Annotation{ entsql.Annotation{ - Table: "records", + Table: "tasks", }, } } -// Fields of the Record. -func (Record) Fields() []ent.Field { +// Fields of the Task. +func (Task) Fields() []ent.Field { return []ent.Field{ field.UUID("id", uuid.UUID{}), + field.String("task_id").Unique(), field.UUID("user_id", uuid.UUID{}).Optional(), field.UUID("model_id", uuid.UUID{}).Optional(), - field.String("task_id"), - field.String("model_type").GoType(consts.ModelType("")).Optional(), + field.String("request_id").Optional(), + field.String("model_type").GoType(consts.ModelType("")), field.String("prompt").Optional(), - field.String("completion").Optional(), field.Bool("is_accept").Default(false), field.String("program_language").Optional(), field.String("work_mode").Optional(), + field.String("completion").Optional(), field.Int64("code_lines").Optional(), - field.Int64("input_tokens"), - field.Int64("output_tokens"), + field.Int64("input_tokens").Optional(), + field.Int64("output_tokens").Optional(), field.Time("created_at").Default(time.Now), field.Time("updated_at").Default(time.Now).UpdateDefault(time.Now), } } -// Edges of the Record. -func (Record) Edges() []ent.Edge { +// Edges of the Task. +func (Task) Edges() []ent.Edge { return []ent.Edge{ - edge.From("user", User.Type).Ref("records").Field("user_id").Unique(), - edge.From("model", Model.Type).Ref("records").Field("model_id").Unique(), + edge.To("task_records", TaskRecord.Type), + edge.From("user", User.Type).Ref("tasks").Field("user_id").Unique(), + edge.From("model", Model.Type).Ref("tasks").Field("model_id").Unique(), } } diff --git a/backend/ent/schema/taskrecord.go b/backend/ent/schema/taskrecord.go new file mode 100644 index 0000000..b333189 --- /dev/null +++ b/backend/ent/schema/taskrecord.go @@ -0,0 +1,44 @@ +package schema + +import ( + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/schema" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" + "github.com/google/uuid" +) + +// TaskRecord holds the schema definition for the TaskRecord entity. +type TaskRecord struct { + ent.Schema +} + +func (TaskRecord) Annotations() []schema.Annotation { + return []schema.Annotation{ + entsql.Annotation{ + Table: "task_records", + }, + } +} + +// Fields of the TaskRecord. +func (TaskRecord) Fields() []ent.Field { + return []ent.Field{ + field.UUID("id", uuid.UUID{}).Unique(), + field.UUID("task_id", uuid.UUID{}).Optional(), + field.String("completion"), + field.Int64("output_tokens"), + field.Time("created_at").Default(time.Now), + field.Time("updated_at").Default(time.Now).UpdateDefault(time.Now), + } +} + +// Edges of the TaskRecord. +func (TaskRecord) Edges() []ent.Edge { + return []ent.Edge{ + edge.From("task", Task.Type).Ref("task_records").Field("task_id").Unique(), + } +} diff --git a/backend/ent/schema/user.go b/backend/ent/schema/user.go index cee8ba3..01c7898 100644 --- a/backend/ent/schema/user.go +++ b/backend/ent/schema/user.go @@ -42,8 +42,8 @@ func (User) Fields() []ent.Field { // Edges of the User. func (User) Edges() []ent.Edge { return []ent.Edge{ - edge.To("records", Record.Type), edge.To("login_histories", UserLoginHistory.Type), edge.To("models", Model.Type), + edge.To("tasks", Task.Type), } } diff --git a/backend/internal/billing/repo/billing.go b/backend/internal/billing/repo/billing.go index 6e8ac2b..723a19f 100644 --- a/backend/internal/billing/repo/billing.go +++ b/backend/internal/billing/repo/billing.go @@ -4,13 +4,13 @@ import ( "context" "entgo.io/ent/dialect/sql" - "github.com/google/uuid" "github.com/GoYoko/web" "github.com/chaitin/MonkeyCode/backend/consts" "github.com/chaitin/MonkeyCode/backend/db" - "github.com/chaitin/MonkeyCode/backend/db/record" + "github.com/chaitin/MonkeyCode/backend/db/task" + "github.com/chaitin/MonkeyCode/backend/db/taskrecord" "github.com/chaitin/MonkeyCode/backend/domain" "github.com/chaitin/MonkeyCode/backend/pkg/cvt" ) @@ -25,12 +25,12 @@ func NewBillingRepo(db *db.Client) domain.BillingRepo { // ChatInfo implements domain.BillingRepo. func (b *BillingRepo) ChatInfo(ctx context.Context, id string) (*domain.ChatInfo, error) { - uid, err := uuid.Parse(id) - if err != nil { - return nil, err - } - - record, err := b.db.Record.Query().Where(record.ID(uid)).First(ctx) + record, err := b.db.Task.Query(). + WithTaskRecords(func(trq *db.TaskRecordQuery) { + trq.Order(taskrecord.ByCreatedAt(sql.OrderAsc())) + }). + Where(task.TaskID(id)). + First(ctx) if err != nil { return nil, err } @@ -40,12 +40,7 @@ func (b *BillingRepo) ChatInfo(ctx context.Context, id string) (*domain.ChatInfo // CompletionInfo implements domain.BillingRepo. func (b *BillingRepo) CompletionInfo(ctx context.Context, id string) (*domain.CompletionInfo, error) { - uid, err := uuid.Parse(id) - if err != nil { - return nil, err - } - - record, err := b.db.Record.Query().Where(record.ID(uid)).First(ctx) + record, err := b.db.Task.Query().Where(task.TaskID(id)).First(ctx) if err != nil { return nil, err } @@ -55,11 +50,12 @@ func (b *BillingRepo) CompletionInfo(ctx context.Context, id string) (*domain.Co // ListChatRecord implements domain.BillingRepo. func (b *BillingRepo) ListChatRecord(ctx context.Context, page *web.Pagination) (*domain.ListChatRecordResp, error) { - q := b.db.Record.Query(). + q := b.db.Task.Query(). WithUser(). WithModel(). - Where(record.ModelType(consts.ModelTypeLLM)). - Order(record.ByCreatedAt(sql.OrderDesc())) + WithTaskRecords(). + Where(task.ModelType(consts.ModelTypeLLM)). + Order(task.ByCreatedAt(sql.OrderDesc())) records, p, err := q.Page(ctx, page.Page, page.Size) if err != nil { @@ -68,7 +64,7 @@ func (b *BillingRepo) ListChatRecord(ctx context.Context, page *web.Pagination) return &domain.ListChatRecordResp{ PageInfo: p, - Records: cvt.Iter(records, func(_ int, r *db.Record) *domain.ChatRecord { + Records: cvt.Iter(records, func(_ int, r *db.Task) *domain.ChatRecord { return cvt.From(r, &domain.ChatRecord{}) }), }, nil @@ -76,11 +72,11 @@ func (b *BillingRepo) ListChatRecord(ctx context.Context, page *web.Pagination) // ListCompletionRecord implements domain.BillingRepo. func (b *BillingRepo) ListCompletionRecord(ctx context.Context, page *web.Pagination) (*domain.ListCompletionRecordResp, error) { - q := b.db.Record.Query(). + q := b.db.Task.Query(). WithUser(). WithModel(). - Where(record.ModelType(consts.ModelTypeCoder)). - Order(record.ByCreatedAt(sql.OrderDesc())) + Where(task.ModelType(consts.ModelTypeCoder)). + Order(task.ByCreatedAt(sql.OrderDesc())) records, p, err := q.Page(ctx, page.Page, page.Size) if err != nil { return nil, err @@ -88,7 +84,7 @@ func (b *BillingRepo) ListCompletionRecord(ctx context.Context, page *web.Pagina return &domain.ListCompletionRecordResp{ PageInfo: p, - Records: cvt.Iter(records, func(_ int, r *db.Record) *domain.CompletionRecord { + Records: cvt.Iter(records, func(_ int, r *db.Task) *domain.CompletionRecord { return cvt.From(r, &domain.CompletionRecord{}) }), }, nil diff --git a/backend/internal/dashboard/repo/dashboard.go b/backend/internal/dashboard/repo/dashboard.go index c055bd4..d5dc1ba 100644 --- a/backend/internal/dashboard/repo/dashboard.go +++ b/backend/internal/dashboard/repo/dashboard.go @@ -11,7 +11,7 @@ import ( "github.com/chaitin/MonkeyCode/backend/consts" "github.com/chaitin/MonkeyCode/backend/db" - "github.com/chaitin/MonkeyCode/backend/db/record" + "github.com/chaitin/MonkeyCode/backend/db/task" "github.com/chaitin/MonkeyCode/backend/db/user" "github.com/chaitin/MonkeyCode/backend/domain" ) @@ -27,28 +27,28 @@ func NewDashboardRepo(db *db.Client) domain.DashboardRepo { // CategoryStat implements domain.DashboardRepo. func (d *DashboardRepo) CategoryStat(ctx context.Context) (*domain.CategoryStat, error) { var cs []domain.CategoryPoint - if err := d.db.Record.Query(). - Where(record.CreatedAtGTE(time.Now().AddDate(0, 0, -90))). - Where(record.WorkModeNEQ("")). + if err := d.db.Task.Query(). + Where(task.CreatedAtGTE(time.Now().AddDate(0, 0, -90))). + Where(task.WorkModeNEQ("")). Modify(func(s *sql.Selector) { s.Select( sql.As("work_mode", "category"), sql.As("COUNT(*)", "value"), - ).GroupBy(record.FieldWorkMode). + ).GroupBy(task.FieldWorkMode). OrderBy(sql.Desc("value")) }). Scan(ctx, &cs); err != nil { return nil, err } var ps []domain.CategoryPoint - if err := d.db.Record.Query(). - Where(record.CreatedAtGTE(time.Now().AddDate(0, 0, -90))). - Where(record.ProgramLanguageNotNil()). + if err := d.db.Task.Query(). + Where(task.CreatedAtGTE(time.Now().AddDate(0, 0, -90))). + Where(task.ProgramLanguageNEQ("")). Modify(func(s *sql.Selector) { s.Select( sql.As("program_language", "category"), sql.As("COUNT(*)", "value"), - ).GroupBy(record.FieldProgramLanguage). + ).GroupBy(task.FieldProgramLanguage). OrderBy(sql.Desc("value")) }). Scan(ctx, &ps); err != nil { @@ -90,8 +90,8 @@ type DateValue struct { // TimeStat implements domain.DashboardRepo. func (d *DashboardRepo) TimeStat(ctx context.Context) (*domain.TimeStat, error) { ds := make([]DateValue, 0) - if err := d.db.Record.Query(). - Where(record.CreatedAtGTE(time.Now().AddDate(0, 0, -90))). + if err := d.db.Task.Query(). + Where(task.CreatedAtGTE(time.Now().AddDate(0, 0, -90))). Modify(func(s *sql.Selector) { s.Select( sql.As("date_trunc('day', created_at)", "date"), @@ -99,7 +99,7 @@ func (d *DashboardRepo) TimeStat(ctx context.Context) (*domain.TimeStat, error) sql.As("COUNT(*) FILTER (WHERE model_type = 'llm')", "llm_count"), sql.As("COUNT(*) FILTER (WHERE model_type = 'coder')", "code_count"), sql.As("COUNT(*) FILTER (WHERE is_accept = true AND model_type = 'coder')", "accepted_count"), - sql.As(sql.Sum(record.FieldCodeLines), "code_lines"), + sql.As(sql.Sum(task.FieldCodeLines), "code_lines"), ).GroupBy("date"). OrderBy(sql.Asc("date")) }). @@ -108,8 +108,8 @@ func (d *DashboardRepo) TimeStat(ctx context.Context) (*domain.TimeStat, error) } dsOneHour := make([]DateValue, 0) - if err := d.db.Record.Query(). - Where(record.CreatedAtGTE(time.Now().Add(-time.Hour))). + if err := d.db.Task.Query(). + Where(task.CreatedAtGTE(time.Now().Add(-time.Hour))). Modify(func(s *sql.Selector) { s.Select( sql.As("date_trunc('minute', created_at)", "date"), @@ -177,13 +177,13 @@ type UserCodeRank struct { // UserCodeRank implements domain.DashboardRepo. func (d *DashboardRepo) UserCodeRank(ctx context.Context) ([]*domain.UserCodeRank, error) { var rs []UserCodeRank - if err := d.db.Record.Query(). - Where(record.CreatedAtGTE(time.Now().AddDate(0, 0, -90))). + if err := d.db.Task.Query(). + Where(task.CreatedAtGTE(time.Now().AddDate(0, 0, -90))). Modify(func(s *sql.Selector) { s.Select( sql.As("user_id", "user_id"), - sql.As(sql.Sum(record.FieldCodeLines), "code_lines"), - ).GroupBy(record.FieldUserID). + sql.As(sql.Sum(task.FieldCodeLines), "code_lines"), + ).GroupBy(task.FieldUserID). OrderBy(sql.Desc("code_lines")) }). Scan(ctx, &rs); err != nil { @@ -216,18 +216,18 @@ func (d *DashboardRepo) UserEvents(ctx context.Context, userID string) ([]*domai if err != nil { return nil, err } - rs, err := d.db.Record.Query(). + rs, err := d.db.Task.Query(). WithUser(). - Where(record.CreatedAtGTE(time.Now().AddDate(0, 0, -90))). - Where(record.HasUserWith(user.ID(id))). - Order(record.ByCreatedAt(sql.OrderDesc())). + Where(task.CreatedAtGTE(time.Now().AddDate(0, 0, -90))). + Where(task.HasUserWith(user.ID(id))). + Order(task.ByCreatedAt(sql.OrderDesc())). Limit(100). All(ctx) if err != nil { return nil, err } - return cvt.Iter(rs, func(_ int, v *db.Record) *domain.UserEvent { + return cvt.Iter(rs, func(_ int, v *db.Task) *domain.UserEvent { return &domain.UserEvent{ Name: v.Edges.User.Username, CreatedAt: v.CreatedAt.Unix(), @@ -242,9 +242,9 @@ func (d *DashboardRepo) UserStat(ctx context.Context, userID string) (*domain.Us return nil, err } var ds []DateValue - if err := d.db.Record.Query(). - Where(record.HasUserWith(user.ID(id))). - Where(record.CreatedAtGTE(time.Now().AddDate(0, 0, -90))). + if err := d.db.Task.Query(). + Where(task.HasUserWith(user.ID(id))). + Where(task.CreatedAtGTE(time.Now().AddDate(0, 0, -90))). Modify(func(s *sql.Selector) { s.Select( sql.As("date_trunc('day', created_at)", "date"), @@ -252,7 +252,7 @@ func (d *DashboardRepo) UserStat(ctx context.Context, userID string) (*domain.Us sql.As("COUNT(*) FILTER (WHERE model_type = 'llm')", "llm_count"), sql.As("COUNT(*) FILTER (WHERE model_type = 'coder')", "code_count"), sql.As("COUNT(*) FILTER (WHERE is_accept = true AND model_type = 'coder')", "accepted_count"), - sql.As(sql.Sum(record.FieldCodeLines), "code_lines"), + sql.As(sql.Sum(task.FieldCodeLines), "code_lines"), ).GroupBy("date"). OrderBy(sql.Asc("date")) }). @@ -261,30 +261,30 @@ func (d *DashboardRepo) UserStat(ctx context.Context, userID string) (*domain.Us } var cs []domain.CategoryPoint - if err := d.db.Record.Query(). - Where(record.CreatedAtGTE(time.Now().AddDate(0, 0, -90))). - Where(record.HasUserWith(user.ID(id))). - Where(record.WorkModeNotNil()). + if err := d.db.Task.Query(). + Where(task.CreatedAtGTE(time.Now().AddDate(0, 0, -90))). + Where(task.HasUserWith(user.ID(id))). + Where(task.WorkModeNotNil()). Modify(func(s *sql.Selector) { s.Select( sql.As("work_mode", "category"), sql.As("COUNT(*)", "value"), - ).GroupBy(record.FieldWorkMode). + ).GroupBy(task.FieldWorkMode). OrderBy(sql.Desc("value")) }). Scan(ctx, &cs); err != nil { return nil, err } var ps []domain.CategoryPoint - if err := d.db.Record.Query(). - Where(record.CreatedAtGTE(time.Now().AddDate(0, 0, -90))). - Where(record.HasUserWith(user.ID(id))). - Where(record.ProgramLanguageNotNil()). + if err := d.db.Task.Query(). + Where(task.CreatedAtGTE(time.Now().AddDate(0, 0, -90))). + Where(task.HasUserWith(user.ID(id))). + Where(task.ProgramLanguageNotNil()). Modify(func(s *sql.Selector) { s.Select( sql.As("program_language", "category"), sql.As("COUNT(*)", "value"), - ).GroupBy(record.FieldProgramLanguage). + ).GroupBy(task.FieldProgramLanguage). OrderBy(sql.Desc("value")) }). Scan(ctx, &ps); err != nil { @@ -339,9 +339,9 @@ func (d *DashboardRepo) UserHeatmap(ctx context.Context, userID string) ([]*doma } var rs []DateValue - if err := d.db.Record.Query(). - Where(record.HasUserWith(user.ID(id))). - Where(record.CreatedAtGTE(time.Now().AddDate(-1, 0, 0))). + if err := d.db.Task.Query(). + Where(task.HasUserWith(user.ID(id))). + Where(task.CreatedAtGTE(time.Now().AddDate(-1, 0, 0))). Modify(func(s *sql.Selector) { s.Select( sql.As("date_trunc('day', created_at)", "date"), diff --git a/backend/internal/model/repo/model.go b/backend/internal/model/repo/model.go index 437757c..c349102 100644 --- a/backend/internal/model/repo/model.go +++ b/backend/internal/model/repo/model.go @@ -10,7 +10,7 @@ import ( "github.com/chaitin/MonkeyCode/backend/consts" "github.com/chaitin/MonkeyCode/backend/db" "github.com/chaitin/MonkeyCode/backend/db/model" - "github.com/chaitin/MonkeyCode/backend/db/record" + "github.com/chaitin/MonkeyCode/backend/db/task" "github.com/chaitin/MonkeyCode/backend/domain" "github.com/chaitin/MonkeyCode/backend/pkg/cvt" "github.com/chaitin/MonkeyCode/backend/pkg/entx" @@ -75,13 +75,13 @@ func (r *ModelRepo) MyModelList(ctx context.Context, req *domain.MyModelListReq) func (r *ModelRepo) ModelUsage(ctx context.Context, ids []uuid.UUID) (map[uuid.UUID]domain.ModelUsage, error) { var usages []domain.ModelUsage - err := r.db.Record.Query(). - Where(record.ModelIDIn(ids...)). + err := r.db.Task.Query(). + Where(task.ModelIDIn(ids...)). Modify(func(s *entsql.Selector) { s.Select( - entsql.As(record.FieldModelID, "model_id"), - entsql.As(entsql.Sum(record.FieldInputTokens), "input"), - entsql.As(entsql.Sum(record.FieldOutputTokens), "output"), + entsql.As(task.FieldModelID, "model_id"), + entsql.As(entsql.Sum(task.FieldInputTokens), "input"), + entsql.As(entsql.Sum(task.FieldOutputTokens), "output"), ). GroupBy("model_id"). OrderBy("model_id") @@ -109,16 +109,16 @@ type DailyUsage struct { func (r *ModelRepo) GetTokenUsage(ctx context.Context, modelType consts.ModelType) (*domain.ModelTokenUsageResp, error) { var dailyUsages []DailyUsage - err := r.db.Record.Query(). + err := r.db.Task.Query(). Where( - record.ModelType(modelType), - record.CreatedAtGTE(time.Now().AddDate(0, 0, -90)), + task.ModelType(modelType), + task.CreatedAtGTE(time.Now().AddDate(0, 0, -90)), ). Modify(func(s *entsql.Selector) { s.Select( entsql.As("date_trunc('day', created_at)", "date"), - entsql.As(entsql.Sum(record.FieldInputTokens), "input_tokens"), - entsql.As(entsql.Sum(record.FieldOutputTokens), "output_tokens"), + entsql.As(entsql.Sum(task.FieldInputTokens), "input_tokens"), + entsql.As(entsql.Sum(task.FieldOutputTokens), "output_tokens"), ). GroupBy("date"). OrderBy("date") diff --git a/backend/internal/openai/handler/v1/v1.go b/backend/internal/openai/handler/v1/v1.go index 15f1bf8..423d14d 100644 --- a/backend/internal/openai/handler/v1/v1.go +++ b/backend/internal/openai/handler/v1/v1.go @@ -103,8 +103,8 @@ func (h *V1Handler) ChatCompletion(c *web.Context, req openai.ChatCompletionRequ if req.Model == "" { return BadRequest(c, "模型不能为空") } - h.logger.With("request", req).DebugContext(c.Request().Context(), "处理聊天补全请求") + h.logger.With("request", req).DebugContext(c.Request().Context(), "处理聊天补全请求") // if len(req.Tools) > 0 && req.Model != "qwen-max" { // if h.toolsCall(c, req, req.Stream, req.Model) { // return nil diff --git a/backend/internal/proxy/proxy.go b/backend/internal/proxy/proxy.go index b50c484..74ddfa4 100644 --- a/backend/internal/proxy/proxy.go +++ b/backend/internal/proxy/proxy.go @@ -531,9 +531,19 @@ func streamRead(ctx context.Context, r io.Reader, fn func([]byte) error) error { func getPrompt(req *openai.ChatCompletionRequest) string { for _, message := range req.Messages { - if message.Role == "user" && strings.Contains(message.Content, "") { + if message.Role == "system" { + continue + } + + if strings.Contains(message.Content, "") { return message.Content } + + for _, m := range message.MultiContent { + if strings.Contains(m.Text, "") { + return m.Text + } + } } return "" } @@ -672,12 +682,13 @@ func (p *LLMProxy) handleChatCompletionStream(ctx context.Context, w http.Respon w.Header().Set("Transfer-Encoding", "chunked") rc := &domain.RecordParam{ + RequestID: c.RequestID, + TaskID: taskID, UserID: c.UserID, ModelID: m.ID, ModelType: consts.ModelTypeLLM, WorkMode: mode, Prompt: prompt, - TaskID: taskID, } buf := bufio.NewWriterSize(w, 32*1024) defer buf.Flush() @@ -709,8 +720,8 @@ func (p *LLMProxy) handleChatCompletionStream(ctx context.Context, w http.Respon rc.Completion += t.Choices[0].Delta.Content } if t.Usage != nil { - rc.InputTokens += int64(t.Usage.PromptTokens) - rc.OutputTokens += int64(t.Usage.CompletionTokens) + rc.InputTokens = int64(t.Usage.PromptTokens) + rc.OutputTokens = int64(t.Usage.CompletionTokens) } } } diff --git a/backend/internal/proxy/repo/proxy.go b/backend/internal/proxy/repo/proxy.go index 6ae69ce..edfeca8 100644 --- a/backend/internal/proxy/repo/proxy.go +++ b/backend/internal/proxy/repo/proxy.go @@ -3,11 +3,13 @@ package repo import ( "context" + "github.com/google/uuid" + "github.com/chaitin/MonkeyCode/backend/consts" "github.com/chaitin/MonkeyCode/backend/db" "github.com/chaitin/MonkeyCode/backend/db/apikey" "github.com/chaitin/MonkeyCode/backend/db/model" - "github.com/chaitin/MonkeyCode/backend/db/record" + "github.com/chaitin/MonkeyCode/backend/db/task" "github.com/chaitin/MonkeyCode/backend/domain" "github.com/chaitin/MonkeyCode/backend/pkg/entx" ) @@ -41,31 +43,74 @@ func (r *ProxyRepo) ValidateApiKey(ctx context.Context, key string) (*db.ApiKey, return a, nil } -func (r *ProxyRepo) Record(ctx context.Context, record *db.Record) error { - return r.db.Record.Create(). - SetUserID(record.UserID). - SetModelID(record.ModelID). - SetTaskID(record.TaskID). - SetPrompt(record.Prompt). - SetProgramLanguage(record.ProgramLanguage). - SetInputTokens(record.InputTokens). - SetOutputTokens(record.OutputTokens). - SetIsAccept(record.IsAccept). - SetModelType(record.ModelType). - SetCompletion(record.Completion). - SetWorkMode(record.WorkMode). - SetCodeLines(record.CodeLines). - Exec(ctx) -} - -func (r *ProxyRepo) UpdateByTaskID(ctx context.Context, taskID string, fn func(*db.RecordUpdateOne)) error { - rc, err := r.db.Record.Query().Where(record.TaskID(taskID)).Only(ctx) +func (r *ProxyRepo) Record(ctx context.Context, record *domain.RecordParam) error { + userID, err := uuid.Parse(record.UserID) + if err != nil { + return err + } + modelID, err := uuid.Parse(record.ModelID) if err != nil { return err } return entx.WithTx(ctx, r.db, func(tx *db.Tx) error { - up := tx.Record.UpdateOneID(rc.ID) + isNew := false + t, err := tx.Task.Query().ForUpdate().Where(task.TaskID(record.TaskID)).Only(ctx) + if db.IsNotFound(err) { + t, err = tx.Task.Create(). + SetTaskID(record.TaskID). + SetRequestID(record.RequestID). + SetUserID(userID). + SetModelID(modelID). + SetPrompt(record.Prompt). + SetProgramLanguage(record.ProgramLanguage). + SetInputTokens(record.InputTokens). + SetOutputTokens(record.OutputTokens). + SetIsAccept(record.IsAccept). + SetModelType(record.ModelType). + SetWorkMode(record.WorkMode). + SetCodeLines(record.CodeLines). + Save(ctx) + isNew = true + } + if err != nil { + return err + } + if !isNew { + up := tx.Task.UpdateOneID(t.ID) + if record.OutputTokens > 0 { + up.AddOutputTokens(record.OutputTokens) + } + if t.InputTokens == 0 && record.InputTokens > 0 { + up.SetInputTokens(record.InputTokens) + } + if t.RequestID != record.RequestID { + up.SetRequestID(record.RequestID) + up.AddInputTokens(record.InputTokens) + } + if err := up.Exec(ctx); err != nil { + return err + } + } + + _, err = tx.TaskRecord.Create(). + SetTaskID(t.ID). + SetCompletion(record.Completion). + SetOutputTokens(record.OutputTokens). + Save(ctx) + + return err + }) +} + +func (r *ProxyRepo) UpdateByTaskID(ctx context.Context, taskID string, fn func(*db.TaskUpdateOne)) error { + rc, err := r.db.Task.Query().Where(task.TaskID(taskID)).Only(ctx) + if err != nil { + return err + } + + return entx.WithTx(ctx, r.db, func(tx *db.Tx) error { + up := tx.Task.UpdateOneID(rc.ID) fn(up) return up.Exec(ctx) }) diff --git a/backend/internal/proxy/usecase/proxy.go b/backend/internal/proxy/usecase/proxy.go index 797bdc8..22020e5 100644 --- a/backend/internal/proxy/usecase/proxy.go +++ b/backend/internal/proxy/usecase/proxy.go @@ -3,8 +3,6 @@ package usecase import ( "context" - "github.com/google/uuid" - "github.com/chaitin/MonkeyCode/backend/pkg/cvt" "github.com/chaitin/MonkeyCode/backend/consts" @@ -21,29 +19,7 @@ func NewProxyUsecase(repo domain.ProxyRepo) domain.ProxyUsecase { } func (p *ProxyUsecase) Record(ctx context.Context, record *domain.RecordParam) error { - userID, err := uuid.Parse(record.UserID) - if err != nil { - return err - } - modelID, err := uuid.Parse(record.ModelID) - if err != nil { - return err - } - - return p.repo.Record(ctx, &db.Record{ - UserID: userID, - ModelID: modelID, - Prompt: record.Prompt, - TaskID: record.TaskID, - ProgramLanguage: record.ProgramLanguage, - InputTokens: record.InputTokens, - OutputTokens: record.OutputTokens, - IsAccept: record.IsAccept, - ModelType: record.ModelType, - Completion: record.Completion, - WorkMode: record.WorkMode, - CodeLines: record.CodeLines, - }) + return p.repo.Record(ctx, record) } // SelectModelWithLoadBalancing implements domain.ProxyUsecase. @@ -64,7 +40,7 @@ func (p *ProxyUsecase) ValidateApiKey(ctx context.Context, key string) (*domain. } func (p *ProxyUsecase) AcceptCompletion(ctx context.Context, req *domain.AcceptCompletionReq) error { - return p.repo.UpdateByTaskID(ctx, req.ID, func(ruo *db.RecordUpdateOne) { + return p.repo.UpdateByTaskID(ctx, req.ID, func(ruo *db.TaskUpdateOne) { ruo.SetIsAccept(true) ruo.SetCompletion(req.Completion) }) diff --git a/backend/migration/000002_create_core_table.up.sql b/backend/migration/000002_create_core_table.up.sql index 4f33fba..d356f2b 100644 --- a/backend/migration/000002_create_core_table.up.sql +++ b/backend/migration/000002_create_core_table.up.sql @@ -99,11 +99,12 @@ CREATE TABLE IF NOT EXISTS api_keys ( CREATE UNIQUE INDEX IF NOT EXISTS unique_idx_api_keys_user_id ON api_keys(user_id); CREATE INDEX IF NOT EXISTS idx_api_keys_key ON api_keys(key); -CREATE TABLE IF NOT EXISTS records ( +CREATE TABLE IF NOT EXISTS tasks ( id UUID PRIMARY KEY DEFAULT uuid_generate_v1(), + task_id VARCHAR(255) NOT NULL, user_id UUID NOT NULL, model_id UUID NOT NULL, - task_id VARCHAR(255), + request_id VARCHAR(255), model_type VARCHAR(255) NOT NULL, prompt TEXT, completion TEXT, @@ -117,11 +118,25 @@ CREATE TABLE IF NOT EXISTS records ( updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP ); -CREATE INDEX IF NOT EXISTS idx_records_user_id ON records (user_id); -CREATE INDEX IF NOT EXISTS idx_records_model_id ON records (model_id); -CREATE INDEX IF NOT EXISTS idx_records_task_id ON records (task_id); -CREATE INDEX IF NOT EXISTS idx_records_created_at ON records (created_at); -CREATE INDEX IF NOT EXISTS idx_records_updated_at ON records (updated_at); +CREATE UNIQUE INDEX IF NOT EXISTS unique_idx_tasks_task_id ON tasks(task_id); +CREATE INDEX IF NOT EXISTS idx_tasks_user_id ON tasks (user_id); +CREATE INDEX IF NOT EXISTS idx_tasks_model_id ON tasks (model_id); +CREATE INDEX IF NOT EXISTS idx_tasks_model_type ON tasks (model_type); +CREATE INDEX IF NOT EXISTS idx_tasks_work_mode ON tasks (work_mode); +CREATE INDEX IF NOT EXISTS idx_tasks_program_language ON tasks (program_language); +CREATE INDEX IF NOT EXISTS idx_tasks_created_at ON tasks (created_at); +CREATE INDEX IF NOT EXISTS idx_tasks_updated_at ON tasks (updated_at); + +CREATE TABLE IF NOT EXISTS task_records ( + id UUID PRIMARY KEY DEFAULT uuid_generate_v1(), + task_id UUID NOT NULL, + completion TEXT, + output_tokens BIGINT, + created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP +); + +CREATE INDEX IF NOT EXISTS idx_task_records_task_id ON task_records (task_id); CREATE TABLE IF NOT EXISTS settings ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(),