From 3a1affd88e2947de7ce0dfb5e95a809246500603 Mon Sep 17 00:00:00 2001 From: yokowu <18836617@qq.com> Date: Fri, 4 Jul 2025 20:17:49 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=8F=92=E4=BB=B6=E6=9B=B4=E6=96=B0?= =?UTF-8?q?=E7=AE=A1=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/cmd/server/wire_gen.go | 40 +- backend/config/config.go | 8 +- backend/db/client.go | 162 ++++- backend/db/ent.go | 2 + backend/db/extension.go | 129 ++++ backend/db/extension/extension.go | 70 ++ backend/db/extension/where.go | 256 ++++++++ backend/db/extension_create.go | 615 ++++++++++++++++++ backend/db/extension_delete.go | 88 +++ backend/db/extension_query.go | 578 ++++++++++++++++ backend/db/extension_update.go | 294 +++++++++ backend/db/hook/hook.go | 12 + backend/db/intercept/intercept.go | 30 + backend/db/migrate/schema.go | 17 + backend/db/mutation.go | 442 +++++++++++++ backend/db/page.go | 14 + backend/db/predicate/predicate.go | 3 + backend/db/runtime/runtime.go | 7 + backend/db/tx.go | 3 + backend/domain/extension.go | 38 ++ backend/domain/proxy.go | 5 + backend/ent/schema/extension.go | 39 ++ backend/internal/extension/repo/extension.go | 42 ++ .../internal/extension/usecase/extension.go | 146 +++++ backend/internal/openai/handler/v1/v1.go | 21 + backend/internal/provider.go | 4 + backend/internal/user/handler/v1/user.go | 15 +- .../000004_create_extensions_table.down.sql | 0 .../000004_create_extensions_table.up.sql | 8 + 29 files changed, 3053 insertions(+), 35 deletions(-) create mode 100644 backend/db/extension.go create mode 100644 backend/db/extension/extension.go create mode 100644 backend/db/extension/where.go create mode 100644 backend/db/extension_create.go create mode 100644 backend/db/extension_delete.go create mode 100644 backend/db/extension_query.go create mode 100644 backend/db/extension_update.go create mode 100644 backend/domain/extension.go create mode 100644 backend/ent/schema/extension.go create mode 100644 backend/internal/extension/repo/extension.go create mode 100644 backend/internal/extension/usecase/extension.go create mode 100644 backend/migration/000004_create_extensions_table.down.sql create mode 100644 backend/migration/000004_create_extensions_table.up.sql diff --git a/backend/cmd/server/wire_gen.go b/backend/cmd/server/wire_gen.go index 7a01ad1..645b0ce 100644 --- a/backend/cmd/server/wire_gen.go +++ b/backend/cmd/server/wire_gen.go @@ -12,15 +12,17 @@ import ( "github.com/chaitin/MonkeyCode/backend/db" "github.com/chaitin/MonkeyCode/backend/domain" v1_5 "github.com/chaitin/MonkeyCode/backend/internal/billing/handler/http/v1" - repo6 "github.com/chaitin/MonkeyCode/backend/internal/billing/repo" - usecase5 "github.com/chaitin/MonkeyCode/backend/internal/billing/usecase" + repo7 "github.com/chaitin/MonkeyCode/backend/internal/billing/repo" + usecase6 "github.com/chaitin/MonkeyCode/backend/internal/billing/usecase" v1_4 "github.com/chaitin/MonkeyCode/backend/internal/dashboard/handler/v1" - repo5 "github.com/chaitin/MonkeyCode/backend/internal/dashboard/repo" - usecase4 "github.com/chaitin/MonkeyCode/backend/internal/dashboard/usecase" + repo6 "github.com/chaitin/MonkeyCode/backend/internal/dashboard/repo" + usecase5 "github.com/chaitin/MonkeyCode/backend/internal/dashboard/usecase" + repo3 "github.com/chaitin/MonkeyCode/backend/internal/extension/repo" + usecase2 "github.com/chaitin/MonkeyCode/backend/internal/extension/usecase" "github.com/chaitin/MonkeyCode/backend/internal/middleware" v1_2 "github.com/chaitin/MonkeyCode/backend/internal/model/handler/http/v1" - repo3 "github.com/chaitin/MonkeyCode/backend/internal/model/repo" - usecase2 "github.com/chaitin/MonkeyCode/backend/internal/model/usecase" + repo4 "github.com/chaitin/MonkeyCode/backend/internal/model/repo" + usecase3 "github.com/chaitin/MonkeyCode/backend/internal/model/usecase" "github.com/chaitin/MonkeyCode/backend/internal/openai/handler/v1" repo2 "github.com/chaitin/MonkeyCode/backend/internal/openai/repo" "github.com/chaitin/MonkeyCode/backend/internal/openai/usecase" @@ -28,8 +30,8 @@ import ( "github.com/chaitin/MonkeyCode/backend/internal/proxy/repo" "github.com/chaitin/MonkeyCode/backend/internal/proxy/usecase" v1_3 "github.com/chaitin/MonkeyCode/backend/internal/user/handler/v1" - repo4 "github.com/chaitin/MonkeyCode/backend/internal/user/repo" - usecase3 "github.com/chaitin/MonkeyCode/backend/internal/user/usecase" + repo5 "github.com/chaitin/MonkeyCode/backend/internal/user/repo" + usecase4 "github.com/chaitin/MonkeyCode/backend/internal/user/usecase" "github.com/chaitin/MonkeyCode/backend/pkg" "github.com/chaitin/MonkeyCode/backend/pkg/logger" "github.com/chaitin/MonkeyCode/backend/pkg/session" @@ -56,23 +58,25 @@ func newServer(dir string) (*Server, error) { domainProxy := proxy.NewLLMProxy(proxyUsecase, configConfig, slogLogger) openAIRepo := repo2.NewOpenAIRepo(client) openAIUsecase := openai.NewOpenAIUsecase(configConfig, openAIRepo, slogLogger) + extensionRepo := repo3.NewExtensionRepo(client) + extensionUsecase := usecase2.NewExtensionUsecase(extensionRepo, configConfig, slogLogger) proxyMiddleware := middleware.NewProxyMiddleware(proxyUsecase) redisClient := store.NewRedisCli(configConfig) activeMiddleware := middleware.NewActiveMiddleware(redisClient, slogLogger) - v1Handler := v1.NewV1Handler(slogLogger, web, domainProxy, openAIUsecase, proxyMiddleware, activeMiddleware) - modelRepo := repo3.NewModelRepo(client) - modelUsecase := usecase2.NewModelUsecase(slogLogger, modelRepo, configConfig) + v1Handler := v1.NewV1Handler(slogLogger, web, domainProxy, openAIUsecase, extensionUsecase, proxyMiddleware, activeMiddleware, configConfig) + modelRepo := repo4.NewModelRepo(client) + modelUsecase := usecase3.NewModelUsecase(slogLogger, modelRepo, configConfig) sessionSession := session.NewSession(configConfig) authMiddleware := middleware.NewAuthMiddleware(sessionSession, slogLogger) modelHandler := v1_2.NewModelHandler(web, modelUsecase, authMiddleware, slogLogger) - userRepo := repo4.NewUserRepo(client) - userUsecase := usecase3.NewUserUsecase(configConfig, redisClient, userRepo, slogLogger) - userHandler := v1_3.NewUserHandler(web, userUsecase, authMiddleware, sessionSession, slogLogger, configConfig) - dashboardRepo := repo5.NewDashboardRepo(client) - dashboardUsecase := usecase4.NewDashboardUsecase(dashboardRepo) + userRepo := repo5.NewUserRepo(client) + userUsecase := usecase4.NewUserUsecase(configConfig, redisClient, userRepo, slogLogger) + userHandler := v1_3.NewUserHandler(web, userUsecase, extensionUsecase, authMiddleware, sessionSession, slogLogger, configConfig) + dashboardRepo := repo6.NewDashboardRepo(client) + dashboardUsecase := usecase5.NewDashboardUsecase(dashboardRepo) dashboardHandler := v1_4.NewDashboardHandler(web, dashboardUsecase, authMiddleware) - billingRepo := repo6.NewBillingRepo(client) - billingUsecase := usecase5.NewBillingUsecase(billingRepo) + billingRepo := repo7.NewBillingRepo(client) + billingUsecase := usecase6.NewBillingUsecase(billingRepo) billingHandler := v1_5.NewBillingHandler(web, billingUsecase, authMiddleware) server := &Server{ config: configConfig, diff --git a/backend/config/config.go b/backend/config/config.go index f4080c5..e7030dc 100644 --- a/backend/config/config.go +++ b/backend/config/config.go @@ -57,15 +57,15 @@ type Config struct { RequestLogPath string `mapstructure:"request_log_path"` } `mapstructure:"llm_proxy"` - VSCode struct { - VSIXFile string `mapstructure:"vsix_file"` - } `mapstructure:"vscode"` - InitModel struct { ModelName string `mapstructure:"model_name"` ModelKey string `mapstructure:"model_key"` ModelURL string `mapstructure:"model_url"` } `mapstructure:"init_model"` + + Extension struct { + Baseurl string `mapstructure:"baseurl"` + } `mapstructure:"extension"` } func Init(dir string) (*Config, error) { diff --git a/backend/db/client.go b/backend/db/client.go index 8d703d4..659a2b2 100644 --- a/backend/db/client.go +++ b/backend/db/client.go @@ -23,6 +23,7 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/billingquota" "github.com/chaitin/MonkeyCode/backend/db/billingrecord" "github.com/chaitin/MonkeyCode/backend/db/billingusage" + "github.com/chaitin/MonkeyCode/backend/db/extension" "github.com/chaitin/MonkeyCode/backend/db/invitecode" "github.com/chaitin/MonkeyCode/backend/db/model" "github.com/chaitin/MonkeyCode/backend/db/modelprovider" @@ -56,6 +57,8 @@ type Client struct { BillingRecord *BillingRecordClient // BillingUsage is the client for interacting with the BillingUsage builders. BillingUsage *BillingUsageClient + // Extension is the client for interacting with the Extension builders. + Extension *ExtensionClient // InviteCode is the client for interacting with the InviteCode builders. InviteCode *InviteCodeClient // Model is the client for interacting with the Model builders. @@ -94,6 +97,7 @@ func (c *Client) init() { c.BillingQuota = NewBillingQuotaClient(c.config) c.BillingRecord = NewBillingRecordClient(c.config) c.BillingUsage = NewBillingUsageClient(c.config) + c.Extension = NewExtensionClient(c.config) c.InviteCode = NewInviteCodeClient(c.config) c.Model = NewModelClient(c.config) c.ModelProvider = NewModelProviderClient(c.config) @@ -203,6 +207,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { BillingQuota: NewBillingQuotaClient(cfg), BillingRecord: NewBillingRecordClient(cfg), BillingUsage: NewBillingUsageClient(cfg), + Extension: NewExtensionClient(cfg), InviteCode: NewInviteCodeClient(cfg), Model: NewModelClient(cfg), ModelProvider: NewModelProviderClient(cfg), @@ -239,6 +244,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) BillingQuota: NewBillingQuotaClient(cfg), BillingRecord: NewBillingRecordClient(cfg), BillingUsage: NewBillingUsageClient(cfg), + Extension: NewExtensionClient(cfg), InviteCode: NewInviteCodeClient(cfg), Model: NewModelClient(cfg), ModelProvider: NewModelProviderClient(cfg), @@ -279,9 +285,9 @@ 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.ModelProvider, - c.ModelProviderModel, c.Setting, c.Task, c.TaskRecord, c.User, c.UserIdentity, - c.UserLoginHistory, + c.BillingRecord, c.BillingUsage, c.Extension, c.InviteCode, c.Model, + c.ModelProvider, c.ModelProviderModel, c.Setting, c.Task, c.TaskRecord, c.User, + c.UserIdentity, c.UserLoginHistory, } { n.Use(hooks...) } @@ -292,9 +298,9 @@ 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.ModelProvider, - c.ModelProviderModel, c.Setting, c.Task, c.TaskRecord, c.User, c.UserIdentity, - c.UserLoginHistory, + c.BillingRecord, c.BillingUsage, c.Extension, c.InviteCode, c.Model, + c.ModelProvider, c.ModelProviderModel, c.Setting, c.Task, c.TaskRecord, c.User, + c.UserIdentity, c.UserLoginHistory, } { n.Intercept(interceptors...) } @@ -317,6 +323,8 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { return c.BillingRecord.mutate(ctx, m) case *BillingUsageMutation: return c.BillingUsage.mutate(ctx, m) + case *ExtensionMutation: + return c.Extension.mutate(ctx, m) case *InviteCodeMutation: return c.InviteCode.mutate(ctx, m) case *ModelMutation: @@ -1309,6 +1317,139 @@ func (c *BillingUsageClient) mutate(ctx context.Context, m *BillingUsageMutation } } +// ExtensionClient is a client for the Extension schema. +type ExtensionClient struct { + config +} + +// NewExtensionClient returns a client for the Extension from the given config. +func NewExtensionClient(c config) *ExtensionClient { + return &ExtensionClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `extension.Hooks(f(g(h())))`. +func (c *ExtensionClient) Use(hooks ...Hook) { + c.hooks.Extension = append(c.hooks.Extension, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `extension.Intercept(f(g(h())))`. +func (c *ExtensionClient) Intercept(interceptors ...Interceptor) { + c.inters.Extension = append(c.inters.Extension, interceptors...) +} + +// Create returns a builder for creating a Extension entity. +func (c *ExtensionClient) Create() *ExtensionCreate { + mutation := newExtensionMutation(c.config, OpCreate) + return &ExtensionCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Extension entities. +func (c *ExtensionClient) CreateBulk(builders ...*ExtensionCreate) *ExtensionCreateBulk { + return &ExtensionCreateBulk{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 *ExtensionClient) MapCreateBulk(slice any, setFunc func(*ExtensionCreate, int)) *ExtensionCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &ExtensionCreateBulk{err: fmt.Errorf("calling to ExtensionClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*ExtensionCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &ExtensionCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Extension. +func (c *ExtensionClient) Update() *ExtensionUpdate { + mutation := newExtensionMutation(c.config, OpUpdate) + return &ExtensionUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *ExtensionClient) UpdateOne(e *Extension) *ExtensionUpdateOne { + mutation := newExtensionMutation(c.config, OpUpdateOne, withExtension(e)) + return &ExtensionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *ExtensionClient) UpdateOneID(id uuid.UUID) *ExtensionUpdateOne { + mutation := newExtensionMutation(c.config, OpUpdateOne, withExtensionID(id)) + return &ExtensionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Extension. +func (c *ExtensionClient) Delete() *ExtensionDelete { + mutation := newExtensionMutation(c.config, OpDelete) + return &ExtensionDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *ExtensionClient) DeleteOne(e *Extension) *ExtensionDeleteOne { + return c.DeleteOneID(e.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *ExtensionClient) DeleteOneID(id uuid.UUID) *ExtensionDeleteOne { + builder := c.Delete().Where(extension.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &ExtensionDeleteOne{builder} +} + +// Query returns a query builder for Extension. +func (c *ExtensionClient) Query() *ExtensionQuery { + return &ExtensionQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeExtension}, + inters: c.Interceptors(), + } +} + +// Get returns a Extension entity by its id. +func (c *ExtensionClient) Get(ctx context.Context, id uuid.UUID) (*Extension, error) { + return c.Query().Where(extension.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *ExtensionClient) GetX(ctx context.Context, id uuid.UUID) *Extension { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *ExtensionClient) Hooks() []Hook { + return c.hooks.Extension +} + +// Interceptors returns the client interceptors. +func (c *ExtensionClient) Interceptors() []Interceptor { + return c.inters.Extension +} + +func (c *ExtensionClient) mutate(ctx context.Context, m *ExtensionMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&ExtensionCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&ExtensionUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&ExtensionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&ExtensionDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown Extension mutation op: %q", m.Op()) + } +} + // InviteCodeClient is a client for the InviteCode schema. type InviteCodeClient struct { config @@ -2871,13 +3012,14 @@ func (c *UserLoginHistoryClient) mutate(ctx context.Context, m *UserLoginHistory type ( hooks struct { Admin, AdminLoginHistory, ApiKey, BillingPlan, BillingQuota, BillingRecord, - BillingUsage, InviteCode, Model, ModelProvider, ModelProviderModel, Setting, - Task, TaskRecord, User, UserIdentity, UserLoginHistory []ent.Hook + BillingUsage, Extension, InviteCode, Model, ModelProvider, ModelProviderModel, + Setting, Task, TaskRecord, User, UserIdentity, UserLoginHistory []ent.Hook } inters struct { Admin, AdminLoginHistory, ApiKey, BillingPlan, BillingQuota, BillingRecord, - BillingUsage, InviteCode, Model, ModelProvider, ModelProviderModel, Setting, - Task, TaskRecord, User, UserIdentity, UserLoginHistory []ent.Interceptor + BillingUsage, Extension, InviteCode, Model, ModelProvider, ModelProviderModel, + Setting, Task, TaskRecord, User, UserIdentity, + UserLoginHistory []ent.Interceptor } ) diff --git a/backend/db/ent.go b/backend/db/ent.go index a96a362..318f11a 100644 --- a/backend/db/ent.go +++ b/backend/db/ent.go @@ -19,6 +19,7 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/billingquota" "github.com/chaitin/MonkeyCode/backend/db/billingrecord" "github.com/chaitin/MonkeyCode/backend/db/billingusage" + "github.com/chaitin/MonkeyCode/backend/db/extension" "github.com/chaitin/MonkeyCode/backend/db/invitecode" "github.com/chaitin/MonkeyCode/backend/db/model" "github.com/chaitin/MonkeyCode/backend/db/modelprovider" @@ -96,6 +97,7 @@ func checkColumn(table, column string) error { billingquota.Table: billingquota.ValidColumn, billingrecord.Table: billingrecord.ValidColumn, billingusage.Table: billingusage.ValidColumn, + extension.Table: extension.ValidColumn, invitecode.Table: invitecode.ValidColumn, model.Table: model.ValidColumn, modelprovider.Table: modelprovider.ValidColumn, diff --git a/backend/db/extension.go b/backend/db/extension.go new file mode 100644 index 0000000..ec70ba9 --- /dev/null +++ b/backend/db/extension.go @@ -0,0 +1,129 @@ +// 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/extension" + "github.com/google/uuid" +) + +// Extension is the model entity for the Extension schema. +type Extension struct { + config `json:"-"` + // ID of the ent. + ID uuid.UUID `json:"id,omitempty"` + // Version holds the value of the "version" field. + Version string `json:"version,omitempty"` + // Path holds the value of the "path" field. + Path string `json:"path,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Extension) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case extension.FieldVersion, extension.FieldPath: + values[i] = new(sql.NullString) + case extension.FieldCreatedAt: + values[i] = new(sql.NullTime) + case extension.FieldID: + values[i] = new(uuid.UUID) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the Extension fields. +func (e *Extension) 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 extension.FieldID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value != nil { + e.ID = *value + } + case extension.FieldVersion: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field version", values[i]) + } else if value.Valid { + e.Version = value.String + } + case extension.FieldPath: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field path", values[i]) + } else if value.Valid { + e.Path = value.String + } + case extension.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 { + e.CreatedAt = value.Time + } + default: + e.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the Extension. +// This includes values selected through modifiers, order, etc. +func (e *Extension) Value(name string) (ent.Value, error) { + return e.selectValues.Get(name) +} + +// Update returns a builder for updating this Extension. +// Note that you need to call Extension.Unwrap() before calling this method if this Extension +// was returned from a transaction, and the transaction was committed or rolled back. +func (e *Extension) Update() *ExtensionUpdateOne { + return NewExtensionClient(e.config).UpdateOne(e) +} + +// Unwrap unwraps the Extension 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 (e *Extension) Unwrap() *Extension { + _tx, ok := e.config.driver.(*txDriver) + if !ok { + panic("db: Extension is not a transactional entity") + } + e.config.driver = _tx.drv + return e +} + +// String implements the fmt.Stringer. +func (e *Extension) String() string { + var builder strings.Builder + builder.WriteString("Extension(") + builder.WriteString(fmt.Sprintf("id=%v, ", e.ID)) + builder.WriteString("version=") + builder.WriteString(e.Version) + builder.WriteString(", ") + builder.WriteString("path=") + builder.WriteString(e.Path) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(e.CreatedAt.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// Extensions is a parsable slice of Extension. +type Extensions []*Extension diff --git a/backend/db/extension/extension.go b/backend/db/extension/extension.go new file mode 100644 index 0000000..1625796 --- /dev/null +++ b/backend/db/extension/extension.go @@ -0,0 +1,70 @@ +// Code generated by ent, DO NOT EDIT. + +package extension + +import ( + "time" + + "entgo.io/ent/dialect/sql" +) + +const ( + // Label holds the string label denoting the extension type in the database. + Label = "extension" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldVersion holds the string denoting the version field in the database. + FieldVersion = "version" + // FieldPath holds the string denoting the path field in the database. + FieldPath = "path" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // Table holds the table name of the extension in the database. + Table = "extensions" +) + +// Columns holds all SQL columns for extension fields. +var Columns = []string{ + FieldID, + FieldVersion, + FieldPath, + FieldCreatedAt, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time +) + +// OrderOption defines the ordering options for the Extension 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() +} + +// ByVersion orders the results by the version field. +func ByVersion(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldVersion, opts...).ToFunc() +} + +// ByPath orders the results by the path field. +func ByPath(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPath, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} diff --git a/backend/db/extension/where.go b/backend/db/extension/where.go new file mode 100644 index 0000000..f28050e --- /dev/null +++ b/backend/db/extension/where.go @@ -0,0 +1,256 @@ +// Code generated by ent, DO NOT EDIT. + +package extension + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/google/uuid" +) + +// ID filters vertices based on their ID field. +func ID(id uuid.UUID) predicate.Extension { + return predicate.Extension(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id uuid.UUID) predicate.Extension { + return predicate.Extension(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id uuid.UUID) predicate.Extension { + return predicate.Extension(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...uuid.UUID) predicate.Extension { + return predicate.Extension(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...uuid.UUID) predicate.Extension { + return predicate.Extension(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id uuid.UUID) predicate.Extension { + return predicate.Extension(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id uuid.UUID) predicate.Extension { + return predicate.Extension(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id uuid.UUID) predicate.Extension { + return predicate.Extension(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id uuid.UUID) predicate.Extension { + return predicate.Extension(sql.FieldLTE(FieldID, id)) +} + +// Version applies equality check predicate on the "version" field. It's identical to VersionEQ. +func Version(v string) predicate.Extension { + return predicate.Extension(sql.FieldEQ(FieldVersion, v)) +} + +// Path applies equality check predicate on the "path" field. It's identical to PathEQ. +func Path(v string) predicate.Extension { + return predicate.Extension(sql.FieldEQ(FieldPath, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.Extension { + return predicate.Extension(sql.FieldEQ(FieldCreatedAt, v)) +} + +// VersionEQ applies the EQ predicate on the "version" field. +func VersionEQ(v string) predicate.Extension { + return predicate.Extension(sql.FieldEQ(FieldVersion, v)) +} + +// VersionNEQ applies the NEQ predicate on the "version" field. +func VersionNEQ(v string) predicate.Extension { + return predicate.Extension(sql.FieldNEQ(FieldVersion, v)) +} + +// VersionIn applies the In predicate on the "version" field. +func VersionIn(vs ...string) predicate.Extension { + return predicate.Extension(sql.FieldIn(FieldVersion, vs...)) +} + +// VersionNotIn applies the NotIn predicate on the "version" field. +func VersionNotIn(vs ...string) predicate.Extension { + return predicate.Extension(sql.FieldNotIn(FieldVersion, vs...)) +} + +// VersionGT applies the GT predicate on the "version" field. +func VersionGT(v string) predicate.Extension { + return predicate.Extension(sql.FieldGT(FieldVersion, v)) +} + +// VersionGTE applies the GTE predicate on the "version" field. +func VersionGTE(v string) predicate.Extension { + return predicate.Extension(sql.FieldGTE(FieldVersion, v)) +} + +// VersionLT applies the LT predicate on the "version" field. +func VersionLT(v string) predicate.Extension { + return predicate.Extension(sql.FieldLT(FieldVersion, v)) +} + +// VersionLTE applies the LTE predicate on the "version" field. +func VersionLTE(v string) predicate.Extension { + return predicate.Extension(sql.FieldLTE(FieldVersion, v)) +} + +// VersionContains applies the Contains predicate on the "version" field. +func VersionContains(v string) predicate.Extension { + return predicate.Extension(sql.FieldContains(FieldVersion, v)) +} + +// VersionHasPrefix applies the HasPrefix predicate on the "version" field. +func VersionHasPrefix(v string) predicate.Extension { + return predicate.Extension(sql.FieldHasPrefix(FieldVersion, v)) +} + +// VersionHasSuffix applies the HasSuffix predicate on the "version" field. +func VersionHasSuffix(v string) predicate.Extension { + return predicate.Extension(sql.FieldHasSuffix(FieldVersion, v)) +} + +// VersionEqualFold applies the EqualFold predicate on the "version" field. +func VersionEqualFold(v string) predicate.Extension { + return predicate.Extension(sql.FieldEqualFold(FieldVersion, v)) +} + +// VersionContainsFold applies the ContainsFold predicate on the "version" field. +func VersionContainsFold(v string) predicate.Extension { + return predicate.Extension(sql.FieldContainsFold(FieldVersion, v)) +} + +// PathEQ applies the EQ predicate on the "path" field. +func PathEQ(v string) predicate.Extension { + return predicate.Extension(sql.FieldEQ(FieldPath, v)) +} + +// PathNEQ applies the NEQ predicate on the "path" field. +func PathNEQ(v string) predicate.Extension { + return predicate.Extension(sql.FieldNEQ(FieldPath, v)) +} + +// PathIn applies the In predicate on the "path" field. +func PathIn(vs ...string) predicate.Extension { + return predicate.Extension(sql.FieldIn(FieldPath, vs...)) +} + +// PathNotIn applies the NotIn predicate on the "path" field. +func PathNotIn(vs ...string) predicate.Extension { + return predicate.Extension(sql.FieldNotIn(FieldPath, vs...)) +} + +// PathGT applies the GT predicate on the "path" field. +func PathGT(v string) predicate.Extension { + return predicate.Extension(sql.FieldGT(FieldPath, v)) +} + +// PathGTE applies the GTE predicate on the "path" field. +func PathGTE(v string) predicate.Extension { + return predicate.Extension(sql.FieldGTE(FieldPath, v)) +} + +// PathLT applies the LT predicate on the "path" field. +func PathLT(v string) predicate.Extension { + return predicate.Extension(sql.FieldLT(FieldPath, v)) +} + +// PathLTE applies the LTE predicate on the "path" field. +func PathLTE(v string) predicate.Extension { + return predicate.Extension(sql.FieldLTE(FieldPath, v)) +} + +// PathContains applies the Contains predicate on the "path" field. +func PathContains(v string) predicate.Extension { + return predicate.Extension(sql.FieldContains(FieldPath, v)) +} + +// PathHasPrefix applies the HasPrefix predicate on the "path" field. +func PathHasPrefix(v string) predicate.Extension { + return predicate.Extension(sql.FieldHasPrefix(FieldPath, v)) +} + +// PathHasSuffix applies the HasSuffix predicate on the "path" field. +func PathHasSuffix(v string) predicate.Extension { + return predicate.Extension(sql.FieldHasSuffix(FieldPath, v)) +} + +// PathEqualFold applies the EqualFold predicate on the "path" field. +func PathEqualFold(v string) predicate.Extension { + return predicate.Extension(sql.FieldEqualFold(FieldPath, v)) +} + +// PathContainsFold applies the ContainsFold predicate on the "path" field. +func PathContainsFold(v string) predicate.Extension { + return predicate.Extension(sql.FieldContainsFold(FieldPath, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.Extension { + return predicate.Extension(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.Extension { + return predicate.Extension(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.Extension { + return predicate.Extension(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.Extension { + return predicate.Extension(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.Extension { + return predicate.Extension(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.Extension { + return predicate.Extension(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.Extension { + return predicate.Extension(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.Extension { + return predicate.Extension(sql.FieldLTE(FieldCreatedAt, v)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.Extension) predicate.Extension { + return predicate.Extension(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Extension) predicate.Extension { + return predicate.Extension(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Extension) predicate.Extension { + return predicate.Extension(sql.NotPredicates(p)) +} diff --git a/backend/db/extension_create.go b/backend/db/extension_create.go new file mode 100644 index 0000000..0d0d956 --- /dev/null +++ b/backend/db/extension_create.go @@ -0,0 +1,615 @@ +// 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/extension" + "github.com/google/uuid" +) + +// ExtensionCreate is the builder for creating a Extension entity. +type ExtensionCreate struct { + config + mutation *ExtensionMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetVersion sets the "version" field. +func (ec *ExtensionCreate) SetVersion(s string) *ExtensionCreate { + ec.mutation.SetVersion(s) + return ec +} + +// SetPath sets the "path" field. +func (ec *ExtensionCreate) SetPath(s string) *ExtensionCreate { + ec.mutation.SetPath(s) + return ec +} + +// SetCreatedAt sets the "created_at" field. +func (ec *ExtensionCreate) SetCreatedAt(t time.Time) *ExtensionCreate { + ec.mutation.SetCreatedAt(t) + return ec +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (ec *ExtensionCreate) SetNillableCreatedAt(t *time.Time) *ExtensionCreate { + if t != nil { + ec.SetCreatedAt(*t) + } + return ec +} + +// SetID sets the "id" field. +func (ec *ExtensionCreate) SetID(u uuid.UUID) *ExtensionCreate { + ec.mutation.SetID(u) + return ec +} + +// Mutation returns the ExtensionMutation object of the builder. +func (ec *ExtensionCreate) Mutation() *ExtensionMutation { + return ec.mutation +} + +// Save creates the Extension in the database. +func (ec *ExtensionCreate) Save(ctx context.Context) (*Extension, error) { + ec.defaults() + return withHooks(ctx, ec.sqlSave, ec.mutation, ec.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (ec *ExtensionCreate) SaveX(ctx context.Context) *Extension { + v, err := ec.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (ec *ExtensionCreate) Exec(ctx context.Context) error { + _, err := ec.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ec *ExtensionCreate) ExecX(ctx context.Context) { + if err := ec.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (ec *ExtensionCreate) defaults() { + if _, ok := ec.mutation.CreatedAt(); !ok { + v := extension.DefaultCreatedAt() + ec.mutation.SetCreatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (ec *ExtensionCreate) check() error { + if _, ok := ec.mutation.Version(); !ok { + return &ValidationError{Name: "version", err: errors.New(`db: missing required field "Extension.version"`)} + } + if _, ok := ec.mutation.Path(); !ok { + return &ValidationError{Name: "path", err: errors.New(`db: missing required field "Extension.path"`)} + } + if _, ok := ec.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "Extension.created_at"`)} + } + return nil +} + +func (ec *ExtensionCreate) sqlSave(ctx context.Context) (*Extension, error) { + if err := ec.check(); err != nil { + return nil, err + } + _node, _spec := ec.createSpec() + if err := sqlgraph.CreateNode(ctx, ec.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 + } + } + ec.mutation.id = &_node.ID + ec.mutation.done = true + return _node, nil +} + +func (ec *ExtensionCreate) createSpec() (*Extension, *sqlgraph.CreateSpec) { + var ( + _node = &Extension{config: ec.config} + _spec = sqlgraph.NewCreateSpec(extension.Table, sqlgraph.NewFieldSpec(extension.FieldID, field.TypeUUID)) + ) + _spec.OnConflict = ec.conflict + if id, ok := ec.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = &id + } + if value, ok := ec.mutation.Version(); ok { + _spec.SetField(extension.FieldVersion, field.TypeString, value) + _node.Version = value + } + if value, ok := ec.mutation.Path(); ok { + _spec.SetField(extension.FieldPath, field.TypeString, value) + _node.Path = value + } + if value, ok := ec.mutation.CreatedAt(); ok { + _spec.SetField(extension.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.Extension.Create(). +// SetVersion(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.ExtensionUpsert) { +// SetVersion(v+v). +// }). +// Exec(ctx) +func (ec *ExtensionCreate) OnConflict(opts ...sql.ConflictOption) *ExtensionUpsertOne { + ec.conflict = opts + return &ExtensionUpsertOne{ + create: ec, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.Extension.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (ec *ExtensionCreate) OnConflictColumns(columns ...string) *ExtensionUpsertOne { + ec.conflict = append(ec.conflict, sql.ConflictColumns(columns...)) + return &ExtensionUpsertOne{ + create: ec, + } +} + +type ( + // ExtensionUpsertOne is the builder for "upsert"-ing + // one Extension node. + ExtensionUpsertOne struct { + create *ExtensionCreate + } + + // ExtensionUpsert is the "OnConflict" setter. + ExtensionUpsert struct { + *sql.UpdateSet + } +) + +// SetVersion sets the "version" field. +func (u *ExtensionUpsert) SetVersion(v string) *ExtensionUpsert { + u.Set(extension.FieldVersion, v) + return u +} + +// UpdateVersion sets the "version" field to the value that was provided on create. +func (u *ExtensionUpsert) UpdateVersion() *ExtensionUpsert { + u.SetExcluded(extension.FieldVersion) + return u +} + +// SetPath sets the "path" field. +func (u *ExtensionUpsert) SetPath(v string) *ExtensionUpsert { + u.Set(extension.FieldPath, v) + return u +} + +// UpdatePath sets the "path" field to the value that was provided on create. +func (u *ExtensionUpsert) UpdatePath() *ExtensionUpsert { + u.SetExcluded(extension.FieldPath) + return u +} + +// SetCreatedAt sets the "created_at" field. +func (u *ExtensionUpsert) SetCreatedAt(v time.Time) *ExtensionUpsert { + u.Set(extension.FieldCreatedAt, v) + return u +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *ExtensionUpsert) UpdateCreatedAt() *ExtensionUpsert { + u.SetExcluded(extension.FieldCreatedAt) + return u +} + +// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field. +// Using this option is equivalent to using: +// +// client.Extension.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(extension.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ExtensionUpsertOne) UpdateNewValues() *ExtensionUpsertOne { + 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(extension.FieldID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.Extension.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ExtensionUpsertOne) Ignore() *ExtensionUpsertOne { + 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 *ExtensionUpsertOne) DoNothing() *ExtensionUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ExtensionCreate.OnConflict +// documentation for more info. +func (u *ExtensionUpsertOne) Update(set func(*ExtensionUpsert)) *ExtensionUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ExtensionUpsert{UpdateSet: update}) + })) + return u +} + +// SetVersion sets the "version" field. +func (u *ExtensionUpsertOne) SetVersion(v string) *ExtensionUpsertOne { + return u.Update(func(s *ExtensionUpsert) { + s.SetVersion(v) + }) +} + +// UpdateVersion sets the "version" field to the value that was provided on create. +func (u *ExtensionUpsertOne) UpdateVersion() *ExtensionUpsertOne { + return u.Update(func(s *ExtensionUpsert) { + s.UpdateVersion() + }) +} + +// SetPath sets the "path" field. +func (u *ExtensionUpsertOne) SetPath(v string) *ExtensionUpsertOne { + return u.Update(func(s *ExtensionUpsert) { + s.SetPath(v) + }) +} + +// UpdatePath sets the "path" field to the value that was provided on create. +func (u *ExtensionUpsertOne) UpdatePath() *ExtensionUpsertOne { + return u.Update(func(s *ExtensionUpsert) { + s.UpdatePath() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *ExtensionUpsertOne) SetCreatedAt(v time.Time) *ExtensionUpsertOne { + return u.Update(func(s *ExtensionUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *ExtensionUpsertOne) UpdateCreatedAt() *ExtensionUpsertOne { + return u.Update(func(s *ExtensionUpsert) { + s.UpdateCreatedAt() + }) +} + +// Exec executes the query. +func (u *ExtensionUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for ExtensionCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ExtensionUpsertOne) 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 *ExtensionUpsertOne) 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: ExtensionUpsertOne.ID is not supported by MySQL driver. Use ExtensionUpsertOne.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 *ExtensionUpsertOne) IDX(ctx context.Context) uuid.UUID { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// ExtensionCreateBulk is the builder for creating many Extension entities in bulk. +type ExtensionCreateBulk struct { + config + err error + builders []*ExtensionCreate + conflict []sql.ConflictOption +} + +// Save creates the Extension entities in the database. +func (ecb *ExtensionCreateBulk) Save(ctx context.Context) ([]*Extension, error) { + if ecb.err != nil { + return nil, ecb.err + } + specs := make([]*sqlgraph.CreateSpec, len(ecb.builders)) + nodes := make([]*Extension, len(ecb.builders)) + mutators := make([]Mutator, len(ecb.builders)) + for i := range ecb.builders { + func(i int, root context.Context) { + builder := ecb.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*ExtensionMutation) + 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, ecb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = ecb.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, ecb.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, ecb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (ecb *ExtensionCreateBulk) SaveX(ctx context.Context) []*Extension { + v, err := ecb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (ecb *ExtensionCreateBulk) Exec(ctx context.Context) error { + _, err := ecb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ecb *ExtensionCreateBulk) ExecX(ctx context.Context) { + if err := ecb.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.Extension.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.ExtensionUpsert) { +// SetVersion(v+v). +// }). +// Exec(ctx) +func (ecb *ExtensionCreateBulk) OnConflict(opts ...sql.ConflictOption) *ExtensionUpsertBulk { + ecb.conflict = opts + return &ExtensionUpsertBulk{ + create: ecb, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.Extension.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (ecb *ExtensionCreateBulk) OnConflictColumns(columns ...string) *ExtensionUpsertBulk { + ecb.conflict = append(ecb.conflict, sql.ConflictColumns(columns...)) + return &ExtensionUpsertBulk{ + create: ecb, + } +} + +// ExtensionUpsertBulk is the builder for "upsert"-ing +// a bulk of Extension nodes. +type ExtensionUpsertBulk struct { + create *ExtensionCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.Extension.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(extension.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ExtensionUpsertBulk) UpdateNewValues() *ExtensionUpsertBulk { + 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(extension.FieldID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.Extension.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ExtensionUpsertBulk) Ignore() *ExtensionUpsertBulk { + 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 *ExtensionUpsertBulk) DoNothing() *ExtensionUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ExtensionCreateBulk.OnConflict +// documentation for more info. +func (u *ExtensionUpsertBulk) Update(set func(*ExtensionUpsert)) *ExtensionUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ExtensionUpsert{UpdateSet: update}) + })) + return u +} + +// SetVersion sets the "version" field. +func (u *ExtensionUpsertBulk) SetVersion(v string) *ExtensionUpsertBulk { + return u.Update(func(s *ExtensionUpsert) { + s.SetVersion(v) + }) +} + +// UpdateVersion sets the "version" field to the value that was provided on create. +func (u *ExtensionUpsertBulk) UpdateVersion() *ExtensionUpsertBulk { + return u.Update(func(s *ExtensionUpsert) { + s.UpdateVersion() + }) +} + +// SetPath sets the "path" field. +func (u *ExtensionUpsertBulk) SetPath(v string) *ExtensionUpsertBulk { + return u.Update(func(s *ExtensionUpsert) { + s.SetPath(v) + }) +} + +// UpdatePath sets the "path" field to the value that was provided on create. +func (u *ExtensionUpsertBulk) UpdatePath() *ExtensionUpsertBulk { + return u.Update(func(s *ExtensionUpsert) { + s.UpdatePath() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *ExtensionUpsertBulk) SetCreatedAt(v time.Time) *ExtensionUpsertBulk { + return u.Update(func(s *ExtensionUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *ExtensionUpsertBulk) UpdateCreatedAt() *ExtensionUpsertBulk { + return u.Update(func(s *ExtensionUpsert) { + s.UpdateCreatedAt() + }) +} + +// Exec executes the query. +func (u *ExtensionUpsertBulk) 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 ExtensionCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for ExtensionCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ExtensionUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/extension_delete.go b/backend/db/extension_delete.go new file mode 100644 index 0000000..053d281 --- /dev/null +++ b/backend/db/extension_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/extension" + "github.com/chaitin/MonkeyCode/backend/db/predicate" +) + +// ExtensionDelete is the builder for deleting a Extension entity. +type ExtensionDelete struct { + config + hooks []Hook + mutation *ExtensionMutation +} + +// Where appends a list predicates to the ExtensionDelete builder. +func (ed *ExtensionDelete) Where(ps ...predicate.Extension) *ExtensionDelete { + ed.mutation.Where(ps...) + return ed +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (ed *ExtensionDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, ed.sqlExec, ed.mutation, ed.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (ed *ExtensionDelete) ExecX(ctx context.Context) int { + n, err := ed.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (ed *ExtensionDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(extension.Table, sqlgraph.NewFieldSpec(extension.FieldID, field.TypeUUID)) + if ps := ed.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, ed.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + ed.mutation.done = true + return affected, err +} + +// ExtensionDeleteOne is the builder for deleting a single Extension entity. +type ExtensionDeleteOne struct { + ed *ExtensionDelete +} + +// Where appends a list predicates to the ExtensionDelete builder. +func (edo *ExtensionDeleteOne) Where(ps ...predicate.Extension) *ExtensionDeleteOne { + edo.ed.mutation.Where(ps...) + return edo +} + +// Exec executes the deletion query. +func (edo *ExtensionDeleteOne) Exec(ctx context.Context) error { + n, err := edo.ed.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{extension.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (edo *ExtensionDeleteOne) ExecX(ctx context.Context) { + if err := edo.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/extension_query.go b/backend/db/extension_query.go new file mode 100644 index 0000000..4c791ad --- /dev/null +++ b/backend/db/extension_query.go @@ -0,0 +1,578 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/extension" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/google/uuid" +) + +// ExtensionQuery is the builder for querying Extension entities. +type ExtensionQuery struct { + config + ctx *QueryContext + order []extension.OrderOption + inters []Interceptor + predicates []predicate.Extension + 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 ExtensionQuery builder. +func (eq *ExtensionQuery) Where(ps ...predicate.Extension) *ExtensionQuery { + eq.predicates = append(eq.predicates, ps...) + return eq +} + +// Limit the number of records to be returned by this query. +func (eq *ExtensionQuery) Limit(limit int) *ExtensionQuery { + eq.ctx.Limit = &limit + return eq +} + +// Offset to start from. +func (eq *ExtensionQuery) Offset(offset int) *ExtensionQuery { + eq.ctx.Offset = &offset + return eq +} + +// 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 (eq *ExtensionQuery) Unique(unique bool) *ExtensionQuery { + eq.ctx.Unique = &unique + return eq +} + +// Order specifies how the records should be ordered. +func (eq *ExtensionQuery) Order(o ...extension.OrderOption) *ExtensionQuery { + eq.order = append(eq.order, o...) + return eq +} + +// First returns the first Extension entity from the query. +// Returns a *NotFoundError when no Extension was found. +func (eq *ExtensionQuery) First(ctx context.Context) (*Extension, error) { + nodes, err := eq.Limit(1).All(setContextOp(ctx, eq.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{extension.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (eq *ExtensionQuery) FirstX(ctx context.Context) *Extension { + node, err := eq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Extension ID from the query. +// Returns a *NotFoundError when no Extension ID was found. +func (eq *ExtensionQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = eq.Limit(1).IDs(setContextOp(ctx, eq.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{extension.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (eq *ExtensionQuery) FirstIDX(ctx context.Context) uuid.UUID { + id, err := eq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Extension entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Extension entity is found. +// Returns a *NotFoundError when no Extension entities are found. +func (eq *ExtensionQuery) Only(ctx context.Context) (*Extension, error) { + nodes, err := eq.Limit(2).All(setContextOp(ctx, eq.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{extension.Label} + default: + return nil, &NotSingularError{extension.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (eq *ExtensionQuery) OnlyX(ctx context.Context) *Extension { + node, err := eq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Extension ID in the query. +// Returns a *NotSingularError when more than one Extension ID is found. +// Returns a *NotFoundError when no entities are found. +func (eq *ExtensionQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = eq.Limit(2).IDs(setContextOp(ctx, eq.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{extension.Label} + default: + err = &NotSingularError{extension.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (eq *ExtensionQuery) OnlyIDX(ctx context.Context) uuid.UUID { + id, err := eq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Extensions. +func (eq *ExtensionQuery) All(ctx context.Context) ([]*Extension, error) { + ctx = setContextOp(ctx, eq.ctx, ent.OpQueryAll) + if err := eq.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Extension, *ExtensionQuery]() + return withInterceptors[[]*Extension](ctx, eq, qr, eq.inters) +} + +// AllX is like All, but panics if an error occurs. +func (eq *ExtensionQuery) AllX(ctx context.Context) []*Extension { + nodes, err := eq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Extension IDs. +func (eq *ExtensionQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) { + if eq.ctx.Unique == nil && eq.path != nil { + eq.Unique(true) + } + ctx = setContextOp(ctx, eq.ctx, ent.OpQueryIDs) + if err = eq.Select(extension.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (eq *ExtensionQuery) IDsX(ctx context.Context) []uuid.UUID { + ids, err := eq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (eq *ExtensionQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, eq.ctx, ent.OpQueryCount) + if err := eq.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, eq, querierCount[*ExtensionQuery](), eq.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (eq *ExtensionQuery) CountX(ctx context.Context) int { + count, err := eq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (eq *ExtensionQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, eq.ctx, ent.OpQueryExist) + switch _, err := eq.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 (eq *ExtensionQuery) ExistX(ctx context.Context) bool { + exist, err := eq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the ExtensionQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (eq *ExtensionQuery) Clone() *ExtensionQuery { + if eq == nil { + return nil + } + return &ExtensionQuery{ + config: eq.config, + ctx: eq.ctx.Clone(), + order: append([]extension.OrderOption{}, eq.order...), + inters: append([]Interceptor{}, eq.inters...), + predicates: append([]predicate.Extension{}, eq.predicates...), + // clone intermediate query. + sql: eq.sql.Clone(), + path: eq.path, + modifiers: append([]func(*sql.Selector){}, eq.modifiers...), + } +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// Version string `json:"version,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Extension.Query(). +// GroupBy(extension.FieldVersion). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (eq *ExtensionQuery) GroupBy(field string, fields ...string) *ExtensionGroupBy { + eq.ctx.Fields = append([]string{field}, fields...) + grbuild := &ExtensionGroupBy{build: eq} + grbuild.flds = &eq.ctx.Fields + grbuild.label = extension.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 { +// Version string `json:"version,omitempty"` +// } +// +// client.Extension.Query(). +// Select(extension.FieldVersion). +// Scan(ctx, &v) +func (eq *ExtensionQuery) Select(fields ...string) *ExtensionSelect { + eq.ctx.Fields = append(eq.ctx.Fields, fields...) + sbuild := &ExtensionSelect{ExtensionQuery: eq} + sbuild.label = extension.Label + sbuild.flds, sbuild.scan = &eq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a ExtensionSelect configured with the given aggregations. +func (eq *ExtensionQuery) Aggregate(fns ...AggregateFunc) *ExtensionSelect { + return eq.Select().Aggregate(fns...) +} + +func (eq *ExtensionQuery) prepareQuery(ctx context.Context) error { + for _, inter := range eq.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, eq); err != nil { + return err + } + } + } + for _, f := range eq.ctx.Fields { + if !extension.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + } + if eq.path != nil { + prev, err := eq.path(ctx) + if err != nil { + return err + } + eq.sql = prev + } + return nil +} + +func (eq *ExtensionQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Extension, error) { + var ( + nodes = []*Extension{} + _spec = eq.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Extension).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Extension{config: eq.config} + nodes = append(nodes, node) + return node.assignValues(columns, values) + } + if len(eq.modifiers) > 0 { + _spec.Modifiers = eq.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, eq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (eq *ExtensionQuery) sqlCount(ctx context.Context) (int, error) { + _spec := eq.querySpec() + if len(eq.modifiers) > 0 { + _spec.Modifiers = eq.modifiers + } + _spec.Node.Columns = eq.ctx.Fields + if len(eq.ctx.Fields) > 0 { + _spec.Unique = eq.ctx.Unique != nil && *eq.ctx.Unique + } + return sqlgraph.CountNodes(ctx, eq.driver, _spec) +} + +func (eq *ExtensionQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(extension.Table, extension.Columns, sqlgraph.NewFieldSpec(extension.FieldID, field.TypeUUID)) + _spec.From = eq.sql + if unique := eq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if eq.path != nil { + _spec.Unique = true + } + if fields := eq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, extension.FieldID) + for i := range fields { + if fields[i] != extension.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := eq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := eq.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := eq.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := eq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (eq *ExtensionQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(eq.driver.Dialect()) + t1 := builder.Table(extension.Table) + columns := eq.ctx.Fields + if len(columns) == 0 { + columns = extension.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if eq.sql != nil { + selector = eq.sql + selector.Select(selector.Columns(columns...)...) + } + if eq.ctx.Unique != nil && *eq.ctx.Unique { + selector.Distinct() + } + for _, m := range eq.modifiers { + m(selector) + } + for _, p := range eq.predicates { + p(selector) + } + for _, p := range eq.order { + p(selector) + } + if offset := eq.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 := eq.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 (eq *ExtensionQuery) ForUpdate(opts ...sql.LockOption) *ExtensionQuery { + if eq.driver.Dialect() == dialect.Postgres { + eq.Unique(false) + } + eq.modifiers = append(eq.modifiers, func(s *sql.Selector) { + s.ForUpdate(opts...) + }) + return eq +} + +// 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 (eq *ExtensionQuery) ForShare(opts ...sql.LockOption) *ExtensionQuery { + if eq.driver.Dialect() == dialect.Postgres { + eq.Unique(false) + } + eq.modifiers = append(eq.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return eq +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (eq *ExtensionQuery) Modify(modifiers ...func(s *sql.Selector)) *ExtensionSelect { + eq.modifiers = append(eq.modifiers, modifiers...) + return eq.Select() +} + +// ExtensionGroupBy is the group-by builder for Extension entities. +type ExtensionGroupBy struct { + selector + build *ExtensionQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (egb *ExtensionGroupBy) Aggregate(fns ...AggregateFunc) *ExtensionGroupBy { + egb.fns = append(egb.fns, fns...) + return egb +} + +// Scan applies the selector query and scans the result into the given value. +func (egb *ExtensionGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, egb.build.ctx, ent.OpQueryGroupBy) + if err := egb.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*ExtensionQuery, *ExtensionGroupBy](ctx, egb.build, egb, egb.build.inters, v) +} + +func (egb *ExtensionGroupBy) sqlScan(ctx context.Context, root *ExtensionQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(egb.fns)) + for _, fn := range egb.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*egb.flds)+len(egb.fns)) + for _, f := range *egb.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*egb.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := egb.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// ExtensionSelect is the builder for selecting fields of Extension entities. +type ExtensionSelect struct { + *ExtensionQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (es *ExtensionSelect) Aggregate(fns ...AggregateFunc) *ExtensionSelect { + es.fns = append(es.fns, fns...) + return es +} + +// Scan applies the selector query and scans the result into the given value. +func (es *ExtensionSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, es.ctx, ent.OpQuerySelect) + if err := es.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*ExtensionQuery, *ExtensionSelect](ctx, es.ExtensionQuery, es, es.inters, v) +} + +func (es *ExtensionSelect) sqlScan(ctx context.Context, root *ExtensionQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(es.fns)) + for _, fn := range es.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*es.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 := es.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 (es *ExtensionSelect) Modify(modifiers ...func(s *sql.Selector)) *ExtensionSelect { + es.modifiers = append(es.modifiers, modifiers...) + return es +} diff --git a/backend/db/extension_update.go b/backend/db/extension_update.go new file mode 100644 index 0000000..aff3b1e --- /dev/null +++ b/backend/db/extension_update.go @@ -0,0 +1,294 @@ +// 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/extension" + "github.com/chaitin/MonkeyCode/backend/db/predicate" +) + +// ExtensionUpdate is the builder for updating Extension entities. +type ExtensionUpdate struct { + config + hooks []Hook + mutation *ExtensionMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the ExtensionUpdate builder. +func (eu *ExtensionUpdate) Where(ps ...predicate.Extension) *ExtensionUpdate { + eu.mutation.Where(ps...) + return eu +} + +// SetVersion sets the "version" field. +func (eu *ExtensionUpdate) SetVersion(s string) *ExtensionUpdate { + eu.mutation.SetVersion(s) + return eu +} + +// SetNillableVersion sets the "version" field if the given value is not nil. +func (eu *ExtensionUpdate) SetNillableVersion(s *string) *ExtensionUpdate { + if s != nil { + eu.SetVersion(*s) + } + return eu +} + +// SetPath sets the "path" field. +func (eu *ExtensionUpdate) SetPath(s string) *ExtensionUpdate { + eu.mutation.SetPath(s) + return eu +} + +// SetNillablePath sets the "path" field if the given value is not nil. +func (eu *ExtensionUpdate) SetNillablePath(s *string) *ExtensionUpdate { + if s != nil { + eu.SetPath(*s) + } + return eu +} + +// SetCreatedAt sets the "created_at" field. +func (eu *ExtensionUpdate) SetCreatedAt(t time.Time) *ExtensionUpdate { + eu.mutation.SetCreatedAt(t) + return eu +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (eu *ExtensionUpdate) SetNillableCreatedAt(t *time.Time) *ExtensionUpdate { + if t != nil { + eu.SetCreatedAt(*t) + } + return eu +} + +// Mutation returns the ExtensionMutation object of the builder. +func (eu *ExtensionUpdate) Mutation() *ExtensionMutation { + return eu.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (eu *ExtensionUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, eu.sqlSave, eu.mutation, eu.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (eu *ExtensionUpdate) SaveX(ctx context.Context) int { + affected, err := eu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (eu *ExtensionUpdate) Exec(ctx context.Context) error { + _, err := eu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (eu *ExtensionUpdate) ExecX(ctx context.Context) { + if err := eu.Exec(ctx); err != nil { + panic(err) + } +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (eu *ExtensionUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *ExtensionUpdate { + eu.modifiers = append(eu.modifiers, modifiers...) + return eu +} + +func (eu *ExtensionUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := sqlgraph.NewUpdateSpec(extension.Table, extension.Columns, sqlgraph.NewFieldSpec(extension.FieldID, field.TypeUUID)) + if ps := eu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := eu.mutation.Version(); ok { + _spec.SetField(extension.FieldVersion, field.TypeString, value) + } + if value, ok := eu.mutation.Path(); ok { + _spec.SetField(extension.FieldPath, field.TypeString, value) + } + if value, ok := eu.mutation.CreatedAt(); ok { + _spec.SetField(extension.FieldCreatedAt, field.TypeTime, value) + } + _spec.AddModifiers(eu.modifiers...) + if n, err = sqlgraph.UpdateNodes(ctx, eu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{extension.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + eu.mutation.done = true + return n, nil +} + +// ExtensionUpdateOne is the builder for updating a single Extension entity. +type ExtensionUpdateOne struct { + config + fields []string + hooks []Hook + mutation *ExtensionMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetVersion sets the "version" field. +func (euo *ExtensionUpdateOne) SetVersion(s string) *ExtensionUpdateOne { + euo.mutation.SetVersion(s) + return euo +} + +// SetNillableVersion sets the "version" field if the given value is not nil. +func (euo *ExtensionUpdateOne) SetNillableVersion(s *string) *ExtensionUpdateOne { + if s != nil { + euo.SetVersion(*s) + } + return euo +} + +// SetPath sets the "path" field. +func (euo *ExtensionUpdateOne) SetPath(s string) *ExtensionUpdateOne { + euo.mutation.SetPath(s) + return euo +} + +// SetNillablePath sets the "path" field if the given value is not nil. +func (euo *ExtensionUpdateOne) SetNillablePath(s *string) *ExtensionUpdateOne { + if s != nil { + euo.SetPath(*s) + } + return euo +} + +// SetCreatedAt sets the "created_at" field. +func (euo *ExtensionUpdateOne) SetCreatedAt(t time.Time) *ExtensionUpdateOne { + euo.mutation.SetCreatedAt(t) + return euo +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (euo *ExtensionUpdateOne) SetNillableCreatedAt(t *time.Time) *ExtensionUpdateOne { + if t != nil { + euo.SetCreatedAt(*t) + } + return euo +} + +// Mutation returns the ExtensionMutation object of the builder. +func (euo *ExtensionUpdateOne) Mutation() *ExtensionMutation { + return euo.mutation +} + +// Where appends a list predicates to the ExtensionUpdate builder. +func (euo *ExtensionUpdateOne) Where(ps ...predicate.Extension) *ExtensionUpdateOne { + euo.mutation.Where(ps...) + return euo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (euo *ExtensionUpdateOne) Select(field string, fields ...string) *ExtensionUpdateOne { + euo.fields = append([]string{field}, fields...) + return euo +} + +// Save executes the query and returns the updated Extension entity. +func (euo *ExtensionUpdateOne) Save(ctx context.Context) (*Extension, error) { + return withHooks(ctx, euo.sqlSave, euo.mutation, euo.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (euo *ExtensionUpdateOne) SaveX(ctx context.Context) *Extension { + node, err := euo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (euo *ExtensionUpdateOne) Exec(ctx context.Context) error { + _, err := euo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (euo *ExtensionUpdateOne) ExecX(ctx context.Context) { + if err := euo.Exec(ctx); err != nil { + panic(err) + } +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (euo *ExtensionUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *ExtensionUpdateOne { + euo.modifiers = append(euo.modifiers, modifiers...) + return euo +} + +func (euo *ExtensionUpdateOne) sqlSave(ctx context.Context) (_node *Extension, err error) { + _spec := sqlgraph.NewUpdateSpec(extension.Table, extension.Columns, sqlgraph.NewFieldSpec(extension.FieldID, field.TypeUUID)) + id, ok := euo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "Extension.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := euo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, extension.FieldID) + for _, f := range fields { + if !extension.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != extension.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := euo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := euo.mutation.Version(); ok { + _spec.SetField(extension.FieldVersion, field.TypeString, value) + } + if value, ok := euo.mutation.Path(); ok { + _spec.SetField(extension.FieldPath, field.TypeString, value) + } + if value, ok := euo.mutation.CreatedAt(); ok { + _spec.SetField(extension.FieldCreatedAt, field.TypeTime, value) + } + _spec.AddModifiers(euo.modifiers...) + _node = &Extension{config: euo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, euo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{extension.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + euo.mutation.done = true + return _node, nil +} diff --git a/backend/db/hook/hook.go b/backend/db/hook/hook.go index acf38f5..6c69838 100644 --- a/backend/db/hook/hook.go +++ b/backend/db/hook/hook.go @@ -93,6 +93,18 @@ func (f BillingUsageFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, return nil, fmt.Errorf("unexpected mutation type %T. expect *db.BillingUsageMutation", m) } +// The ExtensionFunc type is an adapter to allow the use of ordinary +// function as Extension mutator. +type ExtensionFunc func(context.Context, *db.ExtensionMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f ExtensionFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.ExtensionMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.ExtensionMutation", m) +} + // The InviteCodeFunc type is an adapter to allow the use of ordinary // function as InviteCode mutator. type InviteCodeFunc func(context.Context, *db.InviteCodeMutation) (db.Value, error) diff --git a/backend/db/intercept/intercept.go b/backend/db/intercept/intercept.go index 45cce4f..c8356eb 100644 --- a/backend/db/intercept/intercept.go +++ b/backend/db/intercept/intercept.go @@ -15,6 +15,7 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/billingquota" "github.com/chaitin/MonkeyCode/backend/db/billingrecord" "github.com/chaitin/MonkeyCode/backend/db/billingusage" + "github.com/chaitin/MonkeyCode/backend/db/extension" "github.com/chaitin/MonkeyCode/backend/db/invitecode" "github.com/chaitin/MonkeyCode/backend/db/model" "github.com/chaitin/MonkeyCode/backend/db/modelprovider" @@ -273,6 +274,33 @@ func (f TraverseBillingUsage) Traverse(ctx context.Context, q db.Query) error { return fmt.Errorf("unexpected query type %T. expect *db.BillingUsageQuery", q) } +// The ExtensionFunc type is an adapter to allow the use of ordinary function as a Querier. +type ExtensionFunc func(context.Context, *db.ExtensionQuery) (db.Value, error) + +// Query calls f(ctx, q). +func (f ExtensionFunc) Query(ctx context.Context, q db.Query) (db.Value, error) { + if q, ok := q.(*db.ExtensionQuery); ok { + return f(ctx, q) + } + return nil, fmt.Errorf("unexpected query type %T. expect *db.ExtensionQuery", q) +} + +// The TraverseExtension type is an adapter to allow the use of ordinary function as Traverser. +type TraverseExtension func(context.Context, *db.ExtensionQuery) error + +// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline. +func (f TraverseExtension) Intercept(next db.Querier) db.Querier { + return next +} + +// Traverse calls f(ctx, q). +func (f TraverseExtension) Traverse(ctx context.Context, q db.Query) error { + if q, ok := q.(*db.ExtensionQuery); ok { + return f(ctx, q) + } + return fmt.Errorf("unexpected query type %T. expect *db.ExtensionQuery", q) +} + // The InviteCodeFunc type is an adapter to allow the use of ordinary function as a Querier. type InviteCodeFunc func(context.Context, *db.InviteCodeQuery) (db.Value, error) @@ -560,6 +588,8 @@ func NewQuery(q db.Query) (Query, error) { return &query[*db.BillingRecordQuery, predicate.BillingRecord, billingrecord.OrderOption]{typ: db.TypeBillingRecord, tq: q}, nil case *db.BillingUsageQuery: return &query[*db.BillingUsageQuery, predicate.BillingUsage, billingusage.OrderOption]{typ: db.TypeBillingUsage, tq: q}, nil + case *db.ExtensionQuery: + return &query[*db.ExtensionQuery, predicate.Extension, extension.OrderOption]{typ: db.TypeExtension, tq: q}, nil case *db.InviteCodeQuery: return &query[*db.InviteCodeQuery, predicate.InviteCode, invitecode.OrderOption]{typ: db.TypeInviteCode, tq: q}, nil case *db.ModelQuery: diff --git a/backend/db/migrate/schema.go b/backend/db/migrate/schema.go index 91eb26f..0c15719 100644 --- a/backend/db/migrate/schema.go +++ b/backend/db/migrate/schema.go @@ -141,6 +141,19 @@ var ( Columns: BillingUsagesColumns, PrimaryKey: []*schema.Column{BillingUsagesColumns[0]}, } + // ExtensionsColumns holds the columns for the "extensions" table. + ExtensionsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeUUID}, + {Name: "version", Type: field.TypeString}, + {Name: "path", Type: field.TypeString}, + {Name: "created_at", Type: field.TypeTime}, + } + // ExtensionsTable holds the schema information for the "extensions" table. + ExtensionsTable = &schema.Table{ + Name: "extensions", + Columns: ExtensionsColumns, + PrimaryKey: []*schema.Column{ExtensionsColumns[0]}, + } // InviteCodesColumns holds the columns for the "invite_codes" table. InviteCodesColumns = []*schema.Column{ {Name: "id", Type: field.TypeUUID}, @@ -387,6 +400,7 @@ var ( BillingQuotasTable, BillingRecordsTable, BillingUsagesTable, + ExtensionsTable, InviteCodesTable, ModelsTable, ModelProvidersTable, @@ -423,6 +437,9 @@ func init() { BillingUsagesTable.Annotation = &entsql.Annotation{ Table: "billing_usages", } + ExtensionsTable.Annotation = &entsql.Annotation{ + Table: "extensions", + } InviteCodesTable.Annotation = &entsql.Annotation{ Table: "invite_codes", } diff --git a/backend/db/mutation.go b/backend/db/mutation.go index e57cc5e..5d0b18e 100644 --- a/backend/db/mutation.go +++ b/backend/db/mutation.go @@ -19,6 +19,7 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/billingquota" "github.com/chaitin/MonkeyCode/backend/db/billingrecord" "github.com/chaitin/MonkeyCode/backend/db/billingusage" + "github.com/chaitin/MonkeyCode/backend/db/extension" "github.com/chaitin/MonkeyCode/backend/db/invitecode" "github.com/chaitin/MonkeyCode/backend/db/model" "github.com/chaitin/MonkeyCode/backend/db/modelprovider" @@ -49,6 +50,7 @@ const ( TypeBillingQuota = "BillingQuota" TypeBillingRecord = "BillingRecord" TypeBillingUsage = "BillingUsage" + TypeExtension = "Extension" TypeInviteCode = "InviteCode" TypeModel = "Model" TypeModelProvider = "ModelProvider" @@ -5335,6 +5337,446 @@ func (m *BillingUsageMutation) ResetEdge(name string) error { return fmt.Errorf("unknown BillingUsage edge %s", name) } +// ExtensionMutation represents an operation that mutates the Extension nodes in the graph. +type ExtensionMutation struct { + config + op Op + typ string + id *uuid.UUID + version *string + _path *string + created_at *time.Time + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*Extension, error) + predicates []predicate.Extension +} + +var _ ent.Mutation = (*ExtensionMutation)(nil) + +// extensionOption allows management of the mutation configuration using functional options. +type extensionOption func(*ExtensionMutation) + +// newExtensionMutation creates new mutation for the Extension entity. +func newExtensionMutation(c config, op Op, opts ...extensionOption) *ExtensionMutation { + m := &ExtensionMutation{ + config: c, + op: op, + typ: TypeExtension, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withExtensionID sets the ID field of the mutation. +func withExtensionID(id uuid.UUID) extensionOption { + return func(m *ExtensionMutation) { + var ( + err error + once sync.Once + value *Extension + ) + m.oldValue = func(ctx context.Context) (*Extension, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Extension.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withExtension sets the old Extension of the mutation. +func withExtension(node *Extension) extensionOption { + return func(m *ExtensionMutation) { + m.oldValue = func(context.Context) (*Extension, 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 ExtensionMutation) 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 ExtensionMutation) 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 Extension entities. +func (m *ExtensionMutation) 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 *ExtensionMutation) 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 *ExtensionMutation) 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().Extension.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetVersion sets the "version" field. +func (m *ExtensionMutation) SetVersion(s string) { + m.version = &s +} + +// Version returns the value of the "version" field in the mutation. +func (m *ExtensionMutation) Version() (r string, exists bool) { + v := m.version + if v == nil { + return + } + return *v, true +} + +// OldVersion returns the old "version" field's value of the Extension entity. +// If the Extension 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 *ExtensionMutation) OldVersion(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldVersion is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldVersion requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldVersion: %w", err) + } + return oldValue.Version, nil +} + +// ResetVersion resets all changes to the "version" field. +func (m *ExtensionMutation) ResetVersion() { + m.version = nil +} + +// SetPath sets the "path" field. +func (m *ExtensionMutation) SetPath(s string) { + m._path = &s +} + +// Path returns the value of the "path" field in the mutation. +func (m *ExtensionMutation) Path() (r string, exists bool) { + v := m._path + if v == nil { + return + } + return *v, true +} + +// OldPath returns the old "path" field's value of the Extension entity. +// If the Extension 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 *ExtensionMutation) OldPath(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPath is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPath requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPath: %w", err) + } + return oldValue.Path, nil +} + +// ResetPath resets all changes to the "path" field. +func (m *ExtensionMutation) ResetPath() { + m._path = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *ExtensionMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *ExtensionMutation) 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 Extension entity. +// If the Extension 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 *ExtensionMutation) 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 *ExtensionMutation) ResetCreatedAt() { + m.created_at = nil +} + +// Where appends a list predicates to the ExtensionMutation builder. +func (m *ExtensionMutation) Where(ps ...predicate.Extension) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the ExtensionMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *ExtensionMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Extension, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *ExtensionMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *ExtensionMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Extension). +func (m *ExtensionMutation) 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 *ExtensionMutation) Fields() []string { + fields := make([]string, 0, 3) + if m.version != nil { + fields = append(fields, extension.FieldVersion) + } + if m._path != nil { + fields = append(fields, extension.FieldPath) + } + if m.created_at != nil { + fields = append(fields, extension.FieldCreatedAt) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *ExtensionMutation) Field(name string) (ent.Value, bool) { + switch name { + case extension.FieldVersion: + return m.Version() + case extension.FieldPath: + return m.Path() + case extension.FieldCreatedAt: + return m.CreatedAt() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *ExtensionMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case extension.FieldVersion: + return m.OldVersion(ctx) + case extension.FieldPath: + return m.OldPath(ctx) + case extension.FieldCreatedAt: + return m.OldCreatedAt(ctx) + } + return nil, fmt.Errorf("unknown Extension 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 *ExtensionMutation) SetField(name string, value ent.Value) error { + switch name { + case extension.FieldVersion: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetVersion(v) + return nil + case extension.FieldPath: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPath(v) + return nil + case extension.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + } + return fmt.Errorf("unknown Extension field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *ExtensionMutation) AddedFields() []string { + return nil +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *ExtensionMutation) AddedField(name string) (ent.Value, bool) { + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *ExtensionMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown Extension numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *ExtensionMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *ExtensionMutation) 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 *ExtensionMutation) ClearField(name string) error { + return fmt.Errorf("unknown Extension 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 *ExtensionMutation) ResetField(name string) error { + switch name { + case extension.FieldVersion: + m.ResetVersion() + return nil + case extension.FieldPath: + m.ResetPath() + return nil + case extension.FieldCreatedAt: + m.ResetCreatedAt() + return nil + } + return fmt.Errorf("unknown Extension field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *ExtensionMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *ExtensionMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *ExtensionMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *ExtensionMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *ExtensionMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *ExtensionMutation) EdgeCleared(name string) bool { + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *ExtensionMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown Extension 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 *ExtensionMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown Extension edge %s", name) +} + // InviteCodeMutation represents an operation that mutates the InviteCode nodes in the graph. type InviteCodeMutation struct { config diff --git a/backend/db/page.go b/backend/db/page.go index e4d4f3a..61bca73 100644 --- a/backend/db/page.go +++ b/backend/db/page.go @@ -109,6 +109,20 @@ func (bu *BillingUsageQuery) Page(ctx context.Context, page, size int) ([]*Billi return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil } +func (e *ExtensionQuery) Page(ctx context.Context, page, size int) ([]*Extension, *PageInfo, error) { + cnt, err := e.Count(ctx) + if err != nil { + return nil, nil, err + } + offset := size * (page - 1) + rs, err := e.Offset(offset).Limit(size).All(ctx) + if err != nil { + return nil, nil, err + } + has := (page * size) < cnt + return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil +} + func (ic *InviteCodeQuery) Page(ctx context.Context, page, size int) ([]*InviteCode, *PageInfo, error) { cnt, err := ic.Count(ctx) if err != nil { diff --git a/backend/db/predicate/predicate.go b/backend/db/predicate/predicate.go index 02da24f..3ee6c94 100644 --- a/backend/db/predicate/predicate.go +++ b/backend/db/predicate/predicate.go @@ -27,6 +27,9 @@ type BillingRecord func(*sql.Selector) // BillingUsage is the predicate function for billingusage builders. type BillingUsage func(*sql.Selector) +// Extension is the predicate function for extension builders. +type Extension func(*sql.Selector) + // InviteCode is the predicate function for invitecode builders. type InviteCode func(*sql.Selector) diff --git a/backend/db/runtime/runtime.go b/backend/db/runtime/runtime.go index 457ad00..246e327 100644 --- a/backend/db/runtime/runtime.go +++ b/backend/db/runtime/runtime.go @@ -13,6 +13,7 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/billingquota" "github.com/chaitin/MonkeyCode/backend/db/billingrecord" "github.com/chaitin/MonkeyCode/backend/db/billingusage" + "github.com/chaitin/MonkeyCode/backend/db/extension" "github.com/chaitin/MonkeyCode/backend/db/invitecode" "github.com/chaitin/MonkeyCode/backend/db/model" "github.com/chaitin/MonkeyCode/backend/db/modelprovider" @@ -131,6 +132,12 @@ func init() { billingusage.DefaultUpdatedAt = billingusageDescUpdatedAt.Default.(func() time.Time) // billingusage.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. billingusage.UpdateDefaultUpdatedAt = billingusageDescUpdatedAt.UpdateDefault.(func() time.Time) + extensionFields := schema.Extension{}.Fields() + _ = extensionFields + // extensionDescCreatedAt is the schema descriptor for created_at field. + extensionDescCreatedAt := extensionFields[3].Descriptor() + // extension.DefaultCreatedAt holds the default value on creation for the created_at field. + extension.DefaultCreatedAt = extensionDescCreatedAt.Default.(func() time.Time) invitecodeFields := schema.InviteCode{}.Fields() _ = invitecodeFields // invitecodeDescCreatedAt is the schema descriptor for created_at field. diff --git a/backend/db/tx.go b/backend/db/tx.go index b6fa6c3..9bd85f0 100644 --- a/backend/db/tx.go +++ b/backend/db/tx.go @@ -28,6 +28,8 @@ type Tx struct { BillingRecord *BillingRecordClient // BillingUsage is the client for interacting with the BillingUsage builders. BillingUsage *BillingUsageClient + // Extension is the client for interacting with the Extension builders. + Extension *ExtensionClient // InviteCode is the client for interacting with the InviteCode builders. InviteCode *InviteCodeClient // Model is the client for interacting with the Model builders. @@ -186,6 +188,7 @@ func (tx *Tx) init() { tx.BillingQuota = NewBillingQuotaClient(tx.config) tx.BillingRecord = NewBillingRecordClient(tx.config) tx.BillingUsage = NewBillingUsageClient(tx.config) + tx.Extension = NewExtensionClient(tx.config) tx.InviteCode = NewInviteCodeClient(tx.config) tx.Model = NewModelClient(tx.config) tx.ModelProvider = NewModelProviderClient(tx.config) diff --git a/backend/domain/extension.go b/backend/domain/extension.go new file mode 100644 index 0000000..ba970b8 --- /dev/null +++ b/backend/domain/extension.go @@ -0,0 +1,38 @@ +package domain + +import ( + "context" + + "github.com/google/uuid" + + "github.com/chaitin/MonkeyCode/backend/db" +) + +type ExtensionUsecase interface { + Latest(ctx context.Context) (*Extension, error) + GetByVersion(ctx context.Context, version string) (*Extension, error) +} + +type ExtensionRepo interface { + Latest(ctx context.Context) (*db.Extension, error) + Save(ctx context.Context, ext *db.Extension) (*db.Extension, error) + GetByVersion(ctx context.Context, version string) (*db.Extension, error) +} + +type Extension struct { + ID uuid.UUID `json:"id"` + Version string `json:"version"` + Path string `json:"path"` + CreatedAt int64 `json:"created_at"` +} + +func (et *Extension) From(e *db.Extension) *Extension { + if e == nil { + return et + } + et.ID = e.ID + et.Version = e.Version + et.Path = e.Path + et.CreatedAt = e.CreatedAt.Unix() + return et +} diff --git a/backend/domain/proxy.go b/backend/domain/proxy.go index 2b0bdbb..8ce36d8 100644 --- a/backend/domain/proxy.go +++ b/backend/domain/proxy.go @@ -32,6 +32,11 @@ type ProxyRepo interface { ValidateApiKey(ctx context.Context, key string) (*db.ApiKey, error) } +type VersionInfo struct { + Version string `json:"version"` + URL string `json:"url"` +} + type AcceptCompletionReq struct { ID string `json:"id"` // 记录ID Completion string `json:"completion"` // 补全内容 diff --git a/backend/ent/schema/extension.go b/backend/ent/schema/extension.go new file mode 100644 index 0000000..698dd44 --- /dev/null +++ b/backend/ent/schema/extension.go @@ -0,0 +1,39 @@ +package schema + +import ( + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/schema" + "entgo.io/ent/schema/field" + "github.com/google/uuid" +) + +// Extension holds the schema definition for the Extension entity. +type Extension struct { + ent.Schema +} + +func (Extension) Annotations() []schema.Annotation { + return []schema.Annotation{ + entsql.Annotation{ + Table: "extensions", + }, + } +} + +// Fields of the Extension. +func (Extension) Fields() []ent.Field { + return []ent.Field{ + field.UUID("id", uuid.UUID{}), + field.String("version"), + field.String("path"), + field.Time("created_at").Default(time.Now), + } +} + +// Edges of the Extension. +func (Extension) Edges() []ent.Edge { + return nil +} diff --git a/backend/internal/extension/repo/extension.go b/backend/internal/extension/repo/extension.go new file mode 100644 index 0000000..f26a659 --- /dev/null +++ b/backend/internal/extension/repo/extension.go @@ -0,0 +1,42 @@ +package repo + +import ( + "context" + + "entgo.io/ent/dialect/sql" + + "github.com/chaitin/MonkeyCode/backend/db" + "github.com/chaitin/MonkeyCode/backend/db/extension" + "github.com/chaitin/MonkeyCode/backend/domain" +) + +type ExtensionRepo struct { + db *db.Client +} + +func NewExtensionRepo(db *db.Client) domain.ExtensionRepo { + return &ExtensionRepo{ + db: db, + } +} + +// Latest implements domain.ExtensionRepo. +func (e *ExtensionRepo) Latest(ctx context.Context) (*db.Extension, error) { + return e.db.Extension. + Query(). + Order(extension.ByCreatedAt(sql.OrderDesc())). + Limit(1). + Only(ctx) +} + +// Save implements domain.ExtensionRepo. +func (e *ExtensionRepo) Save(ctx context.Context, ext *db.Extension) (*db.Extension, error) { + return e.db.Extension.Create(). + SetVersion(ext.Version). + SetPath(ext.Path). + Save(ctx) +} + +func (e *ExtensionRepo) GetByVersion(ctx context.Context, version string) (*db.Extension, error) { + return e.db.Extension.Query().Where(extension.Version(version)).Only(ctx) +} diff --git a/backend/internal/extension/usecase/extension.go b/backend/internal/extension/usecase/extension.go new file mode 100644 index 0000000..5e21fe9 --- /dev/null +++ b/backend/internal/extension/usecase/extension.go @@ -0,0 +1,146 @@ +package usecase + +import ( + "context" + "fmt" + "io" + "log/slog" + "net/http" + "os" + "sync" + "time" + + "github.com/chaitin/MonkeyCode/backend/config" + "github.com/chaitin/MonkeyCode/backend/db" + "github.com/chaitin/MonkeyCode/backend/domain" + "github.com/chaitin/MonkeyCode/backend/pkg/cvt" +) + +type ExtensionUsecase struct { + logger *slog.Logger + repo domain.ExtensionRepo + config *config.Config + version string + mu sync.Mutex +} + +func NewExtensionUsecase( + repo domain.ExtensionRepo, + config *config.Config, + logger *slog.Logger, +) domain.ExtensionUsecase { + e := &ExtensionUsecase{ + repo: repo, + config: config, + mu: sync.Mutex{}, + logger: logger, + } + go e.syncLatest() + return e +} + +// GetByVersion implements domain.ExtensionUsecase. +func (e *ExtensionUsecase) GetByVersion(ctx context.Context, version string) (*domain.Extension, error) { + ee, err := e.repo.GetByVersion(ctx, version) + if err != nil { + return nil, err + } + + return cvt.From(ee, &domain.Extension{}), nil +} + +// Latest implements domain.ExtensionUsecase. +func (e *ExtensionUsecase) Latest(ctx context.Context) (*domain.Extension, error) { + ee, err := e.repo.Latest(ctx) + if err != nil { + return nil, err + } + + return cvt.From(ee, &domain.Extension{}), nil +} + +func (e *ExtensionUsecase) syncLatest() { + latest, err := e.repo.Latest(context.Background()) + if err == nil { + e.version = latest.Version + } + + logger := e.logger.With("fn", "syncLatest") + logger.With("version", e.version).Debug("开始同步插件版本信息") + t := time.NewTicker(1 * time.Minute) + + e.innerSync() + for range t.C { + e.innerSync() + } +} + +func (e *ExtensionUsecase) innerSync() { + logger := e.logger.With("fn", "syncLatest") + v, err := e.getRemoteVersion() + if err != nil { + logger.With("error", err).Error("获取远程插件版本信息失败") + return + } + if v == e.version { + return + } + + e.download(v) +} + +func (e *ExtensionUsecase) download(version string) { + logger := e.logger.With("fn", "download") + url := fmt.Sprintf("%s/monkeycode/vsixs/monkeycode-%s.vsix", e.config.Extension.Baseurl, version) + logger.With("url", url).With("version", version).Debug("发现新版本,开始下载") + resp, err := http.Get(url) + if err != nil { + logger.With("error", err).Error("下载插件失败") + return + } + defer resp.Body.Close() + filename := fmt.Sprintf("/app/static/monkeycode-%s.vsix", version) + f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE, 0644) + if err != nil { + logger.With("error", err).Error("创建文件失败") + return + } + defer f.Close() + _, err = io.Copy(f, resp.Body) + if err != nil { + logger.With("error", err).Error("复制文件内容失败") + return + } + logger.Debug("下载插件成功") + + if _, err := e.repo.Save(context.Background(), &db.Extension{ + Version: version, + Path: filename, + }); err != nil { + logger.With("error", err).Error("保存插件版本信息失败") + os.Remove(filename) + return + } + e.version = version +} + +func (e *ExtensionUsecase) getRemoteVersion() (string, error) { + logger := e.logger.With("fn", "getRemoteVersion") + u := fmt.Sprintf("%s/monkeycode/vsix_version.txt", e.config.Extension.Baseurl) + logger.With("url", u).Debug("开始获取远程插件版本信息") + resp, err := http.Get(u) + if err != nil { + logger.With("error", err).Error("获取插件版本信息失败") + return "", err + } + defer resp.Body.Close() + + version, err := io.ReadAll(resp.Body) + if err != nil { + logger.With("error", err).Error("读取插件body信息失败") + return "", err + } + + logger.With("version", string(version)).Debug("读取到的插件版本信息") + return string(version), nil +} diff --git a/backend/internal/openai/handler/v1/v1.go b/backend/internal/openai/handler/v1/v1.go index 158c360..86684ab 100644 --- a/backend/internal/openai/handler/v1/v1.go +++ b/backend/internal/openai/handler/v1/v1.go @@ -1,6 +1,7 @@ package v1 import ( + "fmt" "log/slog" "net/http" @@ -9,6 +10,7 @@ import ( "github.com/GoYoko/web" + "github.com/chaitin/MonkeyCode/backend/config" "github.com/chaitin/MonkeyCode/backend/domain" "github.com/chaitin/MonkeyCode/backend/internal/middleware" ) @@ -17,6 +19,8 @@ type V1Handler struct { logger *slog.Logger proxy domain.Proxy usecase domain.OpenAIUsecase + euse domain.ExtensionUsecase + config *config.Config } func NewV1Handler( @@ -24,15 +28,20 @@ func NewV1Handler( w *web.Web, proxy domain.Proxy, usecase domain.OpenAIUsecase, + euse domain.ExtensionUsecase, middleware *middleware.ProxyMiddleware, active *middleware.ActiveMiddleware, + config *config.Config, ) *V1Handler { h := &V1Handler{ logger: logger.With(slog.String("handler", "openai")), proxy: proxy, usecase: usecase, + euse: euse, + config: config, } w.GET("/api/config", web.BindHandler(h.GetConfig), middleware.Auth()) + w.GET("/v1/version", web.BaseHandler(h.Version), middleware.Auth()) g := w.Group("/v1", middleware.Auth()) g.GET("/models", web.BaseHandler(h.ModelList)) @@ -53,6 +62,18 @@ func BadRequest(c *web.Context, msg string) error { return nil } +func (h *V1Handler) Version(c *web.Context) error { + v, err := h.euse.Latest(c.Request().Context()) + if err != nil { + return err + } + + return c.JSON(http.StatusOK, domain.VersionInfo{ + Version: v.Version, + URL: fmt.Sprintf("%s/api/v1/static/vsix/%s", h.config.BaseUrl, v.Version), + }) +} + // AcceptCompletion 接受补全请求 // // @Tags OpenAIV1 diff --git a/backend/internal/provider.go b/backend/internal/provider.go index 48a5862..e523709 100644 --- a/backend/internal/provider.go +++ b/backend/internal/provider.go @@ -9,6 +9,8 @@ import ( dashv1 "github.com/chaitin/MonkeyCode/backend/internal/dashboard/handler/v1" dashrepo "github.com/chaitin/MonkeyCode/backend/internal/dashboard/repo" dashusecase "github.com/chaitin/MonkeyCode/backend/internal/dashboard/usecase" + erepo "github.com/chaitin/MonkeyCode/backend/internal/extension/repo" + eusecase "github.com/chaitin/MonkeyCode/backend/internal/extension/usecase" "github.com/chaitin/MonkeyCode/backend/internal/middleware" modelv1 "github.com/chaitin/MonkeyCode/backend/internal/model/handler/http/v1" modelrepo "github.com/chaitin/MonkeyCode/backend/internal/model/repo" @@ -46,4 +48,6 @@ var Provider = wire.NewSet( billingv1.NewBillingHandler, billingrepo.NewBillingRepo, billingusecase.NewBillingUsecase, + erepo.NewExtensionRepo, + eusecase.NewExtensionUsecase, ) diff --git a/backend/internal/user/handler/v1/user.go b/backend/internal/user/handler/v1/user.go index 725c4de..73a0bbe 100644 --- a/backend/internal/user/handler/v1/user.go +++ b/backend/internal/user/handler/v1/user.go @@ -2,6 +2,7 @@ package v1 import ( "context" + "fmt" "log/slog" "net/http" @@ -18,6 +19,7 @@ import ( type UserHandler struct { usecase domain.UserUsecase + euse domain.ExtensionUsecase session *session.Session logger *slog.Logger cfg *config.Config @@ -26,6 +28,7 @@ type UserHandler struct { func NewUserHandler( w *web.Web, usecase domain.UserUsecase, + euse domain.ExtensionUsecase, auth *middleware.AuthMiddleware, session *session.Session, logger *slog.Logger, @@ -36,9 +39,10 @@ func NewUserHandler( session: session, logger: logger, cfg: cfg, + euse: euse, } - w.GET("/api/v1/static/vsix", web.BaseHandler(u.VSIXDownload)) + w.GET("/api/v1/static/vsix/:version", web.BaseHandler(u.VSIXDownload)) w.POST("/api/v1/vscode/init-auth", web.BindHandler(u.VSCodeAuthInit)) // admin @@ -88,9 +92,14 @@ func (h *UserHandler) VSCodeAuthInit(c *web.Context, req domain.VSCodeAuthInitRe // @Produce octet-stream // @Router /api/v1/static/vsix [get] func (h *UserHandler) VSIXDownload(c *web.Context) error { + v, err := h.euse.GetByVersion(c.Request().Context(), c.Param("version")) + if err != nil { + return err + } + disposition := fmt.Sprintf("attachment; filename=monkeycode-%s.vsix", v.Version) c.Response().Header().Set("Content-Type", "application/octet-stream") - c.Response().Header().Set("Content-Disposition", "attachment; filename=monkeycode.vsix") - if err := vsix.ChangeVsixEndpoint(h.cfg.VSCode.VSIXFile, "extension/package.json", h.cfg.BaseUrl, c.Response().Writer); err != nil { + c.Response().Header().Set("Content-Disposition", disposition) + if err := vsix.ChangeVsixEndpoint(v.Path, "extension/package.json", h.cfg.BaseUrl, c.Response().Writer); err != nil { return err } return nil diff --git a/backend/migration/000004_create_extensions_table.down.sql b/backend/migration/000004_create_extensions_table.down.sql new file mode 100644 index 0000000..e69de29 diff --git a/backend/migration/000004_create_extensions_table.up.sql b/backend/migration/000004_create_extensions_table.up.sql new file mode 100644 index 0000000..61f685a --- /dev/null +++ b/backend/migration/000004_create_extensions_table.up.sql @@ -0,0 +1,8 @@ +CREATE TABLE extensions ( + id UUID PRIMARY KEY DEFAULT uuid_generate_v1(), + version VARCHAR(255) NOT NULL, + path VARCHAR(1024) NOT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); + +CREATE UNIQUE INDEX unique_idx_extensions_version ON extensions(version); \ No newline at end of file