From e72a3678fb57a65c1a0d5946bb51aafb21b768d2 Mon Sep 17 00:00:00 2001 From: xmv97 Date: Fri, 5 Jun 2026 08:49:19 +0000 Subject: [PATCH 01/11] feat(ent+migration): mirror agent_* schemas for slim resources Mirror the 9 agent_* tables from mcai-backend as read-only ent schemas on the mcai-gh/backend side (shared Postgres consumer). Skill/plugin version tables keep s3_key; rule_versions intentionally omits s3_key / s3_synced_at (rule content is DB-authoritative, no S3 mirror). - ent/schema: agent_rule(+version), agent_skill_repo, agent_plugin_repo, agent_skill(+version), agent_plugin(+version), agent_sync_job - ent/types/agent_resources.go: SkillParsedMeta, PluginParsedMeta, PluginManualEntries, SyncJobErrors, SyncJobResultSummary jsonb GoTypes - migration/000011_agent_resources.{up,down}.sql: full schema with CHECK constraints + reverse FKs (rule_versions has no s3 columns) --- backend/db/agentplugin.go | 280 + backend/db/agentplugin/agentplugin.go | 239 + backend/db/agentplugin/where.go | 618 ++ backend/db/agentplugin_create.go | 1290 +++ backend/db/agentplugin_delete.go | 88 + backend/db/agentplugin_query.go | 732 ++ backend/db/agentplugin_update.go | 919 ++ backend/db/agentpluginrepo.go | 352 + backend/db/agentpluginrepo/agentpluginrepo.go | 305 + backend/db/agentpluginrepo/where.go | 1015 ++ backend/db/agentpluginrepo_create.go | 1752 ++++ backend/db/agentpluginrepo_delete.go | 88 + backend/db/agentpluginrepo_query.go | 657 ++ backend/db/agentpluginrepo_update.go | 1196 +++ backend/db/agentpluginversion.go | 186 + .../agentpluginversion/agentpluginversion.go | 112 + backend/db/agentpluginversion/where.go | 315 + backend/db/agentpluginversion_create.go | 797 ++ backend/db/agentpluginversion_delete.go | 88 + backend/db/agentpluginversion_query.go | 657 ++ backend/db/agentpluginversion_update.go | 511 + backend/db/agentrule.go | 228 + backend/db/agentrule/agentrule.go | 188 + backend/db/agentrule/where.go | 540 + backend/db/agentrule_create.go | 1085 ++ backend/db/agentrule_delete.go | 88 + backend/db/agentrule_query.go | 657 ++ backend/db/agentrule_update.go | 736 ++ backend/db/agentruleversion.go | 169 + .../db/agentruleversion/agentruleversion.go | 107 + backend/db/agentruleversion/where.go | 305 + backend/db/agentruleversion_create.go | 707 ++ backend/db/agentruleversion_delete.go | 88 + backend/db/agentruleversion_query.go | 657 ++ backend/db/agentruleversion_update.go | 436 + backend/db/agentskill.go | 280 + backend/db/agentskill/agentskill.go | 239 + backend/db/agentskill/where.go | 618 ++ backend/db/agentskill_create.go | 1290 +++ backend/db/agentskill_delete.go | 88 + backend/db/agentskill_query.go | 732 ++ backend/db/agentskill_update.go | 919 ++ backend/db/agentskillrepo.go | 282 + backend/db/agentskillrepo/agentskillrepo.go | 267 + backend/db/agentskillrepo/where.go | 750 ++ backend/db/agentskillrepo_create.go | 1382 +++ backend/db/agentskillrepo_delete.go | 88 + backend/db/agentskillrepo_query.go | 657 ++ backend/db/agentskillrepo_update.go | 946 ++ backend/db/agentskillversion.go | 186 + .../db/agentskillversion/agentskillversion.go | 112 + backend/db/agentskillversion/where.go | 315 + backend/db/agentskillversion_create.go | 797 ++ backend/db/agentskillversion_delete.go | 88 + backend/db/agentskillversion_query.go | 657 ++ backend/db/agentskillversion_update.go | 511 + backend/db/agentsyncjob.go | 264 + backend/db/agentsyncjob/agentsyncjob.go | 251 + backend/db/agentsyncjob/where.go | 536 + backend/db/agentsyncjob_create.go | 1369 +++ backend/db/agentsyncjob_delete.go | 88 + backend/db/agentsyncjob_query.go | 578 ++ backend/db/agentsyncjob_update.go | 827 ++ backend/db/client.go | 1459 ++- backend/db/ent.go | 18 + backend/db/hook/hook.go | 108 + backend/db/intercept/intercept.go | 270 + backend/db/migrate/schema.go | 360 + backend/db/mutation.go | 8788 +++++++++++++++++ backend/db/page.go | 126 + backend/db/predicate/predicate.go | 27 + backend/db/runtime/runtime.go | 249 + backend/db/tx.go | 29 +- backend/ent/schema/agent_plugin.go | 99 + backend/ent/schema/agent_plugin_repo.go | 70 + backend/ent/schema/agent_rule.go | 91 + backend/ent/schema/agent_skill.go | 99 + backend/ent/schema/agent_skill_repo.go | 61 + backend/ent/schema/agent_sync_job.go | 59 + backend/ent/types/agent_resources.go | 40 + .../migration/000011_agent_resources.down.sql | 21 + .../migration/000011_agent_resources.up.sql | 286 + 82 files changed, 45553 insertions(+), 12 deletions(-) create mode 100644 backend/db/agentplugin.go create mode 100644 backend/db/agentplugin/agentplugin.go create mode 100644 backend/db/agentplugin/where.go create mode 100644 backend/db/agentplugin_create.go create mode 100644 backend/db/agentplugin_delete.go create mode 100644 backend/db/agentplugin_query.go create mode 100644 backend/db/agentplugin_update.go create mode 100644 backend/db/agentpluginrepo.go create mode 100644 backend/db/agentpluginrepo/agentpluginrepo.go create mode 100644 backend/db/agentpluginrepo/where.go create mode 100644 backend/db/agentpluginrepo_create.go create mode 100644 backend/db/agentpluginrepo_delete.go create mode 100644 backend/db/agentpluginrepo_query.go create mode 100644 backend/db/agentpluginrepo_update.go create mode 100644 backend/db/agentpluginversion.go create mode 100644 backend/db/agentpluginversion/agentpluginversion.go create mode 100644 backend/db/agentpluginversion/where.go create mode 100644 backend/db/agentpluginversion_create.go create mode 100644 backend/db/agentpluginversion_delete.go create mode 100644 backend/db/agentpluginversion_query.go create mode 100644 backend/db/agentpluginversion_update.go create mode 100644 backend/db/agentrule.go create mode 100644 backend/db/agentrule/agentrule.go create mode 100644 backend/db/agentrule/where.go create mode 100644 backend/db/agentrule_create.go create mode 100644 backend/db/agentrule_delete.go create mode 100644 backend/db/agentrule_query.go create mode 100644 backend/db/agentrule_update.go create mode 100644 backend/db/agentruleversion.go create mode 100644 backend/db/agentruleversion/agentruleversion.go create mode 100644 backend/db/agentruleversion/where.go create mode 100644 backend/db/agentruleversion_create.go create mode 100644 backend/db/agentruleversion_delete.go create mode 100644 backend/db/agentruleversion_query.go create mode 100644 backend/db/agentruleversion_update.go create mode 100644 backend/db/agentskill.go create mode 100644 backend/db/agentskill/agentskill.go create mode 100644 backend/db/agentskill/where.go create mode 100644 backend/db/agentskill_create.go create mode 100644 backend/db/agentskill_delete.go create mode 100644 backend/db/agentskill_query.go create mode 100644 backend/db/agentskill_update.go create mode 100644 backend/db/agentskillrepo.go create mode 100644 backend/db/agentskillrepo/agentskillrepo.go create mode 100644 backend/db/agentskillrepo/where.go create mode 100644 backend/db/agentskillrepo_create.go create mode 100644 backend/db/agentskillrepo_delete.go create mode 100644 backend/db/agentskillrepo_query.go create mode 100644 backend/db/agentskillrepo_update.go create mode 100644 backend/db/agentskillversion.go create mode 100644 backend/db/agentskillversion/agentskillversion.go create mode 100644 backend/db/agentskillversion/where.go create mode 100644 backend/db/agentskillversion_create.go create mode 100644 backend/db/agentskillversion_delete.go create mode 100644 backend/db/agentskillversion_query.go create mode 100644 backend/db/agentskillversion_update.go create mode 100644 backend/db/agentsyncjob.go create mode 100644 backend/db/agentsyncjob/agentsyncjob.go create mode 100644 backend/db/agentsyncjob/where.go create mode 100644 backend/db/agentsyncjob_create.go create mode 100644 backend/db/agentsyncjob_delete.go create mode 100644 backend/db/agentsyncjob_query.go create mode 100644 backend/db/agentsyncjob_update.go create mode 100644 backend/ent/schema/agent_plugin.go create mode 100644 backend/ent/schema/agent_plugin_repo.go create mode 100644 backend/ent/schema/agent_rule.go create mode 100644 backend/ent/schema/agent_skill.go create mode 100644 backend/ent/schema/agent_skill_repo.go create mode 100644 backend/ent/schema/agent_sync_job.go create mode 100644 backend/ent/types/agent_resources.go create mode 100644 backend/migration/000011_agent_resources.down.sql create mode 100644 backend/migration/000011_agent_resources.up.sql diff --git a/backend/db/agentplugin.go b/backend/db/agentplugin.go new file mode 100644 index 00000000..ef923717 --- /dev/null +++ b/backend/db/agentplugin.go @@ -0,0 +1,280 @@ +// 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/agentplugin" + "github.com/chaitin/MonkeyCode/backend/db/agentpluginrepo" + "github.com/google/uuid" +) + +// AgentPlugin is the model entity for the AgentPlugin schema. +type AgentPlugin struct { + config `json:"-"` + // ID of the ent. + ID uuid.UUID `json:"id,omitempty"` + // RepoID holds the value of the "repo_id" field. + RepoID uuid.UUID `json:"repo_id,omitempty"` + // Name holds the value of the "name" field. + Name string `json:"name,omitempty"` + // Description holds the value of the "description" field. + Description string `json:"description,omitempty"` + // ScopeType holds the value of the "scope_type" field. + ScopeType agentplugin.ScopeType `json:"scope_type,omitempty"` + // ScopeID holds the value of the "scope_id" field. + ScopeID string `json:"scope_id,omitempty"` + // CreatedBy holds the value of the "created_by" field. + CreatedBy uuid.UUID `json:"created_by,omitempty"` + // ActiveVersionID holds the value of the "active_version_id" field. + ActiveVersionID *uuid.UUID `json:"active_version_id,omitempty"` + // IsForceDelivery holds the value of the "is_force_delivery" field. + IsForceDelivery bool `json:"is_force_delivery,omitempty"` + // IsOrphan holds the value of the "is_orphan" field. + IsOrphan bool `json:"is_orphan,omitempty"` + // IsDeleted holds the value of the "is_deleted" field. + IsDeleted bool `json:"is_deleted,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + // UpdatedAt holds the value of the "updated_at" field. + UpdatedAt time.Time `json:"updated_at,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the AgentPluginQuery when eager-loading is set. + Edges AgentPluginEdges `json:"edges"` + selectValues sql.SelectValues +} + +// AgentPluginEdges holds the relations/edges for other nodes in the graph. +type AgentPluginEdges struct { + // Repo holds the value of the repo edge. + Repo *AgentPluginRepo `json:"repo,omitempty"` + // Versions holds the value of the versions edge. + Versions []*AgentPluginVersion `json:"versions,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool +} + +// RepoOrErr returns the Repo value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e AgentPluginEdges) RepoOrErr() (*AgentPluginRepo, error) { + if e.Repo != nil { + return e.Repo, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: agentpluginrepo.Label} + } + return nil, &NotLoadedError{edge: "repo"} +} + +// VersionsOrErr returns the Versions value or an error if the edge +// was not loaded in eager-loading. +func (e AgentPluginEdges) VersionsOrErr() ([]*AgentPluginVersion, error) { + if e.loadedTypes[1] { + return e.Versions, nil + } + return nil, &NotLoadedError{edge: "versions"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*AgentPlugin) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case agentplugin.FieldActiveVersionID: + values[i] = &sql.NullScanner{S: new(uuid.UUID)} + case agentplugin.FieldIsForceDelivery, agentplugin.FieldIsOrphan, agentplugin.FieldIsDeleted: + values[i] = new(sql.NullBool) + case agentplugin.FieldName, agentplugin.FieldDescription, agentplugin.FieldScopeType, agentplugin.FieldScopeID: + values[i] = new(sql.NullString) + case agentplugin.FieldCreatedAt, agentplugin.FieldUpdatedAt: + values[i] = new(sql.NullTime) + case agentplugin.FieldID, agentplugin.FieldRepoID, agentplugin.FieldCreatedBy: + 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 AgentPlugin fields. +func (_m *AgentPlugin) 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 agentplugin.FieldID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value != nil { + _m.ID = *value + } + case agentplugin.FieldRepoID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field repo_id", values[i]) + } else if value != nil { + _m.RepoID = *value + } + case agentplugin.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + _m.Name = value.String + } + case agentplugin.FieldDescription: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field description", values[i]) + } else if value.Valid { + _m.Description = value.String + } + case agentplugin.FieldScopeType: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field scope_type", values[i]) + } else if value.Valid { + _m.ScopeType = agentplugin.ScopeType(value.String) + } + case agentplugin.FieldScopeID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field scope_id", values[i]) + } else if value.Valid { + _m.ScopeID = value.String + } + case agentplugin.FieldCreatedBy: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field created_by", values[i]) + } else if value != nil { + _m.CreatedBy = *value + } + case agentplugin.FieldActiveVersionID: + if value, ok := values[i].(*sql.NullScanner); !ok { + return fmt.Errorf("unexpected type %T for field active_version_id", values[i]) + } else if value.Valid { + _m.ActiveVersionID = new(uuid.UUID) + *_m.ActiveVersionID = *value.S.(*uuid.UUID) + } + case agentplugin.FieldIsForceDelivery: + if value, ok := values[i].(*sql.NullBool); !ok { + return fmt.Errorf("unexpected type %T for field is_force_delivery", values[i]) + } else if value.Valid { + _m.IsForceDelivery = value.Bool + } + case agentplugin.FieldIsOrphan: + if value, ok := values[i].(*sql.NullBool); !ok { + return fmt.Errorf("unexpected type %T for field is_orphan", values[i]) + } else if value.Valid { + _m.IsOrphan = value.Bool + } + case agentplugin.FieldIsDeleted: + if value, ok := values[i].(*sql.NullBool); !ok { + return fmt.Errorf("unexpected type %T for field is_deleted", values[i]) + } else if value.Valid { + _m.IsDeleted = value.Bool + } + case agentplugin.FieldCreatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field created_at", values[i]) + } else if value.Valid { + _m.CreatedAt = value.Time + } + case agentplugin.FieldUpdatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field updated_at", values[i]) + } else if value.Valid { + _m.UpdatedAt = value.Time + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the AgentPlugin. +// This includes values selected through modifiers, order, etc. +func (_m *AgentPlugin) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryRepo queries the "repo" edge of the AgentPlugin entity. +func (_m *AgentPlugin) QueryRepo() *AgentPluginRepoQuery { + return NewAgentPluginClient(_m.config).QueryRepo(_m) +} + +// QueryVersions queries the "versions" edge of the AgentPlugin entity. +func (_m *AgentPlugin) QueryVersions() *AgentPluginVersionQuery { + return NewAgentPluginClient(_m.config).QueryVersions(_m) +} + +// Update returns a builder for updating this AgentPlugin. +// Note that you need to call AgentPlugin.Unwrap() before calling this method if this AgentPlugin +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *AgentPlugin) Update() *AgentPluginUpdateOne { + return NewAgentPluginClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the AgentPlugin entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (_m *AgentPlugin) Unwrap() *AgentPlugin { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: AgentPlugin is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *AgentPlugin) String() string { + var builder strings.Builder + builder.WriteString("AgentPlugin(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("repo_id=") + builder.WriteString(fmt.Sprintf("%v", _m.RepoID)) + builder.WriteString(", ") + builder.WriteString("name=") + builder.WriteString(_m.Name) + builder.WriteString(", ") + builder.WriteString("description=") + builder.WriteString(_m.Description) + builder.WriteString(", ") + builder.WriteString("scope_type=") + builder.WriteString(fmt.Sprintf("%v", _m.ScopeType)) + builder.WriteString(", ") + builder.WriteString("scope_id=") + builder.WriteString(_m.ScopeID) + builder.WriteString(", ") + builder.WriteString("created_by=") + builder.WriteString(fmt.Sprintf("%v", _m.CreatedBy)) + builder.WriteString(", ") + if v := _m.ActiveVersionID; v != nil { + builder.WriteString("active_version_id=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + builder.WriteString("is_force_delivery=") + builder.WriteString(fmt.Sprintf("%v", _m.IsForceDelivery)) + builder.WriteString(", ") + builder.WriteString("is_orphan=") + builder.WriteString(fmt.Sprintf("%v", _m.IsOrphan)) + builder.WriteString(", ") + builder.WriteString("is_deleted=") + builder.WriteString(fmt.Sprintf("%v", _m.IsDeleted)) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("updated_at=") + builder.WriteString(_m.UpdatedAt.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// AgentPlugins is a parsable slice of AgentPlugin. +type AgentPlugins []*AgentPlugin diff --git a/backend/db/agentplugin/agentplugin.go b/backend/db/agentplugin/agentplugin.go new file mode 100644 index 00000000..1fc37772 --- /dev/null +++ b/backend/db/agentplugin/agentplugin.go @@ -0,0 +1,239 @@ +// Code generated by ent, DO NOT EDIT. + +package agentplugin + +import ( + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/google/uuid" +) + +const ( + // Label holds the string label denoting the agentplugin type in the database. + Label = "agent_plugin" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldRepoID holds the string denoting the repo_id field in the database. + FieldRepoID = "repo_id" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldDescription holds the string denoting the description field in the database. + FieldDescription = "description" + // FieldScopeType holds the string denoting the scope_type field in the database. + FieldScopeType = "scope_type" + // FieldScopeID holds the string denoting the scope_id field in the database. + FieldScopeID = "scope_id" + // FieldCreatedBy holds the string denoting the created_by field in the database. + FieldCreatedBy = "created_by" + // FieldActiveVersionID holds the string denoting the active_version_id field in the database. + FieldActiveVersionID = "active_version_id" + // FieldIsForceDelivery holds the string denoting the is_force_delivery field in the database. + FieldIsForceDelivery = "is_force_delivery" + // FieldIsOrphan holds the string denoting the is_orphan field in the database. + FieldIsOrphan = "is_orphan" + // FieldIsDeleted holds the string denoting the is_deleted field in the database. + FieldIsDeleted = "is_deleted" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // FieldUpdatedAt holds the string denoting the updated_at field in the database. + FieldUpdatedAt = "updated_at" + // EdgeRepo holds the string denoting the repo edge name in mutations. + EdgeRepo = "repo" + // EdgeVersions holds the string denoting the versions edge name in mutations. + EdgeVersions = "versions" + // Table holds the table name of the agentplugin in the database. + Table = "agent_plugins" + // RepoTable is the table that holds the repo relation/edge. + RepoTable = "agent_plugins" + // RepoInverseTable is the table name for the AgentPluginRepo entity. + // It exists in this package in order to avoid circular dependency with the "agentpluginrepo" package. + RepoInverseTable = "agent_plugin_repos" + // RepoColumn is the table column denoting the repo relation/edge. + RepoColumn = "repo_id" + // VersionsTable is the table that holds the versions relation/edge. + VersionsTable = "agent_plugin_versions" + // VersionsInverseTable is the table name for the AgentPluginVersion entity. + // It exists in this package in order to avoid circular dependency with the "agentpluginversion" package. + VersionsInverseTable = "agent_plugin_versions" + // VersionsColumn is the table column denoting the versions relation/edge. + VersionsColumn = "resource_id" +) + +// Columns holds all SQL columns for agentplugin fields. +var Columns = []string{ + FieldID, + FieldRepoID, + FieldName, + FieldDescription, + FieldScopeType, + FieldScopeID, + FieldCreatedBy, + FieldActiveVersionID, + FieldIsForceDelivery, + FieldIsOrphan, + FieldIsDeleted, + FieldCreatedAt, + FieldUpdatedAt, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // NameValidator is a validator for the "name" field. It is called by the builders before save. + NameValidator func(string) error + // DefaultScopeID holds the default value on creation for the "scope_id" field. + DefaultScopeID string + // DefaultIsForceDelivery holds the default value on creation for the "is_force_delivery" field. + DefaultIsForceDelivery bool + // DefaultIsOrphan holds the default value on creation for the "is_orphan" field. + DefaultIsOrphan bool + // DefaultIsDeleted holds the default value on creation for the "is_deleted" field. + DefaultIsDeleted bool + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time + // DefaultUpdatedAt holds the default value on creation for the "updated_at" field. + DefaultUpdatedAt func() time.Time + // UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field. + UpdateDefaultUpdatedAt func() time.Time + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() uuid.UUID +) + +// ScopeType defines the type for the "scope_type" enum field. +type ScopeType string + +// ScopeTypeGlobal is the default value of the ScopeType enum. +const DefaultScopeType = ScopeTypeGlobal + +// ScopeType values. +const ( + ScopeTypeGlobal ScopeType = "global" +) + +func (st ScopeType) String() string { + return string(st) +} + +// ScopeTypeValidator is a validator for the "scope_type" field enum values. It is called by the builders before save. +func ScopeTypeValidator(st ScopeType) error { + switch st { + case ScopeTypeGlobal: + return nil + default: + return fmt.Errorf("agentplugin: invalid enum value for scope_type field: %q", st) + } +} + +// OrderOption defines the ordering options for the AgentPlugin 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() +} + +// ByRepoID orders the results by the repo_id field. +func ByRepoID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRepoID, opts...).ToFunc() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} + +// ByDescription orders the results by the description field. +func ByDescription(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDescription, opts...).ToFunc() +} + +// ByScopeType orders the results by the scope_type field. +func ByScopeType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldScopeType, opts...).ToFunc() +} + +// ByScopeID orders the results by the scope_id field. +func ByScopeID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldScopeID, opts...).ToFunc() +} + +// ByCreatedBy orders the results by the created_by field. +func ByCreatedBy(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedBy, opts...).ToFunc() +} + +// ByActiveVersionID orders the results by the active_version_id field. +func ByActiveVersionID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldActiveVersionID, opts...).ToFunc() +} + +// ByIsForceDelivery orders the results by the is_force_delivery field. +func ByIsForceDelivery(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldIsForceDelivery, opts...).ToFunc() +} + +// ByIsOrphan orders the results by the is_orphan field. +func ByIsOrphan(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldIsOrphan, opts...).ToFunc() +} + +// ByIsDeleted orders the results by the is_deleted field. +func ByIsDeleted(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldIsDeleted, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// ByUpdatedAt orders the results by the updated_at field. +func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc() +} + +// ByRepoField orders the results by repo field. +func ByRepoField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newRepoStep(), sql.OrderByField(field, opts...)) + } +} + +// ByVersionsCount orders the results by versions count. +func ByVersionsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newVersionsStep(), opts...) + } +} + +// ByVersions orders the results by versions terms. +func ByVersions(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newVersionsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newRepoStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(RepoInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, RepoTable, RepoColumn), + ) +} +func newVersionsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(VersionsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, VersionsTable, VersionsColumn), + ) +} diff --git a/backend/db/agentplugin/where.go b/backend/db/agentplugin/where.go new file mode 100644 index 00000000..7f8cc898 --- /dev/null +++ b/backend/db/agentplugin/where.go @@ -0,0 +1,618 @@ +// Code generated by ent, DO NOT EDIT. + +package agentplugin + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/google/uuid" +) + +// ID filters vertices based on their ID field. +func ID(id uuid.UUID) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id uuid.UUID) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id uuid.UUID) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...uuid.UUID) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...uuid.UUID) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id uuid.UUID) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id uuid.UUID) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id uuid.UUID) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id uuid.UUID) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldLTE(FieldID, id)) +} + +// RepoID applies equality check predicate on the "repo_id" field. It's identical to RepoIDEQ. +func RepoID(v uuid.UUID) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldEQ(FieldRepoID, v)) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldEQ(FieldName, v)) +} + +// Description applies equality check predicate on the "description" field. It's identical to DescriptionEQ. +func Description(v string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldEQ(FieldDescription, v)) +} + +// ScopeID applies equality check predicate on the "scope_id" field. It's identical to ScopeIDEQ. +func ScopeID(v string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldEQ(FieldScopeID, v)) +} + +// CreatedBy applies equality check predicate on the "created_by" field. It's identical to CreatedByEQ. +func CreatedBy(v uuid.UUID) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldEQ(FieldCreatedBy, v)) +} + +// ActiveVersionID applies equality check predicate on the "active_version_id" field. It's identical to ActiveVersionIDEQ. +func ActiveVersionID(v uuid.UUID) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldEQ(FieldActiveVersionID, v)) +} + +// IsForceDelivery applies equality check predicate on the "is_force_delivery" field. It's identical to IsForceDeliveryEQ. +func IsForceDelivery(v bool) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldEQ(FieldIsForceDelivery, v)) +} + +// IsOrphan applies equality check predicate on the "is_orphan" field. It's identical to IsOrphanEQ. +func IsOrphan(v bool) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldEQ(FieldIsOrphan, v)) +} + +// IsDeleted applies equality check predicate on the "is_deleted" field. It's identical to IsDeletedEQ. +func IsDeleted(v bool) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldEQ(FieldIsDeleted, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldEQ(FieldCreatedAt, v)) +} + +// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ. +func UpdatedAt(v time.Time) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// RepoIDEQ applies the EQ predicate on the "repo_id" field. +func RepoIDEQ(v uuid.UUID) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldEQ(FieldRepoID, v)) +} + +// RepoIDNEQ applies the NEQ predicate on the "repo_id" field. +func RepoIDNEQ(v uuid.UUID) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldNEQ(FieldRepoID, v)) +} + +// RepoIDIn applies the In predicate on the "repo_id" field. +func RepoIDIn(vs ...uuid.UUID) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldIn(FieldRepoID, vs...)) +} + +// RepoIDNotIn applies the NotIn predicate on the "repo_id" field. +func RepoIDNotIn(vs ...uuid.UUID) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldNotIn(FieldRepoID, vs...)) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldEQ(FieldName, v)) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldNEQ(FieldName, v)) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldIn(FieldName, vs...)) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldNotIn(FieldName, vs...)) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldGT(FieldName, v)) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldGTE(FieldName, v)) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldLT(FieldName, v)) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldLTE(FieldName, v)) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldContains(FieldName, v)) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldHasPrefix(FieldName, v)) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldHasSuffix(FieldName, v)) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldEqualFold(FieldName, v)) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldContainsFold(FieldName, v)) +} + +// DescriptionEQ applies the EQ predicate on the "description" field. +func DescriptionEQ(v string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldEQ(FieldDescription, v)) +} + +// DescriptionNEQ applies the NEQ predicate on the "description" field. +func DescriptionNEQ(v string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldNEQ(FieldDescription, v)) +} + +// DescriptionIn applies the In predicate on the "description" field. +func DescriptionIn(vs ...string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldIn(FieldDescription, vs...)) +} + +// DescriptionNotIn applies the NotIn predicate on the "description" field. +func DescriptionNotIn(vs ...string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldNotIn(FieldDescription, vs...)) +} + +// DescriptionGT applies the GT predicate on the "description" field. +func DescriptionGT(v string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldGT(FieldDescription, v)) +} + +// DescriptionGTE applies the GTE predicate on the "description" field. +func DescriptionGTE(v string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldGTE(FieldDescription, v)) +} + +// DescriptionLT applies the LT predicate on the "description" field. +func DescriptionLT(v string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldLT(FieldDescription, v)) +} + +// DescriptionLTE applies the LTE predicate on the "description" field. +func DescriptionLTE(v string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldLTE(FieldDescription, v)) +} + +// DescriptionContains applies the Contains predicate on the "description" field. +func DescriptionContains(v string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldContains(FieldDescription, v)) +} + +// DescriptionHasPrefix applies the HasPrefix predicate on the "description" field. +func DescriptionHasPrefix(v string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldHasPrefix(FieldDescription, v)) +} + +// DescriptionHasSuffix applies the HasSuffix predicate on the "description" field. +func DescriptionHasSuffix(v string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldHasSuffix(FieldDescription, v)) +} + +// DescriptionIsNil applies the IsNil predicate on the "description" field. +func DescriptionIsNil() predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldIsNull(FieldDescription)) +} + +// DescriptionNotNil applies the NotNil predicate on the "description" field. +func DescriptionNotNil() predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldNotNull(FieldDescription)) +} + +// DescriptionEqualFold applies the EqualFold predicate on the "description" field. +func DescriptionEqualFold(v string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldEqualFold(FieldDescription, v)) +} + +// DescriptionContainsFold applies the ContainsFold predicate on the "description" field. +func DescriptionContainsFold(v string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldContainsFold(FieldDescription, v)) +} + +// ScopeTypeEQ applies the EQ predicate on the "scope_type" field. +func ScopeTypeEQ(v ScopeType) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldEQ(FieldScopeType, v)) +} + +// ScopeTypeNEQ applies the NEQ predicate on the "scope_type" field. +func ScopeTypeNEQ(v ScopeType) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldNEQ(FieldScopeType, v)) +} + +// ScopeTypeIn applies the In predicate on the "scope_type" field. +func ScopeTypeIn(vs ...ScopeType) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldIn(FieldScopeType, vs...)) +} + +// ScopeTypeNotIn applies the NotIn predicate on the "scope_type" field. +func ScopeTypeNotIn(vs ...ScopeType) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldNotIn(FieldScopeType, vs...)) +} + +// ScopeIDEQ applies the EQ predicate on the "scope_id" field. +func ScopeIDEQ(v string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldEQ(FieldScopeID, v)) +} + +// ScopeIDNEQ applies the NEQ predicate on the "scope_id" field. +func ScopeIDNEQ(v string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldNEQ(FieldScopeID, v)) +} + +// ScopeIDIn applies the In predicate on the "scope_id" field. +func ScopeIDIn(vs ...string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldIn(FieldScopeID, vs...)) +} + +// ScopeIDNotIn applies the NotIn predicate on the "scope_id" field. +func ScopeIDNotIn(vs ...string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldNotIn(FieldScopeID, vs...)) +} + +// ScopeIDGT applies the GT predicate on the "scope_id" field. +func ScopeIDGT(v string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldGT(FieldScopeID, v)) +} + +// ScopeIDGTE applies the GTE predicate on the "scope_id" field. +func ScopeIDGTE(v string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldGTE(FieldScopeID, v)) +} + +// ScopeIDLT applies the LT predicate on the "scope_id" field. +func ScopeIDLT(v string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldLT(FieldScopeID, v)) +} + +// ScopeIDLTE applies the LTE predicate on the "scope_id" field. +func ScopeIDLTE(v string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldLTE(FieldScopeID, v)) +} + +// ScopeIDContains applies the Contains predicate on the "scope_id" field. +func ScopeIDContains(v string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldContains(FieldScopeID, v)) +} + +// ScopeIDHasPrefix applies the HasPrefix predicate on the "scope_id" field. +func ScopeIDHasPrefix(v string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldHasPrefix(FieldScopeID, v)) +} + +// ScopeIDHasSuffix applies the HasSuffix predicate on the "scope_id" field. +func ScopeIDHasSuffix(v string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldHasSuffix(FieldScopeID, v)) +} + +// ScopeIDEqualFold applies the EqualFold predicate on the "scope_id" field. +func ScopeIDEqualFold(v string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldEqualFold(FieldScopeID, v)) +} + +// ScopeIDContainsFold applies the ContainsFold predicate on the "scope_id" field. +func ScopeIDContainsFold(v string) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldContainsFold(FieldScopeID, v)) +} + +// CreatedByEQ applies the EQ predicate on the "created_by" field. +func CreatedByEQ(v uuid.UUID) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldEQ(FieldCreatedBy, v)) +} + +// CreatedByNEQ applies the NEQ predicate on the "created_by" field. +func CreatedByNEQ(v uuid.UUID) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldNEQ(FieldCreatedBy, v)) +} + +// CreatedByIn applies the In predicate on the "created_by" field. +func CreatedByIn(vs ...uuid.UUID) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldIn(FieldCreatedBy, vs...)) +} + +// CreatedByNotIn applies the NotIn predicate on the "created_by" field. +func CreatedByNotIn(vs ...uuid.UUID) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldNotIn(FieldCreatedBy, vs...)) +} + +// CreatedByGT applies the GT predicate on the "created_by" field. +func CreatedByGT(v uuid.UUID) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldGT(FieldCreatedBy, v)) +} + +// CreatedByGTE applies the GTE predicate on the "created_by" field. +func CreatedByGTE(v uuid.UUID) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldGTE(FieldCreatedBy, v)) +} + +// CreatedByLT applies the LT predicate on the "created_by" field. +func CreatedByLT(v uuid.UUID) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldLT(FieldCreatedBy, v)) +} + +// CreatedByLTE applies the LTE predicate on the "created_by" field. +func CreatedByLTE(v uuid.UUID) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldLTE(FieldCreatedBy, v)) +} + +// ActiveVersionIDEQ applies the EQ predicate on the "active_version_id" field. +func ActiveVersionIDEQ(v uuid.UUID) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldEQ(FieldActiveVersionID, v)) +} + +// ActiveVersionIDNEQ applies the NEQ predicate on the "active_version_id" field. +func ActiveVersionIDNEQ(v uuid.UUID) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldNEQ(FieldActiveVersionID, v)) +} + +// ActiveVersionIDIn applies the In predicate on the "active_version_id" field. +func ActiveVersionIDIn(vs ...uuid.UUID) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldIn(FieldActiveVersionID, vs...)) +} + +// ActiveVersionIDNotIn applies the NotIn predicate on the "active_version_id" field. +func ActiveVersionIDNotIn(vs ...uuid.UUID) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldNotIn(FieldActiveVersionID, vs...)) +} + +// ActiveVersionIDGT applies the GT predicate on the "active_version_id" field. +func ActiveVersionIDGT(v uuid.UUID) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldGT(FieldActiveVersionID, v)) +} + +// ActiveVersionIDGTE applies the GTE predicate on the "active_version_id" field. +func ActiveVersionIDGTE(v uuid.UUID) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldGTE(FieldActiveVersionID, v)) +} + +// ActiveVersionIDLT applies the LT predicate on the "active_version_id" field. +func ActiveVersionIDLT(v uuid.UUID) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldLT(FieldActiveVersionID, v)) +} + +// ActiveVersionIDLTE applies the LTE predicate on the "active_version_id" field. +func ActiveVersionIDLTE(v uuid.UUID) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldLTE(FieldActiveVersionID, v)) +} + +// ActiveVersionIDIsNil applies the IsNil predicate on the "active_version_id" field. +func ActiveVersionIDIsNil() predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldIsNull(FieldActiveVersionID)) +} + +// ActiveVersionIDNotNil applies the NotNil predicate on the "active_version_id" field. +func ActiveVersionIDNotNil() predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldNotNull(FieldActiveVersionID)) +} + +// IsForceDeliveryEQ applies the EQ predicate on the "is_force_delivery" field. +func IsForceDeliveryEQ(v bool) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldEQ(FieldIsForceDelivery, v)) +} + +// IsForceDeliveryNEQ applies the NEQ predicate on the "is_force_delivery" field. +func IsForceDeliveryNEQ(v bool) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldNEQ(FieldIsForceDelivery, v)) +} + +// IsOrphanEQ applies the EQ predicate on the "is_orphan" field. +func IsOrphanEQ(v bool) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldEQ(FieldIsOrphan, v)) +} + +// IsOrphanNEQ applies the NEQ predicate on the "is_orphan" field. +func IsOrphanNEQ(v bool) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldNEQ(FieldIsOrphan, v)) +} + +// IsDeletedEQ applies the EQ predicate on the "is_deleted" field. +func IsDeletedEQ(v bool) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldEQ(FieldIsDeleted, v)) +} + +// IsDeletedNEQ applies the NEQ predicate on the "is_deleted" field. +func IsDeletedNEQ(v bool) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldNEQ(FieldIsDeleted, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// HasRepo applies the HasEdge predicate on the "repo" edge. +func HasRepo() predicate.AgentPlugin { + return predicate.AgentPlugin(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, RepoTable, RepoColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasRepoWith applies the HasEdge predicate on the "repo" edge with a given conditions (other predicates). +func HasRepoWith(preds ...predicate.AgentPluginRepo) predicate.AgentPlugin { + return predicate.AgentPlugin(func(s *sql.Selector) { + step := newRepoStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasVersions applies the HasEdge predicate on the "versions" edge. +func HasVersions() predicate.AgentPlugin { + return predicate.AgentPlugin(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, VersionsTable, VersionsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasVersionsWith applies the HasEdge predicate on the "versions" edge with a given conditions (other predicates). +func HasVersionsWith(preds ...predicate.AgentPluginVersion) predicate.AgentPlugin { + return predicate.AgentPlugin(func(s *sql.Selector) { + step := newVersionsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.AgentPlugin) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.AgentPlugin) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.AgentPlugin) predicate.AgentPlugin { + return predicate.AgentPlugin(sql.NotPredicates(p)) +} diff --git a/backend/db/agentplugin_create.go b/backend/db/agentplugin_create.go new file mode 100644 index 00000000..20517804 --- /dev/null +++ b/backend/db/agentplugin_create.go @@ -0,0 +1,1290 @@ +// 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/agentplugin" + "github.com/chaitin/MonkeyCode/backend/db/agentpluginrepo" + "github.com/chaitin/MonkeyCode/backend/db/agentpluginversion" + "github.com/google/uuid" +) + +// AgentPluginCreate is the builder for creating a AgentPlugin entity. +type AgentPluginCreate struct { + config + mutation *AgentPluginMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetRepoID sets the "repo_id" field. +func (_c *AgentPluginCreate) SetRepoID(v uuid.UUID) *AgentPluginCreate { + _c.mutation.SetRepoID(v) + return _c +} + +// SetName sets the "name" field. +func (_c *AgentPluginCreate) SetName(v string) *AgentPluginCreate { + _c.mutation.SetName(v) + return _c +} + +// SetDescription sets the "description" field. +func (_c *AgentPluginCreate) SetDescription(v string) *AgentPluginCreate { + _c.mutation.SetDescription(v) + return _c +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_c *AgentPluginCreate) SetNillableDescription(v *string) *AgentPluginCreate { + if v != nil { + _c.SetDescription(*v) + } + return _c +} + +// SetScopeType sets the "scope_type" field. +func (_c *AgentPluginCreate) SetScopeType(v agentplugin.ScopeType) *AgentPluginCreate { + _c.mutation.SetScopeType(v) + return _c +} + +// SetNillableScopeType sets the "scope_type" field if the given value is not nil. +func (_c *AgentPluginCreate) SetNillableScopeType(v *agentplugin.ScopeType) *AgentPluginCreate { + if v != nil { + _c.SetScopeType(*v) + } + return _c +} + +// SetScopeID sets the "scope_id" field. +func (_c *AgentPluginCreate) SetScopeID(v string) *AgentPluginCreate { + _c.mutation.SetScopeID(v) + return _c +} + +// SetNillableScopeID sets the "scope_id" field if the given value is not nil. +func (_c *AgentPluginCreate) SetNillableScopeID(v *string) *AgentPluginCreate { + if v != nil { + _c.SetScopeID(*v) + } + return _c +} + +// SetCreatedBy sets the "created_by" field. +func (_c *AgentPluginCreate) SetCreatedBy(v uuid.UUID) *AgentPluginCreate { + _c.mutation.SetCreatedBy(v) + return _c +} + +// SetActiveVersionID sets the "active_version_id" field. +func (_c *AgentPluginCreate) SetActiveVersionID(v uuid.UUID) *AgentPluginCreate { + _c.mutation.SetActiveVersionID(v) + return _c +} + +// SetNillableActiveVersionID sets the "active_version_id" field if the given value is not nil. +func (_c *AgentPluginCreate) SetNillableActiveVersionID(v *uuid.UUID) *AgentPluginCreate { + if v != nil { + _c.SetActiveVersionID(*v) + } + return _c +} + +// SetIsForceDelivery sets the "is_force_delivery" field. +func (_c *AgentPluginCreate) SetIsForceDelivery(v bool) *AgentPluginCreate { + _c.mutation.SetIsForceDelivery(v) + return _c +} + +// SetNillableIsForceDelivery sets the "is_force_delivery" field if the given value is not nil. +func (_c *AgentPluginCreate) SetNillableIsForceDelivery(v *bool) *AgentPluginCreate { + if v != nil { + _c.SetIsForceDelivery(*v) + } + return _c +} + +// SetIsOrphan sets the "is_orphan" field. +func (_c *AgentPluginCreate) SetIsOrphan(v bool) *AgentPluginCreate { + _c.mutation.SetIsOrphan(v) + return _c +} + +// SetNillableIsOrphan sets the "is_orphan" field if the given value is not nil. +func (_c *AgentPluginCreate) SetNillableIsOrphan(v *bool) *AgentPluginCreate { + if v != nil { + _c.SetIsOrphan(*v) + } + return _c +} + +// SetIsDeleted sets the "is_deleted" field. +func (_c *AgentPluginCreate) SetIsDeleted(v bool) *AgentPluginCreate { + _c.mutation.SetIsDeleted(v) + return _c +} + +// SetNillableIsDeleted sets the "is_deleted" field if the given value is not nil. +func (_c *AgentPluginCreate) SetNillableIsDeleted(v *bool) *AgentPluginCreate { + if v != nil { + _c.SetIsDeleted(*v) + } + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *AgentPluginCreate) SetCreatedAt(v time.Time) *AgentPluginCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *AgentPluginCreate) SetNillableCreatedAt(v *time.Time) *AgentPluginCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *AgentPluginCreate) SetUpdatedAt(v time.Time) *AgentPluginCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *AgentPluginCreate) SetNillableUpdatedAt(v *time.Time) *AgentPluginCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *AgentPluginCreate) SetID(v uuid.UUID) *AgentPluginCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *AgentPluginCreate) SetNillableID(v *uuid.UUID) *AgentPluginCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetRepo sets the "repo" edge to the AgentPluginRepo entity. +func (_c *AgentPluginCreate) SetRepo(v *AgentPluginRepo) *AgentPluginCreate { + return _c.SetRepoID(v.ID) +} + +// AddVersionIDs adds the "versions" edge to the AgentPluginVersion entity by IDs. +func (_c *AgentPluginCreate) AddVersionIDs(ids ...uuid.UUID) *AgentPluginCreate { + _c.mutation.AddVersionIDs(ids...) + return _c +} + +// AddVersions adds the "versions" edges to the AgentPluginVersion entity. +func (_c *AgentPluginCreate) AddVersions(v ...*AgentPluginVersion) *AgentPluginCreate { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddVersionIDs(ids...) +} + +// Mutation returns the AgentPluginMutation object of the builder. +func (_c *AgentPluginCreate) Mutation() *AgentPluginMutation { + return _c.mutation +} + +// Save creates the AgentPlugin in the database. +func (_c *AgentPluginCreate) Save(ctx context.Context) (*AgentPlugin, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *AgentPluginCreate) SaveX(ctx context.Context) *AgentPlugin { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *AgentPluginCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *AgentPluginCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *AgentPluginCreate) defaults() { + if _, ok := _c.mutation.ScopeType(); !ok { + v := agentplugin.DefaultScopeType + _c.mutation.SetScopeType(v) + } + if _, ok := _c.mutation.ScopeID(); !ok { + v := agentplugin.DefaultScopeID + _c.mutation.SetScopeID(v) + } + if _, ok := _c.mutation.IsForceDelivery(); !ok { + v := agentplugin.DefaultIsForceDelivery + _c.mutation.SetIsForceDelivery(v) + } + if _, ok := _c.mutation.IsOrphan(); !ok { + v := agentplugin.DefaultIsOrphan + _c.mutation.SetIsOrphan(v) + } + if _, ok := _c.mutation.IsDeleted(); !ok { + v := agentplugin.DefaultIsDeleted + _c.mutation.SetIsDeleted(v) + } + if _, ok := _c.mutation.CreatedAt(); !ok { + v := agentplugin.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := agentplugin.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := agentplugin.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *AgentPluginCreate) check() error { + if _, ok := _c.mutation.RepoID(); !ok { + return &ValidationError{Name: "repo_id", err: errors.New(`db: missing required field "AgentPlugin.repo_id"`)} + } + if _, ok := _c.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`db: missing required field "AgentPlugin.name"`)} + } + if v, ok := _c.mutation.Name(); ok { + if err := agentplugin.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "AgentPlugin.name": %w`, err)} + } + } + if _, ok := _c.mutation.ScopeType(); !ok { + return &ValidationError{Name: "scope_type", err: errors.New(`db: missing required field "AgentPlugin.scope_type"`)} + } + if v, ok := _c.mutation.ScopeType(); ok { + if err := agentplugin.ScopeTypeValidator(v); err != nil { + return &ValidationError{Name: "scope_type", err: fmt.Errorf(`db: validator failed for field "AgentPlugin.scope_type": %w`, err)} + } + } + if _, ok := _c.mutation.ScopeID(); !ok { + return &ValidationError{Name: "scope_id", err: errors.New(`db: missing required field "AgentPlugin.scope_id"`)} + } + if _, ok := _c.mutation.CreatedBy(); !ok { + return &ValidationError{Name: "created_by", err: errors.New(`db: missing required field "AgentPlugin.created_by"`)} + } + if _, ok := _c.mutation.IsForceDelivery(); !ok { + return &ValidationError{Name: "is_force_delivery", err: errors.New(`db: missing required field "AgentPlugin.is_force_delivery"`)} + } + if _, ok := _c.mutation.IsOrphan(); !ok { + return &ValidationError{Name: "is_orphan", err: errors.New(`db: missing required field "AgentPlugin.is_orphan"`)} + } + if _, ok := _c.mutation.IsDeleted(); !ok { + return &ValidationError{Name: "is_deleted", err: errors.New(`db: missing required field "AgentPlugin.is_deleted"`)} + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "AgentPlugin.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "AgentPlugin.updated_at"`)} + } + if len(_c.mutation.RepoIDs()) == 0 { + return &ValidationError{Name: "repo", err: errors.New(`db: missing required edge "AgentPlugin.repo"`)} + } + return nil +} + +func (_c *AgentPluginCreate) sqlSave(ctx context.Context) (*AgentPlugin, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.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 + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *AgentPluginCreate) createSpec() (*AgentPlugin, *sqlgraph.CreateSpec) { + var ( + _node = &AgentPlugin{config: _c.config} + _spec = sqlgraph.NewCreateSpec(agentplugin.Table, sqlgraph.NewFieldSpec(agentplugin.FieldID, field.TypeUUID)) + ) + _spec.OnConflict = _c.conflict + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = &id + } + if value, ok := _c.mutation.Name(); ok { + _spec.SetField(agentplugin.FieldName, field.TypeString, value) + _node.Name = value + } + if value, ok := _c.mutation.Description(); ok { + _spec.SetField(agentplugin.FieldDescription, field.TypeString, value) + _node.Description = value + } + if value, ok := _c.mutation.ScopeType(); ok { + _spec.SetField(agentplugin.FieldScopeType, field.TypeEnum, value) + _node.ScopeType = value + } + if value, ok := _c.mutation.ScopeID(); ok { + _spec.SetField(agentplugin.FieldScopeID, field.TypeString, value) + _node.ScopeID = value + } + if value, ok := _c.mutation.CreatedBy(); ok { + _spec.SetField(agentplugin.FieldCreatedBy, field.TypeUUID, value) + _node.CreatedBy = value + } + if value, ok := _c.mutation.ActiveVersionID(); ok { + _spec.SetField(agentplugin.FieldActiveVersionID, field.TypeUUID, value) + _node.ActiveVersionID = &value + } + if value, ok := _c.mutation.IsForceDelivery(); ok { + _spec.SetField(agentplugin.FieldIsForceDelivery, field.TypeBool, value) + _node.IsForceDelivery = value + } + if value, ok := _c.mutation.IsOrphan(); ok { + _spec.SetField(agentplugin.FieldIsOrphan, field.TypeBool, value) + _node.IsOrphan = value + } + if value, ok := _c.mutation.IsDeleted(); ok { + _spec.SetField(agentplugin.FieldIsDeleted, field.TypeBool, value) + _node.IsDeleted = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(agentplugin.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(agentplugin.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if nodes := _c.mutation.RepoIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: agentplugin.RepoTable, + Columns: []string{agentplugin.RepoColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentpluginrepo.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.RepoID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.VersionsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agentplugin.VersionsTable, + Columns: []string{agentplugin.VersionsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentpluginversion.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.AgentPlugin.Create(). +// SetRepoID(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.AgentPluginUpsert) { +// SetRepoID(v+v). +// }). +// Exec(ctx) +func (_c *AgentPluginCreate) OnConflict(opts ...sql.ConflictOption) *AgentPluginUpsertOne { + _c.conflict = opts + return &AgentPluginUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.AgentPlugin.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *AgentPluginCreate) OnConflictColumns(columns ...string) *AgentPluginUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &AgentPluginUpsertOne{ + create: _c, + } +} + +type ( + // AgentPluginUpsertOne is the builder for "upsert"-ing + // one AgentPlugin node. + AgentPluginUpsertOne struct { + create *AgentPluginCreate + } + + // AgentPluginUpsert is the "OnConflict" setter. + AgentPluginUpsert struct { + *sql.UpdateSet + } +) + +// SetRepoID sets the "repo_id" field. +func (u *AgentPluginUpsert) SetRepoID(v uuid.UUID) *AgentPluginUpsert { + u.Set(agentplugin.FieldRepoID, v) + return u +} + +// UpdateRepoID sets the "repo_id" field to the value that was provided on create. +func (u *AgentPluginUpsert) UpdateRepoID() *AgentPluginUpsert { + u.SetExcluded(agentplugin.FieldRepoID) + return u +} + +// SetName sets the "name" field. +func (u *AgentPluginUpsert) SetName(v string) *AgentPluginUpsert { + u.Set(agentplugin.FieldName, v) + return u +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *AgentPluginUpsert) UpdateName() *AgentPluginUpsert { + u.SetExcluded(agentplugin.FieldName) + return u +} + +// SetDescription sets the "description" field. +func (u *AgentPluginUpsert) SetDescription(v string) *AgentPluginUpsert { + u.Set(agentplugin.FieldDescription, v) + return u +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *AgentPluginUpsert) UpdateDescription() *AgentPluginUpsert { + u.SetExcluded(agentplugin.FieldDescription) + return u +} + +// ClearDescription clears the value of the "description" field. +func (u *AgentPluginUpsert) ClearDescription() *AgentPluginUpsert { + u.SetNull(agentplugin.FieldDescription) + return u +} + +// SetScopeType sets the "scope_type" field. +func (u *AgentPluginUpsert) SetScopeType(v agentplugin.ScopeType) *AgentPluginUpsert { + u.Set(agentplugin.FieldScopeType, v) + return u +} + +// UpdateScopeType sets the "scope_type" field to the value that was provided on create. +func (u *AgentPluginUpsert) UpdateScopeType() *AgentPluginUpsert { + u.SetExcluded(agentplugin.FieldScopeType) + return u +} + +// SetScopeID sets the "scope_id" field. +func (u *AgentPluginUpsert) SetScopeID(v string) *AgentPluginUpsert { + u.Set(agentplugin.FieldScopeID, v) + return u +} + +// UpdateScopeID sets the "scope_id" field to the value that was provided on create. +func (u *AgentPluginUpsert) UpdateScopeID() *AgentPluginUpsert { + u.SetExcluded(agentplugin.FieldScopeID) + return u +} + +// SetCreatedBy sets the "created_by" field. +func (u *AgentPluginUpsert) SetCreatedBy(v uuid.UUID) *AgentPluginUpsert { + u.Set(agentplugin.FieldCreatedBy, v) + return u +} + +// UpdateCreatedBy sets the "created_by" field to the value that was provided on create. +func (u *AgentPluginUpsert) UpdateCreatedBy() *AgentPluginUpsert { + u.SetExcluded(agentplugin.FieldCreatedBy) + return u +} + +// SetActiveVersionID sets the "active_version_id" field. +func (u *AgentPluginUpsert) SetActiveVersionID(v uuid.UUID) *AgentPluginUpsert { + u.Set(agentplugin.FieldActiveVersionID, v) + return u +} + +// UpdateActiveVersionID sets the "active_version_id" field to the value that was provided on create. +func (u *AgentPluginUpsert) UpdateActiveVersionID() *AgentPluginUpsert { + u.SetExcluded(agentplugin.FieldActiveVersionID) + return u +} + +// ClearActiveVersionID clears the value of the "active_version_id" field. +func (u *AgentPluginUpsert) ClearActiveVersionID() *AgentPluginUpsert { + u.SetNull(agentplugin.FieldActiveVersionID) + return u +} + +// SetIsForceDelivery sets the "is_force_delivery" field. +func (u *AgentPluginUpsert) SetIsForceDelivery(v bool) *AgentPluginUpsert { + u.Set(agentplugin.FieldIsForceDelivery, v) + return u +} + +// UpdateIsForceDelivery sets the "is_force_delivery" field to the value that was provided on create. +func (u *AgentPluginUpsert) UpdateIsForceDelivery() *AgentPluginUpsert { + u.SetExcluded(agentplugin.FieldIsForceDelivery) + return u +} + +// SetIsOrphan sets the "is_orphan" field. +func (u *AgentPluginUpsert) SetIsOrphan(v bool) *AgentPluginUpsert { + u.Set(agentplugin.FieldIsOrphan, v) + return u +} + +// UpdateIsOrphan sets the "is_orphan" field to the value that was provided on create. +func (u *AgentPluginUpsert) UpdateIsOrphan() *AgentPluginUpsert { + u.SetExcluded(agentplugin.FieldIsOrphan) + return u +} + +// SetIsDeleted sets the "is_deleted" field. +func (u *AgentPluginUpsert) SetIsDeleted(v bool) *AgentPluginUpsert { + u.Set(agentplugin.FieldIsDeleted, v) + return u +} + +// UpdateIsDeleted sets the "is_deleted" field to the value that was provided on create. +func (u *AgentPluginUpsert) UpdateIsDeleted() *AgentPluginUpsert { + u.SetExcluded(agentplugin.FieldIsDeleted) + return u +} + +// SetCreatedAt sets the "created_at" field. +func (u *AgentPluginUpsert) SetCreatedAt(v time.Time) *AgentPluginUpsert { + u.Set(agentplugin.FieldCreatedAt, v) + return u +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *AgentPluginUpsert) UpdateCreatedAt() *AgentPluginUpsert { + u.SetExcluded(agentplugin.FieldCreatedAt) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *AgentPluginUpsert) SetUpdatedAt(v time.Time) *AgentPluginUpsert { + u.Set(agentplugin.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *AgentPluginUpsert) UpdateUpdatedAt() *AgentPluginUpsert { + u.SetExcluded(agentplugin.FieldUpdatedAt) + return u +} + +// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field. +// Using this option is equivalent to using: +// +// client.AgentPlugin.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(agentplugin.FieldID) +// }), +// ). +// Exec(ctx) +func (u *AgentPluginUpsertOne) UpdateNewValues() *AgentPluginUpsertOne { + 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(agentplugin.FieldID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.AgentPlugin.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *AgentPluginUpsertOne) Ignore() *AgentPluginUpsertOne { + 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 *AgentPluginUpsertOne) DoNothing() *AgentPluginUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the AgentPluginCreate.OnConflict +// documentation for more info. +func (u *AgentPluginUpsertOne) Update(set func(*AgentPluginUpsert)) *AgentPluginUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&AgentPluginUpsert{UpdateSet: update}) + })) + return u +} + +// SetRepoID sets the "repo_id" field. +func (u *AgentPluginUpsertOne) SetRepoID(v uuid.UUID) *AgentPluginUpsertOne { + return u.Update(func(s *AgentPluginUpsert) { + s.SetRepoID(v) + }) +} + +// UpdateRepoID sets the "repo_id" field to the value that was provided on create. +func (u *AgentPluginUpsertOne) UpdateRepoID() *AgentPluginUpsertOne { + return u.Update(func(s *AgentPluginUpsert) { + s.UpdateRepoID() + }) +} + +// SetName sets the "name" field. +func (u *AgentPluginUpsertOne) SetName(v string) *AgentPluginUpsertOne { + return u.Update(func(s *AgentPluginUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *AgentPluginUpsertOne) UpdateName() *AgentPluginUpsertOne { + return u.Update(func(s *AgentPluginUpsert) { + s.UpdateName() + }) +} + +// SetDescription sets the "description" field. +func (u *AgentPluginUpsertOne) SetDescription(v string) *AgentPluginUpsertOne { + return u.Update(func(s *AgentPluginUpsert) { + s.SetDescription(v) + }) +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *AgentPluginUpsertOne) UpdateDescription() *AgentPluginUpsertOne { + return u.Update(func(s *AgentPluginUpsert) { + s.UpdateDescription() + }) +} + +// ClearDescription clears the value of the "description" field. +func (u *AgentPluginUpsertOne) ClearDescription() *AgentPluginUpsertOne { + return u.Update(func(s *AgentPluginUpsert) { + s.ClearDescription() + }) +} + +// SetScopeType sets the "scope_type" field. +func (u *AgentPluginUpsertOne) SetScopeType(v agentplugin.ScopeType) *AgentPluginUpsertOne { + return u.Update(func(s *AgentPluginUpsert) { + s.SetScopeType(v) + }) +} + +// UpdateScopeType sets the "scope_type" field to the value that was provided on create. +func (u *AgentPluginUpsertOne) UpdateScopeType() *AgentPluginUpsertOne { + return u.Update(func(s *AgentPluginUpsert) { + s.UpdateScopeType() + }) +} + +// SetScopeID sets the "scope_id" field. +func (u *AgentPluginUpsertOne) SetScopeID(v string) *AgentPluginUpsertOne { + return u.Update(func(s *AgentPluginUpsert) { + s.SetScopeID(v) + }) +} + +// UpdateScopeID sets the "scope_id" field to the value that was provided on create. +func (u *AgentPluginUpsertOne) UpdateScopeID() *AgentPluginUpsertOne { + return u.Update(func(s *AgentPluginUpsert) { + s.UpdateScopeID() + }) +} + +// SetCreatedBy sets the "created_by" field. +func (u *AgentPluginUpsertOne) SetCreatedBy(v uuid.UUID) *AgentPluginUpsertOne { + return u.Update(func(s *AgentPluginUpsert) { + s.SetCreatedBy(v) + }) +} + +// UpdateCreatedBy sets the "created_by" field to the value that was provided on create. +func (u *AgentPluginUpsertOne) UpdateCreatedBy() *AgentPluginUpsertOne { + return u.Update(func(s *AgentPluginUpsert) { + s.UpdateCreatedBy() + }) +} + +// SetActiveVersionID sets the "active_version_id" field. +func (u *AgentPluginUpsertOne) SetActiveVersionID(v uuid.UUID) *AgentPluginUpsertOne { + return u.Update(func(s *AgentPluginUpsert) { + s.SetActiveVersionID(v) + }) +} + +// UpdateActiveVersionID sets the "active_version_id" field to the value that was provided on create. +func (u *AgentPluginUpsertOne) UpdateActiveVersionID() *AgentPluginUpsertOne { + return u.Update(func(s *AgentPluginUpsert) { + s.UpdateActiveVersionID() + }) +} + +// ClearActiveVersionID clears the value of the "active_version_id" field. +func (u *AgentPluginUpsertOne) ClearActiveVersionID() *AgentPluginUpsertOne { + return u.Update(func(s *AgentPluginUpsert) { + s.ClearActiveVersionID() + }) +} + +// SetIsForceDelivery sets the "is_force_delivery" field. +func (u *AgentPluginUpsertOne) SetIsForceDelivery(v bool) *AgentPluginUpsertOne { + return u.Update(func(s *AgentPluginUpsert) { + s.SetIsForceDelivery(v) + }) +} + +// UpdateIsForceDelivery sets the "is_force_delivery" field to the value that was provided on create. +func (u *AgentPluginUpsertOne) UpdateIsForceDelivery() *AgentPluginUpsertOne { + return u.Update(func(s *AgentPluginUpsert) { + s.UpdateIsForceDelivery() + }) +} + +// SetIsOrphan sets the "is_orphan" field. +func (u *AgentPluginUpsertOne) SetIsOrphan(v bool) *AgentPluginUpsertOne { + return u.Update(func(s *AgentPluginUpsert) { + s.SetIsOrphan(v) + }) +} + +// UpdateIsOrphan sets the "is_orphan" field to the value that was provided on create. +func (u *AgentPluginUpsertOne) UpdateIsOrphan() *AgentPluginUpsertOne { + return u.Update(func(s *AgentPluginUpsert) { + s.UpdateIsOrphan() + }) +} + +// SetIsDeleted sets the "is_deleted" field. +func (u *AgentPluginUpsertOne) SetIsDeleted(v bool) *AgentPluginUpsertOne { + return u.Update(func(s *AgentPluginUpsert) { + s.SetIsDeleted(v) + }) +} + +// UpdateIsDeleted sets the "is_deleted" field to the value that was provided on create. +func (u *AgentPluginUpsertOne) UpdateIsDeleted() *AgentPluginUpsertOne { + return u.Update(func(s *AgentPluginUpsert) { + s.UpdateIsDeleted() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *AgentPluginUpsertOne) SetCreatedAt(v time.Time) *AgentPluginUpsertOne { + return u.Update(func(s *AgentPluginUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *AgentPluginUpsertOne) UpdateCreatedAt() *AgentPluginUpsertOne { + return u.Update(func(s *AgentPluginUpsert) { + s.UpdateCreatedAt() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *AgentPluginUpsertOne) SetUpdatedAt(v time.Time) *AgentPluginUpsertOne { + return u.Update(func(s *AgentPluginUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *AgentPluginUpsertOne) UpdateUpdatedAt() *AgentPluginUpsertOne { + return u.Update(func(s *AgentPluginUpsert) { + s.UpdateUpdatedAt() + }) +} + +// Exec executes the query. +func (u *AgentPluginUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for AgentPluginCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *AgentPluginUpsertOne) 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 *AgentPluginUpsertOne) 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: AgentPluginUpsertOne.ID is not supported by MySQL driver. Use AgentPluginUpsertOne.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 *AgentPluginUpsertOne) IDX(ctx context.Context) uuid.UUID { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// AgentPluginCreateBulk is the builder for creating many AgentPlugin entities in bulk. +type AgentPluginCreateBulk struct { + config + err error + builders []*AgentPluginCreate + conflict []sql.ConflictOption +} + +// Save creates the AgentPlugin entities in the database. +func (_c *AgentPluginCreateBulk) Save(ctx context.Context) ([]*AgentPlugin, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*AgentPlugin, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*AgentPluginMutation) + 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, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = _c.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.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, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *AgentPluginCreateBulk) SaveX(ctx context.Context) []*AgentPlugin { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *AgentPluginCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *AgentPluginCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.AgentPlugin.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.AgentPluginUpsert) { +// SetRepoID(v+v). +// }). +// Exec(ctx) +func (_c *AgentPluginCreateBulk) OnConflict(opts ...sql.ConflictOption) *AgentPluginUpsertBulk { + _c.conflict = opts + return &AgentPluginUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.AgentPlugin.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *AgentPluginCreateBulk) OnConflictColumns(columns ...string) *AgentPluginUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &AgentPluginUpsertBulk{ + create: _c, + } +} + +// AgentPluginUpsertBulk is the builder for "upsert"-ing +// a bulk of AgentPlugin nodes. +type AgentPluginUpsertBulk struct { + create *AgentPluginCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.AgentPlugin.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(agentplugin.FieldID) +// }), +// ). +// Exec(ctx) +func (u *AgentPluginUpsertBulk) UpdateNewValues() *AgentPluginUpsertBulk { + 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(agentplugin.FieldID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.AgentPlugin.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *AgentPluginUpsertBulk) Ignore() *AgentPluginUpsertBulk { + 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 *AgentPluginUpsertBulk) DoNothing() *AgentPluginUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the AgentPluginCreateBulk.OnConflict +// documentation for more info. +func (u *AgentPluginUpsertBulk) Update(set func(*AgentPluginUpsert)) *AgentPluginUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&AgentPluginUpsert{UpdateSet: update}) + })) + return u +} + +// SetRepoID sets the "repo_id" field. +func (u *AgentPluginUpsertBulk) SetRepoID(v uuid.UUID) *AgentPluginUpsertBulk { + return u.Update(func(s *AgentPluginUpsert) { + s.SetRepoID(v) + }) +} + +// UpdateRepoID sets the "repo_id" field to the value that was provided on create. +func (u *AgentPluginUpsertBulk) UpdateRepoID() *AgentPluginUpsertBulk { + return u.Update(func(s *AgentPluginUpsert) { + s.UpdateRepoID() + }) +} + +// SetName sets the "name" field. +func (u *AgentPluginUpsertBulk) SetName(v string) *AgentPluginUpsertBulk { + return u.Update(func(s *AgentPluginUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *AgentPluginUpsertBulk) UpdateName() *AgentPluginUpsertBulk { + return u.Update(func(s *AgentPluginUpsert) { + s.UpdateName() + }) +} + +// SetDescription sets the "description" field. +func (u *AgentPluginUpsertBulk) SetDescription(v string) *AgentPluginUpsertBulk { + return u.Update(func(s *AgentPluginUpsert) { + s.SetDescription(v) + }) +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *AgentPluginUpsertBulk) UpdateDescription() *AgentPluginUpsertBulk { + return u.Update(func(s *AgentPluginUpsert) { + s.UpdateDescription() + }) +} + +// ClearDescription clears the value of the "description" field. +func (u *AgentPluginUpsertBulk) ClearDescription() *AgentPluginUpsertBulk { + return u.Update(func(s *AgentPluginUpsert) { + s.ClearDescription() + }) +} + +// SetScopeType sets the "scope_type" field. +func (u *AgentPluginUpsertBulk) SetScopeType(v agentplugin.ScopeType) *AgentPluginUpsertBulk { + return u.Update(func(s *AgentPluginUpsert) { + s.SetScopeType(v) + }) +} + +// UpdateScopeType sets the "scope_type" field to the value that was provided on create. +func (u *AgentPluginUpsertBulk) UpdateScopeType() *AgentPluginUpsertBulk { + return u.Update(func(s *AgentPluginUpsert) { + s.UpdateScopeType() + }) +} + +// SetScopeID sets the "scope_id" field. +func (u *AgentPluginUpsertBulk) SetScopeID(v string) *AgentPluginUpsertBulk { + return u.Update(func(s *AgentPluginUpsert) { + s.SetScopeID(v) + }) +} + +// UpdateScopeID sets the "scope_id" field to the value that was provided on create. +func (u *AgentPluginUpsertBulk) UpdateScopeID() *AgentPluginUpsertBulk { + return u.Update(func(s *AgentPluginUpsert) { + s.UpdateScopeID() + }) +} + +// SetCreatedBy sets the "created_by" field. +func (u *AgentPluginUpsertBulk) SetCreatedBy(v uuid.UUID) *AgentPluginUpsertBulk { + return u.Update(func(s *AgentPluginUpsert) { + s.SetCreatedBy(v) + }) +} + +// UpdateCreatedBy sets the "created_by" field to the value that was provided on create. +func (u *AgentPluginUpsertBulk) UpdateCreatedBy() *AgentPluginUpsertBulk { + return u.Update(func(s *AgentPluginUpsert) { + s.UpdateCreatedBy() + }) +} + +// SetActiveVersionID sets the "active_version_id" field. +func (u *AgentPluginUpsertBulk) SetActiveVersionID(v uuid.UUID) *AgentPluginUpsertBulk { + return u.Update(func(s *AgentPluginUpsert) { + s.SetActiveVersionID(v) + }) +} + +// UpdateActiveVersionID sets the "active_version_id" field to the value that was provided on create. +func (u *AgentPluginUpsertBulk) UpdateActiveVersionID() *AgentPluginUpsertBulk { + return u.Update(func(s *AgentPluginUpsert) { + s.UpdateActiveVersionID() + }) +} + +// ClearActiveVersionID clears the value of the "active_version_id" field. +func (u *AgentPluginUpsertBulk) ClearActiveVersionID() *AgentPluginUpsertBulk { + return u.Update(func(s *AgentPluginUpsert) { + s.ClearActiveVersionID() + }) +} + +// SetIsForceDelivery sets the "is_force_delivery" field. +func (u *AgentPluginUpsertBulk) SetIsForceDelivery(v bool) *AgentPluginUpsertBulk { + return u.Update(func(s *AgentPluginUpsert) { + s.SetIsForceDelivery(v) + }) +} + +// UpdateIsForceDelivery sets the "is_force_delivery" field to the value that was provided on create. +func (u *AgentPluginUpsertBulk) UpdateIsForceDelivery() *AgentPluginUpsertBulk { + return u.Update(func(s *AgentPluginUpsert) { + s.UpdateIsForceDelivery() + }) +} + +// SetIsOrphan sets the "is_orphan" field. +func (u *AgentPluginUpsertBulk) SetIsOrphan(v bool) *AgentPluginUpsertBulk { + return u.Update(func(s *AgentPluginUpsert) { + s.SetIsOrphan(v) + }) +} + +// UpdateIsOrphan sets the "is_orphan" field to the value that was provided on create. +func (u *AgentPluginUpsertBulk) UpdateIsOrphan() *AgentPluginUpsertBulk { + return u.Update(func(s *AgentPluginUpsert) { + s.UpdateIsOrphan() + }) +} + +// SetIsDeleted sets the "is_deleted" field. +func (u *AgentPluginUpsertBulk) SetIsDeleted(v bool) *AgentPluginUpsertBulk { + return u.Update(func(s *AgentPluginUpsert) { + s.SetIsDeleted(v) + }) +} + +// UpdateIsDeleted sets the "is_deleted" field to the value that was provided on create. +func (u *AgentPluginUpsertBulk) UpdateIsDeleted() *AgentPluginUpsertBulk { + return u.Update(func(s *AgentPluginUpsert) { + s.UpdateIsDeleted() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *AgentPluginUpsertBulk) SetCreatedAt(v time.Time) *AgentPluginUpsertBulk { + return u.Update(func(s *AgentPluginUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *AgentPluginUpsertBulk) UpdateCreatedAt() *AgentPluginUpsertBulk { + return u.Update(func(s *AgentPluginUpsert) { + s.UpdateCreatedAt() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *AgentPluginUpsertBulk) SetUpdatedAt(v time.Time) *AgentPluginUpsertBulk { + return u.Update(func(s *AgentPluginUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *AgentPluginUpsertBulk) UpdateUpdatedAt() *AgentPluginUpsertBulk { + return u.Update(func(s *AgentPluginUpsert) { + s.UpdateUpdatedAt() + }) +} + +// Exec executes the query. +func (u *AgentPluginUpsertBulk) 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 AgentPluginCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for AgentPluginCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *AgentPluginUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/agentplugin_delete.go b/backend/db/agentplugin_delete.go new file mode 100644 index 00000000..82fcd0ba --- /dev/null +++ b/backend/db/agentplugin_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/agentplugin" + "github.com/chaitin/MonkeyCode/backend/db/predicate" +) + +// AgentPluginDelete is the builder for deleting a AgentPlugin entity. +type AgentPluginDelete struct { + config + hooks []Hook + mutation *AgentPluginMutation +} + +// Where appends a list predicates to the AgentPluginDelete builder. +func (_d *AgentPluginDelete) Where(ps ...predicate.AgentPlugin) *AgentPluginDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *AgentPluginDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *AgentPluginDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *AgentPluginDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(agentplugin.Table, sqlgraph.NewFieldSpec(agentplugin.FieldID, field.TypeUUID)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// AgentPluginDeleteOne is the builder for deleting a single AgentPlugin entity. +type AgentPluginDeleteOne struct { + _d *AgentPluginDelete +} + +// Where appends a list predicates to the AgentPluginDelete builder. +func (_d *AgentPluginDeleteOne) Where(ps ...predicate.AgentPlugin) *AgentPluginDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *AgentPluginDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{agentplugin.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *AgentPluginDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/agentplugin_query.go b/backend/db/agentplugin_query.go new file mode 100644 index 00000000..fc8d11e0 --- /dev/null +++ b/backend/db/agentplugin_query.go @@ -0,0 +1,732 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "database/sql/driver" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/agentplugin" + "github.com/chaitin/MonkeyCode/backend/db/agentpluginrepo" + "github.com/chaitin/MonkeyCode/backend/db/agentpluginversion" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/google/uuid" +) + +// AgentPluginQuery is the builder for querying AgentPlugin entities. +type AgentPluginQuery struct { + config + ctx *QueryContext + order []agentplugin.OrderOption + inters []Interceptor + predicates []predicate.AgentPlugin + withRepo *AgentPluginRepoQuery + withVersions *AgentPluginVersionQuery + 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 AgentPluginQuery builder. +func (_q *AgentPluginQuery) Where(ps ...predicate.AgentPlugin) *AgentPluginQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *AgentPluginQuery) Limit(limit int) *AgentPluginQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *AgentPluginQuery) Offset(offset int) *AgentPluginQuery { + _q.ctx.Offset = &offset + return _q +} + +// 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 (_q *AgentPluginQuery) Unique(unique bool) *AgentPluginQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *AgentPluginQuery) Order(o ...agentplugin.OrderOption) *AgentPluginQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryRepo chains the current query on the "repo" edge. +func (_q *AgentPluginQuery) QueryRepo() *AgentPluginRepoQuery { + query := (&AgentPluginRepoClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(agentplugin.Table, agentplugin.FieldID, selector), + sqlgraph.To(agentpluginrepo.Table, agentpluginrepo.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, agentplugin.RepoTable, agentplugin.RepoColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryVersions chains the current query on the "versions" edge. +func (_q *AgentPluginQuery) QueryVersions() *AgentPluginVersionQuery { + query := (&AgentPluginVersionClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(agentplugin.Table, agentplugin.FieldID, selector), + sqlgraph.To(agentpluginversion.Table, agentpluginversion.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, agentplugin.VersionsTable, agentplugin.VersionsColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first AgentPlugin entity from the query. +// Returns a *NotFoundError when no AgentPlugin was found. +func (_q *AgentPluginQuery) First(ctx context.Context) (*AgentPlugin, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{agentplugin.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *AgentPluginQuery) FirstX(ctx context.Context) *AgentPlugin { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first AgentPlugin ID from the query. +// Returns a *NotFoundError when no AgentPlugin ID was found. +func (_q *AgentPluginQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{agentplugin.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *AgentPluginQuery) FirstIDX(ctx context.Context) uuid.UUID { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single AgentPlugin entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one AgentPlugin entity is found. +// Returns a *NotFoundError when no AgentPlugin entities are found. +func (_q *AgentPluginQuery) Only(ctx context.Context) (*AgentPlugin, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{agentplugin.Label} + default: + return nil, &NotSingularError{agentplugin.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *AgentPluginQuery) OnlyX(ctx context.Context) *AgentPlugin { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only AgentPlugin ID in the query. +// Returns a *NotSingularError when more than one AgentPlugin ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *AgentPluginQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{agentplugin.Label} + default: + err = &NotSingularError{agentplugin.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *AgentPluginQuery) OnlyIDX(ctx context.Context) uuid.UUID { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of AgentPlugins. +func (_q *AgentPluginQuery) All(ctx context.Context) ([]*AgentPlugin, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*AgentPlugin, *AgentPluginQuery]() + return withInterceptors[[]*AgentPlugin](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *AgentPluginQuery) AllX(ctx context.Context) []*AgentPlugin { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of AgentPlugin IDs. +func (_q *AgentPluginQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(agentplugin.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *AgentPluginQuery) IDsX(ctx context.Context) []uuid.UUID { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *AgentPluginQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*AgentPluginQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *AgentPluginQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *AgentPluginQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.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 (_q *AgentPluginQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the AgentPluginQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *AgentPluginQuery) Clone() *AgentPluginQuery { + if _q == nil { + return nil + } + return &AgentPluginQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]agentplugin.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.AgentPlugin{}, _q.predicates...), + withRepo: _q.withRepo.Clone(), + withVersions: _q.withVersions.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + modifiers: append([]func(*sql.Selector){}, _q.modifiers...), + } +} + +// WithRepo tells the query-builder to eager-load the nodes that are connected to +// the "repo" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *AgentPluginQuery) WithRepo(opts ...func(*AgentPluginRepoQuery)) *AgentPluginQuery { + query := (&AgentPluginRepoClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withRepo = query + return _q +} + +// WithVersions tells the query-builder to eager-load the nodes that are connected to +// the "versions" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *AgentPluginQuery) WithVersions(opts ...func(*AgentPluginVersionQuery)) *AgentPluginQuery { + query := (&AgentPluginVersionClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withVersions = query + return _q +} + +// 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 { +// RepoID uuid.UUID `json:"repo_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.AgentPlugin.Query(). +// GroupBy(agentplugin.FieldRepoID). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *AgentPluginQuery) GroupBy(field string, fields ...string) *AgentPluginGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &AgentPluginGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = agentplugin.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 { +// RepoID uuid.UUID `json:"repo_id,omitempty"` +// } +// +// client.AgentPlugin.Query(). +// Select(agentplugin.FieldRepoID). +// Scan(ctx, &v) +func (_q *AgentPluginQuery) Select(fields ...string) *AgentPluginSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &AgentPluginSelect{AgentPluginQuery: _q} + sbuild.label = agentplugin.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a AgentPluginSelect configured with the given aggregations. +func (_q *AgentPluginQuery) Aggregate(fns ...AggregateFunc) *AgentPluginSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *AgentPluginQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.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, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !agentplugin.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *AgentPluginQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*AgentPlugin, error) { + var ( + nodes = []*AgentPlugin{} + _spec = _q.querySpec() + loadedTypes = [2]bool{ + _q.withRepo != nil, + _q.withVersions != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*AgentPlugin).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &AgentPlugin{config: _q.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := _q.withRepo; query != nil { + if err := _q.loadRepo(ctx, query, nodes, nil, + func(n *AgentPlugin, e *AgentPluginRepo) { n.Edges.Repo = e }); err != nil { + return nil, err + } + } + if query := _q.withVersions; query != nil { + if err := _q.loadVersions(ctx, query, nodes, + func(n *AgentPlugin) { n.Edges.Versions = []*AgentPluginVersion{} }, + func(n *AgentPlugin, e *AgentPluginVersion) { n.Edges.Versions = append(n.Edges.Versions, e) }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *AgentPluginQuery) loadRepo(ctx context.Context, query *AgentPluginRepoQuery, nodes []*AgentPlugin, init func(*AgentPlugin), assign func(*AgentPlugin, *AgentPluginRepo)) error { + ids := make([]uuid.UUID, 0, len(nodes)) + nodeids := make(map[uuid.UUID][]*AgentPlugin) + for i := range nodes { + fk := nodes[i].RepoID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(agentpluginrepo.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return fmt.Errorf(`unexpected foreign-key "repo_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *AgentPluginQuery) loadVersions(ctx context.Context, query *AgentPluginVersionQuery, nodes []*AgentPlugin, init func(*AgentPlugin), assign func(*AgentPlugin, *AgentPluginVersion)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[uuid.UUID]*AgentPlugin) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) + } + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(agentpluginversion.FieldResourceID) + } + query.Where(predicate.AgentPluginVersion(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(agentplugin.VersionsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.ResourceID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "resource_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} + +func (_q *AgentPluginQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *AgentPluginQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(agentplugin.Table, agentplugin.Columns, sqlgraph.NewFieldSpec(agentplugin.FieldID, field.TypeUUID)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, agentplugin.FieldID) + for i := range fields { + if fields[i] != agentplugin.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withRepo != nil { + _spec.Node.AddColumnOnce(agentplugin.FieldRepoID) + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *AgentPluginQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(agentplugin.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = agentplugin.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, m := range _q.modifiers { + m(selector) + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.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 := _q.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 (_q *AgentPluginQuery) ForUpdate(opts ...sql.LockOption) *AgentPluginQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForUpdate(opts...) + }) + return _q +} + +// 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 (_q *AgentPluginQuery) ForShare(opts ...sql.LockOption) *AgentPluginQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (_q *AgentPluginQuery) Modify(modifiers ...func(s *sql.Selector)) *AgentPluginSelect { + _q.modifiers = append(_q.modifiers, modifiers...) + return _q.Select() +} + +// AgentPluginGroupBy is the group-by builder for AgentPlugin entities. +type AgentPluginGroupBy struct { + selector + build *AgentPluginQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *AgentPluginGroupBy) Aggregate(fns ...AggregateFunc) *AgentPluginGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *AgentPluginGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*AgentPluginQuery, *AgentPluginGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *AgentPluginGroupBy) sqlScan(ctx context.Context, root *AgentPluginQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// AgentPluginSelect is the builder for selecting fields of AgentPlugin entities. +type AgentPluginSelect struct { + *AgentPluginQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *AgentPluginSelect) Aggregate(fns ...AggregateFunc) *AgentPluginSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *AgentPluginSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*AgentPluginQuery, *AgentPluginSelect](ctx, _s.AgentPluginQuery, _s, _s.inters, v) +} + +func (_s *AgentPluginSelect) sqlScan(ctx context.Context, root *AgentPluginQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.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 := _s.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 (_s *AgentPluginSelect) Modify(modifiers ...func(s *sql.Selector)) *AgentPluginSelect { + _s.modifiers = append(_s.modifiers, modifiers...) + return _s +} diff --git a/backend/db/agentplugin_update.go b/backend/db/agentplugin_update.go new file mode 100644 index 00000000..c19da25d --- /dev/null +++ b/backend/db/agentplugin_update.go @@ -0,0 +1,919 @@ +// 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/agentplugin" + "github.com/chaitin/MonkeyCode/backend/db/agentpluginrepo" + "github.com/chaitin/MonkeyCode/backend/db/agentpluginversion" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/google/uuid" +) + +// AgentPluginUpdate is the builder for updating AgentPlugin entities. +type AgentPluginUpdate struct { + config + hooks []Hook + mutation *AgentPluginMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the AgentPluginUpdate builder. +func (_u *AgentPluginUpdate) Where(ps ...predicate.AgentPlugin) *AgentPluginUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetRepoID sets the "repo_id" field. +func (_u *AgentPluginUpdate) SetRepoID(v uuid.UUID) *AgentPluginUpdate { + _u.mutation.SetRepoID(v) + return _u +} + +// SetNillableRepoID sets the "repo_id" field if the given value is not nil. +func (_u *AgentPluginUpdate) SetNillableRepoID(v *uuid.UUID) *AgentPluginUpdate { + if v != nil { + _u.SetRepoID(*v) + } + return _u +} + +// SetName sets the "name" field. +func (_u *AgentPluginUpdate) SetName(v string) *AgentPluginUpdate { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *AgentPluginUpdate) SetNillableName(v *string) *AgentPluginUpdate { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetDescription sets the "description" field. +func (_u *AgentPluginUpdate) SetDescription(v string) *AgentPluginUpdate { + _u.mutation.SetDescription(v) + return _u +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_u *AgentPluginUpdate) SetNillableDescription(v *string) *AgentPluginUpdate { + if v != nil { + _u.SetDescription(*v) + } + return _u +} + +// ClearDescription clears the value of the "description" field. +func (_u *AgentPluginUpdate) ClearDescription() *AgentPluginUpdate { + _u.mutation.ClearDescription() + return _u +} + +// SetScopeType sets the "scope_type" field. +func (_u *AgentPluginUpdate) SetScopeType(v agentplugin.ScopeType) *AgentPluginUpdate { + _u.mutation.SetScopeType(v) + return _u +} + +// SetNillableScopeType sets the "scope_type" field if the given value is not nil. +func (_u *AgentPluginUpdate) SetNillableScopeType(v *agentplugin.ScopeType) *AgentPluginUpdate { + if v != nil { + _u.SetScopeType(*v) + } + return _u +} + +// SetScopeID sets the "scope_id" field. +func (_u *AgentPluginUpdate) SetScopeID(v string) *AgentPluginUpdate { + _u.mutation.SetScopeID(v) + return _u +} + +// SetNillableScopeID sets the "scope_id" field if the given value is not nil. +func (_u *AgentPluginUpdate) SetNillableScopeID(v *string) *AgentPluginUpdate { + if v != nil { + _u.SetScopeID(*v) + } + return _u +} + +// SetCreatedBy sets the "created_by" field. +func (_u *AgentPluginUpdate) SetCreatedBy(v uuid.UUID) *AgentPluginUpdate { + _u.mutation.SetCreatedBy(v) + return _u +} + +// SetNillableCreatedBy sets the "created_by" field if the given value is not nil. +func (_u *AgentPluginUpdate) SetNillableCreatedBy(v *uuid.UUID) *AgentPluginUpdate { + if v != nil { + _u.SetCreatedBy(*v) + } + return _u +} + +// SetActiveVersionID sets the "active_version_id" field. +func (_u *AgentPluginUpdate) SetActiveVersionID(v uuid.UUID) *AgentPluginUpdate { + _u.mutation.SetActiveVersionID(v) + return _u +} + +// SetNillableActiveVersionID sets the "active_version_id" field if the given value is not nil. +func (_u *AgentPluginUpdate) SetNillableActiveVersionID(v *uuid.UUID) *AgentPluginUpdate { + if v != nil { + _u.SetActiveVersionID(*v) + } + return _u +} + +// ClearActiveVersionID clears the value of the "active_version_id" field. +func (_u *AgentPluginUpdate) ClearActiveVersionID() *AgentPluginUpdate { + _u.mutation.ClearActiveVersionID() + return _u +} + +// SetIsForceDelivery sets the "is_force_delivery" field. +func (_u *AgentPluginUpdate) SetIsForceDelivery(v bool) *AgentPluginUpdate { + _u.mutation.SetIsForceDelivery(v) + return _u +} + +// SetNillableIsForceDelivery sets the "is_force_delivery" field if the given value is not nil. +func (_u *AgentPluginUpdate) SetNillableIsForceDelivery(v *bool) *AgentPluginUpdate { + if v != nil { + _u.SetIsForceDelivery(*v) + } + return _u +} + +// SetIsOrphan sets the "is_orphan" field. +func (_u *AgentPluginUpdate) SetIsOrphan(v bool) *AgentPluginUpdate { + _u.mutation.SetIsOrphan(v) + return _u +} + +// SetNillableIsOrphan sets the "is_orphan" field if the given value is not nil. +func (_u *AgentPluginUpdate) SetNillableIsOrphan(v *bool) *AgentPluginUpdate { + if v != nil { + _u.SetIsOrphan(*v) + } + return _u +} + +// SetIsDeleted sets the "is_deleted" field. +func (_u *AgentPluginUpdate) SetIsDeleted(v bool) *AgentPluginUpdate { + _u.mutation.SetIsDeleted(v) + return _u +} + +// SetNillableIsDeleted sets the "is_deleted" field if the given value is not nil. +func (_u *AgentPluginUpdate) SetNillableIsDeleted(v *bool) *AgentPluginUpdate { + if v != nil { + _u.SetIsDeleted(*v) + } + return _u +} + +// SetCreatedAt sets the "created_at" field. +func (_u *AgentPluginUpdate) SetCreatedAt(v time.Time) *AgentPluginUpdate { + _u.mutation.SetCreatedAt(v) + return _u +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_u *AgentPluginUpdate) SetNillableCreatedAt(v *time.Time) *AgentPluginUpdate { + if v != nil { + _u.SetCreatedAt(*v) + } + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *AgentPluginUpdate) SetUpdatedAt(v time.Time) *AgentPluginUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetRepo sets the "repo" edge to the AgentPluginRepo entity. +func (_u *AgentPluginUpdate) SetRepo(v *AgentPluginRepo) *AgentPluginUpdate { + return _u.SetRepoID(v.ID) +} + +// AddVersionIDs adds the "versions" edge to the AgentPluginVersion entity by IDs. +func (_u *AgentPluginUpdate) AddVersionIDs(ids ...uuid.UUID) *AgentPluginUpdate { + _u.mutation.AddVersionIDs(ids...) + return _u +} + +// AddVersions adds the "versions" edges to the AgentPluginVersion entity. +func (_u *AgentPluginUpdate) AddVersions(v ...*AgentPluginVersion) *AgentPluginUpdate { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddVersionIDs(ids...) +} + +// Mutation returns the AgentPluginMutation object of the builder. +func (_u *AgentPluginUpdate) Mutation() *AgentPluginMutation { + return _u.mutation +} + +// ClearRepo clears the "repo" edge to the AgentPluginRepo entity. +func (_u *AgentPluginUpdate) ClearRepo() *AgentPluginUpdate { + _u.mutation.ClearRepo() + return _u +} + +// ClearVersions clears all "versions" edges to the AgentPluginVersion entity. +func (_u *AgentPluginUpdate) ClearVersions() *AgentPluginUpdate { + _u.mutation.ClearVersions() + return _u +} + +// RemoveVersionIDs removes the "versions" edge to AgentPluginVersion entities by IDs. +func (_u *AgentPluginUpdate) RemoveVersionIDs(ids ...uuid.UUID) *AgentPluginUpdate { + _u.mutation.RemoveVersionIDs(ids...) + return _u +} + +// RemoveVersions removes "versions" edges to AgentPluginVersion entities. +func (_u *AgentPluginUpdate) RemoveVersions(v ...*AgentPluginVersion) *AgentPluginUpdate { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveVersionIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *AgentPluginUpdate) Save(ctx context.Context) (int, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *AgentPluginUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *AgentPluginUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *AgentPluginUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_u *AgentPluginUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := agentplugin.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *AgentPluginUpdate) check() error { + if v, ok := _u.mutation.Name(); ok { + if err := agentplugin.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "AgentPlugin.name": %w`, err)} + } + } + if v, ok := _u.mutation.ScopeType(); ok { + if err := agentplugin.ScopeTypeValidator(v); err != nil { + return &ValidationError{Name: "scope_type", err: fmt.Errorf(`db: validator failed for field "AgentPlugin.scope_type": %w`, err)} + } + } + if _u.mutation.RepoCleared() && len(_u.mutation.RepoIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "AgentPlugin.repo"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (_u *AgentPluginUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *AgentPluginUpdate { + _u.modifiers = append(_u.modifiers, modifiers...) + return _u +} + +func (_u *AgentPluginUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(agentplugin.Table, agentplugin.Columns, sqlgraph.NewFieldSpec(agentplugin.FieldID, field.TypeUUID)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(agentplugin.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Description(); ok { + _spec.SetField(agentplugin.FieldDescription, field.TypeString, value) + } + if _u.mutation.DescriptionCleared() { + _spec.ClearField(agentplugin.FieldDescription, field.TypeString) + } + if value, ok := _u.mutation.ScopeType(); ok { + _spec.SetField(agentplugin.FieldScopeType, field.TypeEnum, value) + } + if value, ok := _u.mutation.ScopeID(); ok { + _spec.SetField(agentplugin.FieldScopeID, field.TypeString, value) + } + if value, ok := _u.mutation.CreatedBy(); ok { + _spec.SetField(agentplugin.FieldCreatedBy, field.TypeUUID, value) + } + if value, ok := _u.mutation.ActiveVersionID(); ok { + _spec.SetField(agentplugin.FieldActiveVersionID, field.TypeUUID, value) + } + if _u.mutation.ActiveVersionIDCleared() { + _spec.ClearField(agentplugin.FieldActiveVersionID, field.TypeUUID) + } + if value, ok := _u.mutation.IsForceDelivery(); ok { + _spec.SetField(agentplugin.FieldIsForceDelivery, field.TypeBool, value) + } + if value, ok := _u.mutation.IsOrphan(); ok { + _spec.SetField(agentplugin.FieldIsOrphan, field.TypeBool, value) + } + if value, ok := _u.mutation.IsDeleted(); ok { + _spec.SetField(agentplugin.FieldIsDeleted, field.TypeBool, value) + } + if value, ok := _u.mutation.CreatedAt(); ok { + _spec.SetField(agentplugin.FieldCreatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(agentplugin.FieldUpdatedAt, field.TypeTime, value) + } + if _u.mutation.RepoCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: agentplugin.RepoTable, + Columns: []string{agentplugin.RepoColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentpluginrepo.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RepoIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: agentplugin.RepoTable, + Columns: []string{agentplugin.RepoColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentpluginrepo.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.VersionsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agentplugin.VersionsTable, + Columns: []string{agentplugin.VersionsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentpluginversion.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedVersionsIDs(); len(nodes) > 0 && !_u.mutation.VersionsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agentplugin.VersionsTable, + Columns: []string{agentplugin.VersionsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentpluginversion.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.VersionsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agentplugin.VersionsTable, + Columns: []string{agentplugin.VersionsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentpluginversion.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(_u.modifiers...) + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{agentplugin.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// AgentPluginUpdateOne is the builder for updating a single AgentPlugin entity. +type AgentPluginUpdateOne struct { + config + fields []string + hooks []Hook + mutation *AgentPluginMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetRepoID sets the "repo_id" field. +func (_u *AgentPluginUpdateOne) SetRepoID(v uuid.UUID) *AgentPluginUpdateOne { + _u.mutation.SetRepoID(v) + return _u +} + +// SetNillableRepoID sets the "repo_id" field if the given value is not nil. +func (_u *AgentPluginUpdateOne) SetNillableRepoID(v *uuid.UUID) *AgentPluginUpdateOne { + if v != nil { + _u.SetRepoID(*v) + } + return _u +} + +// SetName sets the "name" field. +func (_u *AgentPluginUpdateOne) SetName(v string) *AgentPluginUpdateOne { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *AgentPluginUpdateOne) SetNillableName(v *string) *AgentPluginUpdateOne { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetDescription sets the "description" field. +func (_u *AgentPluginUpdateOne) SetDescription(v string) *AgentPluginUpdateOne { + _u.mutation.SetDescription(v) + return _u +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_u *AgentPluginUpdateOne) SetNillableDescription(v *string) *AgentPluginUpdateOne { + if v != nil { + _u.SetDescription(*v) + } + return _u +} + +// ClearDescription clears the value of the "description" field. +func (_u *AgentPluginUpdateOne) ClearDescription() *AgentPluginUpdateOne { + _u.mutation.ClearDescription() + return _u +} + +// SetScopeType sets the "scope_type" field. +func (_u *AgentPluginUpdateOne) SetScopeType(v agentplugin.ScopeType) *AgentPluginUpdateOne { + _u.mutation.SetScopeType(v) + return _u +} + +// SetNillableScopeType sets the "scope_type" field if the given value is not nil. +func (_u *AgentPluginUpdateOne) SetNillableScopeType(v *agentplugin.ScopeType) *AgentPluginUpdateOne { + if v != nil { + _u.SetScopeType(*v) + } + return _u +} + +// SetScopeID sets the "scope_id" field. +func (_u *AgentPluginUpdateOne) SetScopeID(v string) *AgentPluginUpdateOne { + _u.mutation.SetScopeID(v) + return _u +} + +// SetNillableScopeID sets the "scope_id" field if the given value is not nil. +func (_u *AgentPluginUpdateOne) SetNillableScopeID(v *string) *AgentPluginUpdateOne { + if v != nil { + _u.SetScopeID(*v) + } + return _u +} + +// SetCreatedBy sets the "created_by" field. +func (_u *AgentPluginUpdateOne) SetCreatedBy(v uuid.UUID) *AgentPluginUpdateOne { + _u.mutation.SetCreatedBy(v) + return _u +} + +// SetNillableCreatedBy sets the "created_by" field if the given value is not nil. +func (_u *AgentPluginUpdateOne) SetNillableCreatedBy(v *uuid.UUID) *AgentPluginUpdateOne { + if v != nil { + _u.SetCreatedBy(*v) + } + return _u +} + +// SetActiveVersionID sets the "active_version_id" field. +func (_u *AgentPluginUpdateOne) SetActiveVersionID(v uuid.UUID) *AgentPluginUpdateOne { + _u.mutation.SetActiveVersionID(v) + return _u +} + +// SetNillableActiveVersionID sets the "active_version_id" field if the given value is not nil. +func (_u *AgentPluginUpdateOne) SetNillableActiveVersionID(v *uuid.UUID) *AgentPluginUpdateOne { + if v != nil { + _u.SetActiveVersionID(*v) + } + return _u +} + +// ClearActiveVersionID clears the value of the "active_version_id" field. +func (_u *AgentPluginUpdateOne) ClearActiveVersionID() *AgentPluginUpdateOne { + _u.mutation.ClearActiveVersionID() + return _u +} + +// SetIsForceDelivery sets the "is_force_delivery" field. +func (_u *AgentPluginUpdateOne) SetIsForceDelivery(v bool) *AgentPluginUpdateOne { + _u.mutation.SetIsForceDelivery(v) + return _u +} + +// SetNillableIsForceDelivery sets the "is_force_delivery" field if the given value is not nil. +func (_u *AgentPluginUpdateOne) SetNillableIsForceDelivery(v *bool) *AgentPluginUpdateOne { + if v != nil { + _u.SetIsForceDelivery(*v) + } + return _u +} + +// SetIsOrphan sets the "is_orphan" field. +func (_u *AgentPluginUpdateOne) SetIsOrphan(v bool) *AgentPluginUpdateOne { + _u.mutation.SetIsOrphan(v) + return _u +} + +// SetNillableIsOrphan sets the "is_orphan" field if the given value is not nil. +func (_u *AgentPluginUpdateOne) SetNillableIsOrphan(v *bool) *AgentPluginUpdateOne { + if v != nil { + _u.SetIsOrphan(*v) + } + return _u +} + +// SetIsDeleted sets the "is_deleted" field. +func (_u *AgentPluginUpdateOne) SetIsDeleted(v bool) *AgentPluginUpdateOne { + _u.mutation.SetIsDeleted(v) + return _u +} + +// SetNillableIsDeleted sets the "is_deleted" field if the given value is not nil. +func (_u *AgentPluginUpdateOne) SetNillableIsDeleted(v *bool) *AgentPluginUpdateOne { + if v != nil { + _u.SetIsDeleted(*v) + } + return _u +} + +// SetCreatedAt sets the "created_at" field. +func (_u *AgentPluginUpdateOne) SetCreatedAt(v time.Time) *AgentPluginUpdateOne { + _u.mutation.SetCreatedAt(v) + return _u +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_u *AgentPluginUpdateOne) SetNillableCreatedAt(v *time.Time) *AgentPluginUpdateOne { + if v != nil { + _u.SetCreatedAt(*v) + } + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *AgentPluginUpdateOne) SetUpdatedAt(v time.Time) *AgentPluginUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetRepo sets the "repo" edge to the AgentPluginRepo entity. +func (_u *AgentPluginUpdateOne) SetRepo(v *AgentPluginRepo) *AgentPluginUpdateOne { + return _u.SetRepoID(v.ID) +} + +// AddVersionIDs adds the "versions" edge to the AgentPluginVersion entity by IDs. +func (_u *AgentPluginUpdateOne) AddVersionIDs(ids ...uuid.UUID) *AgentPluginUpdateOne { + _u.mutation.AddVersionIDs(ids...) + return _u +} + +// AddVersions adds the "versions" edges to the AgentPluginVersion entity. +func (_u *AgentPluginUpdateOne) AddVersions(v ...*AgentPluginVersion) *AgentPluginUpdateOne { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddVersionIDs(ids...) +} + +// Mutation returns the AgentPluginMutation object of the builder. +func (_u *AgentPluginUpdateOne) Mutation() *AgentPluginMutation { + return _u.mutation +} + +// ClearRepo clears the "repo" edge to the AgentPluginRepo entity. +func (_u *AgentPluginUpdateOne) ClearRepo() *AgentPluginUpdateOne { + _u.mutation.ClearRepo() + return _u +} + +// ClearVersions clears all "versions" edges to the AgentPluginVersion entity. +func (_u *AgentPluginUpdateOne) ClearVersions() *AgentPluginUpdateOne { + _u.mutation.ClearVersions() + return _u +} + +// RemoveVersionIDs removes the "versions" edge to AgentPluginVersion entities by IDs. +func (_u *AgentPluginUpdateOne) RemoveVersionIDs(ids ...uuid.UUID) *AgentPluginUpdateOne { + _u.mutation.RemoveVersionIDs(ids...) + return _u +} + +// RemoveVersions removes "versions" edges to AgentPluginVersion entities. +func (_u *AgentPluginUpdateOne) RemoveVersions(v ...*AgentPluginVersion) *AgentPluginUpdateOne { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveVersionIDs(ids...) +} + +// Where appends a list predicates to the AgentPluginUpdate builder. +func (_u *AgentPluginUpdateOne) Where(ps ...predicate.AgentPlugin) *AgentPluginUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *AgentPluginUpdateOne) Select(field string, fields ...string) *AgentPluginUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated AgentPlugin entity. +func (_u *AgentPluginUpdateOne) Save(ctx context.Context) (*AgentPlugin, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *AgentPluginUpdateOne) SaveX(ctx context.Context) *AgentPlugin { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *AgentPluginUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *AgentPluginUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_u *AgentPluginUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := agentplugin.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *AgentPluginUpdateOne) check() error { + if v, ok := _u.mutation.Name(); ok { + if err := agentplugin.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "AgentPlugin.name": %w`, err)} + } + } + if v, ok := _u.mutation.ScopeType(); ok { + if err := agentplugin.ScopeTypeValidator(v); err != nil { + return &ValidationError{Name: "scope_type", err: fmt.Errorf(`db: validator failed for field "AgentPlugin.scope_type": %w`, err)} + } + } + if _u.mutation.RepoCleared() && len(_u.mutation.RepoIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "AgentPlugin.repo"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (_u *AgentPluginUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *AgentPluginUpdateOne { + _u.modifiers = append(_u.modifiers, modifiers...) + return _u +} + +func (_u *AgentPluginUpdateOne) sqlSave(ctx context.Context) (_node *AgentPlugin, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(agentplugin.Table, agentplugin.Columns, sqlgraph.NewFieldSpec(agentplugin.FieldID, field.TypeUUID)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "AgentPlugin.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, agentplugin.FieldID) + for _, f := range fields { + if !agentplugin.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != agentplugin.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(agentplugin.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Description(); ok { + _spec.SetField(agentplugin.FieldDescription, field.TypeString, value) + } + if _u.mutation.DescriptionCleared() { + _spec.ClearField(agentplugin.FieldDescription, field.TypeString) + } + if value, ok := _u.mutation.ScopeType(); ok { + _spec.SetField(agentplugin.FieldScopeType, field.TypeEnum, value) + } + if value, ok := _u.mutation.ScopeID(); ok { + _spec.SetField(agentplugin.FieldScopeID, field.TypeString, value) + } + if value, ok := _u.mutation.CreatedBy(); ok { + _spec.SetField(agentplugin.FieldCreatedBy, field.TypeUUID, value) + } + if value, ok := _u.mutation.ActiveVersionID(); ok { + _spec.SetField(agentplugin.FieldActiveVersionID, field.TypeUUID, value) + } + if _u.mutation.ActiveVersionIDCleared() { + _spec.ClearField(agentplugin.FieldActiveVersionID, field.TypeUUID) + } + if value, ok := _u.mutation.IsForceDelivery(); ok { + _spec.SetField(agentplugin.FieldIsForceDelivery, field.TypeBool, value) + } + if value, ok := _u.mutation.IsOrphan(); ok { + _spec.SetField(agentplugin.FieldIsOrphan, field.TypeBool, value) + } + if value, ok := _u.mutation.IsDeleted(); ok { + _spec.SetField(agentplugin.FieldIsDeleted, field.TypeBool, value) + } + if value, ok := _u.mutation.CreatedAt(); ok { + _spec.SetField(agentplugin.FieldCreatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(agentplugin.FieldUpdatedAt, field.TypeTime, value) + } + if _u.mutation.RepoCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: agentplugin.RepoTable, + Columns: []string{agentplugin.RepoColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentpluginrepo.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RepoIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: agentplugin.RepoTable, + Columns: []string{agentplugin.RepoColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentpluginrepo.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.VersionsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agentplugin.VersionsTable, + Columns: []string{agentplugin.VersionsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentpluginversion.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedVersionsIDs(); len(nodes) > 0 && !_u.mutation.VersionsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agentplugin.VersionsTable, + Columns: []string{agentplugin.VersionsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentpluginversion.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.VersionsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agentplugin.VersionsTable, + Columns: []string{agentplugin.VersionsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentpluginversion.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(_u.modifiers...) + _node = &AgentPlugin{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{agentplugin.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/backend/db/agentpluginrepo.go b/backend/db/agentpluginrepo.go new file mode 100644 index 00000000..b347aa5d --- /dev/null +++ b/backend/db/agentpluginrepo.go @@ -0,0 +1,352 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "encoding/json" + "fmt" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/chaitin/MonkeyCode/backend/db/agentpluginrepo" + "github.com/chaitin/MonkeyCode/backend/ent/types" + "github.com/google/uuid" +) + +// AgentPluginRepo is the model entity for the AgentPluginRepo schema. +type AgentPluginRepo struct { + config `json:"-"` + // ID of the ent. + ID uuid.UUID `json:"id,omitempty"` + // Name holds the value of the "name" field. + Name string `json:"name,omitempty"` + // ScopeType holds the value of the "scope_type" field. + ScopeType agentpluginrepo.ScopeType `json:"scope_type,omitempty"` + // ScopeID holds the value of the "scope_id" field. + ScopeID string `json:"scope_id,omitempty"` + // CreatedBy holds the value of the "created_by" field. + CreatedBy uuid.UUID `json:"created_by,omitempty"` + // SourceType holds the value of the "source_type" field. + SourceType agentpluginrepo.SourceType `json:"source_type,omitempty"` + // GithubURL holds the value of the "github_url" field. + GithubURL *string `json:"github_url,omitempty"` + // RefType holds the value of the "ref_type" field. + RefType *agentpluginrepo.RefType `json:"ref_type,omitempty"` + // RefValue holds the value of the "ref_value" field. + RefValue *string `json:"ref_value,omitempty"` + // LastUploadFilename holds the value of the "last_upload_filename" field. + LastUploadFilename *string `json:"last_upload_filename,omitempty"` + // LastUploadAt holds the value of the "last_upload_at" field. + LastUploadAt *time.Time `json:"last_upload_at,omitempty"` + // PluginDiscoveryAutoPackageJSON holds the value of the "plugin_discovery_auto_package_json" field. + PluginDiscoveryAutoPackageJSON bool `json:"plugin_discovery_auto_package_json,omitempty"` + // PluginManualEntries holds the value of the "plugin_manual_entries" field. + PluginManualEntries types.PluginManualEntries `json:"plugin_manual_entries,omitempty"` + // NpmPackageName holds the value of the "npm_package_name" field. + NpmPackageName *string `json:"npm_package_name,omitempty"` + // NpmVersionSpec holds the value of the "npm_version_spec" field. + NpmVersionSpec *string `json:"npm_version_spec,omitempty"` + // NpmRegistryURL holds the value of the "npm_registry_url" field. + NpmRegistryURL *string `json:"npm_registry_url,omitempty"` + // IsDeleted holds the value of the "is_deleted" field. + IsDeleted bool `json:"is_deleted,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + // UpdatedAt holds the value of the "updated_at" field. + UpdatedAt time.Time `json:"updated_at,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the AgentPluginRepoQuery when eager-loading is set. + Edges AgentPluginRepoEdges `json:"edges"` + selectValues sql.SelectValues +} + +// AgentPluginRepoEdges holds the relations/edges for other nodes in the graph. +type AgentPluginRepoEdges struct { + // Plugins holds the value of the plugins edge. + Plugins []*AgentPlugin `json:"plugins,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// PluginsOrErr returns the Plugins value or an error if the edge +// was not loaded in eager-loading. +func (e AgentPluginRepoEdges) PluginsOrErr() ([]*AgentPlugin, error) { + if e.loadedTypes[0] { + return e.Plugins, nil + } + return nil, &NotLoadedError{edge: "plugins"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*AgentPluginRepo) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case agentpluginrepo.FieldPluginManualEntries: + values[i] = new([]byte) + case agentpluginrepo.FieldPluginDiscoveryAutoPackageJSON, agentpluginrepo.FieldIsDeleted: + values[i] = new(sql.NullBool) + case agentpluginrepo.FieldName, agentpluginrepo.FieldScopeType, agentpluginrepo.FieldScopeID, agentpluginrepo.FieldSourceType, agentpluginrepo.FieldGithubURL, agentpluginrepo.FieldRefType, agentpluginrepo.FieldRefValue, agentpluginrepo.FieldLastUploadFilename, agentpluginrepo.FieldNpmPackageName, agentpluginrepo.FieldNpmVersionSpec, agentpluginrepo.FieldNpmRegistryURL: + values[i] = new(sql.NullString) + case agentpluginrepo.FieldLastUploadAt, agentpluginrepo.FieldCreatedAt, agentpluginrepo.FieldUpdatedAt: + values[i] = new(sql.NullTime) + case agentpluginrepo.FieldID, agentpluginrepo.FieldCreatedBy: + 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 AgentPluginRepo fields. +func (_m *AgentPluginRepo) 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 agentpluginrepo.FieldID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value != nil { + _m.ID = *value + } + case agentpluginrepo.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + _m.Name = value.String + } + case agentpluginrepo.FieldScopeType: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field scope_type", values[i]) + } else if value.Valid { + _m.ScopeType = agentpluginrepo.ScopeType(value.String) + } + case agentpluginrepo.FieldScopeID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field scope_id", values[i]) + } else if value.Valid { + _m.ScopeID = value.String + } + case agentpluginrepo.FieldCreatedBy: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field created_by", values[i]) + } else if value != nil { + _m.CreatedBy = *value + } + case agentpluginrepo.FieldSourceType: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field source_type", values[i]) + } else if value.Valid { + _m.SourceType = agentpluginrepo.SourceType(value.String) + } + case agentpluginrepo.FieldGithubURL: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field github_url", values[i]) + } else if value.Valid { + _m.GithubURL = new(string) + *_m.GithubURL = value.String + } + case agentpluginrepo.FieldRefType: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field ref_type", values[i]) + } else if value.Valid { + _m.RefType = new(agentpluginrepo.RefType) + *_m.RefType = agentpluginrepo.RefType(value.String) + } + case agentpluginrepo.FieldRefValue: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field ref_value", values[i]) + } else if value.Valid { + _m.RefValue = new(string) + *_m.RefValue = value.String + } + case agentpluginrepo.FieldLastUploadFilename: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field last_upload_filename", values[i]) + } else if value.Valid { + _m.LastUploadFilename = new(string) + *_m.LastUploadFilename = value.String + } + case agentpluginrepo.FieldLastUploadAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field last_upload_at", values[i]) + } else if value.Valid { + _m.LastUploadAt = new(time.Time) + *_m.LastUploadAt = value.Time + } + case agentpluginrepo.FieldPluginDiscoveryAutoPackageJSON: + if value, ok := values[i].(*sql.NullBool); !ok { + return fmt.Errorf("unexpected type %T for field plugin_discovery_auto_package_json", values[i]) + } else if value.Valid { + _m.PluginDiscoveryAutoPackageJSON = value.Bool + } + case agentpluginrepo.FieldPluginManualEntries: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field plugin_manual_entries", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.PluginManualEntries); err != nil { + return fmt.Errorf("unmarshal field plugin_manual_entries: %w", err) + } + } + case agentpluginrepo.FieldNpmPackageName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field npm_package_name", values[i]) + } else if value.Valid { + _m.NpmPackageName = new(string) + *_m.NpmPackageName = value.String + } + case agentpluginrepo.FieldNpmVersionSpec: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field npm_version_spec", values[i]) + } else if value.Valid { + _m.NpmVersionSpec = new(string) + *_m.NpmVersionSpec = value.String + } + case agentpluginrepo.FieldNpmRegistryURL: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field npm_registry_url", values[i]) + } else if value.Valid { + _m.NpmRegistryURL = new(string) + *_m.NpmRegistryURL = value.String + } + case agentpluginrepo.FieldIsDeleted: + if value, ok := values[i].(*sql.NullBool); !ok { + return fmt.Errorf("unexpected type %T for field is_deleted", values[i]) + } else if value.Valid { + _m.IsDeleted = value.Bool + } + case agentpluginrepo.FieldCreatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field created_at", values[i]) + } else if value.Valid { + _m.CreatedAt = value.Time + } + case agentpluginrepo.FieldUpdatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field updated_at", values[i]) + } else if value.Valid { + _m.UpdatedAt = value.Time + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the AgentPluginRepo. +// This includes values selected through modifiers, order, etc. +func (_m *AgentPluginRepo) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryPlugins queries the "plugins" edge of the AgentPluginRepo entity. +func (_m *AgentPluginRepo) QueryPlugins() *AgentPluginQuery { + return NewAgentPluginRepoClient(_m.config).QueryPlugins(_m) +} + +// Update returns a builder for updating this AgentPluginRepo. +// Note that you need to call AgentPluginRepo.Unwrap() before calling this method if this AgentPluginRepo +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *AgentPluginRepo) Update() *AgentPluginRepoUpdateOne { + return NewAgentPluginRepoClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the AgentPluginRepo entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (_m *AgentPluginRepo) Unwrap() *AgentPluginRepo { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: AgentPluginRepo is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *AgentPluginRepo) String() string { + var builder strings.Builder + builder.WriteString("AgentPluginRepo(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("name=") + builder.WriteString(_m.Name) + builder.WriteString(", ") + builder.WriteString("scope_type=") + builder.WriteString(fmt.Sprintf("%v", _m.ScopeType)) + builder.WriteString(", ") + builder.WriteString("scope_id=") + builder.WriteString(_m.ScopeID) + builder.WriteString(", ") + builder.WriteString("created_by=") + builder.WriteString(fmt.Sprintf("%v", _m.CreatedBy)) + builder.WriteString(", ") + builder.WriteString("source_type=") + builder.WriteString(fmt.Sprintf("%v", _m.SourceType)) + builder.WriteString(", ") + if v := _m.GithubURL; v != nil { + builder.WriteString("github_url=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.RefType; v != nil { + builder.WriteString("ref_type=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.RefValue; v != nil { + builder.WriteString("ref_value=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.LastUploadFilename; v != nil { + builder.WriteString("last_upload_filename=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.LastUploadAt; v != nil { + builder.WriteString("last_upload_at=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteString(", ") + builder.WriteString("plugin_discovery_auto_package_json=") + builder.WriteString(fmt.Sprintf("%v", _m.PluginDiscoveryAutoPackageJSON)) + builder.WriteString(", ") + builder.WriteString("plugin_manual_entries=") + builder.WriteString(fmt.Sprintf("%v", _m.PluginManualEntries)) + builder.WriteString(", ") + if v := _m.NpmPackageName; v != nil { + builder.WriteString("npm_package_name=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.NpmVersionSpec; v != nil { + builder.WriteString("npm_version_spec=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.NpmRegistryURL; v != nil { + builder.WriteString("npm_registry_url=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("is_deleted=") + builder.WriteString(fmt.Sprintf("%v", _m.IsDeleted)) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("updated_at=") + builder.WriteString(_m.UpdatedAt.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// AgentPluginRepos is a parsable slice of AgentPluginRepo. +type AgentPluginRepos []*AgentPluginRepo diff --git a/backend/db/agentpluginrepo/agentpluginrepo.go b/backend/db/agentpluginrepo/agentpluginrepo.go new file mode 100644 index 00000000..b6694120 --- /dev/null +++ b/backend/db/agentpluginrepo/agentpluginrepo.go @@ -0,0 +1,305 @@ +// Code generated by ent, DO NOT EDIT. + +package agentpluginrepo + +import ( + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/google/uuid" +) + +const ( + // Label holds the string label denoting the agentpluginrepo type in the database. + Label = "agent_plugin_repo" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldScopeType holds the string denoting the scope_type field in the database. + FieldScopeType = "scope_type" + // FieldScopeID holds the string denoting the scope_id field in the database. + FieldScopeID = "scope_id" + // FieldCreatedBy holds the string denoting the created_by field in the database. + FieldCreatedBy = "created_by" + // FieldSourceType holds the string denoting the source_type field in the database. + FieldSourceType = "source_type" + // FieldGithubURL holds the string denoting the github_url field in the database. + FieldGithubURL = "github_url" + // FieldRefType holds the string denoting the ref_type field in the database. + FieldRefType = "ref_type" + // FieldRefValue holds the string denoting the ref_value field in the database. + FieldRefValue = "ref_value" + // FieldLastUploadFilename holds the string denoting the last_upload_filename field in the database. + FieldLastUploadFilename = "last_upload_filename" + // FieldLastUploadAt holds the string denoting the last_upload_at field in the database. + FieldLastUploadAt = "last_upload_at" + // FieldPluginDiscoveryAutoPackageJSON holds the string denoting the plugin_discovery_auto_package_json field in the database. + FieldPluginDiscoveryAutoPackageJSON = "plugin_discovery_auto_package_json" + // FieldPluginManualEntries holds the string denoting the plugin_manual_entries field in the database. + FieldPluginManualEntries = "plugin_manual_entries" + // FieldNpmPackageName holds the string denoting the npm_package_name field in the database. + FieldNpmPackageName = "npm_package_name" + // FieldNpmVersionSpec holds the string denoting the npm_version_spec field in the database. + FieldNpmVersionSpec = "npm_version_spec" + // FieldNpmRegistryURL holds the string denoting the npm_registry_url field in the database. + FieldNpmRegistryURL = "npm_registry_url" + // FieldIsDeleted holds the string denoting the is_deleted field in the database. + FieldIsDeleted = "is_deleted" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // FieldUpdatedAt holds the string denoting the updated_at field in the database. + FieldUpdatedAt = "updated_at" + // EdgePlugins holds the string denoting the plugins edge name in mutations. + EdgePlugins = "plugins" + // Table holds the table name of the agentpluginrepo in the database. + Table = "agent_plugin_repos" + // PluginsTable is the table that holds the plugins relation/edge. + PluginsTable = "agent_plugins" + // PluginsInverseTable is the table name for the AgentPlugin entity. + // It exists in this package in order to avoid circular dependency with the "agentplugin" package. + PluginsInverseTable = "agent_plugins" + // PluginsColumn is the table column denoting the plugins relation/edge. + PluginsColumn = "repo_id" +) + +// Columns holds all SQL columns for agentpluginrepo fields. +var Columns = []string{ + FieldID, + FieldName, + FieldScopeType, + FieldScopeID, + FieldCreatedBy, + FieldSourceType, + FieldGithubURL, + FieldRefType, + FieldRefValue, + FieldLastUploadFilename, + FieldLastUploadAt, + FieldPluginDiscoveryAutoPackageJSON, + FieldPluginManualEntries, + FieldNpmPackageName, + FieldNpmVersionSpec, + FieldNpmRegistryURL, + FieldIsDeleted, + FieldCreatedAt, + FieldUpdatedAt, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // NameValidator is a validator for the "name" field. It is called by the builders before save. + NameValidator func(string) error + // DefaultScopeID holds the default value on creation for the "scope_id" field. + DefaultScopeID string + // DefaultPluginDiscoveryAutoPackageJSON holds the default value on creation for the "plugin_discovery_auto_package_json" field. + DefaultPluginDiscoveryAutoPackageJSON bool + // DefaultIsDeleted holds the default value on creation for the "is_deleted" field. + DefaultIsDeleted bool + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time + // DefaultUpdatedAt holds the default value on creation for the "updated_at" field. + DefaultUpdatedAt func() time.Time + // UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field. + UpdateDefaultUpdatedAt func() time.Time + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() uuid.UUID +) + +// ScopeType defines the type for the "scope_type" enum field. +type ScopeType string + +// ScopeTypeGlobal is the default value of the ScopeType enum. +const DefaultScopeType = ScopeTypeGlobal + +// ScopeType values. +const ( + ScopeTypeGlobal ScopeType = "global" +) + +func (st ScopeType) String() string { + return string(st) +} + +// ScopeTypeValidator is a validator for the "scope_type" field enum values. It is called by the builders before save. +func ScopeTypeValidator(st ScopeType) error { + switch st { + case ScopeTypeGlobal: + return nil + default: + return fmt.Errorf("agentpluginrepo: invalid enum value for scope_type field: %q", st) + } +} + +// SourceType defines the type for the "source_type" enum field. +type SourceType string + +// SourceType values. +const ( + SourceTypeGithub SourceType = "github" + SourceTypeUpload SourceType = "upload" + SourceTypeNpm SourceType = "npm" +) + +func (st SourceType) String() string { + return string(st) +} + +// SourceTypeValidator is a validator for the "source_type" field enum values. It is called by the builders before save. +func SourceTypeValidator(st SourceType) error { + switch st { + case SourceTypeGithub, SourceTypeUpload, SourceTypeNpm: + return nil + default: + return fmt.Errorf("agentpluginrepo: invalid enum value for source_type field: %q", st) + } +} + +// RefType defines the type for the "ref_type" enum field. +type RefType string + +// RefType values. +const ( + RefTypeBranch RefType = "branch" + RefTypeTag RefType = "tag" + RefTypeCommit RefType = "commit" +) + +func (rt RefType) String() string { + return string(rt) +} + +// RefTypeValidator is a validator for the "ref_type" field enum values. It is called by the builders before save. +func RefTypeValidator(rt RefType) error { + switch rt { + case RefTypeBranch, RefTypeTag, RefTypeCommit: + return nil + default: + return fmt.Errorf("agentpluginrepo: invalid enum value for ref_type field: %q", rt) + } +} + +// OrderOption defines the ordering options for the AgentPluginRepo queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} + +// ByScopeType orders the results by the scope_type field. +func ByScopeType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldScopeType, opts...).ToFunc() +} + +// ByScopeID orders the results by the scope_id field. +func ByScopeID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldScopeID, opts...).ToFunc() +} + +// ByCreatedBy orders the results by the created_by field. +func ByCreatedBy(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedBy, opts...).ToFunc() +} + +// BySourceType orders the results by the source_type field. +func BySourceType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSourceType, opts...).ToFunc() +} + +// ByGithubURL orders the results by the github_url field. +func ByGithubURL(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldGithubURL, opts...).ToFunc() +} + +// ByRefType orders the results by the ref_type field. +func ByRefType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRefType, opts...).ToFunc() +} + +// ByRefValue orders the results by the ref_value field. +func ByRefValue(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRefValue, opts...).ToFunc() +} + +// ByLastUploadFilename orders the results by the last_upload_filename field. +func ByLastUploadFilename(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldLastUploadFilename, opts...).ToFunc() +} + +// ByLastUploadAt orders the results by the last_upload_at field. +func ByLastUploadAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldLastUploadAt, opts...).ToFunc() +} + +// ByPluginDiscoveryAutoPackageJSON orders the results by the plugin_discovery_auto_package_json field. +func ByPluginDiscoveryAutoPackageJSON(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPluginDiscoveryAutoPackageJSON, opts...).ToFunc() +} + +// ByNpmPackageName orders the results by the npm_package_name field. +func ByNpmPackageName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldNpmPackageName, opts...).ToFunc() +} + +// ByNpmVersionSpec orders the results by the npm_version_spec field. +func ByNpmVersionSpec(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldNpmVersionSpec, opts...).ToFunc() +} + +// ByNpmRegistryURL orders the results by the npm_registry_url field. +func ByNpmRegistryURL(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldNpmRegistryURL, opts...).ToFunc() +} + +// ByIsDeleted orders the results by the is_deleted field. +func ByIsDeleted(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldIsDeleted, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// ByUpdatedAt orders the results by the updated_at field. +func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc() +} + +// ByPluginsCount orders the results by plugins count. +func ByPluginsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newPluginsStep(), opts...) + } +} + +// ByPlugins orders the results by plugins terms. +func ByPlugins(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newPluginsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newPluginsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(PluginsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, PluginsTable, PluginsColumn), + ) +} diff --git a/backend/db/agentpluginrepo/where.go b/backend/db/agentpluginrepo/where.go new file mode 100644 index 00000000..0e96ea76 --- /dev/null +++ b/backend/db/agentpluginrepo/where.go @@ -0,0 +1,1015 @@ +// Code generated by ent, DO NOT EDIT. + +package agentpluginrepo + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/google/uuid" +) + +// ID filters vertices based on their ID field. +func ID(id uuid.UUID) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id uuid.UUID) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id uuid.UUID) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...uuid.UUID) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...uuid.UUID) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id uuid.UUID) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id uuid.UUID) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id uuid.UUID) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id uuid.UUID) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldLTE(FieldID, id)) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldEQ(FieldName, v)) +} + +// ScopeID applies equality check predicate on the "scope_id" field. It's identical to ScopeIDEQ. +func ScopeID(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldEQ(FieldScopeID, v)) +} + +// CreatedBy applies equality check predicate on the "created_by" field. It's identical to CreatedByEQ. +func CreatedBy(v uuid.UUID) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldEQ(FieldCreatedBy, v)) +} + +// GithubURL applies equality check predicate on the "github_url" field. It's identical to GithubURLEQ. +func GithubURL(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldEQ(FieldGithubURL, v)) +} + +// RefValue applies equality check predicate on the "ref_value" field. It's identical to RefValueEQ. +func RefValue(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldEQ(FieldRefValue, v)) +} + +// LastUploadFilename applies equality check predicate on the "last_upload_filename" field. It's identical to LastUploadFilenameEQ. +func LastUploadFilename(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldEQ(FieldLastUploadFilename, v)) +} + +// LastUploadAt applies equality check predicate on the "last_upload_at" field. It's identical to LastUploadAtEQ. +func LastUploadAt(v time.Time) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldEQ(FieldLastUploadAt, v)) +} + +// PluginDiscoveryAutoPackageJSON applies equality check predicate on the "plugin_discovery_auto_package_json" field. It's identical to PluginDiscoveryAutoPackageJSONEQ. +func PluginDiscoveryAutoPackageJSON(v bool) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldEQ(FieldPluginDiscoveryAutoPackageJSON, v)) +} + +// NpmPackageName applies equality check predicate on the "npm_package_name" field. It's identical to NpmPackageNameEQ. +func NpmPackageName(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldEQ(FieldNpmPackageName, v)) +} + +// NpmVersionSpec applies equality check predicate on the "npm_version_spec" field. It's identical to NpmVersionSpecEQ. +func NpmVersionSpec(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldEQ(FieldNpmVersionSpec, v)) +} + +// NpmRegistryURL applies equality check predicate on the "npm_registry_url" field. It's identical to NpmRegistryURLEQ. +func NpmRegistryURL(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldEQ(FieldNpmRegistryURL, v)) +} + +// IsDeleted applies equality check predicate on the "is_deleted" field. It's identical to IsDeletedEQ. +func IsDeleted(v bool) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldEQ(FieldIsDeleted, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldEQ(FieldCreatedAt, v)) +} + +// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ. +func UpdatedAt(v time.Time) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldEQ(FieldName, v)) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNEQ(FieldName, v)) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldIn(FieldName, vs...)) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNotIn(FieldName, vs...)) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldGT(FieldName, v)) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldGTE(FieldName, v)) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldLT(FieldName, v)) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldLTE(FieldName, v)) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldContains(FieldName, v)) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldHasPrefix(FieldName, v)) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldHasSuffix(FieldName, v)) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldEqualFold(FieldName, v)) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldContainsFold(FieldName, v)) +} + +// ScopeTypeEQ applies the EQ predicate on the "scope_type" field. +func ScopeTypeEQ(v ScopeType) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldEQ(FieldScopeType, v)) +} + +// ScopeTypeNEQ applies the NEQ predicate on the "scope_type" field. +func ScopeTypeNEQ(v ScopeType) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNEQ(FieldScopeType, v)) +} + +// ScopeTypeIn applies the In predicate on the "scope_type" field. +func ScopeTypeIn(vs ...ScopeType) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldIn(FieldScopeType, vs...)) +} + +// ScopeTypeNotIn applies the NotIn predicate on the "scope_type" field. +func ScopeTypeNotIn(vs ...ScopeType) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNotIn(FieldScopeType, vs...)) +} + +// ScopeIDEQ applies the EQ predicate on the "scope_id" field. +func ScopeIDEQ(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldEQ(FieldScopeID, v)) +} + +// ScopeIDNEQ applies the NEQ predicate on the "scope_id" field. +func ScopeIDNEQ(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNEQ(FieldScopeID, v)) +} + +// ScopeIDIn applies the In predicate on the "scope_id" field. +func ScopeIDIn(vs ...string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldIn(FieldScopeID, vs...)) +} + +// ScopeIDNotIn applies the NotIn predicate on the "scope_id" field. +func ScopeIDNotIn(vs ...string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNotIn(FieldScopeID, vs...)) +} + +// ScopeIDGT applies the GT predicate on the "scope_id" field. +func ScopeIDGT(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldGT(FieldScopeID, v)) +} + +// ScopeIDGTE applies the GTE predicate on the "scope_id" field. +func ScopeIDGTE(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldGTE(FieldScopeID, v)) +} + +// ScopeIDLT applies the LT predicate on the "scope_id" field. +func ScopeIDLT(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldLT(FieldScopeID, v)) +} + +// ScopeIDLTE applies the LTE predicate on the "scope_id" field. +func ScopeIDLTE(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldLTE(FieldScopeID, v)) +} + +// ScopeIDContains applies the Contains predicate on the "scope_id" field. +func ScopeIDContains(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldContains(FieldScopeID, v)) +} + +// ScopeIDHasPrefix applies the HasPrefix predicate on the "scope_id" field. +func ScopeIDHasPrefix(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldHasPrefix(FieldScopeID, v)) +} + +// ScopeIDHasSuffix applies the HasSuffix predicate on the "scope_id" field. +func ScopeIDHasSuffix(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldHasSuffix(FieldScopeID, v)) +} + +// ScopeIDEqualFold applies the EqualFold predicate on the "scope_id" field. +func ScopeIDEqualFold(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldEqualFold(FieldScopeID, v)) +} + +// ScopeIDContainsFold applies the ContainsFold predicate on the "scope_id" field. +func ScopeIDContainsFold(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldContainsFold(FieldScopeID, v)) +} + +// CreatedByEQ applies the EQ predicate on the "created_by" field. +func CreatedByEQ(v uuid.UUID) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldEQ(FieldCreatedBy, v)) +} + +// CreatedByNEQ applies the NEQ predicate on the "created_by" field. +func CreatedByNEQ(v uuid.UUID) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNEQ(FieldCreatedBy, v)) +} + +// CreatedByIn applies the In predicate on the "created_by" field. +func CreatedByIn(vs ...uuid.UUID) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldIn(FieldCreatedBy, vs...)) +} + +// CreatedByNotIn applies the NotIn predicate on the "created_by" field. +func CreatedByNotIn(vs ...uuid.UUID) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNotIn(FieldCreatedBy, vs...)) +} + +// CreatedByGT applies the GT predicate on the "created_by" field. +func CreatedByGT(v uuid.UUID) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldGT(FieldCreatedBy, v)) +} + +// CreatedByGTE applies the GTE predicate on the "created_by" field. +func CreatedByGTE(v uuid.UUID) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldGTE(FieldCreatedBy, v)) +} + +// CreatedByLT applies the LT predicate on the "created_by" field. +func CreatedByLT(v uuid.UUID) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldLT(FieldCreatedBy, v)) +} + +// CreatedByLTE applies the LTE predicate on the "created_by" field. +func CreatedByLTE(v uuid.UUID) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldLTE(FieldCreatedBy, v)) +} + +// SourceTypeEQ applies the EQ predicate on the "source_type" field. +func SourceTypeEQ(v SourceType) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldEQ(FieldSourceType, v)) +} + +// SourceTypeNEQ applies the NEQ predicate on the "source_type" field. +func SourceTypeNEQ(v SourceType) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNEQ(FieldSourceType, v)) +} + +// SourceTypeIn applies the In predicate on the "source_type" field. +func SourceTypeIn(vs ...SourceType) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldIn(FieldSourceType, vs...)) +} + +// SourceTypeNotIn applies the NotIn predicate on the "source_type" field. +func SourceTypeNotIn(vs ...SourceType) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNotIn(FieldSourceType, vs...)) +} + +// GithubURLEQ applies the EQ predicate on the "github_url" field. +func GithubURLEQ(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldEQ(FieldGithubURL, v)) +} + +// GithubURLNEQ applies the NEQ predicate on the "github_url" field. +func GithubURLNEQ(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNEQ(FieldGithubURL, v)) +} + +// GithubURLIn applies the In predicate on the "github_url" field. +func GithubURLIn(vs ...string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldIn(FieldGithubURL, vs...)) +} + +// GithubURLNotIn applies the NotIn predicate on the "github_url" field. +func GithubURLNotIn(vs ...string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNotIn(FieldGithubURL, vs...)) +} + +// GithubURLGT applies the GT predicate on the "github_url" field. +func GithubURLGT(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldGT(FieldGithubURL, v)) +} + +// GithubURLGTE applies the GTE predicate on the "github_url" field. +func GithubURLGTE(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldGTE(FieldGithubURL, v)) +} + +// GithubURLLT applies the LT predicate on the "github_url" field. +func GithubURLLT(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldLT(FieldGithubURL, v)) +} + +// GithubURLLTE applies the LTE predicate on the "github_url" field. +func GithubURLLTE(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldLTE(FieldGithubURL, v)) +} + +// GithubURLContains applies the Contains predicate on the "github_url" field. +func GithubURLContains(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldContains(FieldGithubURL, v)) +} + +// GithubURLHasPrefix applies the HasPrefix predicate on the "github_url" field. +func GithubURLHasPrefix(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldHasPrefix(FieldGithubURL, v)) +} + +// GithubURLHasSuffix applies the HasSuffix predicate on the "github_url" field. +func GithubURLHasSuffix(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldHasSuffix(FieldGithubURL, v)) +} + +// GithubURLIsNil applies the IsNil predicate on the "github_url" field. +func GithubURLIsNil() predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldIsNull(FieldGithubURL)) +} + +// GithubURLNotNil applies the NotNil predicate on the "github_url" field. +func GithubURLNotNil() predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNotNull(FieldGithubURL)) +} + +// GithubURLEqualFold applies the EqualFold predicate on the "github_url" field. +func GithubURLEqualFold(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldEqualFold(FieldGithubURL, v)) +} + +// GithubURLContainsFold applies the ContainsFold predicate on the "github_url" field. +func GithubURLContainsFold(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldContainsFold(FieldGithubURL, v)) +} + +// RefTypeEQ applies the EQ predicate on the "ref_type" field. +func RefTypeEQ(v RefType) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldEQ(FieldRefType, v)) +} + +// RefTypeNEQ applies the NEQ predicate on the "ref_type" field. +func RefTypeNEQ(v RefType) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNEQ(FieldRefType, v)) +} + +// RefTypeIn applies the In predicate on the "ref_type" field. +func RefTypeIn(vs ...RefType) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldIn(FieldRefType, vs...)) +} + +// RefTypeNotIn applies the NotIn predicate on the "ref_type" field. +func RefTypeNotIn(vs ...RefType) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNotIn(FieldRefType, vs...)) +} + +// RefTypeIsNil applies the IsNil predicate on the "ref_type" field. +func RefTypeIsNil() predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldIsNull(FieldRefType)) +} + +// RefTypeNotNil applies the NotNil predicate on the "ref_type" field. +func RefTypeNotNil() predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNotNull(FieldRefType)) +} + +// RefValueEQ applies the EQ predicate on the "ref_value" field. +func RefValueEQ(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldEQ(FieldRefValue, v)) +} + +// RefValueNEQ applies the NEQ predicate on the "ref_value" field. +func RefValueNEQ(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNEQ(FieldRefValue, v)) +} + +// RefValueIn applies the In predicate on the "ref_value" field. +func RefValueIn(vs ...string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldIn(FieldRefValue, vs...)) +} + +// RefValueNotIn applies the NotIn predicate on the "ref_value" field. +func RefValueNotIn(vs ...string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNotIn(FieldRefValue, vs...)) +} + +// RefValueGT applies the GT predicate on the "ref_value" field. +func RefValueGT(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldGT(FieldRefValue, v)) +} + +// RefValueGTE applies the GTE predicate on the "ref_value" field. +func RefValueGTE(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldGTE(FieldRefValue, v)) +} + +// RefValueLT applies the LT predicate on the "ref_value" field. +func RefValueLT(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldLT(FieldRefValue, v)) +} + +// RefValueLTE applies the LTE predicate on the "ref_value" field. +func RefValueLTE(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldLTE(FieldRefValue, v)) +} + +// RefValueContains applies the Contains predicate on the "ref_value" field. +func RefValueContains(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldContains(FieldRefValue, v)) +} + +// RefValueHasPrefix applies the HasPrefix predicate on the "ref_value" field. +func RefValueHasPrefix(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldHasPrefix(FieldRefValue, v)) +} + +// RefValueHasSuffix applies the HasSuffix predicate on the "ref_value" field. +func RefValueHasSuffix(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldHasSuffix(FieldRefValue, v)) +} + +// RefValueIsNil applies the IsNil predicate on the "ref_value" field. +func RefValueIsNil() predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldIsNull(FieldRefValue)) +} + +// RefValueNotNil applies the NotNil predicate on the "ref_value" field. +func RefValueNotNil() predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNotNull(FieldRefValue)) +} + +// RefValueEqualFold applies the EqualFold predicate on the "ref_value" field. +func RefValueEqualFold(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldEqualFold(FieldRefValue, v)) +} + +// RefValueContainsFold applies the ContainsFold predicate on the "ref_value" field. +func RefValueContainsFold(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldContainsFold(FieldRefValue, v)) +} + +// LastUploadFilenameEQ applies the EQ predicate on the "last_upload_filename" field. +func LastUploadFilenameEQ(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldEQ(FieldLastUploadFilename, v)) +} + +// LastUploadFilenameNEQ applies the NEQ predicate on the "last_upload_filename" field. +func LastUploadFilenameNEQ(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNEQ(FieldLastUploadFilename, v)) +} + +// LastUploadFilenameIn applies the In predicate on the "last_upload_filename" field. +func LastUploadFilenameIn(vs ...string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldIn(FieldLastUploadFilename, vs...)) +} + +// LastUploadFilenameNotIn applies the NotIn predicate on the "last_upload_filename" field. +func LastUploadFilenameNotIn(vs ...string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNotIn(FieldLastUploadFilename, vs...)) +} + +// LastUploadFilenameGT applies the GT predicate on the "last_upload_filename" field. +func LastUploadFilenameGT(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldGT(FieldLastUploadFilename, v)) +} + +// LastUploadFilenameGTE applies the GTE predicate on the "last_upload_filename" field. +func LastUploadFilenameGTE(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldGTE(FieldLastUploadFilename, v)) +} + +// LastUploadFilenameLT applies the LT predicate on the "last_upload_filename" field. +func LastUploadFilenameLT(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldLT(FieldLastUploadFilename, v)) +} + +// LastUploadFilenameLTE applies the LTE predicate on the "last_upload_filename" field. +func LastUploadFilenameLTE(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldLTE(FieldLastUploadFilename, v)) +} + +// LastUploadFilenameContains applies the Contains predicate on the "last_upload_filename" field. +func LastUploadFilenameContains(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldContains(FieldLastUploadFilename, v)) +} + +// LastUploadFilenameHasPrefix applies the HasPrefix predicate on the "last_upload_filename" field. +func LastUploadFilenameHasPrefix(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldHasPrefix(FieldLastUploadFilename, v)) +} + +// LastUploadFilenameHasSuffix applies the HasSuffix predicate on the "last_upload_filename" field. +func LastUploadFilenameHasSuffix(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldHasSuffix(FieldLastUploadFilename, v)) +} + +// LastUploadFilenameIsNil applies the IsNil predicate on the "last_upload_filename" field. +func LastUploadFilenameIsNil() predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldIsNull(FieldLastUploadFilename)) +} + +// LastUploadFilenameNotNil applies the NotNil predicate on the "last_upload_filename" field. +func LastUploadFilenameNotNil() predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNotNull(FieldLastUploadFilename)) +} + +// LastUploadFilenameEqualFold applies the EqualFold predicate on the "last_upload_filename" field. +func LastUploadFilenameEqualFold(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldEqualFold(FieldLastUploadFilename, v)) +} + +// LastUploadFilenameContainsFold applies the ContainsFold predicate on the "last_upload_filename" field. +func LastUploadFilenameContainsFold(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldContainsFold(FieldLastUploadFilename, v)) +} + +// LastUploadAtEQ applies the EQ predicate on the "last_upload_at" field. +func LastUploadAtEQ(v time.Time) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldEQ(FieldLastUploadAt, v)) +} + +// LastUploadAtNEQ applies the NEQ predicate on the "last_upload_at" field. +func LastUploadAtNEQ(v time.Time) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNEQ(FieldLastUploadAt, v)) +} + +// LastUploadAtIn applies the In predicate on the "last_upload_at" field. +func LastUploadAtIn(vs ...time.Time) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldIn(FieldLastUploadAt, vs...)) +} + +// LastUploadAtNotIn applies the NotIn predicate on the "last_upload_at" field. +func LastUploadAtNotIn(vs ...time.Time) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNotIn(FieldLastUploadAt, vs...)) +} + +// LastUploadAtGT applies the GT predicate on the "last_upload_at" field. +func LastUploadAtGT(v time.Time) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldGT(FieldLastUploadAt, v)) +} + +// LastUploadAtGTE applies the GTE predicate on the "last_upload_at" field. +func LastUploadAtGTE(v time.Time) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldGTE(FieldLastUploadAt, v)) +} + +// LastUploadAtLT applies the LT predicate on the "last_upload_at" field. +func LastUploadAtLT(v time.Time) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldLT(FieldLastUploadAt, v)) +} + +// LastUploadAtLTE applies the LTE predicate on the "last_upload_at" field. +func LastUploadAtLTE(v time.Time) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldLTE(FieldLastUploadAt, v)) +} + +// LastUploadAtIsNil applies the IsNil predicate on the "last_upload_at" field. +func LastUploadAtIsNil() predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldIsNull(FieldLastUploadAt)) +} + +// LastUploadAtNotNil applies the NotNil predicate on the "last_upload_at" field. +func LastUploadAtNotNil() predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNotNull(FieldLastUploadAt)) +} + +// PluginDiscoveryAutoPackageJSONEQ applies the EQ predicate on the "plugin_discovery_auto_package_json" field. +func PluginDiscoveryAutoPackageJSONEQ(v bool) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldEQ(FieldPluginDiscoveryAutoPackageJSON, v)) +} + +// PluginDiscoveryAutoPackageJSONNEQ applies the NEQ predicate on the "plugin_discovery_auto_package_json" field. +func PluginDiscoveryAutoPackageJSONNEQ(v bool) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNEQ(FieldPluginDiscoveryAutoPackageJSON, v)) +} + +// PluginManualEntriesIsNil applies the IsNil predicate on the "plugin_manual_entries" field. +func PluginManualEntriesIsNil() predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldIsNull(FieldPluginManualEntries)) +} + +// PluginManualEntriesNotNil applies the NotNil predicate on the "plugin_manual_entries" field. +func PluginManualEntriesNotNil() predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNotNull(FieldPluginManualEntries)) +} + +// NpmPackageNameEQ applies the EQ predicate on the "npm_package_name" field. +func NpmPackageNameEQ(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldEQ(FieldNpmPackageName, v)) +} + +// NpmPackageNameNEQ applies the NEQ predicate on the "npm_package_name" field. +func NpmPackageNameNEQ(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNEQ(FieldNpmPackageName, v)) +} + +// NpmPackageNameIn applies the In predicate on the "npm_package_name" field. +func NpmPackageNameIn(vs ...string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldIn(FieldNpmPackageName, vs...)) +} + +// NpmPackageNameNotIn applies the NotIn predicate on the "npm_package_name" field. +func NpmPackageNameNotIn(vs ...string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNotIn(FieldNpmPackageName, vs...)) +} + +// NpmPackageNameGT applies the GT predicate on the "npm_package_name" field. +func NpmPackageNameGT(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldGT(FieldNpmPackageName, v)) +} + +// NpmPackageNameGTE applies the GTE predicate on the "npm_package_name" field. +func NpmPackageNameGTE(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldGTE(FieldNpmPackageName, v)) +} + +// NpmPackageNameLT applies the LT predicate on the "npm_package_name" field. +func NpmPackageNameLT(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldLT(FieldNpmPackageName, v)) +} + +// NpmPackageNameLTE applies the LTE predicate on the "npm_package_name" field. +func NpmPackageNameLTE(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldLTE(FieldNpmPackageName, v)) +} + +// NpmPackageNameContains applies the Contains predicate on the "npm_package_name" field. +func NpmPackageNameContains(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldContains(FieldNpmPackageName, v)) +} + +// NpmPackageNameHasPrefix applies the HasPrefix predicate on the "npm_package_name" field. +func NpmPackageNameHasPrefix(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldHasPrefix(FieldNpmPackageName, v)) +} + +// NpmPackageNameHasSuffix applies the HasSuffix predicate on the "npm_package_name" field. +func NpmPackageNameHasSuffix(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldHasSuffix(FieldNpmPackageName, v)) +} + +// NpmPackageNameIsNil applies the IsNil predicate on the "npm_package_name" field. +func NpmPackageNameIsNil() predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldIsNull(FieldNpmPackageName)) +} + +// NpmPackageNameNotNil applies the NotNil predicate on the "npm_package_name" field. +func NpmPackageNameNotNil() predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNotNull(FieldNpmPackageName)) +} + +// NpmPackageNameEqualFold applies the EqualFold predicate on the "npm_package_name" field. +func NpmPackageNameEqualFold(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldEqualFold(FieldNpmPackageName, v)) +} + +// NpmPackageNameContainsFold applies the ContainsFold predicate on the "npm_package_name" field. +func NpmPackageNameContainsFold(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldContainsFold(FieldNpmPackageName, v)) +} + +// NpmVersionSpecEQ applies the EQ predicate on the "npm_version_spec" field. +func NpmVersionSpecEQ(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldEQ(FieldNpmVersionSpec, v)) +} + +// NpmVersionSpecNEQ applies the NEQ predicate on the "npm_version_spec" field. +func NpmVersionSpecNEQ(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNEQ(FieldNpmVersionSpec, v)) +} + +// NpmVersionSpecIn applies the In predicate on the "npm_version_spec" field. +func NpmVersionSpecIn(vs ...string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldIn(FieldNpmVersionSpec, vs...)) +} + +// NpmVersionSpecNotIn applies the NotIn predicate on the "npm_version_spec" field. +func NpmVersionSpecNotIn(vs ...string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNotIn(FieldNpmVersionSpec, vs...)) +} + +// NpmVersionSpecGT applies the GT predicate on the "npm_version_spec" field. +func NpmVersionSpecGT(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldGT(FieldNpmVersionSpec, v)) +} + +// NpmVersionSpecGTE applies the GTE predicate on the "npm_version_spec" field. +func NpmVersionSpecGTE(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldGTE(FieldNpmVersionSpec, v)) +} + +// NpmVersionSpecLT applies the LT predicate on the "npm_version_spec" field. +func NpmVersionSpecLT(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldLT(FieldNpmVersionSpec, v)) +} + +// NpmVersionSpecLTE applies the LTE predicate on the "npm_version_spec" field. +func NpmVersionSpecLTE(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldLTE(FieldNpmVersionSpec, v)) +} + +// NpmVersionSpecContains applies the Contains predicate on the "npm_version_spec" field. +func NpmVersionSpecContains(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldContains(FieldNpmVersionSpec, v)) +} + +// NpmVersionSpecHasPrefix applies the HasPrefix predicate on the "npm_version_spec" field. +func NpmVersionSpecHasPrefix(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldHasPrefix(FieldNpmVersionSpec, v)) +} + +// NpmVersionSpecHasSuffix applies the HasSuffix predicate on the "npm_version_spec" field. +func NpmVersionSpecHasSuffix(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldHasSuffix(FieldNpmVersionSpec, v)) +} + +// NpmVersionSpecIsNil applies the IsNil predicate on the "npm_version_spec" field. +func NpmVersionSpecIsNil() predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldIsNull(FieldNpmVersionSpec)) +} + +// NpmVersionSpecNotNil applies the NotNil predicate on the "npm_version_spec" field. +func NpmVersionSpecNotNil() predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNotNull(FieldNpmVersionSpec)) +} + +// NpmVersionSpecEqualFold applies the EqualFold predicate on the "npm_version_spec" field. +func NpmVersionSpecEqualFold(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldEqualFold(FieldNpmVersionSpec, v)) +} + +// NpmVersionSpecContainsFold applies the ContainsFold predicate on the "npm_version_spec" field. +func NpmVersionSpecContainsFold(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldContainsFold(FieldNpmVersionSpec, v)) +} + +// NpmRegistryURLEQ applies the EQ predicate on the "npm_registry_url" field. +func NpmRegistryURLEQ(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldEQ(FieldNpmRegistryURL, v)) +} + +// NpmRegistryURLNEQ applies the NEQ predicate on the "npm_registry_url" field. +func NpmRegistryURLNEQ(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNEQ(FieldNpmRegistryURL, v)) +} + +// NpmRegistryURLIn applies the In predicate on the "npm_registry_url" field. +func NpmRegistryURLIn(vs ...string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldIn(FieldNpmRegistryURL, vs...)) +} + +// NpmRegistryURLNotIn applies the NotIn predicate on the "npm_registry_url" field. +func NpmRegistryURLNotIn(vs ...string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNotIn(FieldNpmRegistryURL, vs...)) +} + +// NpmRegistryURLGT applies the GT predicate on the "npm_registry_url" field. +func NpmRegistryURLGT(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldGT(FieldNpmRegistryURL, v)) +} + +// NpmRegistryURLGTE applies the GTE predicate on the "npm_registry_url" field. +func NpmRegistryURLGTE(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldGTE(FieldNpmRegistryURL, v)) +} + +// NpmRegistryURLLT applies the LT predicate on the "npm_registry_url" field. +func NpmRegistryURLLT(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldLT(FieldNpmRegistryURL, v)) +} + +// NpmRegistryURLLTE applies the LTE predicate on the "npm_registry_url" field. +func NpmRegistryURLLTE(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldLTE(FieldNpmRegistryURL, v)) +} + +// NpmRegistryURLContains applies the Contains predicate on the "npm_registry_url" field. +func NpmRegistryURLContains(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldContains(FieldNpmRegistryURL, v)) +} + +// NpmRegistryURLHasPrefix applies the HasPrefix predicate on the "npm_registry_url" field. +func NpmRegistryURLHasPrefix(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldHasPrefix(FieldNpmRegistryURL, v)) +} + +// NpmRegistryURLHasSuffix applies the HasSuffix predicate on the "npm_registry_url" field. +func NpmRegistryURLHasSuffix(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldHasSuffix(FieldNpmRegistryURL, v)) +} + +// NpmRegistryURLIsNil applies the IsNil predicate on the "npm_registry_url" field. +func NpmRegistryURLIsNil() predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldIsNull(FieldNpmRegistryURL)) +} + +// NpmRegistryURLNotNil applies the NotNil predicate on the "npm_registry_url" field. +func NpmRegistryURLNotNil() predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNotNull(FieldNpmRegistryURL)) +} + +// NpmRegistryURLEqualFold applies the EqualFold predicate on the "npm_registry_url" field. +func NpmRegistryURLEqualFold(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldEqualFold(FieldNpmRegistryURL, v)) +} + +// NpmRegistryURLContainsFold applies the ContainsFold predicate on the "npm_registry_url" field. +func NpmRegistryURLContainsFold(v string) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldContainsFold(FieldNpmRegistryURL, v)) +} + +// IsDeletedEQ applies the EQ predicate on the "is_deleted" field. +func IsDeletedEQ(v bool) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldEQ(FieldIsDeleted, v)) +} + +// IsDeletedNEQ applies the NEQ predicate on the "is_deleted" field. +func IsDeletedNEQ(v bool) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNEQ(FieldIsDeleted, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// HasPlugins applies the HasEdge predicate on the "plugins" edge. +func HasPlugins() predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, PluginsTable, PluginsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasPluginsWith applies the HasEdge predicate on the "plugins" edge with a given conditions (other predicates). +func HasPluginsWith(preds ...predicate.AgentPlugin) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(func(s *sql.Selector) { + step := newPluginsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.AgentPluginRepo) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.AgentPluginRepo) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.AgentPluginRepo) predicate.AgentPluginRepo { + return predicate.AgentPluginRepo(sql.NotPredicates(p)) +} diff --git a/backend/db/agentpluginrepo_create.go b/backend/db/agentpluginrepo_create.go new file mode 100644 index 00000000..d4d7166b --- /dev/null +++ b/backend/db/agentpluginrepo_create.go @@ -0,0 +1,1752 @@ +// 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/agentplugin" + "github.com/chaitin/MonkeyCode/backend/db/agentpluginrepo" + "github.com/chaitin/MonkeyCode/backend/ent/types" + "github.com/google/uuid" +) + +// AgentPluginRepoCreate is the builder for creating a AgentPluginRepo entity. +type AgentPluginRepoCreate struct { + config + mutation *AgentPluginRepoMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetName sets the "name" field. +func (_c *AgentPluginRepoCreate) SetName(v string) *AgentPluginRepoCreate { + _c.mutation.SetName(v) + return _c +} + +// SetScopeType sets the "scope_type" field. +func (_c *AgentPluginRepoCreate) SetScopeType(v agentpluginrepo.ScopeType) *AgentPluginRepoCreate { + _c.mutation.SetScopeType(v) + return _c +} + +// SetNillableScopeType sets the "scope_type" field if the given value is not nil. +func (_c *AgentPluginRepoCreate) SetNillableScopeType(v *agentpluginrepo.ScopeType) *AgentPluginRepoCreate { + if v != nil { + _c.SetScopeType(*v) + } + return _c +} + +// SetScopeID sets the "scope_id" field. +func (_c *AgentPluginRepoCreate) SetScopeID(v string) *AgentPluginRepoCreate { + _c.mutation.SetScopeID(v) + return _c +} + +// SetNillableScopeID sets the "scope_id" field if the given value is not nil. +func (_c *AgentPluginRepoCreate) SetNillableScopeID(v *string) *AgentPluginRepoCreate { + if v != nil { + _c.SetScopeID(*v) + } + return _c +} + +// SetCreatedBy sets the "created_by" field. +func (_c *AgentPluginRepoCreate) SetCreatedBy(v uuid.UUID) *AgentPluginRepoCreate { + _c.mutation.SetCreatedBy(v) + return _c +} + +// SetSourceType sets the "source_type" field. +func (_c *AgentPluginRepoCreate) SetSourceType(v agentpluginrepo.SourceType) *AgentPluginRepoCreate { + _c.mutation.SetSourceType(v) + return _c +} + +// SetGithubURL sets the "github_url" field. +func (_c *AgentPluginRepoCreate) SetGithubURL(v string) *AgentPluginRepoCreate { + _c.mutation.SetGithubURL(v) + return _c +} + +// SetNillableGithubURL sets the "github_url" field if the given value is not nil. +func (_c *AgentPluginRepoCreate) SetNillableGithubURL(v *string) *AgentPluginRepoCreate { + if v != nil { + _c.SetGithubURL(*v) + } + return _c +} + +// SetRefType sets the "ref_type" field. +func (_c *AgentPluginRepoCreate) SetRefType(v agentpluginrepo.RefType) *AgentPluginRepoCreate { + _c.mutation.SetRefType(v) + return _c +} + +// SetNillableRefType sets the "ref_type" field if the given value is not nil. +func (_c *AgentPluginRepoCreate) SetNillableRefType(v *agentpluginrepo.RefType) *AgentPluginRepoCreate { + if v != nil { + _c.SetRefType(*v) + } + return _c +} + +// SetRefValue sets the "ref_value" field. +func (_c *AgentPluginRepoCreate) SetRefValue(v string) *AgentPluginRepoCreate { + _c.mutation.SetRefValue(v) + return _c +} + +// SetNillableRefValue sets the "ref_value" field if the given value is not nil. +func (_c *AgentPluginRepoCreate) SetNillableRefValue(v *string) *AgentPluginRepoCreate { + if v != nil { + _c.SetRefValue(*v) + } + return _c +} + +// SetLastUploadFilename sets the "last_upload_filename" field. +func (_c *AgentPluginRepoCreate) SetLastUploadFilename(v string) *AgentPluginRepoCreate { + _c.mutation.SetLastUploadFilename(v) + return _c +} + +// SetNillableLastUploadFilename sets the "last_upload_filename" field if the given value is not nil. +func (_c *AgentPluginRepoCreate) SetNillableLastUploadFilename(v *string) *AgentPluginRepoCreate { + if v != nil { + _c.SetLastUploadFilename(*v) + } + return _c +} + +// SetLastUploadAt sets the "last_upload_at" field. +func (_c *AgentPluginRepoCreate) SetLastUploadAt(v time.Time) *AgentPluginRepoCreate { + _c.mutation.SetLastUploadAt(v) + return _c +} + +// SetNillableLastUploadAt sets the "last_upload_at" field if the given value is not nil. +func (_c *AgentPluginRepoCreate) SetNillableLastUploadAt(v *time.Time) *AgentPluginRepoCreate { + if v != nil { + _c.SetLastUploadAt(*v) + } + return _c +} + +// SetPluginDiscoveryAutoPackageJSON sets the "plugin_discovery_auto_package_json" field. +func (_c *AgentPluginRepoCreate) SetPluginDiscoveryAutoPackageJSON(v bool) *AgentPluginRepoCreate { + _c.mutation.SetPluginDiscoveryAutoPackageJSON(v) + return _c +} + +// SetNillablePluginDiscoveryAutoPackageJSON sets the "plugin_discovery_auto_package_json" field if the given value is not nil. +func (_c *AgentPluginRepoCreate) SetNillablePluginDiscoveryAutoPackageJSON(v *bool) *AgentPluginRepoCreate { + if v != nil { + _c.SetPluginDiscoveryAutoPackageJSON(*v) + } + return _c +} + +// SetPluginManualEntries sets the "plugin_manual_entries" field. +func (_c *AgentPluginRepoCreate) SetPluginManualEntries(v types.PluginManualEntries) *AgentPluginRepoCreate { + _c.mutation.SetPluginManualEntries(v) + return _c +} + +// SetNpmPackageName sets the "npm_package_name" field. +func (_c *AgentPluginRepoCreate) SetNpmPackageName(v string) *AgentPluginRepoCreate { + _c.mutation.SetNpmPackageName(v) + return _c +} + +// SetNillableNpmPackageName sets the "npm_package_name" field if the given value is not nil. +func (_c *AgentPluginRepoCreate) SetNillableNpmPackageName(v *string) *AgentPluginRepoCreate { + if v != nil { + _c.SetNpmPackageName(*v) + } + return _c +} + +// SetNpmVersionSpec sets the "npm_version_spec" field. +func (_c *AgentPluginRepoCreate) SetNpmVersionSpec(v string) *AgentPluginRepoCreate { + _c.mutation.SetNpmVersionSpec(v) + return _c +} + +// SetNillableNpmVersionSpec sets the "npm_version_spec" field if the given value is not nil. +func (_c *AgentPluginRepoCreate) SetNillableNpmVersionSpec(v *string) *AgentPluginRepoCreate { + if v != nil { + _c.SetNpmVersionSpec(*v) + } + return _c +} + +// SetNpmRegistryURL sets the "npm_registry_url" field. +func (_c *AgentPluginRepoCreate) SetNpmRegistryURL(v string) *AgentPluginRepoCreate { + _c.mutation.SetNpmRegistryURL(v) + return _c +} + +// SetNillableNpmRegistryURL sets the "npm_registry_url" field if the given value is not nil. +func (_c *AgentPluginRepoCreate) SetNillableNpmRegistryURL(v *string) *AgentPluginRepoCreate { + if v != nil { + _c.SetNpmRegistryURL(*v) + } + return _c +} + +// SetIsDeleted sets the "is_deleted" field. +func (_c *AgentPluginRepoCreate) SetIsDeleted(v bool) *AgentPluginRepoCreate { + _c.mutation.SetIsDeleted(v) + return _c +} + +// SetNillableIsDeleted sets the "is_deleted" field if the given value is not nil. +func (_c *AgentPluginRepoCreate) SetNillableIsDeleted(v *bool) *AgentPluginRepoCreate { + if v != nil { + _c.SetIsDeleted(*v) + } + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *AgentPluginRepoCreate) SetCreatedAt(v time.Time) *AgentPluginRepoCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *AgentPluginRepoCreate) SetNillableCreatedAt(v *time.Time) *AgentPluginRepoCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *AgentPluginRepoCreate) SetUpdatedAt(v time.Time) *AgentPluginRepoCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *AgentPluginRepoCreate) SetNillableUpdatedAt(v *time.Time) *AgentPluginRepoCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *AgentPluginRepoCreate) SetID(v uuid.UUID) *AgentPluginRepoCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *AgentPluginRepoCreate) SetNillableID(v *uuid.UUID) *AgentPluginRepoCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// AddPluginIDs adds the "plugins" edge to the AgentPlugin entity by IDs. +func (_c *AgentPluginRepoCreate) AddPluginIDs(ids ...uuid.UUID) *AgentPluginRepoCreate { + _c.mutation.AddPluginIDs(ids...) + return _c +} + +// AddPlugins adds the "plugins" edges to the AgentPlugin entity. +func (_c *AgentPluginRepoCreate) AddPlugins(v ...*AgentPlugin) *AgentPluginRepoCreate { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddPluginIDs(ids...) +} + +// Mutation returns the AgentPluginRepoMutation object of the builder. +func (_c *AgentPluginRepoCreate) Mutation() *AgentPluginRepoMutation { + return _c.mutation +} + +// Save creates the AgentPluginRepo in the database. +func (_c *AgentPluginRepoCreate) Save(ctx context.Context) (*AgentPluginRepo, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *AgentPluginRepoCreate) SaveX(ctx context.Context) *AgentPluginRepo { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *AgentPluginRepoCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *AgentPluginRepoCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *AgentPluginRepoCreate) defaults() { + if _, ok := _c.mutation.ScopeType(); !ok { + v := agentpluginrepo.DefaultScopeType + _c.mutation.SetScopeType(v) + } + if _, ok := _c.mutation.ScopeID(); !ok { + v := agentpluginrepo.DefaultScopeID + _c.mutation.SetScopeID(v) + } + if _, ok := _c.mutation.PluginDiscoveryAutoPackageJSON(); !ok { + v := agentpluginrepo.DefaultPluginDiscoveryAutoPackageJSON + _c.mutation.SetPluginDiscoveryAutoPackageJSON(v) + } + if _, ok := _c.mutation.IsDeleted(); !ok { + v := agentpluginrepo.DefaultIsDeleted + _c.mutation.SetIsDeleted(v) + } + if _, ok := _c.mutation.CreatedAt(); !ok { + v := agentpluginrepo.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := agentpluginrepo.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := agentpluginrepo.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *AgentPluginRepoCreate) check() error { + if _, ok := _c.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`db: missing required field "AgentPluginRepo.name"`)} + } + if v, ok := _c.mutation.Name(); ok { + if err := agentpluginrepo.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "AgentPluginRepo.name": %w`, err)} + } + } + if _, ok := _c.mutation.ScopeType(); !ok { + return &ValidationError{Name: "scope_type", err: errors.New(`db: missing required field "AgentPluginRepo.scope_type"`)} + } + if v, ok := _c.mutation.ScopeType(); ok { + if err := agentpluginrepo.ScopeTypeValidator(v); err != nil { + return &ValidationError{Name: "scope_type", err: fmt.Errorf(`db: validator failed for field "AgentPluginRepo.scope_type": %w`, err)} + } + } + if _, ok := _c.mutation.ScopeID(); !ok { + return &ValidationError{Name: "scope_id", err: errors.New(`db: missing required field "AgentPluginRepo.scope_id"`)} + } + if _, ok := _c.mutation.CreatedBy(); !ok { + return &ValidationError{Name: "created_by", err: errors.New(`db: missing required field "AgentPluginRepo.created_by"`)} + } + if _, ok := _c.mutation.SourceType(); !ok { + return &ValidationError{Name: "source_type", err: errors.New(`db: missing required field "AgentPluginRepo.source_type"`)} + } + if v, ok := _c.mutation.SourceType(); ok { + if err := agentpluginrepo.SourceTypeValidator(v); err != nil { + return &ValidationError{Name: "source_type", err: fmt.Errorf(`db: validator failed for field "AgentPluginRepo.source_type": %w`, err)} + } + } + if v, ok := _c.mutation.RefType(); ok { + if err := agentpluginrepo.RefTypeValidator(v); err != nil { + return &ValidationError{Name: "ref_type", err: fmt.Errorf(`db: validator failed for field "AgentPluginRepo.ref_type": %w`, err)} + } + } + if _, ok := _c.mutation.PluginDiscoveryAutoPackageJSON(); !ok { + return &ValidationError{Name: "plugin_discovery_auto_package_json", err: errors.New(`db: missing required field "AgentPluginRepo.plugin_discovery_auto_package_json"`)} + } + if _, ok := _c.mutation.IsDeleted(); !ok { + return &ValidationError{Name: "is_deleted", err: errors.New(`db: missing required field "AgentPluginRepo.is_deleted"`)} + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "AgentPluginRepo.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "AgentPluginRepo.updated_at"`)} + } + return nil +} + +func (_c *AgentPluginRepoCreate) sqlSave(ctx context.Context) (*AgentPluginRepo, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.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 + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *AgentPluginRepoCreate) createSpec() (*AgentPluginRepo, *sqlgraph.CreateSpec) { + var ( + _node = &AgentPluginRepo{config: _c.config} + _spec = sqlgraph.NewCreateSpec(agentpluginrepo.Table, sqlgraph.NewFieldSpec(agentpluginrepo.FieldID, field.TypeUUID)) + ) + _spec.OnConflict = _c.conflict + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = &id + } + if value, ok := _c.mutation.Name(); ok { + _spec.SetField(agentpluginrepo.FieldName, field.TypeString, value) + _node.Name = value + } + if value, ok := _c.mutation.ScopeType(); ok { + _spec.SetField(agentpluginrepo.FieldScopeType, field.TypeEnum, value) + _node.ScopeType = value + } + if value, ok := _c.mutation.ScopeID(); ok { + _spec.SetField(agentpluginrepo.FieldScopeID, field.TypeString, value) + _node.ScopeID = value + } + if value, ok := _c.mutation.CreatedBy(); ok { + _spec.SetField(agentpluginrepo.FieldCreatedBy, field.TypeUUID, value) + _node.CreatedBy = value + } + if value, ok := _c.mutation.SourceType(); ok { + _spec.SetField(agentpluginrepo.FieldSourceType, field.TypeEnum, value) + _node.SourceType = value + } + if value, ok := _c.mutation.GithubURL(); ok { + _spec.SetField(agentpluginrepo.FieldGithubURL, field.TypeString, value) + _node.GithubURL = &value + } + if value, ok := _c.mutation.RefType(); ok { + _spec.SetField(agentpluginrepo.FieldRefType, field.TypeEnum, value) + _node.RefType = &value + } + if value, ok := _c.mutation.RefValue(); ok { + _spec.SetField(agentpluginrepo.FieldRefValue, field.TypeString, value) + _node.RefValue = &value + } + if value, ok := _c.mutation.LastUploadFilename(); ok { + _spec.SetField(agentpluginrepo.FieldLastUploadFilename, field.TypeString, value) + _node.LastUploadFilename = &value + } + if value, ok := _c.mutation.LastUploadAt(); ok { + _spec.SetField(agentpluginrepo.FieldLastUploadAt, field.TypeTime, value) + _node.LastUploadAt = &value + } + if value, ok := _c.mutation.PluginDiscoveryAutoPackageJSON(); ok { + _spec.SetField(agentpluginrepo.FieldPluginDiscoveryAutoPackageJSON, field.TypeBool, value) + _node.PluginDiscoveryAutoPackageJSON = value + } + if value, ok := _c.mutation.PluginManualEntries(); ok { + _spec.SetField(agentpluginrepo.FieldPluginManualEntries, field.TypeJSON, value) + _node.PluginManualEntries = value + } + if value, ok := _c.mutation.NpmPackageName(); ok { + _spec.SetField(agentpluginrepo.FieldNpmPackageName, field.TypeString, value) + _node.NpmPackageName = &value + } + if value, ok := _c.mutation.NpmVersionSpec(); ok { + _spec.SetField(agentpluginrepo.FieldNpmVersionSpec, field.TypeString, value) + _node.NpmVersionSpec = &value + } + if value, ok := _c.mutation.NpmRegistryURL(); ok { + _spec.SetField(agentpluginrepo.FieldNpmRegistryURL, field.TypeString, value) + _node.NpmRegistryURL = &value + } + if value, ok := _c.mutation.IsDeleted(); ok { + _spec.SetField(agentpluginrepo.FieldIsDeleted, field.TypeBool, value) + _node.IsDeleted = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(agentpluginrepo.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(agentpluginrepo.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if nodes := _c.mutation.PluginsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agentpluginrepo.PluginsTable, + Columns: []string{agentpluginrepo.PluginsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentplugin.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.AgentPluginRepo.Create(). +// SetName(v). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.AgentPluginRepoUpsert) { +// SetName(v+v). +// }). +// Exec(ctx) +func (_c *AgentPluginRepoCreate) OnConflict(opts ...sql.ConflictOption) *AgentPluginRepoUpsertOne { + _c.conflict = opts + return &AgentPluginRepoUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.AgentPluginRepo.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *AgentPluginRepoCreate) OnConflictColumns(columns ...string) *AgentPluginRepoUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &AgentPluginRepoUpsertOne{ + create: _c, + } +} + +type ( + // AgentPluginRepoUpsertOne is the builder for "upsert"-ing + // one AgentPluginRepo node. + AgentPluginRepoUpsertOne struct { + create *AgentPluginRepoCreate + } + + // AgentPluginRepoUpsert is the "OnConflict" setter. + AgentPluginRepoUpsert struct { + *sql.UpdateSet + } +) + +// SetName sets the "name" field. +func (u *AgentPluginRepoUpsert) SetName(v string) *AgentPluginRepoUpsert { + u.Set(agentpluginrepo.FieldName, v) + return u +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *AgentPluginRepoUpsert) UpdateName() *AgentPluginRepoUpsert { + u.SetExcluded(agentpluginrepo.FieldName) + return u +} + +// SetScopeType sets the "scope_type" field. +func (u *AgentPluginRepoUpsert) SetScopeType(v agentpluginrepo.ScopeType) *AgentPluginRepoUpsert { + u.Set(agentpluginrepo.FieldScopeType, v) + return u +} + +// UpdateScopeType sets the "scope_type" field to the value that was provided on create. +func (u *AgentPluginRepoUpsert) UpdateScopeType() *AgentPluginRepoUpsert { + u.SetExcluded(agentpluginrepo.FieldScopeType) + return u +} + +// SetScopeID sets the "scope_id" field. +func (u *AgentPluginRepoUpsert) SetScopeID(v string) *AgentPluginRepoUpsert { + u.Set(agentpluginrepo.FieldScopeID, v) + return u +} + +// UpdateScopeID sets the "scope_id" field to the value that was provided on create. +func (u *AgentPluginRepoUpsert) UpdateScopeID() *AgentPluginRepoUpsert { + u.SetExcluded(agentpluginrepo.FieldScopeID) + return u +} + +// SetCreatedBy sets the "created_by" field. +func (u *AgentPluginRepoUpsert) SetCreatedBy(v uuid.UUID) *AgentPluginRepoUpsert { + u.Set(agentpluginrepo.FieldCreatedBy, v) + return u +} + +// UpdateCreatedBy sets the "created_by" field to the value that was provided on create. +func (u *AgentPluginRepoUpsert) UpdateCreatedBy() *AgentPluginRepoUpsert { + u.SetExcluded(agentpluginrepo.FieldCreatedBy) + return u +} + +// SetSourceType sets the "source_type" field. +func (u *AgentPluginRepoUpsert) SetSourceType(v agentpluginrepo.SourceType) *AgentPluginRepoUpsert { + u.Set(agentpluginrepo.FieldSourceType, v) + return u +} + +// UpdateSourceType sets the "source_type" field to the value that was provided on create. +func (u *AgentPluginRepoUpsert) UpdateSourceType() *AgentPluginRepoUpsert { + u.SetExcluded(agentpluginrepo.FieldSourceType) + return u +} + +// SetGithubURL sets the "github_url" field. +func (u *AgentPluginRepoUpsert) SetGithubURL(v string) *AgentPluginRepoUpsert { + u.Set(agentpluginrepo.FieldGithubURL, v) + return u +} + +// UpdateGithubURL sets the "github_url" field to the value that was provided on create. +func (u *AgentPluginRepoUpsert) UpdateGithubURL() *AgentPluginRepoUpsert { + u.SetExcluded(agentpluginrepo.FieldGithubURL) + return u +} + +// ClearGithubURL clears the value of the "github_url" field. +func (u *AgentPluginRepoUpsert) ClearGithubURL() *AgentPluginRepoUpsert { + u.SetNull(agentpluginrepo.FieldGithubURL) + return u +} + +// SetRefType sets the "ref_type" field. +func (u *AgentPluginRepoUpsert) SetRefType(v agentpluginrepo.RefType) *AgentPluginRepoUpsert { + u.Set(agentpluginrepo.FieldRefType, v) + return u +} + +// UpdateRefType sets the "ref_type" field to the value that was provided on create. +func (u *AgentPluginRepoUpsert) UpdateRefType() *AgentPluginRepoUpsert { + u.SetExcluded(agentpluginrepo.FieldRefType) + return u +} + +// ClearRefType clears the value of the "ref_type" field. +func (u *AgentPluginRepoUpsert) ClearRefType() *AgentPluginRepoUpsert { + u.SetNull(agentpluginrepo.FieldRefType) + return u +} + +// SetRefValue sets the "ref_value" field. +func (u *AgentPluginRepoUpsert) SetRefValue(v string) *AgentPluginRepoUpsert { + u.Set(agentpluginrepo.FieldRefValue, v) + return u +} + +// UpdateRefValue sets the "ref_value" field to the value that was provided on create. +func (u *AgentPluginRepoUpsert) UpdateRefValue() *AgentPluginRepoUpsert { + u.SetExcluded(agentpluginrepo.FieldRefValue) + return u +} + +// ClearRefValue clears the value of the "ref_value" field. +func (u *AgentPluginRepoUpsert) ClearRefValue() *AgentPluginRepoUpsert { + u.SetNull(agentpluginrepo.FieldRefValue) + return u +} + +// SetLastUploadFilename sets the "last_upload_filename" field. +func (u *AgentPluginRepoUpsert) SetLastUploadFilename(v string) *AgentPluginRepoUpsert { + u.Set(agentpluginrepo.FieldLastUploadFilename, v) + return u +} + +// UpdateLastUploadFilename sets the "last_upload_filename" field to the value that was provided on create. +func (u *AgentPluginRepoUpsert) UpdateLastUploadFilename() *AgentPluginRepoUpsert { + u.SetExcluded(agentpluginrepo.FieldLastUploadFilename) + return u +} + +// ClearLastUploadFilename clears the value of the "last_upload_filename" field. +func (u *AgentPluginRepoUpsert) ClearLastUploadFilename() *AgentPluginRepoUpsert { + u.SetNull(agentpluginrepo.FieldLastUploadFilename) + return u +} + +// SetLastUploadAt sets the "last_upload_at" field. +func (u *AgentPluginRepoUpsert) SetLastUploadAt(v time.Time) *AgentPluginRepoUpsert { + u.Set(agentpluginrepo.FieldLastUploadAt, v) + return u +} + +// UpdateLastUploadAt sets the "last_upload_at" field to the value that was provided on create. +func (u *AgentPluginRepoUpsert) UpdateLastUploadAt() *AgentPluginRepoUpsert { + u.SetExcluded(agentpluginrepo.FieldLastUploadAt) + return u +} + +// ClearLastUploadAt clears the value of the "last_upload_at" field. +func (u *AgentPluginRepoUpsert) ClearLastUploadAt() *AgentPluginRepoUpsert { + u.SetNull(agentpluginrepo.FieldLastUploadAt) + return u +} + +// SetPluginDiscoveryAutoPackageJSON sets the "plugin_discovery_auto_package_json" field. +func (u *AgentPluginRepoUpsert) SetPluginDiscoveryAutoPackageJSON(v bool) *AgentPluginRepoUpsert { + u.Set(agentpluginrepo.FieldPluginDiscoveryAutoPackageJSON, v) + return u +} + +// UpdatePluginDiscoveryAutoPackageJSON sets the "plugin_discovery_auto_package_json" field to the value that was provided on create. +func (u *AgentPluginRepoUpsert) UpdatePluginDiscoveryAutoPackageJSON() *AgentPluginRepoUpsert { + u.SetExcluded(agentpluginrepo.FieldPluginDiscoveryAutoPackageJSON) + return u +} + +// SetPluginManualEntries sets the "plugin_manual_entries" field. +func (u *AgentPluginRepoUpsert) SetPluginManualEntries(v types.PluginManualEntries) *AgentPluginRepoUpsert { + u.Set(agentpluginrepo.FieldPluginManualEntries, v) + return u +} + +// UpdatePluginManualEntries sets the "plugin_manual_entries" field to the value that was provided on create. +func (u *AgentPluginRepoUpsert) UpdatePluginManualEntries() *AgentPluginRepoUpsert { + u.SetExcluded(agentpluginrepo.FieldPluginManualEntries) + return u +} + +// ClearPluginManualEntries clears the value of the "plugin_manual_entries" field. +func (u *AgentPluginRepoUpsert) ClearPluginManualEntries() *AgentPluginRepoUpsert { + u.SetNull(agentpluginrepo.FieldPluginManualEntries) + return u +} + +// SetNpmPackageName sets the "npm_package_name" field. +func (u *AgentPluginRepoUpsert) SetNpmPackageName(v string) *AgentPluginRepoUpsert { + u.Set(agentpluginrepo.FieldNpmPackageName, v) + return u +} + +// UpdateNpmPackageName sets the "npm_package_name" field to the value that was provided on create. +func (u *AgentPluginRepoUpsert) UpdateNpmPackageName() *AgentPluginRepoUpsert { + u.SetExcluded(agentpluginrepo.FieldNpmPackageName) + return u +} + +// ClearNpmPackageName clears the value of the "npm_package_name" field. +func (u *AgentPluginRepoUpsert) ClearNpmPackageName() *AgentPluginRepoUpsert { + u.SetNull(agentpluginrepo.FieldNpmPackageName) + return u +} + +// SetNpmVersionSpec sets the "npm_version_spec" field. +func (u *AgentPluginRepoUpsert) SetNpmVersionSpec(v string) *AgentPluginRepoUpsert { + u.Set(agentpluginrepo.FieldNpmVersionSpec, v) + return u +} + +// UpdateNpmVersionSpec sets the "npm_version_spec" field to the value that was provided on create. +func (u *AgentPluginRepoUpsert) UpdateNpmVersionSpec() *AgentPluginRepoUpsert { + u.SetExcluded(agentpluginrepo.FieldNpmVersionSpec) + return u +} + +// ClearNpmVersionSpec clears the value of the "npm_version_spec" field. +func (u *AgentPluginRepoUpsert) ClearNpmVersionSpec() *AgentPluginRepoUpsert { + u.SetNull(agentpluginrepo.FieldNpmVersionSpec) + return u +} + +// SetNpmRegistryURL sets the "npm_registry_url" field. +func (u *AgentPluginRepoUpsert) SetNpmRegistryURL(v string) *AgentPluginRepoUpsert { + u.Set(agentpluginrepo.FieldNpmRegistryURL, v) + return u +} + +// UpdateNpmRegistryURL sets the "npm_registry_url" field to the value that was provided on create. +func (u *AgentPluginRepoUpsert) UpdateNpmRegistryURL() *AgentPluginRepoUpsert { + u.SetExcluded(agentpluginrepo.FieldNpmRegistryURL) + return u +} + +// ClearNpmRegistryURL clears the value of the "npm_registry_url" field. +func (u *AgentPluginRepoUpsert) ClearNpmRegistryURL() *AgentPluginRepoUpsert { + u.SetNull(agentpluginrepo.FieldNpmRegistryURL) + return u +} + +// SetIsDeleted sets the "is_deleted" field. +func (u *AgentPluginRepoUpsert) SetIsDeleted(v bool) *AgentPluginRepoUpsert { + u.Set(agentpluginrepo.FieldIsDeleted, v) + return u +} + +// UpdateIsDeleted sets the "is_deleted" field to the value that was provided on create. +func (u *AgentPluginRepoUpsert) UpdateIsDeleted() *AgentPluginRepoUpsert { + u.SetExcluded(agentpluginrepo.FieldIsDeleted) + return u +} + +// SetCreatedAt sets the "created_at" field. +func (u *AgentPluginRepoUpsert) SetCreatedAt(v time.Time) *AgentPluginRepoUpsert { + u.Set(agentpluginrepo.FieldCreatedAt, v) + return u +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *AgentPluginRepoUpsert) UpdateCreatedAt() *AgentPluginRepoUpsert { + u.SetExcluded(agentpluginrepo.FieldCreatedAt) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *AgentPluginRepoUpsert) SetUpdatedAt(v time.Time) *AgentPluginRepoUpsert { + u.Set(agentpluginrepo.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *AgentPluginRepoUpsert) UpdateUpdatedAt() *AgentPluginRepoUpsert { + u.SetExcluded(agentpluginrepo.FieldUpdatedAt) + return u +} + +// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field. +// Using this option is equivalent to using: +// +// client.AgentPluginRepo.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(agentpluginrepo.FieldID) +// }), +// ). +// Exec(ctx) +func (u *AgentPluginRepoUpsertOne) UpdateNewValues() *AgentPluginRepoUpsertOne { + 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(agentpluginrepo.FieldID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.AgentPluginRepo.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *AgentPluginRepoUpsertOne) Ignore() *AgentPluginRepoUpsertOne { + 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 *AgentPluginRepoUpsertOne) DoNothing() *AgentPluginRepoUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the AgentPluginRepoCreate.OnConflict +// documentation for more info. +func (u *AgentPluginRepoUpsertOne) Update(set func(*AgentPluginRepoUpsert)) *AgentPluginRepoUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&AgentPluginRepoUpsert{UpdateSet: update}) + })) + return u +} + +// SetName sets the "name" field. +func (u *AgentPluginRepoUpsertOne) SetName(v string) *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *AgentPluginRepoUpsertOne) UpdateName() *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.UpdateName() + }) +} + +// SetScopeType sets the "scope_type" field. +func (u *AgentPluginRepoUpsertOne) SetScopeType(v agentpluginrepo.ScopeType) *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.SetScopeType(v) + }) +} + +// UpdateScopeType sets the "scope_type" field to the value that was provided on create. +func (u *AgentPluginRepoUpsertOne) UpdateScopeType() *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.UpdateScopeType() + }) +} + +// SetScopeID sets the "scope_id" field. +func (u *AgentPluginRepoUpsertOne) SetScopeID(v string) *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.SetScopeID(v) + }) +} + +// UpdateScopeID sets the "scope_id" field to the value that was provided on create. +func (u *AgentPluginRepoUpsertOne) UpdateScopeID() *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.UpdateScopeID() + }) +} + +// SetCreatedBy sets the "created_by" field. +func (u *AgentPluginRepoUpsertOne) SetCreatedBy(v uuid.UUID) *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.SetCreatedBy(v) + }) +} + +// UpdateCreatedBy sets the "created_by" field to the value that was provided on create. +func (u *AgentPluginRepoUpsertOne) UpdateCreatedBy() *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.UpdateCreatedBy() + }) +} + +// SetSourceType sets the "source_type" field. +func (u *AgentPluginRepoUpsertOne) SetSourceType(v agentpluginrepo.SourceType) *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.SetSourceType(v) + }) +} + +// UpdateSourceType sets the "source_type" field to the value that was provided on create. +func (u *AgentPluginRepoUpsertOne) UpdateSourceType() *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.UpdateSourceType() + }) +} + +// SetGithubURL sets the "github_url" field. +func (u *AgentPluginRepoUpsertOne) SetGithubURL(v string) *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.SetGithubURL(v) + }) +} + +// UpdateGithubURL sets the "github_url" field to the value that was provided on create. +func (u *AgentPluginRepoUpsertOne) UpdateGithubURL() *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.UpdateGithubURL() + }) +} + +// ClearGithubURL clears the value of the "github_url" field. +func (u *AgentPluginRepoUpsertOne) ClearGithubURL() *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.ClearGithubURL() + }) +} + +// SetRefType sets the "ref_type" field. +func (u *AgentPluginRepoUpsertOne) SetRefType(v agentpluginrepo.RefType) *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.SetRefType(v) + }) +} + +// UpdateRefType sets the "ref_type" field to the value that was provided on create. +func (u *AgentPluginRepoUpsertOne) UpdateRefType() *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.UpdateRefType() + }) +} + +// ClearRefType clears the value of the "ref_type" field. +func (u *AgentPluginRepoUpsertOne) ClearRefType() *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.ClearRefType() + }) +} + +// SetRefValue sets the "ref_value" field. +func (u *AgentPluginRepoUpsertOne) SetRefValue(v string) *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.SetRefValue(v) + }) +} + +// UpdateRefValue sets the "ref_value" field to the value that was provided on create. +func (u *AgentPluginRepoUpsertOne) UpdateRefValue() *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.UpdateRefValue() + }) +} + +// ClearRefValue clears the value of the "ref_value" field. +func (u *AgentPluginRepoUpsertOne) ClearRefValue() *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.ClearRefValue() + }) +} + +// SetLastUploadFilename sets the "last_upload_filename" field. +func (u *AgentPluginRepoUpsertOne) SetLastUploadFilename(v string) *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.SetLastUploadFilename(v) + }) +} + +// UpdateLastUploadFilename sets the "last_upload_filename" field to the value that was provided on create. +func (u *AgentPluginRepoUpsertOne) UpdateLastUploadFilename() *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.UpdateLastUploadFilename() + }) +} + +// ClearLastUploadFilename clears the value of the "last_upload_filename" field. +func (u *AgentPluginRepoUpsertOne) ClearLastUploadFilename() *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.ClearLastUploadFilename() + }) +} + +// SetLastUploadAt sets the "last_upload_at" field. +func (u *AgentPluginRepoUpsertOne) SetLastUploadAt(v time.Time) *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.SetLastUploadAt(v) + }) +} + +// UpdateLastUploadAt sets the "last_upload_at" field to the value that was provided on create. +func (u *AgentPluginRepoUpsertOne) UpdateLastUploadAt() *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.UpdateLastUploadAt() + }) +} + +// ClearLastUploadAt clears the value of the "last_upload_at" field. +func (u *AgentPluginRepoUpsertOne) ClearLastUploadAt() *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.ClearLastUploadAt() + }) +} + +// SetPluginDiscoveryAutoPackageJSON sets the "plugin_discovery_auto_package_json" field. +func (u *AgentPluginRepoUpsertOne) SetPluginDiscoveryAutoPackageJSON(v bool) *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.SetPluginDiscoveryAutoPackageJSON(v) + }) +} + +// UpdatePluginDiscoveryAutoPackageJSON sets the "plugin_discovery_auto_package_json" field to the value that was provided on create. +func (u *AgentPluginRepoUpsertOne) UpdatePluginDiscoveryAutoPackageJSON() *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.UpdatePluginDiscoveryAutoPackageJSON() + }) +} + +// SetPluginManualEntries sets the "plugin_manual_entries" field. +func (u *AgentPluginRepoUpsertOne) SetPluginManualEntries(v types.PluginManualEntries) *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.SetPluginManualEntries(v) + }) +} + +// UpdatePluginManualEntries sets the "plugin_manual_entries" field to the value that was provided on create. +func (u *AgentPluginRepoUpsertOne) UpdatePluginManualEntries() *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.UpdatePluginManualEntries() + }) +} + +// ClearPluginManualEntries clears the value of the "plugin_manual_entries" field. +func (u *AgentPluginRepoUpsertOne) ClearPluginManualEntries() *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.ClearPluginManualEntries() + }) +} + +// SetNpmPackageName sets the "npm_package_name" field. +func (u *AgentPluginRepoUpsertOne) SetNpmPackageName(v string) *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.SetNpmPackageName(v) + }) +} + +// UpdateNpmPackageName sets the "npm_package_name" field to the value that was provided on create. +func (u *AgentPluginRepoUpsertOne) UpdateNpmPackageName() *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.UpdateNpmPackageName() + }) +} + +// ClearNpmPackageName clears the value of the "npm_package_name" field. +func (u *AgentPluginRepoUpsertOne) ClearNpmPackageName() *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.ClearNpmPackageName() + }) +} + +// SetNpmVersionSpec sets the "npm_version_spec" field. +func (u *AgentPluginRepoUpsertOne) SetNpmVersionSpec(v string) *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.SetNpmVersionSpec(v) + }) +} + +// UpdateNpmVersionSpec sets the "npm_version_spec" field to the value that was provided on create. +func (u *AgentPluginRepoUpsertOne) UpdateNpmVersionSpec() *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.UpdateNpmVersionSpec() + }) +} + +// ClearNpmVersionSpec clears the value of the "npm_version_spec" field. +func (u *AgentPluginRepoUpsertOne) ClearNpmVersionSpec() *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.ClearNpmVersionSpec() + }) +} + +// SetNpmRegistryURL sets the "npm_registry_url" field. +func (u *AgentPluginRepoUpsertOne) SetNpmRegistryURL(v string) *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.SetNpmRegistryURL(v) + }) +} + +// UpdateNpmRegistryURL sets the "npm_registry_url" field to the value that was provided on create. +func (u *AgentPluginRepoUpsertOne) UpdateNpmRegistryURL() *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.UpdateNpmRegistryURL() + }) +} + +// ClearNpmRegistryURL clears the value of the "npm_registry_url" field. +func (u *AgentPluginRepoUpsertOne) ClearNpmRegistryURL() *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.ClearNpmRegistryURL() + }) +} + +// SetIsDeleted sets the "is_deleted" field. +func (u *AgentPluginRepoUpsertOne) SetIsDeleted(v bool) *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.SetIsDeleted(v) + }) +} + +// UpdateIsDeleted sets the "is_deleted" field to the value that was provided on create. +func (u *AgentPluginRepoUpsertOne) UpdateIsDeleted() *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.UpdateIsDeleted() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *AgentPluginRepoUpsertOne) SetCreatedAt(v time.Time) *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *AgentPluginRepoUpsertOne) UpdateCreatedAt() *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.UpdateCreatedAt() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *AgentPluginRepoUpsertOne) SetUpdatedAt(v time.Time) *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *AgentPluginRepoUpsertOne) UpdateUpdatedAt() *AgentPluginRepoUpsertOne { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.UpdateUpdatedAt() + }) +} + +// Exec executes the query. +func (u *AgentPluginRepoUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for AgentPluginRepoCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *AgentPluginRepoUpsertOne) 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 *AgentPluginRepoUpsertOne) 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: AgentPluginRepoUpsertOne.ID is not supported by MySQL driver. Use AgentPluginRepoUpsertOne.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 *AgentPluginRepoUpsertOne) IDX(ctx context.Context) uuid.UUID { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// AgentPluginRepoCreateBulk is the builder for creating many AgentPluginRepo entities in bulk. +type AgentPluginRepoCreateBulk struct { + config + err error + builders []*AgentPluginRepoCreate + conflict []sql.ConflictOption +} + +// Save creates the AgentPluginRepo entities in the database. +func (_c *AgentPluginRepoCreateBulk) Save(ctx context.Context) ([]*AgentPluginRepo, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*AgentPluginRepo, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*AgentPluginRepoMutation) + 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, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = _c.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.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, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *AgentPluginRepoCreateBulk) SaveX(ctx context.Context) []*AgentPluginRepo { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *AgentPluginRepoCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *AgentPluginRepoCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.AgentPluginRepo.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.AgentPluginRepoUpsert) { +// SetName(v+v). +// }). +// Exec(ctx) +func (_c *AgentPluginRepoCreateBulk) OnConflict(opts ...sql.ConflictOption) *AgentPluginRepoUpsertBulk { + _c.conflict = opts + return &AgentPluginRepoUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.AgentPluginRepo.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *AgentPluginRepoCreateBulk) OnConflictColumns(columns ...string) *AgentPluginRepoUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &AgentPluginRepoUpsertBulk{ + create: _c, + } +} + +// AgentPluginRepoUpsertBulk is the builder for "upsert"-ing +// a bulk of AgentPluginRepo nodes. +type AgentPluginRepoUpsertBulk struct { + create *AgentPluginRepoCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.AgentPluginRepo.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(agentpluginrepo.FieldID) +// }), +// ). +// Exec(ctx) +func (u *AgentPluginRepoUpsertBulk) UpdateNewValues() *AgentPluginRepoUpsertBulk { + 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(agentpluginrepo.FieldID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.AgentPluginRepo.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *AgentPluginRepoUpsertBulk) Ignore() *AgentPluginRepoUpsertBulk { + 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 *AgentPluginRepoUpsertBulk) DoNothing() *AgentPluginRepoUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the AgentPluginRepoCreateBulk.OnConflict +// documentation for more info. +func (u *AgentPluginRepoUpsertBulk) Update(set func(*AgentPluginRepoUpsert)) *AgentPluginRepoUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&AgentPluginRepoUpsert{UpdateSet: update}) + })) + return u +} + +// SetName sets the "name" field. +func (u *AgentPluginRepoUpsertBulk) SetName(v string) *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *AgentPluginRepoUpsertBulk) UpdateName() *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.UpdateName() + }) +} + +// SetScopeType sets the "scope_type" field. +func (u *AgentPluginRepoUpsertBulk) SetScopeType(v agentpluginrepo.ScopeType) *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.SetScopeType(v) + }) +} + +// UpdateScopeType sets the "scope_type" field to the value that was provided on create. +func (u *AgentPluginRepoUpsertBulk) UpdateScopeType() *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.UpdateScopeType() + }) +} + +// SetScopeID sets the "scope_id" field. +func (u *AgentPluginRepoUpsertBulk) SetScopeID(v string) *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.SetScopeID(v) + }) +} + +// UpdateScopeID sets the "scope_id" field to the value that was provided on create. +func (u *AgentPluginRepoUpsertBulk) UpdateScopeID() *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.UpdateScopeID() + }) +} + +// SetCreatedBy sets the "created_by" field. +func (u *AgentPluginRepoUpsertBulk) SetCreatedBy(v uuid.UUID) *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.SetCreatedBy(v) + }) +} + +// UpdateCreatedBy sets the "created_by" field to the value that was provided on create. +func (u *AgentPluginRepoUpsertBulk) UpdateCreatedBy() *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.UpdateCreatedBy() + }) +} + +// SetSourceType sets the "source_type" field. +func (u *AgentPluginRepoUpsertBulk) SetSourceType(v agentpluginrepo.SourceType) *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.SetSourceType(v) + }) +} + +// UpdateSourceType sets the "source_type" field to the value that was provided on create. +func (u *AgentPluginRepoUpsertBulk) UpdateSourceType() *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.UpdateSourceType() + }) +} + +// SetGithubURL sets the "github_url" field. +func (u *AgentPluginRepoUpsertBulk) SetGithubURL(v string) *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.SetGithubURL(v) + }) +} + +// UpdateGithubURL sets the "github_url" field to the value that was provided on create. +func (u *AgentPluginRepoUpsertBulk) UpdateGithubURL() *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.UpdateGithubURL() + }) +} + +// ClearGithubURL clears the value of the "github_url" field. +func (u *AgentPluginRepoUpsertBulk) ClearGithubURL() *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.ClearGithubURL() + }) +} + +// SetRefType sets the "ref_type" field. +func (u *AgentPluginRepoUpsertBulk) SetRefType(v agentpluginrepo.RefType) *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.SetRefType(v) + }) +} + +// UpdateRefType sets the "ref_type" field to the value that was provided on create. +func (u *AgentPluginRepoUpsertBulk) UpdateRefType() *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.UpdateRefType() + }) +} + +// ClearRefType clears the value of the "ref_type" field. +func (u *AgentPluginRepoUpsertBulk) ClearRefType() *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.ClearRefType() + }) +} + +// SetRefValue sets the "ref_value" field. +func (u *AgentPluginRepoUpsertBulk) SetRefValue(v string) *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.SetRefValue(v) + }) +} + +// UpdateRefValue sets the "ref_value" field to the value that was provided on create. +func (u *AgentPluginRepoUpsertBulk) UpdateRefValue() *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.UpdateRefValue() + }) +} + +// ClearRefValue clears the value of the "ref_value" field. +func (u *AgentPluginRepoUpsertBulk) ClearRefValue() *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.ClearRefValue() + }) +} + +// SetLastUploadFilename sets the "last_upload_filename" field. +func (u *AgentPluginRepoUpsertBulk) SetLastUploadFilename(v string) *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.SetLastUploadFilename(v) + }) +} + +// UpdateLastUploadFilename sets the "last_upload_filename" field to the value that was provided on create. +func (u *AgentPluginRepoUpsertBulk) UpdateLastUploadFilename() *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.UpdateLastUploadFilename() + }) +} + +// ClearLastUploadFilename clears the value of the "last_upload_filename" field. +func (u *AgentPluginRepoUpsertBulk) ClearLastUploadFilename() *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.ClearLastUploadFilename() + }) +} + +// SetLastUploadAt sets the "last_upload_at" field. +func (u *AgentPluginRepoUpsertBulk) SetLastUploadAt(v time.Time) *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.SetLastUploadAt(v) + }) +} + +// UpdateLastUploadAt sets the "last_upload_at" field to the value that was provided on create. +func (u *AgentPluginRepoUpsertBulk) UpdateLastUploadAt() *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.UpdateLastUploadAt() + }) +} + +// ClearLastUploadAt clears the value of the "last_upload_at" field. +func (u *AgentPluginRepoUpsertBulk) ClearLastUploadAt() *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.ClearLastUploadAt() + }) +} + +// SetPluginDiscoveryAutoPackageJSON sets the "plugin_discovery_auto_package_json" field. +func (u *AgentPluginRepoUpsertBulk) SetPluginDiscoveryAutoPackageJSON(v bool) *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.SetPluginDiscoveryAutoPackageJSON(v) + }) +} + +// UpdatePluginDiscoveryAutoPackageJSON sets the "plugin_discovery_auto_package_json" field to the value that was provided on create. +func (u *AgentPluginRepoUpsertBulk) UpdatePluginDiscoveryAutoPackageJSON() *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.UpdatePluginDiscoveryAutoPackageJSON() + }) +} + +// SetPluginManualEntries sets the "plugin_manual_entries" field. +func (u *AgentPluginRepoUpsertBulk) SetPluginManualEntries(v types.PluginManualEntries) *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.SetPluginManualEntries(v) + }) +} + +// UpdatePluginManualEntries sets the "plugin_manual_entries" field to the value that was provided on create. +func (u *AgentPluginRepoUpsertBulk) UpdatePluginManualEntries() *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.UpdatePluginManualEntries() + }) +} + +// ClearPluginManualEntries clears the value of the "plugin_manual_entries" field. +func (u *AgentPluginRepoUpsertBulk) ClearPluginManualEntries() *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.ClearPluginManualEntries() + }) +} + +// SetNpmPackageName sets the "npm_package_name" field. +func (u *AgentPluginRepoUpsertBulk) SetNpmPackageName(v string) *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.SetNpmPackageName(v) + }) +} + +// UpdateNpmPackageName sets the "npm_package_name" field to the value that was provided on create. +func (u *AgentPluginRepoUpsertBulk) UpdateNpmPackageName() *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.UpdateNpmPackageName() + }) +} + +// ClearNpmPackageName clears the value of the "npm_package_name" field. +func (u *AgentPluginRepoUpsertBulk) ClearNpmPackageName() *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.ClearNpmPackageName() + }) +} + +// SetNpmVersionSpec sets the "npm_version_spec" field. +func (u *AgentPluginRepoUpsertBulk) SetNpmVersionSpec(v string) *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.SetNpmVersionSpec(v) + }) +} + +// UpdateNpmVersionSpec sets the "npm_version_spec" field to the value that was provided on create. +func (u *AgentPluginRepoUpsertBulk) UpdateNpmVersionSpec() *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.UpdateNpmVersionSpec() + }) +} + +// ClearNpmVersionSpec clears the value of the "npm_version_spec" field. +func (u *AgentPluginRepoUpsertBulk) ClearNpmVersionSpec() *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.ClearNpmVersionSpec() + }) +} + +// SetNpmRegistryURL sets the "npm_registry_url" field. +func (u *AgentPluginRepoUpsertBulk) SetNpmRegistryURL(v string) *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.SetNpmRegistryURL(v) + }) +} + +// UpdateNpmRegistryURL sets the "npm_registry_url" field to the value that was provided on create. +func (u *AgentPluginRepoUpsertBulk) UpdateNpmRegistryURL() *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.UpdateNpmRegistryURL() + }) +} + +// ClearNpmRegistryURL clears the value of the "npm_registry_url" field. +func (u *AgentPluginRepoUpsertBulk) ClearNpmRegistryURL() *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.ClearNpmRegistryURL() + }) +} + +// SetIsDeleted sets the "is_deleted" field. +func (u *AgentPluginRepoUpsertBulk) SetIsDeleted(v bool) *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.SetIsDeleted(v) + }) +} + +// UpdateIsDeleted sets the "is_deleted" field to the value that was provided on create. +func (u *AgentPluginRepoUpsertBulk) UpdateIsDeleted() *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.UpdateIsDeleted() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *AgentPluginRepoUpsertBulk) SetCreatedAt(v time.Time) *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *AgentPluginRepoUpsertBulk) UpdateCreatedAt() *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.UpdateCreatedAt() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *AgentPluginRepoUpsertBulk) SetUpdatedAt(v time.Time) *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *AgentPluginRepoUpsertBulk) UpdateUpdatedAt() *AgentPluginRepoUpsertBulk { + return u.Update(func(s *AgentPluginRepoUpsert) { + s.UpdateUpdatedAt() + }) +} + +// Exec executes the query. +func (u *AgentPluginRepoUpsertBulk) 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 AgentPluginRepoCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for AgentPluginRepoCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *AgentPluginRepoUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/agentpluginrepo_delete.go b/backend/db/agentpluginrepo_delete.go new file mode 100644 index 00000000..52ae3cc2 --- /dev/null +++ b/backend/db/agentpluginrepo_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/agentpluginrepo" + "github.com/chaitin/MonkeyCode/backend/db/predicate" +) + +// AgentPluginRepoDelete is the builder for deleting a AgentPluginRepo entity. +type AgentPluginRepoDelete struct { + config + hooks []Hook + mutation *AgentPluginRepoMutation +} + +// Where appends a list predicates to the AgentPluginRepoDelete builder. +func (_d *AgentPluginRepoDelete) Where(ps ...predicate.AgentPluginRepo) *AgentPluginRepoDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *AgentPluginRepoDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *AgentPluginRepoDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *AgentPluginRepoDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(agentpluginrepo.Table, sqlgraph.NewFieldSpec(agentpluginrepo.FieldID, field.TypeUUID)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// AgentPluginRepoDeleteOne is the builder for deleting a single AgentPluginRepo entity. +type AgentPluginRepoDeleteOne struct { + _d *AgentPluginRepoDelete +} + +// Where appends a list predicates to the AgentPluginRepoDelete builder. +func (_d *AgentPluginRepoDeleteOne) Where(ps ...predicate.AgentPluginRepo) *AgentPluginRepoDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *AgentPluginRepoDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{agentpluginrepo.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *AgentPluginRepoDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/agentpluginrepo_query.go b/backend/db/agentpluginrepo_query.go new file mode 100644 index 00000000..b4728654 --- /dev/null +++ b/backend/db/agentpluginrepo_query.go @@ -0,0 +1,657 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "database/sql/driver" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/agentplugin" + "github.com/chaitin/MonkeyCode/backend/db/agentpluginrepo" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/google/uuid" +) + +// AgentPluginRepoQuery is the builder for querying AgentPluginRepo entities. +type AgentPluginRepoQuery struct { + config + ctx *QueryContext + order []agentpluginrepo.OrderOption + inters []Interceptor + predicates []predicate.AgentPluginRepo + withPlugins *AgentPluginQuery + 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 AgentPluginRepoQuery builder. +func (_q *AgentPluginRepoQuery) Where(ps ...predicate.AgentPluginRepo) *AgentPluginRepoQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *AgentPluginRepoQuery) Limit(limit int) *AgentPluginRepoQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *AgentPluginRepoQuery) Offset(offset int) *AgentPluginRepoQuery { + _q.ctx.Offset = &offset + return _q +} + +// 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 (_q *AgentPluginRepoQuery) Unique(unique bool) *AgentPluginRepoQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *AgentPluginRepoQuery) Order(o ...agentpluginrepo.OrderOption) *AgentPluginRepoQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryPlugins chains the current query on the "plugins" edge. +func (_q *AgentPluginRepoQuery) QueryPlugins() *AgentPluginQuery { + query := (&AgentPluginClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(agentpluginrepo.Table, agentpluginrepo.FieldID, selector), + sqlgraph.To(agentplugin.Table, agentplugin.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, agentpluginrepo.PluginsTable, agentpluginrepo.PluginsColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first AgentPluginRepo entity from the query. +// Returns a *NotFoundError when no AgentPluginRepo was found. +func (_q *AgentPluginRepoQuery) First(ctx context.Context) (*AgentPluginRepo, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{agentpluginrepo.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *AgentPluginRepoQuery) FirstX(ctx context.Context) *AgentPluginRepo { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first AgentPluginRepo ID from the query. +// Returns a *NotFoundError when no AgentPluginRepo ID was found. +func (_q *AgentPluginRepoQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{agentpluginrepo.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *AgentPluginRepoQuery) FirstIDX(ctx context.Context) uuid.UUID { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single AgentPluginRepo entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one AgentPluginRepo entity is found. +// Returns a *NotFoundError when no AgentPluginRepo entities are found. +func (_q *AgentPluginRepoQuery) Only(ctx context.Context) (*AgentPluginRepo, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{agentpluginrepo.Label} + default: + return nil, &NotSingularError{agentpluginrepo.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *AgentPluginRepoQuery) OnlyX(ctx context.Context) *AgentPluginRepo { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only AgentPluginRepo ID in the query. +// Returns a *NotSingularError when more than one AgentPluginRepo ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *AgentPluginRepoQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{agentpluginrepo.Label} + default: + err = &NotSingularError{agentpluginrepo.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *AgentPluginRepoQuery) OnlyIDX(ctx context.Context) uuid.UUID { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of AgentPluginRepos. +func (_q *AgentPluginRepoQuery) All(ctx context.Context) ([]*AgentPluginRepo, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*AgentPluginRepo, *AgentPluginRepoQuery]() + return withInterceptors[[]*AgentPluginRepo](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *AgentPluginRepoQuery) AllX(ctx context.Context) []*AgentPluginRepo { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of AgentPluginRepo IDs. +func (_q *AgentPluginRepoQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(agentpluginrepo.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *AgentPluginRepoQuery) IDsX(ctx context.Context) []uuid.UUID { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *AgentPluginRepoQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*AgentPluginRepoQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *AgentPluginRepoQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *AgentPluginRepoQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.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 (_q *AgentPluginRepoQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the AgentPluginRepoQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *AgentPluginRepoQuery) Clone() *AgentPluginRepoQuery { + if _q == nil { + return nil + } + return &AgentPluginRepoQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]agentpluginrepo.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.AgentPluginRepo{}, _q.predicates...), + withPlugins: _q.withPlugins.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + modifiers: append([]func(*sql.Selector){}, _q.modifiers...), + } +} + +// WithPlugins tells the query-builder to eager-load the nodes that are connected to +// the "plugins" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *AgentPluginRepoQuery) WithPlugins(opts ...func(*AgentPluginQuery)) *AgentPluginRepoQuery { + query := (&AgentPluginClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withPlugins = query + return _q +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// Name string `json:"name,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.AgentPluginRepo.Query(). +// GroupBy(agentpluginrepo.FieldName). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *AgentPluginRepoQuery) GroupBy(field string, fields ...string) *AgentPluginRepoGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &AgentPluginRepoGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = agentpluginrepo.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// Name string `json:"name,omitempty"` +// } +// +// client.AgentPluginRepo.Query(). +// Select(agentpluginrepo.FieldName). +// Scan(ctx, &v) +func (_q *AgentPluginRepoQuery) Select(fields ...string) *AgentPluginRepoSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &AgentPluginRepoSelect{AgentPluginRepoQuery: _q} + sbuild.label = agentpluginrepo.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a AgentPluginRepoSelect configured with the given aggregations. +func (_q *AgentPluginRepoQuery) Aggregate(fns ...AggregateFunc) *AgentPluginRepoSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *AgentPluginRepoQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.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, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !agentpluginrepo.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *AgentPluginRepoQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*AgentPluginRepo, error) { + var ( + nodes = []*AgentPluginRepo{} + _spec = _q.querySpec() + loadedTypes = [1]bool{ + _q.withPlugins != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*AgentPluginRepo).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &AgentPluginRepo{config: _q.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := _q.withPlugins; query != nil { + if err := _q.loadPlugins(ctx, query, nodes, + func(n *AgentPluginRepo) { n.Edges.Plugins = []*AgentPlugin{} }, + func(n *AgentPluginRepo, e *AgentPlugin) { n.Edges.Plugins = append(n.Edges.Plugins, e) }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *AgentPluginRepoQuery) loadPlugins(ctx context.Context, query *AgentPluginQuery, nodes []*AgentPluginRepo, init func(*AgentPluginRepo), assign func(*AgentPluginRepo, *AgentPlugin)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[uuid.UUID]*AgentPluginRepo) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) + } + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(agentplugin.FieldRepoID) + } + query.Where(predicate.AgentPlugin(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(agentpluginrepo.PluginsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.RepoID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "repo_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} + +func (_q *AgentPluginRepoQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *AgentPluginRepoQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(agentpluginrepo.Table, agentpluginrepo.Columns, sqlgraph.NewFieldSpec(agentpluginrepo.FieldID, field.TypeUUID)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, agentpluginrepo.FieldID) + for i := range fields { + if fields[i] != agentpluginrepo.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *AgentPluginRepoQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(agentpluginrepo.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = agentpluginrepo.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, m := range _q.modifiers { + m(selector) + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.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 := _q.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 (_q *AgentPluginRepoQuery) ForUpdate(opts ...sql.LockOption) *AgentPluginRepoQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForUpdate(opts...) + }) + return _q +} + +// 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 (_q *AgentPluginRepoQuery) ForShare(opts ...sql.LockOption) *AgentPluginRepoQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (_q *AgentPluginRepoQuery) Modify(modifiers ...func(s *sql.Selector)) *AgentPluginRepoSelect { + _q.modifiers = append(_q.modifiers, modifiers...) + return _q.Select() +} + +// AgentPluginRepoGroupBy is the group-by builder for AgentPluginRepo entities. +type AgentPluginRepoGroupBy struct { + selector + build *AgentPluginRepoQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *AgentPluginRepoGroupBy) Aggregate(fns ...AggregateFunc) *AgentPluginRepoGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *AgentPluginRepoGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*AgentPluginRepoQuery, *AgentPluginRepoGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *AgentPluginRepoGroupBy) sqlScan(ctx context.Context, root *AgentPluginRepoQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// AgentPluginRepoSelect is the builder for selecting fields of AgentPluginRepo entities. +type AgentPluginRepoSelect struct { + *AgentPluginRepoQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *AgentPluginRepoSelect) Aggregate(fns ...AggregateFunc) *AgentPluginRepoSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *AgentPluginRepoSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*AgentPluginRepoQuery, *AgentPluginRepoSelect](ctx, _s.AgentPluginRepoQuery, _s, _s.inters, v) +} + +func (_s *AgentPluginRepoSelect) sqlScan(ctx context.Context, root *AgentPluginRepoQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.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 := _s.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 (_s *AgentPluginRepoSelect) Modify(modifiers ...func(s *sql.Selector)) *AgentPluginRepoSelect { + _s.modifiers = append(_s.modifiers, modifiers...) + return _s +} diff --git a/backend/db/agentpluginrepo_update.go b/backend/db/agentpluginrepo_update.go new file mode 100644 index 00000000..2281f2ea --- /dev/null +++ b/backend/db/agentpluginrepo_update.go @@ -0,0 +1,1196 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/sql/sqljson" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/agentplugin" + "github.com/chaitin/MonkeyCode/backend/db/agentpluginrepo" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/ent/types" + "github.com/google/uuid" +) + +// AgentPluginRepoUpdate is the builder for updating AgentPluginRepo entities. +type AgentPluginRepoUpdate struct { + config + hooks []Hook + mutation *AgentPluginRepoMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the AgentPluginRepoUpdate builder. +func (_u *AgentPluginRepoUpdate) Where(ps ...predicate.AgentPluginRepo) *AgentPluginRepoUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetName sets the "name" field. +func (_u *AgentPluginRepoUpdate) SetName(v string) *AgentPluginRepoUpdate { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *AgentPluginRepoUpdate) SetNillableName(v *string) *AgentPluginRepoUpdate { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetScopeType sets the "scope_type" field. +func (_u *AgentPluginRepoUpdate) SetScopeType(v agentpluginrepo.ScopeType) *AgentPluginRepoUpdate { + _u.mutation.SetScopeType(v) + return _u +} + +// SetNillableScopeType sets the "scope_type" field if the given value is not nil. +func (_u *AgentPluginRepoUpdate) SetNillableScopeType(v *agentpluginrepo.ScopeType) *AgentPluginRepoUpdate { + if v != nil { + _u.SetScopeType(*v) + } + return _u +} + +// SetScopeID sets the "scope_id" field. +func (_u *AgentPluginRepoUpdate) SetScopeID(v string) *AgentPluginRepoUpdate { + _u.mutation.SetScopeID(v) + return _u +} + +// SetNillableScopeID sets the "scope_id" field if the given value is not nil. +func (_u *AgentPluginRepoUpdate) SetNillableScopeID(v *string) *AgentPluginRepoUpdate { + if v != nil { + _u.SetScopeID(*v) + } + return _u +} + +// SetCreatedBy sets the "created_by" field. +func (_u *AgentPluginRepoUpdate) SetCreatedBy(v uuid.UUID) *AgentPluginRepoUpdate { + _u.mutation.SetCreatedBy(v) + return _u +} + +// SetNillableCreatedBy sets the "created_by" field if the given value is not nil. +func (_u *AgentPluginRepoUpdate) SetNillableCreatedBy(v *uuid.UUID) *AgentPluginRepoUpdate { + if v != nil { + _u.SetCreatedBy(*v) + } + return _u +} + +// SetSourceType sets the "source_type" field. +func (_u *AgentPluginRepoUpdate) SetSourceType(v agentpluginrepo.SourceType) *AgentPluginRepoUpdate { + _u.mutation.SetSourceType(v) + return _u +} + +// SetNillableSourceType sets the "source_type" field if the given value is not nil. +func (_u *AgentPluginRepoUpdate) SetNillableSourceType(v *agentpluginrepo.SourceType) *AgentPluginRepoUpdate { + if v != nil { + _u.SetSourceType(*v) + } + return _u +} + +// SetGithubURL sets the "github_url" field. +func (_u *AgentPluginRepoUpdate) SetGithubURL(v string) *AgentPluginRepoUpdate { + _u.mutation.SetGithubURL(v) + return _u +} + +// SetNillableGithubURL sets the "github_url" field if the given value is not nil. +func (_u *AgentPluginRepoUpdate) SetNillableGithubURL(v *string) *AgentPluginRepoUpdate { + if v != nil { + _u.SetGithubURL(*v) + } + return _u +} + +// ClearGithubURL clears the value of the "github_url" field. +func (_u *AgentPluginRepoUpdate) ClearGithubURL() *AgentPluginRepoUpdate { + _u.mutation.ClearGithubURL() + return _u +} + +// SetRefType sets the "ref_type" field. +func (_u *AgentPluginRepoUpdate) SetRefType(v agentpluginrepo.RefType) *AgentPluginRepoUpdate { + _u.mutation.SetRefType(v) + return _u +} + +// SetNillableRefType sets the "ref_type" field if the given value is not nil. +func (_u *AgentPluginRepoUpdate) SetNillableRefType(v *agentpluginrepo.RefType) *AgentPluginRepoUpdate { + if v != nil { + _u.SetRefType(*v) + } + return _u +} + +// ClearRefType clears the value of the "ref_type" field. +func (_u *AgentPluginRepoUpdate) ClearRefType() *AgentPluginRepoUpdate { + _u.mutation.ClearRefType() + return _u +} + +// SetRefValue sets the "ref_value" field. +func (_u *AgentPluginRepoUpdate) SetRefValue(v string) *AgentPluginRepoUpdate { + _u.mutation.SetRefValue(v) + return _u +} + +// SetNillableRefValue sets the "ref_value" field if the given value is not nil. +func (_u *AgentPluginRepoUpdate) SetNillableRefValue(v *string) *AgentPluginRepoUpdate { + if v != nil { + _u.SetRefValue(*v) + } + return _u +} + +// ClearRefValue clears the value of the "ref_value" field. +func (_u *AgentPluginRepoUpdate) ClearRefValue() *AgentPluginRepoUpdate { + _u.mutation.ClearRefValue() + return _u +} + +// SetLastUploadFilename sets the "last_upload_filename" field. +func (_u *AgentPluginRepoUpdate) SetLastUploadFilename(v string) *AgentPluginRepoUpdate { + _u.mutation.SetLastUploadFilename(v) + return _u +} + +// SetNillableLastUploadFilename sets the "last_upload_filename" field if the given value is not nil. +func (_u *AgentPluginRepoUpdate) SetNillableLastUploadFilename(v *string) *AgentPluginRepoUpdate { + if v != nil { + _u.SetLastUploadFilename(*v) + } + return _u +} + +// ClearLastUploadFilename clears the value of the "last_upload_filename" field. +func (_u *AgentPluginRepoUpdate) ClearLastUploadFilename() *AgentPluginRepoUpdate { + _u.mutation.ClearLastUploadFilename() + return _u +} + +// SetLastUploadAt sets the "last_upload_at" field. +func (_u *AgentPluginRepoUpdate) SetLastUploadAt(v time.Time) *AgentPluginRepoUpdate { + _u.mutation.SetLastUploadAt(v) + return _u +} + +// SetNillableLastUploadAt sets the "last_upload_at" field if the given value is not nil. +func (_u *AgentPluginRepoUpdate) SetNillableLastUploadAt(v *time.Time) *AgentPluginRepoUpdate { + if v != nil { + _u.SetLastUploadAt(*v) + } + return _u +} + +// ClearLastUploadAt clears the value of the "last_upload_at" field. +func (_u *AgentPluginRepoUpdate) ClearLastUploadAt() *AgentPluginRepoUpdate { + _u.mutation.ClearLastUploadAt() + return _u +} + +// SetPluginDiscoveryAutoPackageJSON sets the "plugin_discovery_auto_package_json" field. +func (_u *AgentPluginRepoUpdate) SetPluginDiscoveryAutoPackageJSON(v bool) *AgentPluginRepoUpdate { + _u.mutation.SetPluginDiscoveryAutoPackageJSON(v) + return _u +} + +// SetNillablePluginDiscoveryAutoPackageJSON sets the "plugin_discovery_auto_package_json" field if the given value is not nil. +func (_u *AgentPluginRepoUpdate) SetNillablePluginDiscoveryAutoPackageJSON(v *bool) *AgentPluginRepoUpdate { + if v != nil { + _u.SetPluginDiscoveryAutoPackageJSON(*v) + } + return _u +} + +// SetPluginManualEntries sets the "plugin_manual_entries" field. +func (_u *AgentPluginRepoUpdate) SetPluginManualEntries(v types.PluginManualEntries) *AgentPluginRepoUpdate { + _u.mutation.SetPluginManualEntries(v) + return _u +} + +// AppendPluginManualEntries appends value to the "plugin_manual_entries" field. +func (_u *AgentPluginRepoUpdate) AppendPluginManualEntries(v types.PluginManualEntries) *AgentPluginRepoUpdate { + _u.mutation.AppendPluginManualEntries(v) + return _u +} + +// ClearPluginManualEntries clears the value of the "plugin_manual_entries" field. +func (_u *AgentPluginRepoUpdate) ClearPluginManualEntries() *AgentPluginRepoUpdate { + _u.mutation.ClearPluginManualEntries() + return _u +} + +// SetNpmPackageName sets the "npm_package_name" field. +func (_u *AgentPluginRepoUpdate) SetNpmPackageName(v string) *AgentPluginRepoUpdate { + _u.mutation.SetNpmPackageName(v) + return _u +} + +// SetNillableNpmPackageName sets the "npm_package_name" field if the given value is not nil. +func (_u *AgentPluginRepoUpdate) SetNillableNpmPackageName(v *string) *AgentPluginRepoUpdate { + if v != nil { + _u.SetNpmPackageName(*v) + } + return _u +} + +// ClearNpmPackageName clears the value of the "npm_package_name" field. +func (_u *AgentPluginRepoUpdate) ClearNpmPackageName() *AgentPluginRepoUpdate { + _u.mutation.ClearNpmPackageName() + return _u +} + +// SetNpmVersionSpec sets the "npm_version_spec" field. +func (_u *AgentPluginRepoUpdate) SetNpmVersionSpec(v string) *AgentPluginRepoUpdate { + _u.mutation.SetNpmVersionSpec(v) + return _u +} + +// SetNillableNpmVersionSpec sets the "npm_version_spec" field if the given value is not nil. +func (_u *AgentPluginRepoUpdate) SetNillableNpmVersionSpec(v *string) *AgentPluginRepoUpdate { + if v != nil { + _u.SetNpmVersionSpec(*v) + } + return _u +} + +// ClearNpmVersionSpec clears the value of the "npm_version_spec" field. +func (_u *AgentPluginRepoUpdate) ClearNpmVersionSpec() *AgentPluginRepoUpdate { + _u.mutation.ClearNpmVersionSpec() + return _u +} + +// SetNpmRegistryURL sets the "npm_registry_url" field. +func (_u *AgentPluginRepoUpdate) SetNpmRegistryURL(v string) *AgentPluginRepoUpdate { + _u.mutation.SetNpmRegistryURL(v) + return _u +} + +// SetNillableNpmRegistryURL sets the "npm_registry_url" field if the given value is not nil. +func (_u *AgentPluginRepoUpdate) SetNillableNpmRegistryURL(v *string) *AgentPluginRepoUpdate { + if v != nil { + _u.SetNpmRegistryURL(*v) + } + return _u +} + +// ClearNpmRegistryURL clears the value of the "npm_registry_url" field. +func (_u *AgentPluginRepoUpdate) ClearNpmRegistryURL() *AgentPluginRepoUpdate { + _u.mutation.ClearNpmRegistryURL() + return _u +} + +// SetIsDeleted sets the "is_deleted" field. +func (_u *AgentPluginRepoUpdate) SetIsDeleted(v bool) *AgentPluginRepoUpdate { + _u.mutation.SetIsDeleted(v) + return _u +} + +// SetNillableIsDeleted sets the "is_deleted" field if the given value is not nil. +func (_u *AgentPluginRepoUpdate) SetNillableIsDeleted(v *bool) *AgentPluginRepoUpdate { + if v != nil { + _u.SetIsDeleted(*v) + } + return _u +} + +// SetCreatedAt sets the "created_at" field. +func (_u *AgentPluginRepoUpdate) SetCreatedAt(v time.Time) *AgentPluginRepoUpdate { + _u.mutation.SetCreatedAt(v) + return _u +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_u *AgentPluginRepoUpdate) SetNillableCreatedAt(v *time.Time) *AgentPluginRepoUpdate { + if v != nil { + _u.SetCreatedAt(*v) + } + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *AgentPluginRepoUpdate) SetUpdatedAt(v time.Time) *AgentPluginRepoUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// AddPluginIDs adds the "plugins" edge to the AgentPlugin entity by IDs. +func (_u *AgentPluginRepoUpdate) AddPluginIDs(ids ...uuid.UUID) *AgentPluginRepoUpdate { + _u.mutation.AddPluginIDs(ids...) + return _u +} + +// AddPlugins adds the "plugins" edges to the AgentPlugin entity. +func (_u *AgentPluginRepoUpdate) AddPlugins(v ...*AgentPlugin) *AgentPluginRepoUpdate { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddPluginIDs(ids...) +} + +// Mutation returns the AgentPluginRepoMutation object of the builder. +func (_u *AgentPluginRepoUpdate) Mutation() *AgentPluginRepoMutation { + return _u.mutation +} + +// ClearPlugins clears all "plugins" edges to the AgentPlugin entity. +func (_u *AgentPluginRepoUpdate) ClearPlugins() *AgentPluginRepoUpdate { + _u.mutation.ClearPlugins() + return _u +} + +// RemovePluginIDs removes the "plugins" edge to AgentPlugin entities by IDs. +func (_u *AgentPluginRepoUpdate) RemovePluginIDs(ids ...uuid.UUID) *AgentPluginRepoUpdate { + _u.mutation.RemovePluginIDs(ids...) + return _u +} + +// RemovePlugins removes "plugins" edges to AgentPlugin entities. +func (_u *AgentPluginRepoUpdate) RemovePlugins(v ...*AgentPlugin) *AgentPluginRepoUpdate { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemovePluginIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *AgentPluginRepoUpdate) Save(ctx context.Context) (int, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *AgentPluginRepoUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *AgentPluginRepoUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *AgentPluginRepoUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_u *AgentPluginRepoUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := agentpluginrepo.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *AgentPluginRepoUpdate) check() error { + if v, ok := _u.mutation.Name(); ok { + if err := agentpluginrepo.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "AgentPluginRepo.name": %w`, err)} + } + } + if v, ok := _u.mutation.ScopeType(); ok { + if err := agentpluginrepo.ScopeTypeValidator(v); err != nil { + return &ValidationError{Name: "scope_type", err: fmt.Errorf(`db: validator failed for field "AgentPluginRepo.scope_type": %w`, err)} + } + } + if v, ok := _u.mutation.SourceType(); ok { + if err := agentpluginrepo.SourceTypeValidator(v); err != nil { + return &ValidationError{Name: "source_type", err: fmt.Errorf(`db: validator failed for field "AgentPluginRepo.source_type": %w`, err)} + } + } + if v, ok := _u.mutation.RefType(); ok { + if err := agentpluginrepo.RefTypeValidator(v); err != nil { + return &ValidationError{Name: "ref_type", err: fmt.Errorf(`db: validator failed for field "AgentPluginRepo.ref_type": %w`, err)} + } + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (_u *AgentPluginRepoUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *AgentPluginRepoUpdate { + _u.modifiers = append(_u.modifiers, modifiers...) + return _u +} + +func (_u *AgentPluginRepoUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(agentpluginrepo.Table, agentpluginrepo.Columns, sqlgraph.NewFieldSpec(agentpluginrepo.FieldID, field.TypeUUID)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(agentpluginrepo.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.ScopeType(); ok { + _spec.SetField(agentpluginrepo.FieldScopeType, field.TypeEnum, value) + } + if value, ok := _u.mutation.ScopeID(); ok { + _spec.SetField(agentpluginrepo.FieldScopeID, field.TypeString, value) + } + if value, ok := _u.mutation.CreatedBy(); ok { + _spec.SetField(agentpluginrepo.FieldCreatedBy, field.TypeUUID, value) + } + if value, ok := _u.mutation.SourceType(); ok { + _spec.SetField(agentpluginrepo.FieldSourceType, field.TypeEnum, value) + } + if value, ok := _u.mutation.GithubURL(); ok { + _spec.SetField(agentpluginrepo.FieldGithubURL, field.TypeString, value) + } + if _u.mutation.GithubURLCleared() { + _spec.ClearField(agentpluginrepo.FieldGithubURL, field.TypeString) + } + if value, ok := _u.mutation.RefType(); ok { + _spec.SetField(agentpluginrepo.FieldRefType, field.TypeEnum, value) + } + if _u.mutation.RefTypeCleared() { + _spec.ClearField(agentpluginrepo.FieldRefType, field.TypeEnum) + } + if value, ok := _u.mutation.RefValue(); ok { + _spec.SetField(agentpluginrepo.FieldRefValue, field.TypeString, value) + } + if _u.mutation.RefValueCleared() { + _spec.ClearField(agentpluginrepo.FieldRefValue, field.TypeString) + } + if value, ok := _u.mutation.LastUploadFilename(); ok { + _spec.SetField(agentpluginrepo.FieldLastUploadFilename, field.TypeString, value) + } + if _u.mutation.LastUploadFilenameCleared() { + _spec.ClearField(agentpluginrepo.FieldLastUploadFilename, field.TypeString) + } + if value, ok := _u.mutation.LastUploadAt(); ok { + _spec.SetField(agentpluginrepo.FieldLastUploadAt, field.TypeTime, value) + } + if _u.mutation.LastUploadAtCleared() { + _spec.ClearField(agentpluginrepo.FieldLastUploadAt, field.TypeTime) + } + if value, ok := _u.mutation.PluginDiscoveryAutoPackageJSON(); ok { + _spec.SetField(agentpluginrepo.FieldPluginDiscoveryAutoPackageJSON, field.TypeBool, value) + } + if value, ok := _u.mutation.PluginManualEntries(); ok { + _spec.SetField(agentpluginrepo.FieldPluginManualEntries, field.TypeJSON, value) + } + if value, ok := _u.mutation.AppendedPluginManualEntries(); ok { + _spec.AddModifier(func(u *sql.UpdateBuilder) { + sqljson.Append(u, agentpluginrepo.FieldPluginManualEntries, value) + }) + } + if _u.mutation.PluginManualEntriesCleared() { + _spec.ClearField(agentpluginrepo.FieldPluginManualEntries, field.TypeJSON) + } + if value, ok := _u.mutation.NpmPackageName(); ok { + _spec.SetField(agentpluginrepo.FieldNpmPackageName, field.TypeString, value) + } + if _u.mutation.NpmPackageNameCleared() { + _spec.ClearField(agentpluginrepo.FieldNpmPackageName, field.TypeString) + } + if value, ok := _u.mutation.NpmVersionSpec(); ok { + _spec.SetField(agentpluginrepo.FieldNpmVersionSpec, field.TypeString, value) + } + if _u.mutation.NpmVersionSpecCleared() { + _spec.ClearField(agentpluginrepo.FieldNpmVersionSpec, field.TypeString) + } + if value, ok := _u.mutation.NpmRegistryURL(); ok { + _spec.SetField(agentpluginrepo.FieldNpmRegistryURL, field.TypeString, value) + } + if _u.mutation.NpmRegistryURLCleared() { + _spec.ClearField(agentpluginrepo.FieldNpmRegistryURL, field.TypeString) + } + if value, ok := _u.mutation.IsDeleted(); ok { + _spec.SetField(agentpluginrepo.FieldIsDeleted, field.TypeBool, value) + } + if value, ok := _u.mutation.CreatedAt(); ok { + _spec.SetField(agentpluginrepo.FieldCreatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(agentpluginrepo.FieldUpdatedAt, field.TypeTime, value) + } + if _u.mutation.PluginsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agentpluginrepo.PluginsTable, + Columns: []string{agentpluginrepo.PluginsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentplugin.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedPluginsIDs(); len(nodes) > 0 && !_u.mutation.PluginsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agentpluginrepo.PluginsTable, + Columns: []string{agentpluginrepo.PluginsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentplugin.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.PluginsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agentpluginrepo.PluginsTable, + Columns: []string{agentpluginrepo.PluginsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentplugin.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(_u.modifiers...) + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{agentpluginrepo.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// AgentPluginRepoUpdateOne is the builder for updating a single AgentPluginRepo entity. +type AgentPluginRepoUpdateOne struct { + config + fields []string + hooks []Hook + mutation *AgentPluginRepoMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetName sets the "name" field. +func (_u *AgentPluginRepoUpdateOne) SetName(v string) *AgentPluginRepoUpdateOne { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *AgentPluginRepoUpdateOne) SetNillableName(v *string) *AgentPluginRepoUpdateOne { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetScopeType sets the "scope_type" field. +func (_u *AgentPluginRepoUpdateOne) SetScopeType(v agentpluginrepo.ScopeType) *AgentPluginRepoUpdateOne { + _u.mutation.SetScopeType(v) + return _u +} + +// SetNillableScopeType sets the "scope_type" field if the given value is not nil. +func (_u *AgentPluginRepoUpdateOne) SetNillableScopeType(v *agentpluginrepo.ScopeType) *AgentPluginRepoUpdateOne { + if v != nil { + _u.SetScopeType(*v) + } + return _u +} + +// SetScopeID sets the "scope_id" field. +func (_u *AgentPluginRepoUpdateOne) SetScopeID(v string) *AgentPluginRepoUpdateOne { + _u.mutation.SetScopeID(v) + return _u +} + +// SetNillableScopeID sets the "scope_id" field if the given value is not nil. +func (_u *AgentPluginRepoUpdateOne) SetNillableScopeID(v *string) *AgentPluginRepoUpdateOne { + if v != nil { + _u.SetScopeID(*v) + } + return _u +} + +// SetCreatedBy sets the "created_by" field. +func (_u *AgentPluginRepoUpdateOne) SetCreatedBy(v uuid.UUID) *AgentPluginRepoUpdateOne { + _u.mutation.SetCreatedBy(v) + return _u +} + +// SetNillableCreatedBy sets the "created_by" field if the given value is not nil. +func (_u *AgentPluginRepoUpdateOne) SetNillableCreatedBy(v *uuid.UUID) *AgentPluginRepoUpdateOne { + if v != nil { + _u.SetCreatedBy(*v) + } + return _u +} + +// SetSourceType sets the "source_type" field. +func (_u *AgentPluginRepoUpdateOne) SetSourceType(v agentpluginrepo.SourceType) *AgentPluginRepoUpdateOne { + _u.mutation.SetSourceType(v) + return _u +} + +// SetNillableSourceType sets the "source_type" field if the given value is not nil. +func (_u *AgentPluginRepoUpdateOne) SetNillableSourceType(v *agentpluginrepo.SourceType) *AgentPluginRepoUpdateOne { + if v != nil { + _u.SetSourceType(*v) + } + return _u +} + +// SetGithubURL sets the "github_url" field. +func (_u *AgentPluginRepoUpdateOne) SetGithubURL(v string) *AgentPluginRepoUpdateOne { + _u.mutation.SetGithubURL(v) + return _u +} + +// SetNillableGithubURL sets the "github_url" field if the given value is not nil. +func (_u *AgentPluginRepoUpdateOne) SetNillableGithubURL(v *string) *AgentPluginRepoUpdateOne { + if v != nil { + _u.SetGithubURL(*v) + } + return _u +} + +// ClearGithubURL clears the value of the "github_url" field. +func (_u *AgentPluginRepoUpdateOne) ClearGithubURL() *AgentPluginRepoUpdateOne { + _u.mutation.ClearGithubURL() + return _u +} + +// SetRefType sets the "ref_type" field. +func (_u *AgentPluginRepoUpdateOne) SetRefType(v agentpluginrepo.RefType) *AgentPluginRepoUpdateOne { + _u.mutation.SetRefType(v) + return _u +} + +// SetNillableRefType sets the "ref_type" field if the given value is not nil. +func (_u *AgentPluginRepoUpdateOne) SetNillableRefType(v *agentpluginrepo.RefType) *AgentPluginRepoUpdateOne { + if v != nil { + _u.SetRefType(*v) + } + return _u +} + +// ClearRefType clears the value of the "ref_type" field. +func (_u *AgentPluginRepoUpdateOne) ClearRefType() *AgentPluginRepoUpdateOne { + _u.mutation.ClearRefType() + return _u +} + +// SetRefValue sets the "ref_value" field. +func (_u *AgentPluginRepoUpdateOne) SetRefValue(v string) *AgentPluginRepoUpdateOne { + _u.mutation.SetRefValue(v) + return _u +} + +// SetNillableRefValue sets the "ref_value" field if the given value is not nil. +func (_u *AgentPluginRepoUpdateOne) SetNillableRefValue(v *string) *AgentPluginRepoUpdateOne { + if v != nil { + _u.SetRefValue(*v) + } + return _u +} + +// ClearRefValue clears the value of the "ref_value" field. +func (_u *AgentPluginRepoUpdateOne) ClearRefValue() *AgentPluginRepoUpdateOne { + _u.mutation.ClearRefValue() + return _u +} + +// SetLastUploadFilename sets the "last_upload_filename" field. +func (_u *AgentPluginRepoUpdateOne) SetLastUploadFilename(v string) *AgentPluginRepoUpdateOne { + _u.mutation.SetLastUploadFilename(v) + return _u +} + +// SetNillableLastUploadFilename sets the "last_upload_filename" field if the given value is not nil. +func (_u *AgentPluginRepoUpdateOne) SetNillableLastUploadFilename(v *string) *AgentPluginRepoUpdateOne { + if v != nil { + _u.SetLastUploadFilename(*v) + } + return _u +} + +// ClearLastUploadFilename clears the value of the "last_upload_filename" field. +func (_u *AgentPluginRepoUpdateOne) ClearLastUploadFilename() *AgentPluginRepoUpdateOne { + _u.mutation.ClearLastUploadFilename() + return _u +} + +// SetLastUploadAt sets the "last_upload_at" field. +func (_u *AgentPluginRepoUpdateOne) SetLastUploadAt(v time.Time) *AgentPluginRepoUpdateOne { + _u.mutation.SetLastUploadAt(v) + return _u +} + +// SetNillableLastUploadAt sets the "last_upload_at" field if the given value is not nil. +func (_u *AgentPluginRepoUpdateOne) SetNillableLastUploadAt(v *time.Time) *AgentPluginRepoUpdateOne { + if v != nil { + _u.SetLastUploadAt(*v) + } + return _u +} + +// ClearLastUploadAt clears the value of the "last_upload_at" field. +func (_u *AgentPluginRepoUpdateOne) ClearLastUploadAt() *AgentPluginRepoUpdateOne { + _u.mutation.ClearLastUploadAt() + return _u +} + +// SetPluginDiscoveryAutoPackageJSON sets the "plugin_discovery_auto_package_json" field. +func (_u *AgentPluginRepoUpdateOne) SetPluginDiscoveryAutoPackageJSON(v bool) *AgentPluginRepoUpdateOne { + _u.mutation.SetPluginDiscoveryAutoPackageJSON(v) + return _u +} + +// SetNillablePluginDiscoveryAutoPackageJSON sets the "plugin_discovery_auto_package_json" field if the given value is not nil. +func (_u *AgentPluginRepoUpdateOne) SetNillablePluginDiscoveryAutoPackageJSON(v *bool) *AgentPluginRepoUpdateOne { + if v != nil { + _u.SetPluginDiscoveryAutoPackageJSON(*v) + } + return _u +} + +// SetPluginManualEntries sets the "plugin_manual_entries" field. +func (_u *AgentPluginRepoUpdateOne) SetPluginManualEntries(v types.PluginManualEntries) *AgentPluginRepoUpdateOne { + _u.mutation.SetPluginManualEntries(v) + return _u +} + +// AppendPluginManualEntries appends value to the "plugin_manual_entries" field. +func (_u *AgentPluginRepoUpdateOne) AppendPluginManualEntries(v types.PluginManualEntries) *AgentPluginRepoUpdateOne { + _u.mutation.AppendPluginManualEntries(v) + return _u +} + +// ClearPluginManualEntries clears the value of the "plugin_manual_entries" field. +func (_u *AgentPluginRepoUpdateOne) ClearPluginManualEntries() *AgentPluginRepoUpdateOne { + _u.mutation.ClearPluginManualEntries() + return _u +} + +// SetNpmPackageName sets the "npm_package_name" field. +func (_u *AgentPluginRepoUpdateOne) SetNpmPackageName(v string) *AgentPluginRepoUpdateOne { + _u.mutation.SetNpmPackageName(v) + return _u +} + +// SetNillableNpmPackageName sets the "npm_package_name" field if the given value is not nil. +func (_u *AgentPluginRepoUpdateOne) SetNillableNpmPackageName(v *string) *AgentPluginRepoUpdateOne { + if v != nil { + _u.SetNpmPackageName(*v) + } + return _u +} + +// ClearNpmPackageName clears the value of the "npm_package_name" field. +func (_u *AgentPluginRepoUpdateOne) ClearNpmPackageName() *AgentPluginRepoUpdateOne { + _u.mutation.ClearNpmPackageName() + return _u +} + +// SetNpmVersionSpec sets the "npm_version_spec" field. +func (_u *AgentPluginRepoUpdateOne) SetNpmVersionSpec(v string) *AgentPluginRepoUpdateOne { + _u.mutation.SetNpmVersionSpec(v) + return _u +} + +// SetNillableNpmVersionSpec sets the "npm_version_spec" field if the given value is not nil. +func (_u *AgentPluginRepoUpdateOne) SetNillableNpmVersionSpec(v *string) *AgentPluginRepoUpdateOne { + if v != nil { + _u.SetNpmVersionSpec(*v) + } + return _u +} + +// ClearNpmVersionSpec clears the value of the "npm_version_spec" field. +func (_u *AgentPluginRepoUpdateOne) ClearNpmVersionSpec() *AgentPluginRepoUpdateOne { + _u.mutation.ClearNpmVersionSpec() + return _u +} + +// SetNpmRegistryURL sets the "npm_registry_url" field. +func (_u *AgentPluginRepoUpdateOne) SetNpmRegistryURL(v string) *AgentPluginRepoUpdateOne { + _u.mutation.SetNpmRegistryURL(v) + return _u +} + +// SetNillableNpmRegistryURL sets the "npm_registry_url" field if the given value is not nil. +func (_u *AgentPluginRepoUpdateOne) SetNillableNpmRegistryURL(v *string) *AgentPluginRepoUpdateOne { + if v != nil { + _u.SetNpmRegistryURL(*v) + } + return _u +} + +// ClearNpmRegistryURL clears the value of the "npm_registry_url" field. +func (_u *AgentPluginRepoUpdateOne) ClearNpmRegistryURL() *AgentPluginRepoUpdateOne { + _u.mutation.ClearNpmRegistryURL() + return _u +} + +// SetIsDeleted sets the "is_deleted" field. +func (_u *AgentPluginRepoUpdateOne) SetIsDeleted(v bool) *AgentPluginRepoUpdateOne { + _u.mutation.SetIsDeleted(v) + return _u +} + +// SetNillableIsDeleted sets the "is_deleted" field if the given value is not nil. +func (_u *AgentPluginRepoUpdateOne) SetNillableIsDeleted(v *bool) *AgentPluginRepoUpdateOne { + if v != nil { + _u.SetIsDeleted(*v) + } + return _u +} + +// SetCreatedAt sets the "created_at" field. +func (_u *AgentPluginRepoUpdateOne) SetCreatedAt(v time.Time) *AgentPluginRepoUpdateOne { + _u.mutation.SetCreatedAt(v) + return _u +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_u *AgentPluginRepoUpdateOne) SetNillableCreatedAt(v *time.Time) *AgentPluginRepoUpdateOne { + if v != nil { + _u.SetCreatedAt(*v) + } + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *AgentPluginRepoUpdateOne) SetUpdatedAt(v time.Time) *AgentPluginRepoUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// AddPluginIDs adds the "plugins" edge to the AgentPlugin entity by IDs. +func (_u *AgentPluginRepoUpdateOne) AddPluginIDs(ids ...uuid.UUID) *AgentPluginRepoUpdateOne { + _u.mutation.AddPluginIDs(ids...) + return _u +} + +// AddPlugins adds the "plugins" edges to the AgentPlugin entity. +func (_u *AgentPluginRepoUpdateOne) AddPlugins(v ...*AgentPlugin) *AgentPluginRepoUpdateOne { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddPluginIDs(ids...) +} + +// Mutation returns the AgentPluginRepoMutation object of the builder. +func (_u *AgentPluginRepoUpdateOne) Mutation() *AgentPluginRepoMutation { + return _u.mutation +} + +// ClearPlugins clears all "plugins" edges to the AgentPlugin entity. +func (_u *AgentPluginRepoUpdateOne) ClearPlugins() *AgentPluginRepoUpdateOne { + _u.mutation.ClearPlugins() + return _u +} + +// RemovePluginIDs removes the "plugins" edge to AgentPlugin entities by IDs. +func (_u *AgentPluginRepoUpdateOne) RemovePluginIDs(ids ...uuid.UUID) *AgentPluginRepoUpdateOne { + _u.mutation.RemovePluginIDs(ids...) + return _u +} + +// RemovePlugins removes "plugins" edges to AgentPlugin entities. +func (_u *AgentPluginRepoUpdateOne) RemovePlugins(v ...*AgentPlugin) *AgentPluginRepoUpdateOne { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemovePluginIDs(ids...) +} + +// Where appends a list predicates to the AgentPluginRepoUpdate builder. +func (_u *AgentPluginRepoUpdateOne) Where(ps ...predicate.AgentPluginRepo) *AgentPluginRepoUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *AgentPluginRepoUpdateOne) Select(field string, fields ...string) *AgentPluginRepoUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated AgentPluginRepo entity. +func (_u *AgentPluginRepoUpdateOne) Save(ctx context.Context) (*AgentPluginRepo, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *AgentPluginRepoUpdateOne) SaveX(ctx context.Context) *AgentPluginRepo { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *AgentPluginRepoUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *AgentPluginRepoUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_u *AgentPluginRepoUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := agentpluginrepo.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *AgentPluginRepoUpdateOne) check() error { + if v, ok := _u.mutation.Name(); ok { + if err := agentpluginrepo.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "AgentPluginRepo.name": %w`, err)} + } + } + if v, ok := _u.mutation.ScopeType(); ok { + if err := agentpluginrepo.ScopeTypeValidator(v); err != nil { + return &ValidationError{Name: "scope_type", err: fmt.Errorf(`db: validator failed for field "AgentPluginRepo.scope_type": %w`, err)} + } + } + if v, ok := _u.mutation.SourceType(); ok { + if err := agentpluginrepo.SourceTypeValidator(v); err != nil { + return &ValidationError{Name: "source_type", err: fmt.Errorf(`db: validator failed for field "AgentPluginRepo.source_type": %w`, err)} + } + } + if v, ok := _u.mutation.RefType(); ok { + if err := agentpluginrepo.RefTypeValidator(v); err != nil { + return &ValidationError{Name: "ref_type", err: fmt.Errorf(`db: validator failed for field "AgentPluginRepo.ref_type": %w`, err)} + } + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (_u *AgentPluginRepoUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *AgentPluginRepoUpdateOne { + _u.modifiers = append(_u.modifiers, modifiers...) + return _u +} + +func (_u *AgentPluginRepoUpdateOne) sqlSave(ctx context.Context) (_node *AgentPluginRepo, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(agentpluginrepo.Table, agentpluginrepo.Columns, sqlgraph.NewFieldSpec(agentpluginrepo.FieldID, field.TypeUUID)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "AgentPluginRepo.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, agentpluginrepo.FieldID) + for _, f := range fields { + if !agentpluginrepo.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != agentpluginrepo.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(agentpluginrepo.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.ScopeType(); ok { + _spec.SetField(agentpluginrepo.FieldScopeType, field.TypeEnum, value) + } + if value, ok := _u.mutation.ScopeID(); ok { + _spec.SetField(agentpluginrepo.FieldScopeID, field.TypeString, value) + } + if value, ok := _u.mutation.CreatedBy(); ok { + _spec.SetField(agentpluginrepo.FieldCreatedBy, field.TypeUUID, value) + } + if value, ok := _u.mutation.SourceType(); ok { + _spec.SetField(agentpluginrepo.FieldSourceType, field.TypeEnum, value) + } + if value, ok := _u.mutation.GithubURL(); ok { + _spec.SetField(agentpluginrepo.FieldGithubURL, field.TypeString, value) + } + if _u.mutation.GithubURLCleared() { + _spec.ClearField(agentpluginrepo.FieldGithubURL, field.TypeString) + } + if value, ok := _u.mutation.RefType(); ok { + _spec.SetField(agentpluginrepo.FieldRefType, field.TypeEnum, value) + } + if _u.mutation.RefTypeCleared() { + _spec.ClearField(agentpluginrepo.FieldRefType, field.TypeEnum) + } + if value, ok := _u.mutation.RefValue(); ok { + _spec.SetField(agentpluginrepo.FieldRefValue, field.TypeString, value) + } + if _u.mutation.RefValueCleared() { + _spec.ClearField(agentpluginrepo.FieldRefValue, field.TypeString) + } + if value, ok := _u.mutation.LastUploadFilename(); ok { + _spec.SetField(agentpluginrepo.FieldLastUploadFilename, field.TypeString, value) + } + if _u.mutation.LastUploadFilenameCleared() { + _spec.ClearField(agentpluginrepo.FieldLastUploadFilename, field.TypeString) + } + if value, ok := _u.mutation.LastUploadAt(); ok { + _spec.SetField(agentpluginrepo.FieldLastUploadAt, field.TypeTime, value) + } + if _u.mutation.LastUploadAtCleared() { + _spec.ClearField(agentpluginrepo.FieldLastUploadAt, field.TypeTime) + } + if value, ok := _u.mutation.PluginDiscoveryAutoPackageJSON(); ok { + _spec.SetField(agentpluginrepo.FieldPluginDiscoveryAutoPackageJSON, field.TypeBool, value) + } + if value, ok := _u.mutation.PluginManualEntries(); ok { + _spec.SetField(agentpluginrepo.FieldPluginManualEntries, field.TypeJSON, value) + } + if value, ok := _u.mutation.AppendedPluginManualEntries(); ok { + _spec.AddModifier(func(u *sql.UpdateBuilder) { + sqljson.Append(u, agentpluginrepo.FieldPluginManualEntries, value) + }) + } + if _u.mutation.PluginManualEntriesCleared() { + _spec.ClearField(agentpluginrepo.FieldPluginManualEntries, field.TypeJSON) + } + if value, ok := _u.mutation.NpmPackageName(); ok { + _spec.SetField(agentpluginrepo.FieldNpmPackageName, field.TypeString, value) + } + if _u.mutation.NpmPackageNameCleared() { + _spec.ClearField(agentpluginrepo.FieldNpmPackageName, field.TypeString) + } + if value, ok := _u.mutation.NpmVersionSpec(); ok { + _spec.SetField(agentpluginrepo.FieldNpmVersionSpec, field.TypeString, value) + } + if _u.mutation.NpmVersionSpecCleared() { + _spec.ClearField(agentpluginrepo.FieldNpmVersionSpec, field.TypeString) + } + if value, ok := _u.mutation.NpmRegistryURL(); ok { + _spec.SetField(agentpluginrepo.FieldNpmRegistryURL, field.TypeString, value) + } + if _u.mutation.NpmRegistryURLCleared() { + _spec.ClearField(agentpluginrepo.FieldNpmRegistryURL, field.TypeString) + } + if value, ok := _u.mutation.IsDeleted(); ok { + _spec.SetField(agentpluginrepo.FieldIsDeleted, field.TypeBool, value) + } + if value, ok := _u.mutation.CreatedAt(); ok { + _spec.SetField(agentpluginrepo.FieldCreatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(agentpluginrepo.FieldUpdatedAt, field.TypeTime, value) + } + if _u.mutation.PluginsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agentpluginrepo.PluginsTable, + Columns: []string{agentpluginrepo.PluginsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentplugin.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedPluginsIDs(); len(nodes) > 0 && !_u.mutation.PluginsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agentpluginrepo.PluginsTable, + Columns: []string{agentpluginrepo.PluginsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentplugin.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.PluginsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agentpluginrepo.PluginsTable, + Columns: []string{agentpluginrepo.PluginsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentplugin.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(_u.modifiers...) + _node = &AgentPluginRepo{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{agentpluginrepo.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/backend/db/agentpluginversion.go b/backend/db/agentpluginversion.go new file mode 100644 index 00000000..f265e317 --- /dev/null +++ b/backend/db/agentpluginversion.go @@ -0,0 +1,186 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "encoding/json" + "fmt" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/chaitin/MonkeyCode/backend/db/agentplugin" + "github.com/chaitin/MonkeyCode/backend/db/agentpluginversion" + "github.com/chaitin/MonkeyCode/backend/ent/types" + "github.com/google/uuid" +) + +// AgentPluginVersion is the model entity for the AgentPluginVersion schema. +type AgentPluginVersion struct { + config `json:"-"` + // ID of the ent. + ID uuid.UUID `json:"id,omitempty"` + // ResourceID holds the value of the "resource_id" field. + ResourceID uuid.UUID `json:"resource_id,omitempty"` + // Version holds the value of the "version" field. + Version string `json:"version,omitempty"` + // S3Key holds the value of the "s3_key" field. + S3Key string `json:"s3_key,omitempty"` + // ParsedMeta holds the value of the "parsed_meta" field. + ParsedMeta types.PluginParsedMeta `json:"parsed_meta,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the AgentPluginVersionQuery when eager-loading is set. + Edges AgentPluginVersionEdges `json:"edges"` + selectValues sql.SelectValues +} + +// AgentPluginVersionEdges holds the relations/edges for other nodes in the graph. +type AgentPluginVersionEdges struct { + // Plugin holds the value of the plugin edge. + Plugin *AgentPlugin `json:"plugin,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// PluginOrErr returns the Plugin value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e AgentPluginVersionEdges) PluginOrErr() (*AgentPlugin, error) { + if e.Plugin != nil { + return e.Plugin, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: agentplugin.Label} + } + return nil, &NotLoadedError{edge: "plugin"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*AgentPluginVersion) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case agentpluginversion.FieldParsedMeta: + values[i] = new([]byte) + case agentpluginversion.FieldVersion, agentpluginversion.FieldS3Key: + values[i] = new(sql.NullString) + case agentpluginversion.FieldCreatedAt: + values[i] = new(sql.NullTime) + case agentpluginversion.FieldID, agentpluginversion.FieldResourceID: + 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 AgentPluginVersion fields. +func (_m *AgentPluginVersion) 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 agentpluginversion.FieldID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value != nil { + _m.ID = *value + } + case agentpluginversion.FieldResourceID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field resource_id", values[i]) + } else if value != nil { + _m.ResourceID = *value + } + case agentpluginversion.FieldVersion: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field version", values[i]) + } else if value.Valid { + _m.Version = value.String + } + case agentpluginversion.FieldS3Key: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field s3_key", values[i]) + } else if value.Valid { + _m.S3Key = value.String + } + case agentpluginversion.FieldParsedMeta: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field parsed_meta", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.ParsedMeta); err != nil { + return fmt.Errorf("unmarshal field parsed_meta: %w", err) + } + } + case agentpluginversion.FieldCreatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field created_at", values[i]) + } else if value.Valid { + _m.CreatedAt = value.Time + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the AgentPluginVersion. +// This includes values selected through modifiers, order, etc. +func (_m *AgentPluginVersion) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryPlugin queries the "plugin" edge of the AgentPluginVersion entity. +func (_m *AgentPluginVersion) QueryPlugin() *AgentPluginQuery { + return NewAgentPluginVersionClient(_m.config).QueryPlugin(_m) +} + +// Update returns a builder for updating this AgentPluginVersion. +// Note that you need to call AgentPluginVersion.Unwrap() before calling this method if this AgentPluginVersion +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *AgentPluginVersion) Update() *AgentPluginVersionUpdateOne { + return NewAgentPluginVersionClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the AgentPluginVersion entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (_m *AgentPluginVersion) Unwrap() *AgentPluginVersion { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: AgentPluginVersion is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *AgentPluginVersion) String() string { + var builder strings.Builder + builder.WriteString("AgentPluginVersion(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("resource_id=") + builder.WriteString(fmt.Sprintf("%v", _m.ResourceID)) + builder.WriteString(", ") + builder.WriteString("version=") + builder.WriteString(_m.Version) + builder.WriteString(", ") + builder.WriteString("s3_key=") + builder.WriteString(_m.S3Key) + builder.WriteString(", ") + builder.WriteString("parsed_meta=") + builder.WriteString(fmt.Sprintf("%v", _m.ParsedMeta)) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// AgentPluginVersions is a parsable slice of AgentPluginVersion. +type AgentPluginVersions []*AgentPluginVersion diff --git a/backend/db/agentpluginversion/agentpluginversion.go b/backend/db/agentpluginversion/agentpluginversion.go new file mode 100644 index 00000000..bde38d0a --- /dev/null +++ b/backend/db/agentpluginversion/agentpluginversion.go @@ -0,0 +1,112 @@ +// Code generated by ent, DO NOT EDIT. + +package agentpluginversion + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/google/uuid" +) + +const ( + // Label holds the string label denoting the agentpluginversion type in the database. + Label = "agent_plugin_version" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldResourceID holds the string denoting the resource_id field in the database. + FieldResourceID = "resource_id" + // FieldVersion holds the string denoting the version field in the database. + FieldVersion = "version" + // FieldS3Key holds the string denoting the s3_key field in the database. + FieldS3Key = "s3_key" + // FieldParsedMeta holds the string denoting the parsed_meta field in the database. + FieldParsedMeta = "parsed_meta" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // EdgePlugin holds the string denoting the plugin edge name in mutations. + EdgePlugin = "plugin" + // Table holds the table name of the agentpluginversion in the database. + Table = "agent_plugin_versions" + // PluginTable is the table that holds the plugin relation/edge. + PluginTable = "agent_plugin_versions" + // PluginInverseTable is the table name for the AgentPlugin entity. + // It exists in this package in order to avoid circular dependency with the "agentplugin" package. + PluginInverseTable = "agent_plugins" + // PluginColumn is the table column denoting the plugin relation/edge. + PluginColumn = "resource_id" +) + +// Columns holds all SQL columns for agentpluginversion fields. +var Columns = []string{ + FieldID, + FieldResourceID, + FieldVersion, + FieldS3Key, + FieldParsedMeta, + 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 ( + // VersionValidator is a validator for the "version" field. It is called by the builders before save. + VersionValidator func(string) error + // S3KeyValidator is a validator for the "s3_key" field. It is called by the builders before save. + S3KeyValidator func(string) error + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() uuid.UUID +) + +// OrderOption defines the ordering options for the AgentPluginVersion 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() +} + +// ByResourceID orders the results by the resource_id field. +func ByResourceID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldResourceID, opts...).ToFunc() +} + +// ByVersion orders the results by the version field. +func ByVersion(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldVersion, opts...).ToFunc() +} + +// ByS3Key orders the results by the s3_key field. +func ByS3Key(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldS3Key, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// ByPluginField orders the results by plugin field. +func ByPluginField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newPluginStep(), sql.OrderByField(field, opts...)) + } +} +func newPluginStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(PluginInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, PluginTable, PluginColumn), + ) +} diff --git a/backend/db/agentpluginversion/where.go b/backend/db/agentpluginversion/where.go new file mode 100644 index 00000000..395c1d66 --- /dev/null +++ b/backend/db/agentpluginversion/where.go @@ -0,0 +1,315 @@ +// Code generated by ent, DO NOT EDIT. + +package agentpluginversion + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/google/uuid" +) + +// ID filters vertices based on their ID field. +func ID(id uuid.UUID) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id uuid.UUID) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id uuid.UUID) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...uuid.UUID) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...uuid.UUID) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id uuid.UUID) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id uuid.UUID) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id uuid.UUID) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id uuid.UUID) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldLTE(FieldID, id)) +} + +// ResourceID applies equality check predicate on the "resource_id" field. It's identical to ResourceIDEQ. +func ResourceID(v uuid.UUID) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldEQ(FieldResourceID, v)) +} + +// Version applies equality check predicate on the "version" field. It's identical to VersionEQ. +func Version(v string) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldEQ(FieldVersion, v)) +} + +// S3Key applies equality check predicate on the "s3_key" field. It's identical to S3KeyEQ. +func S3Key(v string) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldEQ(FieldS3Key, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldEQ(FieldCreatedAt, v)) +} + +// ResourceIDEQ applies the EQ predicate on the "resource_id" field. +func ResourceIDEQ(v uuid.UUID) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldEQ(FieldResourceID, v)) +} + +// ResourceIDNEQ applies the NEQ predicate on the "resource_id" field. +func ResourceIDNEQ(v uuid.UUID) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldNEQ(FieldResourceID, v)) +} + +// ResourceIDIn applies the In predicate on the "resource_id" field. +func ResourceIDIn(vs ...uuid.UUID) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldIn(FieldResourceID, vs...)) +} + +// ResourceIDNotIn applies the NotIn predicate on the "resource_id" field. +func ResourceIDNotIn(vs ...uuid.UUID) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldNotIn(FieldResourceID, vs...)) +} + +// VersionEQ applies the EQ predicate on the "version" field. +func VersionEQ(v string) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldEQ(FieldVersion, v)) +} + +// VersionNEQ applies the NEQ predicate on the "version" field. +func VersionNEQ(v string) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldNEQ(FieldVersion, v)) +} + +// VersionIn applies the In predicate on the "version" field. +func VersionIn(vs ...string) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldIn(FieldVersion, vs...)) +} + +// VersionNotIn applies the NotIn predicate on the "version" field. +func VersionNotIn(vs ...string) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldNotIn(FieldVersion, vs...)) +} + +// VersionGT applies the GT predicate on the "version" field. +func VersionGT(v string) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldGT(FieldVersion, v)) +} + +// VersionGTE applies the GTE predicate on the "version" field. +func VersionGTE(v string) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldGTE(FieldVersion, v)) +} + +// VersionLT applies the LT predicate on the "version" field. +func VersionLT(v string) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldLT(FieldVersion, v)) +} + +// VersionLTE applies the LTE predicate on the "version" field. +func VersionLTE(v string) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldLTE(FieldVersion, v)) +} + +// VersionContains applies the Contains predicate on the "version" field. +func VersionContains(v string) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldContains(FieldVersion, v)) +} + +// VersionHasPrefix applies the HasPrefix predicate on the "version" field. +func VersionHasPrefix(v string) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldHasPrefix(FieldVersion, v)) +} + +// VersionHasSuffix applies the HasSuffix predicate on the "version" field. +func VersionHasSuffix(v string) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldHasSuffix(FieldVersion, v)) +} + +// VersionEqualFold applies the EqualFold predicate on the "version" field. +func VersionEqualFold(v string) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldEqualFold(FieldVersion, v)) +} + +// VersionContainsFold applies the ContainsFold predicate on the "version" field. +func VersionContainsFold(v string) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldContainsFold(FieldVersion, v)) +} + +// S3KeyEQ applies the EQ predicate on the "s3_key" field. +func S3KeyEQ(v string) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldEQ(FieldS3Key, v)) +} + +// S3KeyNEQ applies the NEQ predicate on the "s3_key" field. +func S3KeyNEQ(v string) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldNEQ(FieldS3Key, v)) +} + +// S3KeyIn applies the In predicate on the "s3_key" field. +func S3KeyIn(vs ...string) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldIn(FieldS3Key, vs...)) +} + +// S3KeyNotIn applies the NotIn predicate on the "s3_key" field. +func S3KeyNotIn(vs ...string) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldNotIn(FieldS3Key, vs...)) +} + +// S3KeyGT applies the GT predicate on the "s3_key" field. +func S3KeyGT(v string) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldGT(FieldS3Key, v)) +} + +// S3KeyGTE applies the GTE predicate on the "s3_key" field. +func S3KeyGTE(v string) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldGTE(FieldS3Key, v)) +} + +// S3KeyLT applies the LT predicate on the "s3_key" field. +func S3KeyLT(v string) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldLT(FieldS3Key, v)) +} + +// S3KeyLTE applies the LTE predicate on the "s3_key" field. +func S3KeyLTE(v string) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldLTE(FieldS3Key, v)) +} + +// S3KeyContains applies the Contains predicate on the "s3_key" field. +func S3KeyContains(v string) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldContains(FieldS3Key, v)) +} + +// S3KeyHasPrefix applies the HasPrefix predicate on the "s3_key" field. +func S3KeyHasPrefix(v string) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldHasPrefix(FieldS3Key, v)) +} + +// S3KeyHasSuffix applies the HasSuffix predicate on the "s3_key" field. +func S3KeyHasSuffix(v string) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldHasSuffix(FieldS3Key, v)) +} + +// S3KeyEqualFold applies the EqualFold predicate on the "s3_key" field. +func S3KeyEqualFold(v string) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldEqualFold(FieldS3Key, v)) +} + +// S3KeyContainsFold applies the ContainsFold predicate on the "s3_key" field. +func S3KeyContainsFold(v string) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldContainsFold(FieldS3Key, v)) +} + +// ParsedMetaIsNil applies the IsNil predicate on the "parsed_meta" field. +func ParsedMetaIsNil() predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldIsNull(FieldParsedMeta)) +} + +// ParsedMetaNotNil applies the NotNil predicate on the "parsed_meta" field. +func ParsedMetaNotNil() predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldNotNull(FieldParsedMeta)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.FieldLTE(FieldCreatedAt, v)) +} + +// HasPlugin applies the HasEdge predicate on the "plugin" edge. +func HasPlugin() predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, PluginTable, PluginColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasPluginWith applies the HasEdge predicate on the "plugin" edge with a given conditions (other predicates). +func HasPluginWith(preds ...predicate.AgentPlugin) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(func(s *sql.Selector) { + step := newPluginStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.AgentPluginVersion) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.AgentPluginVersion) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.AgentPluginVersion) predicate.AgentPluginVersion { + return predicate.AgentPluginVersion(sql.NotPredicates(p)) +} diff --git a/backend/db/agentpluginversion_create.go b/backend/db/agentpluginversion_create.go new file mode 100644 index 00000000..ea5b46cd --- /dev/null +++ b/backend/db/agentpluginversion_create.go @@ -0,0 +1,797 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/agentplugin" + "github.com/chaitin/MonkeyCode/backend/db/agentpluginversion" + "github.com/chaitin/MonkeyCode/backend/ent/types" + "github.com/google/uuid" +) + +// AgentPluginVersionCreate is the builder for creating a AgentPluginVersion entity. +type AgentPluginVersionCreate struct { + config + mutation *AgentPluginVersionMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetResourceID sets the "resource_id" field. +func (_c *AgentPluginVersionCreate) SetResourceID(v uuid.UUID) *AgentPluginVersionCreate { + _c.mutation.SetResourceID(v) + return _c +} + +// SetVersion sets the "version" field. +func (_c *AgentPluginVersionCreate) SetVersion(v string) *AgentPluginVersionCreate { + _c.mutation.SetVersion(v) + return _c +} + +// SetS3Key sets the "s3_key" field. +func (_c *AgentPluginVersionCreate) SetS3Key(v string) *AgentPluginVersionCreate { + _c.mutation.SetS3Key(v) + return _c +} + +// SetParsedMeta sets the "parsed_meta" field. +func (_c *AgentPluginVersionCreate) SetParsedMeta(v types.PluginParsedMeta) *AgentPluginVersionCreate { + _c.mutation.SetParsedMeta(v) + return _c +} + +// SetNillableParsedMeta sets the "parsed_meta" field if the given value is not nil. +func (_c *AgentPluginVersionCreate) SetNillableParsedMeta(v *types.PluginParsedMeta) *AgentPluginVersionCreate { + if v != nil { + _c.SetParsedMeta(*v) + } + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *AgentPluginVersionCreate) SetCreatedAt(v time.Time) *AgentPluginVersionCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *AgentPluginVersionCreate) SetNillableCreatedAt(v *time.Time) *AgentPluginVersionCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *AgentPluginVersionCreate) SetID(v uuid.UUID) *AgentPluginVersionCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *AgentPluginVersionCreate) SetNillableID(v *uuid.UUID) *AgentPluginVersionCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetPluginID sets the "plugin" edge to the AgentPlugin entity by ID. +func (_c *AgentPluginVersionCreate) SetPluginID(id uuid.UUID) *AgentPluginVersionCreate { + _c.mutation.SetPluginID(id) + return _c +} + +// SetPlugin sets the "plugin" edge to the AgentPlugin entity. +func (_c *AgentPluginVersionCreate) SetPlugin(v *AgentPlugin) *AgentPluginVersionCreate { + return _c.SetPluginID(v.ID) +} + +// Mutation returns the AgentPluginVersionMutation object of the builder. +func (_c *AgentPluginVersionCreate) Mutation() *AgentPluginVersionMutation { + return _c.mutation +} + +// Save creates the AgentPluginVersion in the database. +func (_c *AgentPluginVersionCreate) Save(ctx context.Context) (*AgentPluginVersion, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *AgentPluginVersionCreate) SaveX(ctx context.Context) *AgentPluginVersion { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *AgentPluginVersionCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *AgentPluginVersionCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *AgentPluginVersionCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := agentpluginversion.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := agentpluginversion.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *AgentPluginVersionCreate) check() error { + if _, ok := _c.mutation.ResourceID(); !ok { + return &ValidationError{Name: "resource_id", err: errors.New(`db: missing required field "AgentPluginVersion.resource_id"`)} + } + if _, ok := _c.mutation.Version(); !ok { + return &ValidationError{Name: "version", err: errors.New(`db: missing required field "AgentPluginVersion.version"`)} + } + if v, ok := _c.mutation.Version(); ok { + if err := agentpluginversion.VersionValidator(v); err != nil { + return &ValidationError{Name: "version", err: fmt.Errorf(`db: validator failed for field "AgentPluginVersion.version": %w`, err)} + } + } + if _, ok := _c.mutation.S3Key(); !ok { + return &ValidationError{Name: "s3_key", err: errors.New(`db: missing required field "AgentPluginVersion.s3_key"`)} + } + if v, ok := _c.mutation.S3Key(); ok { + if err := agentpluginversion.S3KeyValidator(v); err != nil { + return &ValidationError{Name: "s3_key", err: fmt.Errorf(`db: validator failed for field "AgentPluginVersion.s3_key": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "AgentPluginVersion.created_at"`)} + } + if len(_c.mutation.PluginIDs()) == 0 { + return &ValidationError{Name: "plugin", err: errors.New(`db: missing required edge "AgentPluginVersion.plugin"`)} + } + return nil +} + +func (_c *AgentPluginVersionCreate) sqlSave(ctx context.Context) (*AgentPluginVersion, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.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 + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *AgentPluginVersionCreate) createSpec() (*AgentPluginVersion, *sqlgraph.CreateSpec) { + var ( + _node = &AgentPluginVersion{config: _c.config} + _spec = sqlgraph.NewCreateSpec(agentpluginversion.Table, sqlgraph.NewFieldSpec(agentpluginversion.FieldID, field.TypeUUID)) + ) + _spec.OnConflict = _c.conflict + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = &id + } + if value, ok := _c.mutation.Version(); ok { + _spec.SetField(agentpluginversion.FieldVersion, field.TypeString, value) + _node.Version = value + } + if value, ok := _c.mutation.S3Key(); ok { + _spec.SetField(agentpluginversion.FieldS3Key, field.TypeString, value) + _node.S3Key = value + } + if value, ok := _c.mutation.ParsedMeta(); ok { + _spec.SetField(agentpluginversion.FieldParsedMeta, field.TypeJSON, value) + _node.ParsedMeta = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(agentpluginversion.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if nodes := _c.mutation.PluginIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: agentpluginversion.PluginTable, + Columns: []string{agentpluginversion.PluginColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentplugin.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.ResourceID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.AgentPluginVersion.Create(). +// SetResourceID(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.AgentPluginVersionUpsert) { +// SetResourceID(v+v). +// }). +// Exec(ctx) +func (_c *AgentPluginVersionCreate) OnConflict(opts ...sql.ConflictOption) *AgentPluginVersionUpsertOne { + _c.conflict = opts + return &AgentPluginVersionUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.AgentPluginVersion.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *AgentPluginVersionCreate) OnConflictColumns(columns ...string) *AgentPluginVersionUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &AgentPluginVersionUpsertOne{ + create: _c, + } +} + +type ( + // AgentPluginVersionUpsertOne is the builder for "upsert"-ing + // one AgentPluginVersion node. + AgentPluginVersionUpsertOne struct { + create *AgentPluginVersionCreate + } + + // AgentPluginVersionUpsert is the "OnConflict" setter. + AgentPluginVersionUpsert struct { + *sql.UpdateSet + } +) + +// SetResourceID sets the "resource_id" field. +func (u *AgentPluginVersionUpsert) SetResourceID(v uuid.UUID) *AgentPluginVersionUpsert { + u.Set(agentpluginversion.FieldResourceID, v) + return u +} + +// UpdateResourceID sets the "resource_id" field to the value that was provided on create. +func (u *AgentPluginVersionUpsert) UpdateResourceID() *AgentPluginVersionUpsert { + u.SetExcluded(agentpluginversion.FieldResourceID) + return u +} + +// SetVersion sets the "version" field. +func (u *AgentPluginVersionUpsert) SetVersion(v string) *AgentPluginVersionUpsert { + u.Set(agentpluginversion.FieldVersion, v) + return u +} + +// UpdateVersion sets the "version" field to the value that was provided on create. +func (u *AgentPluginVersionUpsert) UpdateVersion() *AgentPluginVersionUpsert { + u.SetExcluded(agentpluginversion.FieldVersion) + return u +} + +// SetS3Key sets the "s3_key" field. +func (u *AgentPluginVersionUpsert) SetS3Key(v string) *AgentPluginVersionUpsert { + u.Set(agentpluginversion.FieldS3Key, v) + return u +} + +// UpdateS3Key sets the "s3_key" field to the value that was provided on create. +func (u *AgentPluginVersionUpsert) UpdateS3Key() *AgentPluginVersionUpsert { + u.SetExcluded(agentpluginversion.FieldS3Key) + return u +} + +// SetParsedMeta sets the "parsed_meta" field. +func (u *AgentPluginVersionUpsert) SetParsedMeta(v types.PluginParsedMeta) *AgentPluginVersionUpsert { + u.Set(agentpluginversion.FieldParsedMeta, v) + return u +} + +// UpdateParsedMeta sets the "parsed_meta" field to the value that was provided on create. +func (u *AgentPluginVersionUpsert) UpdateParsedMeta() *AgentPluginVersionUpsert { + u.SetExcluded(agentpluginversion.FieldParsedMeta) + return u +} + +// ClearParsedMeta clears the value of the "parsed_meta" field. +func (u *AgentPluginVersionUpsert) ClearParsedMeta() *AgentPluginVersionUpsert { + u.SetNull(agentpluginversion.FieldParsedMeta) + return u +} + +// SetCreatedAt sets the "created_at" field. +func (u *AgentPluginVersionUpsert) SetCreatedAt(v time.Time) *AgentPluginVersionUpsert { + u.Set(agentpluginversion.FieldCreatedAt, v) + return u +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *AgentPluginVersionUpsert) UpdateCreatedAt() *AgentPluginVersionUpsert { + u.SetExcluded(agentpluginversion.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.AgentPluginVersion.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(agentpluginversion.FieldID) +// }), +// ). +// Exec(ctx) +func (u *AgentPluginVersionUpsertOne) UpdateNewValues() *AgentPluginVersionUpsertOne { + 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(agentpluginversion.FieldID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.AgentPluginVersion.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *AgentPluginVersionUpsertOne) Ignore() *AgentPluginVersionUpsertOne { + 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 *AgentPluginVersionUpsertOne) DoNothing() *AgentPluginVersionUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the AgentPluginVersionCreate.OnConflict +// documentation for more info. +func (u *AgentPluginVersionUpsertOne) Update(set func(*AgentPluginVersionUpsert)) *AgentPluginVersionUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&AgentPluginVersionUpsert{UpdateSet: update}) + })) + return u +} + +// SetResourceID sets the "resource_id" field. +func (u *AgentPluginVersionUpsertOne) SetResourceID(v uuid.UUID) *AgentPluginVersionUpsertOne { + return u.Update(func(s *AgentPluginVersionUpsert) { + s.SetResourceID(v) + }) +} + +// UpdateResourceID sets the "resource_id" field to the value that was provided on create. +func (u *AgentPluginVersionUpsertOne) UpdateResourceID() *AgentPluginVersionUpsertOne { + return u.Update(func(s *AgentPluginVersionUpsert) { + s.UpdateResourceID() + }) +} + +// SetVersion sets the "version" field. +func (u *AgentPluginVersionUpsertOne) SetVersion(v string) *AgentPluginVersionUpsertOne { + return u.Update(func(s *AgentPluginVersionUpsert) { + s.SetVersion(v) + }) +} + +// UpdateVersion sets the "version" field to the value that was provided on create. +func (u *AgentPluginVersionUpsertOne) UpdateVersion() *AgentPluginVersionUpsertOne { + return u.Update(func(s *AgentPluginVersionUpsert) { + s.UpdateVersion() + }) +} + +// SetS3Key sets the "s3_key" field. +func (u *AgentPluginVersionUpsertOne) SetS3Key(v string) *AgentPluginVersionUpsertOne { + return u.Update(func(s *AgentPluginVersionUpsert) { + s.SetS3Key(v) + }) +} + +// UpdateS3Key sets the "s3_key" field to the value that was provided on create. +func (u *AgentPluginVersionUpsertOne) UpdateS3Key() *AgentPluginVersionUpsertOne { + return u.Update(func(s *AgentPluginVersionUpsert) { + s.UpdateS3Key() + }) +} + +// SetParsedMeta sets the "parsed_meta" field. +func (u *AgentPluginVersionUpsertOne) SetParsedMeta(v types.PluginParsedMeta) *AgentPluginVersionUpsertOne { + return u.Update(func(s *AgentPluginVersionUpsert) { + s.SetParsedMeta(v) + }) +} + +// UpdateParsedMeta sets the "parsed_meta" field to the value that was provided on create. +func (u *AgentPluginVersionUpsertOne) UpdateParsedMeta() *AgentPluginVersionUpsertOne { + return u.Update(func(s *AgentPluginVersionUpsert) { + s.UpdateParsedMeta() + }) +} + +// ClearParsedMeta clears the value of the "parsed_meta" field. +func (u *AgentPluginVersionUpsertOne) ClearParsedMeta() *AgentPluginVersionUpsertOne { + return u.Update(func(s *AgentPluginVersionUpsert) { + s.ClearParsedMeta() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *AgentPluginVersionUpsertOne) SetCreatedAt(v time.Time) *AgentPluginVersionUpsertOne { + return u.Update(func(s *AgentPluginVersionUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *AgentPluginVersionUpsertOne) UpdateCreatedAt() *AgentPluginVersionUpsertOne { + return u.Update(func(s *AgentPluginVersionUpsert) { + s.UpdateCreatedAt() + }) +} + +// Exec executes the query. +func (u *AgentPluginVersionUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for AgentPluginVersionCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *AgentPluginVersionUpsertOne) 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 *AgentPluginVersionUpsertOne) 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: AgentPluginVersionUpsertOne.ID is not supported by MySQL driver. Use AgentPluginVersionUpsertOne.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 *AgentPluginVersionUpsertOne) IDX(ctx context.Context) uuid.UUID { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// AgentPluginVersionCreateBulk is the builder for creating many AgentPluginVersion entities in bulk. +type AgentPluginVersionCreateBulk struct { + config + err error + builders []*AgentPluginVersionCreate + conflict []sql.ConflictOption +} + +// Save creates the AgentPluginVersion entities in the database. +func (_c *AgentPluginVersionCreateBulk) Save(ctx context.Context) ([]*AgentPluginVersion, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*AgentPluginVersion, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*AgentPluginVersionMutation) + 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, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = _c.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.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, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *AgentPluginVersionCreateBulk) SaveX(ctx context.Context) []*AgentPluginVersion { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *AgentPluginVersionCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *AgentPluginVersionCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.AgentPluginVersion.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.AgentPluginVersionUpsert) { +// SetResourceID(v+v). +// }). +// Exec(ctx) +func (_c *AgentPluginVersionCreateBulk) OnConflict(opts ...sql.ConflictOption) *AgentPluginVersionUpsertBulk { + _c.conflict = opts + return &AgentPluginVersionUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.AgentPluginVersion.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *AgentPluginVersionCreateBulk) OnConflictColumns(columns ...string) *AgentPluginVersionUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &AgentPluginVersionUpsertBulk{ + create: _c, + } +} + +// AgentPluginVersionUpsertBulk is the builder for "upsert"-ing +// a bulk of AgentPluginVersion nodes. +type AgentPluginVersionUpsertBulk struct { + create *AgentPluginVersionCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.AgentPluginVersion.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(agentpluginversion.FieldID) +// }), +// ). +// Exec(ctx) +func (u *AgentPluginVersionUpsertBulk) UpdateNewValues() *AgentPluginVersionUpsertBulk { + 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(agentpluginversion.FieldID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.AgentPluginVersion.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *AgentPluginVersionUpsertBulk) Ignore() *AgentPluginVersionUpsertBulk { + 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 *AgentPluginVersionUpsertBulk) DoNothing() *AgentPluginVersionUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the AgentPluginVersionCreateBulk.OnConflict +// documentation for more info. +func (u *AgentPluginVersionUpsertBulk) Update(set func(*AgentPluginVersionUpsert)) *AgentPluginVersionUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&AgentPluginVersionUpsert{UpdateSet: update}) + })) + return u +} + +// SetResourceID sets the "resource_id" field. +func (u *AgentPluginVersionUpsertBulk) SetResourceID(v uuid.UUID) *AgentPluginVersionUpsertBulk { + return u.Update(func(s *AgentPluginVersionUpsert) { + s.SetResourceID(v) + }) +} + +// UpdateResourceID sets the "resource_id" field to the value that was provided on create. +func (u *AgentPluginVersionUpsertBulk) UpdateResourceID() *AgentPluginVersionUpsertBulk { + return u.Update(func(s *AgentPluginVersionUpsert) { + s.UpdateResourceID() + }) +} + +// SetVersion sets the "version" field. +func (u *AgentPluginVersionUpsertBulk) SetVersion(v string) *AgentPluginVersionUpsertBulk { + return u.Update(func(s *AgentPluginVersionUpsert) { + s.SetVersion(v) + }) +} + +// UpdateVersion sets the "version" field to the value that was provided on create. +func (u *AgentPluginVersionUpsertBulk) UpdateVersion() *AgentPluginVersionUpsertBulk { + return u.Update(func(s *AgentPluginVersionUpsert) { + s.UpdateVersion() + }) +} + +// SetS3Key sets the "s3_key" field. +func (u *AgentPluginVersionUpsertBulk) SetS3Key(v string) *AgentPluginVersionUpsertBulk { + return u.Update(func(s *AgentPluginVersionUpsert) { + s.SetS3Key(v) + }) +} + +// UpdateS3Key sets the "s3_key" field to the value that was provided on create. +func (u *AgentPluginVersionUpsertBulk) UpdateS3Key() *AgentPluginVersionUpsertBulk { + return u.Update(func(s *AgentPluginVersionUpsert) { + s.UpdateS3Key() + }) +} + +// SetParsedMeta sets the "parsed_meta" field. +func (u *AgentPluginVersionUpsertBulk) SetParsedMeta(v types.PluginParsedMeta) *AgentPluginVersionUpsertBulk { + return u.Update(func(s *AgentPluginVersionUpsert) { + s.SetParsedMeta(v) + }) +} + +// UpdateParsedMeta sets the "parsed_meta" field to the value that was provided on create. +func (u *AgentPluginVersionUpsertBulk) UpdateParsedMeta() *AgentPluginVersionUpsertBulk { + return u.Update(func(s *AgentPluginVersionUpsert) { + s.UpdateParsedMeta() + }) +} + +// ClearParsedMeta clears the value of the "parsed_meta" field. +func (u *AgentPluginVersionUpsertBulk) ClearParsedMeta() *AgentPluginVersionUpsertBulk { + return u.Update(func(s *AgentPluginVersionUpsert) { + s.ClearParsedMeta() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *AgentPluginVersionUpsertBulk) SetCreatedAt(v time.Time) *AgentPluginVersionUpsertBulk { + return u.Update(func(s *AgentPluginVersionUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *AgentPluginVersionUpsertBulk) UpdateCreatedAt() *AgentPluginVersionUpsertBulk { + return u.Update(func(s *AgentPluginVersionUpsert) { + s.UpdateCreatedAt() + }) +} + +// Exec executes the query. +func (u *AgentPluginVersionUpsertBulk) 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 AgentPluginVersionCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for AgentPluginVersionCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *AgentPluginVersionUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/agentpluginversion_delete.go b/backend/db/agentpluginversion_delete.go new file mode 100644 index 00000000..98698f05 --- /dev/null +++ b/backend/db/agentpluginversion_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/agentpluginversion" + "github.com/chaitin/MonkeyCode/backend/db/predicate" +) + +// AgentPluginVersionDelete is the builder for deleting a AgentPluginVersion entity. +type AgentPluginVersionDelete struct { + config + hooks []Hook + mutation *AgentPluginVersionMutation +} + +// Where appends a list predicates to the AgentPluginVersionDelete builder. +func (_d *AgentPluginVersionDelete) Where(ps ...predicate.AgentPluginVersion) *AgentPluginVersionDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *AgentPluginVersionDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *AgentPluginVersionDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *AgentPluginVersionDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(agentpluginversion.Table, sqlgraph.NewFieldSpec(agentpluginversion.FieldID, field.TypeUUID)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// AgentPluginVersionDeleteOne is the builder for deleting a single AgentPluginVersion entity. +type AgentPluginVersionDeleteOne struct { + _d *AgentPluginVersionDelete +} + +// Where appends a list predicates to the AgentPluginVersionDelete builder. +func (_d *AgentPluginVersionDeleteOne) Where(ps ...predicate.AgentPluginVersion) *AgentPluginVersionDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *AgentPluginVersionDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{agentpluginversion.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *AgentPluginVersionDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/agentpluginversion_query.go b/backend/db/agentpluginversion_query.go new file mode 100644 index 00000000..0d30e26f --- /dev/null +++ b/backend/db/agentpluginversion_query.go @@ -0,0 +1,657 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/agentplugin" + "github.com/chaitin/MonkeyCode/backend/db/agentpluginversion" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/google/uuid" +) + +// AgentPluginVersionQuery is the builder for querying AgentPluginVersion entities. +type AgentPluginVersionQuery struct { + config + ctx *QueryContext + order []agentpluginversion.OrderOption + inters []Interceptor + predicates []predicate.AgentPluginVersion + withPlugin *AgentPluginQuery + 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 AgentPluginVersionQuery builder. +func (_q *AgentPluginVersionQuery) Where(ps ...predicate.AgentPluginVersion) *AgentPluginVersionQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *AgentPluginVersionQuery) Limit(limit int) *AgentPluginVersionQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *AgentPluginVersionQuery) Offset(offset int) *AgentPluginVersionQuery { + _q.ctx.Offset = &offset + return _q +} + +// 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 (_q *AgentPluginVersionQuery) Unique(unique bool) *AgentPluginVersionQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *AgentPluginVersionQuery) Order(o ...agentpluginversion.OrderOption) *AgentPluginVersionQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryPlugin chains the current query on the "plugin" edge. +func (_q *AgentPluginVersionQuery) QueryPlugin() *AgentPluginQuery { + query := (&AgentPluginClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(agentpluginversion.Table, agentpluginversion.FieldID, selector), + sqlgraph.To(agentplugin.Table, agentplugin.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, agentpluginversion.PluginTable, agentpluginversion.PluginColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first AgentPluginVersion entity from the query. +// Returns a *NotFoundError when no AgentPluginVersion was found. +func (_q *AgentPluginVersionQuery) First(ctx context.Context) (*AgentPluginVersion, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{agentpluginversion.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *AgentPluginVersionQuery) FirstX(ctx context.Context) *AgentPluginVersion { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first AgentPluginVersion ID from the query. +// Returns a *NotFoundError when no AgentPluginVersion ID was found. +func (_q *AgentPluginVersionQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{agentpluginversion.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *AgentPluginVersionQuery) FirstIDX(ctx context.Context) uuid.UUID { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single AgentPluginVersion entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one AgentPluginVersion entity is found. +// Returns a *NotFoundError when no AgentPluginVersion entities are found. +func (_q *AgentPluginVersionQuery) Only(ctx context.Context) (*AgentPluginVersion, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{agentpluginversion.Label} + default: + return nil, &NotSingularError{agentpluginversion.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *AgentPluginVersionQuery) OnlyX(ctx context.Context) *AgentPluginVersion { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only AgentPluginVersion ID in the query. +// Returns a *NotSingularError when more than one AgentPluginVersion ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *AgentPluginVersionQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{agentpluginversion.Label} + default: + err = &NotSingularError{agentpluginversion.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *AgentPluginVersionQuery) OnlyIDX(ctx context.Context) uuid.UUID { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of AgentPluginVersions. +func (_q *AgentPluginVersionQuery) All(ctx context.Context) ([]*AgentPluginVersion, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*AgentPluginVersion, *AgentPluginVersionQuery]() + return withInterceptors[[]*AgentPluginVersion](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *AgentPluginVersionQuery) AllX(ctx context.Context) []*AgentPluginVersion { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of AgentPluginVersion IDs. +func (_q *AgentPluginVersionQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(agentpluginversion.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *AgentPluginVersionQuery) IDsX(ctx context.Context) []uuid.UUID { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *AgentPluginVersionQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*AgentPluginVersionQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *AgentPluginVersionQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *AgentPluginVersionQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.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 (_q *AgentPluginVersionQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the AgentPluginVersionQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *AgentPluginVersionQuery) Clone() *AgentPluginVersionQuery { + if _q == nil { + return nil + } + return &AgentPluginVersionQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]agentpluginversion.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.AgentPluginVersion{}, _q.predicates...), + withPlugin: _q.withPlugin.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + modifiers: append([]func(*sql.Selector){}, _q.modifiers...), + } +} + +// WithPlugin tells the query-builder to eager-load the nodes that are connected to +// the "plugin" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *AgentPluginVersionQuery) WithPlugin(opts ...func(*AgentPluginQuery)) *AgentPluginVersionQuery { + query := (&AgentPluginClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withPlugin = query + return _q +} + +// 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 { +// ResourceID uuid.UUID `json:"resource_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.AgentPluginVersion.Query(). +// GroupBy(agentpluginversion.FieldResourceID). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *AgentPluginVersionQuery) GroupBy(field string, fields ...string) *AgentPluginVersionGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &AgentPluginVersionGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = agentpluginversion.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 { +// ResourceID uuid.UUID `json:"resource_id,omitempty"` +// } +// +// client.AgentPluginVersion.Query(). +// Select(agentpluginversion.FieldResourceID). +// Scan(ctx, &v) +func (_q *AgentPluginVersionQuery) Select(fields ...string) *AgentPluginVersionSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &AgentPluginVersionSelect{AgentPluginVersionQuery: _q} + sbuild.label = agentpluginversion.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a AgentPluginVersionSelect configured with the given aggregations. +func (_q *AgentPluginVersionQuery) Aggregate(fns ...AggregateFunc) *AgentPluginVersionSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *AgentPluginVersionQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.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, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !agentpluginversion.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *AgentPluginVersionQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*AgentPluginVersion, error) { + var ( + nodes = []*AgentPluginVersion{} + _spec = _q.querySpec() + loadedTypes = [1]bool{ + _q.withPlugin != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*AgentPluginVersion).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &AgentPluginVersion{config: _q.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := _q.withPlugin; query != nil { + if err := _q.loadPlugin(ctx, query, nodes, nil, + func(n *AgentPluginVersion, e *AgentPlugin) { n.Edges.Plugin = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *AgentPluginVersionQuery) loadPlugin(ctx context.Context, query *AgentPluginQuery, nodes []*AgentPluginVersion, init func(*AgentPluginVersion), assign func(*AgentPluginVersion, *AgentPlugin)) error { + ids := make([]uuid.UUID, 0, len(nodes)) + nodeids := make(map[uuid.UUID][]*AgentPluginVersion) + for i := range nodes { + fk := nodes[i].ResourceID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(agentplugin.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return fmt.Errorf(`unexpected foreign-key "resource_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *AgentPluginVersionQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *AgentPluginVersionQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(agentpluginversion.Table, agentpluginversion.Columns, sqlgraph.NewFieldSpec(agentpluginversion.FieldID, field.TypeUUID)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, agentpluginversion.FieldID) + for i := range fields { + if fields[i] != agentpluginversion.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withPlugin != nil { + _spec.Node.AddColumnOnce(agentpluginversion.FieldResourceID) + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *AgentPluginVersionQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(agentpluginversion.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = agentpluginversion.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, m := range _q.modifiers { + m(selector) + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.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 := _q.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 (_q *AgentPluginVersionQuery) ForUpdate(opts ...sql.LockOption) *AgentPluginVersionQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForUpdate(opts...) + }) + return _q +} + +// 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 (_q *AgentPluginVersionQuery) ForShare(opts ...sql.LockOption) *AgentPluginVersionQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (_q *AgentPluginVersionQuery) Modify(modifiers ...func(s *sql.Selector)) *AgentPluginVersionSelect { + _q.modifiers = append(_q.modifiers, modifiers...) + return _q.Select() +} + +// AgentPluginVersionGroupBy is the group-by builder for AgentPluginVersion entities. +type AgentPluginVersionGroupBy struct { + selector + build *AgentPluginVersionQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *AgentPluginVersionGroupBy) Aggregate(fns ...AggregateFunc) *AgentPluginVersionGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *AgentPluginVersionGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*AgentPluginVersionQuery, *AgentPluginVersionGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *AgentPluginVersionGroupBy) sqlScan(ctx context.Context, root *AgentPluginVersionQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// AgentPluginVersionSelect is the builder for selecting fields of AgentPluginVersion entities. +type AgentPluginVersionSelect struct { + *AgentPluginVersionQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *AgentPluginVersionSelect) Aggregate(fns ...AggregateFunc) *AgentPluginVersionSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *AgentPluginVersionSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*AgentPluginVersionQuery, *AgentPluginVersionSelect](ctx, _s.AgentPluginVersionQuery, _s, _s.inters, v) +} + +func (_s *AgentPluginVersionSelect) sqlScan(ctx context.Context, root *AgentPluginVersionQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.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 := _s.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 (_s *AgentPluginVersionSelect) Modify(modifiers ...func(s *sql.Selector)) *AgentPluginVersionSelect { + _s.modifiers = append(_s.modifiers, modifiers...) + return _s +} diff --git a/backend/db/agentpluginversion_update.go b/backend/db/agentpluginversion_update.go new file mode 100644 index 00000000..19ace884 --- /dev/null +++ b/backend/db/agentpluginversion_update.go @@ -0,0 +1,511 @@ +// 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/agentplugin" + "github.com/chaitin/MonkeyCode/backend/db/agentpluginversion" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/ent/types" + "github.com/google/uuid" +) + +// AgentPluginVersionUpdate is the builder for updating AgentPluginVersion entities. +type AgentPluginVersionUpdate struct { + config + hooks []Hook + mutation *AgentPluginVersionMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the AgentPluginVersionUpdate builder. +func (_u *AgentPluginVersionUpdate) Where(ps ...predicate.AgentPluginVersion) *AgentPluginVersionUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetResourceID sets the "resource_id" field. +func (_u *AgentPluginVersionUpdate) SetResourceID(v uuid.UUID) *AgentPluginVersionUpdate { + _u.mutation.SetResourceID(v) + return _u +} + +// SetNillableResourceID sets the "resource_id" field if the given value is not nil. +func (_u *AgentPluginVersionUpdate) SetNillableResourceID(v *uuid.UUID) *AgentPluginVersionUpdate { + if v != nil { + _u.SetResourceID(*v) + } + return _u +} + +// SetVersion sets the "version" field. +func (_u *AgentPluginVersionUpdate) SetVersion(v string) *AgentPluginVersionUpdate { + _u.mutation.SetVersion(v) + return _u +} + +// SetNillableVersion sets the "version" field if the given value is not nil. +func (_u *AgentPluginVersionUpdate) SetNillableVersion(v *string) *AgentPluginVersionUpdate { + if v != nil { + _u.SetVersion(*v) + } + return _u +} + +// SetS3Key sets the "s3_key" field. +func (_u *AgentPluginVersionUpdate) SetS3Key(v string) *AgentPluginVersionUpdate { + _u.mutation.SetS3Key(v) + return _u +} + +// SetNillableS3Key sets the "s3_key" field if the given value is not nil. +func (_u *AgentPluginVersionUpdate) SetNillableS3Key(v *string) *AgentPluginVersionUpdate { + if v != nil { + _u.SetS3Key(*v) + } + return _u +} + +// SetParsedMeta sets the "parsed_meta" field. +func (_u *AgentPluginVersionUpdate) SetParsedMeta(v types.PluginParsedMeta) *AgentPluginVersionUpdate { + _u.mutation.SetParsedMeta(v) + return _u +} + +// SetNillableParsedMeta sets the "parsed_meta" field if the given value is not nil. +func (_u *AgentPluginVersionUpdate) SetNillableParsedMeta(v *types.PluginParsedMeta) *AgentPluginVersionUpdate { + if v != nil { + _u.SetParsedMeta(*v) + } + return _u +} + +// ClearParsedMeta clears the value of the "parsed_meta" field. +func (_u *AgentPluginVersionUpdate) ClearParsedMeta() *AgentPluginVersionUpdate { + _u.mutation.ClearParsedMeta() + return _u +} + +// SetCreatedAt sets the "created_at" field. +func (_u *AgentPluginVersionUpdate) SetCreatedAt(v time.Time) *AgentPluginVersionUpdate { + _u.mutation.SetCreatedAt(v) + return _u +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_u *AgentPluginVersionUpdate) SetNillableCreatedAt(v *time.Time) *AgentPluginVersionUpdate { + if v != nil { + _u.SetCreatedAt(*v) + } + return _u +} + +// SetPluginID sets the "plugin" edge to the AgentPlugin entity by ID. +func (_u *AgentPluginVersionUpdate) SetPluginID(id uuid.UUID) *AgentPluginVersionUpdate { + _u.mutation.SetPluginID(id) + return _u +} + +// SetPlugin sets the "plugin" edge to the AgentPlugin entity. +func (_u *AgentPluginVersionUpdate) SetPlugin(v *AgentPlugin) *AgentPluginVersionUpdate { + return _u.SetPluginID(v.ID) +} + +// Mutation returns the AgentPluginVersionMutation object of the builder. +func (_u *AgentPluginVersionUpdate) Mutation() *AgentPluginVersionMutation { + return _u.mutation +} + +// ClearPlugin clears the "plugin" edge to the AgentPlugin entity. +func (_u *AgentPluginVersionUpdate) ClearPlugin() *AgentPluginVersionUpdate { + _u.mutation.ClearPlugin() + return _u +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *AgentPluginVersionUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *AgentPluginVersionUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *AgentPluginVersionUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *AgentPluginVersionUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *AgentPluginVersionUpdate) check() error { + if v, ok := _u.mutation.Version(); ok { + if err := agentpluginversion.VersionValidator(v); err != nil { + return &ValidationError{Name: "version", err: fmt.Errorf(`db: validator failed for field "AgentPluginVersion.version": %w`, err)} + } + } + if v, ok := _u.mutation.S3Key(); ok { + if err := agentpluginversion.S3KeyValidator(v); err != nil { + return &ValidationError{Name: "s3_key", err: fmt.Errorf(`db: validator failed for field "AgentPluginVersion.s3_key": %w`, err)} + } + } + if _u.mutation.PluginCleared() && len(_u.mutation.PluginIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "AgentPluginVersion.plugin"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (_u *AgentPluginVersionUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *AgentPluginVersionUpdate { + _u.modifiers = append(_u.modifiers, modifiers...) + return _u +} + +func (_u *AgentPluginVersionUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(agentpluginversion.Table, agentpluginversion.Columns, sqlgraph.NewFieldSpec(agentpluginversion.FieldID, field.TypeUUID)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.Version(); ok { + _spec.SetField(agentpluginversion.FieldVersion, field.TypeString, value) + } + if value, ok := _u.mutation.S3Key(); ok { + _spec.SetField(agentpluginversion.FieldS3Key, field.TypeString, value) + } + if value, ok := _u.mutation.ParsedMeta(); ok { + _spec.SetField(agentpluginversion.FieldParsedMeta, field.TypeJSON, value) + } + if _u.mutation.ParsedMetaCleared() { + _spec.ClearField(agentpluginversion.FieldParsedMeta, field.TypeJSON) + } + if value, ok := _u.mutation.CreatedAt(); ok { + _spec.SetField(agentpluginversion.FieldCreatedAt, field.TypeTime, value) + } + if _u.mutation.PluginCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: agentpluginversion.PluginTable, + Columns: []string{agentpluginversion.PluginColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentplugin.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.PluginIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: agentpluginversion.PluginTable, + Columns: []string{agentpluginversion.PluginColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentplugin.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(_u.modifiers...) + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{agentpluginversion.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// AgentPluginVersionUpdateOne is the builder for updating a single AgentPluginVersion entity. +type AgentPluginVersionUpdateOne struct { + config + fields []string + hooks []Hook + mutation *AgentPluginVersionMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetResourceID sets the "resource_id" field. +func (_u *AgentPluginVersionUpdateOne) SetResourceID(v uuid.UUID) *AgentPluginVersionUpdateOne { + _u.mutation.SetResourceID(v) + return _u +} + +// SetNillableResourceID sets the "resource_id" field if the given value is not nil. +func (_u *AgentPluginVersionUpdateOne) SetNillableResourceID(v *uuid.UUID) *AgentPluginVersionUpdateOne { + if v != nil { + _u.SetResourceID(*v) + } + return _u +} + +// SetVersion sets the "version" field. +func (_u *AgentPluginVersionUpdateOne) SetVersion(v string) *AgentPluginVersionUpdateOne { + _u.mutation.SetVersion(v) + return _u +} + +// SetNillableVersion sets the "version" field if the given value is not nil. +func (_u *AgentPluginVersionUpdateOne) SetNillableVersion(v *string) *AgentPluginVersionUpdateOne { + if v != nil { + _u.SetVersion(*v) + } + return _u +} + +// SetS3Key sets the "s3_key" field. +func (_u *AgentPluginVersionUpdateOne) SetS3Key(v string) *AgentPluginVersionUpdateOne { + _u.mutation.SetS3Key(v) + return _u +} + +// SetNillableS3Key sets the "s3_key" field if the given value is not nil. +func (_u *AgentPluginVersionUpdateOne) SetNillableS3Key(v *string) *AgentPluginVersionUpdateOne { + if v != nil { + _u.SetS3Key(*v) + } + return _u +} + +// SetParsedMeta sets the "parsed_meta" field. +func (_u *AgentPluginVersionUpdateOne) SetParsedMeta(v types.PluginParsedMeta) *AgentPluginVersionUpdateOne { + _u.mutation.SetParsedMeta(v) + return _u +} + +// SetNillableParsedMeta sets the "parsed_meta" field if the given value is not nil. +func (_u *AgentPluginVersionUpdateOne) SetNillableParsedMeta(v *types.PluginParsedMeta) *AgentPluginVersionUpdateOne { + if v != nil { + _u.SetParsedMeta(*v) + } + return _u +} + +// ClearParsedMeta clears the value of the "parsed_meta" field. +func (_u *AgentPluginVersionUpdateOne) ClearParsedMeta() *AgentPluginVersionUpdateOne { + _u.mutation.ClearParsedMeta() + return _u +} + +// SetCreatedAt sets the "created_at" field. +func (_u *AgentPluginVersionUpdateOne) SetCreatedAt(v time.Time) *AgentPluginVersionUpdateOne { + _u.mutation.SetCreatedAt(v) + return _u +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_u *AgentPluginVersionUpdateOne) SetNillableCreatedAt(v *time.Time) *AgentPluginVersionUpdateOne { + if v != nil { + _u.SetCreatedAt(*v) + } + return _u +} + +// SetPluginID sets the "plugin" edge to the AgentPlugin entity by ID. +func (_u *AgentPluginVersionUpdateOne) SetPluginID(id uuid.UUID) *AgentPluginVersionUpdateOne { + _u.mutation.SetPluginID(id) + return _u +} + +// SetPlugin sets the "plugin" edge to the AgentPlugin entity. +func (_u *AgentPluginVersionUpdateOne) SetPlugin(v *AgentPlugin) *AgentPluginVersionUpdateOne { + return _u.SetPluginID(v.ID) +} + +// Mutation returns the AgentPluginVersionMutation object of the builder. +func (_u *AgentPluginVersionUpdateOne) Mutation() *AgentPluginVersionMutation { + return _u.mutation +} + +// ClearPlugin clears the "plugin" edge to the AgentPlugin entity. +func (_u *AgentPluginVersionUpdateOne) ClearPlugin() *AgentPluginVersionUpdateOne { + _u.mutation.ClearPlugin() + return _u +} + +// Where appends a list predicates to the AgentPluginVersionUpdate builder. +func (_u *AgentPluginVersionUpdateOne) Where(ps ...predicate.AgentPluginVersion) *AgentPluginVersionUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *AgentPluginVersionUpdateOne) Select(field string, fields ...string) *AgentPluginVersionUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated AgentPluginVersion entity. +func (_u *AgentPluginVersionUpdateOne) Save(ctx context.Context) (*AgentPluginVersion, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *AgentPluginVersionUpdateOne) SaveX(ctx context.Context) *AgentPluginVersion { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *AgentPluginVersionUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *AgentPluginVersionUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *AgentPluginVersionUpdateOne) check() error { + if v, ok := _u.mutation.Version(); ok { + if err := agentpluginversion.VersionValidator(v); err != nil { + return &ValidationError{Name: "version", err: fmt.Errorf(`db: validator failed for field "AgentPluginVersion.version": %w`, err)} + } + } + if v, ok := _u.mutation.S3Key(); ok { + if err := agentpluginversion.S3KeyValidator(v); err != nil { + return &ValidationError{Name: "s3_key", err: fmt.Errorf(`db: validator failed for field "AgentPluginVersion.s3_key": %w`, err)} + } + } + if _u.mutation.PluginCleared() && len(_u.mutation.PluginIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "AgentPluginVersion.plugin"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (_u *AgentPluginVersionUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *AgentPluginVersionUpdateOne { + _u.modifiers = append(_u.modifiers, modifiers...) + return _u +} + +func (_u *AgentPluginVersionUpdateOne) sqlSave(ctx context.Context) (_node *AgentPluginVersion, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(agentpluginversion.Table, agentpluginversion.Columns, sqlgraph.NewFieldSpec(agentpluginversion.FieldID, field.TypeUUID)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "AgentPluginVersion.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, agentpluginversion.FieldID) + for _, f := range fields { + if !agentpluginversion.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != agentpluginversion.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.Version(); ok { + _spec.SetField(agentpluginversion.FieldVersion, field.TypeString, value) + } + if value, ok := _u.mutation.S3Key(); ok { + _spec.SetField(agentpluginversion.FieldS3Key, field.TypeString, value) + } + if value, ok := _u.mutation.ParsedMeta(); ok { + _spec.SetField(agentpluginversion.FieldParsedMeta, field.TypeJSON, value) + } + if _u.mutation.ParsedMetaCleared() { + _spec.ClearField(agentpluginversion.FieldParsedMeta, field.TypeJSON) + } + if value, ok := _u.mutation.CreatedAt(); ok { + _spec.SetField(agentpluginversion.FieldCreatedAt, field.TypeTime, value) + } + if _u.mutation.PluginCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: agentpluginversion.PluginTable, + Columns: []string{agentpluginversion.PluginColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentplugin.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.PluginIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: agentpluginversion.PluginTable, + Columns: []string{agentpluginversion.PluginColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentplugin.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(_u.modifiers...) + _node = &AgentPluginVersion{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{agentpluginversion.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/backend/db/agentrule.go b/backend/db/agentrule.go new file mode 100644 index 00000000..aa6a98ec --- /dev/null +++ b/backend/db/agentrule.go @@ -0,0 +1,228 @@ +// 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/agentrule" + "github.com/google/uuid" +) + +// AgentRule is the model entity for the AgentRule schema. +type AgentRule struct { + config `json:"-"` + // ID of the ent. + ID uuid.UUID `json:"id,omitempty"` + // Name holds the value of the "name" field. + Name string `json:"name,omitempty"` + // Description holds the value of the "description" field. + Description string `json:"description,omitempty"` + // ScopeType holds the value of the "scope_type" field. + ScopeType agentrule.ScopeType `json:"scope_type,omitempty"` + // ScopeID holds the value of the "scope_id" field. + ScopeID string `json:"scope_id,omitempty"` + // CreatedBy holds the value of the "created_by" field. + CreatedBy uuid.UUID `json:"created_by,omitempty"` + // ActiveVersionID holds the value of the "active_version_id" field. + ActiveVersionID *uuid.UUID `json:"active_version_id,omitempty"` + // IsDeleted holds the value of the "is_deleted" field. + IsDeleted bool `json:"is_deleted,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + // UpdatedAt holds the value of the "updated_at" field. + UpdatedAt time.Time `json:"updated_at,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the AgentRuleQuery when eager-loading is set. + Edges AgentRuleEdges `json:"edges"` + selectValues sql.SelectValues +} + +// AgentRuleEdges holds the relations/edges for other nodes in the graph. +type AgentRuleEdges struct { + // Versions holds the value of the versions edge. + Versions []*AgentRuleVersion `json:"versions,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// VersionsOrErr returns the Versions value or an error if the edge +// was not loaded in eager-loading. +func (e AgentRuleEdges) VersionsOrErr() ([]*AgentRuleVersion, error) { + if e.loadedTypes[0] { + return e.Versions, nil + } + return nil, &NotLoadedError{edge: "versions"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*AgentRule) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case agentrule.FieldActiveVersionID: + values[i] = &sql.NullScanner{S: new(uuid.UUID)} + case agentrule.FieldIsDeleted: + values[i] = new(sql.NullBool) + case agentrule.FieldName, agentrule.FieldDescription, agentrule.FieldScopeType, agentrule.FieldScopeID: + values[i] = new(sql.NullString) + case agentrule.FieldCreatedAt, agentrule.FieldUpdatedAt: + values[i] = new(sql.NullTime) + case agentrule.FieldID, agentrule.FieldCreatedBy: + 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 AgentRule fields. +func (_m *AgentRule) 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 agentrule.FieldID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value != nil { + _m.ID = *value + } + case agentrule.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + _m.Name = value.String + } + case agentrule.FieldDescription: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field description", values[i]) + } else if value.Valid { + _m.Description = value.String + } + case agentrule.FieldScopeType: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field scope_type", values[i]) + } else if value.Valid { + _m.ScopeType = agentrule.ScopeType(value.String) + } + case agentrule.FieldScopeID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field scope_id", values[i]) + } else if value.Valid { + _m.ScopeID = value.String + } + case agentrule.FieldCreatedBy: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field created_by", values[i]) + } else if value != nil { + _m.CreatedBy = *value + } + case agentrule.FieldActiveVersionID: + if value, ok := values[i].(*sql.NullScanner); !ok { + return fmt.Errorf("unexpected type %T for field active_version_id", values[i]) + } else if value.Valid { + _m.ActiveVersionID = new(uuid.UUID) + *_m.ActiveVersionID = *value.S.(*uuid.UUID) + } + case agentrule.FieldIsDeleted: + if value, ok := values[i].(*sql.NullBool); !ok { + return fmt.Errorf("unexpected type %T for field is_deleted", values[i]) + } else if value.Valid { + _m.IsDeleted = value.Bool + } + case agentrule.FieldCreatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field created_at", values[i]) + } else if value.Valid { + _m.CreatedAt = value.Time + } + case agentrule.FieldUpdatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field updated_at", values[i]) + } else if value.Valid { + _m.UpdatedAt = value.Time + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the AgentRule. +// This includes values selected through modifiers, order, etc. +func (_m *AgentRule) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryVersions queries the "versions" edge of the AgentRule entity. +func (_m *AgentRule) QueryVersions() *AgentRuleVersionQuery { + return NewAgentRuleClient(_m.config).QueryVersions(_m) +} + +// Update returns a builder for updating this AgentRule. +// Note that you need to call AgentRule.Unwrap() before calling this method if this AgentRule +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *AgentRule) Update() *AgentRuleUpdateOne { + return NewAgentRuleClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the AgentRule entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (_m *AgentRule) Unwrap() *AgentRule { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: AgentRule is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *AgentRule) String() string { + var builder strings.Builder + builder.WriteString("AgentRule(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("name=") + builder.WriteString(_m.Name) + builder.WriteString(", ") + builder.WriteString("description=") + builder.WriteString(_m.Description) + builder.WriteString(", ") + builder.WriteString("scope_type=") + builder.WriteString(fmt.Sprintf("%v", _m.ScopeType)) + builder.WriteString(", ") + builder.WriteString("scope_id=") + builder.WriteString(_m.ScopeID) + builder.WriteString(", ") + builder.WriteString("created_by=") + builder.WriteString(fmt.Sprintf("%v", _m.CreatedBy)) + builder.WriteString(", ") + if v := _m.ActiveVersionID; v != nil { + builder.WriteString("active_version_id=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + builder.WriteString("is_deleted=") + builder.WriteString(fmt.Sprintf("%v", _m.IsDeleted)) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("updated_at=") + builder.WriteString(_m.UpdatedAt.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// AgentRules is a parsable slice of AgentRule. +type AgentRules []*AgentRule diff --git a/backend/db/agentrule/agentrule.go b/backend/db/agentrule/agentrule.go new file mode 100644 index 00000000..8dbd29e2 --- /dev/null +++ b/backend/db/agentrule/agentrule.go @@ -0,0 +1,188 @@ +// Code generated by ent, DO NOT EDIT. + +package agentrule + +import ( + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/google/uuid" +) + +const ( + // Label holds the string label denoting the agentrule type in the database. + Label = "agent_rule" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldDescription holds the string denoting the description field in the database. + FieldDescription = "description" + // FieldScopeType holds the string denoting the scope_type field in the database. + FieldScopeType = "scope_type" + // FieldScopeID holds the string denoting the scope_id field in the database. + FieldScopeID = "scope_id" + // FieldCreatedBy holds the string denoting the created_by field in the database. + FieldCreatedBy = "created_by" + // FieldActiveVersionID holds the string denoting the active_version_id field in the database. + FieldActiveVersionID = "active_version_id" + // FieldIsDeleted holds the string denoting the is_deleted field in the database. + FieldIsDeleted = "is_deleted" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // FieldUpdatedAt holds the string denoting the updated_at field in the database. + FieldUpdatedAt = "updated_at" + // EdgeVersions holds the string denoting the versions edge name in mutations. + EdgeVersions = "versions" + // Table holds the table name of the agentrule in the database. + Table = "agent_rules" + // VersionsTable is the table that holds the versions relation/edge. + VersionsTable = "agent_rule_versions" + // VersionsInverseTable is the table name for the AgentRuleVersion entity. + // It exists in this package in order to avoid circular dependency with the "agentruleversion" package. + VersionsInverseTable = "agent_rule_versions" + // VersionsColumn is the table column denoting the versions relation/edge. + VersionsColumn = "rule_id" +) + +// Columns holds all SQL columns for agentrule fields. +var Columns = []string{ + FieldID, + FieldName, + FieldDescription, + FieldScopeType, + FieldScopeID, + FieldCreatedBy, + FieldActiveVersionID, + FieldIsDeleted, + FieldCreatedAt, + FieldUpdatedAt, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // NameValidator is a validator for the "name" field. It is called by the builders before save. + NameValidator func(string) error + // DefaultScopeID holds the default value on creation for the "scope_id" field. + DefaultScopeID string + // DefaultIsDeleted holds the default value on creation for the "is_deleted" field. + DefaultIsDeleted bool + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time + // DefaultUpdatedAt holds the default value on creation for the "updated_at" field. + DefaultUpdatedAt func() time.Time + // UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field. + UpdateDefaultUpdatedAt func() time.Time + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() uuid.UUID +) + +// ScopeType defines the type for the "scope_type" enum field. +type ScopeType string + +// ScopeTypeGlobal is the default value of the ScopeType enum. +const DefaultScopeType = ScopeTypeGlobal + +// ScopeType values. +const ( + ScopeTypeGlobal ScopeType = "global" +) + +func (st ScopeType) String() string { + return string(st) +} + +// ScopeTypeValidator is a validator for the "scope_type" field enum values. It is called by the builders before save. +func ScopeTypeValidator(st ScopeType) error { + switch st { + case ScopeTypeGlobal: + return nil + default: + return fmt.Errorf("agentrule: invalid enum value for scope_type field: %q", st) + } +} + +// OrderOption defines the ordering options for the AgentRule queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} + +// ByDescription orders the results by the description field. +func ByDescription(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDescription, opts...).ToFunc() +} + +// ByScopeType orders the results by the scope_type field. +func ByScopeType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldScopeType, opts...).ToFunc() +} + +// ByScopeID orders the results by the scope_id field. +func ByScopeID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldScopeID, opts...).ToFunc() +} + +// ByCreatedBy orders the results by the created_by field. +func ByCreatedBy(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedBy, opts...).ToFunc() +} + +// ByActiveVersionID orders the results by the active_version_id field. +func ByActiveVersionID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldActiveVersionID, opts...).ToFunc() +} + +// ByIsDeleted orders the results by the is_deleted field. +func ByIsDeleted(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldIsDeleted, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// ByUpdatedAt orders the results by the updated_at field. +func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc() +} + +// ByVersionsCount orders the results by versions count. +func ByVersionsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newVersionsStep(), opts...) + } +} + +// ByVersions orders the results by versions terms. +func ByVersions(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newVersionsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newVersionsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(VersionsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, VersionsTable, VersionsColumn), + ) +} diff --git a/backend/db/agentrule/where.go b/backend/db/agentrule/where.go new file mode 100644 index 00000000..d12fcb91 --- /dev/null +++ b/backend/db/agentrule/where.go @@ -0,0 +1,540 @@ +// Code generated by ent, DO NOT EDIT. + +package agentrule + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/google/uuid" +) + +// ID filters vertices based on their ID field. +func ID(id uuid.UUID) predicate.AgentRule { + return predicate.AgentRule(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id uuid.UUID) predicate.AgentRule { + return predicate.AgentRule(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id uuid.UUID) predicate.AgentRule { + return predicate.AgentRule(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...uuid.UUID) predicate.AgentRule { + return predicate.AgentRule(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...uuid.UUID) predicate.AgentRule { + return predicate.AgentRule(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id uuid.UUID) predicate.AgentRule { + return predicate.AgentRule(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id uuid.UUID) predicate.AgentRule { + return predicate.AgentRule(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id uuid.UUID) predicate.AgentRule { + return predicate.AgentRule(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id uuid.UUID) predicate.AgentRule { + return predicate.AgentRule(sql.FieldLTE(FieldID, id)) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldEQ(FieldName, v)) +} + +// Description applies equality check predicate on the "description" field. It's identical to DescriptionEQ. +func Description(v string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldEQ(FieldDescription, v)) +} + +// ScopeID applies equality check predicate on the "scope_id" field. It's identical to ScopeIDEQ. +func ScopeID(v string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldEQ(FieldScopeID, v)) +} + +// CreatedBy applies equality check predicate on the "created_by" field. It's identical to CreatedByEQ. +func CreatedBy(v uuid.UUID) predicate.AgentRule { + return predicate.AgentRule(sql.FieldEQ(FieldCreatedBy, v)) +} + +// ActiveVersionID applies equality check predicate on the "active_version_id" field. It's identical to ActiveVersionIDEQ. +func ActiveVersionID(v uuid.UUID) predicate.AgentRule { + return predicate.AgentRule(sql.FieldEQ(FieldActiveVersionID, v)) +} + +// IsDeleted applies equality check predicate on the "is_deleted" field. It's identical to IsDeletedEQ. +func IsDeleted(v bool) predicate.AgentRule { + return predicate.AgentRule(sql.FieldEQ(FieldIsDeleted, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.AgentRule { + return predicate.AgentRule(sql.FieldEQ(FieldCreatedAt, v)) +} + +// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ. +func UpdatedAt(v time.Time) predicate.AgentRule { + return predicate.AgentRule(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldEQ(FieldName, v)) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldNEQ(FieldName, v)) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldIn(FieldName, vs...)) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldNotIn(FieldName, vs...)) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldGT(FieldName, v)) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldGTE(FieldName, v)) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldLT(FieldName, v)) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldLTE(FieldName, v)) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldContains(FieldName, v)) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldHasPrefix(FieldName, v)) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldHasSuffix(FieldName, v)) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldEqualFold(FieldName, v)) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldContainsFold(FieldName, v)) +} + +// DescriptionEQ applies the EQ predicate on the "description" field. +func DescriptionEQ(v string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldEQ(FieldDescription, v)) +} + +// DescriptionNEQ applies the NEQ predicate on the "description" field. +func DescriptionNEQ(v string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldNEQ(FieldDescription, v)) +} + +// DescriptionIn applies the In predicate on the "description" field. +func DescriptionIn(vs ...string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldIn(FieldDescription, vs...)) +} + +// DescriptionNotIn applies the NotIn predicate on the "description" field. +func DescriptionNotIn(vs ...string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldNotIn(FieldDescription, vs...)) +} + +// DescriptionGT applies the GT predicate on the "description" field. +func DescriptionGT(v string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldGT(FieldDescription, v)) +} + +// DescriptionGTE applies the GTE predicate on the "description" field. +func DescriptionGTE(v string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldGTE(FieldDescription, v)) +} + +// DescriptionLT applies the LT predicate on the "description" field. +func DescriptionLT(v string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldLT(FieldDescription, v)) +} + +// DescriptionLTE applies the LTE predicate on the "description" field. +func DescriptionLTE(v string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldLTE(FieldDescription, v)) +} + +// DescriptionContains applies the Contains predicate on the "description" field. +func DescriptionContains(v string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldContains(FieldDescription, v)) +} + +// DescriptionHasPrefix applies the HasPrefix predicate on the "description" field. +func DescriptionHasPrefix(v string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldHasPrefix(FieldDescription, v)) +} + +// DescriptionHasSuffix applies the HasSuffix predicate on the "description" field. +func DescriptionHasSuffix(v string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldHasSuffix(FieldDescription, v)) +} + +// DescriptionIsNil applies the IsNil predicate on the "description" field. +func DescriptionIsNil() predicate.AgentRule { + return predicate.AgentRule(sql.FieldIsNull(FieldDescription)) +} + +// DescriptionNotNil applies the NotNil predicate on the "description" field. +func DescriptionNotNil() predicate.AgentRule { + return predicate.AgentRule(sql.FieldNotNull(FieldDescription)) +} + +// DescriptionEqualFold applies the EqualFold predicate on the "description" field. +func DescriptionEqualFold(v string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldEqualFold(FieldDescription, v)) +} + +// DescriptionContainsFold applies the ContainsFold predicate on the "description" field. +func DescriptionContainsFold(v string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldContainsFold(FieldDescription, v)) +} + +// ScopeTypeEQ applies the EQ predicate on the "scope_type" field. +func ScopeTypeEQ(v ScopeType) predicate.AgentRule { + return predicate.AgentRule(sql.FieldEQ(FieldScopeType, v)) +} + +// ScopeTypeNEQ applies the NEQ predicate on the "scope_type" field. +func ScopeTypeNEQ(v ScopeType) predicate.AgentRule { + return predicate.AgentRule(sql.FieldNEQ(FieldScopeType, v)) +} + +// ScopeTypeIn applies the In predicate on the "scope_type" field. +func ScopeTypeIn(vs ...ScopeType) predicate.AgentRule { + return predicate.AgentRule(sql.FieldIn(FieldScopeType, vs...)) +} + +// ScopeTypeNotIn applies the NotIn predicate on the "scope_type" field. +func ScopeTypeNotIn(vs ...ScopeType) predicate.AgentRule { + return predicate.AgentRule(sql.FieldNotIn(FieldScopeType, vs...)) +} + +// ScopeIDEQ applies the EQ predicate on the "scope_id" field. +func ScopeIDEQ(v string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldEQ(FieldScopeID, v)) +} + +// ScopeIDNEQ applies the NEQ predicate on the "scope_id" field. +func ScopeIDNEQ(v string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldNEQ(FieldScopeID, v)) +} + +// ScopeIDIn applies the In predicate on the "scope_id" field. +func ScopeIDIn(vs ...string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldIn(FieldScopeID, vs...)) +} + +// ScopeIDNotIn applies the NotIn predicate on the "scope_id" field. +func ScopeIDNotIn(vs ...string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldNotIn(FieldScopeID, vs...)) +} + +// ScopeIDGT applies the GT predicate on the "scope_id" field. +func ScopeIDGT(v string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldGT(FieldScopeID, v)) +} + +// ScopeIDGTE applies the GTE predicate on the "scope_id" field. +func ScopeIDGTE(v string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldGTE(FieldScopeID, v)) +} + +// ScopeIDLT applies the LT predicate on the "scope_id" field. +func ScopeIDLT(v string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldLT(FieldScopeID, v)) +} + +// ScopeIDLTE applies the LTE predicate on the "scope_id" field. +func ScopeIDLTE(v string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldLTE(FieldScopeID, v)) +} + +// ScopeIDContains applies the Contains predicate on the "scope_id" field. +func ScopeIDContains(v string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldContains(FieldScopeID, v)) +} + +// ScopeIDHasPrefix applies the HasPrefix predicate on the "scope_id" field. +func ScopeIDHasPrefix(v string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldHasPrefix(FieldScopeID, v)) +} + +// ScopeIDHasSuffix applies the HasSuffix predicate on the "scope_id" field. +func ScopeIDHasSuffix(v string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldHasSuffix(FieldScopeID, v)) +} + +// ScopeIDEqualFold applies the EqualFold predicate on the "scope_id" field. +func ScopeIDEqualFold(v string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldEqualFold(FieldScopeID, v)) +} + +// ScopeIDContainsFold applies the ContainsFold predicate on the "scope_id" field. +func ScopeIDContainsFold(v string) predicate.AgentRule { + return predicate.AgentRule(sql.FieldContainsFold(FieldScopeID, v)) +} + +// CreatedByEQ applies the EQ predicate on the "created_by" field. +func CreatedByEQ(v uuid.UUID) predicate.AgentRule { + return predicate.AgentRule(sql.FieldEQ(FieldCreatedBy, v)) +} + +// CreatedByNEQ applies the NEQ predicate on the "created_by" field. +func CreatedByNEQ(v uuid.UUID) predicate.AgentRule { + return predicate.AgentRule(sql.FieldNEQ(FieldCreatedBy, v)) +} + +// CreatedByIn applies the In predicate on the "created_by" field. +func CreatedByIn(vs ...uuid.UUID) predicate.AgentRule { + return predicate.AgentRule(sql.FieldIn(FieldCreatedBy, vs...)) +} + +// CreatedByNotIn applies the NotIn predicate on the "created_by" field. +func CreatedByNotIn(vs ...uuid.UUID) predicate.AgentRule { + return predicate.AgentRule(sql.FieldNotIn(FieldCreatedBy, vs...)) +} + +// CreatedByGT applies the GT predicate on the "created_by" field. +func CreatedByGT(v uuid.UUID) predicate.AgentRule { + return predicate.AgentRule(sql.FieldGT(FieldCreatedBy, v)) +} + +// CreatedByGTE applies the GTE predicate on the "created_by" field. +func CreatedByGTE(v uuid.UUID) predicate.AgentRule { + return predicate.AgentRule(sql.FieldGTE(FieldCreatedBy, v)) +} + +// CreatedByLT applies the LT predicate on the "created_by" field. +func CreatedByLT(v uuid.UUID) predicate.AgentRule { + return predicate.AgentRule(sql.FieldLT(FieldCreatedBy, v)) +} + +// CreatedByLTE applies the LTE predicate on the "created_by" field. +func CreatedByLTE(v uuid.UUID) predicate.AgentRule { + return predicate.AgentRule(sql.FieldLTE(FieldCreatedBy, v)) +} + +// ActiveVersionIDEQ applies the EQ predicate on the "active_version_id" field. +func ActiveVersionIDEQ(v uuid.UUID) predicate.AgentRule { + return predicate.AgentRule(sql.FieldEQ(FieldActiveVersionID, v)) +} + +// ActiveVersionIDNEQ applies the NEQ predicate on the "active_version_id" field. +func ActiveVersionIDNEQ(v uuid.UUID) predicate.AgentRule { + return predicate.AgentRule(sql.FieldNEQ(FieldActiveVersionID, v)) +} + +// ActiveVersionIDIn applies the In predicate on the "active_version_id" field. +func ActiveVersionIDIn(vs ...uuid.UUID) predicate.AgentRule { + return predicate.AgentRule(sql.FieldIn(FieldActiveVersionID, vs...)) +} + +// ActiveVersionIDNotIn applies the NotIn predicate on the "active_version_id" field. +func ActiveVersionIDNotIn(vs ...uuid.UUID) predicate.AgentRule { + return predicate.AgentRule(sql.FieldNotIn(FieldActiveVersionID, vs...)) +} + +// ActiveVersionIDGT applies the GT predicate on the "active_version_id" field. +func ActiveVersionIDGT(v uuid.UUID) predicate.AgentRule { + return predicate.AgentRule(sql.FieldGT(FieldActiveVersionID, v)) +} + +// ActiveVersionIDGTE applies the GTE predicate on the "active_version_id" field. +func ActiveVersionIDGTE(v uuid.UUID) predicate.AgentRule { + return predicate.AgentRule(sql.FieldGTE(FieldActiveVersionID, v)) +} + +// ActiveVersionIDLT applies the LT predicate on the "active_version_id" field. +func ActiveVersionIDLT(v uuid.UUID) predicate.AgentRule { + return predicate.AgentRule(sql.FieldLT(FieldActiveVersionID, v)) +} + +// ActiveVersionIDLTE applies the LTE predicate on the "active_version_id" field. +func ActiveVersionIDLTE(v uuid.UUID) predicate.AgentRule { + return predicate.AgentRule(sql.FieldLTE(FieldActiveVersionID, v)) +} + +// ActiveVersionIDIsNil applies the IsNil predicate on the "active_version_id" field. +func ActiveVersionIDIsNil() predicate.AgentRule { + return predicate.AgentRule(sql.FieldIsNull(FieldActiveVersionID)) +} + +// ActiveVersionIDNotNil applies the NotNil predicate on the "active_version_id" field. +func ActiveVersionIDNotNil() predicate.AgentRule { + return predicate.AgentRule(sql.FieldNotNull(FieldActiveVersionID)) +} + +// IsDeletedEQ applies the EQ predicate on the "is_deleted" field. +func IsDeletedEQ(v bool) predicate.AgentRule { + return predicate.AgentRule(sql.FieldEQ(FieldIsDeleted, v)) +} + +// IsDeletedNEQ applies the NEQ predicate on the "is_deleted" field. +func IsDeletedNEQ(v bool) predicate.AgentRule { + return predicate.AgentRule(sql.FieldNEQ(FieldIsDeleted, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.AgentRule { + return predicate.AgentRule(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.AgentRule { + return predicate.AgentRule(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.AgentRule { + return predicate.AgentRule(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.AgentRule { + return predicate.AgentRule(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.AgentRule { + return predicate.AgentRule(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.AgentRule { + return predicate.AgentRule(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.AgentRule { + return predicate.AgentRule(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.AgentRule { + return predicate.AgentRule(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.AgentRule { + return predicate.AgentRule(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.AgentRule { + return predicate.AgentRule(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.AgentRule { + return predicate.AgentRule(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.AgentRule { + return predicate.AgentRule(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.AgentRule { + return predicate.AgentRule(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.AgentRule { + return predicate.AgentRule(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.AgentRule { + return predicate.AgentRule(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.AgentRule { + return predicate.AgentRule(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// HasVersions applies the HasEdge predicate on the "versions" edge. +func HasVersions() predicate.AgentRule { + return predicate.AgentRule(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, VersionsTable, VersionsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasVersionsWith applies the HasEdge predicate on the "versions" edge with a given conditions (other predicates). +func HasVersionsWith(preds ...predicate.AgentRuleVersion) predicate.AgentRule { + return predicate.AgentRule(func(s *sql.Selector) { + step := newVersionsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.AgentRule) predicate.AgentRule { + return predicate.AgentRule(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.AgentRule) predicate.AgentRule { + return predicate.AgentRule(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.AgentRule) predicate.AgentRule { + return predicate.AgentRule(sql.NotPredicates(p)) +} diff --git a/backend/db/agentrule_create.go b/backend/db/agentrule_create.go new file mode 100644 index 00000000..638c0ca7 --- /dev/null +++ b/backend/db/agentrule_create.go @@ -0,0 +1,1085 @@ +// 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/agentrule" + "github.com/chaitin/MonkeyCode/backend/db/agentruleversion" + "github.com/google/uuid" +) + +// AgentRuleCreate is the builder for creating a AgentRule entity. +type AgentRuleCreate struct { + config + mutation *AgentRuleMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetName sets the "name" field. +func (_c *AgentRuleCreate) SetName(v string) *AgentRuleCreate { + _c.mutation.SetName(v) + return _c +} + +// SetDescription sets the "description" field. +func (_c *AgentRuleCreate) SetDescription(v string) *AgentRuleCreate { + _c.mutation.SetDescription(v) + return _c +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_c *AgentRuleCreate) SetNillableDescription(v *string) *AgentRuleCreate { + if v != nil { + _c.SetDescription(*v) + } + return _c +} + +// SetScopeType sets the "scope_type" field. +func (_c *AgentRuleCreate) SetScopeType(v agentrule.ScopeType) *AgentRuleCreate { + _c.mutation.SetScopeType(v) + return _c +} + +// SetNillableScopeType sets the "scope_type" field if the given value is not nil. +func (_c *AgentRuleCreate) SetNillableScopeType(v *agentrule.ScopeType) *AgentRuleCreate { + if v != nil { + _c.SetScopeType(*v) + } + return _c +} + +// SetScopeID sets the "scope_id" field. +func (_c *AgentRuleCreate) SetScopeID(v string) *AgentRuleCreate { + _c.mutation.SetScopeID(v) + return _c +} + +// SetNillableScopeID sets the "scope_id" field if the given value is not nil. +func (_c *AgentRuleCreate) SetNillableScopeID(v *string) *AgentRuleCreate { + if v != nil { + _c.SetScopeID(*v) + } + return _c +} + +// SetCreatedBy sets the "created_by" field. +func (_c *AgentRuleCreate) SetCreatedBy(v uuid.UUID) *AgentRuleCreate { + _c.mutation.SetCreatedBy(v) + return _c +} + +// SetActiveVersionID sets the "active_version_id" field. +func (_c *AgentRuleCreate) SetActiveVersionID(v uuid.UUID) *AgentRuleCreate { + _c.mutation.SetActiveVersionID(v) + return _c +} + +// SetNillableActiveVersionID sets the "active_version_id" field if the given value is not nil. +func (_c *AgentRuleCreate) SetNillableActiveVersionID(v *uuid.UUID) *AgentRuleCreate { + if v != nil { + _c.SetActiveVersionID(*v) + } + return _c +} + +// SetIsDeleted sets the "is_deleted" field. +func (_c *AgentRuleCreate) SetIsDeleted(v bool) *AgentRuleCreate { + _c.mutation.SetIsDeleted(v) + return _c +} + +// SetNillableIsDeleted sets the "is_deleted" field if the given value is not nil. +func (_c *AgentRuleCreate) SetNillableIsDeleted(v *bool) *AgentRuleCreate { + if v != nil { + _c.SetIsDeleted(*v) + } + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *AgentRuleCreate) SetCreatedAt(v time.Time) *AgentRuleCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *AgentRuleCreate) SetNillableCreatedAt(v *time.Time) *AgentRuleCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *AgentRuleCreate) SetUpdatedAt(v time.Time) *AgentRuleCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *AgentRuleCreate) SetNillableUpdatedAt(v *time.Time) *AgentRuleCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *AgentRuleCreate) SetID(v uuid.UUID) *AgentRuleCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *AgentRuleCreate) SetNillableID(v *uuid.UUID) *AgentRuleCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// AddVersionIDs adds the "versions" edge to the AgentRuleVersion entity by IDs. +func (_c *AgentRuleCreate) AddVersionIDs(ids ...uuid.UUID) *AgentRuleCreate { + _c.mutation.AddVersionIDs(ids...) + return _c +} + +// AddVersions adds the "versions" edges to the AgentRuleVersion entity. +func (_c *AgentRuleCreate) AddVersions(v ...*AgentRuleVersion) *AgentRuleCreate { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddVersionIDs(ids...) +} + +// Mutation returns the AgentRuleMutation object of the builder. +func (_c *AgentRuleCreate) Mutation() *AgentRuleMutation { + return _c.mutation +} + +// Save creates the AgentRule in the database. +func (_c *AgentRuleCreate) Save(ctx context.Context) (*AgentRule, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *AgentRuleCreate) SaveX(ctx context.Context) *AgentRule { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *AgentRuleCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *AgentRuleCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *AgentRuleCreate) defaults() { + if _, ok := _c.mutation.ScopeType(); !ok { + v := agentrule.DefaultScopeType + _c.mutation.SetScopeType(v) + } + if _, ok := _c.mutation.ScopeID(); !ok { + v := agentrule.DefaultScopeID + _c.mutation.SetScopeID(v) + } + if _, ok := _c.mutation.IsDeleted(); !ok { + v := agentrule.DefaultIsDeleted + _c.mutation.SetIsDeleted(v) + } + if _, ok := _c.mutation.CreatedAt(); !ok { + v := agentrule.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := agentrule.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := agentrule.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *AgentRuleCreate) check() error { + if _, ok := _c.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`db: missing required field "AgentRule.name"`)} + } + if v, ok := _c.mutation.Name(); ok { + if err := agentrule.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "AgentRule.name": %w`, err)} + } + } + if _, ok := _c.mutation.ScopeType(); !ok { + return &ValidationError{Name: "scope_type", err: errors.New(`db: missing required field "AgentRule.scope_type"`)} + } + if v, ok := _c.mutation.ScopeType(); ok { + if err := agentrule.ScopeTypeValidator(v); err != nil { + return &ValidationError{Name: "scope_type", err: fmt.Errorf(`db: validator failed for field "AgentRule.scope_type": %w`, err)} + } + } + if _, ok := _c.mutation.ScopeID(); !ok { + return &ValidationError{Name: "scope_id", err: errors.New(`db: missing required field "AgentRule.scope_id"`)} + } + if _, ok := _c.mutation.CreatedBy(); !ok { + return &ValidationError{Name: "created_by", err: errors.New(`db: missing required field "AgentRule.created_by"`)} + } + if _, ok := _c.mutation.IsDeleted(); !ok { + return &ValidationError{Name: "is_deleted", err: errors.New(`db: missing required field "AgentRule.is_deleted"`)} + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "AgentRule.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "AgentRule.updated_at"`)} + } + return nil +} + +func (_c *AgentRuleCreate) sqlSave(ctx context.Context) (*AgentRule, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.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 + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *AgentRuleCreate) createSpec() (*AgentRule, *sqlgraph.CreateSpec) { + var ( + _node = &AgentRule{config: _c.config} + _spec = sqlgraph.NewCreateSpec(agentrule.Table, sqlgraph.NewFieldSpec(agentrule.FieldID, field.TypeUUID)) + ) + _spec.OnConflict = _c.conflict + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = &id + } + if value, ok := _c.mutation.Name(); ok { + _spec.SetField(agentrule.FieldName, field.TypeString, value) + _node.Name = value + } + if value, ok := _c.mutation.Description(); ok { + _spec.SetField(agentrule.FieldDescription, field.TypeString, value) + _node.Description = value + } + if value, ok := _c.mutation.ScopeType(); ok { + _spec.SetField(agentrule.FieldScopeType, field.TypeEnum, value) + _node.ScopeType = value + } + if value, ok := _c.mutation.ScopeID(); ok { + _spec.SetField(agentrule.FieldScopeID, field.TypeString, value) + _node.ScopeID = value + } + if value, ok := _c.mutation.CreatedBy(); ok { + _spec.SetField(agentrule.FieldCreatedBy, field.TypeUUID, value) + _node.CreatedBy = value + } + if value, ok := _c.mutation.ActiveVersionID(); ok { + _spec.SetField(agentrule.FieldActiveVersionID, field.TypeUUID, value) + _node.ActiveVersionID = &value + } + if value, ok := _c.mutation.IsDeleted(); ok { + _spec.SetField(agentrule.FieldIsDeleted, field.TypeBool, value) + _node.IsDeleted = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(agentrule.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(agentrule.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if nodes := _c.mutation.VersionsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agentrule.VersionsTable, + Columns: []string{agentrule.VersionsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentruleversion.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.AgentRule.Create(). +// SetName(v). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.AgentRuleUpsert) { +// SetName(v+v). +// }). +// Exec(ctx) +func (_c *AgentRuleCreate) OnConflict(opts ...sql.ConflictOption) *AgentRuleUpsertOne { + _c.conflict = opts + return &AgentRuleUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.AgentRule.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *AgentRuleCreate) OnConflictColumns(columns ...string) *AgentRuleUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &AgentRuleUpsertOne{ + create: _c, + } +} + +type ( + // AgentRuleUpsertOne is the builder for "upsert"-ing + // one AgentRule node. + AgentRuleUpsertOne struct { + create *AgentRuleCreate + } + + // AgentRuleUpsert is the "OnConflict" setter. + AgentRuleUpsert struct { + *sql.UpdateSet + } +) + +// SetName sets the "name" field. +func (u *AgentRuleUpsert) SetName(v string) *AgentRuleUpsert { + u.Set(agentrule.FieldName, v) + return u +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *AgentRuleUpsert) UpdateName() *AgentRuleUpsert { + u.SetExcluded(agentrule.FieldName) + return u +} + +// SetDescription sets the "description" field. +func (u *AgentRuleUpsert) SetDescription(v string) *AgentRuleUpsert { + u.Set(agentrule.FieldDescription, v) + return u +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *AgentRuleUpsert) UpdateDescription() *AgentRuleUpsert { + u.SetExcluded(agentrule.FieldDescription) + return u +} + +// ClearDescription clears the value of the "description" field. +func (u *AgentRuleUpsert) ClearDescription() *AgentRuleUpsert { + u.SetNull(agentrule.FieldDescription) + return u +} + +// SetScopeType sets the "scope_type" field. +func (u *AgentRuleUpsert) SetScopeType(v agentrule.ScopeType) *AgentRuleUpsert { + u.Set(agentrule.FieldScopeType, v) + return u +} + +// UpdateScopeType sets the "scope_type" field to the value that was provided on create. +func (u *AgentRuleUpsert) UpdateScopeType() *AgentRuleUpsert { + u.SetExcluded(agentrule.FieldScopeType) + return u +} + +// SetScopeID sets the "scope_id" field. +func (u *AgentRuleUpsert) SetScopeID(v string) *AgentRuleUpsert { + u.Set(agentrule.FieldScopeID, v) + return u +} + +// UpdateScopeID sets the "scope_id" field to the value that was provided on create. +func (u *AgentRuleUpsert) UpdateScopeID() *AgentRuleUpsert { + u.SetExcluded(agentrule.FieldScopeID) + return u +} + +// SetCreatedBy sets the "created_by" field. +func (u *AgentRuleUpsert) SetCreatedBy(v uuid.UUID) *AgentRuleUpsert { + u.Set(agentrule.FieldCreatedBy, v) + return u +} + +// UpdateCreatedBy sets the "created_by" field to the value that was provided on create. +func (u *AgentRuleUpsert) UpdateCreatedBy() *AgentRuleUpsert { + u.SetExcluded(agentrule.FieldCreatedBy) + return u +} + +// SetActiveVersionID sets the "active_version_id" field. +func (u *AgentRuleUpsert) SetActiveVersionID(v uuid.UUID) *AgentRuleUpsert { + u.Set(agentrule.FieldActiveVersionID, v) + return u +} + +// UpdateActiveVersionID sets the "active_version_id" field to the value that was provided on create. +func (u *AgentRuleUpsert) UpdateActiveVersionID() *AgentRuleUpsert { + u.SetExcluded(agentrule.FieldActiveVersionID) + return u +} + +// ClearActiveVersionID clears the value of the "active_version_id" field. +func (u *AgentRuleUpsert) ClearActiveVersionID() *AgentRuleUpsert { + u.SetNull(agentrule.FieldActiveVersionID) + return u +} + +// SetIsDeleted sets the "is_deleted" field. +func (u *AgentRuleUpsert) SetIsDeleted(v bool) *AgentRuleUpsert { + u.Set(agentrule.FieldIsDeleted, v) + return u +} + +// UpdateIsDeleted sets the "is_deleted" field to the value that was provided on create. +func (u *AgentRuleUpsert) UpdateIsDeleted() *AgentRuleUpsert { + u.SetExcluded(agentrule.FieldIsDeleted) + return u +} + +// SetCreatedAt sets the "created_at" field. +func (u *AgentRuleUpsert) SetCreatedAt(v time.Time) *AgentRuleUpsert { + u.Set(agentrule.FieldCreatedAt, v) + return u +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *AgentRuleUpsert) UpdateCreatedAt() *AgentRuleUpsert { + u.SetExcluded(agentrule.FieldCreatedAt) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *AgentRuleUpsert) SetUpdatedAt(v time.Time) *AgentRuleUpsert { + u.Set(agentrule.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *AgentRuleUpsert) UpdateUpdatedAt() *AgentRuleUpsert { + u.SetExcluded(agentrule.FieldUpdatedAt) + return u +} + +// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field. +// Using this option is equivalent to using: +// +// client.AgentRule.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(agentrule.FieldID) +// }), +// ). +// Exec(ctx) +func (u *AgentRuleUpsertOne) UpdateNewValues() *AgentRuleUpsertOne { + 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(agentrule.FieldID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.AgentRule.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *AgentRuleUpsertOne) Ignore() *AgentRuleUpsertOne { + 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 *AgentRuleUpsertOne) DoNothing() *AgentRuleUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the AgentRuleCreate.OnConflict +// documentation for more info. +func (u *AgentRuleUpsertOne) Update(set func(*AgentRuleUpsert)) *AgentRuleUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&AgentRuleUpsert{UpdateSet: update}) + })) + return u +} + +// SetName sets the "name" field. +func (u *AgentRuleUpsertOne) SetName(v string) *AgentRuleUpsertOne { + return u.Update(func(s *AgentRuleUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *AgentRuleUpsertOne) UpdateName() *AgentRuleUpsertOne { + return u.Update(func(s *AgentRuleUpsert) { + s.UpdateName() + }) +} + +// SetDescription sets the "description" field. +func (u *AgentRuleUpsertOne) SetDescription(v string) *AgentRuleUpsertOne { + return u.Update(func(s *AgentRuleUpsert) { + s.SetDescription(v) + }) +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *AgentRuleUpsertOne) UpdateDescription() *AgentRuleUpsertOne { + return u.Update(func(s *AgentRuleUpsert) { + s.UpdateDescription() + }) +} + +// ClearDescription clears the value of the "description" field. +func (u *AgentRuleUpsertOne) ClearDescription() *AgentRuleUpsertOne { + return u.Update(func(s *AgentRuleUpsert) { + s.ClearDescription() + }) +} + +// SetScopeType sets the "scope_type" field. +func (u *AgentRuleUpsertOne) SetScopeType(v agentrule.ScopeType) *AgentRuleUpsertOne { + return u.Update(func(s *AgentRuleUpsert) { + s.SetScopeType(v) + }) +} + +// UpdateScopeType sets the "scope_type" field to the value that was provided on create. +func (u *AgentRuleUpsertOne) UpdateScopeType() *AgentRuleUpsertOne { + return u.Update(func(s *AgentRuleUpsert) { + s.UpdateScopeType() + }) +} + +// SetScopeID sets the "scope_id" field. +func (u *AgentRuleUpsertOne) SetScopeID(v string) *AgentRuleUpsertOne { + return u.Update(func(s *AgentRuleUpsert) { + s.SetScopeID(v) + }) +} + +// UpdateScopeID sets the "scope_id" field to the value that was provided on create. +func (u *AgentRuleUpsertOne) UpdateScopeID() *AgentRuleUpsertOne { + return u.Update(func(s *AgentRuleUpsert) { + s.UpdateScopeID() + }) +} + +// SetCreatedBy sets the "created_by" field. +func (u *AgentRuleUpsertOne) SetCreatedBy(v uuid.UUID) *AgentRuleUpsertOne { + return u.Update(func(s *AgentRuleUpsert) { + s.SetCreatedBy(v) + }) +} + +// UpdateCreatedBy sets the "created_by" field to the value that was provided on create. +func (u *AgentRuleUpsertOne) UpdateCreatedBy() *AgentRuleUpsertOne { + return u.Update(func(s *AgentRuleUpsert) { + s.UpdateCreatedBy() + }) +} + +// SetActiveVersionID sets the "active_version_id" field. +func (u *AgentRuleUpsertOne) SetActiveVersionID(v uuid.UUID) *AgentRuleUpsertOne { + return u.Update(func(s *AgentRuleUpsert) { + s.SetActiveVersionID(v) + }) +} + +// UpdateActiveVersionID sets the "active_version_id" field to the value that was provided on create. +func (u *AgentRuleUpsertOne) UpdateActiveVersionID() *AgentRuleUpsertOne { + return u.Update(func(s *AgentRuleUpsert) { + s.UpdateActiveVersionID() + }) +} + +// ClearActiveVersionID clears the value of the "active_version_id" field. +func (u *AgentRuleUpsertOne) ClearActiveVersionID() *AgentRuleUpsertOne { + return u.Update(func(s *AgentRuleUpsert) { + s.ClearActiveVersionID() + }) +} + +// SetIsDeleted sets the "is_deleted" field. +func (u *AgentRuleUpsertOne) SetIsDeleted(v bool) *AgentRuleUpsertOne { + return u.Update(func(s *AgentRuleUpsert) { + s.SetIsDeleted(v) + }) +} + +// UpdateIsDeleted sets the "is_deleted" field to the value that was provided on create. +func (u *AgentRuleUpsertOne) UpdateIsDeleted() *AgentRuleUpsertOne { + return u.Update(func(s *AgentRuleUpsert) { + s.UpdateIsDeleted() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *AgentRuleUpsertOne) SetCreatedAt(v time.Time) *AgentRuleUpsertOne { + return u.Update(func(s *AgentRuleUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *AgentRuleUpsertOne) UpdateCreatedAt() *AgentRuleUpsertOne { + return u.Update(func(s *AgentRuleUpsert) { + s.UpdateCreatedAt() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *AgentRuleUpsertOne) SetUpdatedAt(v time.Time) *AgentRuleUpsertOne { + return u.Update(func(s *AgentRuleUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *AgentRuleUpsertOne) UpdateUpdatedAt() *AgentRuleUpsertOne { + return u.Update(func(s *AgentRuleUpsert) { + s.UpdateUpdatedAt() + }) +} + +// Exec executes the query. +func (u *AgentRuleUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for AgentRuleCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *AgentRuleUpsertOne) 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 *AgentRuleUpsertOne) 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: AgentRuleUpsertOne.ID is not supported by MySQL driver. Use AgentRuleUpsertOne.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 *AgentRuleUpsertOne) IDX(ctx context.Context) uuid.UUID { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// AgentRuleCreateBulk is the builder for creating many AgentRule entities in bulk. +type AgentRuleCreateBulk struct { + config + err error + builders []*AgentRuleCreate + conflict []sql.ConflictOption +} + +// Save creates the AgentRule entities in the database. +func (_c *AgentRuleCreateBulk) Save(ctx context.Context) ([]*AgentRule, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*AgentRule, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*AgentRuleMutation) + 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, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = _c.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.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, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *AgentRuleCreateBulk) SaveX(ctx context.Context) []*AgentRule { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *AgentRuleCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *AgentRuleCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.AgentRule.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.AgentRuleUpsert) { +// SetName(v+v). +// }). +// Exec(ctx) +func (_c *AgentRuleCreateBulk) OnConflict(opts ...sql.ConflictOption) *AgentRuleUpsertBulk { + _c.conflict = opts + return &AgentRuleUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.AgentRule.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *AgentRuleCreateBulk) OnConflictColumns(columns ...string) *AgentRuleUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &AgentRuleUpsertBulk{ + create: _c, + } +} + +// AgentRuleUpsertBulk is the builder for "upsert"-ing +// a bulk of AgentRule nodes. +type AgentRuleUpsertBulk struct { + create *AgentRuleCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.AgentRule.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(agentrule.FieldID) +// }), +// ). +// Exec(ctx) +func (u *AgentRuleUpsertBulk) UpdateNewValues() *AgentRuleUpsertBulk { + 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(agentrule.FieldID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.AgentRule.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *AgentRuleUpsertBulk) Ignore() *AgentRuleUpsertBulk { + 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 *AgentRuleUpsertBulk) DoNothing() *AgentRuleUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the AgentRuleCreateBulk.OnConflict +// documentation for more info. +func (u *AgentRuleUpsertBulk) Update(set func(*AgentRuleUpsert)) *AgentRuleUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&AgentRuleUpsert{UpdateSet: update}) + })) + return u +} + +// SetName sets the "name" field. +func (u *AgentRuleUpsertBulk) SetName(v string) *AgentRuleUpsertBulk { + return u.Update(func(s *AgentRuleUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *AgentRuleUpsertBulk) UpdateName() *AgentRuleUpsertBulk { + return u.Update(func(s *AgentRuleUpsert) { + s.UpdateName() + }) +} + +// SetDescription sets the "description" field. +func (u *AgentRuleUpsertBulk) SetDescription(v string) *AgentRuleUpsertBulk { + return u.Update(func(s *AgentRuleUpsert) { + s.SetDescription(v) + }) +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *AgentRuleUpsertBulk) UpdateDescription() *AgentRuleUpsertBulk { + return u.Update(func(s *AgentRuleUpsert) { + s.UpdateDescription() + }) +} + +// ClearDescription clears the value of the "description" field. +func (u *AgentRuleUpsertBulk) ClearDescription() *AgentRuleUpsertBulk { + return u.Update(func(s *AgentRuleUpsert) { + s.ClearDescription() + }) +} + +// SetScopeType sets the "scope_type" field. +func (u *AgentRuleUpsertBulk) SetScopeType(v agentrule.ScopeType) *AgentRuleUpsertBulk { + return u.Update(func(s *AgentRuleUpsert) { + s.SetScopeType(v) + }) +} + +// UpdateScopeType sets the "scope_type" field to the value that was provided on create. +func (u *AgentRuleUpsertBulk) UpdateScopeType() *AgentRuleUpsertBulk { + return u.Update(func(s *AgentRuleUpsert) { + s.UpdateScopeType() + }) +} + +// SetScopeID sets the "scope_id" field. +func (u *AgentRuleUpsertBulk) SetScopeID(v string) *AgentRuleUpsertBulk { + return u.Update(func(s *AgentRuleUpsert) { + s.SetScopeID(v) + }) +} + +// UpdateScopeID sets the "scope_id" field to the value that was provided on create. +func (u *AgentRuleUpsertBulk) UpdateScopeID() *AgentRuleUpsertBulk { + return u.Update(func(s *AgentRuleUpsert) { + s.UpdateScopeID() + }) +} + +// SetCreatedBy sets the "created_by" field. +func (u *AgentRuleUpsertBulk) SetCreatedBy(v uuid.UUID) *AgentRuleUpsertBulk { + return u.Update(func(s *AgentRuleUpsert) { + s.SetCreatedBy(v) + }) +} + +// UpdateCreatedBy sets the "created_by" field to the value that was provided on create. +func (u *AgentRuleUpsertBulk) UpdateCreatedBy() *AgentRuleUpsertBulk { + return u.Update(func(s *AgentRuleUpsert) { + s.UpdateCreatedBy() + }) +} + +// SetActiveVersionID sets the "active_version_id" field. +func (u *AgentRuleUpsertBulk) SetActiveVersionID(v uuid.UUID) *AgentRuleUpsertBulk { + return u.Update(func(s *AgentRuleUpsert) { + s.SetActiveVersionID(v) + }) +} + +// UpdateActiveVersionID sets the "active_version_id" field to the value that was provided on create. +func (u *AgentRuleUpsertBulk) UpdateActiveVersionID() *AgentRuleUpsertBulk { + return u.Update(func(s *AgentRuleUpsert) { + s.UpdateActiveVersionID() + }) +} + +// ClearActiveVersionID clears the value of the "active_version_id" field. +func (u *AgentRuleUpsertBulk) ClearActiveVersionID() *AgentRuleUpsertBulk { + return u.Update(func(s *AgentRuleUpsert) { + s.ClearActiveVersionID() + }) +} + +// SetIsDeleted sets the "is_deleted" field. +func (u *AgentRuleUpsertBulk) SetIsDeleted(v bool) *AgentRuleUpsertBulk { + return u.Update(func(s *AgentRuleUpsert) { + s.SetIsDeleted(v) + }) +} + +// UpdateIsDeleted sets the "is_deleted" field to the value that was provided on create. +func (u *AgentRuleUpsertBulk) UpdateIsDeleted() *AgentRuleUpsertBulk { + return u.Update(func(s *AgentRuleUpsert) { + s.UpdateIsDeleted() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *AgentRuleUpsertBulk) SetCreatedAt(v time.Time) *AgentRuleUpsertBulk { + return u.Update(func(s *AgentRuleUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *AgentRuleUpsertBulk) UpdateCreatedAt() *AgentRuleUpsertBulk { + return u.Update(func(s *AgentRuleUpsert) { + s.UpdateCreatedAt() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *AgentRuleUpsertBulk) SetUpdatedAt(v time.Time) *AgentRuleUpsertBulk { + return u.Update(func(s *AgentRuleUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *AgentRuleUpsertBulk) UpdateUpdatedAt() *AgentRuleUpsertBulk { + return u.Update(func(s *AgentRuleUpsert) { + s.UpdateUpdatedAt() + }) +} + +// Exec executes the query. +func (u *AgentRuleUpsertBulk) 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 AgentRuleCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for AgentRuleCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *AgentRuleUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/agentrule_delete.go b/backend/db/agentrule_delete.go new file mode 100644 index 00000000..8401bce9 --- /dev/null +++ b/backend/db/agentrule_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/agentrule" + "github.com/chaitin/MonkeyCode/backend/db/predicate" +) + +// AgentRuleDelete is the builder for deleting a AgentRule entity. +type AgentRuleDelete struct { + config + hooks []Hook + mutation *AgentRuleMutation +} + +// Where appends a list predicates to the AgentRuleDelete builder. +func (_d *AgentRuleDelete) Where(ps ...predicate.AgentRule) *AgentRuleDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *AgentRuleDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *AgentRuleDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *AgentRuleDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(agentrule.Table, sqlgraph.NewFieldSpec(agentrule.FieldID, field.TypeUUID)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// AgentRuleDeleteOne is the builder for deleting a single AgentRule entity. +type AgentRuleDeleteOne struct { + _d *AgentRuleDelete +} + +// Where appends a list predicates to the AgentRuleDelete builder. +func (_d *AgentRuleDeleteOne) Where(ps ...predicate.AgentRule) *AgentRuleDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *AgentRuleDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{agentrule.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *AgentRuleDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/agentrule_query.go b/backend/db/agentrule_query.go new file mode 100644 index 00000000..02535958 --- /dev/null +++ b/backend/db/agentrule_query.go @@ -0,0 +1,657 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "database/sql/driver" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/agentrule" + "github.com/chaitin/MonkeyCode/backend/db/agentruleversion" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/google/uuid" +) + +// AgentRuleQuery is the builder for querying AgentRule entities. +type AgentRuleQuery struct { + config + ctx *QueryContext + order []agentrule.OrderOption + inters []Interceptor + predicates []predicate.AgentRule + withVersions *AgentRuleVersionQuery + 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 AgentRuleQuery builder. +func (_q *AgentRuleQuery) Where(ps ...predicate.AgentRule) *AgentRuleQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *AgentRuleQuery) Limit(limit int) *AgentRuleQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *AgentRuleQuery) Offset(offset int) *AgentRuleQuery { + _q.ctx.Offset = &offset + return _q +} + +// 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 (_q *AgentRuleQuery) Unique(unique bool) *AgentRuleQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *AgentRuleQuery) Order(o ...agentrule.OrderOption) *AgentRuleQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryVersions chains the current query on the "versions" edge. +func (_q *AgentRuleQuery) QueryVersions() *AgentRuleVersionQuery { + query := (&AgentRuleVersionClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(agentrule.Table, agentrule.FieldID, selector), + sqlgraph.To(agentruleversion.Table, agentruleversion.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, agentrule.VersionsTable, agentrule.VersionsColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first AgentRule entity from the query. +// Returns a *NotFoundError when no AgentRule was found. +func (_q *AgentRuleQuery) First(ctx context.Context) (*AgentRule, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{agentrule.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *AgentRuleQuery) FirstX(ctx context.Context) *AgentRule { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first AgentRule ID from the query. +// Returns a *NotFoundError when no AgentRule ID was found. +func (_q *AgentRuleQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{agentrule.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *AgentRuleQuery) FirstIDX(ctx context.Context) uuid.UUID { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single AgentRule entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one AgentRule entity is found. +// Returns a *NotFoundError when no AgentRule entities are found. +func (_q *AgentRuleQuery) Only(ctx context.Context) (*AgentRule, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{agentrule.Label} + default: + return nil, &NotSingularError{agentrule.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *AgentRuleQuery) OnlyX(ctx context.Context) *AgentRule { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only AgentRule ID in the query. +// Returns a *NotSingularError when more than one AgentRule ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *AgentRuleQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{agentrule.Label} + default: + err = &NotSingularError{agentrule.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *AgentRuleQuery) OnlyIDX(ctx context.Context) uuid.UUID { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of AgentRules. +func (_q *AgentRuleQuery) All(ctx context.Context) ([]*AgentRule, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*AgentRule, *AgentRuleQuery]() + return withInterceptors[[]*AgentRule](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *AgentRuleQuery) AllX(ctx context.Context) []*AgentRule { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of AgentRule IDs. +func (_q *AgentRuleQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(agentrule.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *AgentRuleQuery) IDsX(ctx context.Context) []uuid.UUID { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *AgentRuleQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*AgentRuleQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *AgentRuleQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *AgentRuleQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.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 (_q *AgentRuleQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the AgentRuleQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *AgentRuleQuery) Clone() *AgentRuleQuery { + if _q == nil { + return nil + } + return &AgentRuleQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]agentrule.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.AgentRule{}, _q.predicates...), + withVersions: _q.withVersions.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + modifiers: append([]func(*sql.Selector){}, _q.modifiers...), + } +} + +// WithVersions tells the query-builder to eager-load the nodes that are connected to +// the "versions" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *AgentRuleQuery) WithVersions(opts ...func(*AgentRuleVersionQuery)) *AgentRuleQuery { + query := (&AgentRuleVersionClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withVersions = query + return _q +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// Name string `json:"name,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.AgentRule.Query(). +// GroupBy(agentrule.FieldName). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *AgentRuleQuery) GroupBy(field string, fields ...string) *AgentRuleGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &AgentRuleGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = agentrule.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// Name string `json:"name,omitempty"` +// } +// +// client.AgentRule.Query(). +// Select(agentrule.FieldName). +// Scan(ctx, &v) +func (_q *AgentRuleQuery) Select(fields ...string) *AgentRuleSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &AgentRuleSelect{AgentRuleQuery: _q} + sbuild.label = agentrule.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a AgentRuleSelect configured with the given aggregations. +func (_q *AgentRuleQuery) Aggregate(fns ...AggregateFunc) *AgentRuleSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *AgentRuleQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.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, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !agentrule.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *AgentRuleQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*AgentRule, error) { + var ( + nodes = []*AgentRule{} + _spec = _q.querySpec() + loadedTypes = [1]bool{ + _q.withVersions != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*AgentRule).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &AgentRule{config: _q.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := _q.withVersions; query != nil { + if err := _q.loadVersions(ctx, query, nodes, + func(n *AgentRule) { n.Edges.Versions = []*AgentRuleVersion{} }, + func(n *AgentRule, e *AgentRuleVersion) { n.Edges.Versions = append(n.Edges.Versions, e) }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *AgentRuleQuery) loadVersions(ctx context.Context, query *AgentRuleVersionQuery, nodes []*AgentRule, init func(*AgentRule), assign func(*AgentRule, *AgentRuleVersion)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[uuid.UUID]*AgentRule) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) + } + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(agentruleversion.FieldRuleID) + } + query.Where(predicate.AgentRuleVersion(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(agentrule.VersionsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.RuleID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "rule_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} + +func (_q *AgentRuleQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *AgentRuleQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(agentrule.Table, agentrule.Columns, sqlgraph.NewFieldSpec(agentrule.FieldID, field.TypeUUID)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, agentrule.FieldID) + for i := range fields { + if fields[i] != agentrule.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *AgentRuleQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(agentrule.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = agentrule.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, m := range _q.modifiers { + m(selector) + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.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 := _q.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 (_q *AgentRuleQuery) ForUpdate(opts ...sql.LockOption) *AgentRuleQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForUpdate(opts...) + }) + return _q +} + +// 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 (_q *AgentRuleQuery) ForShare(opts ...sql.LockOption) *AgentRuleQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (_q *AgentRuleQuery) Modify(modifiers ...func(s *sql.Selector)) *AgentRuleSelect { + _q.modifiers = append(_q.modifiers, modifiers...) + return _q.Select() +} + +// AgentRuleGroupBy is the group-by builder for AgentRule entities. +type AgentRuleGroupBy struct { + selector + build *AgentRuleQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *AgentRuleGroupBy) Aggregate(fns ...AggregateFunc) *AgentRuleGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *AgentRuleGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*AgentRuleQuery, *AgentRuleGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *AgentRuleGroupBy) sqlScan(ctx context.Context, root *AgentRuleQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// AgentRuleSelect is the builder for selecting fields of AgentRule entities. +type AgentRuleSelect struct { + *AgentRuleQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *AgentRuleSelect) Aggregate(fns ...AggregateFunc) *AgentRuleSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *AgentRuleSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*AgentRuleQuery, *AgentRuleSelect](ctx, _s.AgentRuleQuery, _s, _s.inters, v) +} + +func (_s *AgentRuleSelect) sqlScan(ctx context.Context, root *AgentRuleQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.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 := _s.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 (_s *AgentRuleSelect) Modify(modifiers ...func(s *sql.Selector)) *AgentRuleSelect { + _s.modifiers = append(_s.modifiers, modifiers...) + return _s +} diff --git a/backend/db/agentrule_update.go b/backend/db/agentrule_update.go new file mode 100644 index 00000000..9ed5d1aa --- /dev/null +++ b/backend/db/agentrule_update.go @@ -0,0 +1,736 @@ +// 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/agentrule" + "github.com/chaitin/MonkeyCode/backend/db/agentruleversion" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/google/uuid" +) + +// AgentRuleUpdate is the builder for updating AgentRule entities. +type AgentRuleUpdate struct { + config + hooks []Hook + mutation *AgentRuleMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the AgentRuleUpdate builder. +func (_u *AgentRuleUpdate) Where(ps ...predicate.AgentRule) *AgentRuleUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetName sets the "name" field. +func (_u *AgentRuleUpdate) SetName(v string) *AgentRuleUpdate { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *AgentRuleUpdate) SetNillableName(v *string) *AgentRuleUpdate { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetDescription sets the "description" field. +func (_u *AgentRuleUpdate) SetDescription(v string) *AgentRuleUpdate { + _u.mutation.SetDescription(v) + return _u +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_u *AgentRuleUpdate) SetNillableDescription(v *string) *AgentRuleUpdate { + if v != nil { + _u.SetDescription(*v) + } + return _u +} + +// ClearDescription clears the value of the "description" field. +func (_u *AgentRuleUpdate) ClearDescription() *AgentRuleUpdate { + _u.mutation.ClearDescription() + return _u +} + +// SetScopeType sets the "scope_type" field. +func (_u *AgentRuleUpdate) SetScopeType(v agentrule.ScopeType) *AgentRuleUpdate { + _u.mutation.SetScopeType(v) + return _u +} + +// SetNillableScopeType sets the "scope_type" field if the given value is not nil. +func (_u *AgentRuleUpdate) SetNillableScopeType(v *agentrule.ScopeType) *AgentRuleUpdate { + if v != nil { + _u.SetScopeType(*v) + } + return _u +} + +// SetScopeID sets the "scope_id" field. +func (_u *AgentRuleUpdate) SetScopeID(v string) *AgentRuleUpdate { + _u.mutation.SetScopeID(v) + return _u +} + +// SetNillableScopeID sets the "scope_id" field if the given value is not nil. +func (_u *AgentRuleUpdate) SetNillableScopeID(v *string) *AgentRuleUpdate { + if v != nil { + _u.SetScopeID(*v) + } + return _u +} + +// SetCreatedBy sets the "created_by" field. +func (_u *AgentRuleUpdate) SetCreatedBy(v uuid.UUID) *AgentRuleUpdate { + _u.mutation.SetCreatedBy(v) + return _u +} + +// SetNillableCreatedBy sets the "created_by" field if the given value is not nil. +func (_u *AgentRuleUpdate) SetNillableCreatedBy(v *uuid.UUID) *AgentRuleUpdate { + if v != nil { + _u.SetCreatedBy(*v) + } + return _u +} + +// SetActiveVersionID sets the "active_version_id" field. +func (_u *AgentRuleUpdate) SetActiveVersionID(v uuid.UUID) *AgentRuleUpdate { + _u.mutation.SetActiveVersionID(v) + return _u +} + +// SetNillableActiveVersionID sets the "active_version_id" field if the given value is not nil. +func (_u *AgentRuleUpdate) SetNillableActiveVersionID(v *uuid.UUID) *AgentRuleUpdate { + if v != nil { + _u.SetActiveVersionID(*v) + } + return _u +} + +// ClearActiveVersionID clears the value of the "active_version_id" field. +func (_u *AgentRuleUpdate) ClearActiveVersionID() *AgentRuleUpdate { + _u.mutation.ClearActiveVersionID() + return _u +} + +// SetIsDeleted sets the "is_deleted" field. +func (_u *AgentRuleUpdate) SetIsDeleted(v bool) *AgentRuleUpdate { + _u.mutation.SetIsDeleted(v) + return _u +} + +// SetNillableIsDeleted sets the "is_deleted" field if the given value is not nil. +func (_u *AgentRuleUpdate) SetNillableIsDeleted(v *bool) *AgentRuleUpdate { + if v != nil { + _u.SetIsDeleted(*v) + } + return _u +} + +// SetCreatedAt sets the "created_at" field. +func (_u *AgentRuleUpdate) SetCreatedAt(v time.Time) *AgentRuleUpdate { + _u.mutation.SetCreatedAt(v) + return _u +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_u *AgentRuleUpdate) SetNillableCreatedAt(v *time.Time) *AgentRuleUpdate { + if v != nil { + _u.SetCreatedAt(*v) + } + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *AgentRuleUpdate) SetUpdatedAt(v time.Time) *AgentRuleUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// AddVersionIDs adds the "versions" edge to the AgentRuleVersion entity by IDs. +func (_u *AgentRuleUpdate) AddVersionIDs(ids ...uuid.UUID) *AgentRuleUpdate { + _u.mutation.AddVersionIDs(ids...) + return _u +} + +// AddVersions adds the "versions" edges to the AgentRuleVersion entity. +func (_u *AgentRuleUpdate) AddVersions(v ...*AgentRuleVersion) *AgentRuleUpdate { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddVersionIDs(ids...) +} + +// Mutation returns the AgentRuleMutation object of the builder. +func (_u *AgentRuleUpdate) Mutation() *AgentRuleMutation { + return _u.mutation +} + +// ClearVersions clears all "versions" edges to the AgentRuleVersion entity. +func (_u *AgentRuleUpdate) ClearVersions() *AgentRuleUpdate { + _u.mutation.ClearVersions() + return _u +} + +// RemoveVersionIDs removes the "versions" edge to AgentRuleVersion entities by IDs. +func (_u *AgentRuleUpdate) RemoveVersionIDs(ids ...uuid.UUID) *AgentRuleUpdate { + _u.mutation.RemoveVersionIDs(ids...) + return _u +} + +// RemoveVersions removes "versions" edges to AgentRuleVersion entities. +func (_u *AgentRuleUpdate) RemoveVersions(v ...*AgentRuleVersion) *AgentRuleUpdate { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveVersionIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *AgentRuleUpdate) Save(ctx context.Context) (int, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *AgentRuleUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *AgentRuleUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *AgentRuleUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_u *AgentRuleUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := agentrule.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *AgentRuleUpdate) check() error { + if v, ok := _u.mutation.Name(); ok { + if err := agentrule.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "AgentRule.name": %w`, err)} + } + } + if v, ok := _u.mutation.ScopeType(); ok { + if err := agentrule.ScopeTypeValidator(v); err != nil { + return &ValidationError{Name: "scope_type", err: fmt.Errorf(`db: validator failed for field "AgentRule.scope_type": %w`, err)} + } + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (_u *AgentRuleUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *AgentRuleUpdate { + _u.modifiers = append(_u.modifiers, modifiers...) + return _u +} + +func (_u *AgentRuleUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(agentrule.Table, agentrule.Columns, sqlgraph.NewFieldSpec(agentrule.FieldID, field.TypeUUID)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(agentrule.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Description(); ok { + _spec.SetField(agentrule.FieldDescription, field.TypeString, value) + } + if _u.mutation.DescriptionCleared() { + _spec.ClearField(agentrule.FieldDescription, field.TypeString) + } + if value, ok := _u.mutation.ScopeType(); ok { + _spec.SetField(agentrule.FieldScopeType, field.TypeEnum, value) + } + if value, ok := _u.mutation.ScopeID(); ok { + _spec.SetField(agentrule.FieldScopeID, field.TypeString, value) + } + if value, ok := _u.mutation.CreatedBy(); ok { + _spec.SetField(agentrule.FieldCreatedBy, field.TypeUUID, value) + } + if value, ok := _u.mutation.ActiveVersionID(); ok { + _spec.SetField(agentrule.FieldActiveVersionID, field.TypeUUID, value) + } + if _u.mutation.ActiveVersionIDCleared() { + _spec.ClearField(agentrule.FieldActiveVersionID, field.TypeUUID) + } + if value, ok := _u.mutation.IsDeleted(); ok { + _spec.SetField(agentrule.FieldIsDeleted, field.TypeBool, value) + } + if value, ok := _u.mutation.CreatedAt(); ok { + _spec.SetField(agentrule.FieldCreatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(agentrule.FieldUpdatedAt, field.TypeTime, value) + } + if _u.mutation.VersionsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agentrule.VersionsTable, + Columns: []string{agentrule.VersionsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentruleversion.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedVersionsIDs(); len(nodes) > 0 && !_u.mutation.VersionsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agentrule.VersionsTable, + Columns: []string{agentrule.VersionsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentruleversion.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.VersionsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agentrule.VersionsTable, + Columns: []string{agentrule.VersionsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentruleversion.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(_u.modifiers...) + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{agentrule.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// AgentRuleUpdateOne is the builder for updating a single AgentRule entity. +type AgentRuleUpdateOne struct { + config + fields []string + hooks []Hook + mutation *AgentRuleMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetName sets the "name" field. +func (_u *AgentRuleUpdateOne) SetName(v string) *AgentRuleUpdateOne { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *AgentRuleUpdateOne) SetNillableName(v *string) *AgentRuleUpdateOne { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetDescription sets the "description" field. +func (_u *AgentRuleUpdateOne) SetDescription(v string) *AgentRuleUpdateOne { + _u.mutation.SetDescription(v) + return _u +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_u *AgentRuleUpdateOne) SetNillableDescription(v *string) *AgentRuleUpdateOne { + if v != nil { + _u.SetDescription(*v) + } + return _u +} + +// ClearDescription clears the value of the "description" field. +func (_u *AgentRuleUpdateOne) ClearDescription() *AgentRuleUpdateOne { + _u.mutation.ClearDescription() + return _u +} + +// SetScopeType sets the "scope_type" field. +func (_u *AgentRuleUpdateOne) SetScopeType(v agentrule.ScopeType) *AgentRuleUpdateOne { + _u.mutation.SetScopeType(v) + return _u +} + +// SetNillableScopeType sets the "scope_type" field if the given value is not nil. +func (_u *AgentRuleUpdateOne) SetNillableScopeType(v *agentrule.ScopeType) *AgentRuleUpdateOne { + if v != nil { + _u.SetScopeType(*v) + } + return _u +} + +// SetScopeID sets the "scope_id" field. +func (_u *AgentRuleUpdateOne) SetScopeID(v string) *AgentRuleUpdateOne { + _u.mutation.SetScopeID(v) + return _u +} + +// SetNillableScopeID sets the "scope_id" field if the given value is not nil. +func (_u *AgentRuleUpdateOne) SetNillableScopeID(v *string) *AgentRuleUpdateOne { + if v != nil { + _u.SetScopeID(*v) + } + return _u +} + +// SetCreatedBy sets the "created_by" field. +func (_u *AgentRuleUpdateOne) SetCreatedBy(v uuid.UUID) *AgentRuleUpdateOne { + _u.mutation.SetCreatedBy(v) + return _u +} + +// SetNillableCreatedBy sets the "created_by" field if the given value is not nil. +func (_u *AgentRuleUpdateOne) SetNillableCreatedBy(v *uuid.UUID) *AgentRuleUpdateOne { + if v != nil { + _u.SetCreatedBy(*v) + } + return _u +} + +// SetActiveVersionID sets the "active_version_id" field. +func (_u *AgentRuleUpdateOne) SetActiveVersionID(v uuid.UUID) *AgentRuleUpdateOne { + _u.mutation.SetActiveVersionID(v) + return _u +} + +// SetNillableActiveVersionID sets the "active_version_id" field if the given value is not nil. +func (_u *AgentRuleUpdateOne) SetNillableActiveVersionID(v *uuid.UUID) *AgentRuleUpdateOne { + if v != nil { + _u.SetActiveVersionID(*v) + } + return _u +} + +// ClearActiveVersionID clears the value of the "active_version_id" field. +func (_u *AgentRuleUpdateOne) ClearActiveVersionID() *AgentRuleUpdateOne { + _u.mutation.ClearActiveVersionID() + return _u +} + +// SetIsDeleted sets the "is_deleted" field. +func (_u *AgentRuleUpdateOne) SetIsDeleted(v bool) *AgentRuleUpdateOne { + _u.mutation.SetIsDeleted(v) + return _u +} + +// SetNillableIsDeleted sets the "is_deleted" field if the given value is not nil. +func (_u *AgentRuleUpdateOne) SetNillableIsDeleted(v *bool) *AgentRuleUpdateOne { + if v != nil { + _u.SetIsDeleted(*v) + } + return _u +} + +// SetCreatedAt sets the "created_at" field. +func (_u *AgentRuleUpdateOne) SetCreatedAt(v time.Time) *AgentRuleUpdateOne { + _u.mutation.SetCreatedAt(v) + return _u +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_u *AgentRuleUpdateOne) SetNillableCreatedAt(v *time.Time) *AgentRuleUpdateOne { + if v != nil { + _u.SetCreatedAt(*v) + } + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *AgentRuleUpdateOne) SetUpdatedAt(v time.Time) *AgentRuleUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// AddVersionIDs adds the "versions" edge to the AgentRuleVersion entity by IDs. +func (_u *AgentRuleUpdateOne) AddVersionIDs(ids ...uuid.UUID) *AgentRuleUpdateOne { + _u.mutation.AddVersionIDs(ids...) + return _u +} + +// AddVersions adds the "versions" edges to the AgentRuleVersion entity. +func (_u *AgentRuleUpdateOne) AddVersions(v ...*AgentRuleVersion) *AgentRuleUpdateOne { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddVersionIDs(ids...) +} + +// Mutation returns the AgentRuleMutation object of the builder. +func (_u *AgentRuleUpdateOne) Mutation() *AgentRuleMutation { + return _u.mutation +} + +// ClearVersions clears all "versions" edges to the AgentRuleVersion entity. +func (_u *AgentRuleUpdateOne) ClearVersions() *AgentRuleUpdateOne { + _u.mutation.ClearVersions() + return _u +} + +// RemoveVersionIDs removes the "versions" edge to AgentRuleVersion entities by IDs. +func (_u *AgentRuleUpdateOne) RemoveVersionIDs(ids ...uuid.UUID) *AgentRuleUpdateOne { + _u.mutation.RemoveVersionIDs(ids...) + return _u +} + +// RemoveVersions removes "versions" edges to AgentRuleVersion entities. +func (_u *AgentRuleUpdateOne) RemoveVersions(v ...*AgentRuleVersion) *AgentRuleUpdateOne { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveVersionIDs(ids...) +} + +// Where appends a list predicates to the AgentRuleUpdate builder. +func (_u *AgentRuleUpdateOne) Where(ps ...predicate.AgentRule) *AgentRuleUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *AgentRuleUpdateOne) Select(field string, fields ...string) *AgentRuleUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated AgentRule entity. +func (_u *AgentRuleUpdateOne) Save(ctx context.Context) (*AgentRule, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *AgentRuleUpdateOne) SaveX(ctx context.Context) *AgentRule { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *AgentRuleUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *AgentRuleUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_u *AgentRuleUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := agentrule.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *AgentRuleUpdateOne) check() error { + if v, ok := _u.mutation.Name(); ok { + if err := agentrule.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "AgentRule.name": %w`, err)} + } + } + if v, ok := _u.mutation.ScopeType(); ok { + if err := agentrule.ScopeTypeValidator(v); err != nil { + return &ValidationError{Name: "scope_type", err: fmt.Errorf(`db: validator failed for field "AgentRule.scope_type": %w`, err)} + } + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (_u *AgentRuleUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *AgentRuleUpdateOne { + _u.modifiers = append(_u.modifiers, modifiers...) + return _u +} + +func (_u *AgentRuleUpdateOne) sqlSave(ctx context.Context) (_node *AgentRule, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(agentrule.Table, agentrule.Columns, sqlgraph.NewFieldSpec(agentrule.FieldID, field.TypeUUID)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "AgentRule.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, agentrule.FieldID) + for _, f := range fields { + if !agentrule.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != agentrule.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(agentrule.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Description(); ok { + _spec.SetField(agentrule.FieldDescription, field.TypeString, value) + } + if _u.mutation.DescriptionCleared() { + _spec.ClearField(agentrule.FieldDescription, field.TypeString) + } + if value, ok := _u.mutation.ScopeType(); ok { + _spec.SetField(agentrule.FieldScopeType, field.TypeEnum, value) + } + if value, ok := _u.mutation.ScopeID(); ok { + _spec.SetField(agentrule.FieldScopeID, field.TypeString, value) + } + if value, ok := _u.mutation.CreatedBy(); ok { + _spec.SetField(agentrule.FieldCreatedBy, field.TypeUUID, value) + } + if value, ok := _u.mutation.ActiveVersionID(); ok { + _spec.SetField(agentrule.FieldActiveVersionID, field.TypeUUID, value) + } + if _u.mutation.ActiveVersionIDCleared() { + _spec.ClearField(agentrule.FieldActiveVersionID, field.TypeUUID) + } + if value, ok := _u.mutation.IsDeleted(); ok { + _spec.SetField(agentrule.FieldIsDeleted, field.TypeBool, value) + } + if value, ok := _u.mutation.CreatedAt(); ok { + _spec.SetField(agentrule.FieldCreatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(agentrule.FieldUpdatedAt, field.TypeTime, value) + } + if _u.mutation.VersionsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agentrule.VersionsTable, + Columns: []string{agentrule.VersionsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentruleversion.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedVersionsIDs(); len(nodes) > 0 && !_u.mutation.VersionsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agentrule.VersionsTable, + Columns: []string{agentrule.VersionsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentruleversion.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.VersionsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agentrule.VersionsTable, + Columns: []string{agentrule.VersionsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentruleversion.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(_u.modifiers...) + _node = &AgentRule{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{agentrule.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/backend/db/agentruleversion.go b/backend/db/agentruleversion.go new file mode 100644 index 00000000..74fc5a4e --- /dev/null +++ b/backend/db/agentruleversion.go @@ -0,0 +1,169 @@ +// 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/agentrule" + "github.com/chaitin/MonkeyCode/backend/db/agentruleversion" + "github.com/google/uuid" +) + +// AgentRuleVersion is the model entity for the AgentRuleVersion schema. +type AgentRuleVersion struct { + config `json:"-"` + // ID of the ent. + ID uuid.UUID `json:"id,omitempty"` + // RuleID holds the value of the "rule_id" field. + RuleID uuid.UUID `json:"rule_id,omitempty"` + // Version holds the value of the "version" field. + Version string `json:"version,omitempty"` + // Content holds the value of the "content" field. + Content string `json:"content,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the AgentRuleVersionQuery when eager-loading is set. + Edges AgentRuleVersionEdges `json:"edges"` + selectValues sql.SelectValues +} + +// AgentRuleVersionEdges holds the relations/edges for other nodes in the graph. +type AgentRuleVersionEdges struct { + // Rule holds the value of the rule edge. + Rule *AgentRule `json:"rule,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// RuleOrErr returns the Rule value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e AgentRuleVersionEdges) RuleOrErr() (*AgentRule, error) { + if e.Rule != nil { + return e.Rule, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: agentrule.Label} + } + return nil, &NotLoadedError{edge: "rule"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*AgentRuleVersion) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case agentruleversion.FieldVersion, agentruleversion.FieldContent: + values[i] = new(sql.NullString) + case agentruleversion.FieldCreatedAt: + values[i] = new(sql.NullTime) + case agentruleversion.FieldID, agentruleversion.FieldRuleID: + 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 AgentRuleVersion fields. +func (_m *AgentRuleVersion) 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 agentruleversion.FieldID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value != nil { + _m.ID = *value + } + case agentruleversion.FieldRuleID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field rule_id", values[i]) + } else if value != nil { + _m.RuleID = *value + } + case agentruleversion.FieldVersion: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field version", values[i]) + } else if value.Valid { + _m.Version = value.String + } + case agentruleversion.FieldContent: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field content", values[i]) + } else if value.Valid { + _m.Content = value.String + } + case agentruleversion.FieldCreatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field created_at", values[i]) + } else if value.Valid { + _m.CreatedAt = value.Time + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the AgentRuleVersion. +// This includes values selected through modifiers, order, etc. +func (_m *AgentRuleVersion) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryRule queries the "rule" edge of the AgentRuleVersion entity. +func (_m *AgentRuleVersion) QueryRule() *AgentRuleQuery { + return NewAgentRuleVersionClient(_m.config).QueryRule(_m) +} + +// Update returns a builder for updating this AgentRuleVersion. +// Note that you need to call AgentRuleVersion.Unwrap() before calling this method if this AgentRuleVersion +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *AgentRuleVersion) Update() *AgentRuleVersionUpdateOne { + return NewAgentRuleVersionClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the AgentRuleVersion entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (_m *AgentRuleVersion) Unwrap() *AgentRuleVersion { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: AgentRuleVersion is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *AgentRuleVersion) String() string { + var builder strings.Builder + builder.WriteString("AgentRuleVersion(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("rule_id=") + builder.WriteString(fmt.Sprintf("%v", _m.RuleID)) + builder.WriteString(", ") + builder.WriteString("version=") + builder.WriteString(_m.Version) + builder.WriteString(", ") + builder.WriteString("content=") + builder.WriteString(_m.Content) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// AgentRuleVersions is a parsable slice of AgentRuleVersion. +type AgentRuleVersions []*AgentRuleVersion diff --git a/backend/db/agentruleversion/agentruleversion.go b/backend/db/agentruleversion/agentruleversion.go new file mode 100644 index 00000000..27005303 --- /dev/null +++ b/backend/db/agentruleversion/agentruleversion.go @@ -0,0 +1,107 @@ +// Code generated by ent, DO NOT EDIT. + +package agentruleversion + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/google/uuid" +) + +const ( + // Label holds the string label denoting the agentruleversion type in the database. + Label = "agent_rule_version" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldRuleID holds the string denoting the rule_id field in the database. + FieldRuleID = "rule_id" + // FieldVersion holds the string denoting the version field in the database. + FieldVersion = "version" + // FieldContent holds the string denoting the content field in the database. + FieldContent = "content" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // EdgeRule holds the string denoting the rule edge name in mutations. + EdgeRule = "rule" + // Table holds the table name of the agentruleversion in the database. + Table = "agent_rule_versions" + // RuleTable is the table that holds the rule relation/edge. + RuleTable = "agent_rule_versions" + // RuleInverseTable is the table name for the AgentRule entity. + // It exists in this package in order to avoid circular dependency with the "agentrule" package. + RuleInverseTable = "agent_rules" + // RuleColumn is the table column denoting the rule relation/edge. + RuleColumn = "rule_id" +) + +// Columns holds all SQL columns for agentruleversion fields. +var Columns = []string{ + FieldID, + FieldRuleID, + FieldVersion, + FieldContent, + 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 ( + // VersionValidator is a validator for the "version" field. It is called by the builders before save. + VersionValidator func(string) error + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() uuid.UUID +) + +// OrderOption defines the ordering options for the AgentRuleVersion 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() +} + +// ByRuleID orders the results by the rule_id field. +func ByRuleID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRuleID, opts...).ToFunc() +} + +// ByVersion orders the results by the version field. +func ByVersion(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldVersion, opts...).ToFunc() +} + +// ByContent orders the results by the content field. +func ByContent(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldContent, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// ByRuleField orders the results by rule field. +func ByRuleField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newRuleStep(), sql.OrderByField(field, opts...)) + } +} +func newRuleStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(RuleInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, RuleTable, RuleColumn), + ) +} diff --git a/backend/db/agentruleversion/where.go b/backend/db/agentruleversion/where.go new file mode 100644 index 00000000..47cb7814 --- /dev/null +++ b/backend/db/agentruleversion/where.go @@ -0,0 +1,305 @@ +// Code generated by ent, DO NOT EDIT. + +package agentruleversion + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/google/uuid" +) + +// ID filters vertices based on their ID field. +func ID(id uuid.UUID) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id uuid.UUID) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id uuid.UUID) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...uuid.UUID) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...uuid.UUID) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id uuid.UUID) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id uuid.UUID) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id uuid.UUID) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id uuid.UUID) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldLTE(FieldID, id)) +} + +// RuleID applies equality check predicate on the "rule_id" field. It's identical to RuleIDEQ. +func RuleID(v uuid.UUID) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldEQ(FieldRuleID, v)) +} + +// Version applies equality check predicate on the "version" field. It's identical to VersionEQ. +func Version(v string) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldEQ(FieldVersion, v)) +} + +// Content applies equality check predicate on the "content" field. It's identical to ContentEQ. +func Content(v string) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldEQ(FieldContent, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldEQ(FieldCreatedAt, v)) +} + +// RuleIDEQ applies the EQ predicate on the "rule_id" field. +func RuleIDEQ(v uuid.UUID) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldEQ(FieldRuleID, v)) +} + +// RuleIDNEQ applies the NEQ predicate on the "rule_id" field. +func RuleIDNEQ(v uuid.UUID) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldNEQ(FieldRuleID, v)) +} + +// RuleIDIn applies the In predicate on the "rule_id" field. +func RuleIDIn(vs ...uuid.UUID) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldIn(FieldRuleID, vs...)) +} + +// RuleIDNotIn applies the NotIn predicate on the "rule_id" field. +func RuleIDNotIn(vs ...uuid.UUID) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldNotIn(FieldRuleID, vs...)) +} + +// VersionEQ applies the EQ predicate on the "version" field. +func VersionEQ(v string) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldEQ(FieldVersion, v)) +} + +// VersionNEQ applies the NEQ predicate on the "version" field. +func VersionNEQ(v string) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldNEQ(FieldVersion, v)) +} + +// VersionIn applies the In predicate on the "version" field. +func VersionIn(vs ...string) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldIn(FieldVersion, vs...)) +} + +// VersionNotIn applies the NotIn predicate on the "version" field. +func VersionNotIn(vs ...string) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldNotIn(FieldVersion, vs...)) +} + +// VersionGT applies the GT predicate on the "version" field. +func VersionGT(v string) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldGT(FieldVersion, v)) +} + +// VersionGTE applies the GTE predicate on the "version" field. +func VersionGTE(v string) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldGTE(FieldVersion, v)) +} + +// VersionLT applies the LT predicate on the "version" field. +func VersionLT(v string) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldLT(FieldVersion, v)) +} + +// VersionLTE applies the LTE predicate on the "version" field. +func VersionLTE(v string) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldLTE(FieldVersion, v)) +} + +// VersionContains applies the Contains predicate on the "version" field. +func VersionContains(v string) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldContains(FieldVersion, v)) +} + +// VersionHasPrefix applies the HasPrefix predicate on the "version" field. +func VersionHasPrefix(v string) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldHasPrefix(FieldVersion, v)) +} + +// VersionHasSuffix applies the HasSuffix predicate on the "version" field. +func VersionHasSuffix(v string) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldHasSuffix(FieldVersion, v)) +} + +// VersionEqualFold applies the EqualFold predicate on the "version" field. +func VersionEqualFold(v string) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldEqualFold(FieldVersion, v)) +} + +// VersionContainsFold applies the ContainsFold predicate on the "version" field. +func VersionContainsFold(v string) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldContainsFold(FieldVersion, v)) +} + +// ContentEQ applies the EQ predicate on the "content" field. +func ContentEQ(v string) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldEQ(FieldContent, v)) +} + +// ContentNEQ applies the NEQ predicate on the "content" field. +func ContentNEQ(v string) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldNEQ(FieldContent, v)) +} + +// ContentIn applies the In predicate on the "content" field. +func ContentIn(vs ...string) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldIn(FieldContent, vs...)) +} + +// ContentNotIn applies the NotIn predicate on the "content" field. +func ContentNotIn(vs ...string) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldNotIn(FieldContent, vs...)) +} + +// ContentGT applies the GT predicate on the "content" field. +func ContentGT(v string) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldGT(FieldContent, v)) +} + +// ContentGTE applies the GTE predicate on the "content" field. +func ContentGTE(v string) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldGTE(FieldContent, v)) +} + +// ContentLT applies the LT predicate on the "content" field. +func ContentLT(v string) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldLT(FieldContent, v)) +} + +// ContentLTE applies the LTE predicate on the "content" field. +func ContentLTE(v string) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldLTE(FieldContent, v)) +} + +// ContentContains applies the Contains predicate on the "content" field. +func ContentContains(v string) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldContains(FieldContent, v)) +} + +// ContentHasPrefix applies the HasPrefix predicate on the "content" field. +func ContentHasPrefix(v string) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldHasPrefix(FieldContent, v)) +} + +// ContentHasSuffix applies the HasSuffix predicate on the "content" field. +func ContentHasSuffix(v string) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldHasSuffix(FieldContent, v)) +} + +// ContentEqualFold applies the EqualFold predicate on the "content" field. +func ContentEqualFold(v string) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldEqualFold(FieldContent, v)) +} + +// ContentContainsFold applies the ContainsFold predicate on the "content" field. +func ContentContainsFold(v string) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldContainsFold(FieldContent, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.FieldLTE(FieldCreatedAt, v)) +} + +// HasRule applies the HasEdge predicate on the "rule" edge. +func HasRule() predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, RuleTable, RuleColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasRuleWith applies the HasEdge predicate on the "rule" edge with a given conditions (other predicates). +func HasRuleWith(preds ...predicate.AgentRule) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(func(s *sql.Selector) { + step := newRuleStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.AgentRuleVersion) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.AgentRuleVersion) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.AgentRuleVersion) predicate.AgentRuleVersion { + return predicate.AgentRuleVersion(sql.NotPredicates(p)) +} diff --git a/backend/db/agentruleversion_create.go b/backend/db/agentruleversion_create.go new file mode 100644 index 00000000..cf065c6c --- /dev/null +++ b/backend/db/agentruleversion_create.go @@ -0,0 +1,707 @@ +// 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/agentrule" + "github.com/chaitin/MonkeyCode/backend/db/agentruleversion" + "github.com/google/uuid" +) + +// AgentRuleVersionCreate is the builder for creating a AgentRuleVersion entity. +type AgentRuleVersionCreate struct { + config + mutation *AgentRuleVersionMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetRuleID sets the "rule_id" field. +func (_c *AgentRuleVersionCreate) SetRuleID(v uuid.UUID) *AgentRuleVersionCreate { + _c.mutation.SetRuleID(v) + return _c +} + +// SetVersion sets the "version" field. +func (_c *AgentRuleVersionCreate) SetVersion(v string) *AgentRuleVersionCreate { + _c.mutation.SetVersion(v) + return _c +} + +// SetContent sets the "content" field. +func (_c *AgentRuleVersionCreate) SetContent(v string) *AgentRuleVersionCreate { + _c.mutation.SetContent(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *AgentRuleVersionCreate) SetCreatedAt(v time.Time) *AgentRuleVersionCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *AgentRuleVersionCreate) SetNillableCreatedAt(v *time.Time) *AgentRuleVersionCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *AgentRuleVersionCreate) SetID(v uuid.UUID) *AgentRuleVersionCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *AgentRuleVersionCreate) SetNillableID(v *uuid.UUID) *AgentRuleVersionCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetRule sets the "rule" edge to the AgentRule entity. +func (_c *AgentRuleVersionCreate) SetRule(v *AgentRule) *AgentRuleVersionCreate { + return _c.SetRuleID(v.ID) +} + +// Mutation returns the AgentRuleVersionMutation object of the builder. +func (_c *AgentRuleVersionCreate) Mutation() *AgentRuleVersionMutation { + return _c.mutation +} + +// Save creates the AgentRuleVersion in the database. +func (_c *AgentRuleVersionCreate) Save(ctx context.Context) (*AgentRuleVersion, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *AgentRuleVersionCreate) SaveX(ctx context.Context) *AgentRuleVersion { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *AgentRuleVersionCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *AgentRuleVersionCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *AgentRuleVersionCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := agentruleversion.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := agentruleversion.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *AgentRuleVersionCreate) check() error { + if _, ok := _c.mutation.RuleID(); !ok { + return &ValidationError{Name: "rule_id", err: errors.New(`db: missing required field "AgentRuleVersion.rule_id"`)} + } + if _, ok := _c.mutation.Version(); !ok { + return &ValidationError{Name: "version", err: errors.New(`db: missing required field "AgentRuleVersion.version"`)} + } + if v, ok := _c.mutation.Version(); ok { + if err := agentruleversion.VersionValidator(v); err != nil { + return &ValidationError{Name: "version", err: fmt.Errorf(`db: validator failed for field "AgentRuleVersion.version": %w`, err)} + } + } + if _, ok := _c.mutation.Content(); !ok { + return &ValidationError{Name: "content", err: errors.New(`db: missing required field "AgentRuleVersion.content"`)} + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "AgentRuleVersion.created_at"`)} + } + if len(_c.mutation.RuleIDs()) == 0 { + return &ValidationError{Name: "rule", err: errors.New(`db: missing required edge "AgentRuleVersion.rule"`)} + } + return nil +} + +func (_c *AgentRuleVersionCreate) sqlSave(ctx context.Context) (*AgentRuleVersion, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.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 + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *AgentRuleVersionCreate) createSpec() (*AgentRuleVersion, *sqlgraph.CreateSpec) { + var ( + _node = &AgentRuleVersion{config: _c.config} + _spec = sqlgraph.NewCreateSpec(agentruleversion.Table, sqlgraph.NewFieldSpec(agentruleversion.FieldID, field.TypeUUID)) + ) + _spec.OnConflict = _c.conflict + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = &id + } + if value, ok := _c.mutation.Version(); ok { + _spec.SetField(agentruleversion.FieldVersion, field.TypeString, value) + _node.Version = value + } + if value, ok := _c.mutation.Content(); ok { + _spec.SetField(agentruleversion.FieldContent, field.TypeString, value) + _node.Content = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(agentruleversion.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if nodes := _c.mutation.RuleIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: agentruleversion.RuleTable, + Columns: []string{agentruleversion.RuleColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentrule.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.RuleID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.AgentRuleVersion.Create(). +// SetRuleID(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.AgentRuleVersionUpsert) { +// SetRuleID(v+v). +// }). +// Exec(ctx) +func (_c *AgentRuleVersionCreate) OnConflict(opts ...sql.ConflictOption) *AgentRuleVersionUpsertOne { + _c.conflict = opts + return &AgentRuleVersionUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.AgentRuleVersion.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *AgentRuleVersionCreate) OnConflictColumns(columns ...string) *AgentRuleVersionUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &AgentRuleVersionUpsertOne{ + create: _c, + } +} + +type ( + // AgentRuleVersionUpsertOne is the builder for "upsert"-ing + // one AgentRuleVersion node. + AgentRuleVersionUpsertOne struct { + create *AgentRuleVersionCreate + } + + // AgentRuleVersionUpsert is the "OnConflict" setter. + AgentRuleVersionUpsert struct { + *sql.UpdateSet + } +) + +// SetRuleID sets the "rule_id" field. +func (u *AgentRuleVersionUpsert) SetRuleID(v uuid.UUID) *AgentRuleVersionUpsert { + u.Set(agentruleversion.FieldRuleID, v) + return u +} + +// UpdateRuleID sets the "rule_id" field to the value that was provided on create. +func (u *AgentRuleVersionUpsert) UpdateRuleID() *AgentRuleVersionUpsert { + u.SetExcluded(agentruleversion.FieldRuleID) + return u +} + +// SetVersion sets the "version" field. +func (u *AgentRuleVersionUpsert) SetVersion(v string) *AgentRuleVersionUpsert { + u.Set(agentruleversion.FieldVersion, v) + return u +} + +// UpdateVersion sets the "version" field to the value that was provided on create. +func (u *AgentRuleVersionUpsert) UpdateVersion() *AgentRuleVersionUpsert { + u.SetExcluded(agentruleversion.FieldVersion) + return u +} + +// SetContent sets the "content" field. +func (u *AgentRuleVersionUpsert) SetContent(v string) *AgentRuleVersionUpsert { + u.Set(agentruleversion.FieldContent, v) + return u +} + +// UpdateContent sets the "content" field to the value that was provided on create. +func (u *AgentRuleVersionUpsert) UpdateContent() *AgentRuleVersionUpsert { + u.SetExcluded(agentruleversion.FieldContent) + return u +} + +// SetCreatedAt sets the "created_at" field. +func (u *AgentRuleVersionUpsert) SetCreatedAt(v time.Time) *AgentRuleVersionUpsert { + u.Set(agentruleversion.FieldCreatedAt, v) + return u +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *AgentRuleVersionUpsert) UpdateCreatedAt() *AgentRuleVersionUpsert { + u.SetExcluded(agentruleversion.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.AgentRuleVersion.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(agentruleversion.FieldID) +// }), +// ). +// Exec(ctx) +func (u *AgentRuleVersionUpsertOne) UpdateNewValues() *AgentRuleVersionUpsertOne { + 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(agentruleversion.FieldID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.AgentRuleVersion.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *AgentRuleVersionUpsertOne) Ignore() *AgentRuleVersionUpsertOne { + 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 *AgentRuleVersionUpsertOne) DoNothing() *AgentRuleVersionUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the AgentRuleVersionCreate.OnConflict +// documentation for more info. +func (u *AgentRuleVersionUpsertOne) Update(set func(*AgentRuleVersionUpsert)) *AgentRuleVersionUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&AgentRuleVersionUpsert{UpdateSet: update}) + })) + return u +} + +// SetRuleID sets the "rule_id" field. +func (u *AgentRuleVersionUpsertOne) SetRuleID(v uuid.UUID) *AgentRuleVersionUpsertOne { + return u.Update(func(s *AgentRuleVersionUpsert) { + s.SetRuleID(v) + }) +} + +// UpdateRuleID sets the "rule_id" field to the value that was provided on create. +func (u *AgentRuleVersionUpsertOne) UpdateRuleID() *AgentRuleVersionUpsertOne { + return u.Update(func(s *AgentRuleVersionUpsert) { + s.UpdateRuleID() + }) +} + +// SetVersion sets the "version" field. +func (u *AgentRuleVersionUpsertOne) SetVersion(v string) *AgentRuleVersionUpsertOne { + return u.Update(func(s *AgentRuleVersionUpsert) { + s.SetVersion(v) + }) +} + +// UpdateVersion sets the "version" field to the value that was provided on create. +func (u *AgentRuleVersionUpsertOne) UpdateVersion() *AgentRuleVersionUpsertOne { + return u.Update(func(s *AgentRuleVersionUpsert) { + s.UpdateVersion() + }) +} + +// SetContent sets the "content" field. +func (u *AgentRuleVersionUpsertOne) SetContent(v string) *AgentRuleVersionUpsertOne { + return u.Update(func(s *AgentRuleVersionUpsert) { + s.SetContent(v) + }) +} + +// UpdateContent sets the "content" field to the value that was provided on create. +func (u *AgentRuleVersionUpsertOne) UpdateContent() *AgentRuleVersionUpsertOne { + return u.Update(func(s *AgentRuleVersionUpsert) { + s.UpdateContent() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *AgentRuleVersionUpsertOne) SetCreatedAt(v time.Time) *AgentRuleVersionUpsertOne { + return u.Update(func(s *AgentRuleVersionUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *AgentRuleVersionUpsertOne) UpdateCreatedAt() *AgentRuleVersionUpsertOne { + return u.Update(func(s *AgentRuleVersionUpsert) { + s.UpdateCreatedAt() + }) +} + +// Exec executes the query. +func (u *AgentRuleVersionUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for AgentRuleVersionCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *AgentRuleVersionUpsertOne) 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 *AgentRuleVersionUpsertOne) 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: AgentRuleVersionUpsertOne.ID is not supported by MySQL driver. Use AgentRuleVersionUpsertOne.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 *AgentRuleVersionUpsertOne) IDX(ctx context.Context) uuid.UUID { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// AgentRuleVersionCreateBulk is the builder for creating many AgentRuleVersion entities in bulk. +type AgentRuleVersionCreateBulk struct { + config + err error + builders []*AgentRuleVersionCreate + conflict []sql.ConflictOption +} + +// Save creates the AgentRuleVersion entities in the database. +func (_c *AgentRuleVersionCreateBulk) Save(ctx context.Context) ([]*AgentRuleVersion, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*AgentRuleVersion, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*AgentRuleVersionMutation) + 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, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = _c.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.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, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *AgentRuleVersionCreateBulk) SaveX(ctx context.Context) []*AgentRuleVersion { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *AgentRuleVersionCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *AgentRuleVersionCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.AgentRuleVersion.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.AgentRuleVersionUpsert) { +// SetRuleID(v+v). +// }). +// Exec(ctx) +func (_c *AgentRuleVersionCreateBulk) OnConflict(opts ...sql.ConflictOption) *AgentRuleVersionUpsertBulk { + _c.conflict = opts + return &AgentRuleVersionUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.AgentRuleVersion.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *AgentRuleVersionCreateBulk) OnConflictColumns(columns ...string) *AgentRuleVersionUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &AgentRuleVersionUpsertBulk{ + create: _c, + } +} + +// AgentRuleVersionUpsertBulk is the builder for "upsert"-ing +// a bulk of AgentRuleVersion nodes. +type AgentRuleVersionUpsertBulk struct { + create *AgentRuleVersionCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.AgentRuleVersion.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(agentruleversion.FieldID) +// }), +// ). +// Exec(ctx) +func (u *AgentRuleVersionUpsertBulk) UpdateNewValues() *AgentRuleVersionUpsertBulk { + 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(agentruleversion.FieldID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.AgentRuleVersion.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *AgentRuleVersionUpsertBulk) Ignore() *AgentRuleVersionUpsertBulk { + 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 *AgentRuleVersionUpsertBulk) DoNothing() *AgentRuleVersionUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the AgentRuleVersionCreateBulk.OnConflict +// documentation for more info. +func (u *AgentRuleVersionUpsertBulk) Update(set func(*AgentRuleVersionUpsert)) *AgentRuleVersionUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&AgentRuleVersionUpsert{UpdateSet: update}) + })) + return u +} + +// SetRuleID sets the "rule_id" field. +func (u *AgentRuleVersionUpsertBulk) SetRuleID(v uuid.UUID) *AgentRuleVersionUpsertBulk { + return u.Update(func(s *AgentRuleVersionUpsert) { + s.SetRuleID(v) + }) +} + +// UpdateRuleID sets the "rule_id" field to the value that was provided on create. +func (u *AgentRuleVersionUpsertBulk) UpdateRuleID() *AgentRuleVersionUpsertBulk { + return u.Update(func(s *AgentRuleVersionUpsert) { + s.UpdateRuleID() + }) +} + +// SetVersion sets the "version" field. +func (u *AgentRuleVersionUpsertBulk) SetVersion(v string) *AgentRuleVersionUpsertBulk { + return u.Update(func(s *AgentRuleVersionUpsert) { + s.SetVersion(v) + }) +} + +// UpdateVersion sets the "version" field to the value that was provided on create. +func (u *AgentRuleVersionUpsertBulk) UpdateVersion() *AgentRuleVersionUpsertBulk { + return u.Update(func(s *AgentRuleVersionUpsert) { + s.UpdateVersion() + }) +} + +// SetContent sets the "content" field. +func (u *AgentRuleVersionUpsertBulk) SetContent(v string) *AgentRuleVersionUpsertBulk { + return u.Update(func(s *AgentRuleVersionUpsert) { + s.SetContent(v) + }) +} + +// UpdateContent sets the "content" field to the value that was provided on create. +func (u *AgentRuleVersionUpsertBulk) UpdateContent() *AgentRuleVersionUpsertBulk { + return u.Update(func(s *AgentRuleVersionUpsert) { + s.UpdateContent() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *AgentRuleVersionUpsertBulk) SetCreatedAt(v time.Time) *AgentRuleVersionUpsertBulk { + return u.Update(func(s *AgentRuleVersionUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *AgentRuleVersionUpsertBulk) UpdateCreatedAt() *AgentRuleVersionUpsertBulk { + return u.Update(func(s *AgentRuleVersionUpsert) { + s.UpdateCreatedAt() + }) +} + +// Exec executes the query. +func (u *AgentRuleVersionUpsertBulk) 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 AgentRuleVersionCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for AgentRuleVersionCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *AgentRuleVersionUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/agentruleversion_delete.go b/backend/db/agentruleversion_delete.go new file mode 100644 index 00000000..50a13378 --- /dev/null +++ b/backend/db/agentruleversion_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/agentruleversion" + "github.com/chaitin/MonkeyCode/backend/db/predicate" +) + +// AgentRuleVersionDelete is the builder for deleting a AgentRuleVersion entity. +type AgentRuleVersionDelete struct { + config + hooks []Hook + mutation *AgentRuleVersionMutation +} + +// Where appends a list predicates to the AgentRuleVersionDelete builder. +func (_d *AgentRuleVersionDelete) Where(ps ...predicate.AgentRuleVersion) *AgentRuleVersionDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *AgentRuleVersionDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *AgentRuleVersionDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *AgentRuleVersionDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(agentruleversion.Table, sqlgraph.NewFieldSpec(agentruleversion.FieldID, field.TypeUUID)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// AgentRuleVersionDeleteOne is the builder for deleting a single AgentRuleVersion entity. +type AgentRuleVersionDeleteOne struct { + _d *AgentRuleVersionDelete +} + +// Where appends a list predicates to the AgentRuleVersionDelete builder. +func (_d *AgentRuleVersionDeleteOne) Where(ps ...predicate.AgentRuleVersion) *AgentRuleVersionDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *AgentRuleVersionDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{agentruleversion.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *AgentRuleVersionDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/agentruleversion_query.go b/backend/db/agentruleversion_query.go new file mode 100644 index 00000000..7a0ba010 --- /dev/null +++ b/backend/db/agentruleversion_query.go @@ -0,0 +1,657 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/agentrule" + "github.com/chaitin/MonkeyCode/backend/db/agentruleversion" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/google/uuid" +) + +// AgentRuleVersionQuery is the builder for querying AgentRuleVersion entities. +type AgentRuleVersionQuery struct { + config + ctx *QueryContext + order []agentruleversion.OrderOption + inters []Interceptor + predicates []predicate.AgentRuleVersion + withRule *AgentRuleQuery + 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 AgentRuleVersionQuery builder. +func (_q *AgentRuleVersionQuery) Where(ps ...predicate.AgentRuleVersion) *AgentRuleVersionQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *AgentRuleVersionQuery) Limit(limit int) *AgentRuleVersionQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *AgentRuleVersionQuery) Offset(offset int) *AgentRuleVersionQuery { + _q.ctx.Offset = &offset + return _q +} + +// 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 (_q *AgentRuleVersionQuery) Unique(unique bool) *AgentRuleVersionQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *AgentRuleVersionQuery) Order(o ...agentruleversion.OrderOption) *AgentRuleVersionQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryRule chains the current query on the "rule" edge. +func (_q *AgentRuleVersionQuery) QueryRule() *AgentRuleQuery { + query := (&AgentRuleClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(agentruleversion.Table, agentruleversion.FieldID, selector), + sqlgraph.To(agentrule.Table, agentrule.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, agentruleversion.RuleTable, agentruleversion.RuleColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first AgentRuleVersion entity from the query. +// Returns a *NotFoundError when no AgentRuleVersion was found. +func (_q *AgentRuleVersionQuery) First(ctx context.Context) (*AgentRuleVersion, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{agentruleversion.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *AgentRuleVersionQuery) FirstX(ctx context.Context) *AgentRuleVersion { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first AgentRuleVersion ID from the query. +// Returns a *NotFoundError when no AgentRuleVersion ID was found. +func (_q *AgentRuleVersionQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{agentruleversion.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *AgentRuleVersionQuery) FirstIDX(ctx context.Context) uuid.UUID { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single AgentRuleVersion entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one AgentRuleVersion entity is found. +// Returns a *NotFoundError when no AgentRuleVersion entities are found. +func (_q *AgentRuleVersionQuery) Only(ctx context.Context) (*AgentRuleVersion, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{agentruleversion.Label} + default: + return nil, &NotSingularError{agentruleversion.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *AgentRuleVersionQuery) OnlyX(ctx context.Context) *AgentRuleVersion { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only AgentRuleVersion ID in the query. +// Returns a *NotSingularError when more than one AgentRuleVersion ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *AgentRuleVersionQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{agentruleversion.Label} + default: + err = &NotSingularError{agentruleversion.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *AgentRuleVersionQuery) OnlyIDX(ctx context.Context) uuid.UUID { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of AgentRuleVersions. +func (_q *AgentRuleVersionQuery) All(ctx context.Context) ([]*AgentRuleVersion, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*AgentRuleVersion, *AgentRuleVersionQuery]() + return withInterceptors[[]*AgentRuleVersion](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *AgentRuleVersionQuery) AllX(ctx context.Context) []*AgentRuleVersion { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of AgentRuleVersion IDs. +func (_q *AgentRuleVersionQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(agentruleversion.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *AgentRuleVersionQuery) IDsX(ctx context.Context) []uuid.UUID { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *AgentRuleVersionQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*AgentRuleVersionQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *AgentRuleVersionQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *AgentRuleVersionQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.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 (_q *AgentRuleVersionQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the AgentRuleVersionQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *AgentRuleVersionQuery) Clone() *AgentRuleVersionQuery { + if _q == nil { + return nil + } + return &AgentRuleVersionQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]agentruleversion.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.AgentRuleVersion{}, _q.predicates...), + withRule: _q.withRule.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + modifiers: append([]func(*sql.Selector){}, _q.modifiers...), + } +} + +// WithRule tells the query-builder to eager-load the nodes that are connected to +// the "rule" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *AgentRuleVersionQuery) WithRule(opts ...func(*AgentRuleQuery)) *AgentRuleVersionQuery { + query := (&AgentRuleClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withRule = query + return _q +} + +// 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 { +// RuleID uuid.UUID `json:"rule_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.AgentRuleVersion.Query(). +// GroupBy(agentruleversion.FieldRuleID). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *AgentRuleVersionQuery) GroupBy(field string, fields ...string) *AgentRuleVersionGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &AgentRuleVersionGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = agentruleversion.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 { +// RuleID uuid.UUID `json:"rule_id,omitempty"` +// } +// +// client.AgentRuleVersion.Query(). +// Select(agentruleversion.FieldRuleID). +// Scan(ctx, &v) +func (_q *AgentRuleVersionQuery) Select(fields ...string) *AgentRuleVersionSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &AgentRuleVersionSelect{AgentRuleVersionQuery: _q} + sbuild.label = agentruleversion.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a AgentRuleVersionSelect configured with the given aggregations. +func (_q *AgentRuleVersionQuery) Aggregate(fns ...AggregateFunc) *AgentRuleVersionSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *AgentRuleVersionQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.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, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !agentruleversion.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *AgentRuleVersionQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*AgentRuleVersion, error) { + var ( + nodes = []*AgentRuleVersion{} + _spec = _q.querySpec() + loadedTypes = [1]bool{ + _q.withRule != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*AgentRuleVersion).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &AgentRuleVersion{config: _q.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := _q.withRule; query != nil { + if err := _q.loadRule(ctx, query, nodes, nil, + func(n *AgentRuleVersion, e *AgentRule) { n.Edges.Rule = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *AgentRuleVersionQuery) loadRule(ctx context.Context, query *AgentRuleQuery, nodes []*AgentRuleVersion, init func(*AgentRuleVersion), assign func(*AgentRuleVersion, *AgentRule)) error { + ids := make([]uuid.UUID, 0, len(nodes)) + nodeids := make(map[uuid.UUID][]*AgentRuleVersion) + for i := range nodes { + fk := nodes[i].RuleID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(agentrule.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return fmt.Errorf(`unexpected foreign-key "rule_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *AgentRuleVersionQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *AgentRuleVersionQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(agentruleversion.Table, agentruleversion.Columns, sqlgraph.NewFieldSpec(agentruleversion.FieldID, field.TypeUUID)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, agentruleversion.FieldID) + for i := range fields { + if fields[i] != agentruleversion.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withRule != nil { + _spec.Node.AddColumnOnce(agentruleversion.FieldRuleID) + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *AgentRuleVersionQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(agentruleversion.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = agentruleversion.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, m := range _q.modifiers { + m(selector) + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.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 := _q.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 (_q *AgentRuleVersionQuery) ForUpdate(opts ...sql.LockOption) *AgentRuleVersionQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForUpdate(opts...) + }) + return _q +} + +// 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 (_q *AgentRuleVersionQuery) ForShare(opts ...sql.LockOption) *AgentRuleVersionQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (_q *AgentRuleVersionQuery) Modify(modifiers ...func(s *sql.Selector)) *AgentRuleVersionSelect { + _q.modifiers = append(_q.modifiers, modifiers...) + return _q.Select() +} + +// AgentRuleVersionGroupBy is the group-by builder for AgentRuleVersion entities. +type AgentRuleVersionGroupBy struct { + selector + build *AgentRuleVersionQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *AgentRuleVersionGroupBy) Aggregate(fns ...AggregateFunc) *AgentRuleVersionGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *AgentRuleVersionGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*AgentRuleVersionQuery, *AgentRuleVersionGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *AgentRuleVersionGroupBy) sqlScan(ctx context.Context, root *AgentRuleVersionQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// AgentRuleVersionSelect is the builder for selecting fields of AgentRuleVersion entities. +type AgentRuleVersionSelect struct { + *AgentRuleVersionQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *AgentRuleVersionSelect) Aggregate(fns ...AggregateFunc) *AgentRuleVersionSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *AgentRuleVersionSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*AgentRuleVersionQuery, *AgentRuleVersionSelect](ctx, _s.AgentRuleVersionQuery, _s, _s.inters, v) +} + +func (_s *AgentRuleVersionSelect) sqlScan(ctx context.Context, root *AgentRuleVersionQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.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 := _s.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 (_s *AgentRuleVersionSelect) Modify(modifiers ...func(s *sql.Selector)) *AgentRuleVersionSelect { + _s.modifiers = append(_s.modifiers, modifiers...) + return _s +} diff --git a/backend/db/agentruleversion_update.go b/backend/db/agentruleversion_update.go new file mode 100644 index 00000000..91222d08 --- /dev/null +++ b/backend/db/agentruleversion_update.go @@ -0,0 +1,436 @@ +// 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/agentrule" + "github.com/chaitin/MonkeyCode/backend/db/agentruleversion" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/google/uuid" +) + +// AgentRuleVersionUpdate is the builder for updating AgentRuleVersion entities. +type AgentRuleVersionUpdate struct { + config + hooks []Hook + mutation *AgentRuleVersionMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the AgentRuleVersionUpdate builder. +func (_u *AgentRuleVersionUpdate) Where(ps ...predicate.AgentRuleVersion) *AgentRuleVersionUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetRuleID sets the "rule_id" field. +func (_u *AgentRuleVersionUpdate) SetRuleID(v uuid.UUID) *AgentRuleVersionUpdate { + _u.mutation.SetRuleID(v) + return _u +} + +// SetNillableRuleID sets the "rule_id" field if the given value is not nil. +func (_u *AgentRuleVersionUpdate) SetNillableRuleID(v *uuid.UUID) *AgentRuleVersionUpdate { + if v != nil { + _u.SetRuleID(*v) + } + return _u +} + +// SetVersion sets the "version" field. +func (_u *AgentRuleVersionUpdate) SetVersion(v string) *AgentRuleVersionUpdate { + _u.mutation.SetVersion(v) + return _u +} + +// SetNillableVersion sets the "version" field if the given value is not nil. +func (_u *AgentRuleVersionUpdate) SetNillableVersion(v *string) *AgentRuleVersionUpdate { + if v != nil { + _u.SetVersion(*v) + } + return _u +} + +// SetContent sets the "content" field. +func (_u *AgentRuleVersionUpdate) SetContent(v string) *AgentRuleVersionUpdate { + _u.mutation.SetContent(v) + return _u +} + +// SetNillableContent sets the "content" field if the given value is not nil. +func (_u *AgentRuleVersionUpdate) SetNillableContent(v *string) *AgentRuleVersionUpdate { + if v != nil { + _u.SetContent(*v) + } + return _u +} + +// SetCreatedAt sets the "created_at" field. +func (_u *AgentRuleVersionUpdate) SetCreatedAt(v time.Time) *AgentRuleVersionUpdate { + _u.mutation.SetCreatedAt(v) + return _u +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_u *AgentRuleVersionUpdate) SetNillableCreatedAt(v *time.Time) *AgentRuleVersionUpdate { + if v != nil { + _u.SetCreatedAt(*v) + } + return _u +} + +// SetRule sets the "rule" edge to the AgentRule entity. +func (_u *AgentRuleVersionUpdate) SetRule(v *AgentRule) *AgentRuleVersionUpdate { + return _u.SetRuleID(v.ID) +} + +// Mutation returns the AgentRuleVersionMutation object of the builder. +func (_u *AgentRuleVersionUpdate) Mutation() *AgentRuleVersionMutation { + return _u.mutation +} + +// ClearRule clears the "rule" edge to the AgentRule entity. +func (_u *AgentRuleVersionUpdate) ClearRule() *AgentRuleVersionUpdate { + _u.mutation.ClearRule() + return _u +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *AgentRuleVersionUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *AgentRuleVersionUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *AgentRuleVersionUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *AgentRuleVersionUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *AgentRuleVersionUpdate) check() error { + if v, ok := _u.mutation.Version(); ok { + if err := agentruleversion.VersionValidator(v); err != nil { + return &ValidationError{Name: "version", err: fmt.Errorf(`db: validator failed for field "AgentRuleVersion.version": %w`, err)} + } + } + if _u.mutation.RuleCleared() && len(_u.mutation.RuleIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "AgentRuleVersion.rule"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (_u *AgentRuleVersionUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *AgentRuleVersionUpdate { + _u.modifiers = append(_u.modifiers, modifiers...) + return _u +} + +func (_u *AgentRuleVersionUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(agentruleversion.Table, agentruleversion.Columns, sqlgraph.NewFieldSpec(agentruleversion.FieldID, field.TypeUUID)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.Version(); ok { + _spec.SetField(agentruleversion.FieldVersion, field.TypeString, value) + } + if value, ok := _u.mutation.Content(); ok { + _spec.SetField(agentruleversion.FieldContent, field.TypeString, value) + } + if value, ok := _u.mutation.CreatedAt(); ok { + _spec.SetField(agentruleversion.FieldCreatedAt, field.TypeTime, value) + } + if _u.mutation.RuleCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: agentruleversion.RuleTable, + Columns: []string{agentruleversion.RuleColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentrule.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RuleIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: agentruleversion.RuleTable, + Columns: []string{agentruleversion.RuleColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentrule.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(_u.modifiers...) + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{agentruleversion.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// AgentRuleVersionUpdateOne is the builder for updating a single AgentRuleVersion entity. +type AgentRuleVersionUpdateOne struct { + config + fields []string + hooks []Hook + mutation *AgentRuleVersionMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetRuleID sets the "rule_id" field. +func (_u *AgentRuleVersionUpdateOne) SetRuleID(v uuid.UUID) *AgentRuleVersionUpdateOne { + _u.mutation.SetRuleID(v) + return _u +} + +// SetNillableRuleID sets the "rule_id" field if the given value is not nil. +func (_u *AgentRuleVersionUpdateOne) SetNillableRuleID(v *uuid.UUID) *AgentRuleVersionUpdateOne { + if v != nil { + _u.SetRuleID(*v) + } + return _u +} + +// SetVersion sets the "version" field. +func (_u *AgentRuleVersionUpdateOne) SetVersion(v string) *AgentRuleVersionUpdateOne { + _u.mutation.SetVersion(v) + return _u +} + +// SetNillableVersion sets the "version" field if the given value is not nil. +func (_u *AgentRuleVersionUpdateOne) SetNillableVersion(v *string) *AgentRuleVersionUpdateOne { + if v != nil { + _u.SetVersion(*v) + } + return _u +} + +// SetContent sets the "content" field. +func (_u *AgentRuleVersionUpdateOne) SetContent(v string) *AgentRuleVersionUpdateOne { + _u.mutation.SetContent(v) + return _u +} + +// SetNillableContent sets the "content" field if the given value is not nil. +func (_u *AgentRuleVersionUpdateOne) SetNillableContent(v *string) *AgentRuleVersionUpdateOne { + if v != nil { + _u.SetContent(*v) + } + return _u +} + +// SetCreatedAt sets the "created_at" field. +func (_u *AgentRuleVersionUpdateOne) SetCreatedAt(v time.Time) *AgentRuleVersionUpdateOne { + _u.mutation.SetCreatedAt(v) + return _u +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_u *AgentRuleVersionUpdateOne) SetNillableCreatedAt(v *time.Time) *AgentRuleVersionUpdateOne { + if v != nil { + _u.SetCreatedAt(*v) + } + return _u +} + +// SetRule sets the "rule" edge to the AgentRule entity. +func (_u *AgentRuleVersionUpdateOne) SetRule(v *AgentRule) *AgentRuleVersionUpdateOne { + return _u.SetRuleID(v.ID) +} + +// Mutation returns the AgentRuleVersionMutation object of the builder. +func (_u *AgentRuleVersionUpdateOne) Mutation() *AgentRuleVersionMutation { + return _u.mutation +} + +// ClearRule clears the "rule" edge to the AgentRule entity. +func (_u *AgentRuleVersionUpdateOne) ClearRule() *AgentRuleVersionUpdateOne { + _u.mutation.ClearRule() + return _u +} + +// Where appends a list predicates to the AgentRuleVersionUpdate builder. +func (_u *AgentRuleVersionUpdateOne) Where(ps ...predicate.AgentRuleVersion) *AgentRuleVersionUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *AgentRuleVersionUpdateOne) Select(field string, fields ...string) *AgentRuleVersionUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated AgentRuleVersion entity. +func (_u *AgentRuleVersionUpdateOne) Save(ctx context.Context) (*AgentRuleVersion, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *AgentRuleVersionUpdateOne) SaveX(ctx context.Context) *AgentRuleVersion { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *AgentRuleVersionUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *AgentRuleVersionUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *AgentRuleVersionUpdateOne) check() error { + if v, ok := _u.mutation.Version(); ok { + if err := agentruleversion.VersionValidator(v); err != nil { + return &ValidationError{Name: "version", err: fmt.Errorf(`db: validator failed for field "AgentRuleVersion.version": %w`, err)} + } + } + if _u.mutation.RuleCleared() && len(_u.mutation.RuleIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "AgentRuleVersion.rule"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (_u *AgentRuleVersionUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *AgentRuleVersionUpdateOne { + _u.modifiers = append(_u.modifiers, modifiers...) + return _u +} + +func (_u *AgentRuleVersionUpdateOne) sqlSave(ctx context.Context) (_node *AgentRuleVersion, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(agentruleversion.Table, agentruleversion.Columns, sqlgraph.NewFieldSpec(agentruleversion.FieldID, field.TypeUUID)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "AgentRuleVersion.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, agentruleversion.FieldID) + for _, f := range fields { + if !agentruleversion.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != agentruleversion.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.Version(); ok { + _spec.SetField(agentruleversion.FieldVersion, field.TypeString, value) + } + if value, ok := _u.mutation.Content(); ok { + _spec.SetField(agentruleversion.FieldContent, field.TypeString, value) + } + if value, ok := _u.mutation.CreatedAt(); ok { + _spec.SetField(agentruleversion.FieldCreatedAt, field.TypeTime, value) + } + if _u.mutation.RuleCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: agentruleversion.RuleTable, + Columns: []string{agentruleversion.RuleColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentrule.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RuleIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: agentruleversion.RuleTable, + Columns: []string{agentruleversion.RuleColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentrule.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(_u.modifiers...) + _node = &AgentRuleVersion{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{agentruleversion.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/backend/db/agentskill.go b/backend/db/agentskill.go new file mode 100644 index 00000000..32c996f3 --- /dev/null +++ b/backend/db/agentskill.go @@ -0,0 +1,280 @@ +// 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/agentskill" + "github.com/chaitin/MonkeyCode/backend/db/agentskillrepo" + "github.com/google/uuid" +) + +// AgentSkill is the model entity for the AgentSkill schema. +type AgentSkill struct { + config `json:"-"` + // ID of the ent. + ID uuid.UUID `json:"id,omitempty"` + // RepoID holds the value of the "repo_id" field. + RepoID uuid.UUID `json:"repo_id,omitempty"` + // Name holds the value of the "name" field. + Name string `json:"name,omitempty"` + // Description holds the value of the "description" field. + Description string `json:"description,omitempty"` + // ScopeType holds the value of the "scope_type" field. + ScopeType agentskill.ScopeType `json:"scope_type,omitempty"` + // ScopeID holds the value of the "scope_id" field. + ScopeID string `json:"scope_id,omitempty"` + // CreatedBy holds the value of the "created_by" field. + CreatedBy uuid.UUID `json:"created_by,omitempty"` + // ActiveVersionID holds the value of the "active_version_id" field. + ActiveVersionID *uuid.UUID `json:"active_version_id,omitempty"` + // IsForceDelivery holds the value of the "is_force_delivery" field. + IsForceDelivery bool `json:"is_force_delivery,omitempty"` + // IsOrphan holds the value of the "is_orphan" field. + IsOrphan bool `json:"is_orphan,omitempty"` + // IsDeleted holds the value of the "is_deleted" field. + IsDeleted bool `json:"is_deleted,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + // UpdatedAt holds the value of the "updated_at" field. + UpdatedAt time.Time `json:"updated_at,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the AgentSkillQuery when eager-loading is set. + Edges AgentSkillEdges `json:"edges"` + selectValues sql.SelectValues +} + +// AgentSkillEdges holds the relations/edges for other nodes in the graph. +type AgentSkillEdges struct { + // Repo holds the value of the repo edge. + Repo *AgentSkillRepo `json:"repo,omitempty"` + // Versions holds the value of the versions edge. + Versions []*AgentSkillVersion `json:"versions,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool +} + +// RepoOrErr returns the Repo value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e AgentSkillEdges) RepoOrErr() (*AgentSkillRepo, error) { + if e.Repo != nil { + return e.Repo, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: agentskillrepo.Label} + } + return nil, &NotLoadedError{edge: "repo"} +} + +// VersionsOrErr returns the Versions value or an error if the edge +// was not loaded in eager-loading. +func (e AgentSkillEdges) VersionsOrErr() ([]*AgentSkillVersion, error) { + if e.loadedTypes[1] { + return e.Versions, nil + } + return nil, &NotLoadedError{edge: "versions"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*AgentSkill) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case agentskill.FieldActiveVersionID: + values[i] = &sql.NullScanner{S: new(uuid.UUID)} + case agentskill.FieldIsForceDelivery, agentskill.FieldIsOrphan, agentskill.FieldIsDeleted: + values[i] = new(sql.NullBool) + case agentskill.FieldName, agentskill.FieldDescription, agentskill.FieldScopeType, agentskill.FieldScopeID: + values[i] = new(sql.NullString) + case agentskill.FieldCreatedAt, agentskill.FieldUpdatedAt: + values[i] = new(sql.NullTime) + case agentskill.FieldID, agentskill.FieldRepoID, agentskill.FieldCreatedBy: + 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 AgentSkill fields. +func (_m *AgentSkill) 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 agentskill.FieldID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value != nil { + _m.ID = *value + } + case agentskill.FieldRepoID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field repo_id", values[i]) + } else if value != nil { + _m.RepoID = *value + } + case agentskill.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + _m.Name = value.String + } + case agentskill.FieldDescription: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field description", values[i]) + } else if value.Valid { + _m.Description = value.String + } + case agentskill.FieldScopeType: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field scope_type", values[i]) + } else if value.Valid { + _m.ScopeType = agentskill.ScopeType(value.String) + } + case agentskill.FieldScopeID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field scope_id", values[i]) + } else if value.Valid { + _m.ScopeID = value.String + } + case agentskill.FieldCreatedBy: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field created_by", values[i]) + } else if value != nil { + _m.CreatedBy = *value + } + case agentskill.FieldActiveVersionID: + if value, ok := values[i].(*sql.NullScanner); !ok { + return fmt.Errorf("unexpected type %T for field active_version_id", values[i]) + } else if value.Valid { + _m.ActiveVersionID = new(uuid.UUID) + *_m.ActiveVersionID = *value.S.(*uuid.UUID) + } + case agentskill.FieldIsForceDelivery: + if value, ok := values[i].(*sql.NullBool); !ok { + return fmt.Errorf("unexpected type %T for field is_force_delivery", values[i]) + } else if value.Valid { + _m.IsForceDelivery = value.Bool + } + case agentskill.FieldIsOrphan: + if value, ok := values[i].(*sql.NullBool); !ok { + return fmt.Errorf("unexpected type %T for field is_orphan", values[i]) + } else if value.Valid { + _m.IsOrphan = value.Bool + } + case agentskill.FieldIsDeleted: + if value, ok := values[i].(*sql.NullBool); !ok { + return fmt.Errorf("unexpected type %T for field is_deleted", values[i]) + } else if value.Valid { + _m.IsDeleted = value.Bool + } + case agentskill.FieldCreatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field created_at", values[i]) + } else if value.Valid { + _m.CreatedAt = value.Time + } + case agentskill.FieldUpdatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field updated_at", values[i]) + } else if value.Valid { + _m.UpdatedAt = value.Time + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the AgentSkill. +// This includes values selected through modifiers, order, etc. +func (_m *AgentSkill) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryRepo queries the "repo" edge of the AgentSkill entity. +func (_m *AgentSkill) QueryRepo() *AgentSkillRepoQuery { + return NewAgentSkillClient(_m.config).QueryRepo(_m) +} + +// QueryVersions queries the "versions" edge of the AgentSkill entity. +func (_m *AgentSkill) QueryVersions() *AgentSkillVersionQuery { + return NewAgentSkillClient(_m.config).QueryVersions(_m) +} + +// Update returns a builder for updating this AgentSkill. +// Note that you need to call AgentSkill.Unwrap() before calling this method if this AgentSkill +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *AgentSkill) Update() *AgentSkillUpdateOne { + return NewAgentSkillClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the AgentSkill entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (_m *AgentSkill) Unwrap() *AgentSkill { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: AgentSkill is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *AgentSkill) String() string { + var builder strings.Builder + builder.WriteString("AgentSkill(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("repo_id=") + builder.WriteString(fmt.Sprintf("%v", _m.RepoID)) + builder.WriteString(", ") + builder.WriteString("name=") + builder.WriteString(_m.Name) + builder.WriteString(", ") + builder.WriteString("description=") + builder.WriteString(_m.Description) + builder.WriteString(", ") + builder.WriteString("scope_type=") + builder.WriteString(fmt.Sprintf("%v", _m.ScopeType)) + builder.WriteString(", ") + builder.WriteString("scope_id=") + builder.WriteString(_m.ScopeID) + builder.WriteString(", ") + builder.WriteString("created_by=") + builder.WriteString(fmt.Sprintf("%v", _m.CreatedBy)) + builder.WriteString(", ") + if v := _m.ActiveVersionID; v != nil { + builder.WriteString("active_version_id=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + builder.WriteString("is_force_delivery=") + builder.WriteString(fmt.Sprintf("%v", _m.IsForceDelivery)) + builder.WriteString(", ") + builder.WriteString("is_orphan=") + builder.WriteString(fmt.Sprintf("%v", _m.IsOrphan)) + builder.WriteString(", ") + builder.WriteString("is_deleted=") + builder.WriteString(fmt.Sprintf("%v", _m.IsDeleted)) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("updated_at=") + builder.WriteString(_m.UpdatedAt.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// AgentSkills is a parsable slice of AgentSkill. +type AgentSkills []*AgentSkill diff --git a/backend/db/agentskill/agentskill.go b/backend/db/agentskill/agentskill.go new file mode 100644 index 00000000..66b2619c --- /dev/null +++ b/backend/db/agentskill/agentskill.go @@ -0,0 +1,239 @@ +// Code generated by ent, DO NOT EDIT. + +package agentskill + +import ( + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/google/uuid" +) + +const ( + // Label holds the string label denoting the agentskill type in the database. + Label = "agent_skill" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldRepoID holds the string denoting the repo_id field in the database. + FieldRepoID = "repo_id" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldDescription holds the string denoting the description field in the database. + FieldDescription = "description" + // FieldScopeType holds the string denoting the scope_type field in the database. + FieldScopeType = "scope_type" + // FieldScopeID holds the string denoting the scope_id field in the database. + FieldScopeID = "scope_id" + // FieldCreatedBy holds the string denoting the created_by field in the database. + FieldCreatedBy = "created_by" + // FieldActiveVersionID holds the string denoting the active_version_id field in the database. + FieldActiveVersionID = "active_version_id" + // FieldIsForceDelivery holds the string denoting the is_force_delivery field in the database. + FieldIsForceDelivery = "is_force_delivery" + // FieldIsOrphan holds the string denoting the is_orphan field in the database. + FieldIsOrphan = "is_orphan" + // FieldIsDeleted holds the string denoting the is_deleted field in the database. + FieldIsDeleted = "is_deleted" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // FieldUpdatedAt holds the string denoting the updated_at field in the database. + FieldUpdatedAt = "updated_at" + // EdgeRepo holds the string denoting the repo edge name in mutations. + EdgeRepo = "repo" + // EdgeVersions holds the string denoting the versions edge name in mutations. + EdgeVersions = "versions" + // Table holds the table name of the agentskill in the database. + Table = "agent_skills" + // RepoTable is the table that holds the repo relation/edge. + RepoTable = "agent_skills" + // RepoInverseTable is the table name for the AgentSkillRepo entity. + // It exists in this package in order to avoid circular dependency with the "agentskillrepo" package. + RepoInverseTable = "agent_skill_repos" + // RepoColumn is the table column denoting the repo relation/edge. + RepoColumn = "repo_id" + // VersionsTable is the table that holds the versions relation/edge. + VersionsTable = "agent_skill_versions" + // VersionsInverseTable is the table name for the AgentSkillVersion entity. + // It exists in this package in order to avoid circular dependency with the "agentskillversion" package. + VersionsInverseTable = "agent_skill_versions" + // VersionsColumn is the table column denoting the versions relation/edge. + VersionsColumn = "resource_id" +) + +// Columns holds all SQL columns for agentskill fields. +var Columns = []string{ + FieldID, + FieldRepoID, + FieldName, + FieldDescription, + FieldScopeType, + FieldScopeID, + FieldCreatedBy, + FieldActiveVersionID, + FieldIsForceDelivery, + FieldIsOrphan, + FieldIsDeleted, + FieldCreatedAt, + FieldUpdatedAt, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // NameValidator is a validator for the "name" field. It is called by the builders before save. + NameValidator func(string) error + // DefaultScopeID holds the default value on creation for the "scope_id" field. + DefaultScopeID string + // DefaultIsForceDelivery holds the default value on creation for the "is_force_delivery" field. + DefaultIsForceDelivery bool + // DefaultIsOrphan holds the default value on creation for the "is_orphan" field. + DefaultIsOrphan bool + // DefaultIsDeleted holds the default value on creation for the "is_deleted" field. + DefaultIsDeleted bool + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time + // DefaultUpdatedAt holds the default value on creation for the "updated_at" field. + DefaultUpdatedAt func() time.Time + // UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field. + UpdateDefaultUpdatedAt func() time.Time + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() uuid.UUID +) + +// ScopeType defines the type for the "scope_type" enum field. +type ScopeType string + +// ScopeTypeGlobal is the default value of the ScopeType enum. +const DefaultScopeType = ScopeTypeGlobal + +// ScopeType values. +const ( + ScopeTypeGlobal ScopeType = "global" +) + +func (st ScopeType) String() string { + return string(st) +} + +// ScopeTypeValidator is a validator for the "scope_type" field enum values. It is called by the builders before save. +func ScopeTypeValidator(st ScopeType) error { + switch st { + case ScopeTypeGlobal: + return nil + default: + return fmt.Errorf("agentskill: invalid enum value for scope_type field: %q", st) + } +} + +// OrderOption defines the ordering options for the AgentSkill 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() +} + +// ByRepoID orders the results by the repo_id field. +func ByRepoID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRepoID, opts...).ToFunc() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} + +// ByDescription orders the results by the description field. +func ByDescription(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDescription, opts...).ToFunc() +} + +// ByScopeType orders the results by the scope_type field. +func ByScopeType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldScopeType, opts...).ToFunc() +} + +// ByScopeID orders the results by the scope_id field. +func ByScopeID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldScopeID, opts...).ToFunc() +} + +// ByCreatedBy orders the results by the created_by field. +func ByCreatedBy(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedBy, opts...).ToFunc() +} + +// ByActiveVersionID orders the results by the active_version_id field. +func ByActiveVersionID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldActiveVersionID, opts...).ToFunc() +} + +// ByIsForceDelivery orders the results by the is_force_delivery field. +func ByIsForceDelivery(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldIsForceDelivery, opts...).ToFunc() +} + +// ByIsOrphan orders the results by the is_orphan field. +func ByIsOrphan(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldIsOrphan, opts...).ToFunc() +} + +// ByIsDeleted orders the results by the is_deleted field. +func ByIsDeleted(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldIsDeleted, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// ByUpdatedAt orders the results by the updated_at field. +func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc() +} + +// ByRepoField orders the results by repo field. +func ByRepoField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newRepoStep(), sql.OrderByField(field, opts...)) + } +} + +// ByVersionsCount orders the results by versions count. +func ByVersionsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newVersionsStep(), opts...) + } +} + +// ByVersions orders the results by versions terms. +func ByVersions(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newVersionsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newRepoStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(RepoInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, RepoTable, RepoColumn), + ) +} +func newVersionsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(VersionsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, VersionsTable, VersionsColumn), + ) +} diff --git a/backend/db/agentskill/where.go b/backend/db/agentskill/where.go new file mode 100644 index 00000000..c04d20e9 --- /dev/null +++ b/backend/db/agentskill/where.go @@ -0,0 +1,618 @@ +// Code generated by ent, DO NOT EDIT. + +package agentskill + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/google/uuid" +) + +// ID filters vertices based on their ID field. +func ID(id uuid.UUID) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id uuid.UUID) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id uuid.UUID) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...uuid.UUID) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...uuid.UUID) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id uuid.UUID) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id uuid.UUID) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id uuid.UUID) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id uuid.UUID) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldLTE(FieldID, id)) +} + +// RepoID applies equality check predicate on the "repo_id" field. It's identical to RepoIDEQ. +func RepoID(v uuid.UUID) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldEQ(FieldRepoID, v)) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldEQ(FieldName, v)) +} + +// Description applies equality check predicate on the "description" field. It's identical to DescriptionEQ. +func Description(v string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldEQ(FieldDescription, v)) +} + +// ScopeID applies equality check predicate on the "scope_id" field. It's identical to ScopeIDEQ. +func ScopeID(v string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldEQ(FieldScopeID, v)) +} + +// CreatedBy applies equality check predicate on the "created_by" field. It's identical to CreatedByEQ. +func CreatedBy(v uuid.UUID) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldEQ(FieldCreatedBy, v)) +} + +// ActiveVersionID applies equality check predicate on the "active_version_id" field. It's identical to ActiveVersionIDEQ. +func ActiveVersionID(v uuid.UUID) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldEQ(FieldActiveVersionID, v)) +} + +// IsForceDelivery applies equality check predicate on the "is_force_delivery" field. It's identical to IsForceDeliveryEQ. +func IsForceDelivery(v bool) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldEQ(FieldIsForceDelivery, v)) +} + +// IsOrphan applies equality check predicate on the "is_orphan" field. It's identical to IsOrphanEQ. +func IsOrphan(v bool) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldEQ(FieldIsOrphan, v)) +} + +// IsDeleted applies equality check predicate on the "is_deleted" field. It's identical to IsDeletedEQ. +func IsDeleted(v bool) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldEQ(FieldIsDeleted, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldEQ(FieldCreatedAt, v)) +} + +// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ. +func UpdatedAt(v time.Time) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// RepoIDEQ applies the EQ predicate on the "repo_id" field. +func RepoIDEQ(v uuid.UUID) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldEQ(FieldRepoID, v)) +} + +// RepoIDNEQ applies the NEQ predicate on the "repo_id" field. +func RepoIDNEQ(v uuid.UUID) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldNEQ(FieldRepoID, v)) +} + +// RepoIDIn applies the In predicate on the "repo_id" field. +func RepoIDIn(vs ...uuid.UUID) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldIn(FieldRepoID, vs...)) +} + +// RepoIDNotIn applies the NotIn predicate on the "repo_id" field. +func RepoIDNotIn(vs ...uuid.UUID) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldNotIn(FieldRepoID, vs...)) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldEQ(FieldName, v)) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldNEQ(FieldName, v)) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldIn(FieldName, vs...)) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldNotIn(FieldName, vs...)) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldGT(FieldName, v)) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldGTE(FieldName, v)) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldLT(FieldName, v)) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldLTE(FieldName, v)) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldContains(FieldName, v)) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldHasPrefix(FieldName, v)) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldHasSuffix(FieldName, v)) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldEqualFold(FieldName, v)) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldContainsFold(FieldName, v)) +} + +// DescriptionEQ applies the EQ predicate on the "description" field. +func DescriptionEQ(v string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldEQ(FieldDescription, v)) +} + +// DescriptionNEQ applies the NEQ predicate on the "description" field. +func DescriptionNEQ(v string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldNEQ(FieldDescription, v)) +} + +// DescriptionIn applies the In predicate on the "description" field. +func DescriptionIn(vs ...string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldIn(FieldDescription, vs...)) +} + +// DescriptionNotIn applies the NotIn predicate on the "description" field. +func DescriptionNotIn(vs ...string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldNotIn(FieldDescription, vs...)) +} + +// DescriptionGT applies the GT predicate on the "description" field. +func DescriptionGT(v string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldGT(FieldDescription, v)) +} + +// DescriptionGTE applies the GTE predicate on the "description" field. +func DescriptionGTE(v string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldGTE(FieldDescription, v)) +} + +// DescriptionLT applies the LT predicate on the "description" field. +func DescriptionLT(v string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldLT(FieldDescription, v)) +} + +// DescriptionLTE applies the LTE predicate on the "description" field. +func DescriptionLTE(v string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldLTE(FieldDescription, v)) +} + +// DescriptionContains applies the Contains predicate on the "description" field. +func DescriptionContains(v string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldContains(FieldDescription, v)) +} + +// DescriptionHasPrefix applies the HasPrefix predicate on the "description" field. +func DescriptionHasPrefix(v string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldHasPrefix(FieldDescription, v)) +} + +// DescriptionHasSuffix applies the HasSuffix predicate on the "description" field. +func DescriptionHasSuffix(v string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldHasSuffix(FieldDescription, v)) +} + +// DescriptionIsNil applies the IsNil predicate on the "description" field. +func DescriptionIsNil() predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldIsNull(FieldDescription)) +} + +// DescriptionNotNil applies the NotNil predicate on the "description" field. +func DescriptionNotNil() predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldNotNull(FieldDescription)) +} + +// DescriptionEqualFold applies the EqualFold predicate on the "description" field. +func DescriptionEqualFold(v string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldEqualFold(FieldDescription, v)) +} + +// DescriptionContainsFold applies the ContainsFold predicate on the "description" field. +func DescriptionContainsFold(v string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldContainsFold(FieldDescription, v)) +} + +// ScopeTypeEQ applies the EQ predicate on the "scope_type" field. +func ScopeTypeEQ(v ScopeType) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldEQ(FieldScopeType, v)) +} + +// ScopeTypeNEQ applies the NEQ predicate on the "scope_type" field. +func ScopeTypeNEQ(v ScopeType) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldNEQ(FieldScopeType, v)) +} + +// ScopeTypeIn applies the In predicate on the "scope_type" field. +func ScopeTypeIn(vs ...ScopeType) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldIn(FieldScopeType, vs...)) +} + +// ScopeTypeNotIn applies the NotIn predicate on the "scope_type" field. +func ScopeTypeNotIn(vs ...ScopeType) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldNotIn(FieldScopeType, vs...)) +} + +// ScopeIDEQ applies the EQ predicate on the "scope_id" field. +func ScopeIDEQ(v string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldEQ(FieldScopeID, v)) +} + +// ScopeIDNEQ applies the NEQ predicate on the "scope_id" field. +func ScopeIDNEQ(v string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldNEQ(FieldScopeID, v)) +} + +// ScopeIDIn applies the In predicate on the "scope_id" field. +func ScopeIDIn(vs ...string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldIn(FieldScopeID, vs...)) +} + +// ScopeIDNotIn applies the NotIn predicate on the "scope_id" field. +func ScopeIDNotIn(vs ...string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldNotIn(FieldScopeID, vs...)) +} + +// ScopeIDGT applies the GT predicate on the "scope_id" field. +func ScopeIDGT(v string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldGT(FieldScopeID, v)) +} + +// ScopeIDGTE applies the GTE predicate on the "scope_id" field. +func ScopeIDGTE(v string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldGTE(FieldScopeID, v)) +} + +// ScopeIDLT applies the LT predicate on the "scope_id" field. +func ScopeIDLT(v string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldLT(FieldScopeID, v)) +} + +// ScopeIDLTE applies the LTE predicate on the "scope_id" field. +func ScopeIDLTE(v string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldLTE(FieldScopeID, v)) +} + +// ScopeIDContains applies the Contains predicate on the "scope_id" field. +func ScopeIDContains(v string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldContains(FieldScopeID, v)) +} + +// ScopeIDHasPrefix applies the HasPrefix predicate on the "scope_id" field. +func ScopeIDHasPrefix(v string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldHasPrefix(FieldScopeID, v)) +} + +// ScopeIDHasSuffix applies the HasSuffix predicate on the "scope_id" field. +func ScopeIDHasSuffix(v string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldHasSuffix(FieldScopeID, v)) +} + +// ScopeIDEqualFold applies the EqualFold predicate on the "scope_id" field. +func ScopeIDEqualFold(v string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldEqualFold(FieldScopeID, v)) +} + +// ScopeIDContainsFold applies the ContainsFold predicate on the "scope_id" field. +func ScopeIDContainsFold(v string) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldContainsFold(FieldScopeID, v)) +} + +// CreatedByEQ applies the EQ predicate on the "created_by" field. +func CreatedByEQ(v uuid.UUID) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldEQ(FieldCreatedBy, v)) +} + +// CreatedByNEQ applies the NEQ predicate on the "created_by" field. +func CreatedByNEQ(v uuid.UUID) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldNEQ(FieldCreatedBy, v)) +} + +// CreatedByIn applies the In predicate on the "created_by" field. +func CreatedByIn(vs ...uuid.UUID) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldIn(FieldCreatedBy, vs...)) +} + +// CreatedByNotIn applies the NotIn predicate on the "created_by" field. +func CreatedByNotIn(vs ...uuid.UUID) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldNotIn(FieldCreatedBy, vs...)) +} + +// CreatedByGT applies the GT predicate on the "created_by" field. +func CreatedByGT(v uuid.UUID) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldGT(FieldCreatedBy, v)) +} + +// CreatedByGTE applies the GTE predicate on the "created_by" field. +func CreatedByGTE(v uuid.UUID) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldGTE(FieldCreatedBy, v)) +} + +// CreatedByLT applies the LT predicate on the "created_by" field. +func CreatedByLT(v uuid.UUID) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldLT(FieldCreatedBy, v)) +} + +// CreatedByLTE applies the LTE predicate on the "created_by" field. +func CreatedByLTE(v uuid.UUID) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldLTE(FieldCreatedBy, v)) +} + +// ActiveVersionIDEQ applies the EQ predicate on the "active_version_id" field. +func ActiveVersionIDEQ(v uuid.UUID) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldEQ(FieldActiveVersionID, v)) +} + +// ActiveVersionIDNEQ applies the NEQ predicate on the "active_version_id" field. +func ActiveVersionIDNEQ(v uuid.UUID) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldNEQ(FieldActiveVersionID, v)) +} + +// ActiveVersionIDIn applies the In predicate on the "active_version_id" field. +func ActiveVersionIDIn(vs ...uuid.UUID) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldIn(FieldActiveVersionID, vs...)) +} + +// ActiveVersionIDNotIn applies the NotIn predicate on the "active_version_id" field. +func ActiveVersionIDNotIn(vs ...uuid.UUID) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldNotIn(FieldActiveVersionID, vs...)) +} + +// ActiveVersionIDGT applies the GT predicate on the "active_version_id" field. +func ActiveVersionIDGT(v uuid.UUID) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldGT(FieldActiveVersionID, v)) +} + +// ActiveVersionIDGTE applies the GTE predicate on the "active_version_id" field. +func ActiveVersionIDGTE(v uuid.UUID) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldGTE(FieldActiveVersionID, v)) +} + +// ActiveVersionIDLT applies the LT predicate on the "active_version_id" field. +func ActiveVersionIDLT(v uuid.UUID) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldLT(FieldActiveVersionID, v)) +} + +// ActiveVersionIDLTE applies the LTE predicate on the "active_version_id" field. +func ActiveVersionIDLTE(v uuid.UUID) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldLTE(FieldActiveVersionID, v)) +} + +// ActiveVersionIDIsNil applies the IsNil predicate on the "active_version_id" field. +func ActiveVersionIDIsNil() predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldIsNull(FieldActiveVersionID)) +} + +// ActiveVersionIDNotNil applies the NotNil predicate on the "active_version_id" field. +func ActiveVersionIDNotNil() predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldNotNull(FieldActiveVersionID)) +} + +// IsForceDeliveryEQ applies the EQ predicate on the "is_force_delivery" field. +func IsForceDeliveryEQ(v bool) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldEQ(FieldIsForceDelivery, v)) +} + +// IsForceDeliveryNEQ applies the NEQ predicate on the "is_force_delivery" field. +func IsForceDeliveryNEQ(v bool) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldNEQ(FieldIsForceDelivery, v)) +} + +// IsOrphanEQ applies the EQ predicate on the "is_orphan" field. +func IsOrphanEQ(v bool) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldEQ(FieldIsOrphan, v)) +} + +// IsOrphanNEQ applies the NEQ predicate on the "is_orphan" field. +func IsOrphanNEQ(v bool) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldNEQ(FieldIsOrphan, v)) +} + +// IsDeletedEQ applies the EQ predicate on the "is_deleted" field. +func IsDeletedEQ(v bool) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldEQ(FieldIsDeleted, v)) +} + +// IsDeletedNEQ applies the NEQ predicate on the "is_deleted" field. +func IsDeletedNEQ(v bool) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldNEQ(FieldIsDeleted, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.AgentSkill { + return predicate.AgentSkill(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// HasRepo applies the HasEdge predicate on the "repo" edge. +func HasRepo() predicate.AgentSkill { + return predicate.AgentSkill(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, RepoTable, RepoColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasRepoWith applies the HasEdge predicate on the "repo" edge with a given conditions (other predicates). +func HasRepoWith(preds ...predicate.AgentSkillRepo) predicate.AgentSkill { + return predicate.AgentSkill(func(s *sql.Selector) { + step := newRepoStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasVersions applies the HasEdge predicate on the "versions" edge. +func HasVersions() predicate.AgentSkill { + return predicate.AgentSkill(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, VersionsTable, VersionsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasVersionsWith applies the HasEdge predicate on the "versions" edge with a given conditions (other predicates). +func HasVersionsWith(preds ...predicate.AgentSkillVersion) predicate.AgentSkill { + return predicate.AgentSkill(func(s *sql.Selector) { + step := newVersionsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.AgentSkill) predicate.AgentSkill { + return predicate.AgentSkill(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.AgentSkill) predicate.AgentSkill { + return predicate.AgentSkill(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.AgentSkill) predicate.AgentSkill { + return predicate.AgentSkill(sql.NotPredicates(p)) +} diff --git a/backend/db/agentskill_create.go b/backend/db/agentskill_create.go new file mode 100644 index 00000000..1f13ff6a --- /dev/null +++ b/backend/db/agentskill_create.go @@ -0,0 +1,1290 @@ +// 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/agentskill" + "github.com/chaitin/MonkeyCode/backend/db/agentskillrepo" + "github.com/chaitin/MonkeyCode/backend/db/agentskillversion" + "github.com/google/uuid" +) + +// AgentSkillCreate is the builder for creating a AgentSkill entity. +type AgentSkillCreate struct { + config + mutation *AgentSkillMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetRepoID sets the "repo_id" field. +func (_c *AgentSkillCreate) SetRepoID(v uuid.UUID) *AgentSkillCreate { + _c.mutation.SetRepoID(v) + return _c +} + +// SetName sets the "name" field. +func (_c *AgentSkillCreate) SetName(v string) *AgentSkillCreate { + _c.mutation.SetName(v) + return _c +} + +// SetDescription sets the "description" field. +func (_c *AgentSkillCreate) SetDescription(v string) *AgentSkillCreate { + _c.mutation.SetDescription(v) + return _c +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_c *AgentSkillCreate) SetNillableDescription(v *string) *AgentSkillCreate { + if v != nil { + _c.SetDescription(*v) + } + return _c +} + +// SetScopeType sets the "scope_type" field. +func (_c *AgentSkillCreate) SetScopeType(v agentskill.ScopeType) *AgentSkillCreate { + _c.mutation.SetScopeType(v) + return _c +} + +// SetNillableScopeType sets the "scope_type" field if the given value is not nil. +func (_c *AgentSkillCreate) SetNillableScopeType(v *agentskill.ScopeType) *AgentSkillCreate { + if v != nil { + _c.SetScopeType(*v) + } + return _c +} + +// SetScopeID sets the "scope_id" field. +func (_c *AgentSkillCreate) SetScopeID(v string) *AgentSkillCreate { + _c.mutation.SetScopeID(v) + return _c +} + +// SetNillableScopeID sets the "scope_id" field if the given value is not nil. +func (_c *AgentSkillCreate) SetNillableScopeID(v *string) *AgentSkillCreate { + if v != nil { + _c.SetScopeID(*v) + } + return _c +} + +// SetCreatedBy sets the "created_by" field. +func (_c *AgentSkillCreate) SetCreatedBy(v uuid.UUID) *AgentSkillCreate { + _c.mutation.SetCreatedBy(v) + return _c +} + +// SetActiveVersionID sets the "active_version_id" field. +func (_c *AgentSkillCreate) SetActiveVersionID(v uuid.UUID) *AgentSkillCreate { + _c.mutation.SetActiveVersionID(v) + return _c +} + +// SetNillableActiveVersionID sets the "active_version_id" field if the given value is not nil. +func (_c *AgentSkillCreate) SetNillableActiveVersionID(v *uuid.UUID) *AgentSkillCreate { + if v != nil { + _c.SetActiveVersionID(*v) + } + return _c +} + +// SetIsForceDelivery sets the "is_force_delivery" field. +func (_c *AgentSkillCreate) SetIsForceDelivery(v bool) *AgentSkillCreate { + _c.mutation.SetIsForceDelivery(v) + return _c +} + +// SetNillableIsForceDelivery sets the "is_force_delivery" field if the given value is not nil. +func (_c *AgentSkillCreate) SetNillableIsForceDelivery(v *bool) *AgentSkillCreate { + if v != nil { + _c.SetIsForceDelivery(*v) + } + return _c +} + +// SetIsOrphan sets the "is_orphan" field. +func (_c *AgentSkillCreate) SetIsOrphan(v bool) *AgentSkillCreate { + _c.mutation.SetIsOrphan(v) + return _c +} + +// SetNillableIsOrphan sets the "is_orphan" field if the given value is not nil. +func (_c *AgentSkillCreate) SetNillableIsOrphan(v *bool) *AgentSkillCreate { + if v != nil { + _c.SetIsOrphan(*v) + } + return _c +} + +// SetIsDeleted sets the "is_deleted" field. +func (_c *AgentSkillCreate) SetIsDeleted(v bool) *AgentSkillCreate { + _c.mutation.SetIsDeleted(v) + return _c +} + +// SetNillableIsDeleted sets the "is_deleted" field if the given value is not nil. +func (_c *AgentSkillCreate) SetNillableIsDeleted(v *bool) *AgentSkillCreate { + if v != nil { + _c.SetIsDeleted(*v) + } + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *AgentSkillCreate) SetCreatedAt(v time.Time) *AgentSkillCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *AgentSkillCreate) SetNillableCreatedAt(v *time.Time) *AgentSkillCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *AgentSkillCreate) SetUpdatedAt(v time.Time) *AgentSkillCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *AgentSkillCreate) SetNillableUpdatedAt(v *time.Time) *AgentSkillCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *AgentSkillCreate) SetID(v uuid.UUID) *AgentSkillCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *AgentSkillCreate) SetNillableID(v *uuid.UUID) *AgentSkillCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetRepo sets the "repo" edge to the AgentSkillRepo entity. +func (_c *AgentSkillCreate) SetRepo(v *AgentSkillRepo) *AgentSkillCreate { + return _c.SetRepoID(v.ID) +} + +// AddVersionIDs adds the "versions" edge to the AgentSkillVersion entity by IDs. +func (_c *AgentSkillCreate) AddVersionIDs(ids ...uuid.UUID) *AgentSkillCreate { + _c.mutation.AddVersionIDs(ids...) + return _c +} + +// AddVersions adds the "versions" edges to the AgentSkillVersion entity. +func (_c *AgentSkillCreate) AddVersions(v ...*AgentSkillVersion) *AgentSkillCreate { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddVersionIDs(ids...) +} + +// Mutation returns the AgentSkillMutation object of the builder. +func (_c *AgentSkillCreate) Mutation() *AgentSkillMutation { + return _c.mutation +} + +// Save creates the AgentSkill in the database. +func (_c *AgentSkillCreate) Save(ctx context.Context) (*AgentSkill, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *AgentSkillCreate) SaveX(ctx context.Context) *AgentSkill { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *AgentSkillCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *AgentSkillCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *AgentSkillCreate) defaults() { + if _, ok := _c.mutation.ScopeType(); !ok { + v := agentskill.DefaultScopeType + _c.mutation.SetScopeType(v) + } + if _, ok := _c.mutation.ScopeID(); !ok { + v := agentskill.DefaultScopeID + _c.mutation.SetScopeID(v) + } + if _, ok := _c.mutation.IsForceDelivery(); !ok { + v := agentskill.DefaultIsForceDelivery + _c.mutation.SetIsForceDelivery(v) + } + if _, ok := _c.mutation.IsOrphan(); !ok { + v := agentskill.DefaultIsOrphan + _c.mutation.SetIsOrphan(v) + } + if _, ok := _c.mutation.IsDeleted(); !ok { + v := agentskill.DefaultIsDeleted + _c.mutation.SetIsDeleted(v) + } + if _, ok := _c.mutation.CreatedAt(); !ok { + v := agentskill.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := agentskill.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := agentskill.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *AgentSkillCreate) check() error { + if _, ok := _c.mutation.RepoID(); !ok { + return &ValidationError{Name: "repo_id", err: errors.New(`db: missing required field "AgentSkill.repo_id"`)} + } + if _, ok := _c.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`db: missing required field "AgentSkill.name"`)} + } + if v, ok := _c.mutation.Name(); ok { + if err := agentskill.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "AgentSkill.name": %w`, err)} + } + } + if _, ok := _c.mutation.ScopeType(); !ok { + return &ValidationError{Name: "scope_type", err: errors.New(`db: missing required field "AgentSkill.scope_type"`)} + } + if v, ok := _c.mutation.ScopeType(); ok { + if err := agentskill.ScopeTypeValidator(v); err != nil { + return &ValidationError{Name: "scope_type", err: fmt.Errorf(`db: validator failed for field "AgentSkill.scope_type": %w`, err)} + } + } + if _, ok := _c.mutation.ScopeID(); !ok { + return &ValidationError{Name: "scope_id", err: errors.New(`db: missing required field "AgentSkill.scope_id"`)} + } + if _, ok := _c.mutation.CreatedBy(); !ok { + return &ValidationError{Name: "created_by", err: errors.New(`db: missing required field "AgentSkill.created_by"`)} + } + if _, ok := _c.mutation.IsForceDelivery(); !ok { + return &ValidationError{Name: "is_force_delivery", err: errors.New(`db: missing required field "AgentSkill.is_force_delivery"`)} + } + if _, ok := _c.mutation.IsOrphan(); !ok { + return &ValidationError{Name: "is_orphan", err: errors.New(`db: missing required field "AgentSkill.is_orphan"`)} + } + if _, ok := _c.mutation.IsDeleted(); !ok { + return &ValidationError{Name: "is_deleted", err: errors.New(`db: missing required field "AgentSkill.is_deleted"`)} + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "AgentSkill.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "AgentSkill.updated_at"`)} + } + if len(_c.mutation.RepoIDs()) == 0 { + return &ValidationError{Name: "repo", err: errors.New(`db: missing required edge "AgentSkill.repo"`)} + } + return nil +} + +func (_c *AgentSkillCreate) sqlSave(ctx context.Context) (*AgentSkill, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.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 + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *AgentSkillCreate) createSpec() (*AgentSkill, *sqlgraph.CreateSpec) { + var ( + _node = &AgentSkill{config: _c.config} + _spec = sqlgraph.NewCreateSpec(agentskill.Table, sqlgraph.NewFieldSpec(agentskill.FieldID, field.TypeUUID)) + ) + _spec.OnConflict = _c.conflict + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = &id + } + if value, ok := _c.mutation.Name(); ok { + _spec.SetField(agentskill.FieldName, field.TypeString, value) + _node.Name = value + } + if value, ok := _c.mutation.Description(); ok { + _spec.SetField(agentskill.FieldDescription, field.TypeString, value) + _node.Description = value + } + if value, ok := _c.mutation.ScopeType(); ok { + _spec.SetField(agentskill.FieldScopeType, field.TypeEnum, value) + _node.ScopeType = value + } + if value, ok := _c.mutation.ScopeID(); ok { + _spec.SetField(agentskill.FieldScopeID, field.TypeString, value) + _node.ScopeID = value + } + if value, ok := _c.mutation.CreatedBy(); ok { + _spec.SetField(agentskill.FieldCreatedBy, field.TypeUUID, value) + _node.CreatedBy = value + } + if value, ok := _c.mutation.ActiveVersionID(); ok { + _spec.SetField(agentskill.FieldActiveVersionID, field.TypeUUID, value) + _node.ActiveVersionID = &value + } + if value, ok := _c.mutation.IsForceDelivery(); ok { + _spec.SetField(agentskill.FieldIsForceDelivery, field.TypeBool, value) + _node.IsForceDelivery = value + } + if value, ok := _c.mutation.IsOrphan(); ok { + _spec.SetField(agentskill.FieldIsOrphan, field.TypeBool, value) + _node.IsOrphan = value + } + if value, ok := _c.mutation.IsDeleted(); ok { + _spec.SetField(agentskill.FieldIsDeleted, field.TypeBool, value) + _node.IsDeleted = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(agentskill.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(agentskill.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if nodes := _c.mutation.RepoIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: agentskill.RepoTable, + Columns: []string{agentskill.RepoColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentskillrepo.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.RepoID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.VersionsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agentskill.VersionsTable, + Columns: []string{agentskill.VersionsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentskillversion.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.AgentSkill.Create(). +// SetRepoID(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.AgentSkillUpsert) { +// SetRepoID(v+v). +// }). +// Exec(ctx) +func (_c *AgentSkillCreate) OnConflict(opts ...sql.ConflictOption) *AgentSkillUpsertOne { + _c.conflict = opts + return &AgentSkillUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.AgentSkill.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *AgentSkillCreate) OnConflictColumns(columns ...string) *AgentSkillUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &AgentSkillUpsertOne{ + create: _c, + } +} + +type ( + // AgentSkillUpsertOne is the builder for "upsert"-ing + // one AgentSkill node. + AgentSkillUpsertOne struct { + create *AgentSkillCreate + } + + // AgentSkillUpsert is the "OnConflict" setter. + AgentSkillUpsert struct { + *sql.UpdateSet + } +) + +// SetRepoID sets the "repo_id" field. +func (u *AgentSkillUpsert) SetRepoID(v uuid.UUID) *AgentSkillUpsert { + u.Set(agentskill.FieldRepoID, v) + return u +} + +// UpdateRepoID sets the "repo_id" field to the value that was provided on create. +func (u *AgentSkillUpsert) UpdateRepoID() *AgentSkillUpsert { + u.SetExcluded(agentskill.FieldRepoID) + return u +} + +// SetName sets the "name" field. +func (u *AgentSkillUpsert) SetName(v string) *AgentSkillUpsert { + u.Set(agentskill.FieldName, v) + return u +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *AgentSkillUpsert) UpdateName() *AgentSkillUpsert { + u.SetExcluded(agentskill.FieldName) + return u +} + +// SetDescription sets the "description" field. +func (u *AgentSkillUpsert) SetDescription(v string) *AgentSkillUpsert { + u.Set(agentskill.FieldDescription, v) + return u +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *AgentSkillUpsert) UpdateDescription() *AgentSkillUpsert { + u.SetExcluded(agentskill.FieldDescription) + return u +} + +// ClearDescription clears the value of the "description" field. +func (u *AgentSkillUpsert) ClearDescription() *AgentSkillUpsert { + u.SetNull(agentskill.FieldDescription) + return u +} + +// SetScopeType sets the "scope_type" field. +func (u *AgentSkillUpsert) SetScopeType(v agentskill.ScopeType) *AgentSkillUpsert { + u.Set(agentskill.FieldScopeType, v) + return u +} + +// UpdateScopeType sets the "scope_type" field to the value that was provided on create. +func (u *AgentSkillUpsert) UpdateScopeType() *AgentSkillUpsert { + u.SetExcluded(agentskill.FieldScopeType) + return u +} + +// SetScopeID sets the "scope_id" field. +func (u *AgentSkillUpsert) SetScopeID(v string) *AgentSkillUpsert { + u.Set(agentskill.FieldScopeID, v) + return u +} + +// UpdateScopeID sets the "scope_id" field to the value that was provided on create. +func (u *AgentSkillUpsert) UpdateScopeID() *AgentSkillUpsert { + u.SetExcluded(agentskill.FieldScopeID) + return u +} + +// SetCreatedBy sets the "created_by" field. +func (u *AgentSkillUpsert) SetCreatedBy(v uuid.UUID) *AgentSkillUpsert { + u.Set(agentskill.FieldCreatedBy, v) + return u +} + +// UpdateCreatedBy sets the "created_by" field to the value that was provided on create. +func (u *AgentSkillUpsert) UpdateCreatedBy() *AgentSkillUpsert { + u.SetExcluded(agentskill.FieldCreatedBy) + return u +} + +// SetActiveVersionID sets the "active_version_id" field. +func (u *AgentSkillUpsert) SetActiveVersionID(v uuid.UUID) *AgentSkillUpsert { + u.Set(agentskill.FieldActiveVersionID, v) + return u +} + +// UpdateActiveVersionID sets the "active_version_id" field to the value that was provided on create. +func (u *AgentSkillUpsert) UpdateActiveVersionID() *AgentSkillUpsert { + u.SetExcluded(agentskill.FieldActiveVersionID) + return u +} + +// ClearActiveVersionID clears the value of the "active_version_id" field. +func (u *AgentSkillUpsert) ClearActiveVersionID() *AgentSkillUpsert { + u.SetNull(agentskill.FieldActiveVersionID) + return u +} + +// SetIsForceDelivery sets the "is_force_delivery" field. +func (u *AgentSkillUpsert) SetIsForceDelivery(v bool) *AgentSkillUpsert { + u.Set(agentskill.FieldIsForceDelivery, v) + return u +} + +// UpdateIsForceDelivery sets the "is_force_delivery" field to the value that was provided on create. +func (u *AgentSkillUpsert) UpdateIsForceDelivery() *AgentSkillUpsert { + u.SetExcluded(agentskill.FieldIsForceDelivery) + return u +} + +// SetIsOrphan sets the "is_orphan" field. +func (u *AgentSkillUpsert) SetIsOrphan(v bool) *AgentSkillUpsert { + u.Set(agentskill.FieldIsOrphan, v) + return u +} + +// UpdateIsOrphan sets the "is_orphan" field to the value that was provided on create. +func (u *AgentSkillUpsert) UpdateIsOrphan() *AgentSkillUpsert { + u.SetExcluded(agentskill.FieldIsOrphan) + return u +} + +// SetIsDeleted sets the "is_deleted" field. +func (u *AgentSkillUpsert) SetIsDeleted(v bool) *AgentSkillUpsert { + u.Set(agentskill.FieldIsDeleted, v) + return u +} + +// UpdateIsDeleted sets the "is_deleted" field to the value that was provided on create. +func (u *AgentSkillUpsert) UpdateIsDeleted() *AgentSkillUpsert { + u.SetExcluded(agentskill.FieldIsDeleted) + return u +} + +// SetCreatedAt sets the "created_at" field. +func (u *AgentSkillUpsert) SetCreatedAt(v time.Time) *AgentSkillUpsert { + u.Set(agentskill.FieldCreatedAt, v) + return u +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *AgentSkillUpsert) UpdateCreatedAt() *AgentSkillUpsert { + u.SetExcluded(agentskill.FieldCreatedAt) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *AgentSkillUpsert) SetUpdatedAt(v time.Time) *AgentSkillUpsert { + u.Set(agentskill.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *AgentSkillUpsert) UpdateUpdatedAt() *AgentSkillUpsert { + u.SetExcluded(agentskill.FieldUpdatedAt) + return u +} + +// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field. +// Using this option is equivalent to using: +// +// client.AgentSkill.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(agentskill.FieldID) +// }), +// ). +// Exec(ctx) +func (u *AgentSkillUpsertOne) UpdateNewValues() *AgentSkillUpsertOne { + 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(agentskill.FieldID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.AgentSkill.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *AgentSkillUpsertOne) Ignore() *AgentSkillUpsertOne { + 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 *AgentSkillUpsertOne) DoNothing() *AgentSkillUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the AgentSkillCreate.OnConflict +// documentation for more info. +func (u *AgentSkillUpsertOne) Update(set func(*AgentSkillUpsert)) *AgentSkillUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&AgentSkillUpsert{UpdateSet: update}) + })) + return u +} + +// SetRepoID sets the "repo_id" field. +func (u *AgentSkillUpsertOne) SetRepoID(v uuid.UUID) *AgentSkillUpsertOne { + return u.Update(func(s *AgentSkillUpsert) { + s.SetRepoID(v) + }) +} + +// UpdateRepoID sets the "repo_id" field to the value that was provided on create. +func (u *AgentSkillUpsertOne) UpdateRepoID() *AgentSkillUpsertOne { + return u.Update(func(s *AgentSkillUpsert) { + s.UpdateRepoID() + }) +} + +// SetName sets the "name" field. +func (u *AgentSkillUpsertOne) SetName(v string) *AgentSkillUpsertOne { + return u.Update(func(s *AgentSkillUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *AgentSkillUpsertOne) UpdateName() *AgentSkillUpsertOne { + return u.Update(func(s *AgentSkillUpsert) { + s.UpdateName() + }) +} + +// SetDescription sets the "description" field. +func (u *AgentSkillUpsertOne) SetDescription(v string) *AgentSkillUpsertOne { + return u.Update(func(s *AgentSkillUpsert) { + s.SetDescription(v) + }) +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *AgentSkillUpsertOne) UpdateDescription() *AgentSkillUpsertOne { + return u.Update(func(s *AgentSkillUpsert) { + s.UpdateDescription() + }) +} + +// ClearDescription clears the value of the "description" field. +func (u *AgentSkillUpsertOne) ClearDescription() *AgentSkillUpsertOne { + return u.Update(func(s *AgentSkillUpsert) { + s.ClearDescription() + }) +} + +// SetScopeType sets the "scope_type" field. +func (u *AgentSkillUpsertOne) SetScopeType(v agentskill.ScopeType) *AgentSkillUpsertOne { + return u.Update(func(s *AgentSkillUpsert) { + s.SetScopeType(v) + }) +} + +// UpdateScopeType sets the "scope_type" field to the value that was provided on create. +func (u *AgentSkillUpsertOne) UpdateScopeType() *AgentSkillUpsertOne { + return u.Update(func(s *AgentSkillUpsert) { + s.UpdateScopeType() + }) +} + +// SetScopeID sets the "scope_id" field. +func (u *AgentSkillUpsertOne) SetScopeID(v string) *AgentSkillUpsertOne { + return u.Update(func(s *AgentSkillUpsert) { + s.SetScopeID(v) + }) +} + +// UpdateScopeID sets the "scope_id" field to the value that was provided on create. +func (u *AgentSkillUpsertOne) UpdateScopeID() *AgentSkillUpsertOne { + return u.Update(func(s *AgentSkillUpsert) { + s.UpdateScopeID() + }) +} + +// SetCreatedBy sets the "created_by" field. +func (u *AgentSkillUpsertOne) SetCreatedBy(v uuid.UUID) *AgentSkillUpsertOne { + return u.Update(func(s *AgentSkillUpsert) { + s.SetCreatedBy(v) + }) +} + +// UpdateCreatedBy sets the "created_by" field to the value that was provided on create. +func (u *AgentSkillUpsertOne) UpdateCreatedBy() *AgentSkillUpsertOne { + return u.Update(func(s *AgentSkillUpsert) { + s.UpdateCreatedBy() + }) +} + +// SetActiveVersionID sets the "active_version_id" field. +func (u *AgentSkillUpsertOne) SetActiveVersionID(v uuid.UUID) *AgentSkillUpsertOne { + return u.Update(func(s *AgentSkillUpsert) { + s.SetActiveVersionID(v) + }) +} + +// UpdateActiveVersionID sets the "active_version_id" field to the value that was provided on create. +func (u *AgentSkillUpsertOne) UpdateActiveVersionID() *AgentSkillUpsertOne { + return u.Update(func(s *AgentSkillUpsert) { + s.UpdateActiveVersionID() + }) +} + +// ClearActiveVersionID clears the value of the "active_version_id" field. +func (u *AgentSkillUpsertOne) ClearActiveVersionID() *AgentSkillUpsertOne { + return u.Update(func(s *AgentSkillUpsert) { + s.ClearActiveVersionID() + }) +} + +// SetIsForceDelivery sets the "is_force_delivery" field. +func (u *AgentSkillUpsertOne) SetIsForceDelivery(v bool) *AgentSkillUpsertOne { + return u.Update(func(s *AgentSkillUpsert) { + s.SetIsForceDelivery(v) + }) +} + +// UpdateIsForceDelivery sets the "is_force_delivery" field to the value that was provided on create. +func (u *AgentSkillUpsertOne) UpdateIsForceDelivery() *AgentSkillUpsertOne { + return u.Update(func(s *AgentSkillUpsert) { + s.UpdateIsForceDelivery() + }) +} + +// SetIsOrphan sets the "is_orphan" field. +func (u *AgentSkillUpsertOne) SetIsOrphan(v bool) *AgentSkillUpsertOne { + return u.Update(func(s *AgentSkillUpsert) { + s.SetIsOrphan(v) + }) +} + +// UpdateIsOrphan sets the "is_orphan" field to the value that was provided on create. +func (u *AgentSkillUpsertOne) UpdateIsOrphan() *AgentSkillUpsertOne { + return u.Update(func(s *AgentSkillUpsert) { + s.UpdateIsOrphan() + }) +} + +// SetIsDeleted sets the "is_deleted" field. +func (u *AgentSkillUpsertOne) SetIsDeleted(v bool) *AgentSkillUpsertOne { + return u.Update(func(s *AgentSkillUpsert) { + s.SetIsDeleted(v) + }) +} + +// UpdateIsDeleted sets the "is_deleted" field to the value that was provided on create. +func (u *AgentSkillUpsertOne) UpdateIsDeleted() *AgentSkillUpsertOne { + return u.Update(func(s *AgentSkillUpsert) { + s.UpdateIsDeleted() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *AgentSkillUpsertOne) SetCreatedAt(v time.Time) *AgentSkillUpsertOne { + return u.Update(func(s *AgentSkillUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *AgentSkillUpsertOne) UpdateCreatedAt() *AgentSkillUpsertOne { + return u.Update(func(s *AgentSkillUpsert) { + s.UpdateCreatedAt() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *AgentSkillUpsertOne) SetUpdatedAt(v time.Time) *AgentSkillUpsertOne { + return u.Update(func(s *AgentSkillUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *AgentSkillUpsertOne) UpdateUpdatedAt() *AgentSkillUpsertOne { + return u.Update(func(s *AgentSkillUpsert) { + s.UpdateUpdatedAt() + }) +} + +// Exec executes the query. +func (u *AgentSkillUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for AgentSkillCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *AgentSkillUpsertOne) 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 *AgentSkillUpsertOne) 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: AgentSkillUpsertOne.ID is not supported by MySQL driver. Use AgentSkillUpsertOne.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 *AgentSkillUpsertOne) IDX(ctx context.Context) uuid.UUID { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// AgentSkillCreateBulk is the builder for creating many AgentSkill entities in bulk. +type AgentSkillCreateBulk struct { + config + err error + builders []*AgentSkillCreate + conflict []sql.ConflictOption +} + +// Save creates the AgentSkill entities in the database. +func (_c *AgentSkillCreateBulk) Save(ctx context.Context) ([]*AgentSkill, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*AgentSkill, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*AgentSkillMutation) + 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, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = _c.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.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, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *AgentSkillCreateBulk) SaveX(ctx context.Context) []*AgentSkill { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *AgentSkillCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *AgentSkillCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.AgentSkill.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.AgentSkillUpsert) { +// SetRepoID(v+v). +// }). +// Exec(ctx) +func (_c *AgentSkillCreateBulk) OnConflict(opts ...sql.ConflictOption) *AgentSkillUpsertBulk { + _c.conflict = opts + return &AgentSkillUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.AgentSkill.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *AgentSkillCreateBulk) OnConflictColumns(columns ...string) *AgentSkillUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &AgentSkillUpsertBulk{ + create: _c, + } +} + +// AgentSkillUpsertBulk is the builder for "upsert"-ing +// a bulk of AgentSkill nodes. +type AgentSkillUpsertBulk struct { + create *AgentSkillCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.AgentSkill.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(agentskill.FieldID) +// }), +// ). +// Exec(ctx) +func (u *AgentSkillUpsertBulk) UpdateNewValues() *AgentSkillUpsertBulk { + 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(agentskill.FieldID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.AgentSkill.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *AgentSkillUpsertBulk) Ignore() *AgentSkillUpsertBulk { + 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 *AgentSkillUpsertBulk) DoNothing() *AgentSkillUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the AgentSkillCreateBulk.OnConflict +// documentation for more info. +func (u *AgentSkillUpsertBulk) Update(set func(*AgentSkillUpsert)) *AgentSkillUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&AgentSkillUpsert{UpdateSet: update}) + })) + return u +} + +// SetRepoID sets the "repo_id" field. +func (u *AgentSkillUpsertBulk) SetRepoID(v uuid.UUID) *AgentSkillUpsertBulk { + return u.Update(func(s *AgentSkillUpsert) { + s.SetRepoID(v) + }) +} + +// UpdateRepoID sets the "repo_id" field to the value that was provided on create. +func (u *AgentSkillUpsertBulk) UpdateRepoID() *AgentSkillUpsertBulk { + return u.Update(func(s *AgentSkillUpsert) { + s.UpdateRepoID() + }) +} + +// SetName sets the "name" field. +func (u *AgentSkillUpsertBulk) SetName(v string) *AgentSkillUpsertBulk { + return u.Update(func(s *AgentSkillUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *AgentSkillUpsertBulk) UpdateName() *AgentSkillUpsertBulk { + return u.Update(func(s *AgentSkillUpsert) { + s.UpdateName() + }) +} + +// SetDescription sets the "description" field. +func (u *AgentSkillUpsertBulk) SetDescription(v string) *AgentSkillUpsertBulk { + return u.Update(func(s *AgentSkillUpsert) { + s.SetDescription(v) + }) +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *AgentSkillUpsertBulk) UpdateDescription() *AgentSkillUpsertBulk { + return u.Update(func(s *AgentSkillUpsert) { + s.UpdateDescription() + }) +} + +// ClearDescription clears the value of the "description" field. +func (u *AgentSkillUpsertBulk) ClearDescription() *AgentSkillUpsertBulk { + return u.Update(func(s *AgentSkillUpsert) { + s.ClearDescription() + }) +} + +// SetScopeType sets the "scope_type" field. +func (u *AgentSkillUpsertBulk) SetScopeType(v agentskill.ScopeType) *AgentSkillUpsertBulk { + return u.Update(func(s *AgentSkillUpsert) { + s.SetScopeType(v) + }) +} + +// UpdateScopeType sets the "scope_type" field to the value that was provided on create. +func (u *AgentSkillUpsertBulk) UpdateScopeType() *AgentSkillUpsertBulk { + return u.Update(func(s *AgentSkillUpsert) { + s.UpdateScopeType() + }) +} + +// SetScopeID sets the "scope_id" field. +func (u *AgentSkillUpsertBulk) SetScopeID(v string) *AgentSkillUpsertBulk { + return u.Update(func(s *AgentSkillUpsert) { + s.SetScopeID(v) + }) +} + +// UpdateScopeID sets the "scope_id" field to the value that was provided on create. +func (u *AgentSkillUpsertBulk) UpdateScopeID() *AgentSkillUpsertBulk { + return u.Update(func(s *AgentSkillUpsert) { + s.UpdateScopeID() + }) +} + +// SetCreatedBy sets the "created_by" field. +func (u *AgentSkillUpsertBulk) SetCreatedBy(v uuid.UUID) *AgentSkillUpsertBulk { + return u.Update(func(s *AgentSkillUpsert) { + s.SetCreatedBy(v) + }) +} + +// UpdateCreatedBy sets the "created_by" field to the value that was provided on create. +func (u *AgentSkillUpsertBulk) UpdateCreatedBy() *AgentSkillUpsertBulk { + return u.Update(func(s *AgentSkillUpsert) { + s.UpdateCreatedBy() + }) +} + +// SetActiveVersionID sets the "active_version_id" field. +func (u *AgentSkillUpsertBulk) SetActiveVersionID(v uuid.UUID) *AgentSkillUpsertBulk { + return u.Update(func(s *AgentSkillUpsert) { + s.SetActiveVersionID(v) + }) +} + +// UpdateActiveVersionID sets the "active_version_id" field to the value that was provided on create. +func (u *AgentSkillUpsertBulk) UpdateActiveVersionID() *AgentSkillUpsertBulk { + return u.Update(func(s *AgentSkillUpsert) { + s.UpdateActiveVersionID() + }) +} + +// ClearActiveVersionID clears the value of the "active_version_id" field. +func (u *AgentSkillUpsertBulk) ClearActiveVersionID() *AgentSkillUpsertBulk { + return u.Update(func(s *AgentSkillUpsert) { + s.ClearActiveVersionID() + }) +} + +// SetIsForceDelivery sets the "is_force_delivery" field. +func (u *AgentSkillUpsertBulk) SetIsForceDelivery(v bool) *AgentSkillUpsertBulk { + return u.Update(func(s *AgentSkillUpsert) { + s.SetIsForceDelivery(v) + }) +} + +// UpdateIsForceDelivery sets the "is_force_delivery" field to the value that was provided on create. +func (u *AgentSkillUpsertBulk) UpdateIsForceDelivery() *AgentSkillUpsertBulk { + return u.Update(func(s *AgentSkillUpsert) { + s.UpdateIsForceDelivery() + }) +} + +// SetIsOrphan sets the "is_orphan" field. +func (u *AgentSkillUpsertBulk) SetIsOrphan(v bool) *AgentSkillUpsertBulk { + return u.Update(func(s *AgentSkillUpsert) { + s.SetIsOrphan(v) + }) +} + +// UpdateIsOrphan sets the "is_orphan" field to the value that was provided on create. +func (u *AgentSkillUpsertBulk) UpdateIsOrphan() *AgentSkillUpsertBulk { + return u.Update(func(s *AgentSkillUpsert) { + s.UpdateIsOrphan() + }) +} + +// SetIsDeleted sets the "is_deleted" field. +func (u *AgentSkillUpsertBulk) SetIsDeleted(v bool) *AgentSkillUpsertBulk { + return u.Update(func(s *AgentSkillUpsert) { + s.SetIsDeleted(v) + }) +} + +// UpdateIsDeleted sets the "is_deleted" field to the value that was provided on create. +func (u *AgentSkillUpsertBulk) UpdateIsDeleted() *AgentSkillUpsertBulk { + return u.Update(func(s *AgentSkillUpsert) { + s.UpdateIsDeleted() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *AgentSkillUpsertBulk) SetCreatedAt(v time.Time) *AgentSkillUpsertBulk { + return u.Update(func(s *AgentSkillUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *AgentSkillUpsertBulk) UpdateCreatedAt() *AgentSkillUpsertBulk { + return u.Update(func(s *AgentSkillUpsert) { + s.UpdateCreatedAt() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *AgentSkillUpsertBulk) SetUpdatedAt(v time.Time) *AgentSkillUpsertBulk { + return u.Update(func(s *AgentSkillUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *AgentSkillUpsertBulk) UpdateUpdatedAt() *AgentSkillUpsertBulk { + return u.Update(func(s *AgentSkillUpsert) { + s.UpdateUpdatedAt() + }) +} + +// Exec executes the query. +func (u *AgentSkillUpsertBulk) 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 AgentSkillCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for AgentSkillCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *AgentSkillUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/agentskill_delete.go b/backend/db/agentskill_delete.go new file mode 100644 index 00000000..39d5784a --- /dev/null +++ b/backend/db/agentskill_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/agentskill" + "github.com/chaitin/MonkeyCode/backend/db/predicate" +) + +// AgentSkillDelete is the builder for deleting a AgentSkill entity. +type AgentSkillDelete struct { + config + hooks []Hook + mutation *AgentSkillMutation +} + +// Where appends a list predicates to the AgentSkillDelete builder. +func (_d *AgentSkillDelete) Where(ps ...predicate.AgentSkill) *AgentSkillDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *AgentSkillDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *AgentSkillDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *AgentSkillDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(agentskill.Table, sqlgraph.NewFieldSpec(agentskill.FieldID, field.TypeUUID)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// AgentSkillDeleteOne is the builder for deleting a single AgentSkill entity. +type AgentSkillDeleteOne struct { + _d *AgentSkillDelete +} + +// Where appends a list predicates to the AgentSkillDelete builder. +func (_d *AgentSkillDeleteOne) Where(ps ...predicate.AgentSkill) *AgentSkillDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *AgentSkillDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{agentskill.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *AgentSkillDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/agentskill_query.go b/backend/db/agentskill_query.go new file mode 100644 index 00000000..40bc8be9 --- /dev/null +++ b/backend/db/agentskill_query.go @@ -0,0 +1,732 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "database/sql/driver" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/agentskill" + "github.com/chaitin/MonkeyCode/backend/db/agentskillrepo" + "github.com/chaitin/MonkeyCode/backend/db/agentskillversion" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/google/uuid" +) + +// AgentSkillQuery is the builder for querying AgentSkill entities. +type AgentSkillQuery struct { + config + ctx *QueryContext + order []agentskill.OrderOption + inters []Interceptor + predicates []predicate.AgentSkill + withRepo *AgentSkillRepoQuery + withVersions *AgentSkillVersionQuery + 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 AgentSkillQuery builder. +func (_q *AgentSkillQuery) Where(ps ...predicate.AgentSkill) *AgentSkillQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *AgentSkillQuery) Limit(limit int) *AgentSkillQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *AgentSkillQuery) Offset(offset int) *AgentSkillQuery { + _q.ctx.Offset = &offset + return _q +} + +// 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 (_q *AgentSkillQuery) Unique(unique bool) *AgentSkillQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *AgentSkillQuery) Order(o ...agentskill.OrderOption) *AgentSkillQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryRepo chains the current query on the "repo" edge. +func (_q *AgentSkillQuery) QueryRepo() *AgentSkillRepoQuery { + query := (&AgentSkillRepoClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(agentskill.Table, agentskill.FieldID, selector), + sqlgraph.To(agentskillrepo.Table, agentskillrepo.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, agentskill.RepoTable, agentskill.RepoColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryVersions chains the current query on the "versions" edge. +func (_q *AgentSkillQuery) QueryVersions() *AgentSkillVersionQuery { + query := (&AgentSkillVersionClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(agentskill.Table, agentskill.FieldID, selector), + sqlgraph.To(agentskillversion.Table, agentskillversion.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, agentskill.VersionsTable, agentskill.VersionsColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first AgentSkill entity from the query. +// Returns a *NotFoundError when no AgentSkill was found. +func (_q *AgentSkillQuery) First(ctx context.Context) (*AgentSkill, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{agentskill.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *AgentSkillQuery) FirstX(ctx context.Context) *AgentSkill { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first AgentSkill ID from the query. +// Returns a *NotFoundError when no AgentSkill ID was found. +func (_q *AgentSkillQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{agentskill.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *AgentSkillQuery) FirstIDX(ctx context.Context) uuid.UUID { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single AgentSkill entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one AgentSkill entity is found. +// Returns a *NotFoundError when no AgentSkill entities are found. +func (_q *AgentSkillQuery) Only(ctx context.Context) (*AgentSkill, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{agentskill.Label} + default: + return nil, &NotSingularError{agentskill.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *AgentSkillQuery) OnlyX(ctx context.Context) *AgentSkill { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only AgentSkill ID in the query. +// Returns a *NotSingularError when more than one AgentSkill ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *AgentSkillQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{agentskill.Label} + default: + err = &NotSingularError{agentskill.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *AgentSkillQuery) OnlyIDX(ctx context.Context) uuid.UUID { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of AgentSkills. +func (_q *AgentSkillQuery) All(ctx context.Context) ([]*AgentSkill, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*AgentSkill, *AgentSkillQuery]() + return withInterceptors[[]*AgentSkill](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *AgentSkillQuery) AllX(ctx context.Context) []*AgentSkill { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of AgentSkill IDs. +func (_q *AgentSkillQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(agentskill.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *AgentSkillQuery) IDsX(ctx context.Context) []uuid.UUID { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *AgentSkillQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*AgentSkillQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *AgentSkillQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *AgentSkillQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.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 (_q *AgentSkillQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the AgentSkillQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *AgentSkillQuery) Clone() *AgentSkillQuery { + if _q == nil { + return nil + } + return &AgentSkillQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]agentskill.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.AgentSkill{}, _q.predicates...), + withRepo: _q.withRepo.Clone(), + withVersions: _q.withVersions.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + modifiers: append([]func(*sql.Selector){}, _q.modifiers...), + } +} + +// WithRepo tells the query-builder to eager-load the nodes that are connected to +// the "repo" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *AgentSkillQuery) WithRepo(opts ...func(*AgentSkillRepoQuery)) *AgentSkillQuery { + query := (&AgentSkillRepoClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withRepo = query + return _q +} + +// WithVersions tells the query-builder to eager-load the nodes that are connected to +// the "versions" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *AgentSkillQuery) WithVersions(opts ...func(*AgentSkillVersionQuery)) *AgentSkillQuery { + query := (&AgentSkillVersionClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withVersions = query + return _q +} + +// 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 { +// RepoID uuid.UUID `json:"repo_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.AgentSkill.Query(). +// GroupBy(agentskill.FieldRepoID). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *AgentSkillQuery) GroupBy(field string, fields ...string) *AgentSkillGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &AgentSkillGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = agentskill.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 { +// RepoID uuid.UUID `json:"repo_id,omitempty"` +// } +// +// client.AgentSkill.Query(). +// Select(agentskill.FieldRepoID). +// Scan(ctx, &v) +func (_q *AgentSkillQuery) Select(fields ...string) *AgentSkillSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &AgentSkillSelect{AgentSkillQuery: _q} + sbuild.label = agentskill.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a AgentSkillSelect configured with the given aggregations. +func (_q *AgentSkillQuery) Aggregate(fns ...AggregateFunc) *AgentSkillSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *AgentSkillQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.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, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !agentskill.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *AgentSkillQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*AgentSkill, error) { + var ( + nodes = []*AgentSkill{} + _spec = _q.querySpec() + loadedTypes = [2]bool{ + _q.withRepo != nil, + _q.withVersions != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*AgentSkill).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &AgentSkill{config: _q.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := _q.withRepo; query != nil { + if err := _q.loadRepo(ctx, query, nodes, nil, + func(n *AgentSkill, e *AgentSkillRepo) { n.Edges.Repo = e }); err != nil { + return nil, err + } + } + if query := _q.withVersions; query != nil { + if err := _q.loadVersions(ctx, query, nodes, + func(n *AgentSkill) { n.Edges.Versions = []*AgentSkillVersion{} }, + func(n *AgentSkill, e *AgentSkillVersion) { n.Edges.Versions = append(n.Edges.Versions, e) }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *AgentSkillQuery) loadRepo(ctx context.Context, query *AgentSkillRepoQuery, nodes []*AgentSkill, init func(*AgentSkill), assign func(*AgentSkill, *AgentSkillRepo)) error { + ids := make([]uuid.UUID, 0, len(nodes)) + nodeids := make(map[uuid.UUID][]*AgentSkill) + for i := range nodes { + fk := nodes[i].RepoID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(agentskillrepo.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return fmt.Errorf(`unexpected foreign-key "repo_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *AgentSkillQuery) loadVersions(ctx context.Context, query *AgentSkillVersionQuery, nodes []*AgentSkill, init func(*AgentSkill), assign func(*AgentSkill, *AgentSkillVersion)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[uuid.UUID]*AgentSkill) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) + } + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(agentskillversion.FieldResourceID) + } + query.Where(predicate.AgentSkillVersion(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(agentskill.VersionsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.ResourceID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "resource_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} + +func (_q *AgentSkillQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *AgentSkillQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(agentskill.Table, agentskill.Columns, sqlgraph.NewFieldSpec(agentskill.FieldID, field.TypeUUID)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, agentskill.FieldID) + for i := range fields { + if fields[i] != agentskill.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withRepo != nil { + _spec.Node.AddColumnOnce(agentskill.FieldRepoID) + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *AgentSkillQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(agentskill.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = agentskill.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, m := range _q.modifiers { + m(selector) + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.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 := _q.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 (_q *AgentSkillQuery) ForUpdate(opts ...sql.LockOption) *AgentSkillQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForUpdate(opts...) + }) + return _q +} + +// 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 (_q *AgentSkillQuery) ForShare(opts ...sql.LockOption) *AgentSkillQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (_q *AgentSkillQuery) Modify(modifiers ...func(s *sql.Selector)) *AgentSkillSelect { + _q.modifiers = append(_q.modifiers, modifiers...) + return _q.Select() +} + +// AgentSkillGroupBy is the group-by builder for AgentSkill entities. +type AgentSkillGroupBy struct { + selector + build *AgentSkillQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *AgentSkillGroupBy) Aggregate(fns ...AggregateFunc) *AgentSkillGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *AgentSkillGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*AgentSkillQuery, *AgentSkillGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *AgentSkillGroupBy) sqlScan(ctx context.Context, root *AgentSkillQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// AgentSkillSelect is the builder for selecting fields of AgentSkill entities. +type AgentSkillSelect struct { + *AgentSkillQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *AgentSkillSelect) Aggregate(fns ...AggregateFunc) *AgentSkillSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *AgentSkillSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*AgentSkillQuery, *AgentSkillSelect](ctx, _s.AgentSkillQuery, _s, _s.inters, v) +} + +func (_s *AgentSkillSelect) sqlScan(ctx context.Context, root *AgentSkillQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.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 := _s.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 (_s *AgentSkillSelect) Modify(modifiers ...func(s *sql.Selector)) *AgentSkillSelect { + _s.modifiers = append(_s.modifiers, modifiers...) + return _s +} diff --git a/backend/db/agentskill_update.go b/backend/db/agentskill_update.go new file mode 100644 index 00000000..daeb6dd7 --- /dev/null +++ b/backend/db/agentskill_update.go @@ -0,0 +1,919 @@ +// 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/agentskill" + "github.com/chaitin/MonkeyCode/backend/db/agentskillrepo" + "github.com/chaitin/MonkeyCode/backend/db/agentskillversion" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/google/uuid" +) + +// AgentSkillUpdate is the builder for updating AgentSkill entities. +type AgentSkillUpdate struct { + config + hooks []Hook + mutation *AgentSkillMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the AgentSkillUpdate builder. +func (_u *AgentSkillUpdate) Where(ps ...predicate.AgentSkill) *AgentSkillUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetRepoID sets the "repo_id" field. +func (_u *AgentSkillUpdate) SetRepoID(v uuid.UUID) *AgentSkillUpdate { + _u.mutation.SetRepoID(v) + return _u +} + +// SetNillableRepoID sets the "repo_id" field if the given value is not nil. +func (_u *AgentSkillUpdate) SetNillableRepoID(v *uuid.UUID) *AgentSkillUpdate { + if v != nil { + _u.SetRepoID(*v) + } + return _u +} + +// SetName sets the "name" field. +func (_u *AgentSkillUpdate) SetName(v string) *AgentSkillUpdate { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *AgentSkillUpdate) SetNillableName(v *string) *AgentSkillUpdate { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetDescription sets the "description" field. +func (_u *AgentSkillUpdate) SetDescription(v string) *AgentSkillUpdate { + _u.mutation.SetDescription(v) + return _u +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_u *AgentSkillUpdate) SetNillableDescription(v *string) *AgentSkillUpdate { + if v != nil { + _u.SetDescription(*v) + } + return _u +} + +// ClearDescription clears the value of the "description" field. +func (_u *AgentSkillUpdate) ClearDescription() *AgentSkillUpdate { + _u.mutation.ClearDescription() + return _u +} + +// SetScopeType sets the "scope_type" field. +func (_u *AgentSkillUpdate) SetScopeType(v agentskill.ScopeType) *AgentSkillUpdate { + _u.mutation.SetScopeType(v) + return _u +} + +// SetNillableScopeType sets the "scope_type" field if the given value is not nil. +func (_u *AgentSkillUpdate) SetNillableScopeType(v *agentskill.ScopeType) *AgentSkillUpdate { + if v != nil { + _u.SetScopeType(*v) + } + return _u +} + +// SetScopeID sets the "scope_id" field. +func (_u *AgentSkillUpdate) SetScopeID(v string) *AgentSkillUpdate { + _u.mutation.SetScopeID(v) + return _u +} + +// SetNillableScopeID sets the "scope_id" field if the given value is not nil. +func (_u *AgentSkillUpdate) SetNillableScopeID(v *string) *AgentSkillUpdate { + if v != nil { + _u.SetScopeID(*v) + } + return _u +} + +// SetCreatedBy sets the "created_by" field. +func (_u *AgentSkillUpdate) SetCreatedBy(v uuid.UUID) *AgentSkillUpdate { + _u.mutation.SetCreatedBy(v) + return _u +} + +// SetNillableCreatedBy sets the "created_by" field if the given value is not nil. +func (_u *AgentSkillUpdate) SetNillableCreatedBy(v *uuid.UUID) *AgentSkillUpdate { + if v != nil { + _u.SetCreatedBy(*v) + } + return _u +} + +// SetActiveVersionID sets the "active_version_id" field. +func (_u *AgentSkillUpdate) SetActiveVersionID(v uuid.UUID) *AgentSkillUpdate { + _u.mutation.SetActiveVersionID(v) + return _u +} + +// SetNillableActiveVersionID sets the "active_version_id" field if the given value is not nil. +func (_u *AgentSkillUpdate) SetNillableActiveVersionID(v *uuid.UUID) *AgentSkillUpdate { + if v != nil { + _u.SetActiveVersionID(*v) + } + return _u +} + +// ClearActiveVersionID clears the value of the "active_version_id" field. +func (_u *AgentSkillUpdate) ClearActiveVersionID() *AgentSkillUpdate { + _u.mutation.ClearActiveVersionID() + return _u +} + +// SetIsForceDelivery sets the "is_force_delivery" field. +func (_u *AgentSkillUpdate) SetIsForceDelivery(v bool) *AgentSkillUpdate { + _u.mutation.SetIsForceDelivery(v) + return _u +} + +// SetNillableIsForceDelivery sets the "is_force_delivery" field if the given value is not nil. +func (_u *AgentSkillUpdate) SetNillableIsForceDelivery(v *bool) *AgentSkillUpdate { + if v != nil { + _u.SetIsForceDelivery(*v) + } + return _u +} + +// SetIsOrphan sets the "is_orphan" field. +func (_u *AgentSkillUpdate) SetIsOrphan(v bool) *AgentSkillUpdate { + _u.mutation.SetIsOrphan(v) + return _u +} + +// SetNillableIsOrphan sets the "is_orphan" field if the given value is not nil. +func (_u *AgentSkillUpdate) SetNillableIsOrphan(v *bool) *AgentSkillUpdate { + if v != nil { + _u.SetIsOrphan(*v) + } + return _u +} + +// SetIsDeleted sets the "is_deleted" field. +func (_u *AgentSkillUpdate) SetIsDeleted(v bool) *AgentSkillUpdate { + _u.mutation.SetIsDeleted(v) + return _u +} + +// SetNillableIsDeleted sets the "is_deleted" field if the given value is not nil. +func (_u *AgentSkillUpdate) SetNillableIsDeleted(v *bool) *AgentSkillUpdate { + if v != nil { + _u.SetIsDeleted(*v) + } + return _u +} + +// SetCreatedAt sets the "created_at" field. +func (_u *AgentSkillUpdate) SetCreatedAt(v time.Time) *AgentSkillUpdate { + _u.mutation.SetCreatedAt(v) + return _u +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_u *AgentSkillUpdate) SetNillableCreatedAt(v *time.Time) *AgentSkillUpdate { + if v != nil { + _u.SetCreatedAt(*v) + } + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *AgentSkillUpdate) SetUpdatedAt(v time.Time) *AgentSkillUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetRepo sets the "repo" edge to the AgentSkillRepo entity. +func (_u *AgentSkillUpdate) SetRepo(v *AgentSkillRepo) *AgentSkillUpdate { + return _u.SetRepoID(v.ID) +} + +// AddVersionIDs adds the "versions" edge to the AgentSkillVersion entity by IDs. +func (_u *AgentSkillUpdate) AddVersionIDs(ids ...uuid.UUID) *AgentSkillUpdate { + _u.mutation.AddVersionIDs(ids...) + return _u +} + +// AddVersions adds the "versions" edges to the AgentSkillVersion entity. +func (_u *AgentSkillUpdate) AddVersions(v ...*AgentSkillVersion) *AgentSkillUpdate { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddVersionIDs(ids...) +} + +// Mutation returns the AgentSkillMutation object of the builder. +func (_u *AgentSkillUpdate) Mutation() *AgentSkillMutation { + return _u.mutation +} + +// ClearRepo clears the "repo" edge to the AgentSkillRepo entity. +func (_u *AgentSkillUpdate) ClearRepo() *AgentSkillUpdate { + _u.mutation.ClearRepo() + return _u +} + +// ClearVersions clears all "versions" edges to the AgentSkillVersion entity. +func (_u *AgentSkillUpdate) ClearVersions() *AgentSkillUpdate { + _u.mutation.ClearVersions() + return _u +} + +// RemoveVersionIDs removes the "versions" edge to AgentSkillVersion entities by IDs. +func (_u *AgentSkillUpdate) RemoveVersionIDs(ids ...uuid.UUID) *AgentSkillUpdate { + _u.mutation.RemoveVersionIDs(ids...) + return _u +} + +// RemoveVersions removes "versions" edges to AgentSkillVersion entities. +func (_u *AgentSkillUpdate) RemoveVersions(v ...*AgentSkillVersion) *AgentSkillUpdate { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveVersionIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *AgentSkillUpdate) Save(ctx context.Context) (int, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *AgentSkillUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *AgentSkillUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *AgentSkillUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_u *AgentSkillUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := agentskill.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *AgentSkillUpdate) check() error { + if v, ok := _u.mutation.Name(); ok { + if err := agentskill.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "AgentSkill.name": %w`, err)} + } + } + if v, ok := _u.mutation.ScopeType(); ok { + if err := agentskill.ScopeTypeValidator(v); err != nil { + return &ValidationError{Name: "scope_type", err: fmt.Errorf(`db: validator failed for field "AgentSkill.scope_type": %w`, err)} + } + } + if _u.mutation.RepoCleared() && len(_u.mutation.RepoIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "AgentSkill.repo"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (_u *AgentSkillUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *AgentSkillUpdate { + _u.modifiers = append(_u.modifiers, modifiers...) + return _u +} + +func (_u *AgentSkillUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(agentskill.Table, agentskill.Columns, sqlgraph.NewFieldSpec(agentskill.FieldID, field.TypeUUID)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(agentskill.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Description(); ok { + _spec.SetField(agentskill.FieldDescription, field.TypeString, value) + } + if _u.mutation.DescriptionCleared() { + _spec.ClearField(agentskill.FieldDescription, field.TypeString) + } + if value, ok := _u.mutation.ScopeType(); ok { + _spec.SetField(agentskill.FieldScopeType, field.TypeEnum, value) + } + if value, ok := _u.mutation.ScopeID(); ok { + _spec.SetField(agentskill.FieldScopeID, field.TypeString, value) + } + if value, ok := _u.mutation.CreatedBy(); ok { + _spec.SetField(agentskill.FieldCreatedBy, field.TypeUUID, value) + } + if value, ok := _u.mutation.ActiveVersionID(); ok { + _spec.SetField(agentskill.FieldActiveVersionID, field.TypeUUID, value) + } + if _u.mutation.ActiveVersionIDCleared() { + _spec.ClearField(agentskill.FieldActiveVersionID, field.TypeUUID) + } + if value, ok := _u.mutation.IsForceDelivery(); ok { + _spec.SetField(agentskill.FieldIsForceDelivery, field.TypeBool, value) + } + if value, ok := _u.mutation.IsOrphan(); ok { + _spec.SetField(agentskill.FieldIsOrphan, field.TypeBool, value) + } + if value, ok := _u.mutation.IsDeleted(); ok { + _spec.SetField(agentskill.FieldIsDeleted, field.TypeBool, value) + } + if value, ok := _u.mutation.CreatedAt(); ok { + _spec.SetField(agentskill.FieldCreatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(agentskill.FieldUpdatedAt, field.TypeTime, value) + } + if _u.mutation.RepoCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: agentskill.RepoTable, + Columns: []string{agentskill.RepoColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentskillrepo.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RepoIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: agentskill.RepoTable, + Columns: []string{agentskill.RepoColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentskillrepo.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.VersionsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agentskill.VersionsTable, + Columns: []string{agentskill.VersionsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentskillversion.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedVersionsIDs(); len(nodes) > 0 && !_u.mutation.VersionsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agentskill.VersionsTable, + Columns: []string{agentskill.VersionsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentskillversion.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.VersionsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agentskill.VersionsTable, + Columns: []string{agentskill.VersionsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentskillversion.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(_u.modifiers...) + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{agentskill.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// AgentSkillUpdateOne is the builder for updating a single AgentSkill entity. +type AgentSkillUpdateOne struct { + config + fields []string + hooks []Hook + mutation *AgentSkillMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetRepoID sets the "repo_id" field. +func (_u *AgentSkillUpdateOne) SetRepoID(v uuid.UUID) *AgentSkillUpdateOne { + _u.mutation.SetRepoID(v) + return _u +} + +// SetNillableRepoID sets the "repo_id" field if the given value is not nil. +func (_u *AgentSkillUpdateOne) SetNillableRepoID(v *uuid.UUID) *AgentSkillUpdateOne { + if v != nil { + _u.SetRepoID(*v) + } + return _u +} + +// SetName sets the "name" field. +func (_u *AgentSkillUpdateOne) SetName(v string) *AgentSkillUpdateOne { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *AgentSkillUpdateOne) SetNillableName(v *string) *AgentSkillUpdateOne { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetDescription sets the "description" field. +func (_u *AgentSkillUpdateOne) SetDescription(v string) *AgentSkillUpdateOne { + _u.mutation.SetDescription(v) + return _u +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (_u *AgentSkillUpdateOne) SetNillableDescription(v *string) *AgentSkillUpdateOne { + if v != nil { + _u.SetDescription(*v) + } + return _u +} + +// ClearDescription clears the value of the "description" field. +func (_u *AgentSkillUpdateOne) ClearDescription() *AgentSkillUpdateOne { + _u.mutation.ClearDescription() + return _u +} + +// SetScopeType sets the "scope_type" field. +func (_u *AgentSkillUpdateOne) SetScopeType(v agentskill.ScopeType) *AgentSkillUpdateOne { + _u.mutation.SetScopeType(v) + return _u +} + +// SetNillableScopeType sets the "scope_type" field if the given value is not nil. +func (_u *AgentSkillUpdateOne) SetNillableScopeType(v *agentskill.ScopeType) *AgentSkillUpdateOne { + if v != nil { + _u.SetScopeType(*v) + } + return _u +} + +// SetScopeID sets the "scope_id" field. +func (_u *AgentSkillUpdateOne) SetScopeID(v string) *AgentSkillUpdateOne { + _u.mutation.SetScopeID(v) + return _u +} + +// SetNillableScopeID sets the "scope_id" field if the given value is not nil. +func (_u *AgentSkillUpdateOne) SetNillableScopeID(v *string) *AgentSkillUpdateOne { + if v != nil { + _u.SetScopeID(*v) + } + return _u +} + +// SetCreatedBy sets the "created_by" field. +func (_u *AgentSkillUpdateOne) SetCreatedBy(v uuid.UUID) *AgentSkillUpdateOne { + _u.mutation.SetCreatedBy(v) + return _u +} + +// SetNillableCreatedBy sets the "created_by" field if the given value is not nil. +func (_u *AgentSkillUpdateOne) SetNillableCreatedBy(v *uuid.UUID) *AgentSkillUpdateOne { + if v != nil { + _u.SetCreatedBy(*v) + } + return _u +} + +// SetActiveVersionID sets the "active_version_id" field. +func (_u *AgentSkillUpdateOne) SetActiveVersionID(v uuid.UUID) *AgentSkillUpdateOne { + _u.mutation.SetActiveVersionID(v) + return _u +} + +// SetNillableActiveVersionID sets the "active_version_id" field if the given value is not nil. +func (_u *AgentSkillUpdateOne) SetNillableActiveVersionID(v *uuid.UUID) *AgentSkillUpdateOne { + if v != nil { + _u.SetActiveVersionID(*v) + } + return _u +} + +// ClearActiveVersionID clears the value of the "active_version_id" field. +func (_u *AgentSkillUpdateOne) ClearActiveVersionID() *AgentSkillUpdateOne { + _u.mutation.ClearActiveVersionID() + return _u +} + +// SetIsForceDelivery sets the "is_force_delivery" field. +func (_u *AgentSkillUpdateOne) SetIsForceDelivery(v bool) *AgentSkillUpdateOne { + _u.mutation.SetIsForceDelivery(v) + return _u +} + +// SetNillableIsForceDelivery sets the "is_force_delivery" field if the given value is not nil. +func (_u *AgentSkillUpdateOne) SetNillableIsForceDelivery(v *bool) *AgentSkillUpdateOne { + if v != nil { + _u.SetIsForceDelivery(*v) + } + return _u +} + +// SetIsOrphan sets the "is_orphan" field. +func (_u *AgentSkillUpdateOne) SetIsOrphan(v bool) *AgentSkillUpdateOne { + _u.mutation.SetIsOrphan(v) + return _u +} + +// SetNillableIsOrphan sets the "is_orphan" field if the given value is not nil. +func (_u *AgentSkillUpdateOne) SetNillableIsOrphan(v *bool) *AgentSkillUpdateOne { + if v != nil { + _u.SetIsOrphan(*v) + } + return _u +} + +// SetIsDeleted sets the "is_deleted" field. +func (_u *AgentSkillUpdateOne) SetIsDeleted(v bool) *AgentSkillUpdateOne { + _u.mutation.SetIsDeleted(v) + return _u +} + +// SetNillableIsDeleted sets the "is_deleted" field if the given value is not nil. +func (_u *AgentSkillUpdateOne) SetNillableIsDeleted(v *bool) *AgentSkillUpdateOne { + if v != nil { + _u.SetIsDeleted(*v) + } + return _u +} + +// SetCreatedAt sets the "created_at" field. +func (_u *AgentSkillUpdateOne) SetCreatedAt(v time.Time) *AgentSkillUpdateOne { + _u.mutation.SetCreatedAt(v) + return _u +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_u *AgentSkillUpdateOne) SetNillableCreatedAt(v *time.Time) *AgentSkillUpdateOne { + if v != nil { + _u.SetCreatedAt(*v) + } + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *AgentSkillUpdateOne) SetUpdatedAt(v time.Time) *AgentSkillUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetRepo sets the "repo" edge to the AgentSkillRepo entity. +func (_u *AgentSkillUpdateOne) SetRepo(v *AgentSkillRepo) *AgentSkillUpdateOne { + return _u.SetRepoID(v.ID) +} + +// AddVersionIDs adds the "versions" edge to the AgentSkillVersion entity by IDs. +func (_u *AgentSkillUpdateOne) AddVersionIDs(ids ...uuid.UUID) *AgentSkillUpdateOne { + _u.mutation.AddVersionIDs(ids...) + return _u +} + +// AddVersions adds the "versions" edges to the AgentSkillVersion entity. +func (_u *AgentSkillUpdateOne) AddVersions(v ...*AgentSkillVersion) *AgentSkillUpdateOne { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddVersionIDs(ids...) +} + +// Mutation returns the AgentSkillMutation object of the builder. +func (_u *AgentSkillUpdateOne) Mutation() *AgentSkillMutation { + return _u.mutation +} + +// ClearRepo clears the "repo" edge to the AgentSkillRepo entity. +func (_u *AgentSkillUpdateOne) ClearRepo() *AgentSkillUpdateOne { + _u.mutation.ClearRepo() + return _u +} + +// ClearVersions clears all "versions" edges to the AgentSkillVersion entity. +func (_u *AgentSkillUpdateOne) ClearVersions() *AgentSkillUpdateOne { + _u.mutation.ClearVersions() + return _u +} + +// RemoveVersionIDs removes the "versions" edge to AgentSkillVersion entities by IDs. +func (_u *AgentSkillUpdateOne) RemoveVersionIDs(ids ...uuid.UUID) *AgentSkillUpdateOne { + _u.mutation.RemoveVersionIDs(ids...) + return _u +} + +// RemoveVersions removes "versions" edges to AgentSkillVersion entities. +func (_u *AgentSkillUpdateOne) RemoveVersions(v ...*AgentSkillVersion) *AgentSkillUpdateOne { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveVersionIDs(ids...) +} + +// Where appends a list predicates to the AgentSkillUpdate builder. +func (_u *AgentSkillUpdateOne) Where(ps ...predicate.AgentSkill) *AgentSkillUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *AgentSkillUpdateOne) Select(field string, fields ...string) *AgentSkillUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated AgentSkill entity. +func (_u *AgentSkillUpdateOne) Save(ctx context.Context) (*AgentSkill, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *AgentSkillUpdateOne) SaveX(ctx context.Context) *AgentSkill { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *AgentSkillUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *AgentSkillUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_u *AgentSkillUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := agentskill.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *AgentSkillUpdateOne) check() error { + if v, ok := _u.mutation.Name(); ok { + if err := agentskill.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "AgentSkill.name": %w`, err)} + } + } + if v, ok := _u.mutation.ScopeType(); ok { + if err := agentskill.ScopeTypeValidator(v); err != nil { + return &ValidationError{Name: "scope_type", err: fmt.Errorf(`db: validator failed for field "AgentSkill.scope_type": %w`, err)} + } + } + if _u.mutation.RepoCleared() && len(_u.mutation.RepoIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "AgentSkill.repo"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (_u *AgentSkillUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *AgentSkillUpdateOne { + _u.modifiers = append(_u.modifiers, modifiers...) + return _u +} + +func (_u *AgentSkillUpdateOne) sqlSave(ctx context.Context) (_node *AgentSkill, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(agentskill.Table, agentskill.Columns, sqlgraph.NewFieldSpec(agentskill.FieldID, field.TypeUUID)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "AgentSkill.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, agentskill.FieldID) + for _, f := range fields { + if !agentskill.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != agentskill.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(agentskill.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Description(); ok { + _spec.SetField(agentskill.FieldDescription, field.TypeString, value) + } + if _u.mutation.DescriptionCleared() { + _spec.ClearField(agentskill.FieldDescription, field.TypeString) + } + if value, ok := _u.mutation.ScopeType(); ok { + _spec.SetField(agentskill.FieldScopeType, field.TypeEnum, value) + } + if value, ok := _u.mutation.ScopeID(); ok { + _spec.SetField(agentskill.FieldScopeID, field.TypeString, value) + } + if value, ok := _u.mutation.CreatedBy(); ok { + _spec.SetField(agentskill.FieldCreatedBy, field.TypeUUID, value) + } + if value, ok := _u.mutation.ActiveVersionID(); ok { + _spec.SetField(agentskill.FieldActiveVersionID, field.TypeUUID, value) + } + if _u.mutation.ActiveVersionIDCleared() { + _spec.ClearField(agentskill.FieldActiveVersionID, field.TypeUUID) + } + if value, ok := _u.mutation.IsForceDelivery(); ok { + _spec.SetField(agentskill.FieldIsForceDelivery, field.TypeBool, value) + } + if value, ok := _u.mutation.IsOrphan(); ok { + _spec.SetField(agentskill.FieldIsOrphan, field.TypeBool, value) + } + if value, ok := _u.mutation.IsDeleted(); ok { + _spec.SetField(agentskill.FieldIsDeleted, field.TypeBool, value) + } + if value, ok := _u.mutation.CreatedAt(); ok { + _spec.SetField(agentskill.FieldCreatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(agentskill.FieldUpdatedAt, field.TypeTime, value) + } + if _u.mutation.RepoCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: agentskill.RepoTable, + Columns: []string{agentskill.RepoColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentskillrepo.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RepoIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: agentskill.RepoTable, + Columns: []string{agentskill.RepoColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentskillrepo.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.VersionsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agentskill.VersionsTable, + Columns: []string{agentskill.VersionsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentskillversion.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedVersionsIDs(); len(nodes) > 0 && !_u.mutation.VersionsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agentskill.VersionsTable, + Columns: []string{agentskill.VersionsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentskillversion.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.VersionsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agentskill.VersionsTable, + Columns: []string{agentskill.VersionsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentskillversion.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(_u.modifiers...) + _node = &AgentSkill{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{agentskill.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/backend/db/agentskillrepo.go b/backend/db/agentskillrepo.go new file mode 100644 index 00000000..39588330 --- /dev/null +++ b/backend/db/agentskillrepo.go @@ -0,0 +1,282 @@ +// 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/agentskillrepo" + "github.com/google/uuid" +) + +// AgentSkillRepo is the model entity for the AgentSkillRepo schema. +type AgentSkillRepo struct { + config `json:"-"` + // ID of the ent. + ID uuid.UUID `json:"id,omitempty"` + // Name holds the value of the "name" field. + Name string `json:"name,omitempty"` + // ScopeType holds the value of the "scope_type" field. + ScopeType agentskillrepo.ScopeType `json:"scope_type,omitempty"` + // ScopeID holds the value of the "scope_id" field. + ScopeID string `json:"scope_id,omitempty"` + // CreatedBy holds the value of the "created_by" field. + CreatedBy uuid.UUID `json:"created_by,omitempty"` + // SourceType holds the value of the "source_type" field. + SourceType agentskillrepo.SourceType `json:"source_type,omitempty"` + // GithubURL holds the value of the "github_url" field. + GithubURL *string `json:"github_url,omitempty"` + // RefType holds the value of the "ref_type" field. + RefType *agentskillrepo.RefType `json:"ref_type,omitempty"` + // RefValue holds the value of the "ref_value" field. + RefValue *string `json:"ref_value,omitempty"` + // LastUploadFilename holds the value of the "last_upload_filename" field. + LastUploadFilename *string `json:"last_upload_filename,omitempty"` + // LastUploadAt holds the value of the "last_upload_at" field. + LastUploadAt *time.Time `json:"last_upload_at,omitempty"` + // IsDeleted holds the value of the "is_deleted" field. + IsDeleted bool `json:"is_deleted,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + // UpdatedAt holds the value of the "updated_at" field. + UpdatedAt time.Time `json:"updated_at,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the AgentSkillRepoQuery when eager-loading is set. + Edges AgentSkillRepoEdges `json:"edges"` + selectValues sql.SelectValues +} + +// AgentSkillRepoEdges holds the relations/edges for other nodes in the graph. +type AgentSkillRepoEdges struct { + // Skills holds the value of the skills edge. + Skills []*AgentSkill `json:"skills,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// SkillsOrErr returns the Skills value or an error if the edge +// was not loaded in eager-loading. +func (e AgentSkillRepoEdges) SkillsOrErr() ([]*AgentSkill, error) { + if e.loadedTypes[0] { + return e.Skills, nil + } + return nil, &NotLoadedError{edge: "skills"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*AgentSkillRepo) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case agentskillrepo.FieldIsDeleted: + values[i] = new(sql.NullBool) + case agentskillrepo.FieldName, agentskillrepo.FieldScopeType, agentskillrepo.FieldScopeID, agentskillrepo.FieldSourceType, agentskillrepo.FieldGithubURL, agentskillrepo.FieldRefType, agentskillrepo.FieldRefValue, agentskillrepo.FieldLastUploadFilename: + values[i] = new(sql.NullString) + case agentskillrepo.FieldLastUploadAt, agentskillrepo.FieldCreatedAt, agentskillrepo.FieldUpdatedAt: + values[i] = new(sql.NullTime) + case agentskillrepo.FieldID, agentskillrepo.FieldCreatedBy: + 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 AgentSkillRepo fields. +func (_m *AgentSkillRepo) 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 agentskillrepo.FieldID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value != nil { + _m.ID = *value + } + case agentskillrepo.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + _m.Name = value.String + } + case agentskillrepo.FieldScopeType: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field scope_type", values[i]) + } else if value.Valid { + _m.ScopeType = agentskillrepo.ScopeType(value.String) + } + case agentskillrepo.FieldScopeID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field scope_id", values[i]) + } else if value.Valid { + _m.ScopeID = value.String + } + case agentskillrepo.FieldCreatedBy: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field created_by", values[i]) + } else if value != nil { + _m.CreatedBy = *value + } + case agentskillrepo.FieldSourceType: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field source_type", values[i]) + } else if value.Valid { + _m.SourceType = agentskillrepo.SourceType(value.String) + } + case agentskillrepo.FieldGithubURL: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field github_url", values[i]) + } else if value.Valid { + _m.GithubURL = new(string) + *_m.GithubURL = value.String + } + case agentskillrepo.FieldRefType: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field ref_type", values[i]) + } else if value.Valid { + _m.RefType = new(agentskillrepo.RefType) + *_m.RefType = agentskillrepo.RefType(value.String) + } + case agentskillrepo.FieldRefValue: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field ref_value", values[i]) + } else if value.Valid { + _m.RefValue = new(string) + *_m.RefValue = value.String + } + case agentskillrepo.FieldLastUploadFilename: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field last_upload_filename", values[i]) + } else if value.Valid { + _m.LastUploadFilename = new(string) + *_m.LastUploadFilename = value.String + } + case agentskillrepo.FieldLastUploadAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field last_upload_at", values[i]) + } else if value.Valid { + _m.LastUploadAt = new(time.Time) + *_m.LastUploadAt = value.Time + } + case agentskillrepo.FieldIsDeleted: + if value, ok := values[i].(*sql.NullBool); !ok { + return fmt.Errorf("unexpected type %T for field is_deleted", values[i]) + } else if value.Valid { + _m.IsDeleted = value.Bool + } + case agentskillrepo.FieldCreatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field created_at", values[i]) + } else if value.Valid { + _m.CreatedAt = value.Time + } + case agentskillrepo.FieldUpdatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field updated_at", values[i]) + } else if value.Valid { + _m.UpdatedAt = value.Time + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the AgentSkillRepo. +// This includes values selected through modifiers, order, etc. +func (_m *AgentSkillRepo) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QuerySkills queries the "skills" edge of the AgentSkillRepo entity. +func (_m *AgentSkillRepo) QuerySkills() *AgentSkillQuery { + return NewAgentSkillRepoClient(_m.config).QuerySkills(_m) +} + +// Update returns a builder for updating this AgentSkillRepo. +// Note that you need to call AgentSkillRepo.Unwrap() before calling this method if this AgentSkillRepo +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *AgentSkillRepo) Update() *AgentSkillRepoUpdateOne { + return NewAgentSkillRepoClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the AgentSkillRepo entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (_m *AgentSkillRepo) Unwrap() *AgentSkillRepo { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: AgentSkillRepo is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *AgentSkillRepo) String() string { + var builder strings.Builder + builder.WriteString("AgentSkillRepo(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("name=") + builder.WriteString(_m.Name) + builder.WriteString(", ") + builder.WriteString("scope_type=") + builder.WriteString(fmt.Sprintf("%v", _m.ScopeType)) + builder.WriteString(", ") + builder.WriteString("scope_id=") + builder.WriteString(_m.ScopeID) + builder.WriteString(", ") + builder.WriteString("created_by=") + builder.WriteString(fmt.Sprintf("%v", _m.CreatedBy)) + builder.WriteString(", ") + builder.WriteString("source_type=") + builder.WriteString(fmt.Sprintf("%v", _m.SourceType)) + builder.WriteString(", ") + if v := _m.GithubURL; v != nil { + builder.WriteString("github_url=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.RefType; v != nil { + builder.WriteString("ref_type=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.RefValue; v != nil { + builder.WriteString("ref_value=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.LastUploadFilename; v != nil { + builder.WriteString("last_upload_filename=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.LastUploadAt; v != nil { + builder.WriteString("last_upload_at=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteString(", ") + builder.WriteString("is_deleted=") + builder.WriteString(fmt.Sprintf("%v", _m.IsDeleted)) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("updated_at=") + builder.WriteString(_m.UpdatedAt.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// AgentSkillRepos is a parsable slice of AgentSkillRepo. +type AgentSkillRepos []*AgentSkillRepo diff --git a/backend/db/agentskillrepo/agentskillrepo.go b/backend/db/agentskillrepo/agentskillrepo.go new file mode 100644 index 00000000..aa832400 --- /dev/null +++ b/backend/db/agentskillrepo/agentskillrepo.go @@ -0,0 +1,267 @@ +// Code generated by ent, DO NOT EDIT. + +package agentskillrepo + +import ( + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/google/uuid" +) + +const ( + // Label holds the string label denoting the agentskillrepo type in the database. + Label = "agent_skill_repo" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldScopeType holds the string denoting the scope_type field in the database. + FieldScopeType = "scope_type" + // FieldScopeID holds the string denoting the scope_id field in the database. + FieldScopeID = "scope_id" + // FieldCreatedBy holds the string denoting the created_by field in the database. + FieldCreatedBy = "created_by" + // FieldSourceType holds the string denoting the source_type field in the database. + FieldSourceType = "source_type" + // FieldGithubURL holds the string denoting the github_url field in the database. + FieldGithubURL = "github_url" + // FieldRefType holds the string denoting the ref_type field in the database. + FieldRefType = "ref_type" + // FieldRefValue holds the string denoting the ref_value field in the database. + FieldRefValue = "ref_value" + // FieldLastUploadFilename holds the string denoting the last_upload_filename field in the database. + FieldLastUploadFilename = "last_upload_filename" + // FieldLastUploadAt holds the string denoting the last_upload_at field in the database. + FieldLastUploadAt = "last_upload_at" + // FieldIsDeleted holds the string denoting the is_deleted field in the database. + FieldIsDeleted = "is_deleted" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // FieldUpdatedAt holds the string denoting the updated_at field in the database. + FieldUpdatedAt = "updated_at" + // EdgeSkills holds the string denoting the skills edge name in mutations. + EdgeSkills = "skills" + // Table holds the table name of the agentskillrepo in the database. + Table = "agent_skill_repos" + // SkillsTable is the table that holds the skills relation/edge. + SkillsTable = "agent_skills" + // SkillsInverseTable is the table name for the AgentSkill entity. + // It exists in this package in order to avoid circular dependency with the "agentskill" package. + SkillsInverseTable = "agent_skills" + // SkillsColumn is the table column denoting the skills relation/edge. + SkillsColumn = "repo_id" +) + +// Columns holds all SQL columns for agentskillrepo fields. +var Columns = []string{ + FieldID, + FieldName, + FieldScopeType, + FieldScopeID, + FieldCreatedBy, + FieldSourceType, + FieldGithubURL, + FieldRefType, + FieldRefValue, + FieldLastUploadFilename, + FieldLastUploadAt, + FieldIsDeleted, + FieldCreatedAt, + FieldUpdatedAt, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // NameValidator is a validator for the "name" field. It is called by the builders before save. + NameValidator func(string) error + // DefaultScopeID holds the default value on creation for the "scope_id" field. + DefaultScopeID string + // DefaultIsDeleted holds the default value on creation for the "is_deleted" field. + DefaultIsDeleted bool + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time + // DefaultUpdatedAt holds the default value on creation for the "updated_at" field. + DefaultUpdatedAt func() time.Time + // UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field. + UpdateDefaultUpdatedAt func() time.Time + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() uuid.UUID +) + +// ScopeType defines the type for the "scope_type" enum field. +type ScopeType string + +// ScopeTypeGlobal is the default value of the ScopeType enum. +const DefaultScopeType = ScopeTypeGlobal + +// ScopeType values. +const ( + ScopeTypeGlobal ScopeType = "global" +) + +func (st ScopeType) String() string { + return string(st) +} + +// ScopeTypeValidator is a validator for the "scope_type" field enum values. It is called by the builders before save. +func ScopeTypeValidator(st ScopeType) error { + switch st { + case ScopeTypeGlobal: + return nil + default: + return fmt.Errorf("agentskillrepo: invalid enum value for scope_type field: %q", st) + } +} + +// SourceType defines the type for the "source_type" enum field. +type SourceType string + +// SourceType values. +const ( + SourceTypeGithub SourceType = "github" + SourceTypeUpload SourceType = "upload" +) + +func (st SourceType) String() string { + return string(st) +} + +// SourceTypeValidator is a validator for the "source_type" field enum values. It is called by the builders before save. +func SourceTypeValidator(st SourceType) error { + switch st { + case SourceTypeGithub, SourceTypeUpload: + return nil + default: + return fmt.Errorf("agentskillrepo: invalid enum value for source_type field: %q", st) + } +} + +// RefType defines the type for the "ref_type" enum field. +type RefType string + +// RefType values. +const ( + RefTypeBranch RefType = "branch" + RefTypeTag RefType = "tag" + RefTypeCommit RefType = "commit" +) + +func (rt RefType) String() string { + return string(rt) +} + +// RefTypeValidator is a validator for the "ref_type" field enum values. It is called by the builders before save. +func RefTypeValidator(rt RefType) error { + switch rt { + case RefTypeBranch, RefTypeTag, RefTypeCommit: + return nil + default: + return fmt.Errorf("agentskillrepo: invalid enum value for ref_type field: %q", rt) + } +} + +// OrderOption defines the ordering options for the AgentSkillRepo queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} + +// ByScopeType orders the results by the scope_type field. +func ByScopeType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldScopeType, opts...).ToFunc() +} + +// ByScopeID orders the results by the scope_id field. +func ByScopeID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldScopeID, opts...).ToFunc() +} + +// ByCreatedBy orders the results by the created_by field. +func ByCreatedBy(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedBy, opts...).ToFunc() +} + +// BySourceType orders the results by the source_type field. +func BySourceType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSourceType, opts...).ToFunc() +} + +// ByGithubURL orders the results by the github_url field. +func ByGithubURL(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldGithubURL, opts...).ToFunc() +} + +// ByRefType orders the results by the ref_type field. +func ByRefType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRefType, opts...).ToFunc() +} + +// ByRefValue orders the results by the ref_value field. +func ByRefValue(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRefValue, opts...).ToFunc() +} + +// ByLastUploadFilename orders the results by the last_upload_filename field. +func ByLastUploadFilename(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldLastUploadFilename, opts...).ToFunc() +} + +// ByLastUploadAt orders the results by the last_upload_at field. +func ByLastUploadAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldLastUploadAt, opts...).ToFunc() +} + +// ByIsDeleted orders the results by the is_deleted field. +func ByIsDeleted(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldIsDeleted, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// ByUpdatedAt orders the results by the updated_at field. +func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc() +} + +// BySkillsCount orders the results by skills count. +func BySkillsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newSkillsStep(), opts...) + } +} + +// BySkills orders the results by skills terms. +func BySkills(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newSkillsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newSkillsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(SkillsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, SkillsTable, SkillsColumn), + ) +} diff --git a/backend/db/agentskillrepo/where.go b/backend/db/agentskillrepo/where.go new file mode 100644 index 00000000..abcf625b --- /dev/null +++ b/backend/db/agentskillrepo/where.go @@ -0,0 +1,750 @@ +// Code generated by ent, DO NOT EDIT. + +package agentskillrepo + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/google/uuid" +) + +// ID filters vertices based on their ID field. +func ID(id uuid.UUID) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id uuid.UUID) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id uuid.UUID) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...uuid.UUID) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...uuid.UUID) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id uuid.UUID) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id uuid.UUID) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id uuid.UUID) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id uuid.UUID) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldLTE(FieldID, id)) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldEQ(FieldName, v)) +} + +// ScopeID applies equality check predicate on the "scope_id" field. It's identical to ScopeIDEQ. +func ScopeID(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldEQ(FieldScopeID, v)) +} + +// CreatedBy applies equality check predicate on the "created_by" field. It's identical to CreatedByEQ. +func CreatedBy(v uuid.UUID) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldEQ(FieldCreatedBy, v)) +} + +// GithubURL applies equality check predicate on the "github_url" field. It's identical to GithubURLEQ. +func GithubURL(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldEQ(FieldGithubURL, v)) +} + +// RefValue applies equality check predicate on the "ref_value" field. It's identical to RefValueEQ. +func RefValue(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldEQ(FieldRefValue, v)) +} + +// LastUploadFilename applies equality check predicate on the "last_upload_filename" field. It's identical to LastUploadFilenameEQ. +func LastUploadFilename(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldEQ(FieldLastUploadFilename, v)) +} + +// LastUploadAt applies equality check predicate on the "last_upload_at" field. It's identical to LastUploadAtEQ. +func LastUploadAt(v time.Time) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldEQ(FieldLastUploadAt, v)) +} + +// IsDeleted applies equality check predicate on the "is_deleted" field. It's identical to IsDeletedEQ. +func IsDeleted(v bool) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldEQ(FieldIsDeleted, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldEQ(FieldCreatedAt, v)) +} + +// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ. +func UpdatedAt(v time.Time) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldEQ(FieldName, v)) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldNEQ(FieldName, v)) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldIn(FieldName, vs...)) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldNotIn(FieldName, vs...)) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldGT(FieldName, v)) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldGTE(FieldName, v)) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldLT(FieldName, v)) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldLTE(FieldName, v)) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldContains(FieldName, v)) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldHasPrefix(FieldName, v)) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldHasSuffix(FieldName, v)) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldEqualFold(FieldName, v)) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldContainsFold(FieldName, v)) +} + +// ScopeTypeEQ applies the EQ predicate on the "scope_type" field. +func ScopeTypeEQ(v ScopeType) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldEQ(FieldScopeType, v)) +} + +// ScopeTypeNEQ applies the NEQ predicate on the "scope_type" field. +func ScopeTypeNEQ(v ScopeType) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldNEQ(FieldScopeType, v)) +} + +// ScopeTypeIn applies the In predicate on the "scope_type" field. +func ScopeTypeIn(vs ...ScopeType) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldIn(FieldScopeType, vs...)) +} + +// ScopeTypeNotIn applies the NotIn predicate on the "scope_type" field. +func ScopeTypeNotIn(vs ...ScopeType) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldNotIn(FieldScopeType, vs...)) +} + +// ScopeIDEQ applies the EQ predicate on the "scope_id" field. +func ScopeIDEQ(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldEQ(FieldScopeID, v)) +} + +// ScopeIDNEQ applies the NEQ predicate on the "scope_id" field. +func ScopeIDNEQ(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldNEQ(FieldScopeID, v)) +} + +// ScopeIDIn applies the In predicate on the "scope_id" field. +func ScopeIDIn(vs ...string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldIn(FieldScopeID, vs...)) +} + +// ScopeIDNotIn applies the NotIn predicate on the "scope_id" field. +func ScopeIDNotIn(vs ...string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldNotIn(FieldScopeID, vs...)) +} + +// ScopeIDGT applies the GT predicate on the "scope_id" field. +func ScopeIDGT(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldGT(FieldScopeID, v)) +} + +// ScopeIDGTE applies the GTE predicate on the "scope_id" field. +func ScopeIDGTE(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldGTE(FieldScopeID, v)) +} + +// ScopeIDLT applies the LT predicate on the "scope_id" field. +func ScopeIDLT(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldLT(FieldScopeID, v)) +} + +// ScopeIDLTE applies the LTE predicate on the "scope_id" field. +func ScopeIDLTE(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldLTE(FieldScopeID, v)) +} + +// ScopeIDContains applies the Contains predicate on the "scope_id" field. +func ScopeIDContains(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldContains(FieldScopeID, v)) +} + +// ScopeIDHasPrefix applies the HasPrefix predicate on the "scope_id" field. +func ScopeIDHasPrefix(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldHasPrefix(FieldScopeID, v)) +} + +// ScopeIDHasSuffix applies the HasSuffix predicate on the "scope_id" field. +func ScopeIDHasSuffix(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldHasSuffix(FieldScopeID, v)) +} + +// ScopeIDEqualFold applies the EqualFold predicate on the "scope_id" field. +func ScopeIDEqualFold(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldEqualFold(FieldScopeID, v)) +} + +// ScopeIDContainsFold applies the ContainsFold predicate on the "scope_id" field. +func ScopeIDContainsFold(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldContainsFold(FieldScopeID, v)) +} + +// CreatedByEQ applies the EQ predicate on the "created_by" field. +func CreatedByEQ(v uuid.UUID) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldEQ(FieldCreatedBy, v)) +} + +// CreatedByNEQ applies the NEQ predicate on the "created_by" field. +func CreatedByNEQ(v uuid.UUID) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldNEQ(FieldCreatedBy, v)) +} + +// CreatedByIn applies the In predicate on the "created_by" field. +func CreatedByIn(vs ...uuid.UUID) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldIn(FieldCreatedBy, vs...)) +} + +// CreatedByNotIn applies the NotIn predicate on the "created_by" field. +func CreatedByNotIn(vs ...uuid.UUID) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldNotIn(FieldCreatedBy, vs...)) +} + +// CreatedByGT applies the GT predicate on the "created_by" field. +func CreatedByGT(v uuid.UUID) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldGT(FieldCreatedBy, v)) +} + +// CreatedByGTE applies the GTE predicate on the "created_by" field. +func CreatedByGTE(v uuid.UUID) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldGTE(FieldCreatedBy, v)) +} + +// CreatedByLT applies the LT predicate on the "created_by" field. +func CreatedByLT(v uuid.UUID) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldLT(FieldCreatedBy, v)) +} + +// CreatedByLTE applies the LTE predicate on the "created_by" field. +func CreatedByLTE(v uuid.UUID) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldLTE(FieldCreatedBy, v)) +} + +// SourceTypeEQ applies the EQ predicate on the "source_type" field. +func SourceTypeEQ(v SourceType) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldEQ(FieldSourceType, v)) +} + +// SourceTypeNEQ applies the NEQ predicate on the "source_type" field. +func SourceTypeNEQ(v SourceType) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldNEQ(FieldSourceType, v)) +} + +// SourceTypeIn applies the In predicate on the "source_type" field. +func SourceTypeIn(vs ...SourceType) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldIn(FieldSourceType, vs...)) +} + +// SourceTypeNotIn applies the NotIn predicate on the "source_type" field. +func SourceTypeNotIn(vs ...SourceType) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldNotIn(FieldSourceType, vs...)) +} + +// GithubURLEQ applies the EQ predicate on the "github_url" field. +func GithubURLEQ(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldEQ(FieldGithubURL, v)) +} + +// GithubURLNEQ applies the NEQ predicate on the "github_url" field. +func GithubURLNEQ(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldNEQ(FieldGithubURL, v)) +} + +// GithubURLIn applies the In predicate on the "github_url" field. +func GithubURLIn(vs ...string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldIn(FieldGithubURL, vs...)) +} + +// GithubURLNotIn applies the NotIn predicate on the "github_url" field. +func GithubURLNotIn(vs ...string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldNotIn(FieldGithubURL, vs...)) +} + +// GithubURLGT applies the GT predicate on the "github_url" field. +func GithubURLGT(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldGT(FieldGithubURL, v)) +} + +// GithubURLGTE applies the GTE predicate on the "github_url" field. +func GithubURLGTE(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldGTE(FieldGithubURL, v)) +} + +// GithubURLLT applies the LT predicate on the "github_url" field. +func GithubURLLT(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldLT(FieldGithubURL, v)) +} + +// GithubURLLTE applies the LTE predicate on the "github_url" field. +func GithubURLLTE(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldLTE(FieldGithubURL, v)) +} + +// GithubURLContains applies the Contains predicate on the "github_url" field. +func GithubURLContains(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldContains(FieldGithubURL, v)) +} + +// GithubURLHasPrefix applies the HasPrefix predicate on the "github_url" field. +func GithubURLHasPrefix(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldHasPrefix(FieldGithubURL, v)) +} + +// GithubURLHasSuffix applies the HasSuffix predicate on the "github_url" field. +func GithubURLHasSuffix(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldHasSuffix(FieldGithubURL, v)) +} + +// GithubURLIsNil applies the IsNil predicate on the "github_url" field. +func GithubURLIsNil() predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldIsNull(FieldGithubURL)) +} + +// GithubURLNotNil applies the NotNil predicate on the "github_url" field. +func GithubURLNotNil() predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldNotNull(FieldGithubURL)) +} + +// GithubURLEqualFold applies the EqualFold predicate on the "github_url" field. +func GithubURLEqualFold(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldEqualFold(FieldGithubURL, v)) +} + +// GithubURLContainsFold applies the ContainsFold predicate on the "github_url" field. +func GithubURLContainsFold(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldContainsFold(FieldGithubURL, v)) +} + +// RefTypeEQ applies the EQ predicate on the "ref_type" field. +func RefTypeEQ(v RefType) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldEQ(FieldRefType, v)) +} + +// RefTypeNEQ applies the NEQ predicate on the "ref_type" field. +func RefTypeNEQ(v RefType) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldNEQ(FieldRefType, v)) +} + +// RefTypeIn applies the In predicate on the "ref_type" field. +func RefTypeIn(vs ...RefType) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldIn(FieldRefType, vs...)) +} + +// RefTypeNotIn applies the NotIn predicate on the "ref_type" field. +func RefTypeNotIn(vs ...RefType) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldNotIn(FieldRefType, vs...)) +} + +// RefTypeIsNil applies the IsNil predicate on the "ref_type" field. +func RefTypeIsNil() predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldIsNull(FieldRefType)) +} + +// RefTypeNotNil applies the NotNil predicate on the "ref_type" field. +func RefTypeNotNil() predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldNotNull(FieldRefType)) +} + +// RefValueEQ applies the EQ predicate on the "ref_value" field. +func RefValueEQ(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldEQ(FieldRefValue, v)) +} + +// RefValueNEQ applies the NEQ predicate on the "ref_value" field. +func RefValueNEQ(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldNEQ(FieldRefValue, v)) +} + +// RefValueIn applies the In predicate on the "ref_value" field. +func RefValueIn(vs ...string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldIn(FieldRefValue, vs...)) +} + +// RefValueNotIn applies the NotIn predicate on the "ref_value" field. +func RefValueNotIn(vs ...string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldNotIn(FieldRefValue, vs...)) +} + +// RefValueGT applies the GT predicate on the "ref_value" field. +func RefValueGT(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldGT(FieldRefValue, v)) +} + +// RefValueGTE applies the GTE predicate on the "ref_value" field. +func RefValueGTE(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldGTE(FieldRefValue, v)) +} + +// RefValueLT applies the LT predicate on the "ref_value" field. +func RefValueLT(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldLT(FieldRefValue, v)) +} + +// RefValueLTE applies the LTE predicate on the "ref_value" field. +func RefValueLTE(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldLTE(FieldRefValue, v)) +} + +// RefValueContains applies the Contains predicate on the "ref_value" field. +func RefValueContains(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldContains(FieldRefValue, v)) +} + +// RefValueHasPrefix applies the HasPrefix predicate on the "ref_value" field. +func RefValueHasPrefix(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldHasPrefix(FieldRefValue, v)) +} + +// RefValueHasSuffix applies the HasSuffix predicate on the "ref_value" field. +func RefValueHasSuffix(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldHasSuffix(FieldRefValue, v)) +} + +// RefValueIsNil applies the IsNil predicate on the "ref_value" field. +func RefValueIsNil() predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldIsNull(FieldRefValue)) +} + +// RefValueNotNil applies the NotNil predicate on the "ref_value" field. +func RefValueNotNil() predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldNotNull(FieldRefValue)) +} + +// RefValueEqualFold applies the EqualFold predicate on the "ref_value" field. +func RefValueEqualFold(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldEqualFold(FieldRefValue, v)) +} + +// RefValueContainsFold applies the ContainsFold predicate on the "ref_value" field. +func RefValueContainsFold(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldContainsFold(FieldRefValue, v)) +} + +// LastUploadFilenameEQ applies the EQ predicate on the "last_upload_filename" field. +func LastUploadFilenameEQ(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldEQ(FieldLastUploadFilename, v)) +} + +// LastUploadFilenameNEQ applies the NEQ predicate on the "last_upload_filename" field. +func LastUploadFilenameNEQ(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldNEQ(FieldLastUploadFilename, v)) +} + +// LastUploadFilenameIn applies the In predicate on the "last_upload_filename" field. +func LastUploadFilenameIn(vs ...string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldIn(FieldLastUploadFilename, vs...)) +} + +// LastUploadFilenameNotIn applies the NotIn predicate on the "last_upload_filename" field. +func LastUploadFilenameNotIn(vs ...string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldNotIn(FieldLastUploadFilename, vs...)) +} + +// LastUploadFilenameGT applies the GT predicate on the "last_upload_filename" field. +func LastUploadFilenameGT(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldGT(FieldLastUploadFilename, v)) +} + +// LastUploadFilenameGTE applies the GTE predicate on the "last_upload_filename" field. +func LastUploadFilenameGTE(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldGTE(FieldLastUploadFilename, v)) +} + +// LastUploadFilenameLT applies the LT predicate on the "last_upload_filename" field. +func LastUploadFilenameLT(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldLT(FieldLastUploadFilename, v)) +} + +// LastUploadFilenameLTE applies the LTE predicate on the "last_upload_filename" field. +func LastUploadFilenameLTE(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldLTE(FieldLastUploadFilename, v)) +} + +// LastUploadFilenameContains applies the Contains predicate on the "last_upload_filename" field. +func LastUploadFilenameContains(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldContains(FieldLastUploadFilename, v)) +} + +// LastUploadFilenameHasPrefix applies the HasPrefix predicate on the "last_upload_filename" field. +func LastUploadFilenameHasPrefix(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldHasPrefix(FieldLastUploadFilename, v)) +} + +// LastUploadFilenameHasSuffix applies the HasSuffix predicate on the "last_upload_filename" field. +func LastUploadFilenameHasSuffix(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldHasSuffix(FieldLastUploadFilename, v)) +} + +// LastUploadFilenameIsNil applies the IsNil predicate on the "last_upload_filename" field. +func LastUploadFilenameIsNil() predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldIsNull(FieldLastUploadFilename)) +} + +// LastUploadFilenameNotNil applies the NotNil predicate on the "last_upload_filename" field. +func LastUploadFilenameNotNil() predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldNotNull(FieldLastUploadFilename)) +} + +// LastUploadFilenameEqualFold applies the EqualFold predicate on the "last_upload_filename" field. +func LastUploadFilenameEqualFold(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldEqualFold(FieldLastUploadFilename, v)) +} + +// LastUploadFilenameContainsFold applies the ContainsFold predicate on the "last_upload_filename" field. +func LastUploadFilenameContainsFold(v string) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldContainsFold(FieldLastUploadFilename, v)) +} + +// LastUploadAtEQ applies the EQ predicate on the "last_upload_at" field. +func LastUploadAtEQ(v time.Time) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldEQ(FieldLastUploadAt, v)) +} + +// LastUploadAtNEQ applies the NEQ predicate on the "last_upload_at" field. +func LastUploadAtNEQ(v time.Time) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldNEQ(FieldLastUploadAt, v)) +} + +// LastUploadAtIn applies the In predicate on the "last_upload_at" field. +func LastUploadAtIn(vs ...time.Time) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldIn(FieldLastUploadAt, vs...)) +} + +// LastUploadAtNotIn applies the NotIn predicate on the "last_upload_at" field. +func LastUploadAtNotIn(vs ...time.Time) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldNotIn(FieldLastUploadAt, vs...)) +} + +// LastUploadAtGT applies the GT predicate on the "last_upload_at" field. +func LastUploadAtGT(v time.Time) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldGT(FieldLastUploadAt, v)) +} + +// LastUploadAtGTE applies the GTE predicate on the "last_upload_at" field. +func LastUploadAtGTE(v time.Time) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldGTE(FieldLastUploadAt, v)) +} + +// LastUploadAtLT applies the LT predicate on the "last_upload_at" field. +func LastUploadAtLT(v time.Time) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldLT(FieldLastUploadAt, v)) +} + +// LastUploadAtLTE applies the LTE predicate on the "last_upload_at" field. +func LastUploadAtLTE(v time.Time) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldLTE(FieldLastUploadAt, v)) +} + +// LastUploadAtIsNil applies the IsNil predicate on the "last_upload_at" field. +func LastUploadAtIsNil() predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldIsNull(FieldLastUploadAt)) +} + +// LastUploadAtNotNil applies the NotNil predicate on the "last_upload_at" field. +func LastUploadAtNotNil() predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldNotNull(FieldLastUploadAt)) +} + +// IsDeletedEQ applies the EQ predicate on the "is_deleted" field. +func IsDeletedEQ(v bool) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldEQ(FieldIsDeleted, v)) +} + +// IsDeletedNEQ applies the NEQ predicate on the "is_deleted" field. +func IsDeletedNEQ(v bool) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldNEQ(FieldIsDeleted, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// HasSkills applies the HasEdge predicate on the "skills" edge. +func HasSkills() predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, SkillsTable, SkillsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasSkillsWith applies the HasEdge predicate on the "skills" edge with a given conditions (other predicates). +func HasSkillsWith(preds ...predicate.AgentSkill) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(func(s *sql.Selector) { + step := newSkillsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.AgentSkillRepo) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.AgentSkillRepo) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.AgentSkillRepo) predicate.AgentSkillRepo { + return predicate.AgentSkillRepo(sql.NotPredicates(p)) +} diff --git a/backend/db/agentskillrepo_create.go b/backend/db/agentskillrepo_create.go new file mode 100644 index 00000000..dbb2ae4a --- /dev/null +++ b/backend/db/agentskillrepo_create.go @@ -0,0 +1,1382 @@ +// 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/agentskill" + "github.com/chaitin/MonkeyCode/backend/db/agentskillrepo" + "github.com/google/uuid" +) + +// AgentSkillRepoCreate is the builder for creating a AgentSkillRepo entity. +type AgentSkillRepoCreate struct { + config + mutation *AgentSkillRepoMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetName sets the "name" field. +func (_c *AgentSkillRepoCreate) SetName(v string) *AgentSkillRepoCreate { + _c.mutation.SetName(v) + return _c +} + +// SetScopeType sets the "scope_type" field. +func (_c *AgentSkillRepoCreate) SetScopeType(v agentskillrepo.ScopeType) *AgentSkillRepoCreate { + _c.mutation.SetScopeType(v) + return _c +} + +// SetNillableScopeType sets the "scope_type" field if the given value is not nil. +func (_c *AgentSkillRepoCreate) SetNillableScopeType(v *agentskillrepo.ScopeType) *AgentSkillRepoCreate { + if v != nil { + _c.SetScopeType(*v) + } + return _c +} + +// SetScopeID sets the "scope_id" field. +func (_c *AgentSkillRepoCreate) SetScopeID(v string) *AgentSkillRepoCreate { + _c.mutation.SetScopeID(v) + return _c +} + +// SetNillableScopeID sets the "scope_id" field if the given value is not nil. +func (_c *AgentSkillRepoCreate) SetNillableScopeID(v *string) *AgentSkillRepoCreate { + if v != nil { + _c.SetScopeID(*v) + } + return _c +} + +// SetCreatedBy sets the "created_by" field. +func (_c *AgentSkillRepoCreate) SetCreatedBy(v uuid.UUID) *AgentSkillRepoCreate { + _c.mutation.SetCreatedBy(v) + return _c +} + +// SetSourceType sets the "source_type" field. +func (_c *AgentSkillRepoCreate) SetSourceType(v agentskillrepo.SourceType) *AgentSkillRepoCreate { + _c.mutation.SetSourceType(v) + return _c +} + +// SetGithubURL sets the "github_url" field. +func (_c *AgentSkillRepoCreate) SetGithubURL(v string) *AgentSkillRepoCreate { + _c.mutation.SetGithubURL(v) + return _c +} + +// SetNillableGithubURL sets the "github_url" field if the given value is not nil. +func (_c *AgentSkillRepoCreate) SetNillableGithubURL(v *string) *AgentSkillRepoCreate { + if v != nil { + _c.SetGithubURL(*v) + } + return _c +} + +// SetRefType sets the "ref_type" field. +func (_c *AgentSkillRepoCreate) SetRefType(v agentskillrepo.RefType) *AgentSkillRepoCreate { + _c.mutation.SetRefType(v) + return _c +} + +// SetNillableRefType sets the "ref_type" field if the given value is not nil. +func (_c *AgentSkillRepoCreate) SetNillableRefType(v *agentskillrepo.RefType) *AgentSkillRepoCreate { + if v != nil { + _c.SetRefType(*v) + } + return _c +} + +// SetRefValue sets the "ref_value" field. +func (_c *AgentSkillRepoCreate) SetRefValue(v string) *AgentSkillRepoCreate { + _c.mutation.SetRefValue(v) + return _c +} + +// SetNillableRefValue sets the "ref_value" field if the given value is not nil. +func (_c *AgentSkillRepoCreate) SetNillableRefValue(v *string) *AgentSkillRepoCreate { + if v != nil { + _c.SetRefValue(*v) + } + return _c +} + +// SetLastUploadFilename sets the "last_upload_filename" field. +func (_c *AgentSkillRepoCreate) SetLastUploadFilename(v string) *AgentSkillRepoCreate { + _c.mutation.SetLastUploadFilename(v) + return _c +} + +// SetNillableLastUploadFilename sets the "last_upload_filename" field if the given value is not nil. +func (_c *AgentSkillRepoCreate) SetNillableLastUploadFilename(v *string) *AgentSkillRepoCreate { + if v != nil { + _c.SetLastUploadFilename(*v) + } + return _c +} + +// SetLastUploadAt sets the "last_upload_at" field. +func (_c *AgentSkillRepoCreate) SetLastUploadAt(v time.Time) *AgentSkillRepoCreate { + _c.mutation.SetLastUploadAt(v) + return _c +} + +// SetNillableLastUploadAt sets the "last_upload_at" field if the given value is not nil. +func (_c *AgentSkillRepoCreate) SetNillableLastUploadAt(v *time.Time) *AgentSkillRepoCreate { + if v != nil { + _c.SetLastUploadAt(*v) + } + return _c +} + +// SetIsDeleted sets the "is_deleted" field. +func (_c *AgentSkillRepoCreate) SetIsDeleted(v bool) *AgentSkillRepoCreate { + _c.mutation.SetIsDeleted(v) + return _c +} + +// SetNillableIsDeleted sets the "is_deleted" field if the given value is not nil. +func (_c *AgentSkillRepoCreate) SetNillableIsDeleted(v *bool) *AgentSkillRepoCreate { + if v != nil { + _c.SetIsDeleted(*v) + } + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *AgentSkillRepoCreate) SetCreatedAt(v time.Time) *AgentSkillRepoCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *AgentSkillRepoCreate) SetNillableCreatedAt(v *time.Time) *AgentSkillRepoCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *AgentSkillRepoCreate) SetUpdatedAt(v time.Time) *AgentSkillRepoCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *AgentSkillRepoCreate) SetNillableUpdatedAt(v *time.Time) *AgentSkillRepoCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *AgentSkillRepoCreate) SetID(v uuid.UUID) *AgentSkillRepoCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *AgentSkillRepoCreate) SetNillableID(v *uuid.UUID) *AgentSkillRepoCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// AddSkillIDs adds the "skills" edge to the AgentSkill entity by IDs. +func (_c *AgentSkillRepoCreate) AddSkillIDs(ids ...uuid.UUID) *AgentSkillRepoCreate { + _c.mutation.AddSkillIDs(ids...) + return _c +} + +// AddSkills adds the "skills" edges to the AgentSkill entity. +func (_c *AgentSkillRepoCreate) AddSkills(v ...*AgentSkill) *AgentSkillRepoCreate { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddSkillIDs(ids...) +} + +// Mutation returns the AgentSkillRepoMutation object of the builder. +func (_c *AgentSkillRepoCreate) Mutation() *AgentSkillRepoMutation { + return _c.mutation +} + +// Save creates the AgentSkillRepo in the database. +func (_c *AgentSkillRepoCreate) Save(ctx context.Context) (*AgentSkillRepo, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *AgentSkillRepoCreate) SaveX(ctx context.Context) *AgentSkillRepo { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *AgentSkillRepoCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *AgentSkillRepoCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *AgentSkillRepoCreate) defaults() { + if _, ok := _c.mutation.ScopeType(); !ok { + v := agentskillrepo.DefaultScopeType + _c.mutation.SetScopeType(v) + } + if _, ok := _c.mutation.ScopeID(); !ok { + v := agentskillrepo.DefaultScopeID + _c.mutation.SetScopeID(v) + } + if _, ok := _c.mutation.IsDeleted(); !ok { + v := agentskillrepo.DefaultIsDeleted + _c.mutation.SetIsDeleted(v) + } + if _, ok := _c.mutation.CreatedAt(); !ok { + v := agentskillrepo.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := agentskillrepo.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := agentskillrepo.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *AgentSkillRepoCreate) check() error { + if _, ok := _c.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`db: missing required field "AgentSkillRepo.name"`)} + } + if v, ok := _c.mutation.Name(); ok { + if err := agentskillrepo.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "AgentSkillRepo.name": %w`, err)} + } + } + if _, ok := _c.mutation.ScopeType(); !ok { + return &ValidationError{Name: "scope_type", err: errors.New(`db: missing required field "AgentSkillRepo.scope_type"`)} + } + if v, ok := _c.mutation.ScopeType(); ok { + if err := agentskillrepo.ScopeTypeValidator(v); err != nil { + return &ValidationError{Name: "scope_type", err: fmt.Errorf(`db: validator failed for field "AgentSkillRepo.scope_type": %w`, err)} + } + } + if _, ok := _c.mutation.ScopeID(); !ok { + return &ValidationError{Name: "scope_id", err: errors.New(`db: missing required field "AgentSkillRepo.scope_id"`)} + } + if _, ok := _c.mutation.CreatedBy(); !ok { + return &ValidationError{Name: "created_by", err: errors.New(`db: missing required field "AgentSkillRepo.created_by"`)} + } + if _, ok := _c.mutation.SourceType(); !ok { + return &ValidationError{Name: "source_type", err: errors.New(`db: missing required field "AgentSkillRepo.source_type"`)} + } + if v, ok := _c.mutation.SourceType(); ok { + if err := agentskillrepo.SourceTypeValidator(v); err != nil { + return &ValidationError{Name: "source_type", err: fmt.Errorf(`db: validator failed for field "AgentSkillRepo.source_type": %w`, err)} + } + } + if v, ok := _c.mutation.RefType(); ok { + if err := agentskillrepo.RefTypeValidator(v); err != nil { + return &ValidationError{Name: "ref_type", err: fmt.Errorf(`db: validator failed for field "AgentSkillRepo.ref_type": %w`, err)} + } + } + if _, ok := _c.mutation.IsDeleted(); !ok { + return &ValidationError{Name: "is_deleted", err: errors.New(`db: missing required field "AgentSkillRepo.is_deleted"`)} + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "AgentSkillRepo.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "AgentSkillRepo.updated_at"`)} + } + return nil +} + +func (_c *AgentSkillRepoCreate) sqlSave(ctx context.Context) (*AgentSkillRepo, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.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 + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *AgentSkillRepoCreate) createSpec() (*AgentSkillRepo, *sqlgraph.CreateSpec) { + var ( + _node = &AgentSkillRepo{config: _c.config} + _spec = sqlgraph.NewCreateSpec(agentskillrepo.Table, sqlgraph.NewFieldSpec(agentskillrepo.FieldID, field.TypeUUID)) + ) + _spec.OnConflict = _c.conflict + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = &id + } + if value, ok := _c.mutation.Name(); ok { + _spec.SetField(agentskillrepo.FieldName, field.TypeString, value) + _node.Name = value + } + if value, ok := _c.mutation.ScopeType(); ok { + _spec.SetField(agentskillrepo.FieldScopeType, field.TypeEnum, value) + _node.ScopeType = value + } + if value, ok := _c.mutation.ScopeID(); ok { + _spec.SetField(agentskillrepo.FieldScopeID, field.TypeString, value) + _node.ScopeID = value + } + if value, ok := _c.mutation.CreatedBy(); ok { + _spec.SetField(agentskillrepo.FieldCreatedBy, field.TypeUUID, value) + _node.CreatedBy = value + } + if value, ok := _c.mutation.SourceType(); ok { + _spec.SetField(agentskillrepo.FieldSourceType, field.TypeEnum, value) + _node.SourceType = value + } + if value, ok := _c.mutation.GithubURL(); ok { + _spec.SetField(agentskillrepo.FieldGithubURL, field.TypeString, value) + _node.GithubURL = &value + } + if value, ok := _c.mutation.RefType(); ok { + _spec.SetField(agentskillrepo.FieldRefType, field.TypeEnum, value) + _node.RefType = &value + } + if value, ok := _c.mutation.RefValue(); ok { + _spec.SetField(agentskillrepo.FieldRefValue, field.TypeString, value) + _node.RefValue = &value + } + if value, ok := _c.mutation.LastUploadFilename(); ok { + _spec.SetField(agentskillrepo.FieldLastUploadFilename, field.TypeString, value) + _node.LastUploadFilename = &value + } + if value, ok := _c.mutation.LastUploadAt(); ok { + _spec.SetField(agentskillrepo.FieldLastUploadAt, field.TypeTime, value) + _node.LastUploadAt = &value + } + if value, ok := _c.mutation.IsDeleted(); ok { + _spec.SetField(agentskillrepo.FieldIsDeleted, field.TypeBool, value) + _node.IsDeleted = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(agentskillrepo.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(agentskillrepo.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if nodes := _c.mutation.SkillsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agentskillrepo.SkillsTable, + Columns: []string{agentskillrepo.SkillsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentskill.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.AgentSkillRepo.Create(). +// SetName(v). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.AgentSkillRepoUpsert) { +// SetName(v+v). +// }). +// Exec(ctx) +func (_c *AgentSkillRepoCreate) OnConflict(opts ...sql.ConflictOption) *AgentSkillRepoUpsertOne { + _c.conflict = opts + return &AgentSkillRepoUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.AgentSkillRepo.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *AgentSkillRepoCreate) OnConflictColumns(columns ...string) *AgentSkillRepoUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &AgentSkillRepoUpsertOne{ + create: _c, + } +} + +type ( + // AgentSkillRepoUpsertOne is the builder for "upsert"-ing + // one AgentSkillRepo node. + AgentSkillRepoUpsertOne struct { + create *AgentSkillRepoCreate + } + + // AgentSkillRepoUpsert is the "OnConflict" setter. + AgentSkillRepoUpsert struct { + *sql.UpdateSet + } +) + +// SetName sets the "name" field. +func (u *AgentSkillRepoUpsert) SetName(v string) *AgentSkillRepoUpsert { + u.Set(agentskillrepo.FieldName, v) + return u +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *AgentSkillRepoUpsert) UpdateName() *AgentSkillRepoUpsert { + u.SetExcluded(agentskillrepo.FieldName) + return u +} + +// SetScopeType sets the "scope_type" field. +func (u *AgentSkillRepoUpsert) SetScopeType(v agentskillrepo.ScopeType) *AgentSkillRepoUpsert { + u.Set(agentskillrepo.FieldScopeType, v) + return u +} + +// UpdateScopeType sets the "scope_type" field to the value that was provided on create. +func (u *AgentSkillRepoUpsert) UpdateScopeType() *AgentSkillRepoUpsert { + u.SetExcluded(agentskillrepo.FieldScopeType) + return u +} + +// SetScopeID sets the "scope_id" field. +func (u *AgentSkillRepoUpsert) SetScopeID(v string) *AgentSkillRepoUpsert { + u.Set(agentskillrepo.FieldScopeID, v) + return u +} + +// UpdateScopeID sets the "scope_id" field to the value that was provided on create. +func (u *AgentSkillRepoUpsert) UpdateScopeID() *AgentSkillRepoUpsert { + u.SetExcluded(agentskillrepo.FieldScopeID) + return u +} + +// SetCreatedBy sets the "created_by" field. +func (u *AgentSkillRepoUpsert) SetCreatedBy(v uuid.UUID) *AgentSkillRepoUpsert { + u.Set(agentskillrepo.FieldCreatedBy, v) + return u +} + +// UpdateCreatedBy sets the "created_by" field to the value that was provided on create. +func (u *AgentSkillRepoUpsert) UpdateCreatedBy() *AgentSkillRepoUpsert { + u.SetExcluded(agentskillrepo.FieldCreatedBy) + return u +} + +// SetSourceType sets the "source_type" field. +func (u *AgentSkillRepoUpsert) SetSourceType(v agentskillrepo.SourceType) *AgentSkillRepoUpsert { + u.Set(agentskillrepo.FieldSourceType, v) + return u +} + +// UpdateSourceType sets the "source_type" field to the value that was provided on create. +func (u *AgentSkillRepoUpsert) UpdateSourceType() *AgentSkillRepoUpsert { + u.SetExcluded(agentskillrepo.FieldSourceType) + return u +} + +// SetGithubURL sets the "github_url" field. +func (u *AgentSkillRepoUpsert) SetGithubURL(v string) *AgentSkillRepoUpsert { + u.Set(agentskillrepo.FieldGithubURL, v) + return u +} + +// UpdateGithubURL sets the "github_url" field to the value that was provided on create. +func (u *AgentSkillRepoUpsert) UpdateGithubURL() *AgentSkillRepoUpsert { + u.SetExcluded(agentskillrepo.FieldGithubURL) + return u +} + +// ClearGithubURL clears the value of the "github_url" field. +func (u *AgentSkillRepoUpsert) ClearGithubURL() *AgentSkillRepoUpsert { + u.SetNull(agentskillrepo.FieldGithubURL) + return u +} + +// SetRefType sets the "ref_type" field. +func (u *AgentSkillRepoUpsert) SetRefType(v agentskillrepo.RefType) *AgentSkillRepoUpsert { + u.Set(agentskillrepo.FieldRefType, v) + return u +} + +// UpdateRefType sets the "ref_type" field to the value that was provided on create. +func (u *AgentSkillRepoUpsert) UpdateRefType() *AgentSkillRepoUpsert { + u.SetExcluded(agentskillrepo.FieldRefType) + return u +} + +// ClearRefType clears the value of the "ref_type" field. +func (u *AgentSkillRepoUpsert) ClearRefType() *AgentSkillRepoUpsert { + u.SetNull(agentskillrepo.FieldRefType) + return u +} + +// SetRefValue sets the "ref_value" field. +func (u *AgentSkillRepoUpsert) SetRefValue(v string) *AgentSkillRepoUpsert { + u.Set(agentskillrepo.FieldRefValue, v) + return u +} + +// UpdateRefValue sets the "ref_value" field to the value that was provided on create. +func (u *AgentSkillRepoUpsert) UpdateRefValue() *AgentSkillRepoUpsert { + u.SetExcluded(agentskillrepo.FieldRefValue) + return u +} + +// ClearRefValue clears the value of the "ref_value" field. +func (u *AgentSkillRepoUpsert) ClearRefValue() *AgentSkillRepoUpsert { + u.SetNull(agentskillrepo.FieldRefValue) + return u +} + +// SetLastUploadFilename sets the "last_upload_filename" field. +func (u *AgentSkillRepoUpsert) SetLastUploadFilename(v string) *AgentSkillRepoUpsert { + u.Set(agentskillrepo.FieldLastUploadFilename, v) + return u +} + +// UpdateLastUploadFilename sets the "last_upload_filename" field to the value that was provided on create. +func (u *AgentSkillRepoUpsert) UpdateLastUploadFilename() *AgentSkillRepoUpsert { + u.SetExcluded(agentskillrepo.FieldLastUploadFilename) + return u +} + +// ClearLastUploadFilename clears the value of the "last_upload_filename" field. +func (u *AgentSkillRepoUpsert) ClearLastUploadFilename() *AgentSkillRepoUpsert { + u.SetNull(agentskillrepo.FieldLastUploadFilename) + return u +} + +// SetLastUploadAt sets the "last_upload_at" field. +func (u *AgentSkillRepoUpsert) SetLastUploadAt(v time.Time) *AgentSkillRepoUpsert { + u.Set(agentskillrepo.FieldLastUploadAt, v) + return u +} + +// UpdateLastUploadAt sets the "last_upload_at" field to the value that was provided on create. +func (u *AgentSkillRepoUpsert) UpdateLastUploadAt() *AgentSkillRepoUpsert { + u.SetExcluded(agentskillrepo.FieldLastUploadAt) + return u +} + +// ClearLastUploadAt clears the value of the "last_upload_at" field. +func (u *AgentSkillRepoUpsert) ClearLastUploadAt() *AgentSkillRepoUpsert { + u.SetNull(agentskillrepo.FieldLastUploadAt) + return u +} + +// SetIsDeleted sets the "is_deleted" field. +func (u *AgentSkillRepoUpsert) SetIsDeleted(v bool) *AgentSkillRepoUpsert { + u.Set(agentskillrepo.FieldIsDeleted, v) + return u +} + +// UpdateIsDeleted sets the "is_deleted" field to the value that was provided on create. +func (u *AgentSkillRepoUpsert) UpdateIsDeleted() *AgentSkillRepoUpsert { + u.SetExcluded(agentskillrepo.FieldIsDeleted) + return u +} + +// SetCreatedAt sets the "created_at" field. +func (u *AgentSkillRepoUpsert) SetCreatedAt(v time.Time) *AgentSkillRepoUpsert { + u.Set(agentskillrepo.FieldCreatedAt, v) + return u +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *AgentSkillRepoUpsert) UpdateCreatedAt() *AgentSkillRepoUpsert { + u.SetExcluded(agentskillrepo.FieldCreatedAt) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *AgentSkillRepoUpsert) SetUpdatedAt(v time.Time) *AgentSkillRepoUpsert { + u.Set(agentskillrepo.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *AgentSkillRepoUpsert) UpdateUpdatedAt() *AgentSkillRepoUpsert { + u.SetExcluded(agentskillrepo.FieldUpdatedAt) + return u +} + +// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field. +// Using this option is equivalent to using: +// +// client.AgentSkillRepo.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(agentskillrepo.FieldID) +// }), +// ). +// Exec(ctx) +func (u *AgentSkillRepoUpsertOne) UpdateNewValues() *AgentSkillRepoUpsertOne { + 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(agentskillrepo.FieldID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.AgentSkillRepo.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *AgentSkillRepoUpsertOne) Ignore() *AgentSkillRepoUpsertOne { + 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 *AgentSkillRepoUpsertOne) DoNothing() *AgentSkillRepoUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the AgentSkillRepoCreate.OnConflict +// documentation for more info. +func (u *AgentSkillRepoUpsertOne) Update(set func(*AgentSkillRepoUpsert)) *AgentSkillRepoUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&AgentSkillRepoUpsert{UpdateSet: update}) + })) + return u +} + +// SetName sets the "name" field. +func (u *AgentSkillRepoUpsertOne) SetName(v string) *AgentSkillRepoUpsertOne { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *AgentSkillRepoUpsertOne) UpdateName() *AgentSkillRepoUpsertOne { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.UpdateName() + }) +} + +// SetScopeType sets the "scope_type" field. +func (u *AgentSkillRepoUpsertOne) SetScopeType(v agentskillrepo.ScopeType) *AgentSkillRepoUpsertOne { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.SetScopeType(v) + }) +} + +// UpdateScopeType sets the "scope_type" field to the value that was provided on create. +func (u *AgentSkillRepoUpsertOne) UpdateScopeType() *AgentSkillRepoUpsertOne { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.UpdateScopeType() + }) +} + +// SetScopeID sets the "scope_id" field. +func (u *AgentSkillRepoUpsertOne) SetScopeID(v string) *AgentSkillRepoUpsertOne { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.SetScopeID(v) + }) +} + +// UpdateScopeID sets the "scope_id" field to the value that was provided on create. +func (u *AgentSkillRepoUpsertOne) UpdateScopeID() *AgentSkillRepoUpsertOne { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.UpdateScopeID() + }) +} + +// SetCreatedBy sets the "created_by" field. +func (u *AgentSkillRepoUpsertOne) SetCreatedBy(v uuid.UUID) *AgentSkillRepoUpsertOne { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.SetCreatedBy(v) + }) +} + +// UpdateCreatedBy sets the "created_by" field to the value that was provided on create. +func (u *AgentSkillRepoUpsertOne) UpdateCreatedBy() *AgentSkillRepoUpsertOne { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.UpdateCreatedBy() + }) +} + +// SetSourceType sets the "source_type" field. +func (u *AgentSkillRepoUpsertOne) SetSourceType(v agentskillrepo.SourceType) *AgentSkillRepoUpsertOne { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.SetSourceType(v) + }) +} + +// UpdateSourceType sets the "source_type" field to the value that was provided on create. +func (u *AgentSkillRepoUpsertOne) UpdateSourceType() *AgentSkillRepoUpsertOne { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.UpdateSourceType() + }) +} + +// SetGithubURL sets the "github_url" field. +func (u *AgentSkillRepoUpsertOne) SetGithubURL(v string) *AgentSkillRepoUpsertOne { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.SetGithubURL(v) + }) +} + +// UpdateGithubURL sets the "github_url" field to the value that was provided on create. +func (u *AgentSkillRepoUpsertOne) UpdateGithubURL() *AgentSkillRepoUpsertOne { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.UpdateGithubURL() + }) +} + +// ClearGithubURL clears the value of the "github_url" field. +func (u *AgentSkillRepoUpsertOne) ClearGithubURL() *AgentSkillRepoUpsertOne { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.ClearGithubURL() + }) +} + +// SetRefType sets the "ref_type" field. +func (u *AgentSkillRepoUpsertOne) SetRefType(v agentskillrepo.RefType) *AgentSkillRepoUpsertOne { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.SetRefType(v) + }) +} + +// UpdateRefType sets the "ref_type" field to the value that was provided on create. +func (u *AgentSkillRepoUpsertOne) UpdateRefType() *AgentSkillRepoUpsertOne { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.UpdateRefType() + }) +} + +// ClearRefType clears the value of the "ref_type" field. +func (u *AgentSkillRepoUpsertOne) ClearRefType() *AgentSkillRepoUpsertOne { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.ClearRefType() + }) +} + +// SetRefValue sets the "ref_value" field. +func (u *AgentSkillRepoUpsertOne) SetRefValue(v string) *AgentSkillRepoUpsertOne { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.SetRefValue(v) + }) +} + +// UpdateRefValue sets the "ref_value" field to the value that was provided on create. +func (u *AgentSkillRepoUpsertOne) UpdateRefValue() *AgentSkillRepoUpsertOne { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.UpdateRefValue() + }) +} + +// ClearRefValue clears the value of the "ref_value" field. +func (u *AgentSkillRepoUpsertOne) ClearRefValue() *AgentSkillRepoUpsertOne { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.ClearRefValue() + }) +} + +// SetLastUploadFilename sets the "last_upload_filename" field. +func (u *AgentSkillRepoUpsertOne) SetLastUploadFilename(v string) *AgentSkillRepoUpsertOne { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.SetLastUploadFilename(v) + }) +} + +// UpdateLastUploadFilename sets the "last_upload_filename" field to the value that was provided on create. +func (u *AgentSkillRepoUpsertOne) UpdateLastUploadFilename() *AgentSkillRepoUpsertOne { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.UpdateLastUploadFilename() + }) +} + +// ClearLastUploadFilename clears the value of the "last_upload_filename" field. +func (u *AgentSkillRepoUpsertOne) ClearLastUploadFilename() *AgentSkillRepoUpsertOne { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.ClearLastUploadFilename() + }) +} + +// SetLastUploadAt sets the "last_upload_at" field. +func (u *AgentSkillRepoUpsertOne) SetLastUploadAt(v time.Time) *AgentSkillRepoUpsertOne { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.SetLastUploadAt(v) + }) +} + +// UpdateLastUploadAt sets the "last_upload_at" field to the value that was provided on create. +func (u *AgentSkillRepoUpsertOne) UpdateLastUploadAt() *AgentSkillRepoUpsertOne { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.UpdateLastUploadAt() + }) +} + +// ClearLastUploadAt clears the value of the "last_upload_at" field. +func (u *AgentSkillRepoUpsertOne) ClearLastUploadAt() *AgentSkillRepoUpsertOne { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.ClearLastUploadAt() + }) +} + +// SetIsDeleted sets the "is_deleted" field. +func (u *AgentSkillRepoUpsertOne) SetIsDeleted(v bool) *AgentSkillRepoUpsertOne { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.SetIsDeleted(v) + }) +} + +// UpdateIsDeleted sets the "is_deleted" field to the value that was provided on create. +func (u *AgentSkillRepoUpsertOne) UpdateIsDeleted() *AgentSkillRepoUpsertOne { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.UpdateIsDeleted() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *AgentSkillRepoUpsertOne) SetCreatedAt(v time.Time) *AgentSkillRepoUpsertOne { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *AgentSkillRepoUpsertOne) UpdateCreatedAt() *AgentSkillRepoUpsertOne { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.UpdateCreatedAt() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *AgentSkillRepoUpsertOne) SetUpdatedAt(v time.Time) *AgentSkillRepoUpsertOne { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *AgentSkillRepoUpsertOne) UpdateUpdatedAt() *AgentSkillRepoUpsertOne { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.UpdateUpdatedAt() + }) +} + +// Exec executes the query. +func (u *AgentSkillRepoUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for AgentSkillRepoCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *AgentSkillRepoUpsertOne) 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 *AgentSkillRepoUpsertOne) 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: AgentSkillRepoUpsertOne.ID is not supported by MySQL driver. Use AgentSkillRepoUpsertOne.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 *AgentSkillRepoUpsertOne) IDX(ctx context.Context) uuid.UUID { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// AgentSkillRepoCreateBulk is the builder for creating many AgentSkillRepo entities in bulk. +type AgentSkillRepoCreateBulk struct { + config + err error + builders []*AgentSkillRepoCreate + conflict []sql.ConflictOption +} + +// Save creates the AgentSkillRepo entities in the database. +func (_c *AgentSkillRepoCreateBulk) Save(ctx context.Context) ([]*AgentSkillRepo, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*AgentSkillRepo, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*AgentSkillRepoMutation) + 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, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = _c.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.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, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *AgentSkillRepoCreateBulk) SaveX(ctx context.Context) []*AgentSkillRepo { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *AgentSkillRepoCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *AgentSkillRepoCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.AgentSkillRepo.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.AgentSkillRepoUpsert) { +// SetName(v+v). +// }). +// Exec(ctx) +func (_c *AgentSkillRepoCreateBulk) OnConflict(opts ...sql.ConflictOption) *AgentSkillRepoUpsertBulk { + _c.conflict = opts + return &AgentSkillRepoUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.AgentSkillRepo.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *AgentSkillRepoCreateBulk) OnConflictColumns(columns ...string) *AgentSkillRepoUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &AgentSkillRepoUpsertBulk{ + create: _c, + } +} + +// AgentSkillRepoUpsertBulk is the builder for "upsert"-ing +// a bulk of AgentSkillRepo nodes. +type AgentSkillRepoUpsertBulk struct { + create *AgentSkillRepoCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.AgentSkillRepo.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(agentskillrepo.FieldID) +// }), +// ). +// Exec(ctx) +func (u *AgentSkillRepoUpsertBulk) UpdateNewValues() *AgentSkillRepoUpsertBulk { + 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(agentskillrepo.FieldID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.AgentSkillRepo.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *AgentSkillRepoUpsertBulk) Ignore() *AgentSkillRepoUpsertBulk { + 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 *AgentSkillRepoUpsertBulk) DoNothing() *AgentSkillRepoUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the AgentSkillRepoCreateBulk.OnConflict +// documentation for more info. +func (u *AgentSkillRepoUpsertBulk) Update(set func(*AgentSkillRepoUpsert)) *AgentSkillRepoUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&AgentSkillRepoUpsert{UpdateSet: update}) + })) + return u +} + +// SetName sets the "name" field. +func (u *AgentSkillRepoUpsertBulk) SetName(v string) *AgentSkillRepoUpsertBulk { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *AgentSkillRepoUpsertBulk) UpdateName() *AgentSkillRepoUpsertBulk { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.UpdateName() + }) +} + +// SetScopeType sets the "scope_type" field. +func (u *AgentSkillRepoUpsertBulk) SetScopeType(v agentskillrepo.ScopeType) *AgentSkillRepoUpsertBulk { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.SetScopeType(v) + }) +} + +// UpdateScopeType sets the "scope_type" field to the value that was provided on create. +func (u *AgentSkillRepoUpsertBulk) UpdateScopeType() *AgentSkillRepoUpsertBulk { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.UpdateScopeType() + }) +} + +// SetScopeID sets the "scope_id" field. +func (u *AgentSkillRepoUpsertBulk) SetScopeID(v string) *AgentSkillRepoUpsertBulk { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.SetScopeID(v) + }) +} + +// UpdateScopeID sets the "scope_id" field to the value that was provided on create. +func (u *AgentSkillRepoUpsertBulk) UpdateScopeID() *AgentSkillRepoUpsertBulk { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.UpdateScopeID() + }) +} + +// SetCreatedBy sets the "created_by" field. +func (u *AgentSkillRepoUpsertBulk) SetCreatedBy(v uuid.UUID) *AgentSkillRepoUpsertBulk { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.SetCreatedBy(v) + }) +} + +// UpdateCreatedBy sets the "created_by" field to the value that was provided on create. +func (u *AgentSkillRepoUpsertBulk) UpdateCreatedBy() *AgentSkillRepoUpsertBulk { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.UpdateCreatedBy() + }) +} + +// SetSourceType sets the "source_type" field. +func (u *AgentSkillRepoUpsertBulk) SetSourceType(v agentskillrepo.SourceType) *AgentSkillRepoUpsertBulk { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.SetSourceType(v) + }) +} + +// UpdateSourceType sets the "source_type" field to the value that was provided on create. +func (u *AgentSkillRepoUpsertBulk) UpdateSourceType() *AgentSkillRepoUpsertBulk { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.UpdateSourceType() + }) +} + +// SetGithubURL sets the "github_url" field. +func (u *AgentSkillRepoUpsertBulk) SetGithubURL(v string) *AgentSkillRepoUpsertBulk { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.SetGithubURL(v) + }) +} + +// UpdateGithubURL sets the "github_url" field to the value that was provided on create. +func (u *AgentSkillRepoUpsertBulk) UpdateGithubURL() *AgentSkillRepoUpsertBulk { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.UpdateGithubURL() + }) +} + +// ClearGithubURL clears the value of the "github_url" field. +func (u *AgentSkillRepoUpsertBulk) ClearGithubURL() *AgentSkillRepoUpsertBulk { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.ClearGithubURL() + }) +} + +// SetRefType sets the "ref_type" field. +func (u *AgentSkillRepoUpsertBulk) SetRefType(v agentskillrepo.RefType) *AgentSkillRepoUpsertBulk { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.SetRefType(v) + }) +} + +// UpdateRefType sets the "ref_type" field to the value that was provided on create. +func (u *AgentSkillRepoUpsertBulk) UpdateRefType() *AgentSkillRepoUpsertBulk { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.UpdateRefType() + }) +} + +// ClearRefType clears the value of the "ref_type" field. +func (u *AgentSkillRepoUpsertBulk) ClearRefType() *AgentSkillRepoUpsertBulk { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.ClearRefType() + }) +} + +// SetRefValue sets the "ref_value" field. +func (u *AgentSkillRepoUpsertBulk) SetRefValue(v string) *AgentSkillRepoUpsertBulk { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.SetRefValue(v) + }) +} + +// UpdateRefValue sets the "ref_value" field to the value that was provided on create. +func (u *AgentSkillRepoUpsertBulk) UpdateRefValue() *AgentSkillRepoUpsertBulk { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.UpdateRefValue() + }) +} + +// ClearRefValue clears the value of the "ref_value" field. +func (u *AgentSkillRepoUpsertBulk) ClearRefValue() *AgentSkillRepoUpsertBulk { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.ClearRefValue() + }) +} + +// SetLastUploadFilename sets the "last_upload_filename" field. +func (u *AgentSkillRepoUpsertBulk) SetLastUploadFilename(v string) *AgentSkillRepoUpsertBulk { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.SetLastUploadFilename(v) + }) +} + +// UpdateLastUploadFilename sets the "last_upload_filename" field to the value that was provided on create. +func (u *AgentSkillRepoUpsertBulk) UpdateLastUploadFilename() *AgentSkillRepoUpsertBulk { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.UpdateLastUploadFilename() + }) +} + +// ClearLastUploadFilename clears the value of the "last_upload_filename" field. +func (u *AgentSkillRepoUpsertBulk) ClearLastUploadFilename() *AgentSkillRepoUpsertBulk { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.ClearLastUploadFilename() + }) +} + +// SetLastUploadAt sets the "last_upload_at" field. +func (u *AgentSkillRepoUpsertBulk) SetLastUploadAt(v time.Time) *AgentSkillRepoUpsertBulk { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.SetLastUploadAt(v) + }) +} + +// UpdateLastUploadAt sets the "last_upload_at" field to the value that was provided on create. +func (u *AgentSkillRepoUpsertBulk) UpdateLastUploadAt() *AgentSkillRepoUpsertBulk { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.UpdateLastUploadAt() + }) +} + +// ClearLastUploadAt clears the value of the "last_upload_at" field. +func (u *AgentSkillRepoUpsertBulk) ClearLastUploadAt() *AgentSkillRepoUpsertBulk { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.ClearLastUploadAt() + }) +} + +// SetIsDeleted sets the "is_deleted" field. +func (u *AgentSkillRepoUpsertBulk) SetIsDeleted(v bool) *AgentSkillRepoUpsertBulk { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.SetIsDeleted(v) + }) +} + +// UpdateIsDeleted sets the "is_deleted" field to the value that was provided on create. +func (u *AgentSkillRepoUpsertBulk) UpdateIsDeleted() *AgentSkillRepoUpsertBulk { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.UpdateIsDeleted() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *AgentSkillRepoUpsertBulk) SetCreatedAt(v time.Time) *AgentSkillRepoUpsertBulk { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *AgentSkillRepoUpsertBulk) UpdateCreatedAt() *AgentSkillRepoUpsertBulk { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.UpdateCreatedAt() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *AgentSkillRepoUpsertBulk) SetUpdatedAt(v time.Time) *AgentSkillRepoUpsertBulk { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *AgentSkillRepoUpsertBulk) UpdateUpdatedAt() *AgentSkillRepoUpsertBulk { + return u.Update(func(s *AgentSkillRepoUpsert) { + s.UpdateUpdatedAt() + }) +} + +// Exec executes the query. +func (u *AgentSkillRepoUpsertBulk) 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 AgentSkillRepoCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for AgentSkillRepoCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *AgentSkillRepoUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/agentskillrepo_delete.go b/backend/db/agentskillrepo_delete.go new file mode 100644 index 00000000..6e278b66 --- /dev/null +++ b/backend/db/agentskillrepo_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/agentskillrepo" + "github.com/chaitin/MonkeyCode/backend/db/predicate" +) + +// AgentSkillRepoDelete is the builder for deleting a AgentSkillRepo entity. +type AgentSkillRepoDelete struct { + config + hooks []Hook + mutation *AgentSkillRepoMutation +} + +// Where appends a list predicates to the AgentSkillRepoDelete builder. +func (_d *AgentSkillRepoDelete) Where(ps ...predicate.AgentSkillRepo) *AgentSkillRepoDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *AgentSkillRepoDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *AgentSkillRepoDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *AgentSkillRepoDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(agentskillrepo.Table, sqlgraph.NewFieldSpec(agentskillrepo.FieldID, field.TypeUUID)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// AgentSkillRepoDeleteOne is the builder for deleting a single AgentSkillRepo entity. +type AgentSkillRepoDeleteOne struct { + _d *AgentSkillRepoDelete +} + +// Where appends a list predicates to the AgentSkillRepoDelete builder. +func (_d *AgentSkillRepoDeleteOne) Where(ps ...predicate.AgentSkillRepo) *AgentSkillRepoDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *AgentSkillRepoDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{agentskillrepo.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *AgentSkillRepoDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/agentskillrepo_query.go b/backend/db/agentskillrepo_query.go new file mode 100644 index 00000000..b85fd0dd --- /dev/null +++ b/backend/db/agentskillrepo_query.go @@ -0,0 +1,657 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "database/sql/driver" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/agentskill" + "github.com/chaitin/MonkeyCode/backend/db/agentskillrepo" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/google/uuid" +) + +// AgentSkillRepoQuery is the builder for querying AgentSkillRepo entities. +type AgentSkillRepoQuery struct { + config + ctx *QueryContext + order []agentskillrepo.OrderOption + inters []Interceptor + predicates []predicate.AgentSkillRepo + withSkills *AgentSkillQuery + 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 AgentSkillRepoQuery builder. +func (_q *AgentSkillRepoQuery) Where(ps ...predicate.AgentSkillRepo) *AgentSkillRepoQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *AgentSkillRepoQuery) Limit(limit int) *AgentSkillRepoQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *AgentSkillRepoQuery) Offset(offset int) *AgentSkillRepoQuery { + _q.ctx.Offset = &offset + return _q +} + +// 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 (_q *AgentSkillRepoQuery) Unique(unique bool) *AgentSkillRepoQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *AgentSkillRepoQuery) Order(o ...agentskillrepo.OrderOption) *AgentSkillRepoQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QuerySkills chains the current query on the "skills" edge. +func (_q *AgentSkillRepoQuery) QuerySkills() *AgentSkillQuery { + query := (&AgentSkillClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(agentskillrepo.Table, agentskillrepo.FieldID, selector), + sqlgraph.To(agentskill.Table, agentskill.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, agentskillrepo.SkillsTable, agentskillrepo.SkillsColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first AgentSkillRepo entity from the query. +// Returns a *NotFoundError when no AgentSkillRepo was found. +func (_q *AgentSkillRepoQuery) First(ctx context.Context) (*AgentSkillRepo, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{agentskillrepo.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *AgentSkillRepoQuery) FirstX(ctx context.Context) *AgentSkillRepo { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first AgentSkillRepo ID from the query. +// Returns a *NotFoundError when no AgentSkillRepo ID was found. +func (_q *AgentSkillRepoQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{agentskillrepo.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *AgentSkillRepoQuery) FirstIDX(ctx context.Context) uuid.UUID { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single AgentSkillRepo entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one AgentSkillRepo entity is found. +// Returns a *NotFoundError when no AgentSkillRepo entities are found. +func (_q *AgentSkillRepoQuery) Only(ctx context.Context) (*AgentSkillRepo, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{agentskillrepo.Label} + default: + return nil, &NotSingularError{agentskillrepo.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *AgentSkillRepoQuery) OnlyX(ctx context.Context) *AgentSkillRepo { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only AgentSkillRepo ID in the query. +// Returns a *NotSingularError when more than one AgentSkillRepo ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *AgentSkillRepoQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{agentskillrepo.Label} + default: + err = &NotSingularError{agentskillrepo.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *AgentSkillRepoQuery) OnlyIDX(ctx context.Context) uuid.UUID { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of AgentSkillRepos. +func (_q *AgentSkillRepoQuery) All(ctx context.Context) ([]*AgentSkillRepo, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*AgentSkillRepo, *AgentSkillRepoQuery]() + return withInterceptors[[]*AgentSkillRepo](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *AgentSkillRepoQuery) AllX(ctx context.Context) []*AgentSkillRepo { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of AgentSkillRepo IDs. +func (_q *AgentSkillRepoQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(agentskillrepo.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *AgentSkillRepoQuery) IDsX(ctx context.Context) []uuid.UUID { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *AgentSkillRepoQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*AgentSkillRepoQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *AgentSkillRepoQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *AgentSkillRepoQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.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 (_q *AgentSkillRepoQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the AgentSkillRepoQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *AgentSkillRepoQuery) Clone() *AgentSkillRepoQuery { + if _q == nil { + return nil + } + return &AgentSkillRepoQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]agentskillrepo.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.AgentSkillRepo{}, _q.predicates...), + withSkills: _q.withSkills.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + modifiers: append([]func(*sql.Selector){}, _q.modifiers...), + } +} + +// WithSkills tells the query-builder to eager-load the nodes that are connected to +// the "skills" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *AgentSkillRepoQuery) WithSkills(opts ...func(*AgentSkillQuery)) *AgentSkillRepoQuery { + query := (&AgentSkillClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withSkills = query + return _q +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// Name string `json:"name,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.AgentSkillRepo.Query(). +// GroupBy(agentskillrepo.FieldName). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *AgentSkillRepoQuery) GroupBy(field string, fields ...string) *AgentSkillRepoGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &AgentSkillRepoGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = agentskillrepo.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// Name string `json:"name,omitempty"` +// } +// +// client.AgentSkillRepo.Query(). +// Select(agentskillrepo.FieldName). +// Scan(ctx, &v) +func (_q *AgentSkillRepoQuery) Select(fields ...string) *AgentSkillRepoSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &AgentSkillRepoSelect{AgentSkillRepoQuery: _q} + sbuild.label = agentskillrepo.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a AgentSkillRepoSelect configured with the given aggregations. +func (_q *AgentSkillRepoQuery) Aggregate(fns ...AggregateFunc) *AgentSkillRepoSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *AgentSkillRepoQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.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, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !agentskillrepo.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *AgentSkillRepoQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*AgentSkillRepo, error) { + var ( + nodes = []*AgentSkillRepo{} + _spec = _q.querySpec() + loadedTypes = [1]bool{ + _q.withSkills != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*AgentSkillRepo).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &AgentSkillRepo{config: _q.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := _q.withSkills; query != nil { + if err := _q.loadSkills(ctx, query, nodes, + func(n *AgentSkillRepo) { n.Edges.Skills = []*AgentSkill{} }, + func(n *AgentSkillRepo, e *AgentSkill) { n.Edges.Skills = append(n.Edges.Skills, e) }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *AgentSkillRepoQuery) loadSkills(ctx context.Context, query *AgentSkillQuery, nodes []*AgentSkillRepo, init func(*AgentSkillRepo), assign func(*AgentSkillRepo, *AgentSkill)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[uuid.UUID]*AgentSkillRepo) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) + } + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(agentskill.FieldRepoID) + } + query.Where(predicate.AgentSkill(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(agentskillrepo.SkillsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.RepoID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "repo_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} + +func (_q *AgentSkillRepoQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *AgentSkillRepoQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(agentskillrepo.Table, agentskillrepo.Columns, sqlgraph.NewFieldSpec(agentskillrepo.FieldID, field.TypeUUID)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, agentskillrepo.FieldID) + for i := range fields { + if fields[i] != agentskillrepo.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *AgentSkillRepoQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(agentskillrepo.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = agentskillrepo.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, m := range _q.modifiers { + m(selector) + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.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 := _q.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 (_q *AgentSkillRepoQuery) ForUpdate(opts ...sql.LockOption) *AgentSkillRepoQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForUpdate(opts...) + }) + return _q +} + +// 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 (_q *AgentSkillRepoQuery) ForShare(opts ...sql.LockOption) *AgentSkillRepoQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (_q *AgentSkillRepoQuery) Modify(modifiers ...func(s *sql.Selector)) *AgentSkillRepoSelect { + _q.modifiers = append(_q.modifiers, modifiers...) + return _q.Select() +} + +// AgentSkillRepoGroupBy is the group-by builder for AgentSkillRepo entities. +type AgentSkillRepoGroupBy struct { + selector + build *AgentSkillRepoQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *AgentSkillRepoGroupBy) Aggregate(fns ...AggregateFunc) *AgentSkillRepoGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *AgentSkillRepoGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*AgentSkillRepoQuery, *AgentSkillRepoGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *AgentSkillRepoGroupBy) sqlScan(ctx context.Context, root *AgentSkillRepoQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// AgentSkillRepoSelect is the builder for selecting fields of AgentSkillRepo entities. +type AgentSkillRepoSelect struct { + *AgentSkillRepoQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *AgentSkillRepoSelect) Aggregate(fns ...AggregateFunc) *AgentSkillRepoSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *AgentSkillRepoSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*AgentSkillRepoQuery, *AgentSkillRepoSelect](ctx, _s.AgentSkillRepoQuery, _s, _s.inters, v) +} + +func (_s *AgentSkillRepoSelect) sqlScan(ctx context.Context, root *AgentSkillRepoQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.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 := _s.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 (_s *AgentSkillRepoSelect) Modify(modifiers ...func(s *sql.Selector)) *AgentSkillRepoSelect { + _s.modifiers = append(_s.modifiers, modifiers...) + return _s +} diff --git a/backend/db/agentskillrepo_update.go b/backend/db/agentskillrepo_update.go new file mode 100644 index 00000000..1064d49f --- /dev/null +++ b/backend/db/agentskillrepo_update.go @@ -0,0 +1,946 @@ +// 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/agentskill" + "github.com/chaitin/MonkeyCode/backend/db/agentskillrepo" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/google/uuid" +) + +// AgentSkillRepoUpdate is the builder for updating AgentSkillRepo entities. +type AgentSkillRepoUpdate struct { + config + hooks []Hook + mutation *AgentSkillRepoMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the AgentSkillRepoUpdate builder. +func (_u *AgentSkillRepoUpdate) Where(ps ...predicate.AgentSkillRepo) *AgentSkillRepoUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetName sets the "name" field. +func (_u *AgentSkillRepoUpdate) SetName(v string) *AgentSkillRepoUpdate { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *AgentSkillRepoUpdate) SetNillableName(v *string) *AgentSkillRepoUpdate { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetScopeType sets the "scope_type" field. +func (_u *AgentSkillRepoUpdate) SetScopeType(v agentskillrepo.ScopeType) *AgentSkillRepoUpdate { + _u.mutation.SetScopeType(v) + return _u +} + +// SetNillableScopeType sets the "scope_type" field if the given value is not nil. +func (_u *AgentSkillRepoUpdate) SetNillableScopeType(v *agentskillrepo.ScopeType) *AgentSkillRepoUpdate { + if v != nil { + _u.SetScopeType(*v) + } + return _u +} + +// SetScopeID sets the "scope_id" field. +func (_u *AgentSkillRepoUpdate) SetScopeID(v string) *AgentSkillRepoUpdate { + _u.mutation.SetScopeID(v) + return _u +} + +// SetNillableScopeID sets the "scope_id" field if the given value is not nil. +func (_u *AgentSkillRepoUpdate) SetNillableScopeID(v *string) *AgentSkillRepoUpdate { + if v != nil { + _u.SetScopeID(*v) + } + return _u +} + +// SetCreatedBy sets the "created_by" field. +func (_u *AgentSkillRepoUpdate) SetCreatedBy(v uuid.UUID) *AgentSkillRepoUpdate { + _u.mutation.SetCreatedBy(v) + return _u +} + +// SetNillableCreatedBy sets the "created_by" field if the given value is not nil. +func (_u *AgentSkillRepoUpdate) SetNillableCreatedBy(v *uuid.UUID) *AgentSkillRepoUpdate { + if v != nil { + _u.SetCreatedBy(*v) + } + return _u +} + +// SetSourceType sets the "source_type" field. +func (_u *AgentSkillRepoUpdate) SetSourceType(v agentskillrepo.SourceType) *AgentSkillRepoUpdate { + _u.mutation.SetSourceType(v) + return _u +} + +// SetNillableSourceType sets the "source_type" field if the given value is not nil. +func (_u *AgentSkillRepoUpdate) SetNillableSourceType(v *agentskillrepo.SourceType) *AgentSkillRepoUpdate { + if v != nil { + _u.SetSourceType(*v) + } + return _u +} + +// SetGithubURL sets the "github_url" field. +func (_u *AgentSkillRepoUpdate) SetGithubURL(v string) *AgentSkillRepoUpdate { + _u.mutation.SetGithubURL(v) + return _u +} + +// SetNillableGithubURL sets the "github_url" field if the given value is not nil. +func (_u *AgentSkillRepoUpdate) SetNillableGithubURL(v *string) *AgentSkillRepoUpdate { + if v != nil { + _u.SetGithubURL(*v) + } + return _u +} + +// ClearGithubURL clears the value of the "github_url" field. +func (_u *AgentSkillRepoUpdate) ClearGithubURL() *AgentSkillRepoUpdate { + _u.mutation.ClearGithubURL() + return _u +} + +// SetRefType sets the "ref_type" field. +func (_u *AgentSkillRepoUpdate) SetRefType(v agentskillrepo.RefType) *AgentSkillRepoUpdate { + _u.mutation.SetRefType(v) + return _u +} + +// SetNillableRefType sets the "ref_type" field if the given value is not nil. +func (_u *AgentSkillRepoUpdate) SetNillableRefType(v *agentskillrepo.RefType) *AgentSkillRepoUpdate { + if v != nil { + _u.SetRefType(*v) + } + return _u +} + +// ClearRefType clears the value of the "ref_type" field. +func (_u *AgentSkillRepoUpdate) ClearRefType() *AgentSkillRepoUpdate { + _u.mutation.ClearRefType() + return _u +} + +// SetRefValue sets the "ref_value" field. +func (_u *AgentSkillRepoUpdate) SetRefValue(v string) *AgentSkillRepoUpdate { + _u.mutation.SetRefValue(v) + return _u +} + +// SetNillableRefValue sets the "ref_value" field if the given value is not nil. +func (_u *AgentSkillRepoUpdate) SetNillableRefValue(v *string) *AgentSkillRepoUpdate { + if v != nil { + _u.SetRefValue(*v) + } + return _u +} + +// ClearRefValue clears the value of the "ref_value" field. +func (_u *AgentSkillRepoUpdate) ClearRefValue() *AgentSkillRepoUpdate { + _u.mutation.ClearRefValue() + return _u +} + +// SetLastUploadFilename sets the "last_upload_filename" field. +func (_u *AgentSkillRepoUpdate) SetLastUploadFilename(v string) *AgentSkillRepoUpdate { + _u.mutation.SetLastUploadFilename(v) + return _u +} + +// SetNillableLastUploadFilename sets the "last_upload_filename" field if the given value is not nil. +func (_u *AgentSkillRepoUpdate) SetNillableLastUploadFilename(v *string) *AgentSkillRepoUpdate { + if v != nil { + _u.SetLastUploadFilename(*v) + } + return _u +} + +// ClearLastUploadFilename clears the value of the "last_upload_filename" field. +func (_u *AgentSkillRepoUpdate) ClearLastUploadFilename() *AgentSkillRepoUpdate { + _u.mutation.ClearLastUploadFilename() + return _u +} + +// SetLastUploadAt sets the "last_upload_at" field. +func (_u *AgentSkillRepoUpdate) SetLastUploadAt(v time.Time) *AgentSkillRepoUpdate { + _u.mutation.SetLastUploadAt(v) + return _u +} + +// SetNillableLastUploadAt sets the "last_upload_at" field if the given value is not nil. +func (_u *AgentSkillRepoUpdate) SetNillableLastUploadAt(v *time.Time) *AgentSkillRepoUpdate { + if v != nil { + _u.SetLastUploadAt(*v) + } + return _u +} + +// ClearLastUploadAt clears the value of the "last_upload_at" field. +func (_u *AgentSkillRepoUpdate) ClearLastUploadAt() *AgentSkillRepoUpdate { + _u.mutation.ClearLastUploadAt() + return _u +} + +// SetIsDeleted sets the "is_deleted" field. +func (_u *AgentSkillRepoUpdate) SetIsDeleted(v bool) *AgentSkillRepoUpdate { + _u.mutation.SetIsDeleted(v) + return _u +} + +// SetNillableIsDeleted sets the "is_deleted" field if the given value is not nil. +func (_u *AgentSkillRepoUpdate) SetNillableIsDeleted(v *bool) *AgentSkillRepoUpdate { + if v != nil { + _u.SetIsDeleted(*v) + } + return _u +} + +// SetCreatedAt sets the "created_at" field. +func (_u *AgentSkillRepoUpdate) SetCreatedAt(v time.Time) *AgentSkillRepoUpdate { + _u.mutation.SetCreatedAt(v) + return _u +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_u *AgentSkillRepoUpdate) SetNillableCreatedAt(v *time.Time) *AgentSkillRepoUpdate { + if v != nil { + _u.SetCreatedAt(*v) + } + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *AgentSkillRepoUpdate) SetUpdatedAt(v time.Time) *AgentSkillRepoUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// AddSkillIDs adds the "skills" edge to the AgentSkill entity by IDs. +func (_u *AgentSkillRepoUpdate) AddSkillIDs(ids ...uuid.UUID) *AgentSkillRepoUpdate { + _u.mutation.AddSkillIDs(ids...) + return _u +} + +// AddSkills adds the "skills" edges to the AgentSkill entity. +func (_u *AgentSkillRepoUpdate) AddSkills(v ...*AgentSkill) *AgentSkillRepoUpdate { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddSkillIDs(ids...) +} + +// Mutation returns the AgentSkillRepoMutation object of the builder. +func (_u *AgentSkillRepoUpdate) Mutation() *AgentSkillRepoMutation { + return _u.mutation +} + +// ClearSkills clears all "skills" edges to the AgentSkill entity. +func (_u *AgentSkillRepoUpdate) ClearSkills() *AgentSkillRepoUpdate { + _u.mutation.ClearSkills() + return _u +} + +// RemoveSkillIDs removes the "skills" edge to AgentSkill entities by IDs. +func (_u *AgentSkillRepoUpdate) RemoveSkillIDs(ids ...uuid.UUID) *AgentSkillRepoUpdate { + _u.mutation.RemoveSkillIDs(ids...) + return _u +} + +// RemoveSkills removes "skills" edges to AgentSkill entities. +func (_u *AgentSkillRepoUpdate) RemoveSkills(v ...*AgentSkill) *AgentSkillRepoUpdate { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveSkillIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *AgentSkillRepoUpdate) Save(ctx context.Context) (int, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *AgentSkillRepoUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *AgentSkillRepoUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *AgentSkillRepoUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_u *AgentSkillRepoUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := agentskillrepo.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *AgentSkillRepoUpdate) check() error { + if v, ok := _u.mutation.Name(); ok { + if err := agentskillrepo.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "AgentSkillRepo.name": %w`, err)} + } + } + if v, ok := _u.mutation.ScopeType(); ok { + if err := agentskillrepo.ScopeTypeValidator(v); err != nil { + return &ValidationError{Name: "scope_type", err: fmt.Errorf(`db: validator failed for field "AgentSkillRepo.scope_type": %w`, err)} + } + } + if v, ok := _u.mutation.SourceType(); ok { + if err := agentskillrepo.SourceTypeValidator(v); err != nil { + return &ValidationError{Name: "source_type", err: fmt.Errorf(`db: validator failed for field "AgentSkillRepo.source_type": %w`, err)} + } + } + if v, ok := _u.mutation.RefType(); ok { + if err := agentskillrepo.RefTypeValidator(v); err != nil { + return &ValidationError{Name: "ref_type", err: fmt.Errorf(`db: validator failed for field "AgentSkillRepo.ref_type": %w`, err)} + } + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (_u *AgentSkillRepoUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *AgentSkillRepoUpdate { + _u.modifiers = append(_u.modifiers, modifiers...) + return _u +} + +func (_u *AgentSkillRepoUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(agentskillrepo.Table, agentskillrepo.Columns, sqlgraph.NewFieldSpec(agentskillrepo.FieldID, field.TypeUUID)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(agentskillrepo.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.ScopeType(); ok { + _spec.SetField(agentskillrepo.FieldScopeType, field.TypeEnum, value) + } + if value, ok := _u.mutation.ScopeID(); ok { + _spec.SetField(agentskillrepo.FieldScopeID, field.TypeString, value) + } + if value, ok := _u.mutation.CreatedBy(); ok { + _spec.SetField(agentskillrepo.FieldCreatedBy, field.TypeUUID, value) + } + if value, ok := _u.mutation.SourceType(); ok { + _spec.SetField(agentskillrepo.FieldSourceType, field.TypeEnum, value) + } + if value, ok := _u.mutation.GithubURL(); ok { + _spec.SetField(agentskillrepo.FieldGithubURL, field.TypeString, value) + } + if _u.mutation.GithubURLCleared() { + _spec.ClearField(agentskillrepo.FieldGithubURL, field.TypeString) + } + if value, ok := _u.mutation.RefType(); ok { + _spec.SetField(agentskillrepo.FieldRefType, field.TypeEnum, value) + } + if _u.mutation.RefTypeCleared() { + _spec.ClearField(agentskillrepo.FieldRefType, field.TypeEnum) + } + if value, ok := _u.mutation.RefValue(); ok { + _spec.SetField(agentskillrepo.FieldRefValue, field.TypeString, value) + } + if _u.mutation.RefValueCleared() { + _spec.ClearField(agentskillrepo.FieldRefValue, field.TypeString) + } + if value, ok := _u.mutation.LastUploadFilename(); ok { + _spec.SetField(agentskillrepo.FieldLastUploadFilename, field.TypeString, value) + } + if _u.mutation.LastUploadFilenameCleared() { + _spec.ClearField(agentskillrepo.FieldLastUploadFilename, field.TypeString) + } + if value, ok := _u.mutation.LastUploadAt(); ok { + _spec.SetField(agentskillrepo.FieldLastUploadAt, field.TypeTime, value) + } + if _u.mutation.LastUploadAtCleared() { + _spec.ClearField(agentskillrepo.FieldLastUploadAt, field.TypeTime) + } + if value, ok := _u.mutation.IsDeleted(); ok { + _spec.SetField(agentskillrepo.FieldIsDeleted, field.TypeBool, value) + } + if value, ok := _u.mutation.CreatedAt(); ok { + _spec.SetField(agentskillrepo.FieldCreatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(agentskillrepo.FieldUpdatedAt, field.TypeTime, value) + } + if _u.mutation.SkillsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agentskillrepo.SkillsTable, + Columns: []string{agentskillrepo.SkillsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentskill.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedSkillsIDs(); len(nodes) > 0 && !_u.mutation.SkillsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agentskillrepo.SkillsTable, + Columns: []string{agentskillrepo.SkillsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentskill.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.SkillsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agentskillrepo.SkillsTable, + Columns: []string{agentskillrepo.SkillsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentskill.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(_u.modifiers...) + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{agentskillrepo.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// AgentSkillRepoUpdateOne is the builder for updating a single AgentSkillRepo entity. +type AgentSkillRepoUpdateOne struct { + config + fields []string + hooks []Hook + mutation *AgentSkillRepoMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetName sets the "name" field. +func (_u *AgentSkillRepoUpdateOne) SetName(v string) *AgentSkillRepoUpdateOne { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *AgentSkillRepoUpdateOne) SetNillableName(v *string) *AgentSkillRepoUpdateOne { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetScopeType sets the "scope_type" field. +func (_u *AgentSkillRepoUpdateOne) SetScopeType(v agentskillrepo.ScopeType) *AgentSkillRepoUpdateOne { + _u.mutation.SetScopeType(v) + return _u +} + +// SetNillableScopeType sets the "scope_type" field if the given value is not nil. +func (_u *AgentSkillRepoUpdateOne) SetNillableScopeType(v *agentskillrepo.ScopeType) *AgentSkillRepoUpdateOne { + if v != nil { + _u.SetScopeType(*v) + } + return _u +} + +// SetScopeID sets the "scope_id" field. +func (_u *AgentSkillRepoUpdateOne) SetScopeID(v string) *AgentSkillRepoUpdateOne { + _u.mutation.SetScopeID(v) + return _u +} + +// SetNillableScopeID sets the "scope_id" field if the given value is not nil. +func (_u *AgentSkillRepoUpdateOne) SetNillableScopeID(v *string) *AgentSkillRepoUpdateOne { + if v != nil { + _u.SetScopeID(*v) + } + return _u +} + +// SetCreatedBy sets the "created_by" field. +func (_u *AgentSkillRepoUpdateOne) SetCreatedBy(v uuid.UUID) *AgentSkillRepoUpdateOne { + _u.mutation.SetCreatedBy(v) + return _u +} + +// SetNillableCreatedBy sets the "created_by" field if the given value is not nil. +func (_u *AgentSkillRepoUpdateOne) SetNillableCreatedBy(v *uuid.UUID) *AgentSkillRepoUpdateOne { + if v != nil { + _u.SetCreatedBy(*v) + } + return _u +} + +// SetSourceType sets the "source_type" field. +func (_u *AgentSkillRepoUpdateOne) SetSourceType(v agentskillrepo.SourceType) *AgentSkillRepoUpdateOne { + _u.mutation.SetSourceType(v) + return _u +} + +// SetNillableSourceType sets the "source_type" field if the given value is not nil. +func (_u *AgentSkillRepoUpdateOne) SetNillableSourceType(v *agentskillrepo.SourceType) *AgentSkillRepoUpdateOne { + if v != nil { + _u.SetSourceType(*v) + } + return _u +} + +// SetGithubURL sets the "github_url" field. +func (_u *AgentSkillRepoUpdateOne) SetGithubURL(v string) *AgentSkillRepoUpdateOne { + _u.mutation.SetGithubURL(v) + return _u +} + +// SetNillableGithubURL sets the "github_url" field if the given value is not nil. +func (_u *AgentSkillRepoUpdateOne) SetNillableGithubURL(v *string) *AgentSkillRepoUpdateOne { + if v != nil { + _u.SetGithubURL(*v) + } + return _u +} + +// ClearGithubURL clears the value of the "github_url" field. +func (_u *AgentSkillRepoUpdateOne) ClearGithubURL() *AgentSkillRepoUpdateOne { + _u.mutation.ClearGithubURL() + return _u +} + +// SetRefType sets the "ref_type" field. +func (_u *AgentSkillRepoUpdateOne) SetRefType(v agentskillrepo.RefType) *AgentSkillRepoUpdateOne { + _u.mutation.SetRefType(v) + return _u +} + +// SetNillableRefType sets the "ref_type" field if the given value is not nil. +func (_u *AgentSkillRepoUpdateOne) SetNillableRefType(v *agentskillrepo.RefType) *AgentSkillRepoUpdateOne { + if v != nil { + _u.SetRefType(*v) + } + return _u +} + +// ClearRefType clears the value of the "ref_type" field. +func (_u *AgentSkillRepoUpdateOne) ClearRefType() *AgentSkillRepoUpdateOne { + _u.mutation.ClearRefType() + return _u +} + +// SetRefValue sets the "ref_value" field. +func (_u *AgentSkillRepoUpdateOne) SetRefValue(v string) *AgentSkillRepoUpdateOne { + _u.mutation.SetRefValue(v) + return _u +} + +// SetNillableRefValue sets the "ref_value" field if the given value is not nil. +func (_u *AgentSkillRepoUpdateOne) SetNillableRefValue(v *string) *AgentSkillRepoUpdateOne { + if v != nil { + _u.SetRefValue(*v) + } + return _u +} + +// ClearRefValue clears the value of the "ref_value" field. +func (_u *AgentSkillRepoUpdateOne) ClearRefValue() *AgentSkillRepoUpdateOne { + _u.mutation.ClearRefValue() + return _u +} + +// SetLastUploadFilename sets the "last_upload_filename" field. +func (_u *AgentSkillRepoUpdateOne) SetLastUploadFilename(v string) *AgentSkillRepoUpdateOne { + _u.mutation.SetLastUploadFilename(v) + return _u +} + +// SetNillableLastUploadFilename sets the "last_upload_filename" field if the given value is not nil. +func (_u *AgentSkillRepoUpdateOne) SetNillableLastUploadFilename(v *string) *AgentSkillRepoUpdateOne { + if v != nil { + _u.SetLastUploadFilename(*v) + } + return _u +} + +// ClearLastUploadFilename clears the value of the "last_upload_filename" field. +func (_u *AgentSkillRepoUpdateOne) ClearLastUploadFilename() *AgentSkillRepoUpdateOne { + _u.mutation.ClearLastUploadFilename() + return _u +} + +// SetLastUploadAt sets the "last_upload_at" field. +func (_u *AgentSkillRepoUpdateOne) SetLastUploadAt(v time.Time) *AgentSkillRepoUpdateOne { + _u.mutation.SetLastUploadAt(v) + return _u +} + +// SetNillableLastUploadAt sets the "last_upload_at" field if the given value is not nil. +func (_u *AgentSkillRepoUpdateOne) SetNillableLastUploadAt(v *time.Time) *AgentSkillRepoUpdateOne { + if v != nil { + _u.SetLastUploadAt(*v) + } + return _u +} + +// ClearLastUploadAt clears the value of the "last_upload_at" field. +func (_u *AgentSkillRepoUpdateOne) ClearLastUploadAt() *AgentSkillRepoUpdateOne { + _u.mutation.ClearLastUploadAt() + return _u +} + +// SetIsDeleted sets the "is_deleted" field. +func (_u *AgentSkillRepoUpdateOne) SetIsDeleted(v bool) *AgentSkillRepoUpdateOne { + _u.mutation.SetIsDeleted(v) + return _u +} + +// SetNillableIsDeleted sets the "is_deleted" field if the given value is not nil. +func (_u *AgentSkillRepoUpdateOne) SetNillableIsDeleted(v *bool) *AgentSkillRepoUpdateOne { + if v != nil { + _u.SetIsDeleted(*v) + } + return _u +} + +// SetCreatedAt sets the "created_at" field. +func (_u *AgentSkillRepoUpdateOne) SetCreatedAt(v time.Time) *AgentSkillRepoUpdateOne { + _u.mutation.SetCreatedAt(v) + return _u +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_u *AgentSkillRepoUpdateOne) SetNillableCreatedAt(v *time.Time) *AgentSkillRepoUpdateOne { + if v != nil { + _u.SetCreatedAt(*v) + } + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *AgentSkillRepoUpdateOne) SetUpdatedAt(v time.Time) *AgentSkillRepoUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// AddSkillIDs adds the "skills" edge to the AgentSkill entity by IDs. +func (_u *AgentSkillRepoUpdateOne) AddSkillIDs(ids ...uuid.UUID) *AgentSkillRepoUpdateOne { + _u.mutation.AddSkillIDs(ids...) + return _u +} + +// AddSkills adds the "skills" edges to the AgentSkill entity. +func (_u *AgentSkillRepoUpdateOne) AddSkills(v ...*AgentSkill) *AgentSkillRepoUpdateOne { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddSkillIDs(ids...) +} + +// Mutation returns the AgentSkillRepoMutation object of the builder. +func (_u *AgentSkillRepoUpdateOne) Mutation() *AgentSkillRepoMutation { + return _u.mutation +} + +// ClearSkills clears all "skills" edges to the AgentSkill entity. +func (_u *AgentSkillRepoUpdateOne) ClearSkills() *AgentSkillRepoUpdateOne { + _u.mutation.ClearSkills() + return _u +} + +// RemoveSkillIDs removes the "skills" edge to AgentSkill entities by IDs. +func (_u *AgentSkillRepoUpdateOne) RemoveSkillIDs(ids ...uuid.UUID) *AgentSkillRepoUpdateOne { + _u.mutation.RemoveSkillIDs(ids...) + return _u +} + +// RemoveSkills removes "skills" edges to AgentSkill entities. +func (_u *AgentSkillRepoUpdateOne) RemoveSkills(v ...*AgentSkill) *AgentSkillRepoUpdateOne { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveSkillIDs(ids...) +} + +// Where appends a list predicates to the AgentSkillRepoUpdate builder. +func (_u *AgentSkillRepoUpdateOne) Where(ps ...predicate.AgentSkillRepo) *AgentSkillRepoUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *AgentSkillRepoUpdateOne) Select(field string, fields ...string) *AgentSkillRepoUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated AgentSkillRepo entity. +func (_u *AgentSkillRepoUpdateOne) Save(ctx context.Context) (*AgentSkillRepo, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *AgentSkillRepoUpdateOne) SaveX(ctx context.Context) *AgentSkillRepo { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *AgentSkillRepoUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *AgentSkillRepoUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_u *AgentSkillRepoUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := agentskillrepo.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *AgentSkillRepoUpdateOne) check() error { + if v, ok := _u.mutation.Name(); ok { + if err := agentskillrepo.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "AgentSkillRepo.name": %w`, err)} + } + } + if v, ok := _u.mutation.ScopeType(); ok { + if err := agentskillrepo.ScopeTypeValidator(v); err != nil { + return &ValidationError{Name: "scope_type", err: fmt.Errorf(`db: validator failed for field "AgentSkillRepo.scope_type": %w`, err)} + } + } + if v, ok := _u.mutation.SourceType(); ok { + if err := agentskillrepo.SourceTypeValidator(v); err != nil { + return &ValidationError{Name: "source_type", err: fmt.Errorf(`db: validator failed for field "AgentSkillRepo.source_type": %w`, err)} + } + } + if v, ok := _u.mutation.RefType(); ok { + if err := agentskillrepo.RefTypeValidator(v); err != nil { + return &ValidationError{Name: "ref_type", err: fmt.Errorf(`db: validator failed for field "AgentSkillRepo.ref_type": %w`, err)} + } + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (_u *AgentSkillRepoUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *AgentSkillRepoUpdateOne { + _u.modifiers = append(_u.modifiers, modifiers...) + return _u +} + +func (_u *AgentSkillRepoUpdateOne) sqlSave(ctx context.Context) (_node *AgentSkillRepo, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(agentskillrepo.Table, agentskillrepo.Columns, sqlgraph.NewFieldSpec(agentskillrepo.FieldID, field.TypeUUID)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "AgentSkillRepo.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, agentskillrepo.FieldID) + for _, f := range fields { + if !agentskillrepo.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != agentskillrepo.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(agentskillrepo.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.ScopeType(); ok { + _spec.SetField(agentskillrepo.FieldScopeType, field.TypeEnum, value) + } + if value, ok := _u.mutation.ScopeID(); ok { + _spec.SetField(agentskillrepo.FieldScopeID, field.TypeString, value) + } + if value, ok := _u.mutation.CreatedBy(); ok { + _spec.SetField(agentskillrepo.FieldCreatedBy, field.TypeUUID, value) + } + if value, ok := _u.mutation.SourceType(); ok { + _spec.SetField(agentskillrepo.FieldSourceType, field.TypeEnum, value) + } + if value, ok := _u.mutation.GithubURL(); ok { + _spec.SetField(agentskillrepo.FieldGithubURL, field.TypeString, value) + } + if _u.mutation.GithubURLCleared() { + _spec.ClearField(agentskillrepo.FieldGithubURL, field.TypeString) + } + if value, ok := _u.mutation.RefType(); ok { + _spec.SetField(agentskillrepo.FieldRefType, field.TypeEnum, value) + } + if _u.mutation.RefTypeCleared() { + _spec.ClearField(agentskillrepo.FieldRefType, field.TypeEnum) + } + if value, ok := _u.mutation.RefValue(); ok { + _spec.SetField(agentskillrepo.FieldRefValue, field.TypeString, value) + } + if _u.mutation.RefValueCleared() { + _spec.ClearField(agentskillrepo.FieldRefValue, field.TypeString) + } + if value, ok := _u.mutation.LastUploadFilename(); ok { + _spec.SetField(agentskillrepo.FieldLastUploadFilename, field.TypeString, value) + } + if _u.mutation.LastUploadFilenameCleared() { + _spec.ClearField(agentskillrepo.FieldLastUploadFilename, field.TypeString) + } + if value, ok := _u.mutation.LastUploadAt(); ok { + _spec.SetField(agentskillrepo.FieldLastUploadAt, field.TypeTime, value) + } + if _u.mutation.LastUploadAtCleared() { + _spec.ClearField(agentskillrepo.FieldLastUploadAt, field.TypeTime) + } + if value, ok := _u.mutation.IsDeleted(); ok { + _spec.SetField(agentskillrepo.FieldIsDeleted, field.TypeBool, value) + } + if value, ok := _u.mutation.CreatedAt(); ok { + _spec.SetField(agentskillrepo.FieldCreatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(agentskillrepo.FieldUpdatedAt, field.TypeTime, value) + } + if _u.mutation.SkillsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agentskillrepo.SkillsTable, + Columns: []string{agentskillrepo.SkillsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentskill.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedSkillsIDs(); len(nodes) > 0 && !_u.mutation.SkillsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agentskillrepo.SkillsTable, + Columns: []string{agentskillrepo.SkillsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentskill.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.SkillsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agentskillrepo.SkillsTable, + Columns: []string{agentskillrepo.SkillsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentskill.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(_u.modifiers...) + _node = &AgentSkillRepo{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{agentskillrepo.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/backend/db/agentskillversion.go b/backend/db/agentskillversion.go new file mode 100644 index 00000000..7b35aaf9 --- /dev/null +++ b/backend/db/agentskillversion.go @@ -0,0 +1,186 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "encoding/json" + "fmt" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/chaitin/MonkeyCode/backend/db/agentskill" + "github.com/chaitin/MonkeyCode/backend/db/agentskillversion" + "github.com/chaitin/MonkeyCode/backend/ent/types" + "github.com/google/uuid" +) + +// AgentSkillVersion is the model entity for the AgentSkillVersion schema. +type AgentSkillVersion struct { + config `json:"-"` + // ID of the ent. + ID uuid.UUID `json:"id,omitempty"` + // ResourceID holds the value of the "resource_id" field. + ResourceID uuid.UUID `json:"resource_id,omitempty"` + // Version holds the value of the "version" field. + Version string `json:"version,omitempty"` + // S3Key holds the value of the "s3_key" field. + S3Key string `json:"s3_key,omitempty"` + // ParsedMeta holds the value of the "parsed_meta" field. + ParsedMeta types.SkillParsedMeta `json:"parsed_meta,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the AgentSkillVersionQuery when eager-loading is set. + Edges AgentSkillVersionEdges `json:"edges"` + selectValues sql.SelectValues +} + +// AgentSkillVersionEdges holds the relations/edges for other nodes in the graph. +type AgentSkillVersionEdges struct { + // Skill holds the value of the skill edge. + Skill *AgentSkill `json:"skill,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// SkillOrErr returns the Skill value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e AgentSkillVersionEdges) SkillOrErr() (*AgentSkill, error) { + if e.Skill != nil { + return e.Skill, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: agentskill.Label} + } + return nil, &NotLoadedError{edge: "skill"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*AgentSkillVersion) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case agentskillversion.FieldParsedMeta: + values[i] = new([]byte) + case agentskillversion.FieldVersion, agentskillversion.FieldS3Key: + values[i] = new(sql.NullString) + case agentskillversion.FieldCreatedAt: + values[i] = new(sql.NullTime) + case agentskillversion.FieldID, agentskillversion.FieldResourceID: + 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 AgentSkillVersion fields. +func (_m *AgentSkillVersion) 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 agentskillversion.FieldID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value != nil { + _m.ID = *value + } + case agentskillversion.FieldResourceID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field resource_id", values[i]) + } else if value != nil { + _m.ResourceID = *value + } + case agentskillversion.FieldVersion: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field version", values[i]) + } else if value.Valid { + _m.Version = value.String + } + case agentskillversion.FieldS3Key: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field s3_key", values[i]) + } else if value.Valid { + _m.S3Key = value.String + } + case agentskillversion.FieldParsedMeta: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field parsed_meta", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.ParsedMeta); err != nil { + return fmt.Errorf("unmarshal field parsed_meta: %w", err) + } + } + case agentskillversion.FieldCreatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field created_at", values[i]) + } else if value.Valid { + _m.CreatedAt = value.Time + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the AgentSkillVersion. +// This includes values selected through modifiers, order, etc. +func (_m *AgentSkillVersion) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QuerySkill queries the "skill" edge of the AgentSkillVersion entity. +func (_m *AgentSkillVersion) QuerySkill() *AgentSkillQuery { + return NewAgentSkillVersionClient(_m.config).QuerySkill(_m) +} + +// Update returns a builder for updating this AgentSkillVersion. +// Note that you need to call AgentSkillVersion.Unwrap() before calling this method if this AgentSkillVersion +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *AgentSkillVersion) Update() *AgentSkillVersionUpdateOne { + return NewAgentSkillVersionClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the AgentSkillVersion entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (_m *AgentSkillVersion) Unwrap() *AgentSkillVersion { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: AgentSkillVersion is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *AgentSkillVersion) String() string { + var builder strings.Builder + builder.WriteString("AgentSkillVersion(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("resource_id=") + builder.WriteString(fmt.Sprintf("%v", _m.ResourceID)) + builder.WriteString(", ") + builder.WriteString("version=") + builder.WriteString(_m.Version) + builder.WriteString(", ") + builder.WriteString("s3_key=") + builder.WriteString(_m.S3Key) + builder.WriteString(", ") + builder.WriteString("parsed_meta=") + builder.WriteString(fmt.Sprintf("%v", _m.ParsedMeta)) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// AgentSkillVersions is a parsable slice of AgentSkillVersion. +type AgentSkillVersions []*AgentSkillVersion diff --git a/backend/db/agentskillversion/agentskillversion.go b/backend/db/agentskillversion/agentskillversion.go new file mode 100644 index 00000000..b42907ee --- /dev/null +++ b/backend/db/agentskillversion/agentskillversion.go @@ -0,0 +1,112 @@ +// Code generated by ent, DO NOT EDIT. + +package agentskillversion + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/google/uuid" +) + +const ( + // Label holds the string label denoting the agentskillversion type in the database. + Label = "agent_skill_version" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldResourceID holds the string denoting the resource_id field in the database. + FieldResourceID = "resource_id" + // FieldVersion holds the string denoting the version field in the database. + FieldVersion = "version" + // FieldS3Key holds the string denoting the s3_key field in the database. + FieldS3Key = "s3_key" + // FieldParsedMeta holds the string denoting the parsed_meta field in the database. + FieldParsedMeta = "parsed_meta" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // EdgeSkill holds the string denoting the skill edge name in mutations. + EdgeSkill = "skill" + // Table holds the table name of the agentskillversion in the database. + Table = "agent_skill_versions" + // SkillTable is the table that holds the skill relation/edge. + SkillTable = "agent_skill_versions" + // SkillInverseTable is the table name for the AgentSkill entity. + // It exists in this package in order to avoid circular dependency with the "agentskill" package. + SkillInverseTable = "agent_skills" + // SkillColumn is the table column denoting the skill relation/edge. + SkillColumn = "resource_id" +) + +// Columns holds all SQL columns for agentskillversion fields. +var Columns = []string{ + FieldID, + FieldResourceID, + FieldVersion, + FieldS3Key, + FieldParsedMeta, + 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 ( + // VersionValidator is a validator for the "version" field. It is called by the builders before save. + VersionValidator func(string) error + // S3KeyValidator is a validator for the "s3_key" field. It is called by the builders before save. + S3KeyValidator func(string) error + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() uuid.UUID +) + +// OrderOption defines the ordering options for the AgentSkillVersion 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() +} + +// ByResourceID orders the results by the resource_id field. +func ByResourceID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldResourceID, opts...).ToFunc() +} + +// ByVersion orders the results by the version field. +func ByVersion(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldVersion, opts...).ToFunc() +} + +// ByS3Key orders the results by the s3_key field. +func ByS3Key(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldS3Key, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// BySkillField orders the results by skill field. +func BySkillField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newSkillStep(), sql.OrderByField(field, opts...)) + } +} +func newSkillStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(SkillInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SkillTable, SkillColumn), + ) +} diff --git a/backend/db/agentskillversion/where.go b/backend/db/agentskillversion/where.go new file mode 100644 index 00000000..5034e367 --- /dev/null +++ b/backend/db/agentskillversion/where.go @@ -0,0 +1,315 @@ +// Code generated by ent, DO NOT EDIT. + +package agentskillversion + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/google/uuid" +) + +// ID filters vertices based on their ID field. +func ID(id uuid.UUID) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id uuid.UUID) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id uuid.UUID) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...uuid.UUID) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...uuid.UUID) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id uuid.UUID) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id uuid.UUID) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id uuid.UUID) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id uuid.UUID) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldLTE(FieldID, id)) +} + +// ResourceID applies equality check predicate on the "resource_id" field. It's identical to ResourceIDEQ. +func ResourceID(v uuid.UUID) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldEQ(FieldResourceID, v)) +} + +// Version applies equality check predicate on the "version" field. It's identical to VersionEQ. +func Version(v string) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldEQ(FieldVersion, v)) +} + +// S3Key applies equality check predicate on the "s3_key" field. It's identical to S3KeyEQ. +func S3Key(v string) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldEQ(FieldS3Key, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldEQ(FieldCreatedAt, v)) +} + +// ResourceIDEQ applies the EQ predicate on the "resource_id" field. +func ResourceIDEQ(v uuid.UUID) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldEQ(FieldResourceID, v)) +} + +// ResourceIDNEQ applies the NEQ predicate on the "resource_id" field. +func ResourceIDNEQ(v uuid.UUID) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldNEQ(FieldResourceID, v)) +} + +// ResourceIDIn applies the In predicate on the "resource_id" field. +func ResourceIDIn(vs ...uuid.UUID) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldIn(FieldResourceID, vs...)) +} + +// ResourceIDNotIn applies the NotIn predicate on the "resource_id" field. +func ResourceIDNotIn(vs ...uuid.UUID) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldNotIn(FieldResourceID, vs...)) +} + +// VersionEQ applies the EQ predicate on the "version" field. +func VersionEQ(v string) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldEQ(FieldVersion, v)) +} + +// VersionNEQ applies the NEQ predicate on the "version" field. +func VersionNEQ(v string) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldNEQ(FieldVersion, v)) +} + +// VersionIn applies the In predicate on the "version" field. +func VersionIn(vs ...string) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldIn(FieldVersion, vs...)) +} + +// VersionNotIn applies the NotIn predicate on the "version" field. +func VersionNotIn(vs ...string) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldNotIn(FieldVersion, vs...)) +} + +// VersionGT applies the GT predicate on the "version" field. +func VersionGT(v string) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldGT(FieldVersion, v)) +} + +// VersionGTE applies the GTE predicate on the "version" field. +func VersionGTE(v string) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldGTE(FieldVersion, v)) +} + +// VersionLT applies the LT predicate on the "version" field. +func VersionLT(v string) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldLT(FieldVersion, v)) +} + +// VersionLTE applies the LTE predicate on the "version" field. +func VersionLTE(v string) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldLTE(FieldVersion, v)) +} + +// VersionContains applies the Contains predicate on the "version" field. +func VersionContains(v string) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldContains(FieldVersion, v)) +} + +// VersionHasPrefix applies the HasPrefix predicate on the "version" field. +func VersionHasPrefix(v string) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldHasPrefix(FieldVersion, v)) +} + +// VersionHasSuffix applies the HasSuffix predicate on the "version" field. +func VersionHasSuffix(v string) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldHasSuffix(FieldVersion, v)) +} + +// VersionEqualFold applies the EqualFold predicate on the "version" field. +func VersionEqualFold(v string) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldEqualFold(FieldVersion, v)) +} + +// VersionContainsFold applies the ContainsFold predicate on the "version" field. +func VersionContainsFold(v string) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldContainsFold(FieldVersion, v)) +} + +// S3KeyEQ applies the EQ predicate on the "s3_key" field. +func S3KeyEQ(v string) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldEQ(FieldS3Key, v)) +} + +// S3KeyNEQ applies the NEQ predicate on the "s3_key" field. +func S3KeyNEQ(v string) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldNEQ(FieldS3Key, v)) +} + +// S3KeyIn applies the In predicate on the "s3_key" field. +func S3KeyIn(vs ...string) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldIn(FieldS3Key, vs...)) +} + +// S3KeyNotIn applies the NotIn predicate on the "s3_key" field. +func S3KeyNotIn(vs ...string) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldNotIn(FieldS3Key, vs...)) +} + +// S3KeyGT applies the GT predicate on the "s3_key" field. +func S3KeyGT(v string) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldGT(FieldS3Key, v)) +} + +// S3KeyGTE applies the GTE predicate on the "s3_key" field. +func S3KeyGTE(v string) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldGTE(FieldS3Key, v)) +} + +// S3KeyLT applies the LT predicate on the "s3_key" field. +func S3KeyLT(v string) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldLT(FieldS3Key, v)) +} + +// S3KeyLTE applies the LTE predicate on the "s3_key" field. +func S3KeyLTE(v string) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldLTE(FieldS3Key, v)) +} + +// S3KeyContains applies the Contains predicate on the "s3_key" field. +func S3KeyContains(v string) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldContains(FieldS3Key, v)) +} + +// S3KeyHasPrefix applies the HasPrefix predicate on the "s3_key" field. +func S3KeyHasPrefix(v string) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldHasPrefix(FieldS3Key, v)) +} + +// S3KeyHasSuffix applies the HasSuffix predicate on the "s3_key" field. +func S3KeyHasSuffix(v string) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldHasSuffix(FieldS3Key, v)) +} + +// S3KeyEqualFold applies the EqualFold predicate on the "s3_key" field. +func S3KeyEqualFold(v string) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldEqualFold(FieldS3Key, v)) +} + +// S3KeyContainsFold applies the ContainsFold predicate on the "s3_key" field. +func S3KeyContainsFold(v string) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldContainsFold(FieldS3Key, v)) +} + +// ParsedMetaIsNil applies the IsNil predicate on the "parsed_meta" field. +func ParsedMetaIsNil() predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldIsNull(FieldParsedMeta)) +} + +// ParsedMetaNotNil applies the NotNil predicate on the "parsed_meta" field. +func ParsedMetaNotNil() predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldNotNull(FieldParsedMeta)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.FieldLTE(FieldCreatedAt, v)) +} + +// HasSkill applies the HasEdge predicate on the "skill" edge. +func HasSkill() predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, SkillTable, SkillColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasSkillWith applies the HasEdge predicate on the "skill" edge with a given conditions (other predicates). +func HasSkillWith(preds ...predicate.AgentSkill) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(func(s *sql.Selector) { + step := newSkillStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.AgentSkillVersion) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.AgentSkillVersion) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.AgentSkillVersion) predicate.AgentSkillVersion { + return predicate.AgentSkillVersion(sql.NotPredicates(p)) +} diff --git a/backend/db/agentskillversion_create.go b/backend/db/agentskillversion_create.go new file mode 100644 index 00000000..b4f612dc --- /dev/null +++ b/backend/db/agentskillversion_create.go @@ -0,0 +1,797 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/agentskill" + "github.com/chaitin/MonkeyCode/backend/db/agentskillversion" + "github.com/chaitin/MonkeyCode/backend/ent/types" + "github.com/google/uuid" +) + +// AgentSkillVersionCreate is the builder for creating a AgentSkillVersion entity. +type AgentSkillVersionCreate struct { + config + mutation *AgentSkillVersionMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetResourceID sets the "resource_id" field. +func (_c *AgentSkillVersionCreate) SetResourceID(v uuid.UUID) *AgentSkillVersionCreate { + _c.mutation.SetResourceID(v) + return _c +} + +// SetVersion sets the "version" field. +func (_c *AgentSkillVersionCreate) SetVersion(v string) *AgentSkillVersionCreate { + _c.mutation.SetVersion(v) + return _c +} + +// SetS3Key sets the "s3_key" field. +func (_c *AgentSkillVersionCreate) SetS3Key(v string) *AgentSkillVersionCreate { + _c.mutation.SetS3Key(v) + return _c +} + +// SetParsedMeta sets the "parsed_meta" field. +func (_c *AgentSkillVersionCreate) SetParsedMeta(v types.SkillParsedMeta) *AgentSkillVersionCreate { + _c.mutation.SetParsedMeta(v) + return _c +} + +// SetNillableParsedMeta sets the "parsed_meta" field if the given value is not nil. +func (_c *AgentSkillVersionCreate) SetNillableParsedMeta(v *types.SkillParsedMeta) *AgentSkillVersionCreate { + if v != nil { + _c.SetParsedMeta(*v) + } + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *AgentSkillVersionCreate) SetCreatedAt(v time.Time) *AgentSkillVersionCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *AgentSkillVersionCreate) SetNillableCreatedAt(v *time.Time) *AgentSkillVersionCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *AgentSkillVersionCreate) SetID(v uuid.UUID) *AgentSkillVersionCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *AgentSkillVersionCreate) SetNillableID(v *uuid.UUID) *AgentSkillVersionCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetSkillID sets the "skill" edge to the AgentSkill entity by ID. +func (_c *AgentSkillVersionCreate) SetSkillID(id uuid.UUID) *AgentSkillVersionCreate { + _c.mutation.SetSkillID(id) + return _c +} + +// SetSkill sets the "skill" edge to the AgentSkill entity. +func (_c *AgentSkillVersionCreate) SetSkill(v *AgentSkill) *AgentSkillVersionCreate { + return _c.SetSkillID(v.ID) +} + +// Mutation returns the AgentSkillVersionMutation object of the builder. +func (_c *AgentSkillVersionCreate) Mutation() *AgentSkillVersionMutation { + return _c.mutation +} + +// Save creates the AgentSkillVersion in the database. +func (_c *AgentSkillVersionCreate) Save(ctx context.Context) (*AgentSkillVersion, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *AgentSkillVersionCreate) SaveX(ctx context.Context) *AgentSkillVersion { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *AgentSkillVersionCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *AgentSkillVersionCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *AgentSkillVersionCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := agentskillversion.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := agentskillversion.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *AgentSkillVersionCreate) check() error { + if _, ok := _c.mutation.ResourceID(); !ok { + return &ValidationError{Name: "resource_id", err: errors.New(`db: missing required field "AgentSkillVersion.resource_id"`)} + } + if _, ok := _c.mutation.Version(); !ok { + return &ValidationError{Name: "version", err: errors.New(`db: missing required field "AgentSkillVersion.version"`)} + } + if v, ok := _c.mutation.Version(); ok { + if err := agentskillversion.VersionValidator(v); err != nil { + return &ValidationError{Name: "version", err: fmt.Errorf(`db: validator failed for field "AgentSkillVersion.version": %w`, err)} + } + } + if _, ok := _c.mutation.S3Key(); !ok { + return &ValidationError{Name: "s3_key", err: errors.New(`db: missing required field "AgentSkillVersion.s3_key"`)} + } + if v, ok := _c.mutation.S3Key(); ok { + if err := agentskillversion.S3KeyValidator(v); err != nil { + return &ValidationError{Name: "s3_key", err: fmt.Errorf(`db: validator failed for field "AgentSkillVersion.s3_key": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "AgentSkillVersion.created_at"`)} + } + if len(_c.mutation.SkillIDs()) == 0 { + return &ValidationError{Name: "skill", err: errors.New(`db: missing required edge "AgentSkillVersion.skill"`)} + } + return nil +} + +func (_c *AgentSkillVersionCreate) sqlSave(ctx context.Context) (*AgentSkillVersion, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.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 + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *AgentSkillVersionCreate) createSpec() (*AgentSkillVersion, *sqlgraph.CreateSpec) { + var ( + _node = &AgentSkillVersion{config: _c.config} + _spec = sqlgraph.NewCreateSpec(agentskillversion.Table, sqlgraph.NewFieldSpec(agentskillversion.FieldID, field.TypeUUID)) + ) + _spec.OnConflict = _c.conflict + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = &id + } + if value, ok := _c.mutation.Version(); ok { + _spec.SetField(agentskillversion.FieldVersion, field.TypeString, value) + _node.Version = value + } + if value, ok := _c.mutation.S3Key(); ok { + _spec.SetField(agentskillversion.FieldS3Key, field.TypeString, value) + _node.S3Key = value + } + if value, ok := _c.mutation.ParsedMeta(); ok { + _spec.SetField(agentskillversion.FieldParsedMeta, field.TypeJSON, value) + _node.ParsedMeta = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(agentskillversion.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if nodes := _c.mutation.SkillIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: agentskillversion.SkillTable, + Columns: []string{agentskillversion.SkillColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentskill.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.ResourceID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.AgentSkillVersion.Create(). +// SetResourceID(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.AgentSkillVersionUpsert) { +// SetResourceID(v+v). +// }). +// Exec(ctx) +func (_c *AgentSkillVersionCreate) OnConflict(opts ...sql.ConflictOption) *AgentSkillVersionUpsertOne { + _c.conflict = opts + return &AgentSkillVersionUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.AgentSkillVersion.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *AgentSkillVersionCreate) OnConflictColumns(columns ...string) *AgentSkillVersionUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &AgentSkillVersionUpsertOne{ + create: _c, + } +} + +type ( + // AgentSkillVersionUpsertOne is the builder for "upsert"-ing + // one AgentSkillVersion node. + AgentSkillVersionUpsertOne struct { + create *AgentSkillVersionCreate + } + + // AgentSkillVersionUpsert is the "OnConflict" setter. + AgentSkillVersionUpsert struct { + *sql.UpdateSet + } +) + +// SetResourceID sets the "resource_id" field. +func (u *AgentSkillVersionUpsert) SetResourceID(v uuid.UUID) *AgentSkillVersionUpsert { + u.Set(agentskillversion.FieldResourceID, v) + return u +} + +// UpdateResourceID sets the "resource_id" field to the value that was provided on create. +func (u *AgentSkillVersionUpsert) UpdateResourceID() *AgentSkillVersionUpsert { + u.SetExcluded(agentskillversion.FieldResourceID) + return u +} + +// SetVersion sets the "version" field. +func (u *AgentSkillVersionUpsert) SetVersion(v string) *AgentSkillVersionUpsert { + u.Set(agentskillversion.FieldVersion, v) + return u +} + +// UpdateVersion sets the "version" field to the value that was provided on create. +func (u *AgentSkillVersionUpsert) UpdateVersion() *AgentSkillVersionUpsert { + u.SetExcluded(agentskillversion.FieldVersion) + return u +} + +// SetS3Key sets the "s3_key" field. +func (u *AgentSkillVersionUpsert) SetS3Key(v string) *AgentSkillVersionUpsert { + u.Set(agentskillversion.FieldS3Key, v) + return u +} + +// UpdateS3Key sets the "s3_key" field to the value that was provided on create. +func (u *AgentSkillVersionUpsert) UpdateS3Key() *AgentSkillVersionUpsert { + u.SetExcluded(agentskillversion.FieldS3Key) + return u +} + +// SetParsedMeta sets the "parsed_meta" field. +func (u *AgentSkillVersionUpsert) SetParsedMeta(v types.SkillParsedMeta) *AgentSkillVersionUpsert { + u.Set(agentskillversion.FieldParsedMeta, v) + return u +} + +// UpdateParsedMeta sets the "parsed_meta" field to the value that was provided on create. +func (u *AgentSkillVersionUpsert) UpdateParsedMeta() *AgentSkillVersionUpsert { + u.SetExcluded(agentskillversion.FieldParsedMeta) + return u +} + +// ClearParsedMeta clears the value of the "parsed_meta" field. +func (u *AgentSkillVersionUpsert) ClearParsedMeta() *AgentSkillVersionUpsert { + u.SetNull(agentskillversion.FieldParsedMeta) + return u +} + +// SetCreatedAt sets the "created_at" field. +func (u *AgentSkillVersionUpsert) SetCreatedAt(v time.Time) *AgentSkillVersionUpsert { + u.Set(agentskillversion.FieldCreatedAt, v) + return u +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *AgentSkillVersionUpsert) UpdateCreatedAt() *AgentSkillVersionUpsert { + u.SetExcluded(agentskillversion.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.AgentSkillVersion.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(agentskillversion.FieldID) +// }), +// ). +// Exec(ctx) +func (u *AgentSkillVersionUpsertOne) UpdateNewValues() *AgentSkillVersionUpsertOne { + 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(agentskillversion.FieldID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.AgentSkillVersion.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *AgentSkillVersionUpsertOne) Ignore() *AgentSkillVersionUpsertOne { + 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 *AgentSkillVersionUpsertOne) DoNothing() *AgentSkillVersionUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the AgentSkillVersionCreate.OnConflict +// documentation for more info. +func (u *AgentSkillVersionUpsertOne) Update(set func(*AgentSkillVersionUpsert)) *AgentSkillVersionUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&AgentSkillVersionUpsert{UpdateSet: update}) + })) + return u +} + +// SetResourceID sets the "resource_id" field. +func (u *AgentSkillVersionUpsertOne) SetResourceID(v uuid.UUID) *AgentSkillVersionUpsertOne { + return u.Update(func(s *AgentSkillVersionUpsert) { + s.SetResourceID(v) + }) +} + +// UpdateResourceID sets the "resource_id" field to the value that was provided on create. +func (u *AgentSkillVersionUpsertOne) UpdateResourceID() *AgentSkillVersionUpsertOne { + return u.Update(func(s *AgentSkillVersionUpsert) { + s.UpdateResourceID() + }) +} + +// SetVersion sets the "version" field. +func (u *AgentSkillVersionUpsertOne) SetVersion(v string) *AgentSkillVersionUpsertOne { + return u.Update(func(s *AgentSkillVersionUpsert) { + s.SetVersion(v) + }) +} + +// UpdateVersion sets the "version" field to the value that was provided on create. +func (u *AgentSkillVersionUpsertOne) UpdateVersion() *AgentSkillVersionUpsertOne { + return u.Update(func(s *AgentSkillVersionUpsert) { + s.UpdateVersion() + }) +} + +// SetS3Key sets the "s3_key" field. +func (u *AgentSkillVersionUpsertOne) SetS3Key(v string) *AgentSkillVersionUpsertOne { + return u.Update(func(s *AgentSkillVersionUpsert) { + s.SetS3Key(v) + }) +} + +// UpdateS3Key sets the "s3_key" field to the value that was provided on create. +func (u *AgentSkillVersionUpsertOne) UpdateS3Key() *AgentSkillVersionUpsertOne { + return u.Update(func(s *AgentSkillVersionUpsert) { + s.UpdateS3Key() + }) +} + +// SetParsedMeta sets the "parsed_meta" field. +func (u *AgentSkillVersionUpsertOne) SetParsedMeta(v types.SkillParsedMeta) *AgentSkillVersionUpsertOne { + return u.Update(func(s *AgentSkillVersionUpsert) { + s.SetParsedMeta(v) + }) +} + +// UpdateParsedMeta sets the "parsed_meta" field to the value that was provided on create. +func (u *AgentSkillVersionUpsertOne) UpdateParsedMeta() *AgentSkillVersionUpsertOne { + return u.Update(func(s *AgentSkillVersionUpsert) { + s.UpdateParsedMeta() + }) +} + +// ClearParsedMeta clears the value of the "parsed_meta" field. +func (u *AgentSkillVersionUpsertOne) ClearParsedMeta() *AgentSkillVersionUpsertOne { + return u.Update(func(s *AgentSkillVersionUpsert) { + s.ClearParsedMeta() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *AgentSkillVersionUpsertOne) SetCreatedAt(v time.Time) *AgentSkillVersionUpsertOne { + return u.Update(func(s *AgentSkillVersionUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *AgentSkillVersionUpsertOne) UpdateCreatedAt() *AgentSkillVersionUpsertOne { + return u.Update(func(s *AgentSkillVersionUpsert) { + s.UpdateCreatedAt() + }) +} + +// Exec executes the query. +func (u *AgentSkillVersionUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for AgentSkillVersionCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *AgentSkillVersionUpsertOne) 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 *AgentSkillVersionUpsertOne) 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: AgentSkillVersionUpsertOne.ID is not supported by MySQL driver. Use AgentSkillVersionUpsertOne.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 *AgentSkillVersionUpsertOne) IDX(ctx context.Context) uuid.UUID { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// AgentSkillVersionCreateBulk is the builder for creating many AgentSkillVersion entities in bulk. +type AgentSkillVersionCreateBulk struct { + config + err error + builders []*AgentSkillVersionCreate + conflict []sql.ConflictOption +} + +// Save creates the AgentSkillVersion entities in the database. +func (_c *AgentSkillVersionCreateBulk) Save(ctx context.Context) ([]*AgentSkillVersion, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*AgentSkillVersion, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*AgentSkillVersionMutation) + 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, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = _c.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.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, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *AgentSkillVersionCreateBulk) SaveX(ctx context.Context) []*AgentSkillVersion { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *AgentSkillVersionCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *AgentSkillVersionCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.AgentSkillVersion.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.AgentSkillVersionUpsert) { +// SetResourceID(v+v). +// }). +// Exec(ctx) +func (_c *AgentSkillVersionCreateBulk) OnConflict(opts ...sql.ConflictOption) *AgentSkillVersionUpsertBulk { + _c.conflict = opts + return &AgentSkillVersionUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.AgentSkillVersion.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *AgentSkillVersionCreateBulk) OnConflictColumns(columns ...string) *AgentSkillVersionUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &AgentSkillVersionUpsertBulk{ + create: _c, + } +} + +// AgentSkillVersionUpsertBulk is the builder for "upsert"-ing +// a bulk of AgentSkillVersion nodes. +type AgentSkillVersionUpsertBulk struct { + create *AgentSkillVersionCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.AgentSkillVersion.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(agentskillversion.FieldID) +// }), +// ). +// Exec(ctx) +func (u *AgentSkillVersionUpsertBulk) UpdateNewValues() *AgentSkillVersionUpsertBulk { + 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(agentskillversion.FieldID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.AgentSkillVersion.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *AgentSkillVersionUpsertBulk) Ignore() *AgentSkillVersionUpsertBulk { + 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 *AgentSkillVersionUpsertBulk) DoNothing() *AgentSkillVersionUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the AgentSkillVersionCreateBulk.OnConflict +// documentation for more info. +func (u *AgentSkillVersionUpsertBulk) Update(set func(*AgentSkillVersionUpsert)) *AgentSkillVersionUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&AgentSkillVersionUpsert{UpdateSet: update}) + })) + return u +} + +// SetResourceID sets the "resource_id" field. +func (u *AgentSkillVersionUpsertBulk) SetResourceID(v uuid.UUID) *AgentSkillVersionUpsertBulk { + return u.Update(func(s *AgentSkillVersionUpsert) { + s.SetResourceID(v) + }) +} + +// UpdateResourceID sets the "resource_id" field to the value that was provided on create. +func (u *AgentSkillVersionUpsertBulk) UpdateResourceID() *AgentSkillVersionUpsertBulk { + return u.Update(func(s *AgentSkillVersionUpsert) { + s.UpdateResourceID() + }) +} + +// SetVersion sets the "version" field. +func (u *AgentSkillVersionUpsertBulk) SetVersion(v string) *AgentSkillVersionUpsertBulk { + return u.Update(func(s *AgentSkillVersionUpsert) { + s.SetVersion(v) + }) +} + +// UpdateVersion sets the "version" field to the value that was provided on create. +func (u *AgentSkillVersionUpsertBulk) UpdateVersion() *AgentSkillVersionUpsertBulk { + return u.Update(func(s *AgentSkillVersionUpsert) { + s.UpdateVersion() + }) +} + +// SetS3Key sets the "s3_key" field. +func (u *AgentSkillVersionUpsertBulk) SetS3Key(v string) *AgentSkillVersionUpsertBulk { + return u.Update(func(s *AgentSkillVersionUpsert) { + s.SetS3Key(v) + }) +} + +// UpdateS3Key sets the "s3_key" field to the value that was provided on create. +func (u *AgentSkillVersionUpsertBulk) UpdateS3Key() *AgentSkillVersionUpsertBulk { + return u.Update(func(s *AgentSkillVersionUpsert) { + s.UpdateS3Key() + }) +} + +// SetParsedMeta sets the "parsed_meta" field. +func (u *AgentSkillVersionUpsertBulk) SetParsedMeta(v types.SkillParsedMeta) *AgentSkillVersionUpsertBulk { + return u.Update(func(s *AgentSkillVersionUpsert) { + s.SetParsedMeta(v) + }) +} + +// UpdateParsedMeta sets the "parsed_meta" field to the value that was provided on create. +func (u *AgentSkillVersionUpsertBulk) UpdateParsedMeta() *AgentSkillVersionUpsertBulk { + return u.Update(func(s *AgentSkillVersionUpsert) { + s.UpdateParsedMeta() + }) +} + +// ClearParsedMeta clears the value of the "parsed_meta" field. +func (u *AgentSkillVersionUpsertBulk) ClearParsedMeta() *AgentSkillVersionUpsertBulk { + return u.Update(func(s *AgentSkillVersionUpsert) { + s.ClearParsedMeta() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *AgentSkillVersionUpsertBulk) SetCreatedAt(v time.Time) *AgentSkillVersionUpsertBulk { + return u.Update(func(s *AgentSkillVersionUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *AgentSkillVersionUpsertBulk) UpdateCreatedAt() *AgentSkillVersionUpsertBulk { + return u.Update(func(s *AgentSkillVersionUpsert) { + s.UpdateCreatedAt() + }) +} + +// Exec executes the query. +func (u *AgentSkillVersionUpsertBulk) 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 AgentSkillVersionCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for AgentSkillVersionCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *AgentSkillVersionUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/agentskillversion_delete.go b/backend/db/agentskillversion_delete.go new file mode 100644 index 00000000..d553e4f8 --- /dev/null +++ b/backend/db/agentskillversion_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/agentskillversion" + "github.com/chaitin/MonkeyCode/backend/db/predicate" +) + +// AgentSkillVersionDelete is the builder for deleting a AgentSkillVersion entity. +type AgentSkillVersionDelete struct { + config + hooks []Hook + mutation *AgentSkillVersionMutation +} + +// Where appends a list predicates to the AgentSkillVersionDelete builder. +func (_d *AgentSkillVersionDelete) Where(ps ...predicate.AgentSkillVersion) *AgentSkillVersionDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *AgentSkillVersionDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *AgentSkillVersionDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *AgentSkillVersionDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(agentskillversion.Table, sqlgraph.NewFieldSpec(agentskillversion.FieldID, field.TypeUUID)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// AgentSkillVersionDeleteOne is the builder for deleting a single AgentSkillVersion entity. +type AgentSkillVersionDeleteOne struct { + _d *AgentSkillVersionDelete +} + +// Where appends a list predicates to the AgentSkillVersionDelete builder. +func (_d *AgentSkillVersionDeleteOne) Where(ps ...predicate.AgentSkillVersion) *AgentSkillVersionDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *AgentSkillVersionDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{agentskillversion.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *AgentSkillVersionDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/agentskillversion_query.go b/backend/db/agentskillversion_query.go new file mode 100644 index 00000000..c07bbf2c --- /dev/null +++ b/backend/db/agentskillversion_query.go @@ -0,0 +1,657 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/agentskill" + "github.com/chaitin/MonkeyCode/backend/db/agentskillversion" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/google/uuid" +) + +// AgentSkillVersionQuery is the builder for querying AgentSkillVersion entities. +type AgentSkillVersionQuery struct { + config + ctx *QueryContext + order []agentskillversion.OrderOption + inters []Interceptor + predicates []predicate.AgentSkillVersion + withSkill *AgentSkillQuery + 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 AgentSkillVersionQuery builder. +func (_q *AgentSkillVersionQuery) Where(ps ...predicate.AgentSkillVersion) *AgentSkillVersionQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *AgentSkillVersionQuery) Limit(limit int) *AgentSkillVersionQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *AgentSkillVersionQuery) Offset(offset int) *AgentSkillVersionQuery { + _q.ctx.Offset = &offset + return _q +} + +// 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 (_q *AgentSkillVersionQuery) Unique(unique bool) *AgentSkillVersionQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *AgentSkillVersionQuery) Order(o ...agentskillversion.OrderOption) *AgentSkillVersionQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QuerySkill chains the current query on the "skill" edge. +func (_q *AgentSkillVersionQuery) QuerySkill() *AgentSkillQuery { + query := (&AgentSkillClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(agentskillversion.Table, agentskillversion.FieldID, selector), + sqlgraph.To(agentskill.Table, agentskill.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, agentskillversion.SkillTable, agentskillversion.SkillColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first AgentSkillVersion entity from the query. +// Returns a *NotFoundError when no AgentSkillVersion was found. +func (_q *AgentSkillVersionQuery) First(ctx context.Context) (*AgentSkillVersion, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{agentskillversion.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *AgentSkillVersionQuery) FirstX(ctx context.Context) *AgentSkillVersion { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first AgentSkillVersion ID from the query. +// Returns a *NotFoundError when no AgentSkillVersion ID was found. +func (_q *AgentSkillVersionQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{agentskillversion.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *AgentSkillVersionQuery) FirstIDX(ctx context.Context) uuid.UUID { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single AgentSkillVersion entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one AgentSkillVersion entity is found. +// Returns a *NotFoundError when no AgentSkillVersion entities are found. +func (_q *AgentSkillVersionQuery) Only(ctx context.Context) (*AgentSkillVersion, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{agentskillversion.Label} + default: + return nil, &NotSingularError{agentskillversion.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *AgentSkillVersionQuery) OnlyX(ctx context.Context) *AgentSkillVersion { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only AgentSkillVersion ID in the query. +// Returns a *NotSingularError when more than one AgentSkillVersion ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *AgentSkillVersionQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{agentskillversion.Label} + default: + err = &NotSingularError{agentskillversion.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *AgentSkillVersionQuery) OnlyIDX(ctx context.Context) uuid.UUID { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of AgentSkillVersions. +func (_q *AgentSkillVersionQuery) All(ctx context.Context) ([]*AgentSkillVersion, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*AgentSkillVersion, *AgentSkillVersionQuery]() + return withInterceptors[[]*AgentSkillVersion](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *AgentSkillVersionQuery) AllX(ctx context.Context) []*AgentSkillVersion { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of AgentSkillVersion IDs. +func (_q *AgentSkillVersionQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(agentskillversion.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *AgentSkillVersionQuery) IDsX(ctx context.Context) []uuid.UUID { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *AgentSkillVersionQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*AgentSkillVersionQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *AgentSkillVersionQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *AgentSkillVersionQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.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 (_q *AgentSkillVersionQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the AgentSkillVersionQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *AgentSkillVersionQuery) Clone() *AgentSkillVersionQuery { + if _q == nil { + return nil + } + return &AgentSkillVersionQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]agentskillversion.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.AgentSkillVersion{}, _q.predicates...), + withSkill: _q.withSkill.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + modifiers: append([]func(*sql.Selector){}, _q.modifiers...), + } +} + +// WithSkill tells the query-builder to eager-load the nodes that are connected to +// the "skill" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *AgentSkillVersionQuery) WithSkill(opts ...func(*AgentSkillQuery)) *AgentSkillVersionQuery { + query := (&AgentSkillClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withSkill = query + return _q +} + +// 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 { +// ResourceID uuid.UUID `json:"resource_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.AgentSkillVersion.Query(). +// GroupBy(agentskillversion.FieldResourceID). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *AgentSkillVersionQuery) GroupBy(field string, fields ...string) *AgentSkillVersionGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &AgentSkillVersionGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = agentskillversion.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 { +// ResourceID uuid.UUID `json:"resource_id,omitempty"` +// } +// +// client.AgentSkillVersion.Query(). +// Select(agentskillversion.FieldResourceID). +// Scan(ctx, &v) +func (_q *AgentSkillVersionQuery) Select(fields ...string) *AgentSkillVersionSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &AgentSkillVersionSelect{AgentSkillVersionQuery: _q} + sbuild.label = agentskillversion.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a AgentSkillVersionSelect configured with the given aggregations. +func (_q *AgentSkillVersionQuery) Aggregate(fns ...AggregateFunc) *AgentSkillVersionSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *AgentSkillVersionQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.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, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !agentskillversion.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *AgentSkillVersionQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*AgentSkillVersion, error) { + var ( + nodes = []*AgentSkillVersion{} + _spec = _q.querySpec() + loadedTypes = [1]bool{ + _q.withSkill != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*AgentSkillVersion).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &AgentSkillVersion{config: _q.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := _q.withSkill; query != nil { + if err := _q.loadSkill(ctx, query, nodes, nil, + func(n *AgentSkillVersion, e *AgentSkill) { n.Edges.Skill = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *AgentSkillVersionQuery) loadSkill(ctx context.Context, query *AgentSkillQuery, nodes []*AgentSkillVersion, init func(*AgentSkillVersion), assign func(*AgentSkillVersion, *AgentSkill)) error { + ids := make([]uuid.UUID, 0, len(nodes)) + nodeids := make(map[uuid.UUID][]*AgentSkillVersion) + for i := range nodes { + fk := nodes[i].ResourceID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(agentskill.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return fmt.Errorf(`unexpected foreign-key "resource_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *AgentSkillVersionQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *AgentSkillVersionQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(agentskillversion.Table, agentskillversion.Columns, sqlgraph.NewFieldSpec(agentskillversion.FieldID, field.TypeUUID)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, agentskillversion.FieldID) + for i := range fields { + if fields[i] != agentskillversion.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withSkill != nil { + _spec.Node.AddColumnOnce(agentskillversion.FieldResourceID) + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *AgentSkillVersionQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(agentskillversion.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = agentskillversion.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, m := range _q.modifiers { + m(selector) + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.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 := _q.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 (_q *AgentSkillVersionQuery) ForUpdate(opts ...sql.LockOption) *AgentSkillVersionQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForUpdate(opts...) + }) + return _q +} + +// 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 (_q *AgentSkillVersionQuery) ForShare(opts ...sql.LockOption) *AgentSkillVersionQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (_q *AgentSkillVersionQuery) Modify(modifiers ...func(s *sql.Selector)) *AgentSkillVersionSelect { + _q.modifiers = append(_q.modifiers, modifiers...) + return _q.Select() +} + +// AgentSkillVersionGroupBy is the group-by builder for AgentSkillVersion entities. +type AgentSkillVersionGroupBy struct { + selector + build *AgentSkillVersionQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *AgentSkillVersionGroupBy) Aggregate(fns ...AggregateFunc) *AgentSkillVersionGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *AgentSkillVersionGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*AgentSkillVersionQuery, *AgentSkillVersionGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *AgentSkillVersionGroupBy) sqlScan(ctx context.Context, root *AgentSkillVersionQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// AgentSkillVersionSelect is the builder for selecting fields of AgentSkillVersion entities. +type AgentSkillVersionSelect struct { + *AgentSkillVersionQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *AgentSkillVersionSelect) Aggregate(fns ...AggregateFunc) *AgentSkillVersionSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *AgentSkillVersionSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*AgentSkillVersionQuery, *AgentSkillVersionSelect](ctx, _s.AgentSkillVersionQuery, _s, _s.inters, v) +} + +func (_s *AgentSkillVersionSelect) sqlScan(ctx context.Context, root *AgentSkillVersionQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.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 := _s.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 (_s *AgentSkillVersionSelect) Modify(modifiers ...func(s *sql.Selector)) *AgentSkillVersionSelect { + _s.modifiers = append(_s.modifiers, modifiers...) + return _s +} diff --git a/backend/db/agentskillversion_update.go b/backend/db/agentskillversion_update.go new file mode 100644 index 00000000..f92db7b3 --- /dev/null +++ b/backend/db/agentskillversion_update.go @@ -0,0 +1,511 @@ +// 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/agentskill" + "github.com/chaitin/MonkeyCode/backend/db/agentskillversion" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/ent/types" + "github.com/google/uuid" +) + +// AgentSkillVersionUpdate is the builder for updating AgentSkillVersion entities. +type AgentSkillVersionUpdate struct { + config + hooks []Hook + mutation *AgentSkillVersionMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the AgentSkillVersionUpdate builder. +func (_u *AgentSkillVersionUpdate) Where(ps ...predicate.AgentSkillVersion) *AgentSkillVersionUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetResourceID sets the "resource_id" field. +func (_u *AgentSkillVersionUpdate) SetResourceID(v uuid.UUID) *AgentSkillVersionUpdate { + _u.mutation.SetResourceID(v) + return _u +} + +// SetNillableResourceID sets the "resource_id" field if the given value is not nil. +func (_u *AgentSkillVersionUpdate) SetNillableResourceID(v *uuid.UUID) *AgentSkillVersionUpdate { + if v != nil { + _u.SetResourceID(*v) + } + return _u +} + +// SetVersion sets the "version" field. +func (_u *AgentSkillVersionUpdate) SetVersion(v string) *AgentSkillVersionUpdate { + _u.mutation.SetVersion(v) + return _u +} + +// SetNillableVersion sets the "version" field if the given value is not nil. +func (_u *AgentSkillVersionUpdate) SetNillableVersion(v *string) *AgentSkillVersionUpdate { + if v != nil { + _u.SetVersion(*v) + } + return _u +} + +// SetS3Key sets the "s3_key" field. +func (_u *AgentSkillVersionUpdate) SetS3Key(v string) *AgentSkillVersionUpdate { + _u.mutation.SetS3Key(v) + return _u +} + +// SetNillableS3Key sets the "s3_key" field if the given value is not nil. +func (_u *AgentSkillVersionUpdate) SetNillableS3Key(v *string) *AgentSkillVersionUpdate { + if v != nil { + _u.SetS3Key(*v) + } + return _u +} + +// SetParsedMeta sets the "parsed_meta" field. +func (_u *AgentSkillVersionUpdate) SetParsedMeta(v types.SkillParsedMeta) *AgentSkillVersionUpdate { + _u.mutation.SetParsedMeta(v) + return _u +} + +// SetNillableParsedMeta sets the "parsed_meta" field if the given value is not nil. +func (_u *AgentSkillVersionUpdate) SetNillableParsedMeta(v *types.SkillParsedMeta) *AgentSkillVersionUpdate { + if v != nil { + _u.SetParsedMeta(*v) + } + return _u +} + +// ClearParsedMeta clears the value of the "parsed_meta" field. +func (_u *AgentSkillVersionUpdate) ClearParsedMeta() *AgentSkillVersionUpdate { + _u.mutation.ClearParsedMeta() + return _u +} + +// SetCreatedAt sets the "created_at" field. +func (_u *AgentSkillVersionUpdate) SetCreatedAt(v time.Time) *AgentSkillVersionUpdate { + _u.mutation.SetCreatedAt(v) + return _u +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_u *AgentSkillVersionUpdate) SetNillableCreatedAt(v *time.Time) *AgentSkillVersionUpdate { + if v != nil { + _u.SetCreatedAt(*v) + } + return _u +} + +// SetSkillID sets the "skill" edge to the AgentSkill entity by ID. +func (_u *AgentSkillVersionUpdate) SetSkillID(id uuid.UUID) *AgentSkillVersionUpdate { + _u.mutation.SetSkillID(id) + return _u +} + +// SetSkill sets the "skill" edge to the AgentSkill entity. +func (_u *AgentSkillVersionUpdate) SetSkill(v *AgentSkill) *AgentSkillVersionUpdate { + return _u.SetSkillID(v.ID) +} + +// Mutation returns the AgentSkillVersionMutation object of the builder. +func (_u *AgentSkillVersionUpdate) Mutation() *AgentSkillVersionMutation { + return _u.mutation +} + +// ClearSkill clears the "skill" edge to the AgentSkill entity. +func (_u *AgentSkillVersionUpdate) ClearSkill() *AgentSkillVersionUpdate { + _u.mutation.ClearSkill() + return _u +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *AgentSkillVersionUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *AgentSkillVersionUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *AgentSkillVersionUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *AgentSkillVersionUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *AgentSkillVersionUpdate) check() error { + if v, ok := _u.mutation.Version(); ok { + if err := agentskillversion.VersionValidator(v); err != nil { + return &ValidationError{Name: "version", err: fmt.Errorf(`db: validator failed for field "AgentSkillVersion.version": %w`, err)} + } + } + if v, ok := _u.mutation.S3Key(); ok { + if err := agentskillversion.S3KeyValidator(v); err != nil { + return &ValidationError{Name: "s3_key", err: fmt.Errorf(`db: validator failed for field "AgentSkillVersion.s3_key": %w`, err)} + } + } + if _u.mutation.SkillCleared() && len(_u.mutation.SkillIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "AgentSkillVersion.skill"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (_u *AgentSkillVersionUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *AgentSkillVersionUpdate { + _u.modifiers = append(_u.modifiers, modifiers...) + return _u +} + +func (_u *AgentSkillVersionUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(agentskillversion.Table, agentskillversion.Columns, sqlgraph.NewFieldSpec(agentskillversion.FieldID, field.TypeUUID)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.Version(); ok { + _spec.SetField(agentskillversion.FieldVersion, field.TypeString, value) + } + if value, ok := _u.mutation.S3Key(); ok { + _spec.SetField(agentskillversion.FieldS3Key, field.TypeString, value) + } + if value, ok := _u.mutation.ParsedMeta(); ok { + _spec.SetField(agentskillversion.FieldParsedMeta, field.TypeJSON, value) + } + if _u.mutation.ParsedMetaCleared() { + _spec.ClearField(agentskillversion.FieldParsedMeta, field.TypeJSON) + } + if value, ok := _u.mutation.CreatedAt(); ok { + _spec.SetField(agentskillversion.FieldCreatedAt, field.TypeTime, value) + } + if _u.mutation.SkillCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: agentskillversion.SkillTable, + Columns: []string{agentskillversion.SkillColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentskill.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.SkillIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: agentskillversion.SkillTable, + Columns: []string{agentskillversion.SkillColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentskill.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(_u.modifiers...) + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{agentskillversion.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// AgentSkillVersionUpdateOne is the builder for updating a single AgentSkillVersion entity. +type AgentSkillVersionUpdateOne struct { + config + fields []string + hooks []Hook + mutation *AgentSkillVersionMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetResourceID sets the "resource_id" field. +func (_u *AgentSkillVersionUpdateOne) SetResourceID(v uuid.UUID) *AgentSkillVersionUpdateOne { + _u.mutation.SetResourceID(v) + return _u +} + +// SetNillableResourceID sets the "resource_id" field if the given value is not nil. +func (_u *AgentSkillVersionUpdateOne) SetNillableResourceID(v *uuid.UUID) *AgentSkillVersionUpdateOne { + if v != nil { + _u.SetResourceID(*v) + } + return _u +} + +// SetVersion sets the "version" field. +func (_u *AgentSkillVersionUpdateOne) SetVersion(v string) *AgentSkillVersionUpdateOne { + _u.mutation.SetVersion(v) + return _u +} + +// SetNillableVersion sets the "version" field if the given value is not nil. +func (_u *AgentSkillVersionUpdateOne) SetNillableVersion(v *string) *AgentSkillVersionUpdateOne { + if v != nil { + _u.SetVersion(*v) + } + return _u +} + +// SetS3Key sets the "s3_key" field. +func (_u *AgentSkillVersionUpdateOne) SetS3Key(v string) *AgentSkillVersionUpdateOne { + _u.mutation.SetS3Key(v) + return _u +} + +// SetNillableS3Key sets the "s3_key" field if the given value is not nil. +func (_u *AgentSkillVersionUpdateOne) SetNillableS3Key(v *string) *AgentSkillVersionUpdateOne { + if v != nil { + _u.SetS3Key(*v) + } + return _u +} + +// SetParsedMeta sets the "parsed_meta" field. +func (_u *AgentSkillVersionUpdateOne) SetParsedMeta(v types.SkillParsedMeta) *AgentSkillVersionUpdateOne { + _u.mutation.SetParsedMeta(v) + return _u +} + +// SetNillableParsedMeta sets the "parsed_meta" field if the given value is not nil. +func (_u *AgentSkillVersionUpdateOne) SetNillableParsedMeta(v *types.SkillParsedMeta) *AgentSkillVersionUpdateOne { + if v != nil { + _u.SetParsedMeta(*v) + } + return _u +} + +// ClearParsedMeta clears the value of the "parsed_meta" field. +func (_u *AgentSkillVersionUpdateOne) ClearParsedMeta() *AgentSkillVersionUpdateOne { + _u.mutation.ClearParsedMeta() + return _u +} + +// SetCreatedAt sets the "created_at" field. +func (_u *AgentSkillVersionUpdateOne) SetCreatedAt(v time.Time) *AgentSkillVersionUpdateOne { + _u.mutation.SetCreatedAt(v) + return _u +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_u *AgentSkillVersionUpdateOne) SetNillableCreatedAt(v *time.Time) *AgentSkillVersionUpdateOne { + if v != nil { + _u.SetCreatedAt(*v) + } + return _u +} + +// SetSkillID sets the "skill" edge to the AgentSkill entity by ID. +func (_u *AgentSkillVersionUpdateOne) SetSkillID(id uuid.UUID) *AgentSkillVersionUpdateOne { + _u.mutation.SetSkillID(id) + return _u +} + +// SetSkill sets the "skill" edge to the AgentSkill entity. +func (_u *AgentSkillVersionUpdateOne) SetSkill(v *AgentSkill) *AgentSkillVersionUpdateOne { + return _u.SetSkillID(v.ID) +} + +// Mutation returns the AgentSkillVersionMutation object of the builder. +func (_u *AgentSkillVersionUpdateOne) Mutation() *AgentSkillVersionMutation { + return _u.mutation +} + +// ClearSkill clears the "skill" edge to the AgentSkill entity. +func (_u *AgentSkillVersionUpdateOne) ClearSkill() *AgentSkillVersionUpdateOne { + _u.mutation.ClearSkill() + return _u +} + +// Where appends a list predicates to the AgentSkillVersionUpdate builder. +func (_u *AgentSkillVersionUpdateOne) Where(ps ...predicate.AgentSkillVersion) *AgentSkillVersionUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *AgentSkillVersionUpdateOne) Select(field string, fields ...string) *AgentSkillVersionUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated AgentSkillVersion entity. +func (_u *AgentSkillVersionUpdateOne) Save(ctx context.Context) (*AgentSkillVersion, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *AgentSkillVersionUpdateOne) SaveX(ctx context.Context) *AgentSkillVersion { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *AgentSkillVersionUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *AgentSkillVersionUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *AgentSkillVersionUpdateOne) check() error { + if v, ok := _u.mutation.Version(); ok { + if err := agentskillversion.VersionValidator(v); err != nil { + return &ValidationError{Name: "version", err: fmt.Errorf(`db: validator failed for field "AgentSkillVersion.version": %w`, err)} + } + } + if v, ok := _u.mutation.S3Key(); ok { + if err := agentskillversion.S3KeyValidator(v); err != nil { + return &ValidationError{Name: "s3_key", err: fmt.Errorf(`db: validator failed for field "AgentSkillVersion.s3_key": %w`, err)} + } + } + if _u.mutation.SkillCleared() && len(_u.mutation.SkillIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "AgentSkillVersion.skill"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (_u *AgentSkillVersionUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *AgentSkillVersionUpdateOne { + _u.modifiers = append(_u.modifiers, modifiers...) + return _u +} + +func (_u *AgentSkillVersionUpdateOne) sqlSave(ctx context.Context) (_node *AgentSkillVersion, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(agentskillversion.Table, agentskillversion.Columns, sqlgraph.NewFieldSpec(agentskillversion.FieldID, field.TypeUUID)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "AgentSkillVersion.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, agentskillversion.FieldID) + for _, f := range fields { + if !agentskillversion.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != agentskillversion.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.Version(); ok { + _spec.SetField(agentskillversion.FieldVersion, field.TypeString, value) + } + if value, ok := _u.mutation.S3Key(); ok { + _spec.SetField(agentskillversion.FieldS3Key, field.TypeString, value) + } + if value, ok := _u.mutation.ParsedMeta(); ok { + _spec.SetField(agentskillversion.FieldParsedMeta, field.TypeJSON, value) + } + if _u.mutation.ParsedMetaCleared() { + _spec.ClearField(agentskillversion.FieldParsedMeta, field.TypeJSON) + } + if value, ok := _u.mutation.CreatedAt(); ok { + _spec.SetField(agentskillversion.FieldCreatedAt, field.TypeTime, value) + } + if _u.mutation.SkillCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: agentskillversion.SkillTable, + Columns: []string{agentskillversion.SkillColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentskill.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.SkillIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: agentskillversion.SkillTable, + Columns: []string{agentskillversion.SkillColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agentskill.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(_u.modifiers...) + _node = &AgentSkillVersion{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{agentskillversion.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/backend/db/agentsyncjob.go b/backend/db/agentsyncjob.go new file mode 100644 index 00000000..3858bd91 --- /dev/null +++ b/backend/db/agentsyncjob.go @@ -0,0 +1,264 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "encoding/json" + "fmt" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/chaitin/MonkeyCode/backend/db/agentsyncjob" + "github.com/chaitin/MonkeyCode/backend/ent/types" + "github.com/google/uuid" +) + +// AgentSyncJob is the model entity for the AgentSyncJob schema. +type AgentSyncJob struct { + config `json:"-"` + // ID of the ent. + ID uuid.UUID `json:"id,omitempty"` + // ResourceKind holds the value of the "resource_kind" field. + ResourceKind agentsyncjob.ResourceKind `json:"resource_kind,omitempty"` + // RuleID holds the value of the "rule_id" field. + RuleID *uuid.UUID `json:"rule_id,omitempty"` + // RepoID holds the value of the "repo_id" field. + RepoID *uuid.UUID `json:"repo_id,omitempty"` + // SourceType holds the value of the "source_type" field. + SourceType agentsyncjob.SourceType `json:"source_type,omitempty"` + // Status holds the value of the "status" field. + Status agentsyncjob.Status `json:"status,omitempty"` + // TriggerType holds the value of the "trigger_type" field. + TriggerType agentsyncjob.TriggerType `json:"trigger_type,omitempty"` + // TriggeredBy holds the value of the "triggered_by" field. + TriggeredBy *uuid.UUID `json:"triggered_by,omitempty"` + // StartedAt holds the value of the "started_at" field. + StartedAt *time.Time `json:"started_at,omitempty"` + // FinishedAt holds the value of the "finished_at" field. + FinishedAt *time.Time `json:"finished_at,omitempty"` + // Errors holds the value of the "errors" field. + Errors types.SyncJobErrors `json:"errors,omitempty"` + // ResultSummary holds the value of the "result_summary" field. + ResultSummary types.SyncJobResultSummary `json:"result_summary,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + // UpdatedAt holds the value of the "updated_at" field. + UpdatedAt time.Time `json:"updated_at,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*AgentSyncJob) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case agentsyncjob.FieldRuleID, agentsyncjob.FieldRepoID, agentsyncjob.FieldTriggeredBy: + values[i] = &sql.NullScanner{S: new(uuid.UUID)} + case agentsyncjob.FieldErrors, agentsyncjob.FieldResultSummary: + values[i] = new([]byte) + case agentsyncjob.FieldResourceKind, agentsyncjob.FieldSourceType, agentsyncjob.FieldStatus, agentsyncjob.FieldTriggerType: + values[i] = new(sql.NullString) + case agentsyncjob.FieldStartedAt, agentsyncjob.FieldFinishedAt, agentsyncjob.FieldCreatedAt, agentsyncjob.FieldUpdatedAt: + values[i] = new(sql.NullTime) + case agentsyncjob.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 AgentSyncJob fields. +func (_m *AgentSyncJob) 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 agentsyncjob.FieldID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value != nil { + _m.ID = *value + } + case agentsyncjob.FieldResourceKind: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field resource_kind", values[i]) + } else if value.Valid { + _m.ResourceKind = agentsyncjob.ResourceKind(value.String) + } + case agentsyncjob.FieldRuleID: + if value, ok := values[i].(*sql.NullScanner); !ok { + return fmt.Errorf("unexpected type %T for field rule_id", values[i]) + } else if value.Valid { + _m.RuleID = new(uuid.UUID) + *_m.RuleID = *value.S.(*uuid.UUID) + } + case agentsyncjob.FieldRepoID: + if value, ok := values[i].(*sql.NullScanner); !ok { + return fmt.Errorf("unexpected type %T for field repo_id", values[i]) + } else if value.Valid { + _m.RepoID = new(uuid.UUID) + *_m.RepoID = *value.S.(*uuid.UUID) + } + case agentsyncjob.FieldSourceType: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field source_type", values[i]) + } else if value.Valid { + _m.SourceType = agentsyncjob.SourceType(value.String) + } + case agentsyncjob.FieldStatus: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field status", values[i]) + } else if value.Valid { + _m.Status = agentsyncjob.Status(value.String) + } + case agentsyncjob.FieldTriggerType: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field trigger_type", values[i]) + } else if value.Valid { + _m.TriggerType = agentsyncjob.TriggerType(value.String) + } + case agentsyncjob.FieldTriggeredBy: + if value, ok := values[i].(*sql.NullScanner); !ok { + return fmt.Errorf("unexpected type %T for field triggered_by", values[i]) + } else if value.Valid { + _m.TriggeredBy = new(uuid.UUID) + *_m.TriggeredBy = *value.S.(*uuid.UUID) + } + case agentsyncjob.FieldStartedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field started_at", values[i]) + } else if value.Valid { + _m.StartedAt = new(time.Time) + *_m.StartedAt = value.Time + } + case agentsyncjob.FieldFinishedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field finished_at", values[i]) + } else if value.Valid { + _m.FinishedAt = new(time.Time) + *_m.FinishedAt = value.Time + } + case agentsyncjob.FieldErrors: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field errors", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.Errors); err != nil { + return fmt.Errorf("unmarshal field errors: %w", err) + } + } + case agentsyncjob.FieldResultSummary: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field result_summary", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.ResultSummary); err != nil { + return fmt.Errorf("unmarshal field result_summary: %w", err) + } + } + case agentsyncjob.FieldCreatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field created_at", values[i]) + } else if value.Valid { + _m.CreatedAt = value.Time + } + case agentsyncjob.FieldUpdatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field updated_at", values[i]) + } else if value.Valid { + _m.UpdatedAt = value.Time + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the AgentSyncJob. +// This includes values selected through modifiers, order, etc. +func (_m *AgentSyncJob) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// Update returns a builder for updating this AgentSyncJob. +// Note that you need to call AgentSyncJob.Unwrap() before calling this method if this AgentSyncJob +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *AgentSyncJob) Update() *AgentSyncJobUpdateOne { + return NewAgentSyncJobClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the AgentSyncJob entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (_m *AgentSyncJob) Unwrap() *AgentSyncJob { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: AgentSyncJob is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *AgentSyncJob) String() string { + var builder strings.Builder + builder.WriteString("AgentSyncJob(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("resource_kind=") + builder.WriteString(fmt.Sprintf("%v", _m.ResourceKind)) + builder.WriteString(", ") + if v := _m.RuleID; v != nil { + builder.WriteString("rule_id=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.RepoID; v != nil { + builder.WriteString("repo_id=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + builder.WriteString("source_type=") + builder.WriteString(fmt.Sprintf("%v", _m.SourceType)) + builder.WriteString(", ") + builder.WriteString("status=") + builder.WriteString(fmt.Sprintf("%v", _m.Status)) + builder.WriteString(", ") + builder.WriteString("trigger_type=") + builder.WriteString(fmt.Sprintf("%v", _m.TriggerType)) + builder.WriteString(", ") + if v := _m.TriggeredBy; v != nil { + builder.WriteString("triggered_by=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.StartedAt; v != nil { + builder.WriteString("started_at=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteString(", ") + if v := _m.FinishedAt; v != nil { + builder.WriteString("finished_at=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteString(", ") + builder.WriteString("errors=") + builder.WriteString(fmt.Sprintf("%v", _m.Errors)) + builder.WriteString(", ") + builder.WriteString("result_summary=") + builder.WriteString(fmt.Sprintf("%v", _m.ResultSummary)) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("updated_at=") + builder.WriteString(_m.UpdatedAt.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// AgentSyncJobs is a parsable slice of AgentSyncJob. +type AgentSyncJobs []*AgentSyncJob diff --git a/backend/db/agentsyncjob/agentsyncjob.go b/backend/db/agentsyncjob/agentsyncjob.go new file mode 100644 index 00000000..731c8bad --- /dev/null +++ b/backend/db/agentsyncjob/agentsyncjob.go @@ -0,0 +1,251 @@ +// Code generated by ent, DO NOT EDIT. + +package agentsyncjob + +import ( + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "github.com/google/uuid" +) + +const ( + // Label holds the string label denoting the agentsyncjob type in the database. + Label = "agent_sync_job" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldResourceKind holds the string denoting the resource_kind field in the database. + FieldResourceKind = "resource_kind" + // FieldRuleID holds the string denoting the rule_id field in the database. + FieldRuleID = "rule_id" + // FieldRepoID holds the string denoting the repo_id field in the database. + FieldRepoID = "repo_id" + // FieldSourceType holds the string denoting the source_type field in the database. + FieldSourceType = "source_type" + // FieldStatus holds the string denoting the status field in the database. + FieldStatus = "status" + // FieldTriggerType holds the string denoting the trigger_type field in the database. + FieldTriggerType = "trigger_type" + // FieldTriggeredBy holds the string denoting the triggered_by field in the database. + FieldTriggeredBy = "triggered_by" + // FieldStartedAt holds the string denoting the started_at field in the database. + FieldStartedAt = "started_at" + // FieldFinishedAt holds the string denoting the finished_at field in the database. + FieldFinishedAt = "finished_at" + // FieldErrors holds the string denoting the errors field in the database. + FieldErrors = "errors" + // FieldResultSummary holds the string denoting the result_summary field in the database. + FieldResultSummary = "result_summary" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // FieldUpdatedAt holds the string denoting the updated_at field in the database. + FieldUpdatedAt = "updated_at" + // Table holds the table name of the agentsyncjob in the database. + Table = "agent_sync_jobs" +) + +// Columns holds all SQL columns for agentsyncjob fields. +var Columns = []string{ + FieldID, + FieldResourceKind, + FieldRuleID, + FieldRepoID, + FieldSourceType, + FieldStatus, + FieldTriggerType, + FieldTriggeredBy, + FieldStartedAt, + FieldFinishedAt, + FieldErrors, + FieldResultSummary, + FieldCreatedAt, + FieldUpdatedAt, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time + // DefaultUpdatedAt holds the default value on creation for the "updated_at" field. + DefaultUpdatedAt func() time.Time + // UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field. + UpdateDefaultUpdatedAt func() time.Time + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() uuid.UUID +) + +// ResourceKind defines the type for the "resource_kind" enum field. +type ResourceKind string + +// ResourceKind values. +const ( + ResourceKindRule ResourceKind = "rule" + ResourceKindSkill ResourceKind = "skill" + ResourceKindPlugin ResourceKind = "plugin" +) + +func (rk ResourceKind) String() string { + return string(rk) +} + +// ResourceKindValidator is a validator for the "resource_kind" field enum values. It is called by the builders before save. +func ResourceKindValidator(rk ResourceKind) error { + switch rk { + case ResourceKindRule, ResourceKindSkill, ResourceKindPlugin: + return nil + default: + return fmt.Errorf("agentsyncjob: invalid enum value for resource_kind field: %q", rk) + } +} + +// SourceType defines the type for the "source_type" enum field. +type SourceType string + +// SourceType values. +const ( + SourceTypeGithub SourceType = "github" + SourceTypeUpload SourceType = "upload" + SourceTypeNpm SourceType = "npm" + SourceTypeRuleInline SourceType = "rule_inline" +) + +func (st SourceType) String() string { + return string(st) +} + +// SourceTypeValidator is a validator for the "source_type" field enum values. It is called by the builders before save. +func SourceTypeValidator(st SourceType) error { + switch st { + case SourceTypeGithub, SourceTypeUpload, SourceTypeNpm, SourceTypeRuleInline: + return nil + default: + return fmt.Errorf("agentsyncjob: invalid enum value for source_type field: %q", st) + } +} + +// Status defines the type for the "status" enum field. +type Status string + +// StatusPending is the default value of the Status enum. +const DefaultStatus = StatusPending + +// Status values. +const ( + StatusPending Status = "pending" + StatusFetching Status = "fetching" + StatusParsing Status = "parsing" + StatusUploading Status = "uploading" + StatusDone Status = "done" + StatusFailed Status = "failed" +) + +func (s Status) String() string { + return string(s) +} + +// StatusValidator is a validator for the "status" field enum values. It is called by the builders before save. +func StatusValidator(s Status) error { + switch s { + case StatusPending, StatusFetching, StatusParsing, StatusUploading, StatusDone, StatusFailed: + return nil + default: + return fmt.Errorf("agentsyncjob: invalid enum value for status field: %q", s) + } +} + +// TriggerType defines the type for the "trigger_type" enum field. +type TriggerType string + +// TriggerType values. +const ( + TriggerTypeManual TriggerType = "manual" + TriggerTypeUpload TriggerType = "upload" + TriggerTypeRuleSave TriggerType = "rule_save" +) + +func (tt TriggerType) String() string { + return string(tt) +} + +// TriggerTypeValidator is a validator for the "trigger_type" field enum values. It is called by the builders before save. +func TriggerTypeValidator(tt TriggerType) error { + switch tt { + case TriggerTypeManual, TriggerTypeUpload, TriggerTypeRuleSave: + return nil + default: + return fmt.Errorf("agentsyncjob: invalid enum value for trigger_type field: %q", tt) + } +} + +// OrderOption defines the ordering options for the AgentSyncJob 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() +} + +// ByResourceKind orders the results by the resource_kind field. +func ByResourceKind(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldResourceKind, opts...).ToFunc() +} + +// ByRuleID orders the results by the rule_id field. +func ByRuleID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRuleID, opts...).ToFunc() +} + +// ByRepoID orders the results by the repo_id field. +func ByRepoID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRepoID, opts...).ToFunc() +} + +// BySourceType orders the results by the source_type field. +func BySourceType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSourceType, opts...).ToFunc() +} + +// ByStatus orders the results by the status field. +func ByStatus(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldStatus, opts...).ToFunc() +} + +// ByTriggerType orders the results by the trigger_type field. +func ByTriggerType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTriggerType, opts...).ToFunc() +} + +// ByTriggeredBy orders the results by the triggered_by field. +func ByTriggeredBy(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTriggeredBy, opts...).ToFunc() +} + +// ByStartedAt orders the results by the started_at field. +func ByStartedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldStartedAt, opts...).ToFunc() +} + +// ByFinishedAt orders the results by the finished_at field. +func ByFinishedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldFinishedAt, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// ByUpdatedAt orders the results by the updated_at field. +func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc() +} diff --git a/backend/db/agentsyncjob/where.go b/backend/db/agentsyncjob/where.go new file mode 100644 index 00000000..069e4f11 --- /dev/null +++ b/backend/db/agentsyncjob/where.go @@ -0,0 +1,536 @@ +// Code generated by ent, DO NOT EDIT. + +package agentsyncjob + +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.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id uuid.UUID) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id uuid.UUID) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...uuid.UUID) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...uuid.UUID) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id uuid.UUID) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id uuid.UUID) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id uuid.UUID) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id uuid.UUID) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldLTE(FieldID, id)) +} + +// RuleID applies equality check predicate on the "rule_id" field. It's identical to RuleIDEQ. +func RuleID(v uuid.UUID) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldEQ(FieldRuleID, v)) +} + +// RepoID applies equality check predicate on the "repo_id" field. It's identical to RepoIDEQ. +func RepoID(v uuid.UUID) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldEQ(FieldRepoID, v)) +} + +// TriggeredBy applies equality check predicate on the "triggered_by" field. It's identical to TriggeredByEQ. +func TriggeredBy(v uuid.UUID) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldEQ(FieldTriggeredBy, v)) +} + +// StartedAt applies equality check predicate on the "started_at" field. It's identical to StartedAtEQ. +func StartedAt(v time.Time) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldEQ(FieldStartedAt, v)) +} + +// FinishedAt applies equality check predicate on the "finished_at" field. It's identical to FinishedAtEQ. +func FinishedAt(v time.Time) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldEQ(FieldFinishedAt, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldEQ(FieldCreatedAt, v)) +} + +// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ. +func UpdatedAt(v time.Time) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// ResourceKindEQ applies the EQ predicate on the "resource_kind" field. +func ResourceKindEQ(v ResourceKind) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldEQ(FieldResourceKind, v)) +} + +// ResourceKindNEQ applies the NEQ predicate on the "resource_kind" field. +func ResourceKindNEQ(v ResourceKind) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldNEQ(FieldResourceKind, v)) +} + +// ResourceKindIn applies the In predicate on the "resource_kind" field. +func ResourceKindIn(vs ...ResourceKind) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldIn(FieldResourceKind, vs...)) +} + +// ResourceKindNotIn applies the NotIn predicate on the "resource_kind" field. +func ResourceKindNotIn(vs ...ResourceKind) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldNotIn(FieldResourceKind, vs...)) +} + +// RuleIDEQ applies the EQ predicate on the "rule_id" field. +func RuleIDEQ(v uuid.UUID) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldEQ(FieldRuleID, v)) +} + +// RuleIDNEQ applies the NEQ predicate on the "rule_id" field. +func RuleIDNEQ(v uuid.UUID) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldNEQ(FieldRuleID, v)) +} + +// RuleIDIn applies the In predicate on the "rule_id" field. +func RuleIDIn(vs ...uuid.UUID) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldIn(FieldRuleID, vs...)) +} + +// RuleIDNotIn applies the NotIn predicate on the "rule_id" field. +func RuleIDNotIn(vs ...uuid.UUID) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldNotIn(FieldRuleID, vs...)) +} + +// RuleIDGT applies the GT predicate on the "rule_id" field. +func RuleIDGT(v uuid.UUID) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldGT(FieldRuleID, v)) +} + +// RuleIDGTE applies the GTE predicate on the "rule_id" field. +func RuleIDGTE(v uuid.UUID) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldGTE(FieldRuleID, v)) +} + +// RuleIDLT applies the LT predicate on the "rule_id" field. +func RuleIDLT(v uuid.UUID) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldLT(FieldRuleID, v)) +} + +// RuleIDLTE applies the LTE predicate on the "rule_id" field. +func RuleIDLTE(v uuid.UUID) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldLTE(FieldRuleID, v)) +} + +// RuleIDIsNil applies the IsNil predicate on the "rule_id" field. +func RuleIDIsNil() predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldIsNull(FieldRuleID)) +} + +// RuleIDNotNil applies the NotNil predicate on the "rule_id" field. +func RuleIDNotNil() predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldNotNull(FieldRuleID)) +} + +// RepoIDEQ applies the EQ predicate on the "repo_id" field. +func RepoIDEQ(v uuid.UUID) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldEQ(FieldRepoID, v)) +} + +// RepoIDNEQ applies the NEQ predicate on the "repo_id" field. +func RepoIDNEQ(v uuid.UUID) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldNEQ(FieldRepoID, v)) +} + +// RepoIDIn applies the In predicate on the "repo_id" field. +func RepoIDIn(vs ...uuid.UUID) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldIn(FieldRepoID, vs...)) +} + +// RepoIDNotIn applies the NotIn predicate on the "repo_id" field. +func RepoIDNotIn(vs ...uuid.UUID) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldNotIn(FieldRepoID, vs...)) +} + +// RepoIDGT applies the GT predicate on the "repo_id" field. +func RepoIDGT(v uuid.UUID) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldGT(FieldRepoID, v)) +} + +// RepoIDGTE applies the GTE predicate on the "repo_id" field. +func RepoIDGTE(v uuid.UUID) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldGTE(FieldRepoID, v)) +} + +// RepoIDLT applies the LT predicate on the "repo_id" field. +func RepoIDLT(v uuid.UUID) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldLT(FieldRepoID, v)) +} + +// RepoIDLTE applies the LTE predicate on the "repo_id" field. +func RepoIDLTE(v uuid.UUID) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldLTE(FieldRepoID, v)) +} + +// RepoIDIsNil applies the IsNil predicate on the "repo_id" field. +func RepoIDIsNil() predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldIsNull(FieldRepoID)) +} + +// RepoIDNotNil applies the NotNil predicate on the "repo_id" field. +func RepoIDNotNil() predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldNotNull(FieldRepoID)) +} + +// SourceTypeEQ applies the EQ predicate on the "source_type" field. +func SourceTypeEQ(v SourceType) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldEQ(FieldSourceType, v)) +} + +// SourceTypeNEQ applies the NEQ predicate on the "source_type" field. +func SourceTypeNEQ(v SourceType) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldNEQ(FieldSourceType, v)) +} + +// SourceTypeIn applies the In predicate on the "source_type" field. +func SourceTypeIn(vs ...SourceType) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldIn(FieldSourceType, vs...)) +} + +// SourceTypeNotIn applies the NotIn predicate on the "source_type" field. +func SourceTypeNotIn(vs ...SourceType) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldNotIn(FieldSourceType, vs...)) +} + +// StatusEQ applies the EQ predicate on the "status" field. +func StatusEQ(v Status) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldEQ(FieldStatus, v)) +} + +// StatusNEQ applies the NEQ predicate on the "status" field. +func StatusNEQ(v Status) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldNEQ(FieldStatus, v)) +} + +// StatusIn applies the In predicate on the "status" field. +func StatusIn(vs ...Status) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldIn(FieldStatus, vs...)) +} + +// StatusNotIn applies the NotIn predicate on the "status" field. +func StatusNotIn(vs ...Status) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldNotIn(FieldStatus, vs...)) +} + +// TriggerTypeEQ applies the EQ predicate on the "trigger_type" field. +func TriggerTypeEQ(v TriggerType) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldEQ(FieldTriggerType, v)) +} + +// TriggerTypeNEQ applies the NEQ predicate on the "trigger_type" field. +func TriggerTypeNEQ(v TriggerType) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldNEQ(FieldTriggerType, v)) +} + +// TriggerTypeIn applies the In predicate on the "trigger_type" field. +func TriggerTypeIn(vs ...TriggerType) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldIn(FieldTriggerType, vs...)) +} + +// TriggerTypeNotIn applies the NotIn predicate on the "trigger_type" field. +func TriggerTypeNotIn(vs ...TriggerType) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldNotIn(FieldTriggerType, vs...)) +} + +// TriggeredByEQ applies the EQ predicate on the "triggered_by" field. +func TriggeredByEQ(v uuid.UUID) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldEQ(FieldTriggeredBy, v)) +} + +// TriggeredByNEQ applies the NEQ predicate on the "triggered_by" field. +func TriggeredByNEQ(v uuid.UUID) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldNEQ(FieldTriggeredBy, v)) +} + +// TriggeredByIn applies the In predicate on the "triggered_by" field. +func TriggeredByIn(vs ...uuid.UUID) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldIn(FieldTriggeredBy, vs...)) +} + +// TriggeredByNotIn applies the NotIn predicate on the "triggered_by" field. +func TriggeredByNotIn(vs ...uuid.UUID) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldNotIn(FieldTriggeredBy, vs...)) +} + +// TriggeredByGT applies the GT predicate on the "triggered_by" field. +func TriggeredByGT(v uuid.UUID) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldGT(FieldTriggeredBy, v)) +} + +// TriggeredByGTE applies the GTE predicate on the "triggered_by" field. +func TriggeredByGTE(v uuid.UUID) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldGTE(FieldTriggeredBy, v)) +} + +// TriggeredByLT applies the LT predicate on the "triggered_by" field. +func TriggeredByLT(v uuid.UUID) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldLT(FieldTriggeredBy, v)) +} + +// TriggeredByLTE applies the LTE predicate on the "triggered_by" field. +func TriggeredByLTE(v uuid.UUID) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldLTE(FieldTriggeredBy, v)) +} + +// TriggeredByIsNil applies the IsNil predicate on the "triggered_by" field. +func TriggeredByIsNil() predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldIsNull(FieldTriggeredBy)) +} + +// TriggeredByNotNil applies the NotNil predicate on the "triggered_by" field. +func TriggeredByNotNil() predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldNotNull(FieldTriggeredBy)) +} + +// StartedAtEQ applies the EQ predicate on the "started_at" field. +func StartedAtEQ(v time.Time) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldEQ(FieldStartedAt, v)) +} + +// StartedAtNEQ applies the NEQ predicate on the "started_at" field. +func StartedAtNEQ(v time.Time) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldNEQ(FieldStartedAt, v)) +} + +// StartedAtIn applies the In predicate on the "started_at" field. +func StartedAtIn(vs ...time.Time) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldIn(FieldStartedAt, vs...)) +} + +// StartedAtNotIn applies the NotIn predicate on the "started_at" field. +func StartedAtNotIn(vs ...time.Time) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldNotIn(FieldStartedAt, vs...)) +} + +// StartedAtGT applies the GT predicate on the "started_at" field. +func StartedAtGT(v time.Time) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldGT(FieldStartedAt, v)) +} + +// StartedAtGTE applies the GTE predicate on the "started_at" field. +func StartedAtGTE(v time.Time) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldGTE(FieldStartedAt, v)) +} + +// StartedAtLT applies the LT predicate on the "started_at" field. +func StartedAtLT(v time.Time) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldLT(FieldStartedAt, v)) +} + +// StartedAtLTE applies the LTE predicate on the "started_at" field. +func StartedAtLTE(v time.Time) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldLTE(FieldStartedAt, v)) +} + +// StartedAtIsNil applies the IsNil predicate on the "started_at" field. +func StartedAtIsNil() predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldIsNull(FieldStartedAt)) +} + +// StartedAtNotNil applies the NotNil predicate on the "started_at" field. +func StartedAtNotNil() predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldNotNull(FieldStartedAt)) +} + +// FinishedAtEQ applies the EQ predicate on the "finished_at" field. +func FinishedAtEQ(v time.Time) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldEQ(FieldFinishedAt, v)) +} + +// FinishedAtNEQ applies the NEQ predicate on the "finished_at" field. +func FinishedAtNEQ(v time.Time) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldNEQ(FieldFinishedAt, v)) +} + +// FinishedAtIn applies the In predicate on the "finished_at" field. +func FinishedAtIn(vs ...time.Time) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldIn(FieldFinishedAt, vs...)) +} + +// FinishedAtNotIn applies the NotIn predicate on the "finished_at" field. +func FinishedAtNotIn(vs ...time.Time) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldNotIn(FieldFinishedAt, vs...)) +} + +// FinishedAtGT applies the GT predicate on the "finished_at" field. +func FinishedAtGT(v time.Time) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldGT(FieldFinishedAt, v)) +} + +// FinishedAtGTE applies the GTE predicate on the "finished_at" field. +func FinishedAtGTE(v time.Time) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldGTE(FieldFinishedAt, v)) +} + +// FinishedAtLT applies the LT predicate on the "finished_at" field. +func FinishedAtLT(v time.Time) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldLT(FieldFinishedAt, v)) +} + +// FinishedAtLTE applies the LTE predicate on the "finished_at" field. +func FinishedAtLTE(v time.Time) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldLTE(FieldFinishedAt, v)) +} + +// FinishedAtIsNil applies the IsNil predicate on the "finished_at" field. +func FinishedAtIsNil() predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldIsNull(FieldFinishedAt)) +} + +// FinishedAtNotNil applies the NotNil predicate on the "finished_at" field. +func FinishedAtNotNil() predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldNotNull(FieldFinishedAt)) +} + +// ErrorsIsNil applies the IsNil predicate on the "errors" field. +func ErrorsIsNil() predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldIsNull(FieldErrors)) +} + +// ErrorsNotNil applies the NotNil predicate on the "errors" field. +func ErrorsNotNil() predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldNotNull(FieldErrors)) +} + +// ResultSummaryIsNil applies the IsNil predicate on the "result_summary" field. +func ResultSummaryIsNil() predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldIsNull(FieldResultSummary)) +} + +// ResultSummaryNotNil applies the NotNil predicate on the "result_summary" field. +func ResultSummaryNotNil() predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldNotNull(FieldResultSummary)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.AgentSyncJob) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.AgentSyncJob) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.AgentSyncJob) predicate.AgentSyncJob { + return predicate.AgentSyncJob(sql.NotPredicates(p)) +} diff --git a/backend/db/agentsyncjob_create.go b/backend/db/agentsyncjob_create.go new file mode 100644 index 00000000..b549a72a --- /dev/null +++ b/backend/db/agentsyncjob_create.go @@ -0,0 +1,1369 @@ +// 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/agentsyncjob" + "github.com/chaitin/MonkeyCode/backend/ent/types" + "github.com/google/uuid" +) + +// AgentSyncJobCreate is the builder for creating a AgentSyncJob entity. +type AgentSyncJobCreate struct { + config + mutation *AgentSyncJobMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetResourceKind sets the "resource_kind" field. +func (_c *AgentSyncJobCreate) SetResourceKind(v agentsyncjob.ResourceKind) *AgentSyncJobCreate { + _c.mutation.SetResourceKind(v) + return _c +} + +// SetRuleID sets the "rule_id" field. +func (_c *AgentSyncJobCreate) SetRuleID(v uuid.UUID) *AgentSyncJobCreate { + _c.mutation.SetRuleID(v) + return _c +} + +// SetNillableRuleID sets the "rule_id" field if the given value is not nil. +func (_c *AgentSyncJobCreate) SetNillableRuleID(v *uuid.UUID) *AgentSyncJobCreate { + if v != nil { + _c.SetRuleID(*v) + } + return _c +} + +// SetRepoID sets the "repo_id" field. +func (_c *AgentSyncJobCreate) SetRepoID(v uuid.UUID) *AgentSyncJobCreate { + _c.mutation.SetRepoID(v) + return _c +} + +// SetNillableRepoID sets the "repo_id" field if the given value is not nil. +func (_c *AgentSyncJobCreate) SetNillableRepoID(v *uuid.UUID) *AgentSyncJobCreate { + if v != nil { + _c.SetRepoID(*v) + } + return _c +} + +// SetSourceType sets the "source_type" field. +func (_c *AgentSyncJobCreate) SetSourceType(v agentsyncjob.SourceType) *AgentSyncJobCreate { + _c.mutation.SetSourceType(v) + return _c +} + +// SetStatus sets the "status" field. +func (_c *AgentSyncJobCreate) SetStatus(v agentsyncjob.Status) *AgentSyncJobCreate { + _c.mutation.SetStatus(v) + return _c +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (_c *AgentSyncJobCreate) SetNillableStatus(v *agentsyncjob.Status) *AgentSyncJobCreate { + if v != nil { + _c.SetStatus(*v) + } + return _c +} + +// SetTriggerType sets the "trigger_type" field. +func (_c *AgentSyncJobCreate) SetTriggerType(v agentsyncjob.TriggerType) *AgentSyncJobCreate { + _c.mutation.SetTriggerType(v) + return _c +} + +// SetTriggeredBy sets the "triggered_by" field. +func (_c *AgentSyncJobCreate) SetTriggeredBy(v uuid.UUID) *AgentSyncJobCreate { + _c.mutation.SetTriggeredBy(v) + return _c +} + +// SetNillableTriggeredBy sets the "triggered_by" field if the given value is not nil. +func (_c *AgentSyncJobCreate) SetNillableTriggeredBy(v *uuid.UUID) *AgentSyncJobCreate { + if v != nil { + _c.SetTriggeredBy(*v) + } + return _c +} + +// SetStartedAt sets the "started_at" field. +func (_c *AgentSyncJobCreate) SetStartedAt(v time.Time) *AgentSyncJobCreate { + _c.mutation.SetStartedAt(v) + return _c +} + +// SetNillableStartedAt sets the "started_at" field if the given value is not nil. +func (_c *AgentSyncJobCreate) SetNillableStartedAt(v *time.Time) *AgentSyncJobCreate { + if v != nil { + _c.SetStartedAt(*v) + } + return _c +} + +// SetFinishedAt sets the "finished_at" field. +func (_c *AgentSyncJobCreate) SetFinishedAt(v time.Time) *AgentSyncJobCreate { + _c.mutation.SetFinishedAt(v) + return _c +} + +// SetNillableFinishedAt sets the "finished_at" field if the given value is not nil. +func (_c *AgentSyncJobCreate) SetNillableFinishedAt(v *time.Time) *AgentSyncJobCreate { + if v != nil { + _c.SetFinishedAt(*v) + } + return _c +} + +// SetErrors sets the "errors" field. +func (_c *AgentSyncJobCreate) SetErrors(v types.SyncJobErrors) *AgentSyncJobCreate { + _c.mutation.SetErrors(v) + return _c +} + +// SetResultSummary sets the "result_summary" field. +func (_c *AgentSyncJobCreate) SetResultSummary(v types.SyncJobResultSummary) *AgentSyncJobCreate { + _c.mutation.SetResultSummary(v) + return _c +} + +// SetNillableResultSummary sets the "result_summary" field if the given value is not nil. +func (_c *AgentSyncJobCreate) SetNillableResultSummary(v *types.SyncJobResultSummary) *AgentSyncJobCreate { + if v != nil { + _c.SetResultSummary(*v) + } + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *AgentSyncJobCreate) SetCreatedAt(v time.Time) *AgentSyncJobCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *AgentSyncJobCreate) SetNillableCreatedAt(v *time.Time) *AgentSyncJobCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *AgentSyncJobCreate) SetUpdatedAt(v time.Time) *AgentSyncJobCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *AgentSyncJobCreate) SetNillableUpdatedAt(v *time.Time) *AgentSyncJobCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *AgentSyncJobCreate) SetID(v uuid.UUID) *AgentSyncJobCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *AgentSyncJobCreate) SetNillableID(v *uuid.UUID) *AgentSyncJobCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// Mutation returns the AgentSyncJobMutation object of the builder. +func (_c *AgentSyncJobCreate) Mutation() *AgentSyncJobMutation { + return _c.mutation +} + +// Save creates the AgentSyncJob in the database. +func (_c *AgentSyncJobCreate) Save(ctx context.Context) (*AgentSyncJob, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *AgentSyncJobCreate) SaveX(ctx context.Context) *AgentSyncJob { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *AgentSyncJobCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *AgentSyncJobCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *AgentSyncJobCreate) defaults() { + if _, ok := _c.mutation.Status(); !ok { + v := agentsyncjob.DefaultStatus + _c.mutation.SetStatus(v) + } + if _, ok := _c.mutation.CreatedAt(); !ok { + v := agentsyncjob.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := agentsyncjob.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := agentsyncjob.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *AgentSyncJobCreate) check() error { + if _, ok := _c.mutation.ResourceKind(); !ok { + return &ValidationError{Name: "resource_kind", err: errors.New(`db: missing required field "AgentSyncJob.resource_kind"`)} + } + if v, ok := _c.mutation.ResourceKind(); ok { + if err := agentsyncjob.ResourceKindValidator(v); err != nil { + return &ValidationError{Name: "resource_kind", err: fmt.Errorf(`db: validator failed for field "AgentSyncJob.resource_kind": %w`, err)} + } + } + if _, ok := _c.mutation.SourceType(); !ok { + return &ValidationError{Name: "source_type", err: errors.New(`db: missing required field "AgentSyncJob.source_type"`)} + } + if v, ok := _c.mutation.SourceType(); ok { + if err := agentsyncjob.SourceTypeValidator(v); err != nil { + return &ValidationError{Name: "source_type", err: fmt.Errorf(`db: validator failed for field "AgentSyncJob.source_type": %w`, err)} + } + } + if _, ok := _c.mutation.Status(); !ok { + return &ValidationError{Name: "status", err: errors.New(`db: missing required field "AgentSyncJob.status"`)} + } + if v, ok := _c.mutation.Status(); ok { + if err := agentsyncjob.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`db: validator failed for field "AgentSyncJob.status": %w`, err)} + } + } + if _, ok := _c.mutation.TriggerType(); !ok { + return &ValidationError{Name: "trigger_type", err: errors.New(`db: missing required field "AgentSyncJob.trigger_type"`)} + } + if v, ok := _c.mutation.TriggerType(); ok { + if err := agentsyncjob.TriggerTypeValidator(v); err != nil { + return &ValidationError{Name: "trigger_type", err: fmt.Errorf(`db: validator failed for field "AgentSyncJob.trigger_type": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "AgentSyncJob.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "AgentSyncJob.updated_at"`)} + } + return nil +} + +func (_c *AgentSyncJobCreate) sqlSave(ctx context.Context) (*AgentSyncJob, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.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 + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *AgentSyncJobCreate) createSpec() (*AgentSyncJob, *sqlgraph.CreateSpec) { + var ( + _node = &AgentSyncJob{config: _c.config} + _spec = sqlgraph.NewCreateSpec(agentsyncjob.Table, sqlgraph.NewFieldSpec(agentsyncjob.FieldID, field.TypeUUID)) + ) + _spec.OnConflict = _c.conflict + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = &id + } + if value, ok := _c.mutation.ResourceKind(); ok { + _spec.SetField(agentsyncjob.FieldResourceKind, field.TypeEnum, value) + _node.ResourceKind = value + } + if value, ok := _c.mutation.RuleID(); ok { + _spec.SetField(agentsyncjob.FieldRuleID, field.TypeUUID, value) + _node.RuleID = &value + } + if value, ok := _c.mutation.RepoID(); ok { + _spec.SetField(agentsyncjob.FieldRepoID, field.TypeUUID, value) + _node.RepoID = &value + } + if value, ok := _c.mutation.SourceType(); ok { + _spec.SetField(agentsyncjob.FieldSourceType, field.TypeEnum, value) + _node.SourceType = value + } + if value, ok := _c.mutation.Status(); ok { + _spec.SetField(agentsyncjob.FieldStatus, field.TypeEnum, value) + _node.Status = value + } + if value, ok := _c.mutation.TriggerType(); ok { + _spec.SetField(agentsyncjob.FieldTriggerType, field.TypeEnum, value) + _node.TriggerType = value + } + if value, ok := _c.mutation.TriggeredBy(); ok { + _spec.SetField(agentsyncjob.FieldTriggeredBy, field.TypeUUID, value) + _node.TriggeredBy = &value + } + if value, ok := _c.mutation.StartedAt(); ok { + _spec.SetField(agentsyncjob.FieldStartedAt, field.TypeTime, value) + _node.StartedAt = &value + } + if value, ok := _c.mutation.FinishedAt(); ok { + _spec.SetField(agentsyncjob.FieldFinishedAt, field.TypeTime, value) + _node.FinishedAt = &value + } + if value, ok := _c.mutation.Errors(); ok { + _spec.SetField(agentsyncjob.FieldErrors, field.TypeJSON, value) + _node.Errors = value + } + if value, ok := _c.mutation.ResultSummary(); ok { + _spec.SetField(agentsyncjob.FieldResultSummary, field.TypeJSON, value) + _node.ResultSummary = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(agentsyncjob.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(agentsyncjob.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.AgentSyncJob.Create(). +// SetResourceKind(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.AgentSyncJobUpsert) { +// SetResourceKind(v+v). +// }). +// Exec(ctx) +func (_c *AgentSyncJobCreate) OnConflict(opts ...sql.ConflictOption) *AgentSyncJobUpsertOne { + _c.conflict = opts + return &AgentSyncJobUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.AgentSyncJob.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *AgentSyncJobCreate) OnConflictColumns(columns ...string) *AgentSyncJobUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &AgentSyncJobUpsertOne{ + create: _c, + } +} + +type ( + // AgentSyncJobUpsertOne is the builder for "upsert"-ing + // one AgentSyncJob node. + AgentSyncJobUpsertOne struct { + create *AgentSyncJobCreate + } + + // AgentSyncJobUpsert is the "OnConflict" setter. + AgentSyncJobUpsert struct { + *sql.UpdateSet + } +) + +// SetResourceKind sets the "resource_kind" field. +func (u *AgentSyncJobUpsert) SetResourceKind(v agentsyncjob.ResourceKind) *AgentSyncJobUpsert { + u.Set(agentsyncjob.FieldResourceKind, v) + return u +} + +// UpdateResourceKind sets the "resource_kind" field to the value that was provided on create. +func (u *AgentSyncJobUpsert) UpdateResourceKind() *AgentSyncJobUpsert { + u.SetExcluded(agentsyncjob.FieldResourceKind) + return u +} + +// SetRuleID sets the "rule_id" field. +func (u *AgentSyncJobUpsert) SetRuleID(v uuid.UUID) *AgentSyncJobUpsert { + u.Set(agentsyncjob.FieldRuleID, v) + return u +} + +// UpdateRuleID sets the "rule_id" field to the value that was provided on create. +func (u *AgentSyncJobUpsert) UpdateRuleID() *AgentSyncJobUpsert { + u.SetExcluded(agentsyncjob.FieldRuleID) + return u +} + +// ClearRuleID clears the value of the "rule_id" field. +func (u *AgentSyncJobUpsert) ClearRuleID() *AgentSyncJobUpsert { + u.SetNull(agentsyncjob.FieldRuleID) + return u +} + +// SetRepoID sets the "repo_id" field. +func (u *AgentSyncJobUpsert) SetRepoID(v uuid.UUID) *AgentSyncJobUpsert { + u.Set(agentsyncjob.FieldRepoID, v) + return u +} + +// UpdateRepoID sets the "repo_id" field to the value that was provided on create. +func (u *AgentSyncJobUpsert) UpdateRepoID() *AgentSyncJobUpsert { + u.SetExcluded(agentsyncjob.FieldRepoID) + return u +} + +// ClearRepoID clears the value of the "repo_id" field. +func (u *AgentSyncJobUpsert) ClearRepoID() *AgentSyncJobUpsert { + u.SetNull(agentsyncjob.FieldRepoID) + return u +} + +// SetSourceType sets the "source_type" field. +func (u *AgentSyncJobUpsert) SetSourceType(v agentsyncjob.SourceType) *AgentSyncJobUpsert { + u.Set(agentsyncjob.FieldSourceType, v) + return u +} + +// UpdateSourceType sets the "source_type" field to the value that was provided on create. +func (u *AgentSyncJobUpsert) UpdateSourceType() *AgentSyncJobUpsert { + u.SetExcluded(agentsyncjob.FieldSourceType) + return u +} + +// SetStatus sets the "status" field. +func (u *AgentSyncJobUpsert) SetStatus(v agentsyncjob.Status) *AgentSyncJobUpsert { + u.Set(agentsyncjob.FieldStatus, v) + return u +} + +// UpdateStatus sets the "status" field to the value that was provided on create. +func (u *AgentSyncJobUpsert) UpdateStatus() *AgentSyncJobUpsert { + u.SetExcluded(agentsyncjob.FieldStatus) + return u +} + +// SetTriggerType sets the "trigger_type" field. +func (u *AgentSyncJobUpsert) SetTriggerType(v agentsyncjob.TriggerType) *AgentSyncJobUpsert { + u.Set(agentsyncjob.FieldTriggerType, v) + return u +} + +// UpdateTriggerType sets the "trigger_type" field to the value that was provided on create. +func (u *AgentSyncJobUpsert) UpdateTriggerType() *AgentSyncJobUpsert { + u.SetExcluded(agentsyncjob.FieldTriggerType) + return u +} + +// SetTriggeredBy sets the "triggered_by" field. +func (u *AgentSyncJobUpsert) SetTriggeredBy(v uuid.UUID) *AgentSyncJobUpsert { + u.Set(agentsyncjob.FieldTriggeredBy, v) + return u +} + +// UpdateTriggeredBy sets the "triggered_by" field to the value that was provided on create. +func (u *AgentSyncJobUpsert) UpdateTriggeredBy() *AgentSyncJobUpsert { + u.SetExcluded(agentsyncjob.FieldTriggeredBy) + return u +} + +// ClearTriggeredBy clears the value of the "triggered_by" field. +func (u *AgentSyncJobUpsert) ClearTriggeredBy() *AgentSyncJobUpsert { + u.SetNull(agentsyncjob.FieldTriggeredBy) + return u +} + +// SetStartedAt sets the "started_at" field. +func (u *AgentSyncJobUpsert) SetStartedAt(v time.Time) *AgentSyncJobUpsert { + u.Set(agentsyncjob.FieldStartedAt, v) + return u +} + +// UpdateStartedAt sets the "started_at" field to the value that was provided on create. +func (u *AgentSyncJobUpsert) UpdateStartedAt() *AgentSyncJobUpsert { + u.SetExcluded(agentsyncjob.FieldStartedAt) + return u +} + +// ClearStartedAt clears the value of the "started_at" field. +func (u *AgentSyncJobUpsert) ClearStartedAt() *AgentSyncJobUpsert { + u.SetNull(agentsyncjob.FieldStartedAt) + return u +} + +// SetFinishedAt sets the "finished_at" field. +func (u *AgentSyncJobUpsert) SetFinishedAt(v time.Time) *AgentSyncJobUpsert { + u.Set(agentsyncjob.FieldFinishedAt, v) + return u +} + +// UpdateFinishedAt sets the "finished_at" field to the value that was provided on create. +func (u *AgentSyncJobUpsert) UpdateFinishedAt() *AgentSyncJobUpsert { + u.SetExcluded(agentsyncjob.FieldFinishedAt) + return u +} + +// ClearFinishedAt clears the value of the "finished_at" field. +func (u *AgentSyncJobUpsert) ClearFinishedAt() *AgentSyncJobUpsert { + u.SetNull(agentsyncjob.FieldFinishedAt) + return u +} + +// SetErrors sets the "errors" field. +func (u *AgentSyncJobUpsert) SetErrors(v types.SyncJobErrors) *AgentSyncJobUpsert { + u.Set(agentsyncjob.FieldErrors, v) + return u +} + +// UpdateErrors sets the "errors" field to the value that was provided on create. +func (u *AgentSyncJobUpsert) UpdateErrors() *AgentSyncJobUpsert { + u.SetExcluded(agentsyncjob.FieldErrors) + return u +} + +// ClearErrors clears the value of the "errors" field. +func (u *AgentSyncJobUpsert) ClearErrors() *AgentSyncJobUpsert { + u.SetNull(agentsyncjob.FieldErrors) + return u +} + +// SetResultSummary sets the "result_summary" field. +func (u *AgentSyncJobUpsert) SetResultSummary(v types.SyncJobResultSummary) *AgentSyncJobUpsert { + u.Set(agentsyncjob.FieldResultSummary, v) + return u +} + +// UpdateResultSummary sets the "result_summary" field to the value that was provided on create. +func (u *AgentSyncJobUpsert) UpdateResultSummary() *AgentSyncJobUpsert { + u.SetExcluded(agentsyncjob.FieldResultSummary) + return u +} + +// ClearResultSummary clears the value of the "result_summary" field. +func (u *AgentSyncJobUpsert) ClearResultSummary() *AgentSyncJobUpsert { + u.SetNull(agentsyncjob.FieldResultSummary) + return u +} + +// SetCreatedAt sets the "created_at" field. +func (u *AgentSyncJobUpsert) SetCreatedAt(v time.Time) *AgentSyncJobUpsert { + u.Set(agentsyncjob.FieldCreatedAt, v) + return u +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *AgentSyncJobUpsert) UpdateCreatedAt() *AgentSyncJobUpsert { + u.SetExcluded(agentsyncjob.FieldCreatedAt) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *AgentSyncJobUpsert) SetUpdatedAt(v time.Time) *AgentSyncJobUpsert { + u.Set(agentsyncjob.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *AgentSyncJobUpsert) UpdateUpdatedAt() *AgentSyncJobUpsert { + u.SetExcluded(agentsyncjob.FieldUpdatedAt) + return u +} + +// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field. +// Using this option is equivalent to using: +// +// client.AgentSyncJob.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(agentsyncjob.FieldID) +// }), +// ). +// Exec(ctx) +func (u *AgentSyncJobUpsertOne) UpdateNewValues() *AgentSyncJobUpsertOne { + 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(agentsyncjob.FieldID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.AgentSyncJob.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *AgentSyncJobUpsertOne) Ignore() *AgentSyncJobUpsertOne { + 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 *AgentSyncJobUpsertOne) DoNothing() *AgentSyncJobUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the AgentSyncJobCreate.OnConflict +// documentation for more info. +func (u *AgentSyncJobUpsertOne) Update(set func(*AgentSyncJobUpsert)) *AgentSyncJobUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&AgentSyncJobUpsert{UpdateSet: update}) + })) + return u +} + +// SetResourceKind sets the "resource_kind" field. +func (u *AgentSyncJobUpsertOne) SetResourceKind(v agentsyncjob.ResourceKind) *AgentSyncJobUpsertOne { + return u.Update(func(s *AgentSyncJobUpsert) { + s.SetResourceKind(v) + }) +} + +// UpdateResourceKind sets the "resource_kind" field to the value that was provided on create. +func (u *AgentSyncJobUpsertOne) UpdateResourceKind() *AgentSyncJobUpsertOne { + return u.Update(func(s *AgentSyncJobUpsert) { + s.UpdateResourceKind() + }) +} + +// SetRuleID sets the "rule_id" field. +func (u *AgentSyncJobUpsertOne) SetRuleID(v uuid.UUID) *AgentSyncJobUpsertOne { + return u.Update(func(s *AgentSyncJobUpsert) { + s.SetRuleID(v) + }) +} + +// UpdateRuleID sets the "rule_id" field to the value that was provided on create. +func (u *AgentSyncJobUpsertOne) UpdateRuleID() *AgentSyncJobUpsertOne { + return u.Update(func(s *AgentSyncJobUpsert) { + s.UpdateRuleID() + }) +} + +// ClearRuleID clears the value of the "rule_id" field. +func (u *AgentSyncJobUpsertOne) ClearRuleID() *AgentSyncJobUpsertOne { + return u.Update(func(s *AgentSyncJobUpsert) { + s.ClearRuleID() + }) +} + +// SetRepoID sets the "repo_id" field. +func (u *AgentSyncJobUpsertOne) SetRepoID(v uuid.UUID) *AgentSyncJobUpsertOne { + return u.Update(func(s *AgentSyncJobUpsert) { + s.SetRepoID(v) + }) +} + +// UpdateRepoID sets the "repo_id" field to the value that was provided on create. +func (u *AgentSyncJobUpsertOne) UpdateRepoID() *AgentSyncJobUpsertOne { + return u.Update(func(s *AgentSyncJobUpsert) { + s.UpdateRepoID() + }) +} + +// ClearRepoID clears the value of the "repo_id" field. +func (u *AgentSyncJobUpsertOne) ClearRepoID() *AgentSyncJobUpsertOne { + return u.Update(func(s *AgentSyncJobUpsert) { + s.ClearRepoID() + }) +} + +// SetSourceType sets the "source_type" field. +func (u *AgentSyncJobUpsertOne) SetSourceType(v agentsyncjob.SourceType) *AgentSyncJobUpsertOne { + return u.Update(func(s *AgentSyncJobUpsert) { + s.SetSourceType(v) + }) +} + +// UpdateSourceType sets the "source_type" field to the value that was provided on create. +func (u *AgentSyncJobUpsertOne) UpdateSourceType() *AgentSyncJobUpsertOne { + return u.Update(func(s *AgentSyncJobUpsert) { + s.UpdateSourceType() + }) +} + +// SetStatus sets the "status" field. +func (u *AgentSyncJobUpsertOne) SetStatus(v agentsyncjob.Status) *AgentSyncJobUpsertOne { + return u.Update(func(s *AgentSyncJobUpsert) { + s.SetStatus(v) + }) +} + +// UpdateStatus sets the "status" field to the value that was provided on create. +func (u *AgentSyncJobUpsertOne) UpdateStatus() *AgentSyncJobUpsertOne { + return u.Update(func(s *AgentSyncJobUpsert) { + s.UpdateStatus() + }) +} + +// SetTriggerType sets the "trigger_type" field. +func (u *AgentSyncJobUpsertOne) SetTriggerType(v agentsyncjob.TriggerType) *AgentSyncJobUpsertOne { + return u.Update(func(s *AgentSyncJobUpsert) { + s.SetTriggerType(v) + }) +} + +// UpdateTriggerType sets the "trigger_type" field to the value that was provided on create. +func (u *AgentSyncJobUpsertOne) UpdateTriggerType() *AgentSyncJobUpsertOne { + return u.Update(func(s *AgentSyncJobUpsert) { + s.UpdateTriggerType() + }) +} + +// SetTriggeredBy sets the "triggered_by" field. +func (u *AgentSyncJobUpsertOne) SetTriggeredBy(v uuid.UUID) *AgentSyncJobUpsertOne { + return u.Update(func(s *AgentSyncJobUpsert) { + s.SetTriggeredBy(v) + }) +} + +// UpdateTriggeredBy sets the "triggered_by" field to the value that was provided on create. +func (u *AgentSyncJobUpsertOne) UpdateTriggeredBy() *AgentSyncJobUpsertOne { + return u.Update(func(s *AgentSyncJobUpsert) { + s.UpdateTriggeredBy() + }) +} + +// ClearTriggeredBy clears the value of the "triggered_by" field. +func (u *AgentSyncJobUpsertOne) ClearTriggeredBy() *AgentSyncJobUpsertOne { + return u.Update(func(s *AgentSyncJobUpsert) { + s.ClearTriggeredBy() + }) +} + +// SetStartedAt sets the "started_at" field. +func (u *AgentSyncJobUpsertOne) SetStartedAt(v time.Time) *AgentSyncJobUpsertOne { + return u.Update(func(s *AgentSyncJobUpsert) { + s.SetStartedAt(v) + }) +} + +// UpdateStartedAt sets the "started_at" field to the value that was provided on create. +func (u *AgentSyncJobUpsertOne) UpdateStartedAt() *AgentSyncJobUpsertOne { + return u.Update(func(s *AgentSyncJobUpsert) { + s.UpdateStartedAt() + }) +} + +// ClearStartedAt clears the value of the "started_at" field. +func (u *AgentSyncJobUpsertOne) ClearStartedAt() *AgentSyncJobUpsertOne { + return u.Update(func(s *AgentSyncJobUpsert) { + s.ClearStartedAt() + }) +} + +// SetFinishedAt sets the "finished_at" field. +func (u *AgentSyncJobUpsertOne) SetFinishedAt(v time.Time) *AgentSyncJobUpsertOne { + return u.Update(func(s *AgentSyncJobUpsert) { + s.SetFinishedAt(v) + }) +} + +// UpdateFinishedAt sets the "finished_at" field to the value that was provided on create. +func (u *AgentSyncJobUpsertOne) UpdateFinishedAt() *AgentSyncJobUpsertOne { + return u.Update(func(s *AgentSyncJobUpsert) { + s.UpdateFinishedAt() + }) +} + +// ClearFinishedAt clears the value of the "finished_at" field. +func (u *AgentSyncJobUpsertOne) ClearFinishedAt() *AgentSyncJobUpsertOne { + return u.Update(func(s *AgentSyncJobUpsert) { + s.ClearFinishedAt() + }) +} + +// SetErrors sets the "errors" field. +func (u *AgentSyncJobUpsertOne) SetErrors(v types.SyncJobErrors) *AgentSyncJobUpsertOne { + return u.Update(func(s *AgentSyncJobUpsert) { + s.SetErrors(v) + }) +} + +// UpdateErrors sets the "errors" field to the value that was provided on create. +func (u *AgentSyncJobUpsertOne) UpdateErrors() *AgentSyncJobUpsertOne { + return u.Update(func(s *AgentSyncJobUpsert) { + s.UpdateErrors() + }) +} + +// ClearErrors clears the value of the "errors" field. +func (u *AgentSyncJobUpsertOne) ClearErrors() *AgentSyncJobUpsertOne { + return u.Update(func(s *AgentSyncJobUpsert) { + s.ClearErrors() + }) +} + +// SetResultSummary sets the "result_summary" field. +func (u *AgentSyncJobUpsertOne) SetResultSummary(v types.SyncJobResultSummary) *AgentSyncJobUpsertOne { + return u.Update(func(s *AgentSyncJobUpsert) { + s.SetResultSummary(v) + }) +} + +// UpdateResultSummary sets the "result_summary" field to the value that was provided on create. +func (u *AgentSyncJobUpsertOne) UpdateResultSummary() *AgentSyncJobUpsertOne { + return u.Update(func(s *AgentSyncJobUpsert) { + s.UpdateResultSummary() + }) +} + +// ClearResultSummary clears the value of the "result_summary" field. +func (u *AgentSyncJobUpsertOne) ClearResultSummary() *AgentSyncJobUpsertOne { + return u.Update(func(s *AgentSyncJobUpsert) { + s.ClearResultSummary() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *AgentSyncJobUpsertOne) SetCreatedAt(v time.Time) *AgentSyncJobUpsertOne { + return u.Update(func(s *AgentSyncJobUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *AgentSyncJobUpsertOne) UpdateCreatedAt() *AgentSyncJobUpsertOne { + return u.Update(func(s *AgentSyncJobUpsert) { + s.UpdateCreatedAt() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *AgentSyncJobUpsertOne) SetUpdatedAt(v time.Time) *AgentSyncJobUpsertOne { + return u.Update(func(s *AgentSyncJobUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *AgentSyncJobUpsertOne) UpdateUpdatedAt() *AgentSyncJobUpsertOne { + return u.Update(func(s *AgentSyncJobUpsert) { + s.UpdateUpdatedAt() + }) +} + +// Exec executes the query. +func (u *AgentSyncJobUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for AgentSyncJobCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *AgentSyncJobUpsertOne) 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 *AgentSyncJobUpsertOne) 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: AgentSyncJobUpsertOne.ID is not supported by MySQL driver. Use AgentSyncJobUpsertOne.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 *AgentSyncJobUpsertOne) IDX(ctx context.Context) uuid.UUID { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// AgentSyncJobCreateBulk is the builder for creating many AgentSyncJob entities in bulk. +type AgentSyncJobCreateBulk struct { + config + err error + builders []*AgentSyncJobCreate + conflict []sql.ConflictOption +} + +// Save creates the AgentSyncJob entities in the database. +func (_c *AgentSyncJobCreateBulk) Save(ctx context.Context) ([]*AgentSyncJob, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*AgentSyncJob, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*AgentSyncJobMutation) + 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, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = _c.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.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, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *AgentSyncJobCreateBulk) SaveX(ctx context.Context) []*AgentSyncJob { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *AgentSyncJobCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *AgentSyncJobCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.AgentSyncJob.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.AgentSyncJobUpsert) { +// SetResourceKind(v+v). +// }). +// Exec(ctx) +func (_c *AgentSyncJobCreateBulk) OnConflict(opts ...sql.ConflictOption) *AgentSyncJobUpsertBulk { + _c.conflict = opts + return &AgentSyncJobUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.AgentSyncJob.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *AgentSyncJobCreateBulk) OnConflictColumns(columns ...string) *AgentSyncJobUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &AgentSyncJobUpsertBulk{ + create: _c, + } +} + +// AgentSyncJobUpsertBulk is the builder for "upsert"-ing +// a bulk of AgentSyncJob nodes. +type AgentSyncJobUpsertBulk struct { + create *AgentSyncJobCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.AgentSyncJob.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(agentsyncjob.FieldID) +// }), +// ). +// Exec(ctx) +func (u *AgentSyncJobUpsertBulk) UpdateNewValues() *AgentSyncJobUpsertBulk { + 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(agentsyncjob.FieldID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.AgentSyncJob.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *AgentSyncJobUpsertBulk) Ignore() *AgentSyncJobUpsertBulk { + 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 *AgentSyncJobUpsertBulk) DoNothing() *AgentSyncJobUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the AgentSyncJobCreateBulk.OnConflict +// documentation for more info. +func (u *AgentSyncJobUpsertBulk) Update(set func(*AgentSyncJobUpsert)) *AgentSyncJobUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&AgentSyncJobUpsert{UpdateSet: update}) + })) + return u +} + +// SetResourceKind sets the "resource_kind" field. +func (u *AgentSyncJobUpsertBulk) SetResourceKind(v agentsyncjob.ResourceKind) *AgentSyncJobUpsertBulk { + return u.Update(func(s *AgentSyncJobUpsert) { + s.SetResourceKind(v) + }) +} + +// UpdateResourceKind sets the "resource_kind" field to the value that was provided on create. +func (u *AgentSyncJobUpsertBulk) UpdateResourceKind() *AgentSyncJobUpsertBulk { + return u.Update(func(s *AgentSyncJobUpsert) { + s.UpdateResourceKind() + }) +} + +// SetRuleID sets the "rule_id" field. +func (u *AgentSyncJobUpsertBulk) SetRuleID(v uuid.UUID) *AgentSyncJobUpsertBulk { + return u.Update(func(s *AgentSyncJobUpsert) { + s.SetRuleID(v) + }) +} + +// UpdateRuleID sets the "rule_id" field to the value that was provided on create. +func (u *AgentSyncJobUpsertBulk) UpdateRuleID() *AgentSyncJobUpsertBulk { + return u.Update(func(s *AgentSyncJobUpsert) { + s.UpdateRuleID() + }) +} + +// ClearRuleID clears the value of the "rule_id" field. +func (u *AgentSyncJobUpsertBulk) ClearRuleID() *AgentSyncJobUpsertBulk { + return u.Update(func(s *AgentSyncJobUpsert) { + s.ClearRuleID() + }) +} + +// SetRepoID sets the "repo_id" field. +func (u *AgentSyncJobUpsertBulk) SetRepoID(v uuid.UUID) *AgentSyncJobUpsertBulk { + return u.Update(func(s *AgentSyncJobUpsert) { + s.SetRepoID(v) + }) +} + +// UpdateRepoID sets the "repo_id" field to the value that was provided on create. +func (u *AgentSyncJobUpsertBulk) UpdateRepoID() *AgentSyncJobUpsertBulk { + return u.Update(func(s *AgentSyncJobUpsert) { + s.UpdateRepoID() + }) +} + +// ClearRepoID clears the value of the "repo_id" field. +func (u *AgentSyncJobUpsertBulk) ClearRepoID() *AgentSyncJobUpsertBulk { + return u.Update(func(s *AgentSyncJobUpsert) { + s.ClearRepoID() + }) +} + +// SetSourceType sets the "source_type" field. +func (u *AgentSyncJobUpsertBulk) SetSourceType(v agentsyncjob.SourceType) *AgentSyncJobUpsertBulk { + return u.Update(func(s *AgentSyncJobUpsert) { + s.SetSourceType(v) + }) +} + +// UpdateSourceType sets the "source_type" field to the value that was provided on create. +func (u *AgentSyncJobUpsertBulk) UpdateSourceType() *AgentSyncJobUpsertBulk { + return u.Update(func(s *AgentSyncJobUpsert) { + s.UpdateSourceType() + }) +} + +// SetStatus sets the "status" field. +func (u *AgentSyncJobUpsertBulk) SetStatus(v agentsyncjob.Status) *AgentSyncJobUpsertBulk { + return u.Update(func(s *AgentSyncJobUpsert) { + s.SetStatus(v) + }) +} + +// UpdateStatus sets the "status" field to the value that was provided on create. +func (u *AgentSyncJobUpsertBulk) UpdateStatus() *AgentSyncJobUpsertBulk { + return u.Update(func(s *AgentSyncJobUpsert) { + s.UpdateStatus() + }) +} + +// SetTriggerType sets the "trigger_type" field. +func (u *AgentSyncJobUpsertBulk) SetTriggerType(v agentsyncjob.TriggerType) *AgentSyncJobUpsertBulk { + return u.Update(func(s *AgentSyncJobUpsert) { + s.SetTriggerType(v) + }) +} + +// UpdateTriggerType sets the "trigger_type" field to the value that was provided on create. +func (u *AgentSyncJobUpsertBulk) UpdateTriggerType() *AgentSyncJobUpsertBulk { + return u.Update(func(s *AgentSyncJobUpsert) { + s.UpdateTriggerType() + }) +} + +// SetTriggeredBy sets the "triggered_by" field. +func (u *AgentSyncJobUpsertBulk) SetTriggeredBy(v uuid.UUID) *AgentSyncJobUpsertBulk { + return u.Update(func(s *AgentSyncJobUpsert) { + s.SetTriggeredBy(v) + }) +} + +// UpdateTriggeredBy sets the "triggered_by" field to the value that was provided on create. +func (u *AgentSyncJobUpsertBulk) UpdateTriggeredBy() *AgentSyncJobUpsertBulk { + return u.Update(func(s *AgentSyncJobUpsert) { + s.UpdateTriggeredBy() + }) +} + +// ClearTriggeredBy clears the value of the "triggered_by" field. +func (u *AgentSyncJobUpsertBulk) ClearTriggeredBy() *AgentSyncJobUpsertBulk { + return u.Update(func(s *AgentSyncJobUpsert) { + s.ClearTriggeredBy() + }) +} + +// SetStartedAt sets the "started_at" field. +func (u *AgentSyncJobUpsertBulk) SetStartedAt(v time.Time) *AgentSyncJobUpsertBulk { + return u.Update(func(s *AgentSyncJobUpsert) { + s.SetStartedAt(v) + }) +} + +// UpdateStartedAt sets the "started_at" field to the value that was provided on create. +func (u *AgentSyncJobUpsertBulk) UpdateStartedAt() *AgentSyncJobUpsertBulk { + return u.Update(func(s *AgentSyncJobUpsert) { + s.UpdateStartedAt() + }) +} + +// ClearStartedAt clears the value of the "started_at" field. +func (u *AgentSyncJobUpsertBulk) ClearStartedAt() *AgentSyncJobUpsertBulk { + return u.Update(func(s *AgentSyncJobUpsert) { + s.ClearStartedAt() + }) +} + +// SetFinishedAt sets the "finished_at" field. +func (u *AgentSyncJobUpsertBulk) SetFinishedAt(v time.Time) *AgentSyncJobUpsertBulk { + return u.Update(func(s *AgentSyncJobUpsert) { + s.SetFinishedAt(v) + }) +} + +// UpdateFinishedAt sets the "finished_at" field to the value that was provided on create. +func (u *AgentSyncJobUpsertBulk) UpdateFinishedAt() *AgentSyncJobUpsertBulk { + return u.Update(func(s *AgentSyncJobUpsert) { + s.UpdateFinishedAt() + }) +} + +// ClearFinishedAt clears the value of the "finished_at" field. +func (u *AgentSyncJobUpsertBulk) ClearFinishedAt() *AgentSyncJobUpsertBulk { + return u.Update(func(s *AgentSyncJobUpsert) { + s.ClearFinishedAt() + }) +} + +// SetErrors sets the "errors" field. +func (u *AgentSyncJobUpsertBulk) SetErrors(v types.SyncJobErrors) *AgentSyncJobUpsertBulk { + return u.Update(func(s *AgentSyncJobUpsert) { + s.SetErrors(v) + }) +} + +// UpdateErrors sets the "errors" field to the value that was provided on create. +func (u *AgentSyncJobUpsertBulk) UpdateErrors() *AgentSyncJobUpsertBulk { + return u.Update(func(s *AgentSyncJobUpsert) { + s.UpdateErrors() + }) +} + +// ClearErrors clears the value of the "errors" field. +func (u *AgentSyncJobUpsertBulk) ClearErrors() *AgentSyncJobUpsertBulk { + return u.Update(func(s *AgentSyncJobUpsert) { + s.ClearErrors() + }) +} + +// SetResultSummary sets the "result_summary" field. +func (u *AgentSyncJobUpsertBulk) SetResultSummary(v types.SyncJobResultSummary) *AgentSyncJobUpsertBulk { + return u.Update(func(s *AgentSyncJobUpsert) { + s.SetResultSummary(v) + }) +} + +// UpdateResultSummary sets the "result_summary" field to the value that was provided on create. +func (u *AgentSyncJobUpsertBulk) UpdateResultSummary() *AgentSyncJobUpsertBulk { + return u.Update(func(s *AgentSyncJobUpsert) { + s.UpdateResultSummary() + }) +} + +// ClearResultSummary clears the value of the "result_summary" field. +func (u *AgentSyncJobUpsertBulk) ClearResultSummary() *AgentSyncJobUpsertBulk { + return u.Update(func(s *AgentSyncJobUpsert) { + s.ClearResultSummary() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *AgentSyncJobUpsertBulk) SetCreatedAt(v time.Time) *AgentSyncJobUpsertBulk { + return u.Update(func(s *AgentSyncJobUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *AgentSyncJobUpsertBulk) UpdateCreatedAt() *AgentSyncJobUpsertBulk { + return u.Update(func(s *AgentSyncJobUpsert) { + s.UpdateCreatedAt() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *AgentSyncJobUpsertBulk) SetUpdatedAt(v time.Time) *AgentSyncJobUpsertBulk { + return u.Update(func(s *AgentSyncJobUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *AgentSyncJobUpsertBulk) UpdateUpdatedAt() *AgentSyncJobUpsertBulk { + return u.Update(func(s *AgentSyncJobUpsert) { + s.UpdateUpdatedAt() + }) +} + +// Exec executes the query. +func (u *AgentSyncJobUpsertBulk) 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 AgentSyncJobCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for AgentSyncJobCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *AgentSyncJobUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/agentsyncjob_delete.go b/backend/db/agentsyncjob_delete.go new file mode 100644 index 00000000..ea87a907 --- /dev/null +++ b/backend/db/agentsyncjob_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/agentsyncjob" + "github.com/chaitin/MonkeyCode/backend/db/predicate" +) + +// AgentSyncJobDelete is the builder for deleting a AgentSyncJob entity. +type AgentSyncJobDelete struct { + config + hooks []Hook + mutation *AgentSyncJobMutation +} + +// Where appends a list predicates to the AgentSyncJobDelete builder. +func (_d *AgentSyncJobDelete) Where(ps ...predicate.AgentSyncJob) *AgentSyncJobDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *AgentSyncJobDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *AgentSyncJobDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *AgentSyncJobDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(agentsyncjob.Table, sqlgraph.NewFieldSpec(agentsyncjob.FieldID, field.TypeUUID)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// AgentSyncJobDeleteOne is the builder for deleting a single AgentSyncJob entity. +type AgentSyncJobDeleteOne struct { + _d *AgentSyncJobDelete +} + +// Where appends a list predicates to the AgentSyncJobDelete builder. +func (_d *AgentSyncJobDeleteOne) Where(ps ...predicate.AgentSyncJob) *AgentSyncJobDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *AgentSyncJobDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{agentsyncjob.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *AgentSyncJobDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/agentsyncjob_query.go b/backend/db/agentsyncjob_query.go new file mode 100644 index 00000000..7b2d5d01 --- /dev/null +++ b/backend/db/agentsyncjob_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/agentsyncjob" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/google/uuid" +) + +// AgentSyncJobQuery is the builder for querying AgentSyncJob entities. +type AgentSyncJobQuery struct { + config + ctx *QueryContext + order []agentsyncjob.OrderOption + inters []Interceptor + predicates []predicate.AgentSyncJob + 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 AgentSyncJobQuery builder. +func (_q *AgentSyncJobQuery) Where(ps ...predicate.AgentSyncJob) *AgentSyncJobQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *AgentSyncJobQuery) Limit(limit int) *AgentSyncJobQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *AgentSyncJobQuery) Offset(offset int) *AgentSyncJobQuery { + _q.ctx.Offset = &offset + return _q +} + +// 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 (_q *AgentSyncJobQuery) Unique(unique bool) *AgentSyncJobQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *AgentSyncJobQuery) Order(o ...agentsyncjob.OrderOption) *AgentSyncJobQuery { + _q.order = append(_q.order, o...) + return _q +} + +// First returns the first AgentSyncJob entity from the query. +// Returns a *NotFoundError when no AgentSyncJob was found. +func (_q *AgentSyncJobQuery) First(ctx context.Context) (*AgentSyncJob, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{agentsyncjob.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *AgentSyncJobQuery) FirstX(ctx context.Context) *AgentSyncJob { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first AgentSyncJob ID from the query. +// Returns a *NotFoundError when no AgentSyncJob ID was found. +func (_q *AgentSyncJobQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{agentsyncjob.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *AgentSyncJobQuery) FirstIDX(ctx context.Context) uuid.UUID { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single AgentSyncJob entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one AgentSyncJob entity is found. +// Returns a *NotFoundError when no AgentSyncJob entities are found. +func (_q *AgentSyncJobQuery) Only(ctx context.Context) (*AgentSyncJob, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{agentsyncjob.Label} + default: + return nil, &NotSingularError{agentsyncjob.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *AgentSyncJobQuery) OnlyX(ctx context.Context) *AgentSyncJob { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only AgentSyncJob ID in the query. +// Returns a *NotSingularError when more than one AgentSyncJob ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *AgentSyncJobQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{agentsyncjob.Label} + default: + err = &NotSingularError{agentsyncjob.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *AgentSyncJobQuery) OnlyIDX(ctx context.Context) uuid.UUID { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of AgentSyncJobs. +func (_q *AgentSyncJobQuery) All(ctx context.Context) ([]*AgentSyncJob, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*AgentSyncJob, *AgentSyncJobQuery]() + return withInterceptors[[]*AgentSyncJob](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *AgentSyncJobQuery) AllX(ctx context.Context) []*AgentSyncJob { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of AgentSyncJob IDs. +func (_q *AgentSyncJobQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(agentsyncjob.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *AgentSyncJobQuery) IDsX(ctx context.Context) []uuid.UUID { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *AgentSyncJobQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*AgentSyncJobQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *AgentSyncJobQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *AgentSyncJobQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.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 (_q *AgentSyncJobQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the AgentSyncJobQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *AgentSyncJobQuery) Clone() *AgentSyncJobQuery { + if _q == nil { + return nil + } + return &AgentSyncJobQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]agentsyncjob.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.AgentSyncJob{}, _q.predicates...), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + modifiers: append([]func(*sql.Selector){}, _q.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 { +// ResourceKind agentsyncjob.ResourceKind `json:"resource_kind,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.AgentSyncJob.Query(). +// GroupBy(agentsyncjob.FieldResourceKind). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *AgentSyncJobQuery) GroupBy(field string, fields ...string) *AgentSyncJobGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &AgentSyncJobGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = agentsyncjob.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 { +// ResourceKind agentsyncjob.ResourceKind `json:"resource_kind,omitempty"` +// } +// +// client.AgentSyncJob.Query(). +// Select(agentsyncjob.FieldResourceKind). +// Scan(ctx, &v) +func (_q *AgentSyncJobQuery) Select(fields ...string) *AgentSyncJobSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &AgentSyncJobSelect{AgentSyncJobQuery: _q} + sbuild.label = agentsyncjob.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a AgentSyncJobSelect configured with the given aggregations. +func (_q *AgentSyncJobQuery) Aggregate(fns ...AggregateFunc) *AgentSyncJobSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *AgentSyncJobQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.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, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !agentsyncjob.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *AgentSyncJobQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*AgentSyncJob, error) { + var ( + nodes = []*AgentSyncJob{} + _spec = _q.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*AgentSyncJob).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &AgentSyncJob{config: _q.config} + nodes = append(nodes, node) + return node.assignValues(columns, values) + } + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (_q *AgentSyncJobQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *AgentSyncJobQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(agentsyncjob.Table, agentsyncjob.Columns, sqlgraph.NewFieldSpec(agentsyncjob.FieldID, field.TypeUUID)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, agentsyncjob.FieldID) + for i := range fields { + if fields[i] != agentsyncjob.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *AgentSyncJobQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(agentsyncjob.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = agentsyncjob.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, m := range _q.modifiers { + m(selector) + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.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 := _q.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 (_q *AgentSyncJobQuery) ForUpdate(opts ...sql.LockOption) *AgentSyncJobQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForUpdate(opts...) + }) + return _q +} + +// 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 (_q *AgentSyncJobQuery) ForShare(opts ...sql.LockOption) *AgentSyncJobQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (_q *AgentSyncJobQuery) Modify(modifiers ...func(s *sql.Selector)) *AgentSyncJobSelect { + _q.modifiers = append(_q.modifiers, modifiers...) + return _q.Select() +} + +// AgentSyncJobGroupBy is the group-by builder for AgentSyncJob entities. +type AgentSyncJobGroupBy struct { + selector + build *AgentSyncJobQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *AgentSyncJobGroupBy) Aggregate(fns ...AggregateFunc) *AgentSyncJobGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *AgentSyncJobGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*AgentSyncJobQuery, *AgentSyncJobGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *AgentSyncJobGroupBy) sqlScan(ctx context.Context, root *AgentSyncJobQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// AgentSyncJobSelect is the builder for selecting fields of AgentSyncJob entities. +type AgentSyncJobSelect struct { + *AgentSyncJobQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *AgentSyncJobSelect) Aggregate(fns ...AggregateFunc) *AgentSyncJobSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *AgentSyncJobSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*AgentSyncJobQuery, *AgentSyncJobSelect](ctx, _s.AgentSyncJobQuery, _s, _s.inters, v) +} + +func (_s *AgentSyncJobSelect) sqlScan(ctx context.Context, root *AgentSyncJobQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.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 := _s.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 (_s *AgentSyncJobSelect) Modify(modifiers ...func(s *sql.Selector)) *AgentSyncJobSelect { + _s.modifiers = append(_s.modifiers, modifiers...) + return _s +} diff --git a/backend/db/agentsyncjob_update.go b/backend/db/agentsyncjob_update.go new file mode 100644 index 00000000..70591f35 --- /dev/null +++ b/backend/db/agentsyncjob_update.go @@ -0,0 +1,827 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/sql/sqljson" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/agentsyncjob" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/ent/types" + "github.com/google/uuid" +) + +// AgentSyncJobUpdate is the builder for updating AgentSyncJob entities. +type AgentSyncJobUpdate struct { + config + hooks []Hook + mutation *AgentSyncJobMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the AgentSyncJobUpdate builder. +func (_u *AgentSyncJobUpdate) Where(ps ...predicate.AgentSyncJob) *AgentSyncJobUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetResourceKind sets the "resource_kind" field. +func (_u *AgentSyncJobUpdate) SetResourceKind(v agentsyncjob.ResourceKind) *AgentSyncJobUpdate { + _u.mutation.SetResourceKind(v) + return _u +} + +// SetNillableResourceKind sets the "resource_kind" field if the given value is not nil. +func (_u *AgentSyncJobUpdate) SetNillableResourceKind(v *agentsyncjob.ResourceKind) *AgentSyncJobUpdate { + if v != nil { + _u.SetResourceKind(*v) + } + return _u +} + +// SetRuleID sets the "rule_id" field. +func (_u *AgentSyncJobUpdate) SetRuleID(v uuid.UUID) *AgentSyncJobUpdate { + _u.mutation.SetRuleID(v) + return _u +} + +// SetNillableRuleID sets the "rule_id" field if the given value is not nil. +func (_u *AgentSyncJobUpdate) SetNillableRuleID(v *uuid.UUID) *AgentSyncJobUpdate { + if v != nil { + _u.SetRuleID(*v) + } + return _u +} + +// ClearRuleID clears the value of the "rule_id" field. +func (_u *AgentSyncJobUpdate) ClearRuleID() *AgentSyncJobUpdate { + _u.mutation.ClearRuleID() + return _u +} + +// SetRepoID sets the "repo_id" field. +func (_u *AgentSyncJobUpdate) SetRepoID(v uuid.UUID) *AgentSyncJobUpdate { + _u.mutation.SetRepoID(v) + return _u +} + +// SetNillableRepoID sets the "repo_id" field if the given value is not nil. +func (_u *AgentSyncJobUpdate) SetNillableRepoID(v *uuid.UUID) *AgentSyncJobUpdate { + if v != nil { + _u.SetRepoID(*v) + } + return _u +} + +// ClearRepoID clears the value of the "repo_id" field. +func (_u *AgentSyncJobUpdate) ClearRepoID() *AgentSyncJobUpdate { + _u.mutation.ClearRepoID() + return _u +} + +// SetSourceType sets the "source_type" field. +func (_u *AgentSyncJobUpdate) SetSourceType(v agentsyncjob.SourceType) *AgentSyncJobUpdate { + _u.mutation.SetSourceType(v) + return _u +} + +// SetNillableSourceType sets the "source_type" field if the given value is not nil. +func (_u *AgentSyncJobUpdate) SetNillableSourceType(v *agentsyncjob.SourceType) *AgentSyncJobUpdate { + if v != nil { + _u.SetSourceType(*v) + } + return _u +} + +// SetStatus sets the "status" field. +func (_u *AgentSyncJobUpdate) SetStatus(v agentsyncjob.Status) *AgentSyncJobUpdate { + _u.mutation.SetStatus(v) + return _u +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (_u *AgentSyncJobUpdate) SetNillableStatus(v *agentsyncjob.Status) *AgentSyncJobUpdate { + if v != nil { + _u.SetStatus(*v) + } + return _u +} + +// SetTriggerType sets the "trigger_type" field. +func (_u *AgentSyncJobUpdate) SetTriggerType(v agentsyncjob.TriggerType) *AgentSyncJobUpdate { + _u.mutation.SetTriggerType(v) + return _u +} + +// SetNillableTriggerType sets the "trigger_type" field if the given value is not nil. +func (_u *AgentSyncJobUpdate) SetNillableTriggerType(v *agentsyncjob.TriggerType) *AgentSyncJobUpdate { + if v != nil { + _u.SetTriggerType(*v) + } + return _u +} + +// SetTriggeredBy sets the "triggered_by" field. +func (_u *AgentSyncJobUpdate) SetTriggeredBy(v uuid.UUID) *AgentSyncJobUpdate { + _u.mutation.SetTriggeredBy(v) + return _u +} + +// SetNillableTriggeredBy sets the "triggered_by" field if the given value is not nil. +func (_u *AgentSyncJobUpdate) SetNillableTriggeredBy(v *uuid.UUID) *AgentSyncJobUpdate { + if v != nil { + _u.SetTriggeredBy(*v) + } + return _u +} + +// ClearTriggeredBy clears the value of the "triggered_by" field. +func (_u *AgentSyncJobUpdate) ClearTriggeredBy() *AgentSyncJobUpdate { + _u.mutation.ClearTriggeredBy() + return _u +} + +// SetStartedAt sets the "started_at" field. +func (_u *AgentSyncJobUpdate) SetStartedAt(v time.Time) *AgentSyncJobUpdate { + _u.mutation.SetStartedAt(v) + return _u +} + +// SetNillableStartedAt sets the "started_at" field if the given value is not nil. +func (_u *AgentSyncJobUpdate) SetNillableStartedAt(v *time.Time) *AgentSyncJobUpdate { + if v != nil { + _u.SetStartedAt(*v) + } + return _u +} + +// ClearStartedAt clears the value of the "started_at" field. +func (_u *AgentSyncJobUpdate) ClearStartedAt() *AgentSyncJobUpdate { + _u.mutation.ClearStartedAt() + return _u +} + +// SetFinishedAt sets the "finished_at" field. +func (_u *AgentSyncJobUpdate) SetFinishedAt(v time.Time) *AgentSyncJobUpdate { + _u.mutation.SetFinishedAt(v) + return _u +} + +// SetNillableFinishedAt sets the "finished_at" field if the given value is not nil. +func (_u *AgentSyncJobUpdate) SetNillableFinishedAt(v *time.Time) *AgentSyncJobUpdate { + if v != nil { + _u.SetFinishedAt(*v) + } + return _u +} + +// ClearFinishedAt clears the value of the "finished_at" field. +func (_u *AgentSyncJobUpdate) ClearFinishedAt() *AgentSyncJobUpdate { + _u.mutation.ClearFinishedAt() + return _u +} + +// SetErrors sets the "errors" field. +func (_u *AgentSyncJobUpdate) SetErrors(v types.SyncJobErrors) *AgentSyncJobUpdate { + _u.mutation.SetErrors(v) + return _u +} + +// AppendErrors appends value to the "errors" field. +func (_u *AgentSyncJobUpdate) AppendErrors(v types.SyncJobErrors) *AgentSyncJobUpdate { + _u.mutation.AppendErrors(v) + return _u +} + +// ClearErrors clears the value of the "errors" field. +func (_u *AgentSyncJobUpdate) ClearErrors() *AgentSyncJobUpdate { + _u.mutation.ClearErrors() + return _u +} + +// SetResultSummary sets the "result_summary" field. +func (_u *AgentSyncJobUpdate) SetResultSummary(v types.SyncJobResultSummary) *AgentSyncJobUpdate { + _u.mutation.SetResultSummary(v) + return _u +} + +// SetNillableResultSummary sets the "result_summary" field if the given value is not nil. +func (_u *AgentSyncJobUpdate) SetNillableResultSummary(v *types.SyncJobResultSummary) *AgentSyncJobUpdate { + if v != nil { + _u.SetResultSummary(*v) + } + return _u +} + +// ClearResultSummary clears the value of the "result_summary" field. +func (_u *AgentSyncJobUpdate) ClearResultSummary() *AgentSyncJobUpdate { + _u.mutation.ClearResultSummary() + return _u +} + +// SetCreatedAt sets the "created_at" field. +func (_u *AgentSyncJobUpdate) SetCreatedAt(v time.Time) *AgentSyncJobUpdate { + _u.mutation.SetCreatedAt(v) + return _u +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_u *AgentSyncJobUpdate) SetNillableCreatedAt(v *time.Time) *AgentSyncJobUpdate { + if v != nil { + _u.SetCreatedAt(*v) + } + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *AgentSyncJobUpdate) SetUpdatedAt(v time.Time) *AgentSyncJobUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// Mutation returns the AgentSyncJobMutation object of the builder. +func (_u *AgentSyncJobUpdate) Mutation() *AgentSyncJobMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *AgentSyncJobUpdate) Save(ctx context.Context) (int, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *AgentSyncJobUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *AgentSyncJobUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *AgentSyncJobUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_u *AgentSyncJobUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := agentsyncjob.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *AgentSyncJobUpdate) check() error { + if v, ok := _u.mutation.ResourceKind(); ok { + if err := agentsyncjob.ResourceKindValidator(v); err != nil { + return &ValidationError{Name: "resource_kind", err: fmt.Errorf(`db: validator failed for field "AgentSyncJob.resource_kind": %w`, err)} + } + } + if v, ok := _u.mutation.SourceType(); ok { + if err := agentsyncjob.SourceTypeValidator(v); err != nil { + return &ValidationError{Name: "source_type", err: fmt.Errorf(`db: validator failed for field "AgentSyncJob.source_type": %w`, err)} + } + } + if v, ok := _u.mutation.Status(); ok { + if err := agentsyncjob.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`db: validator failed for field "AgentSyncJob.status": %w`, err)} + } + } + if v, ok := _u.mutation.TriggerType(); ok { + if err := agentsyncjob.TriggerTypeValidator(v); err != nil { + return &ValidationError{Name: "trigger_type", err: fmt.Errorf(`db: validator failed for field "AgentSyncJob.trigger_type": %w`, err)} + } + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (_u *AgentSyncJobUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *AgentSyncJobUpdate { + _u.modifiers = append(_u.modifiers, modifiers...) + return _u +} + +func (_u *AgentSyncJobUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(agentsyncjob.Table, agentsyncjob.Columns, sqlgraph.NewFieldSpec(agentsyncjob.FieldID, field.TypeUUID)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.ResourceKind(); ok { + _spec.SetField(agentsyncjob.FieldResourceKind, field.TypeEnum, value) + } + if value, ok := _u.mutation.RuleID(); ok { + _spec.SetField(agentsyncjob.FieldRuleID, field.TypeUUID, value) + } + if _u.mutation.RuleIDCleared() { + _spec.ClearField(agentsyncjob.FieldRuleID, field.TypeUUID) + } + if value, ok := _u.mutation.RepoID(); ok { + _spec.SetField(agentsyncjob.FieldRepoID, field.TypeUUID, value) + } + if _u.mutation.RepoIDCleared() { + _spec.ClearField(agentsyncjob.FieldRepoID, field.TypeUUID) + } + if value, ok := _u.mutation.SourceType(); ok { + _spec.SetField(agentsyncjob.FieldSourceType, field.TypeEnum, value) + } + if value, ok := _u.mutation.Status(); ok { + _spec.SetField(agentsyncjob.FieldStatus, field.TypeEnum, value) + } + if value, ok := _u.mutation.TriggerType(); ok { + _spec.SetField(agentsyncjob.FieldTriggerType, field.TypeEnum, value) + } + if value, ok := _u.mutation.TriggeredBy(); ok { + _spec.SetField(agentsyncjob.FieldTriggeredBy, field.TypeUUID, value) + } + if _u.mutation.TriggeredByCleared() { + _spec.ClearField(agentsyncjob.FieldTriggeredBy, field.TypeUUID) + } + if value, ok := _u.mutation.StartedAt(); ok { + _spec.SetField(agentsyncjob.FieldStartedAt, field.TypeTime, value) + } + if _u.mutation.StartedAtCleared() { + _spec.ClearField(agentsyncjob.FieldStartedAt, field.TypeTime) + } + if value, ok := _u.mutation.FinishedAt(); ok { + _spec.SetField(agentsyncjob.FieldFinishedAt, field.TypeTime, value) + } + if _u.mutation.FinishedAtCleared() { + _spec.ClearField(agentsyncjob.FieldFinishedAt, field.TypeTime) + } + if value, ok := _u.mutation.Errors(); ok { + _spec.SetField(agentsyncjob.FieldErrors, field.TypeJSON, value) + } + if value, ok := _u.mutation.AppendedErrors(); ok { + _spec.AddModifier(func(u *sql.UpdateBuilder) { + sqljson.Append(u, agentsyncjob.FieldErrors, value) + }) + } + if _u.mutation.ErrorsCleared() { + _spec.ClearField(agentsyncjob.FieldErrors, field.TypeJSON) + } + if value, ok := _u.mutation.ResultSummary(); ok { + _spec.SetField(agentsyncjob.FieldResultSummary, field.TypeJSON, value) + } + if _u.mutation.ResultSummaryCleared() { + _spec.ClearField(agentsyncjob.FieldResultSummary, field.TypeJSON) + } + if value, ok := _u.mutation.CreatedAt(); ok { + _spec.SetField(agentsyncjob.FieldCreatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(agentsyncjob.FieldUpdatedAt, field.TypeTime, value) + } + _spec.AddModifiers(_u.modifiers...) + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{agentsyncjob.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// AgentSyncJobUpdateOne is the builder for updating a single AgentSyncJob entity. +type AgentSyncJobUpdateOne struct { + config + fields []string + hooks []Hook + mutation *AgentSyncJobMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetResourceKind sets the "resource_kind" field. +func (_u *AgentSyncJobUpdateOne) SetResourceKind(v agentsyncjob.ResourceKind) *AgentSyncJobUpdateOne { + _u.mutation.SetResourceKind(v) + return _u +} + +// SetNillableResourceKind sets the "resource_kind" field if the given value is not nil. +func (_u *AgentSyncJobUpdateOne) SetNillableResourceKind(v *agentsyncjob.ResourceKind) *AgentSyncJobUpdateOne { + if v != nil { + _u.SetResourceKind(*v) + } + return _u +} + +// SetRuleID sets the "rule_id" field. +func (_u *AgentSyncJobUpdateOne) SetRuleID(v uuid.UUID) *AgentSyncJobUpdateOne { + _u.mutation.SetRuleID(v) + return _u +} + +// SetNillableRuleID sets the "rule_id" field if the given value is not nil. +func (_u *AgentSyncJobUpdateOne) SetNillableRuleID(v *uuid.UUID) *AgentSyncJobUpdateOne { + if v != nil { + _u.SetRuleID(*v) + } + return _u +} + +// ClearRuleID clears the value of the "rule_id" field. +func (_u *AgentSyncJobUpdateOne) ClearRuleID() *AgentSyncJobUpdateOne { + _u.mutation.ClearRuleID() + return _u +} + +// SetRepoID sets the "repo_id" field. +func (_u *AgentSyncJobUpdateOne) SetRepoID(v uuid.UUID) *AgentSyncJobUpdateOne { + _u.mutation.SetRepoID(v) + return _u +} + +// SetNillableRepoID sets the "repo_id" field if the given value is not nil. +func (_u *AgentSyncJobUpdateOne) SetNillableRepoID(v *uuid.UUID) *AgentSyncJobUpdateOne { + if v != nil { + _u.SetRepoID(*v) + } + return _u +} + +// ClearRepoID clears the value of the "repo_id" field. +func (_u *AgentSyncJobUpdateOne) ClearRepoID() *AgentSyncJobUpdateOne { + _u.mutation.ClearRepoID() + return _u +} + +// SetSourceType sets the "source_type" field. +func (_u *AgentSyncJobUpdateOne) SetSourceType(v agentsyncjob.SourceType) *AgentSyncJobUpdateOne { + _u.mutation.SetSourceType(v) + return _u +} + +// SetNillableSourceType sets the "source_type" field if the given value is not nil. +func (_u *AgentSyncJobUpdateOne) SetNillableSourceType(v *agentsyncjob.SourceType) *AgentSyncJobUpdateOne { + if v != nil { + _u.SetSourceType(*v) + } + return _u +} + +// SetStatus sets the "status" field. +func (_u *AgentSyncJobUpdateOne) SetStatus(v agentsyncjob.Status) *AgentSyncJobUpdateOne { + _u.mutation.SetStatus(v) + return _u +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (_u *AgentSyncJobUpdateOne) SetNillableStatus(v *agentsyncjob.Status) *AgentSyncJobUpdateOne { + if v != nil { + _u.SetStatus(*v) + } + return _u +} + +// SetTriggerType sets the "trigger_type" field. +func (_u *AgentSyncJobUpdateOne) SetTriggerType(v agentsyncjob.TriggerType) *AgentSyncJobUpdateOne { + _u.mutation.SetTriggerType(v) + return _u +} + +// SetNillableTriggerType sets the "trigger_type" field if the given value is not nil. +func (_u *AgentSyncJobUpdateOne) SetNillableTriggerType(v *agentsyncjob.TriggerType) *AgentSyncJobUpdateOne { + if v != nil { + _u.SetTriggerType(*v) + } + return _u +} + +// SetTriggeredBy sets the "triggered_by" field. +func (_u *AgentSyncJobUpdateOne) SetTriggeredBy(v uuid.UUID) *AgentSyncJobUpdateOne { + _u.mutation.SetTriggeredBy(v) + return _u +} + +// SetNillableTriggeredBy sets the "triggered_by" field if the given value is not nil. +func (_u *AgentSyncJobUpdateOne) SetNillableTriggeredBy(v *uuid.UUID) *AgentSyncJobUpdateOne { + if v != nil { + _u.SetTriggeredBy(*v) + } + return _u +} + +// ClearTriggeredBy clears the value of the "triggered_by" field. +func (_u *AgentSyncJobUpdateOne) ClearTriggeredBy() *AgentSyncJobUpdateOne { + _u.mutation.ClearTriggeredBy() + return _u +} + +// SetStartedAt sets the "started_at" field. +func (_u *AgentSyncJobUpdateOne) SetStartedAt(v time.Time) *AgentSyncJobUpdateOne { + _u.mutation.SetStartedAt(v) + return _u +} + +// SetNillableStartedAt sets the "started_at" field if the given value is not nil. +func (_u *AgentSyncJobUpdateOne) SetNillableStartedAt(v *time.Time) *AgentSyncJobUpdateOne { + if v != nil { + _u.SetStartedAt(*v) + } + return _u +} + +// ClearStartedAt clears the value of the "started_at" field. +func (_u *AgentSyncJobUpdateOne) ClearStartedAt() *AgentSyncJobUpdateOne { + _u.mutation.ClearStartedAt() + return _u +} + +// SetFinishedAt sets the "finished_at" field. +func (_u *AgentSyncJobUpdateOne) SetFinishedAt(v time.Time) *AgentSyncJobUpdateOne { + _u.mutation.SetFinishedAt(v) + return _u +} + +// SetNillableFinishedAt sets the "finished_at" field if the given value is not nil. +func (_u *AgentSyncJobUpdateOne) SetNillableFinishedAt(v *time.Time) *AgentSyncJobUpdateOne { + if v != nil { + _u.SetFinishedAt(*v) + } + return _u +} + +// ClearFinishedAt clears the value of the "finished_at" field. +func (_u *AgentSyncJobUpdateOne) ClearFinishedAt() *AgentSyncJobUpdateOne { + _u.mutation.ClearFinishedAt() + return _u +} + +// SetErrors sets the "errors" field. +func (_u *AgentSyncJobUpdateOne) SetErrors(v types.SyncJobErrors) *AgentSyncJobUpdateOne { + _u.mutation.SetErrors(v) + return _u +} + +// AppendErrors appends value to the "errors" field. +func (_u *AgentSyncJobUpdateOne) AppendErrors(v types.SyncJobErrors) *AgentSyncJobUpdateOne { + _u.mutation.AppendErrors(v) + return _u +} + +// ClearErrors clears the value of the "errors" field. +func (_u *AgentSyncJobUpdateOne) ClearErrors() *AgentSyncJobUpdateOne { + _u.mutation.ClearErrors() + return _u +} + +// SetResultSummary sets the "result_summary" field. +func (_u *AgentSyncJobUpdateOne) SetResultSummary(v types.SyncJobResultSummary) *AgentSyncJobUpdateOne { + _u.mutation.SetResultSummary(v) + return _u +} + +// SetNillableResultSummary sets the "result_summary" field if the given value is not nil. +func (_u *AgentSyncJobUpdateOne) SetNillableResultSummary(v *types.SyncJobResultSummary) *AgentSyncJobUpdateOne { + if v != nil { + _u.SetResultSummary(*v) + } + return _u +} + +// ClearResultSummary clears the value of the "result_summary" field. +func (_u *AgentSyncJobUpdateOne) ClearResultSummary() *AgentSyncJobUpdateOne { + _u.mutation.ClearResultSummary() + return _u +} + +// SetCreatedAt sets the "created_at" field. +func (_u *AgentSyncJobUpdateOne) SetCreatedAt(v time.Time) *AgentSyncJobUpdateOne { + _u.mutation.SetCreatedAt(v) + return _u +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_u *AgentSyncJobUpdateOne) SetNillableCreatedAt(v *time.Time) *AgentSyncJobUpdateOne { + if v != nil { + _u.SetCreatedAt(*v) + } + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *AgentSyncJobUpdateOne) SetUpdatedAt(v time.Time) *AgentSyncJobUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// Mutation returns the AgentSyncJobMutation object of the builder. +func (_u *AgentSyncJobUpdateOne) Mutation() *AgentSyncJobMutation { + return _u.mutation +} + +// Where appends a list predicates to the AgentSyncJobUpdate builder. +func (_u *AgentSyncJobUpdateOne) Where(ps ...predicate.AgentSyncJob) *AgentSyncJobUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *AgentSyncJobUpdateOne) Select(field string, fields ...string) *AgentSyncJobUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated AgentSyncJob entity. +func (_u *AgentSyncJobUpdateOne) Save(ctx context.Context) (*AgentSyncJob, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *AgentSyncJobUpdateOne) SaveX(ctx context.Context) *AgentSyncJob { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *AgentSyncJobUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *AgentSyncJobUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_u *AgentSyncJobUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := agentsyncjob.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *AgentSyncJobUpdateOne) check() error { + if v, ok := _u.mutation.ResourceKind(); ok { + if err := agentsyncjob.ResourceKindValidator(v); err != nil { + return &ValidationError{Name: "resource_kind", err: fmt.Errorf(`db: validator failed for field "AgentSyncJob.resource_kind": %w`, err)} + } + } + if v, ok := _u.mutation.SourceType(); ok { + if err := agentsyncjob.SourceTypeValidator(v); err != nil { + return &ValidationError{Name: "source_type", err: fmt.Errorf(`db: validator failed for field "AgentSyncJob.source_type": %w`, err)} + } + } + if v, ok := _u.mutation.Status(); ok { + if err := agentsyncjob.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`db: validator failed for field "AgentSyncJob.status": %w`, err)} + } + } + if v, ok := _u.mutation.TriggerType(); ok { + if err := agentsyncjob.TriggerTypeValidator(v); err != nil { + return &ValidationError{Name: "trigger_type", err: fmt.Errorf(`db: validator failed for field "AgentSyncJob.trigger_type": %w`, err)} + } + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (_u *AgentSyncJobUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *AgentSyncJobUpdateOne { + _u.modifiers = append(_u.modifiers, modifiers...) + return _u +} + +func (_u *AgentSyncJobUpdateOne) sqlSave(ctx context.Context) (_node *AgentSyncJob, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(agentsyncjob.Table, agentsyncjob.Columns, sqlgraph.NewFieldSpec(agentsyncjob.FieldID, field.TypeUUID)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "AgentSyncJob.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, agentsyncjob.FieldID) + for _, f := range fields { + if !agentsyncjob.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != agentsyncjob.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.ResourceKind(); ok { + _spec.SetField(agentsyncjob.FieldResourceKind, field.TypeEnum, value) + } + if value, ok := _u.mutation.RuleID(); ok { + _spec.SetField(agentsyncjob.FieldRuleID, field.TypeUUID, value) + } + if _u.mutation.RuleIDCleared() { + _spec.ClearField(agentsyncjob.FieldRuleID, field.TypeUUID) + } + if value, ok := _u.mutation.RepoID(); ok { + _spec.SetField(agentsyncjob.FieldRepoID, field.TypeUUID, value) + } + if _u.mutation.RepoIDCleared() { + _spec.ClearField(agentsyncjob.FieldRepoID, field.TypeUUID) + } + if value, ok := _u.mutation.SourceType(); ok { + _spec.SetField(agentsyncjob.FieldSourceType, field.TypeEnum, value) + } + if value, ok := _u.mutation.Status(); ok { + _spec.SetField(agentsyncjob.FieldStatus, field.TypeEnum, value) + } + if value, ok := _u.mutation.TriggerType(); ok { + _spec.SetField(agentsyncjob.FieldTriggerType, field.TypeEnum, value) + } + if value, ok := _u.mutation.TriggeredBy(); ok { + _spec.SetField(agentsyncjob.FieldTriggeredBy, field.TypeUUID, value) + } + if _u.mutation.TriggeredByCleared() { + _spec.ClearField(agentsyncjob.FieldTriggeredBy, field.TypeUUID) + } + if value, ok := _u.mutation.StartedAt(); ok { + _spec.SetField(agentsyncjob.FieldStartedAt, field.TypeTime, value) + } + if _u.mutation.StartedAtCleared() { + _spec.ClearField(agentsyncjob.FieldStartedAt, field.TypeTime) + } + if value, ok := _u.mutation.FinishedAt(); ok { + _spec.SetField(agentsyncjob.FieldFinishedAt, field.TypeTime, value) + } + if _u.mutation.FinishedAtCleared() { + _spec.ClearField(agentsyncjob.FieldFinishedAt, field.TypeTime) + } + if value, ok := _u.mutation.Errors(); ok { + _spec.SetField(agentsyncjob.FieldErrors, field.TypeJSON, value) + } + if value, ok := _u.mutation.AppendedErrors(); ok { + _spec.AddModifier(func(u *sql.UpdateBuilder) { + sqljson.Append(u, agentsyncjob.FieldErrors, value) + }) + } + if _u.mutation.ErrorsCleared() { + _spec.ClearField(agentsyncjob.FieldErrors, field.TypeJSON) + } + if value, ok := _u.mutation.ResultSummary(); ok { + _spec.SetField(agentsyncjob.FieldResultSummary, field.TypeJSON, value) + } + if _u.mutation.ResultSummaryCleared() { + _spec.ClearField(agentsyncjob.FieldResultSummary, field.TypeJSON) + } + if value, ok := _u.mutation.CreatedAt(); ok { + _spec.SetField(agentsyncjob.FieldCreatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(agentsyncjob.FieldUpdatedAt, field.TypeTime, value) + } + _spec.AddModifiers(_u.modifiers...) + _node = &AgentSyncJob{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{agentsyncjob.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/backend/db/client.go b/backend/db/client.go index eaa61680..6d61c154 100644 --- a/backend/db/client.go +++ b/backend/db/client.go @@ -16,6 +16,15 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/chaitin/MonkeyCode/backend/db/agentplugin" + "github.com/chaitin/MonkeyCode/backend/db/agentpluginrepo" + "github.com/chaitin/MonkeyCode/backend/db/agentpluginversion" + "github.com/chaitin/MonkeyCode/backend/db/agentrule" + "github.com/chaitin/MonkeyCode/backend/db/agentruleversion" + "github.com/chaitin/MonkeyCode/backend/db/agentskill" + "github.com/chaitin/MonkeyCode/backend/db/agentskillrepo" + "github.com/chaitin/MonkeyCode/backend/db/agentskillversion" + "github.com/chaitin/MonkeyCode/backend/db/agentsyncjob" "github.com/chaitin/MonkeyCode/backend/db/audit" "github.com/chaitin/MonkeyCode/backend/db/gitbot" "github.com/chaitin/MonkeyCode/backend/db/gitbottask" @@ -65,6 +74,24 @@ type Client struct { config // Schema is the client for creating, migrating and dropping schema. Schema *migrate.Schema + // AgentPlugin is the client for interacting with the AgentPlugin builders. + AgentPlugin *AgentPluginClient + // AgentPluginRepo is the client for interacting with the AgentPluginRepo builders. + AgentPluginRepo *AgentPluginRepoClient + // AgentPluginVersion is the client for interacting with the AgentPluginVersion builders. + AgentPluginVersion *AgentPluginVersionClient + // AgentRule is the client for interacting with the AgentRule builders. + AgentRule *AgentRuleClient + // AgentRuleVersion is the client for interacting with the AgentRuleVersion builders. + AgentRuleVersion *AgentRuleVersionClient + // AgentSkill is the client for interacting with the AgentSkill builders. + AgentSkill *AgentSkillClient + // AgentSkillRepo is the client for interacting with the AgentSkillRepo builders. + AgentSkillRepo *AgentSkillRepoClient + // AgentSkillVersion is the client for interacting with the AgentSkillVersion builders. + AgentSkillVersion *AgentSkillVersionClient + // AgentSyncJob is the client for interacting with the AgentSyncJob builders. + AgentSyncJob *AgentSyncJobClient // Audit is the client for interacting with the Audit builders. Audit *AuditClient // GitBot is the client for interacting with the GitBot builders. @@ -156,6 +183,15 @@ func NewClient(opts ...Option) *Client { func (c *Client) init() { c.Schema = migrate.NewSchema(c.driver) + c.AgentPlugin = NewAgentPluginClient(c.config) + c.AgentPluginRepo = NewAgentPluginRepoClient(c.config) + c.AgentPluginVersion = NewAgentPluginVersionClient(c.config) + c.AgentRule = NewAgentRuleClient(c.config) + c.AgentRuleVersion = NewAgentRuleVersionClient(c.config) + c.AgentSkill = NewAgentSkillClient(c.config) + c.AgentSkillRepo = NewAgentSkillRepoClient(c.config) + c.AgentSkillVersion = NewAgentSkillVersionClient(c.config) + c.AgentSyncJob = NewAgentSyncJobClient(c.config) c.Audit = NewAuditClient(c.config) c.GitBot = NewGitBotClient(c.config) c.GitBotTask = NewGitBotTaskClient(c.config) @@ -288,6 +324,15 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { return &Tx{ ctx: ctx, config: cfg, + AgentPlugin: NewAgentPluginClient(cfg), + AgentPluginRepo: NewAgentPluginRepoClient(cfg), + AgentPluginVersion: NewAgentPluginVersionClient(cfg), + AgentRule: NewAgentRuleClient(cfg), + AgentRuleVersion: NewAgentRuleVersionClient(cfg), + AgentSkill: NewAgentSkillClient(cfg), + AgentSkillRepo: NewAgentSkillRepoClient(cfg), + AgentSkillVersion: NewAgentSkillVersionClient(cfg), + AgentSyncJob: NewAgentSyncJobClient(cfg), Audit: NewAuditClient(cfg), GitBot: NewGitBotClient(cfg), GitBotTask: NewGitBotTaskClient(cfg), @@ -347,6 +392,15 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) return &Tx{ ctx: ctx, config: cfg, + AgentPlugin: NewAgentPluginClient(cfg), + AgentPluginRepo: NewAgentPluginRepoClient(cfg), + AgentPluginVersion: NewAgentPluginVersionClient(cfg), + AgentRule: NewAgentRuleClient(cfg), + AgentRuleVersion: NewAgentRuleVersionClient(cfg), + AgentSkill: NewAgentSkillClient(cfg), + AgentSkillRepo: NewAgentSkillRepoClient(cfg), + AgentSkillVersion: NewAgentSkillVersionClient(cfg), + AgentSyncJob: NewAgentSyncJobClient(cfg), Audit: NewAuditClient(cfg), GitBot: NewGitBotClient(cfg), GitBotTask: NewGitBotTaskClient(cfg), @@ -393,7 +447,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) // Debug returns a new debug-client. It's used to get verbose logging on specific operations. // // client.Debug(). -// Audit. +// AgentPlugin. // Query(). // Count(ctx) func (c *Client) Debug() *Client { @@ -416,9 +470,11 @@ func (c *Client) Close() error { // In order to add hooks to a specific client, call: `client.Node.Use(...)`. func (c *Client) Use(hooks ...Hook) { for _, n := range []interface{ Use(...Hook) }{ - c.Audit, c.GitBot, c.GitBotTask, c.GitBotUser, c.GitIdentity, c.GitTask, c.Host, - c.Image, c.MCPTool, c.MCPUpstream, c.MCPUserToolSetting, c.Model, - c.ModelApiKey, c.ModelPricing, c.NotifyChannel, c.NotifySendLog, + c.AgentPlugin, c.AgentPluginRepo, c.AgentPluginVersion, c.AgentRule, + c.AgentRuleVersion, c.AgentSkill, c.AgentSkillRepo, c.AgentSkillVersion, + c.AgentSyncJob, c.Audit, c.GitBot, c.GitBotTask, c.GitBotUser, c.GitIdentity, + c.GitTask, c.Host, c.Image, c.MCPTool, c.MCPUpstream, c.MCPUserToolSetting, + c.Model, c.ModelApiKey, c.ModelPricing, c.NotifyChannel, c.NotifySendLog, c.NotifySubscription, c.Project, c.ProjectCollaborator, c.ProjectGitBot, c.ProjectIssue, c.ProjectIssueComment, c.ProjectTask, c.Task, c.TaskModelSwitch, c.TaskUsageStat, c.TaskVirtualMachine, c.Team, c.TeamGroup, @@ -434,9 +490,11 @@ func (c *Client) Use(hooks ...Hook) { // In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`. func (c *Client) Intercept(interceptors ...Interceptor) { for _, n := range []interface{ Intercept(...Interceptor) }{ - c.Audit, c.GitBot, c.GitBotTask, c.GitBotUser, c.GitIdentity, c.GitTask, c.Host, - c.Image, c.MCPTool, c.MCPUpstream, c.MCPUserToolSetting, c.Model, - c.ModelApiKey, c.ModelPricing, c.NotifyChannel, c.NotifySendLog, + c.AgentPlugin, c.AgentPluginRepo, c.AgentPluginVersion, c.AgentRule, + c.AgentRuleVersion, c.AgentSkill, c.AgentSkillRepo, c.AgentSkillVersion, + c.AgentSyncJob, c.Audit, c.GitBot, c.GitBotTask, c.GitBotUser, c.GitIdentity, + c.GitTask, c.Host, c.Image, c.MCPTool, c.MCPUpstream, c.MCPUserToolSetting, + c.Model, c.ModelApiKey, c.ModelPricing, c.NotifyChannel, c.NotifySendLog, c.NotifySubscription, c.Project, c.ProjectCollaborator, c.ProjectGitBot, c.ProjectIssue, c.ProjectIssueComment, c.ProjectTask, c.Task, c.TaskModelSwitch, c.TaskUsageStat, c.TaskVirtualMachine, c.Team, c.TeamGroup, @@ -451,6 +509,24 @@ func (c *Client) Intercept(interceptors ...Interceptor) { // Mutate implements the ent.Mutator interface. func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { switch m := m.(type) { + case *AgentPluginMutation: + return c.AgentPlugin.mutate(ctx, m) + case *AgentPluginRepoMutation: + return c.AgentPluginRepo.mutate(ctx, m) + case *AgentPluginVersionMutation: + return c.AgentPluginVersion.mutate(ctx, m) + case *AgentRuleMutation: + return c.AgentRule.mutate(ctx, m) + case *AgentRuleVersionMutation: + return c.AgentRuleVersion.mutate(ctx, m) + case *AgentSkillMutation: + return c.AgentSkill.mutate(ctx, m) + case *AgentSkillRepoMutation: + return c.AgentSkillRepo.mutate(ctx, m) + case *AgentSkillVersionMutation: + return c.AgentSkillVersion.mutate(ctx, m) + case *AgentSyncJobMutation: + return c.AgentSyncJob.mutate(ctx, m) case *AuditMutation: return c.Audit.mutate(ctx, m) case *GitBotMutation: @@ -536,6 +612,1363 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { } } +// AgentPluginClient is a client for the AgentPlugin schema. +type AgentPluginClient struct { + config +} + +// NewAgentPluginClient returns a client for the AgentPlugin from the given config. +func NewAgentPluginClient(c config) *AgentPluginClient { + return &AgentPluginClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `agentplugin.Hooks(f(g(h())))`. +func (c *AgentPluginClient) Use(hooks ...Hook) { + c.hooks.AgentPlugin = append(c.hooks.AgentPlugin, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `agentplugin.Intercept(f(g(h())))`. +func (c *AgentPluginClient) Intercept(interceptors ...Interceptor) { + c.inters.AgentPlugin = append(c.inters.AgentPlugin, interceptors...) +} + +// Create returns a builder for creating a AgentPlugin entity. +func (c *AgentPluginClient) Create() *AgentPluginCreate { + mutation := newAgentPluginMutation(c.config, OpCreate) + return &AgentPluginCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of AgentPlugin entities. +func (c *AgentPluginClient) CreateBulk(builders ...*AgentPluginCreate) *AgentPluginCreateBulk { + return &AgentPluginCreateBulk{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 *AgentPluginClient) MapCreateBulk(slice any, setFunc func(*AgentPluginCreate, int)) *AgentPluginCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &AgentPluginCreateBulk{err: fmt.Errorf("calling to AgentPluginClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*AgentPluginCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &AgentPluginCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for AgentPlugin. +func (c *AgentPluginClient) Update() *AgentPluginUpdate { + mutation := newAgentPluginMutation(c.config, OpUpdate) + return &AgentPluginUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *AgentPluginClient) UpdateOne(_m *AgentPlugin) *AgentPluginUpdateOne { + mutation := newAgentPluginMutation(c.config, OpUpdateOne, withAgentPlugin(_m)) + return &AgentPluginUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *AgentPluginClient) UpdateOneID(id uuid.UUID) *AgentPluginUpdateOne { + mutation := newAgentPluginMutation(c.config, OpUpdateOne, withAgentPluginID(id)) + return &AgentPluginUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for AgentPlugin. +func (c *AgentPluginClient) Delete() *AgentPluginDelete { + mutation := newAgentPluginMutation(c.config, OpDelete) + return &AgentPluginDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *AgentPluginClient) DeleteOne(_m *AgentPlugin) *AgentPluginDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *AgentPluginClient) DeleteOneID(id uuid.UUID) *AgentPluginDeleteOne { + builder := c.Delete().Where(agentplugin.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &AgentPluginDeleteOne{builder} +} + +// Query returns a query builder for AgentPlugin. +func (c *AgentPluginClient) Query() *AgentPluginQuery { + return &AgentPluginQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeAgentPlugin}, + inters: c.Interceptors(), + } +} + +// Get returns a AgentPlugin entity by its id. +func (c *AgentPluginClient) Get(ctx context.Context, id uuid.UUID) (*AgentPlugin, error) { + return c.Query().Where(agentplugin.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *AgentPluginClient) GetX(ctx context.Context, id uuid.UUID) *AgentPlugin { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryRepo queries the repo edge of a AgentPlugin. +func (c *AgentPluginClient) QueryRepo(_m *AgentPlugin) *AgentPluginRepoQuery { + query := (&AgentPluginRepoClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(agentplugin.Table, agentplugin.FieldID, id), + sqlgraph.To(agentpluginrepo.Table, agentpluginrepo.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, agentplugin.RepoTable, agentplugin.RepoColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryVersions queries the versions edge of a AgentPlugin. +func (c *AgentPluginClient) QueryVersions(_m *AgentPlugin) *AgentPluginVersionQuery { + query := (&AgentPluginVersionClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(agentplugin.Table, agentplugin.FieldID, id), + sqlgraph.To(agentpluginversion.Table, agentpluginversion.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, agentplugin.VersionsTable, agentplugin.VersionsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *AgentPluginClient) Hooks() []Hook { + return c.hooks.AgentPlugin +} + +// Interceptors returns the client interceptors. +func (c *AgentPluginClient) Interceptors() []Interceptor { + return c.inters.AgentPlugin +} + +func (c *AgentPluginClient) mutate(ctx context.Context, m *AgentPluginMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&AgentPluginCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&AgentPluginUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&AgentPluginUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&AgentPluginDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown AgentPlugin mutation op: %q", m.Op()) + } +} + +// AgentPluginRepoClient is a client for the AgentPluginRepo schema. +type AgentPluginRepoClient struct { + config +} + +// NewAgentPluginRepoClient returns a client for the AgentPluginRepo from the given config. +func NewAgentPluginRepoClient(c config) *AgentPluginRepoClient { + return &AgentPluginRepoClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `agentpluginrepo.Hooks(f(g(h())))`. +func (c *AgentPluginRepoClient) Use(hooks ...Hook) { + c.hooks.AgentPluginRepo = append(c.hooks.AgentPluginRepo, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `agentpluginrepo.Intercept(f(g(h())))`. +func (c *AgentPluginRepoClient) Intercept(interceptors ...Interceptor) { + c.inters.AgentPluginRepo = append(c.inters.AgentPluginRepo, interceptors...) +} + +// Create returns a builder for creating a AgentPluginRepo entity. +func (c *AgentPluginRepoClient) Create() *AgentPluginRepoCreate { + mutation := newAgentPluginRepoMutation(c.config, OpCreate) + return &AgentPluginRepoCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of AgentPluginRepo entities. +func (c *AgentPluginRepoClient) CreateBulk(builders ...*AgentPluginRepoCreate) *AgentPluginRepoCreateBulk { + return &AgentPluginRepoCreateBulk{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 *AgentPluginRepoClient) MapCreateBulk(slice any, setFunc func(*AgentPluginRepoCreate, int)) *AgentPluginRepoCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &AgentPluginRepoCreateBulk{err: fmt.Errorf("calling to AgentPluginRepoClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*AgentPluginRepoCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &AgentPluginRepoCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for AgentPluginRepo. +func (c *AgentPluginRepoClient) Update() *AgentPluginRepoUpdate { + mutation := newAgentPluginRepoMutation(c.config, OpUpdate) + return &AgentPluginRepoUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *AgentPluginRepoClient) UpdateOne(_m *AgentPluginRepo) *AgentPluginRepoUpdateOne { + mutation := newAgentPluginRepoMutation(c.config, OpUpdateOne, withAgentPluginRepo(_m)) + return &AgentPluginRepoUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *AgentPluginRepoClient) UpdateOneID(id uuid.UUID) *AgentPluginRepoUpdateOne { + mutation := newAgentPluginRepoMutation(c.config, OpUpdateOne, withAgentPluginRepoID(id)) + return &AgentPluginRepoUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for AgentPluginRepo. +func (c *AgentPluginRepoClient) Delete() *AgentPluginRepoDelete { + mutation := newAgentPluginRepoMutation(c.config, OpDelete) + return &AgentPluginRepoDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *AgentPluginRepoClient) DeleteOne(_m *AgentPluginRepo) *AgentPluginRepoDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *AgentPluginRepoClient) DeleteOneID(id uuid.UUID) *AgentPluginRepoDeleteOne { + builder := c.Delete().Where(agentpluginrepo.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &AgentPluginRepoDeleteOne{builder} +} + +// Query returns a query builder for AgentPluginRepo. +func (c *AgentPluginRepoClient) Query() *AgentPluginRepoQuery { + return &AgentPluginRepoQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeAgentPluginRepo}, + inters: c.Interceptors(), + } +} + +// Get returns a AgentPluginRepo entity by its id. +func (c *AgentPluginRepoClient) Get(ctx context.Context, id uuid.UUID) (*AgentPluginRepo, error) { + return c.Query().Where(agentpluginrepo.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *AgentPluginRepoClient) GetX(ctx context.Context, id uuid.UUID) *AgentPluginRepo { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryPlugins queries the plugins edge of a AgentPluginRepo. +func (c *AgentPluginRepoClient) QueryPlugins(_m *AgentPluginRepo) *AgentPluginQuery { + query := (&AgentPluginClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(agentpluginrepo.Table, agentpluginrepo.FieldID, id), + sqlgraph.To(agentplugin.Table, agentplugin.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, agentpluginrepo.PluginsTable, agentpluginrepo.PluginsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *AgentPluginRepoClient) Hooks() []Hook { + return c.hooks.AgentPluginRepo +} + +// Interceptors returns the client interceptors. +func (c *AgentPluginRepoClient) Interceptors() []Interceptor { + return c.inters.AgentPluginRepo +} + +func (c *AgentPluginRepoClient) mutate(ctx context.Context, m *AgentPluginRepoMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&AgentPluginRepoCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&AgentPluginRepoUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&AgentPluginRepoUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&AgentPluginRepoDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown AgentPluginRepo mutation op: %q", m.Op()) + } +} + +// AgentPluginVersionClient is a client for the AgentPluginVersion schema. +type AgentPluginVersionClient struct { + config +} + +// NewAgentPluginVersionClient returns a client for the AgentPluginVersion from the given config. +func NewAgentPluginVersionClient(c config) *AgentPluginVersionClient { + return &AgentPluginVersionClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `agentpluginversion.Hooks(f(g(h())))`. +func (c *AgentPluginVersionClient) Use(hooks ...Hook) { + c.hooks.AgentPluginVersion = append(c.hooks.AgentPluginVersion, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `agentpluginversion.Intercept(f(g(h())))`. +func (c *AgentPluginVersionClient) Intercept(interceptors ...Interceptor) { + c.inters.AgentPluginVersion = append(c.inters.AgentPluginVersion, interceptors...) +} + +// Create returns a builder for creating a AgentPluginVersion entity. +func (c *AgentPluginVersionClient) Create() *AgentPluginVersionCreate { + mutation := newAgentPluginVersionMutation(c.config, OpCreate) + return &AgentPluginVersionCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of AgentPluginVersion entities. +func (c *AgentPluginVersionClient) CreateBulk(builders ...*AgentPluginVersionCreate) *AgentPluginVersionCreateBulk { + return &AgentPluginVersionCreateBulk{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 *AgentPluginVersionClient) MapCreateBulk(slice any, setFunc func(*AgentPluginVersionCreate, int)) *AgentPluginVersionCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &AgentPluginVersionCreateBulk{err: fmt.Errorf("calling to AgentPluginVersionClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*AgentPluginVersionCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &AgentPluginVersionCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for AgentPluginVersion. +func (c *AgentPluginVersionClient) Update() *AgentPluginVersionUpdate { + mutation := newAgentPluginVersionMutation(c.config, OpUpdate) + return &AgentPluginVersionUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *AgentPluginVersionClient) UpdateOne(_m *AgentPluginVersion) *AgentPluginVersionUpdateOne { + mutation := newAgentPluginVersionMutation(c.config, OpUpdateOne, withAgentPluginVersion(_m)) + return &AgentPluginVersionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *AgentPluginVersionClient) UpdateOneID(id uuid.UUID) *AgentPluginVersionUpdateOne { + mutation := newAgentPluginVersionMutation(c.config, OpUpdateOne, withAgentPluginVersionID(id)) + return &AgentPluginVersionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for AgentPluginVersion. +func (c *AgentPluginVersionClient) Delete() *AgentPluginVersionDelete { + mutation := newAgentPluginVersionMutation(c.config, OpDelete) + return &AgentPluginVersionDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *AgentPluginVersionClient) DeleteOne(_m *AgentPluginVersion) *AgentPluginVersionDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *AgentPluginVersionClient) DeleteOneID(id uuid.UUID) *AgentPluginVersionDeleteOne { + builder := c.Delete().Where(agentpluginversion.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &AgentPluginVersionDeleteOne{builder} +} + +// Query returns a query builder for AgentPluginVersion. +func (c *AgentPluginVersionClient) Query() *AgentPluginVersionQuery { + return &AgentPluginVersionQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeAgentPluginVersion}, + inters: c.Interceptors(), + } +} + +// Get returns a AgentPluginVersion entity by its id. +func (c *AgentPluginVersionClient) Get(ctx context.Context, id uuid.UUID) (*AgentPluginVersion, error) { + return c.Query().Where(agentpluginversion.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *AgentPluginVersionClient) GetX(ctx context.Context, id uuid.UUID) *AgentPluginVersion { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryPlugin queries the plugin edge of a AgentPluginVersion. +func (c *AgentPluginVersionClient) QueryPlugin(_m *AgentPluginVersion) *AgentPluginQuery { + query := (&AgentPluginClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(agentpluginversion.Table, agentpluginversion.FieldID, id), + sqlgraph.To(agentplugin.Table, agentplugin.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, agentpluginversion.PluginTable, agentpluginversion.PluginColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *AgentPluginVersionClient) Hooks() []Hook { + return c.hooks.AgentPluginVersion +} + +// Interceptors returns the client interceptors. +func (c *AgentPluginVersionClient) Interceptors() []Interceptor { + return c.inters.AgentPluginVersion +} + +func (c *AgentPluginVersionClient) mutate(ctx context.Context, m *AgentPluginVersionMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&AgentPluginVersionCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&AgentPluginVersionUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&AgentPluginVersionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&AgentPluginVersionDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown AgentPluginVersion mutation op: %q", m.Op()) + } +} + +// AgentRuleClient is a client for the AgentRule schema. +type AgentRuleClient struct { + config +} + +// NewAgentRuleClient returns a client for the AgentRule from the given config. +func NewAgentRuleClient(c config) *AgentRuleClient { + return &AgentRuleClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `agentrule.Hooks(f(g(h())))`. +func (c *AgentRuleClient) Use(hooks ...Hook) { + c.hooks.AgentRule = append(c.hooks.AgentRule, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `agentrule.Intercept(f(g(h())))`. +func (c *AgentRuleClient) Intercept(interceptors ...Interceptor) { + c.inters.AgentRule = append(c.inters.AgentRule, interceptors...) +} + +// Create returns a builder for creating a AgentRule entity. +func (c *AgentRuleClient) Create() *AgentRuleCreate { + mutation := newAgentRuleMutation(c.config, OpCreate) + return &AgentRuleCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of AgentRule entities. +func (c *AgentRuleClient) CreateBulk(builders ...*AgentRuleCreate) *AgentRuleCreateBulk { + return &AgentRuleCreateBulk{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 *AgentRuleClient) MapCreateBulk(slice any, setFunc func(*AgentRuleCreate, int)) *AgentRuleCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &AgentRuleCreateBulk{err: fmt.Errorf("calling to AgentRuleClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*AgentRuleCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &AgentRuleCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for AgentRule. +func (c *AgentRuleClient) Update() *AgentRuleUpdate { + mutation := newAgentRuleMutation(c.config, OpUpdate) + return &AgentRuleUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *AgentRuleClient) UpdateOne(_m *AgentRule) *AgentRuleUpdateOne { + mutation := newAgentRuleMutation(c.config, OpUpdateOne, withAgentRule(_m)) + return &AgentRuleUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *AgentRuleClient) UpdateOneID(id uuid.UUID) *AgentRuleUpdateOne { + mutation := newAgentRuleMutation(c.config, OpUpdateOne, withAgentRuleID(id)) + return &AgentRuleUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for AgentRule. +func (c *AgentRuleClient) Delete() *AgentRuleDelete { + mutation := newAgentRuleMutation(c.config, OpDelete) + return &AgentRuleDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *AgentRuleClient) DeleteOne(_m *AgentRule) *AgentRuleDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *AgentRuleClient) DeleteOneID(id uuid.UUID) *AgentRuleDeleteOne { + builder := c.Delete().Where(agentrule.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &AgentRuleDeleteOne{builder} +} + +// Query returns a query builder for AgentRule. +func (c *AgentRuleClient) Query() *AgentRuleQuery { + return &AgentRuleQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeAgentRule}, + inters: c.Interceptors(), + } +} + +// Get returns a AgentRule entity by its id. +func (c *AgentRuleClient) Get(ctx context.Context, id uuid.UUID) (*AgentRule, error) { + return c.Query().Where(agentrule.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *AgentRuleClient) GetX(ctx context.Context, id uuid.UUID) *AgentRule { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryVersions queries the versions edge of a AgentRule. +func (c *AgentRuleClient) QueryVersions(_m *AgentRule) *AgentRuleVersionQuery { + query := (&AgentRuleVersionClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(agentrule.Table, agentrule.FieldID, id), + sqlgraph.To(agentruleversion.Table, agentruleversion.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, agentrule.VersionsTable, agentrule.VersionsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *AgentRuleClient) Hooks() []Hook { + return c.hooks.AgentRule +} + +// Interceptors returns the client interceptors. +func (c *AgentRuleClient) Interceptors() []Interceptor { + return c.inters.AgentRule +} + +func (c *AgentRuleClient) mutate(ctx context.Context, m *AgentRuleMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&AgentRuleCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&AgentRuleUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&AgentRuleUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&AgentRuleDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown AgentRule mutation op: %q", m.Op()) + } +} + +// AgentRuleVersionClient is a client for the AgentRuleVersion schema. +type AgentRuleVersionClient struct { + config +} + +// NewAgentRuleVersionClient returns a client for the AgentRuleVersion from the given config. +func NewAgentRuleVersionClient(c config) *AgentRuleVersionClient { + return &AgentRuleVersionClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `agentruleversion.Hooks(f(g(h())))`. +func (c *AgentRuleVersionClient) Use(hooks ...Hook) { + c.hooks.AgentRuleVersion = append(c.hooks.AgentRuleVersion, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `agentruleversion.Intercept(f(g(h())))`. +func (c *AgentRuleVersionClient) Intercept(interceptors ...Interceptor) { + c.inters.AgentRuleVersion = append(c.inters.AgentRuleVersion, interceptors...) +} + +// Create returns a builder for creating a AgentRuleVersion entity. +func (c *AgentRuleVersionClient) Create() *AgentRuleVersionCreate { + mutation := newAgentRuleVersionMutation(c.config, OpCreate) + return &AgentRuleVersionCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of AgentRuleVersion entities. +func (c *AgentRuleVersionClient) CreateBulk(builders ...*AgentRuleVersionCreate) *AgentRuleVersionCreateBulk { + return &AgentRuleVersionCreateBulk{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 *AgentRuleVersionClient) MapCreateBulk(slice any, setFunc func(*AgentRuleVersionCreate, int)) *AgentRuleVersionCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &AgentRuleVersionCreateBulk{err: fmt.Errorf("calling to AgentRuleVersionClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*AgentRuleVersionCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &AgentRuleVersionCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for AgentRuleVersion. +func (c *AgentRuleVersionClient) Update() *AgentRuleVersionUpdate { + mutation := newAgentRuleVersionMutation(c.config, OpUpdate) + return &AgentRuleVersionUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *AgentRuleVersionClient) UpdateOne(_m *AgentRuleVersion) *AgentRuleVersionUpdateOne { + mutation := newAgentRuleVersionMutation(c.config, OpUpdateOne, withAgentRuleVersion(_m)) + return &AgentRuleVersionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *AgentRuleVersionClient) UpdateOneID(id uuid.UUID) *AgentRuleVersionUpdateOne { + mutation := newAgentRuleVersionMutation(c.config, OpUpdateOne, withAgentRuleVersionID(id)) + return &AgentRuleVersionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for AgentRuleVersion. +func (c *AgentRuleVersionClient) Delete() *AgentRuleVersionDelete { + mutation := newAgentRuleVersionMutation(c.config, OpDelete) + return &AgentRuleVersionDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *AgentRuleVersionClient) DeleteOne(_m *AgentRuleVersion) *AgentRuleVersionDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *AgentRuleVersionClient) DeleteOneID(id uuid.UUID) *AgentRuleVersionDeleteOne { + builder := c.Delete().Where(agentruleversion.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &AgentRuleVersionDeleteOne{builder} +} + +// Query returns a query builder for AgentRuleVersion. +func (c *AgentRuleVersionClient) Query() *AgentRuleVersionQuery { + return &AgentRuleVersionQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeAgentRuleVersion}, + inters: c.Interceptors(), + } +} + +// Get returns a AgentRuleVersion entity by its id. +func (c *AgentRuleVersionClient) Get(ctx context.Context, id uuid.UUID) (*AgentRuleVersion, error) { + return c.Query().Where(agentruleversion.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *AgentRuleVersionClient) GetX(ctx context.Context, id uuid.UUID) *AgentRuleVersion { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryRule queries the rule edge of a AgentRuleVersion. +func (c *AgentRuleVersionClient) QueryRule(_m *AgentRuleVersion) *AgentRuleQuery { + query := (&AgentRuleClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(agentruleversion.Table, agentruleversion.FieldID, id), + sqlgraph.To(agentrule.Table, agentrule.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, agentruleversion.RuleTable, agentruleversion.RuleColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *AgentRuleVersionClient) Hooks() []Hook { + return c.hooks.AgentRuleVersion +} + +// Interceptors returns the client interceptors. +func (c *AgentRuleVersionClient) Interceptors() []Interceptor { + return c.inters.AgentRuleVersion +} + +func (c *AgentRuleVersionClient) mutate(ctx context.Context, m *AgentRuleVersionMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&AgentRuleVersionCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&AgentRuleVersionUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&AgentRuleVersionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&AgentRuleVersionDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown AgentRuleVersion mutation op: %q", m.Op()) + } +} + +// AgentSkillClient is a client for the AgentSkill schema. +type AgentSkillClient struct { + config +} + +// NewAgentSkillClient returns a client for the AgentSkill from the given config. +func NewAgentSkillClient(c config) *AgentSkillClient { + return &AgentSkillClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `agentskill.Hooks(f(g(h())))`. +func (c *AgentSkillClient) Use(hooks ...Hook) { + c.hooks.AgentSkill = append(c.hooks.AgentSkill, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `agentskill.Intercept(f(g(h())))`. +func (c *AgentSkillClient) Intercept(interceptors ...Interceptor) { + c.inters.AgentSkill = append(c.inters.AgentSkill, interceptors...) +} + +// Create returns a builder for creating a AgentSkill entity. +func (c *AgentSkillClient) Create() *AgentSkillCreate { + mutation := newAgentSkillMutation(c.config, OpCreate) + return &AgentSkillCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of AgentSkill entities. +func (c *AgentSkillClient) CreateBulk(builders ...*AgentSkillCreate) *AgentSkillCreateBulk { + return &AgentSkillCreateBulk{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 *AgentSkillClient) MapCreateBulk(slice any, setFunc func(*AgentSkillCreate, int)) *AgentSkillCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &AgentSkillCreateBulk{err: fmt.Errorf("calling to AgentSkillClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*AgentSkillCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &AgentSkillCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for AgentSkill. +func (c *AgentSkillClient) Update() *AgentSkillUpdate { + mutation := newAgentSkillMutation(c.config, OpUpdate) + return &AgentSkillUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *AgentSkillClient) UpdateOne(_m *AgentSkill) *AgentSkillUpdateOne { + mutation := newAgentSkillMutation(c.config, OpUpdateOne, withAgentSkill(_m)) + return &AgentSkillUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *AgentSkillClient) UpdateOneID(id uuid.UUID) *AgentSkillUpdateOne { + mutation := newAgentSkillMutation(c.config, OpUpdateOne, withAgentSkillID(id)) + return &AgentSkillUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for AgentSkill. +func (c *AgentSkillClient) Delete() *AgentSkillDelete { + mutation := newAgentSkillMutation(c.config, OpDelete) + return &AgentSkillDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *AgentSkillClient) DeleteOne(_m *AgentSkill) *AgentSkillDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *AgentSkillClient) DeleteOneID(id uuid.UUID) *AgentSkillDeleteOne { + builder := c.Delete().Where(agentskill.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &AgentSkillDeleteOne{builder} +} + +// Query returns a query builder for AgentSkill. +func (c *AgentSkillClient) Query() *AgentSkillQuery { + return &AgentSkillQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeAgentSkill}, + inters: c.Interceptors(), + } +} + +// Get returns a AgentSkill entity by its id. +func (c *AgentSkillClient) Get(ctx context.Context, id uuid.UUID) (*AgentSkill, error) { + return c.Query().Where(agentskill.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *AgentSkillClient) GetX(ctx context.Context, id uuid.UUID) *AgentSkill { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryRepo queries the repo edge of a AgentSkill. +func (c *AgentSkillClient) QueryRepo(_m *AgentSkill) *AgentSkillRepoQuery { + query := (&AgentSkillRepoClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(agentskill.Table, agentskill.FieldID, id), + sqlgraph.To(agentskillrepo.Table, agentskillrepo.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, agentskill.RepoTable, agentskill.RepoColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryVersions queries the versions edge of a AgentSkill. +func (c *AgentSkillClient) QueryVersions(_m *AgentSkill) *AgentSkillVersionQuery { + query := (&AgentSkillVersionClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(agentskill.Table, agentskill.FieldID, id), + sqlgraph.To(agentskillversion.Table, agentskillversion.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, agentskill.VersionsTable, agentskill.VersionsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *AgentSkillClient) Hooks() []Hook { + return c.hooks.AgentSkill +} + +// Interceptors returns the client interceptors. +func (c *AgentSkillClient) Interceptors() []Interceptor { + return c.inters.AgentSkill +} + +func (c *AgentSkillClient) mutate(ctx context.Context, m *AgentSkillMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&AgentSkillCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&AgentSkillUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&AgentSkillUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&AgentSkillDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown AgentSkill mutation op: %q", m.Op()) + } +} + +// AgentSkillRepoClient is a client for the AgentSkillRepo schema. +type AgentSkillRepoClient struct { + config +} + +// NewAgentSkillRepoClient returns a client for the AgentSkillRepo from the given config. +func NewAgentSkillRepoClient(c config) *AgentSkillRepoClient { + return &AgentSkillRepoClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `agentskillrepo.Hooks(f(g(h())))`. +func (c *AgentSkillRepoClient) Use(hooks ...Hook) { + c.hooks.AgentSkillRepo = append(c.hooks.AgentSkillRepo, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `agentskillrepo.Intercept(f(g(h())))`. +func (c *AgentSkillRepoClient) Intercept(interceptors ...Interceptor) { + c.inters.AgentSkillRepo = append(c.inters.AgentSkillRepo, interceptors...) +} + +// Create returns a builder for creating a AgentSkillRepo entity. +func (c *AgentSkillRepoClient) Create() *AgentSkillRepoCreate { + mutation := newAgentSkillRepoMutation(c.config, OpCreate) + return &AgentSkillRepoCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of AgentSkillRepo entities. +func (c *AgentSkillRepoClient) CreateBulk(builders ...*AgentSkillRepoCreate) *AgentSkillRepoCreateBulk { + return &AgentSkillRepoCreateBulk{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 *AgentSkillRepoClient) MapCreateBulk(slice any, setFunc func(*AgentSkillRepoCreate, int)) *AgentSkillRepoCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &AgentSkillRepoCreateBulk{err: fmt.Errorf("calling to AgentSkillRepoClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*AgentSkillRepoCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &AgentSkillRepoCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for AgentSkillRepo. +func (c *AgentSkillRepoClient) Update() *AgentSkillRepoUpdate { + mutation := newAgentSkillRepoMutation(c.config, OpUpdate) + return &AgentSkillRepoUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *AgentSkillRepoClient) UpdateOne(_m *AgentSkillRepo) *AgentSkillRepoUpdateOne { + mutation := newAgentSkillRepoMutation(c.config, OpUpdateOne, withAgentSkillRepo(_m)) + return &AgentSkillRepoUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *AgentSkillRepoClient) UpdateOneID(id uuid.UUID) *AgentSkillRepoUpdateOne { + mutation := newAgentSkillRepoMutation(c.config, OpUpdateOne, withAgentSkillRepoID(id)) + return &AgentSkillRepoUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for AgentSkillRepo. +func (c *AgentSkillRepoClient) Delete() *AgentSkillRepoDelete { + mutation := newAgentSkillRepoMutation(c.config, OpDelete) + return &AgentSkillRepoDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *AgentSkillRepoClient) DeleteOne(_m *AgentSkillRepo) *AgentSkillRepoDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *AgentSkillRepoClient) DeleteOneID(id uuid.UUID) *AgentSkillRepoDeleteOne { + builder := c.Delete().Where(agentskillrepo.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &AgentSkillRepoDeleteOne{builder} +} + +// Query returns a query builder for AgentSkillRepo. +func (c *AgentSkillRepoClient) Query() *AgentSkillRepoQuery { + return &AgentSkillRepoQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeAgentSkillRepo}, + inters: c.Interceptors(), + } +} + +// Get returns a AgentSkillRepo entity by its id. +func (c *AgentSkillRepoClient) Get(ctx context.Context, id uuid.UUID) (*AgentSkillRepo, error) { + return c.Query().Where(agentskillrepo.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *AgentSkillRepoClient) GetX(ctx context.Context, id uuid.UUID) *AgentSkillRepo { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QuerySkills queries the skills edge of a AgentSkillRepo. +func (c *AgentSkillRepoClient) QuerySkills(_m *AgentSkillRepo) *AgentSkillQuery { + query := (&AgentSkillClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(agentskillrepo.Table, agentskillrepo.FieldID, id), + sqlgraph.To(agentskill.Table, agentskill.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, agentskillrepo.SkillsTable, agentskillrepo.SkillsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *AgentSkillRepoClient) Hooks() []Hook { + return c.hooks.AgentSkillRepo +} + +// Interceptors returns the client interceptors. +func (c *AgentSkillRepoClient) Interceptors() []Interceptor { + return c.inters.AgentSkillRepo +} + +func (c *AgentSkillRepoClient) mutate(ctx context.Context, m *AgentSkillRepoMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&AgentSkillRepoCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&AgentSkillRepoUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&AgentSkillRepoUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&AgentSkillRepoDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown AgentSkillRepo mutation op: %q", m.Op()) + } +} + +// AgentSkillVersionClient is a client for the AgentSkillVersion schema. +type AgentSkillVersionClient struct { + config +} + +// NewAgentSkillVersionClient returns a client for the AgentSkillVersion from the given config. +func NewAgentSkillVersionClient(c config) *AgentSkillVersionClient { + return &AgentSkillVersionClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `agentskillversion.Hooks(f(g(h())))`. +func (c *AgentSkillVersionClient) Use(hooks ...Hook) { + c.hooks.AgentSkillVersion = append(c.hooks.AgentSkillVersion, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `agentskillversion.Intercept(f(g(h())))`. +func (c *AgentSkillVersionClient) Intercept(interceptors ...Interceptor) { + c.inters.AgentSkillVersion = append(c.inters.AgentSkillVersion, interceptors...) +} + +// Create returns a builder for creating a AgentSkillVersion entity. +func (c *AgentSkillVersionClient) Create() *AgentSkillVersionCreate { + mutation := newAgentSkillVersionMutation(c.config, OpCreate) + return &AgentSkillVersionCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of AgentSkillVersion entities. +func (c *AgentSkillVersionClient) CreateBulk(builders ...*AgentSkillVersionCreate) *AgentSkillVersionCreateBulk { + return &AgentSkillVersionCreateBulk{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 *AgentSkillVersionClient) MapCreateBulk(slice any, setFunc func(*AgentSkillVersionCreate, int)) *AgentSkillVersionCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &AgentSkillVersionCreateBulk{err: fmt.Errorf("calling to AgentSkillVersionClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*AgentSkillVersionCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &AgentSkillVersionCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for AgentSkillVersion. +func (c *AgentSkillVersionClient) Update() *AgentSkillVersionUpdate { + mutation := newAgentSkillVersionMutation(c.config, OpUpdate) + return &AgentSkillVersionUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *AgentSkillVersionClient) UpdateOne(_m *AgentSkillVersion) *AgentSkillVersionUpdateOne { + mutation := newAgentSkillVersionMutation(c.config, OpUpdateOne, withAgentSkillVersion(_m)) + return &AgentSkillVersionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *AgentSkillVersionClient) UpdateOneID(id uuid.UUID) *AgentSkillVersionUpdateOne { + mutation := newAgentSkillVersionMutation(c.config, OpUpdateOne, withAgentSkillVersionID(id)) + return &AgentSkillVersionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for AgentSkillVersion. +func (c *AgentSkillVersionClient) Delete() *AgentSkillVersionDelete { + mutation := newAgentSkillVersionMutation(c.config, OpDelete) + return &AgentSkillVersionDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *AgentSkillVersionClient) DeleteOne(_m *AgentSkillVersion) *AgentSkillVersionDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *AgentSkillVersionClient) DeleteOneID(id uuid.UUID) *AgentSkillVersionDeleteOne { + builder := c.Delete().Where(agentskillversion.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &AgentSkillVersionDeleteOne{builder} +} + +// Query returns a query builder for AgentSkillVersion. +func (c *AgentSkillVersionClient) Query() *AgentSkillVersionQuery { + return &AgentSkillVersionQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeAgentSkillVersion}, + inters: c.Interceptors(), + } +} + +// Get returns a AgentSkillVersion entity by its id. +func (c *AgentSkillVersionClient) Get(ctx context.Context, id uuid.UUID) (*AgentSkillVersion, error) { + return c.Query().Where(agentskillversion.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *AgentSkillVersionClient) GetX(ctx context.Context, id uuid.UUID) *AgentSkillVersion { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QuerySkill queries the skill edge of a AgentSkillVersion. +func (c *AgentSkillVersionClient) QuerySkill(_m *AgentSkillVersion) *AgentSkillQuery { + query := (&AgentSkillClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(agentskillversion.Table, agentskillversion.FieldID, id), + sqlgraph.To(agentskill.Table, agentskill.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, agentskillversion.SkillTable, agentskillversion.SkillColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *AgentSkillVersionClient) Hooks() []Hook { + return c.hooks.AgentSkillVersion +} + +// Interceptors returns the client interceptors. +func (c *AgentSkillVersionClient) Interceptors() []Interceptor { + return c.inters.AgentSkillVersion +} + +func (c *AgentSkillVersionClient) mutate(ctx context.Context, m *AgentSkillVersionMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&AgentSkillVersionCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&AgentSkillVersionUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&AgentSkillVersionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&AgentSkillVersionDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown AgentSkillVersion mutation op: %q", m.Op()) + } +} + +// AgentSyncJobClient is a client for the AgentSyncJob schema. +type AgentSyncJobClient struct { + config +} + +// NewAgentSyncJobClient returns a client for the AgentSyncJob from the given config. +func NewAgentSyncJobClient(c config) *AgentSyncJobClient { + return &AgentSyncJobClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `agentsyncjob.Hooks(f(g(h())))`. +func (c *AgentSyncJobClient) Use(hooks ...Hook) { + c.hooks.AgentSyncJob = append(c.hooks.AgentSyncJob, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `agentsyncjob.Intercept(f(g(h())))`. +func (c *AgentSyncJobClient) Intercept(interceptors ...Interceptor) { + c.inters.AgentSyncJob = append(c.inters.AgentSyncJob, interceptors...) +} + +// Create returns a builder for creating a AgentSyncJob entity. +func (c *AgentSyncJobClient) Create() *AgentSyncJobCreate { + mutation := newAgentSyncJobMutation(c.config, OpCreate) + return &AgentSyncJobCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of AgentSyncJob entities. +func (c *AgentSyncJobClient) CreateBulk(builders ...*AgentSyncJobCreate) *AgentSyncJobCreateBulk { + return &AgentSyncJobCreateBulk{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 *AgentSyncJobClient) MapCreateBulk(slice any, setFunc func(*AgentSyncJobCreate, int)) *AgentSyncJobCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &AgentSyncJobCreateBulk{err: fmt.Errorf("calling to AgentSyncJobClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*AgentSyncJobCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &AgentSyncJobCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for AgentSyncJob. +func (c *AgentSyncJobClient) Update() *AgentSyncJobUpdate { + mutation := newAgentSyncJobMutation(c.config, OpUpdate) + return &AgentSyncJobUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *AgentSyncJobClient) UpdateOne(_m *AgentSyncJob) *AgentSyncJobUpdateOne { + mutation := newAgentSyncJobMutation(c.config, OpUpdateOne, withAgentSyncJob(_m)) + return &AgentSyncJobUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *AgentSyncJobClient) UpdateOneID(id uuid.UUID) *AgentSyncJobUpdateOne { + mutation := newAgentSyncJobMutation(c.config, OpUpdateOne, withAgentSyncJobID(id)) + return &AgentSyncJobUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for AgentSyncJob. +func (c *AgentSyncJobClient) Delete() *AgentSyncJobDelete { + mutation := newAgentSyncJobMutation(c.config, OpDelete) + return &AgentSyncJobDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *AgentSyncJobClient) DeleteOne(_m *AgentSyncJob) *AgentSyncJobDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *AgentSyncJobClient) DeleteOneID(id uuid.UUID) *AgentSyncJobDeleteOne { + builder := c.Delete().Where(agentsyncjob.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &AgentSyncJobDeleteOne{builder} +} + +// Query returns a query builder for AgentSyncJob. +func (c *AgentSyncJobClient) Query() *AgentSyncJobQuery { + return &AgentSyncJobQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeAgentSyncJob}, + inters: c.Interceptors(), + } +} + +// Get returns a AgentSyncJob entity by its id. +func (c *AgentSyncJobClient) Get(ctx context.Context, id uuid.UUID) (*AgentSyncJob, error) { + return c.Query().Where(agentsyncjob.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *AgentSyncJobClient) GetX(ctx context.Context, id uuid.UUID) *AgentSyncJob { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *AgentSyncJobClient) Hooks() []Hook { + return c.hooks.AgentSyncJob +} + +// Interceptors returns the client interceptors. +func (c *AgentSyncJobClient) Interceptors() []Interceptor { + return c.inters.AgentSyncJob +} + +func (c *AgentSyncJobClient) mutate(ctx context.Context, m *AgentSyncJobMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&AgentSyncJobCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&AgentSyncJobUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&AgentSyncJobUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&AgentSyncJobDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown AgentSyncJob mutation op: %q", m.Op()) + } +} + // AuditClient is a client for the Audit schema. type AuditClient struct { config @@ -8235,8 +9668,10 @@ func (c *VirtualMachineClient) mutate(ctx context.Context, m *VirtualMachineMuta // hooks and interceptors per client, for fast access. type ( hooks struct { - Audit, GitBot, GitBotTask, GitBotUser, GitIdentity, GitTask, Host, Image, - MCPTool, MCPUpstream, MCPUserToolSetting, Model, ModelApiKey, ModelPricing, + AgentPlugin, AgentPluginRepo, AgentPluginVersion, AgentRule, AgentRuleVersion, + AgentSkill, AgentSkillRepo, AgentSkillVersion, AgentSyncJob, Audit, GitBot, + GitBotTask, GitBotUser, GitIdentity, GitTask, Host, Image, MCPTool, + MCPUpstream, MCPUserToolSetting, Model, ModelApiKey, ModelPricing, NotifyChannel, NotifySendLog, NotifySubscription, Project, ProjectCollaborator, ProjectGitBot, ProjectIssue, ProjectIssueComment, ProjectTask, Task, TaskModelSwitch, TaskUsageStat, TaskVirtualMachine, Team, TeamGroup, @@ -8244,8 +9679,10 @@ type ( TeamImage, TeamMember, TeamModel, User, UserIdentity, VirtualMachine []ent.Hook } inters struct { - Audit, GitBot, GitBotTask, GitBotUser, GitIdentity, GitTask, Host, Image, - MCPTool, MCPUpstream, MCPUserToolSetting, Model, ModelApiKey, ModelPricing, + AgentPlugin, AgentPluginRepo, AgentPluginVersion, AgentRule, AgentRuleVersion, + AgentSkill, AgentSkillRepo, AgentSkillVersion, AgentSyncJob, Audit, GitBot, + GitBotTask, GitBotUser, GitIdentity, GitTask, Host, Image, MCPTool, + MCPUpstream, MCPUserToolSetting, Model, ModelApiKey, ModelPricing, NotifyChannel, NotifySendLog, NotifySubscription, Project, ProjectCollaborator, ProjectGitBot, ProjectIssue, ProjectIssueComment, ProjectTask, Task, TaskModelSwitch, TaskUsageStat, TaskVirtualMachine, Team, TeamGroup, diff --git a/backend/db/ent.go b/backend/db/ent.go index 0d83033d..d60b1af8 100644 --- a/backend/db/ent.go +++ b/backend/db/ent.go @@ -12,6 +12,15 @@ import ( "entgo.io/ent" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/chaitin/MonkeyCode/backend/db/agentplugin" + "github.com/chaitin/MonkeyCode/backend/db/agentpluginrepo" + "github.com/chaitin/MonkeyCode/backend/db/agentpluginversion" + "github.com/chaitin/MonkeyCode/backend/db/agentrule" + "github.com/chaitin/MonkeyCode/backend/db/agentruleversion" + "github.com/chaitin/MonkeyCode/backend/db/agentskill" + "github.com/chaitin/MonkeyCode/backend/db/agentskillrepo" + "github.com/chaitin/MonkeyCode/backend/db/agentskillversion" + "github.com/chaitin/MonkeyCode/backend/db/agentsyncjob" "github.com/chaitin/MonkeyCode/backend/db/audit" "github.com/chaitin/MonkeyCode/backend/db/gitbot" "github.com/chaitin/MonkeyCode/backend/db/gitbottask" @@ -112,6 +121,15 @@ var ( func checkColumn(t, c string) error { initCheck.Do(func() { columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ + agentplugin.Table: agentplugin.ValidColumn, + agentpluginrepo.Table: agentpluginrepo.ValidColumn, + agentpluginversion.Table: agentpluginversion.ValidColumn, + agentrule.Table: agentrule.ValidColumn, + agentruleversion.Table: agentruleversion.ValidColumn, + agentskill.Table: agentskill.ValidColumn, + agentskillrepo.Table: agentskillrepo.ValidColumn, + agentskillversion.Table: agentskillversion.ValidColumn, + agentsyncjob.Table: agentsyncjob.ValidColumn, audit.Table: audit.ValidColumn, gitbot.Table: gitbot.ValidColumn, gitbottask.Table: gitbottask.ValidColumn, diff --git a/backend/db/hook/hook.go b/backend/db/hook/hook.go index cf0675e1..298fbe15 100644 --- a/backend/db/hook/hook.go +++ b/backend/db/hook/hook.go @@ -9,6 +9,114 @@ import ( "github.com/chaitin/MonkeyCode/backend/db" ) +// The AgentPluginFunc type is an adapter to allow the use of ordinary +// function as AgentPlugin mutator. +type AgentPluginFunc func(context.Context, *db.AgentPluginMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f AgentPluginFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.AgentPluginMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.AgentPluginMutation", m) +} + +// The AgentPluginRepoFunc type is an adapter to allow the use of ordinary +// function as AgentPluginRepo mutator. +type AgentPluginRepoFunc func(context.Context, *db.AgentPluginRepoMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f AgentPluginRepoFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.AgentPluginRepoMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.AgentPluginRepoMutation", m) +} + +// The AgentPluginVersionFunc type is an adapter to allow the use of ordinary +// function as AgentPluginVersion mutator. +type AgentPluginVersionFunc func(context.Context, *db.AgentPluginVersionMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f AgentPluginVersionFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.AgentPluginVersionMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.AgentPluginVersionMutation", m) +} + +// The AgentRuleFunc type is an adapter to allow the use of ordinary +// function as AgentRule mutator. +type AgentRuleFunc func(context.Context, *db.AgentRuleMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f AgentRuleFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.AgentRuleMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.AgentRuleMutation", m) +} + +// The AgentRuleVersionFunc type is an adapter to allow the use of ordinary +// function as AgentRuleVersion mutator. +type AgentRuleVersionFunc func(context.Context, *db.AgentRuleVersionMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f AgentRuleVersionFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.AgentRuleVersionMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.AgentRuleVersionMutation", m) +} + +// The AgentSkillFunc type is an adapter to allow the use of ordinary +// function as AgentSkill mutator. +type AgentSkillFunc func(context.Context, *db.AgentSkillMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f AgentSkillFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.AgentSkillMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.AgentSkillMutation", m) +} + +// The AgentSkillRepoFunc type is an adapter to allow the use of ordinary +// function as AgentSkillRepo mutator. +type AgentSkillRepoFunc func(context.Context, *db.AgentSkillRepoMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f AgentSkillRepoFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.AgentSkillRepoMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.AgentSkillRepoMutation", m) +} + +// The AgentSkillVersionFunc type is an adapter to allow the use of ordinary +// function as AgentSkillVersion mutator. +type AgentSkillVersionFunc func(context.Context, *db.AgentSkillVersionMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f AgentSkillVersionFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.AgentSkillVersionMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.AgentSkillVersionMutation", m) +} + +// The AgentSyncJobFunc type is an adapter to allow the use of ordinary +// function as AgentSyncJob mutator. +type AgentSyncJobFunc func(context.Context, *db.AgentSyncJobMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f AgentSyncJobFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.AgentSyncJobMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.AgentSyncJobMutation", m) +} + // The AuditFunc type is an adapter to allow the use of ordinary // function as Audit mutator. type AuditFunc func(context.Context, *db.AuditMutation) (db.Value, error) diff --git a/backend/db/intercept/intercept.go b/backend/db/intercept/intercept.go index 6aba2cdb..2498fc82 100644 --- a/backend/db/intercept/intercept.go +++ b/backend/db/intercept/intercept.go @@ -8,6 +8,15 @@ import ( "entgo.io/ent/dialect/sql" "github.com/chaitin/MonkeyCode/backend/db" + "github.com/chaitin/MonkeyCode/backend/db/agentplugin" + "github.com/chaitin/MonkeyCode/backend/db/agentpluginrepo" + "github.com/chaitin/MonkeyCode/backend/db/agentpluginversion" + "github.com/chaitin/MonkeyCode/backend/db/agentrule" + "github.com/chaitin/MonkeyCode/backend/db/agentruleversion" + "github.com/chaitin/MonkeyCode/backend/db/agentskill" + "github.com/chaitin/MonkeyCode/backend/db/agentskillrepo" + "github.com/chaitin/MonkeyCode/backend/db/agentskillversion" + "github.com/chaitin/MonkeyCode/backend/db/agentsyncjob" "github.com/chaitin/MonkeyCode/backend/db/audit" "github.com/chaitin/MonkeyCode/backend/db/gitbot" "github.com/chaitin/MonkeyCode/backend/db/gitbottask" @@ -107,6 +116,249 @@ func (f TraverseFunc) Traverse(ctx context.Context, q db.Query) error { return f(ctx, query) } +// The AgentPluginFunc type is an adapter to allow the use of ordinary function as a Querier. +type AgentPluginFunc func(context.Context, *db.AgentPluginQuery) (db.Value, error) + +// Query calls f(ctx, q). +func (f AgentPluginFunc) Query(ctx context.Context, q db.Query) (db.Value, error) { + if q, ok := q.(*db.AgentPluginQuery); ok { + return f(ctx, q) + } + return nil, fmt.Errorf("unexpected query type %T. expect *db.AgentPluginQuery", q) +} + +// The TraverseAgentPlugin type is an adapter to allow the use of ordinary function as Traverser. +type TraverseAgentPlugin func(context.Context, *db.AgentPluginQuery) error + +// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline. +func (f TraverseAgentPlugin) Intercept(next db.Querier) db.Querier { + return next +} + +// Traverse calls f(ctx, q). +func (f TraverseAgentPlugin) Traverse(ctx context.Context, q db.Query) error { + if q, ok := q.(*db.AgentPluginQuery); ok { + return f(ctx, q) + } + return fmt.Errorf("unexpected query type %T. expect *db.AgentPluginQuery", q) +} + +// The AgentPluginRepoFunc type is an adapter to allow the use of ordinary function as a Querier. +type AgentPluginRepoFunc func(context.Context, *db.AgentPluginRepoQuery) (db.Value, error) + +// Query calls f(ctx, q). +func (f AgentPluginRepoFunc) Query(ctx context.Context, q db.Query) (db.Value, error) { + if q, ok := q.(*db.AgentPluginRepoQuery); ok { + return f(ctx, q) + } + return nil, fmt.Errorf("unexpected query type %T. expect *db.AgentPluginRepoQuery", q) +} + +// The TraverseAgentPluginRepo type is an adapter to allow the use of ordinary function as Traverser. +type TraverseAgentPluginRepo func(context.Context, *db.AgentPluginRepoQuery) error + +// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline. +func (f TraverseAgentPluginRepo) Intercept(next db.Querier) db.Querier { + return next +} + +// Traverse calls f(ctx, q). +func (f TraverseAgentPluginRepo) Traverse(ctx context.Context, q db.Query) error { + if q, ok := q.(*db.AgentPluginRepoQuery); ok { + return f(ctx, q) + } + return fmt.Errorf("unexpected query type %T. expect *db.AgentPluginRepoQuery", q) +} + +// The AgentPluginVersionFunc type is an adapter to allow the use of ordinary function as a Querier. +type AgentPluginVersionFunc func(context.Context, *db.AgentPluginVersionQuery) (db.Value, error) + +// Query calls f(ctx, q). +func (f AgentPluginVersionFunc) Query(ctx context.Context, q db.Query) (db.Value, error) { + if q, ok := q.(*db.AgentPluginVersionQuery); ok { + return f(ctx, q) + } + return nil, fmt.Errorf("unexpected query type %T. expect *db.AgentPluginVersionQuery", q) +} + +// The TraverseAgentPluginVersion type is an adapter to allow the use of ordinary function as Traverser. +type TraverseAgentPluginVersion func(context.Context, *db.AgentPluginVersionQuery) error + +// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline. +func (f TraverseAgentPluginVersion) Intercept(next db.Querier) db.Querier { + return next +} + +// Traverse calls f(ctx, q). +func (f TraverseAgentPluginVersion) Traverse(ctx context.Context, q db.Query) error { + if q, ok := q.(*db.AgentPluginVersionQuery); ok { + return f(ctx, q) + } + return fmt.Errorf("unexpected query type %T. expect *db.AgentPluginVersionQuery", q) +} + +// The AgentRuleFunc type is an adapter to allow the use of ordinary function as a Querier. +type AgentRuleFunc func(context.Context, *db.AgentRuleQuery) (db.Value, error) + +// Query calls f(ctx, q). +func (f AgentRuleFunc) Query(ctx context.Context, q db.Query) (db.Value, error) { + if q, ok := q.(*db.AgentRuleQuery); ok { + return f(ctx, q) + } + return nil, fmt.Errorf("unexpected query type %T. expect *db.AgentRuleQuery", q) +} + +// The TraverseAgentRule type is an adapter to allow the use of ordinary function as Traverser. +type TraverseAgentRule func(context.Context, *db.AgentRuleQuery) error + +// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline. +func (f TraverseAgentRule) Intercept(next db.Querier) db.Querier { + return next +} + +// Traverse calls f(ctx, q). +func (f TraverseAgentRule) Traverse(ctx context.Context, q db.Query) error { + if q, ok := q.(*db.AgentRuleQuery); ok { + return f(ctx, q) + } + return fmt.Errorf("unexpected query type %T. expect *db.AgentRuleQuery", q) +} + +// The AgentRuleVersionFunc type is an adapter to allow the use of ordinary function as a Querier. +type AgentRuleVersionFunc func(context.Context, *db.AgentRuleVersionQuery) (db.Value, error) + +// Query calls f(ctx, q). +func (f AgentRuleVersionFunc) Query(ctx context.Context, q db.Query) (db.Value, error) { + if q, ok := q.(*db.AgentRuleVersionQuery); ok { + return f(ctx, q) + } + return nil, fmt.Errorf("unexpected query type %T. expect *db.AgentRuleVersionQuery", q) +} + +// The TraverseAgentRuleVersion type is an adapter to allow the use of ordinary function as Traverser. +type TraverseAgentRuleVersion func(context.Context, *db.AgentRuleVersionQuery) error + +// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline. +func (f TraverseAgentRuleVersion) Intercept(next db.Querier) db.Querier { + return next +} + +// Traverse calls f(ctx, q). +func (f TraverseAgentRuleVersion) Traverse(ctx context.Context, q db.Query) error { + if q, ok := q.(*db.AgentRuleVersionQuery); ok { + return f(ctx, q) + } + return fmt.Errorf("unexpected query type %T. expect *db.AgentRuleVersionQuery", q) +} + +// The AgentSkillFunc type is an adapter to allow the use of ordinary function as a Querier. +type AgentSkillFunc func(context.Context, *db.AgentSkillQuery) (db.Value, error) + +// Query calls f(ctx, q). +func (f AgentSkillFunc) Query(ctx context.Context, q db.Query) (db.Value, error) { + if q, ok := q.(*db.AgentSkillQuery); ok { + return f(ctx, q) + } + return nil, fmt.Errorf("unexpected query type %T. expect *db.AgentSkillQuery", q) +} + +// The TraverseAgentSkill type is an adapter to allow the use of ordinary function as Traverser. +type TraverseAgentSkill func(context.Context, *db.AgentSkillQuery) error + +// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline. +func (f TraverseAgentSkill) Intercept(next db.Querier) db.Querier { + return next +} + +// Traverse calls f(ctx, q). +func (f TraverseAgentSkill) Traverse(ctx context.Context, q db.Query) error { + if q, ok := q.(*db.AgentSkillQuery); ok { + return f(ctx, q) + } + return fmt.Errorf("unexpected query type %T. expect *db.AgentSkillQuery", q) +} + +// The AgentSkillRepoFunc type is an adapter to allow the use of ordinary function as a Querier. +type AgentSkillRepoFunc func(context.Context, *db.AgentSkillRepoQuery) (db.Value, error) + +// Query calls f(ctx, q). +func (f AgentSkillRepoFunc) Query(ctx context.Context, q db.Query) (db.Value, error) { + if q, ok := q.(*db.AgentSkillRepoQuery); ok { + return f(ctx, q) + } + return nil, fmt.Errorf("unexpected query type %T. expect *db.AgentSkillRepoQuery", q) +} + +// The TraverseAgentSkillRepo type is an adapter to allow the use of ordinary function as Traverser. +type TraverseAgentSkillRepo func(context.Context, *db.AgentSkillRepoQuery) error + +// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline. +func (f TraverseAgentSkillRepo) Intercept(next db.Querier) db.Querier { + return next +} + +// Traverse calls f(ctx, q). +func (f TraverseAgentSkillRepo) Traverse(ctx context.Context, q db.Query) error { + if q, ok := q.(*db.AgentSkillRepoQuery); ok { + return f(ctx, q) + } + return fmt.Errorf("unexpected query type %T. expect *db.AgentSkillRepoQuery", q) +} + +// The AgentSkillVersionFunc type is an adapter to allow the use of ordinary function as a Querier. +type AgentSkillVersionFunc func(context.Context, *db.AgentSkillVersionQuery) (db.Value, error) + +// Query calls f(ctx, q). +func (f AgentSkillVersionFunc) Query(ctx context.Context, q db.Query) (db.Value, error) { + if q, ok := q.(*db.AgentSkillVersionQuery); ok { + return f(ctx, q) + } + return nil, fmt.Errorf("unexpected query type %T. expect *db.AgentSkillVersionQuery", q) +} + +// The TraverseAgentSkillVersion type is an adapter to allow the use of ordinary function as Traverser. +type TraverseAgentSkillVersion func(context.Context, *db.AgentSkillVersionQuery) error + +// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline. +func (f TraverseAgentSkillVersion) Intercept(next db.Querier) db.Querier { + return next +} + +// Traverse calls f(ctx, q). +func (f TraverseAgentSkillVersion) Traverse(ctx context.Context, q db.Query) error { + if q, ok := q.(*db.AgentSkillVersionQuery); ok { + return f(ctx, q) + } + return fmt.Errorf("unexpected query type %T. expect *db.AgentSkillVersionQuery", q) +} + +// The AgentSyncJobFunc type is an adapter to allow the use of ordinary function as a Querier. +type AgentSyncJobFunc func(context.Context, *db.AgentSyncJobQuery) (db.Value, error) + +// Query calls f(ctx, q). +func (f AgentSyncJobFunc) Query(ctx context.Context, q db.Query) (db.Value, error) { + if q, ok := q.(*db.AgentSyncJobQuery); ok { + return f(ctx, q) + } + return nil, fmt.Errorf("unexpected query type %T. expect *db.AgentSyncJobQuery", q) +} + +// The TraverseAgentSyncJob type is an adapter to allow the use of ordinary function as Traverser. +type TraverseAgentSyncJob func(context.Context, *db.AgentSyncJobQuery) error + +// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline. +func (f TraverseAgentSyncJob) Intercept(next db.Querier) db.Querier { + return next +} + +// Traverse calls f(ctx, q). +func (f TraverseAgentSyncJob) Traverse(ctx context.Context, q db.Query) error { + if q, ok := q.(*db.AgentSyncJobQuery); ok { + return f(ctx, q) + } + return fmt.Errorf("unexpected query type %T. expect *db.AgentSyncJobQuery", q) +} + // The AuditFunc type is an adapter to allow the use of ordinary function as a Querier. type AuditFunc func(context.Context, *db.AuditQuery) (db.Value, error) @@ -1190,6 +1442,24 @@ func (f TraverseVirtualMachine) Traverse(ctx context.Context, q db.Query) error // NewQuery returns the generic Query interface for the given typed query. func NewQuery(q db.Query) (Query, error) { switch q := q.(type) { + case *db.AgentPluginQuery: + return &query[*db.AgentPluginQuery, predicate.AgentPlugin, agentplugin.OrderOption]{typ: db.TypeAgentPlugin, tq: q}, nil + case *db.AgentPluginRepoQuery: + return &query[*db.AgentPluginRepoQuery, predicate.AgentPluginRepo, agentpluginrepo.OrderOption]{typ: db.TypeAgentPluginRepo, tq: q}, nil + case *db.AgentPluginVersionQuery: + return &query[*db.AgentPluginVersionQuery, predicate.AgentPluginVersion, agentpluginversion.OrderOption]{typ: db.TypeAgentPluginVersion, tq: q}, nil + case *db.AgentRuleQuery: + return &query[*db.AgentRuleQuery, predicate.AgentRule, agentrule.OrderOption]{typ: db.TypeAgentRule, tq: q}, nil + case *db.AgentRuleVersionQuery: + return &query[*db.AgentRuleVersionQuery, predicate.AgentRuleVersion, agentruleversion.OrderOption]{typ: db.TypeAgentRuleVersion, tq: q}, nil + case *db.AgentSkillQuery: + return &query[*db.AgentSkillQuery, predicate.AgentSkill, agentskill.OrderOption]{typ: db.TypeAgentSkill, tq: q}, nil + case *db.AgentSkillRepoQuery: + return &query[*db.AgentSkillRepoQuery, predicate.AgentSkillRepo, agentskillrepo.OrderOption]{typ: db.TypeAgentSkillRepo, tq: q}, nil + case *db.AgentSkillVersionQuery: + return &query[*db.AgentSkillVersionQuery, predicate.AgentSkillVersion, agentskillversion.OrderOption]{typ: db.TypeAgentSkillVersion, tq: q}, nil + case *db.AgentSyncJobQuery: + return &query[*db.AgentSyncJobQuery, predicate.AgentSyncJob, agentsyncjob.OrderOption]{typ: db.TypeAgentSyncJob, tq: q}, nil case *db.AuditQuery: return &query[*db.AuditQuery, predicate.Audit, audit.OrderOption]{typ: db.TypeAudit, tq: q}, nil case *db.GitBotQuery: diff --git a/backend/db/migrate/schema.go b/backend/db/migrate/schema.go index a6b71e22..676a3c71 100644 --- a/backend/db/migrate/schema.go +++ b/backend/db/migrate/schema.go @@ -9,6 +9,325 @@ import ( ) var ( + // AgentPluginsColumns holds the columns for the "agent_plugins" table. + AgentPluginsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeUUID}, + {Name: "name", Type: field.TypeString}, + {Name: "description", Type: field.TypeString, Nullable: true, Size: 2147483647}, + {Name: "scope_type", Type: field.TypeEnum, Enums: []string{"global"}, Default: "global"}, + {Name: "scope_id", Type: field.TypeString, Default: "global"}, + {Name: "created_by", Type: field.TypeUUID}, + {Name: "active_version_id", Type: field.TypeUUID, Nullable: true}, + {Name: "is_force_delivery", Type: field.TypeBool, Default: false}, + {Name: "is_orphan", Type: field.TypeBool, Default: false}, + {Name: "is_deleted", Type: field.TypeBool, Default: false}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "repo_id", Type: field.TypeUUID}, + } + // AgentPluginsTable holds the schema information for the "agent_plugins" table. + AgentPluginsTable = &schema.Table{ + Name: "agent_plugins", + Columns: AgentPluginsColumns, + PrimaryKey: []*schema.Column{AgentPluginsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "agent_plugins_agent_plugin_repos_plugins", + Columns: []*schema.Column{AgentPluginsColumns[12]}, + RefColumns: []*schema.Column{AgentPluginReposColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + Indexes: []*schema.Index{ + { + Name: "agentplugin_repo_id_name", + Unique: true, + Columns: []*schema.Column{AgentPluginsColumns[12], AgentPluginsColumns[1]}, + }, + { + Name: "agentplugin_scope_type_scope_id", + Unique: false, + Columns: []*schema.Column{AgentPluginsColumns[3], AgentPluginsColumns[4]}, + }, + { + Name: "agentplugin_active_version_id", + Unique: false, + Columns: []*schema.Column{AgentPluginsColumns[6]}, + }, + }, + } + // AgentPluginReposColumns holds the columns for the "agent_plugin_repos" table. + AgentPluginReposColumns = []*schema.Column{ + {Name: "id", Type: field.TypeUUID}, + {Name: "name", Type: field.TypeString}, + {Name: "scope_type", Type: field.TypeEnum, Enums: []string{"global"}, Default: "global"}, + {Name: "scope_id", Type: field.TypeString, Default: "global"}, + {Name: "created_by", Type: field.TypeUUID}, + {Name: "source_type", Type: field.TypeEnum, Enums: []string{"github", "upload", "npm"}}, + {Name: "github_url", Type: field.TypeString, Nullable: true}, + {Name: "ref_type", Type: field.TypeEnum, Nullable: true, Enums: []string{"branch", "tag", "commit"}}, + {Name: "ref_value", Type: field.TypeString, Nullable: true}, + {Name: "last_upload_filename", Type: field.TypeString, Nullable: true}, + {Name: "last_upload_at", Type: field.TypeTime, Nullable: true}, + {Name: "plugin_discovery_auto_package_json", Type: field.TypeBool, Default: true}, + {Name: "plugin_manual_entries", Type: field.TypeJSON, Nullable: true}, + {Name: "npm_package_name", Type: field.TypeString, Nullable: true}, + {Name: "npm_version_spec", Type: field.TypeString, Nullable: true}, + {Name: "npm_registry_url", Type: field.TypeString, Nullable: true}, + {Name: "is_deleted", Type: field.TypeBool, Default: false}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + } + // AgentPluginReposTable holds the schema information for the "agent_plugin_repos" table. + AgentPluginReposTable = &schema.Table{ + Name: "agent_plugin_repos", + Columns: AgentPluginReposColumns, + PrimaryKey: []*schema.Column{AgentPluginReposColumns[0]}, + Indexes: []*schema.Index{ + { + Name: "agentpluginrepo_scope_type_scope_id", + Unique: false, + Columns: []*schema.Column{AgentPluginReposColumns[2], AgentPluginReposColumns[3]}, + }, + }, + } + // AgentPluginVersionsColumns holds the columns for the "agent_plugin_versions" table. + AgentPluginVersionsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeUUID}, + {Name: "version", Type: field.TypeString}, + {Name: "s3_key", Type: field.TypeString}, + {Name: "parsed_meta", Type: field.TypeJSON, Nullable: true}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "resource_id", Type: field.TypeUUID}, + } + // AgentPluginVersionsTable holds the schema information for the "agent_plugin_versions" table. + AgentPluginVersionsTable = &schema.Table{ + Name: "agent_plugin_versions", + Columns: AgentPluginVersionsColumns, + PrimaryKey: []*schema.Column{AgentPluginVersionsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "agent_plugin_versions_agent_plugins_versions", + Columns: []*schema.Column{AgentPluginVersionsColumns[5]}, + RefColumns: []*schema.Column{AgentPluginsColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + Indexes: []*schema.Index{ + { + Name: "agentpluginversion_resource_id", + Unique: false, + Columns: []*schema.Column{AgentPluginVersionsColumns[5]}, + }, + }, + } + // AgentRulesColumns holds the columns for the "agent_rules" table. + AgentRulesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeUUID}, + {Name: "name", Type: field.TypeString}, + {Name: "description", Type: field.TypeString, Nullable: true, Size: 2147483647}, + {Name: "scope_type", Type: field.TypeEnum, Enums: []string{"global"}, Default: "global"}, + {Name: "scope_id", Type: field.TypeString, Default: "global"}, + {Name: "created_by", Type: field.TypeUUID}, + {Name: "active_version_id", Type: field.TypeUUID, Nullable: true}, + {Name: "is_deleted", Type: field.TypeBool, Default: false}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + } + // AgentRulesTable holds the schema information for the "agent_rules" table. + AgentRulesTable = &schema.Table{ + Name: "agent_rules", + Columns: AgentRulesColumns, + PrimaryKey: []*schema.Column{AgentRulesColumns[0]}, + Indexes: []*schema.Index{ + { + Name: "agentrule_scope_type_scope_id", + Unique: false, + Columns: []*schema.Column{AgentRulesColumns[3], AgentRulesColumns[4]}, + }, + { + Name: "agentrule_active_version_id", + Unique: false, + Columns: []*schema.Column{AgentRulesColumns[6]}, + }, + }, + } + // AgentRuleVersionsColumns holds the columns for the "agent_rule_versions" table. + AgentRuleVersionsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeUUID}, + {Name: "version", Type: field.TypeString, Size: 14}, + {Name: "content", Type: field.TypeString, Size: 2147483647}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "rule_id", Type: field.TypeUUID}, + } + // AgentRuleVersionsTable holds the schema information for the "agent_rule_versions" table. + AgentRuleVersionsTable = &schema.Table{ + Name: "agent_rule_versions", + Columns: AgentRuleVersionsColumns, + PrimaryKey: []*schema.Column{AgentRuleVersionsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "agent_rule_versions_agent_rules_versions", + Columns: []*schema.Column{AgentRuleVersionsColumns[4]}, + RefColumns: []*schema.Column{AgentRulesColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + Indexes: []*schema.Index{ + { + Name: "agentruleversion_rule_id", + Unique: false, + Columns: []*schema.Column{AgentRuleVersionsColumns[4]}, + }, + }, + } + // AgentSkillsColumns holds the columns for the "agent_skills" table. + AgentSkillsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeUUID}, + {Name: "name", Type: field.TypeString}, + {Name: "description", Type: field.TypeString, Nullable: true, Size: 2147483647}, + {Name: "scope_type", Type: field.TypeEnum, Enums: []string{"global"}, Default: "global"}, + {Name: "scope_id", Type: field.TypeString, Default: "global"}, + {Name: "created_by", Type: field.TypeUUID}, + {Name: "active_version_id", Type: field.TypeUUID, Nullable: true}, + {Name: "is_force_delivery", Type: field.TypeBool, Default: false}, + {Name: "is_orphan", Type: field.TypeBool, Default: false}, + {Name: "is_deleted", Type: field.TypeBool, Default: false}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "repo_id", Type: field.TypeUUID}, + } + // AgentSkillsTable holds the schema information for the "agent_skills" table. + AgentSkillsTable = &schema.Table{ + Name: "agent_skills", + Columns: AgentSkillsColumns, + PrimaryKey: []*schema.Column{AgentSkillsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "agent_skills_agent_skill_repos_skills", + Columns: []*schema.Column{AgentSkillsColumns[12]}, + RefColumns: []*schema.Column{AgentSkillReposColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + Indexes: []*schema.Index{ + { + Name: "agentskill_repo_id_name", + Unique: true, + Columns: []*schema.Column{AgentSkillsColumns[12], AgentSkillsColumns[1]}, + }, + { + Name: "agentskill_scope_type_scope_id", + Unique: false, + Columns: []*schema.Column{AgentSkillsColumns[3], AgentSkillsColumns[4]}, + }, + { + Name: "agentskill_active_version_id", + Unique: false, + Columns: []*schema.Column{AgentSkillsColumns[6]}, + }, + }, + } + // AgentSkillReposColumns holds the columns for the "agent_skill_repos" table. + AgentSkillReposColumns = []*schema.Column{ + {Name: "id", Type: field.TypeUUID}, + {Name: "name", Type: field.TypeString}, + {Name: "scope_type", Type: field.TypeEnum, Enums: []string{"global"}, Default: "global"}, + {Name: "scope_id", Type: field.TypeString, Default: "global"}, + {Name: "created_by", Type: field.TypeUUID}, + {Name: "source_type", Type: field.TypeEnum, Enums: []string{"github", "upload"}}, + {Name: "github_url", Type: field.TypeString, Nullable: true}, + {Name: "ref_type", Type: field.TypeEnum, Nullable: true, Enums: []string{"branch", "tag", "commit"}}, + {Name: "ref_value", Type: field.TypeString, Nullable: true}, + {Name: "last_upload_filename", Type: field.TypeString, Nullable: true}, + {Name: "last_upload_at", Type: field.TypeTime, Nullable: true}, + {Name: "is_deleted", Type: field.TypeBool, Default: false}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + } + // AgentSkillReposTable holds the schema information for the "agent_skill_repos" table. + AgentSkillReposTable = &schema.Table{ + Name: "agent_skill_repos", + Columns: AgentSkillReposColumns, + PrimaryKey: []*schema.Column{AgentSkillReposColumns[0]}, + Indexes: []*schema.Index{ + { + Name: "agentskillrepo_scope_type_scope_id", + Unique: false, + Columns: []*schema.Column{AgentSkillReposColumns[2], AgentSkillReposColumns[3]}, + }, + }, + } + // AgentSkillVersionsColumns holds the columns for the "agent_skill_versions" table. + AgentSkillVersionsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeUUID}, + {Name: "version", Type: field.TypeString}, + {Name: "s3_key", Type: field.TypeString}, + {Name: "parsed_meta", Type: field.TypeJSON, Nullable: true}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "resource_id", Type: field.TypeUUID}, + } + // AgentSkillVersionsTable holds the schema information for the "agent_skill_versions" table. + AgentSkillVersionsTable = &schema.Table{ + Name: "agent_skill_versions", + Columns: AgentSkillVersionsColumns, + PrimaryKey: []*schema.Column{AgentSkillVersionsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "agent_skill_versions_agent_skills_versions", + Columns: []*schema.Column{AgentSkillVersionsColumns[5]}, + RefColumns: []*schema.Column{AgentSkillsColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + Indexes: []*schema.Index{ + { + Name: "agentskillversion_resource_id", + Unique: false, + Columns: []*schema.Column{AgentSkillVersionsColumns[5]}, + }, + }, + } + // AgentSyncJobsColumns holds the columns for the "agent_sync_jobs" table. + AgentSyncJobsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeUUID}, + {Name: "resource_kind", Type: field.TypeEnum, Enums: []string{"rule", "skill", "plugin"}}, + {Name: "rule_id", Type: field.TypeUUID, Nullable: true}, + {Name: "repo_id", Type: field.TypeUUID, Nullable: true}, + {Name: "source_type", Type: field.TypeEnum, Enums: []string{"github", "upload", "npm", "rule_inline"}}, + {Name: "status", Type: field.TypeEnum, Enums: []string{"pending", "fetching", "parsing", "uploading", "done", "failed"}, Default: "pending"}, + {Name: "trigger_type", Type: field.TypeEnum, Enums: []string{"manual", "upload", "rule_save"}}, + {Name: "triggered_by", Type: field.TypeUUID, Nullable: true}, + {Name: "started_at", Type: field.TypeTime, Nullable: true}, + {Name: "finished_at", Type: field.TypeTime, Nullable: true}, + {Name: "errors", Type: field.TypeJSON, Nullable: true}, + {Name: "result_summary", Type: field.TypeJSON, Nullable: true}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + } + // AgentSyncJobsTable holds the schema information for the "agent_sync_jobs" table. + AgentSyncJobsTable = &schema.Table{ + Name: "agent_sync_jobs", + Columns: AgentSyncJobsColumns, + PrimaryKey: []*schema.Column{AgentSyncJobsColumns[0]}, + Indexes: []*schema.Index{ + { + Name: "agentsyncjob_status_created_at", + Unique: false, + Columns: []*schema.Column{AgentSyncJobsColumns[5], AgentSyncJobsColumns[12]}, + }, + { + Name: "agentsyncjob_rule_id", + Unique: false, + Columns: []*schema.Column{AgentSyncJobsColumns[2]}, + }, + { + Name: "agentsyncjob_repo_id", + Unique: false, + Columns: []*schema.Column{AgentSyncJobsColumns[3]}, + }, + }, + } // AuditsColumns holds the columns for the "audits" table. AuditsColumns = []*schema.Column{ {Name: "id", Type: field.TypeUUID}, @@ -1354,6 +1673,15 @@ var ( } // Tables holds all the tables in the schema. Tables = []*schema.Table{ + AgentPluginsTable, + AgentPluginReposTable, + AgentPluginVersionsTable, + AgentRulesTable, + AgentRuleVersionsTable, + AgentSkillsTable, + AgentSkillReposTable, + AgentSkillVersionsTable, + AgentSyncJobsTable, AuditsTable, GitBotsTable, GitBotTasksTable, @@ -1398,6 +1726,38 @@ var ( ) func init() { + AgentPluginsTable.ForeignKeys[0].RefTable = AgentPluginReposTable + AgentPluginsTable.Annotation = &entsql.Annotation{ + Table: "agent_plugins", + } + AgentPluginReposTable.Annotation = &entsql.Annotation{ + Table: "agent_plugin_repos", + } + AgentPluginVersionsTable.ForeignKeys[0].RefTable = AgentPluginsTable + AgentPluginVersionsTable.Annotation = &entsql.Annotation{ + Table: "agent_plugin_versions", + } + AgentRulesTable.Annotation = &entsql.Annotation{ + Table: "agent_rules", + } + AgentRuleVersionsTable.ForeignKeys[0].RefTable = AgentRulesTable + AgentRuleVersionsTable.Annotation = &entsql.Annotation{ + Table: "agent_rule_versions", + } + AgentSkillsTable.ForeignKeys[0].RefTable = AgentSkillReposTable + AgentSkillsTable.Annotation = &entsql.Annotation{ + Table: "agent_skills", + } + AgentSkillReposTable.Annotation = &entsql.Annotation{ + Table: "agent_skill_repos", + } + AgentSkillVersionsTable.ForeignKeys[0].RefTable = AgentSkillsTable + AgentSkillVersionsTable.Annotation = &entsql.Annotation{ + Table: "agent_skill_versions", + } + AgentSyncJobsTable.Annotation = &entsql.Annotation{ + Table: "agent_sync_jobs", + } AuditsTable.ForeignKeys[0].RefTable = UsersTable AuditsTable.Annotation = &entsql.Annotation{ Table: "audits", diff --git a/backend/db/mutation.go b/backend/db/mutation.go index c201b380..5730f1f3 100644 --- a/backend/db/mutation.go +++ b/backend/db/mutation.go @@ -12,6 +12,15 @@ import ( "entgo.io/ent" "entgo.io/ent/dialect/sql" "github.com/chaitin/MonkeyCode/backend/consts" + "github.com/chaitin/MonkeyCode/backend/db/agentplugin" + "github.com/chaitin/MonkeyCode/backend/db/agentpluginrepo" + "github.com/chaitin/MonkeyCode/backend/db/agentpluginversion" + "github.com/chaitin/MonkeyCode/backend/db/agentrule" + "github.com/chaitin/MonkeyCode/backend/db/agentruleversion" + "github.com/chaitin/MonkeyCode/backend/db/agentskill" + "github.com/chaitin/MonkeyCode/backend/db/agentskillrepo" + "github.com/chaitin/MonkeyCode/backend/db/agentskillversion" + "github.com/chaitin/MonkeyCode/backend/db/agentsyncjob" "github.com/chaitin/MonkeyCode/backend/db/audit" "github.com/chaitin/MonkeyCode/backend/db/gitbot" "github.com/chaitin/MonkeyCode/backend/db/gitbottask" @@ -66,6 +75,15 @@ const ( OpUpdateOne = ent.OpUpdateOne // Node types. + TypeAgentPlugin = "AgentPlugin" + TypeAgentPluginRepo = "AgentPluginRepo" + TypeAgentPluginVersion = "AgentPluginVersion" + TypeAgentRule = "AgentRule" + TypeAgentRuleVersion = "AgentRuleVersion" + TypeAgentSkill = "AgentSkill" + TypeAgentSkillRepo = "AgentSkillRepo" + TypeAgentSkillVersion = "AgentSkillVersion" + TypeAgentSyncJob = "AgentSyncJob" TypeAudit = "Audit" TypeGitBot = "GitBot" TypeGitBotTask = "GitBotTask" @@ -108,6 +126,8776 @@ const ( TypeVirtualMachine = "VirtualMachine" ) +// AgentPluginMutation represents an operation that mutates the AgentPlugin nodes in the graph. +type AgentPluginMutation struct { + config + op Op + typ string + id *uuid.UUID + name *string + description *string + scope_type *agentplugin.ScopeType + scope_id *string + created_by *uuid.UUID + active_version_id *uuid.UUID + is_force_delivery *bool + is_orphan *bool + is_deleted *bool + created_at *time.Time + updated_at *time.Time + clearedFields map[string]struct{} + repo *uuid.UUID + clearedrepo bool + versions map[uuid.UUID]struct{} + removedversions map[uuid.UUID]struct{} + clearedversions bool + done bool + oldValue func(context.Context) (*AgentPlugin, error) + predicates []predicate.AgentPlugin +} + +var _ ent.Mutation = (*AgentPluginMutation)(nil) + +// agentpluginOption allows management of the mutation configuration using functional options. +type agentpluginOption func(*AgentPluginMutation) + +// newAgentPluginMutation creates new mutation for the AgentPlugin entity. +func newAgentPluginMutation(c config, op Op, opts ...agentpluginOption) *AgentPluginMutation { + m := &AgentPluginMutation{ + config: c, + op: op, + typ: TypeAgentPlugin, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withAgentPluginID sets the ID field of the mutation. +func withAgentPluginID(id uuid.UUID) agentpluginOption { + return func(m *AgentPluginMutation) { + var ( + err error + once sync.Once + value *AgentPlugin + ) + m.oldValue = func(ctx context.Context) (*AgentPlugin, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().AgentPlugin.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withAgentPlugin sets the old AgentPlugin of the mutation. +func withAgentPlugin(node *AgentPlugin) agentpluginOption { + return func(m *AgentPluginMutation) { + m.oldValue = func(context.Context) (*AgentPlugin, 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 AgentPluginMutation) 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 AgentPluginMutation) 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 AgentPlugin entities. +func (m *AgentPluginMutation) 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 *AgentPluginMutation) 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 *AgentPluginMutation) 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().AgentPlugin.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetRepoID sets the "repo_id" field. +func (m *AgentPluginMutation) SetRepoID(u uuid.UUID) { + m.repo = &u +} + +// RepoID returns the value of the "repo_id" field in the mutation. +func (m *AgentPluginMutation) RepoID() (r uuid.UUID, exists bool) { + v := m.repo + if v == nil { + return + } + return *v, true +} + +// OldRepoID returns the old "repo_id" field's value of the AgentPlugin entity. +// If the AgentPlugin 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 *AgentPluginMutation) OldRepoID(ctx context.Context) (v uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRepoID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRepoID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRepoID: %w", err) + } + return oldValue.RepoID, nil +} + +// ResetRepoID resets all changes to the "repo_id" field. +func (m *AgentPluginMutation) ResetRepoID() { + m.repo = nil +} + +// SetName sets the "name" field. +func (m *AgentPluginMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *AgentPluginMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the AgentPlugin entity. +// If the AgentPlugin 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 *AgentPluginMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *AgentPluginMutation) ResetName() { + m.name = nil +} + +// SetDescription sets the "description" field. +func (m *AgentPluginMutation) SetDescription(s string) { + m.description = &s +} + +// Description returns the value of the "description" field in the mutation. +func (m *AgentPluginMutation) Description() (r string, exists bool) { + v := m.description + if v == nil { + return + } + return *v, true +} + +// OldDescription returns the old "description" field's value of the AgentPlugin entity. +// If the AgentPlugin 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 *AgentPluginMutation) OldDescription(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDescription is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDescription requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDescription: %w", err) + } + return oldValue.Description, nil +} + +// ClearDescription clears the value of the "description" field. +func (m *AgentPluginMutation) ClearDescription() { + m.description = nil + m.clearedFields[agentplugin.FieldDescription] = struct{}{} +} + +// DescriptionCleared returns if the "description" field was cleared in this mutation. +func (m *AgentPluginMutation) DescriptionCleared() bool { + _, ok := m.clearedFields[agentplugin.FieldDescription] + return ok +} + +// ResetDescription resets all changes to the "description" field. +func (m *AgentPluginMutation) ResetDescription() { + m.description = nil + delete(m.clearedFields, agentplugin.FieldDescription) +} + +// SetScopeType sets the "scope_type" field. +func (m *AgentPluginMutation) SetScopeType(at agentplugin.ScopeType) { + m.scope_type = &at +} + +// ScopeType returns the value of the "scope_type" field in the mutation. +func (m *AgentPluginMutation) ScopeType() (r agentplugin.ScopeType, exists bool) { + v := m.scope_type + if v == nil { + return + } + return *v, true +} + +// OldScopeType returns the old "scope_type" field's value of the AgentPlugin entity. +// If the AgentPlugin 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 *AgentPluginMutation) OldScopeType(ctx context.Context) (v agentplugin.ScopeType, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldScopeType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldScopeType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldScopeType: %w", err) + } + return oldValue.ScopeType, nil +} + +// ResetScopeType resets all changes to the "scope_type" field. +func (m *AgentPluginMutation) ResetScopeType() { + m.scope_type = nil +} + +// SetScopeID sets the "scope_id" field. +func (m *AgentPluginMutation) SetScopeID(s string) { + m.scope_id = &s +} + +// ScopeID returns the value of the "scope_id" field in the mutation. +func (m *AgentPluginMutation) ScopeID() (r string, exists bool) { + v := m.scope_id + if v == nil { + return + } + return *v, true +} + +// OldScopeID returns the old "scope_id" field's value of the AgentPlugin entity. +// If the AgentPlugin 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 *AgentPluginMutation) OldScopeID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldScopeID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldScopeID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldScopeID: %w", err) + } + return oldValue.ScopeID, nil +} + +// ResetScopeID resets all changes to the "scope_id" field. +func (m *AgentPluginMutation) ResetScopeID() { + m.scope_id = nil +} + +// SetCreatedBy sets the "created_by" field. +func (m *AgentPluginMutation) SetCreatedBy(u uuid.UUID) { + m.created_by = &u +} + +// CreatedBy returns the value of the "created_by" field in the mutation. +func (m *AgentPluginMutation) CreatedBy() (r uuid.UUID, exists bool) { + v := m.created_by + if v == nil { + return + } + return *v, true +} + +// OldCreatedBy returns the old "created_by" field's value of the AgentPlugin entity. +// If the AgentPlugin 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 *AgentPluginMutation) OldCreatedBy(ctx context.Context) (v uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreatedBy is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreatedBy requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreatedBy: %w", err) + } + return oldValue.CreatedBy, nil +} + +// ResetCreatedBy resets all changes to the "created_by" field. +func (m *AgentPluginMutation) ResetCreatedBy() { + m.created_by = nil +} + +// SetActiveVersionID sets the "active_version_id" field. +func (m *AgentPluginMutation) SetActiveVersionID(u uuid.UUID) { + m.active_version_id = &u +} + +// ActiveVersionID returns the value of the "active_version_id" field in the mutation. +func (m *AgentPluginMutation) ActiveVersionID() (r uuid.UUID, exists bool) { + v := m.active_version_id + if v == nil { + return + } + return *v, true +} + +// OldActiveVersionID returns the old "active_version_id" field's value of the AgentPlugin entity. +// If the AgentPlugin 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 *AgentPluginMutation) OldActiveVersionID(ctx context.Context) (v *uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldActiveVersionID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldActiveVersionID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldActiveVersionID: %w", err) + } + return oldValue.ActiveVersionID, nil +} + +// ClearActiveVersionID clears the value of the "active_version_id" field. +func (m *AgentPluginMutation) ClearActiveVersionID() { + m.active_version_id = nil + m.clearedFields[agentplugin.FieldActiveVersionID] = struct{}{} +} + +// ActiveVersionIDCleared returns if the "active_version_id" field was cleared in this mutation. +func (m *AgentPluginMutation) ActiveVersionIDCleared() bool { + _, ok := m.clearedFields[agentplugin.FieldActiveVersionID] + return ok +} + +// ResetActiveVersionID resets all changes to the "active_version_id" field. +func (m *AgentPluginMutation) ResetActiveVersionID() { + m.active_version_id = nil + delete(m.clearedFields, agentplugin.FieldActiveVersionID) +} + +// SetIsForceDelivery sets the "is_force_delivery" field. +func (m *AgentPluginMutation) SetIsForceDelivery(b bool) { + m.is_force_delivery = &b +} + +// IsForceDelivery returns the value of the "is_force_delivery" field in the mutation. +func (m *AgentPluginMutation) IsForceDelivery() (r bool, exists bool) { + v := m.is_force_delivery + if v == nil { + return + } + return *v, true +} + +// OldIsForceDelivery returns the old "is_force_delivery" field's value of the AgentPlugin entity. +// If the AgentPlugin 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 *AgentPluginMutation) OldIsForceDelivery(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldIsForceDelivery is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldIsForceDelivery requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldIsForceDelivery: %w", err) + } + return oldValue.IsForceDelivery, nil +} + +// ResetIsForceDelivery resets all changes to the "is_force_delivery" field. +func (m *AgentPluginMutation) ResetIsForceDelivery() { + m.is_force_delivery = nil +} + +// SetIsOrphan sets the "is_orphan" field. +func (m *AgentPluginMutation) SetIsOrphan(b bool) { + m.is_orphan = &b +} + +// IsOrphan returns the value of the "is_orphan" field in the mutation. +func (m *AgentPluginMutation) IsOrphan() (r bool, exists bool) { + v := m.is_orphan + if v == nil { + return + } + return *v, true +} + +// OldIsOrphan returns the old "is_orphan" field's value of the AgentPlugin entity. +// If the AgentPlugin 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 *AgentPluginMutation) OldIsOrphan(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldIsOrphan is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldIsOrphan requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldIsOrphan: %w", err) + } + return oldValue.IsOrphan, nil +} + +// ResetIsOrphan resets all changes to the "is_orphan" field. +func (m *AgentPluginMutation) ResetIsOrphan() { + m.is_orphan = nil +} + +// SetIsDeleted sets the "is_deleted" field. +func (m *AgentPluginMutation) SetIsDeleted(b bool) { + m.is_deleted = &b +} + +// IsDeleted returns the value of the "is_deleted" field in the mutation. +func (m *AgentPluginMutation) IsDeleted() (r bool, exists bool) { + v := m.is_deleted + if v == nil { + return + } + return *v, true +} + +// OldIsDeleted returns the old "is_deleted" field's value of the AgentPlugin entity. +// If the AgentPlugin 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 *AgentPluginMutation) OldIsDeleted(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldIsDeleted is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldIsDeleted requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldIsDeleted: %w", err) + } + return oldValue.IsDeleted, nil +} + +// ResetIsDeleted resets all changes to the "is_deleted" field. +func (m *AgentPluginMutation) ResetIsDeleted() { + m.is_deleted = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *AgentPluginMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *AgentPluginMutation) 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 AgentPlugin entity. +// If the AgentPlugin 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 *AgentPluginMutation) 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 *AgentPluginMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *AgentPluginMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *AgentPluginMutation) UpdatedAt() (r time.Time, exists bool) { + v := m.updated_at + if v == nil { + return + } + return *v, true +} + +// OldUpdatedAt returns the old "updated_at" field's value of the AgentPlugin entity. +// If the AgentPlugin 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 *AgentPluginMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUpdatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) + } + return oldValue.UpdatedAt, nil +} + +// ResetUpdatedAt resets all changes to the "updated_at" field. +func (m *AgentPluginMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// ClearRepo clears the "repo" edge to the AgentPluginRepo entity. +func (m *AgentPluginMutation) ClearRepo() { + m.clearedrepo = true + m.clearedFields[agentplugin.FieldRepoID] = struct{}{} +} + +// RepoCleared reports if the "repo" edge to the AgentPluginRepo entity was cleared. +func (m *AgentPluginMutation) RepoCleared() bool { + return m.clearedrepo +} + +// RepoIDs returns the "repo" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// RepoID instead. It exists only for internal usage by the builders. +func (m *AgentPluginMutation) RepoIDs() (ids []uuid.UUID) { + if id := m.repo; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetRepo resets all changes to the "repo" edge. +func (m *AgentPluginMutation) ResetRepo() { + m.repo = nil + m.clearedrepo = false +} + +// AddVersionIDs adds the "versions" edge to the AgentPluginVersion entity by ids. +func (m *AgentPluginMutation) AddVersionIDs(ids ...uuid.UUID) { + if m.versions == nil { + m.versions = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.versions[ids[i]] = struct{}{} + } +} + +// ClearVersions clears the "versions" edge to the AgentPluginVersion entity. +func (m *AgentPluginMutation) ClearVersions() { + m.clearedversions = true +} + +// VersionsCleared reports if the "versions" edge to the AgentPluginVersion entity was cleared. +func (m *AgentPluginMutation) VersionsCleared() bool { + return m.clearedversions +} + +// RemoveVersionIDs removes the "versions" edge to the AgentPluginVersion entity by IDs. +func (m *AgentPluginMutation) RemoveVersionIDs(ids ...uuid.UUID) { + if m.removedversions == nil { + m.removedversions = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.versions, ids[i]) + m.removedversions[ids[i]] = struct{}{} + } +} + +// RemovedVersions returns the removed IDs of the "versions" edge to the AgentPluginVersion entity. +func (m *AgentPluginMutation) RemovedVersionsIDs() (ids []uuid.UUID) { + for id := range m.removedversions { + ids = append(ids, id) + } + return +} + +// VersionsIDs returns the "versions" edge IDs in the mutation. +func (m *AgentPluginMutation) VersionsIDs() (ids []uuid.UUID) { + for id := range m.versions { + ids = append(ids, id) + } + return +} + +// ResetVersions resets all changes to the "versions" edge. +func (m *AgentPluginMutation) ResetVersions() { + m.versions = nil + m.clearedversions = false + m.removedversions = nil +} + +// Where appends a list predicates to the AgentPluginMutation builder. +func (m *AgentPluginMutation) Where(ps ...predicate.AgentPlugin) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the AgentPluginMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *AgentPluginMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.AgentPlugin, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *AgentPluginMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *AgentPluginMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (AgentPlugin). +func (m *AgentPluginMutation) 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 *AgentPluginMutation) Fields() []string { + fields := make([]string, 0, 12) + if m.repo != nil { + fields = append(fields, agentplugin.FieldRepoID) + } + if m.name != nil { + fields = append(fields, agentplugin.FieldName) + } + if m.description != nil { + fields = append(fields, agentplugin.FieldDescription) + } + if m.scope_type != nil { + fields = append(fields, agentplugin.FieldScopeType) + } + if m.scope_id != nil { + fields = append(fields, agentplugin.FieldScopeID) + } + if m.created_by != nil { + fields = append(fields, agentplugin.FieldCreatedBy) + } + if m.active_version_id != nil { + fields = append(fields, agentplugin.FieldActiveVersionID) + } + if m.is_force_delivery != nil { + fields = append(fields, agentplugin.FieldIsForceDelivery) + } + if m.is_orphan != nil { + fields = append(fields, agentplugin.FieldIsOrphan) + } + if m.is_deleted != nil { + fields = append(fields, agentplugin.FieldIsDeleted) + } + if m.created_at != nil { + fields = append(fields, agentplugin.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, agentplugin.FieldUpdatedAt) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *AgentPluginMutation) Field(name string) (ent.Value, bool) { + switch name { + case agentplugin.FieldRepoID: + return m.RepoID() + case agentplugin.FieldName: + return m.Name() + case agentplugin.FieldDescription: + return m.Description() + case agentplugin.FieldScopeType: + return m.ScopeType() + case agentplugin.FieldScopeID: + return m.ScopeID() + case agentplugin.FieldCreatedBy: + return m.CreatedBy() + case agentplugin.FieldActiveVersionID: + return m.ActiveVersionID() + case agentplugin.FieldIsForceDelivery: + return m.IsForceDelivery() + case agentplugin.FieldIsOrphan: + return m.IsOrphan() + case agentplugin.FieldIsDeleted: + return m.IsDeleted() + case agentplugin.FieldCreatedAt: + return m.CreatedAt() + case agentplugin.FieldUpdatedAt: + return m.UpdatedAt() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *AgentPluginMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case agentplugin.FieldRepoID: + return m.OldRepoID(ctx) + case agentplugin.FieldName: + return m.OldName(ctx) + case agentplugin.FieldDescription: + return m.OldDescription(ctx) + case agentplugin.FieldScopeType: + return m.OldScopeType(ctx) + case agentplugin.FieldScopeID: + return m.OldScopeID(ctx) + case agentplugin.FieldCreatedBy: + return m.OldCreatedBy(ctx) + case agentplugin.FieldActiveVersionID: + return m.OldActiveVersionID(ctx) + case agentplugin.FieldIsForceDelivery: + return m.OldIsForceDelivery(ctx) + case agentplugin.FieldIsOrphan: + return m.OldIsOrphan(ctx) + case agentplugin.FieldIsDeleted: + return m.OldIsDeleted(ctx) + case agentplugin.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case agentplugin.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + } + return nil, fmt.Errorf("unknown AgentPlugin 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 *AgentPluginMutation) SetField(name string, value ent.Value) error { + switch name { + case agentplugin.FieldRepoID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRepoID(v) + return nil + case agentplugin.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case agentplugin.FieldDescription: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDescription(v) + return nil + case agentplugin.FieldScopeType: + v, ok := value.(agentplugin.ScopeType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetScopeType(v) + return nil + case agentplugin.FieldScopeID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetScopeID(v) + return nil + case agentplugin.FieldCreatedBy: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedBy(v) + return nil + case agentplugin.FieldActiveVersionID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetActiveVersionID(v) + return nil + case agentplugin.FieldIsForceDelivery: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIsForceDelivery(v) + return nil + case agentplugin.FieldIsOrphan: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIsOrphan(v) + return nil + case agentplugin.FieldIsDeleted: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIsDeleted(v) + return nil + case agentplugin.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + case agentplugin.FieldUpdatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdatedAt(v) + return nil + } + return fmt.Errorf("unknown AgentPlugin field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *AgentPluginMutation) 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 *AgentPluginMutation) 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 *AgentPluginMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown AgentPlugin numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *AgentPluginMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(agentplugin.FieldDescription) { + fields = append(fields, agentplugin.FieldDescription) + } + if m.FieldCleared(agentplugin.FieldActiveVersionID) { + fields = append(fields, agentplugin.FieldActiveVersionID) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *AgentPluginMutation) 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 *AgentPluginMutation) ClearField(name string) error { + switch name { + case agentplugin.FieldDescription: + m.ClearDescription() + return nil + case agentplugin.FieldActiveVersionID: + m.ClearActiveVersionID() + return nil + } + return fmt.Errorf("unknown AgentPlugin 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 *AgentPluginMutation) ResetField(name string) error { + switch name { + case agentplugin.FieldRepoID: + m.ResetRepoID() + return nil + case agentplugin.FieldName: + m.ResetName() + return nil + case agentplugin.FieldDescription: + m.ResetDescription() + return nil + case agentplugin.FieldScopeType: + m.ResetScopeType() + return nil + case agentplugin.FieldScopeID: + m.ResetScopeID() + return nil + case agentplugin.FieldCreatedBy: + m.ResetCreatedBy() + return nil + case agentplugin.FieldActiveVersionID: + m.ResetActiveVersionID() + return nil + case agentplugin.FieldIsForceDelivery: + m.ResetIsForceDelivery() + return nil + case agentplugin.FieldIsOrphan: + m.ResetIsOrphan() + return nil + case agentplugin.FieldIsDeleted: + m.ResetIsDeleted() + return nil + case agentplugin.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case agentplugin.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + } + return fmt.Errorf("unknown AgentPlugin field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *AgentPluginMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.repo != nil { + edges = append(edges, agentplugin.EdgeRepo) + } + if m.versions != nil { + edges = append(edges, agentplugin.EdgeVersions) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *AgentPluginMutation) AddedIDs(name string) []ent.Value { + switch name { + case agentplugin.EdgeRepo: + if id := m.repo; id != nil { + return []ent.Value{*id} + } + case agentplugin.EdgeVersions: + ids := make([]ent.Value, 0, len(m.versions)) + for id := range m.versions { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *AgentPluginMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + if m.removedversions != nil { + edges = append(edges, agentplugin.EdgeVersions) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *AgentPluginMutation) RemovedIDs(name string) []ent.Value { + switch name { + case agentplugin.EdgeVersions: + ids := make([]ent.Value, 0, len(m.removedversions)) + for id := range m.removedversions { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *AgentPluginMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedrepo { + edges = append(edges, agentplugin.EdgeRepo) + } + if m.clearedversions { + edges = append(edges, agentplugin.EdgeVersions) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *AgentPluginMutation) EdgeCleared(name string) bool { + switch name { + case agentplugin.EdgeRepo: + return m.clearedrepo + case agentplugin.EdgeVersions: + return m.clearedversions + } + 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 *AgentPluginMutation) ClearEdge(name string) error { + switch name { + case agentplugin.EdgeRepo: + m.ClearRepo() + return nil + } + return fmt.Errorf("unknown AgentPlugin 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 *AgentPluginMutation) ResetEdge(name string) error { + switch name { + case agentplugin.EdgeRepo: + m.ResetRepo() + return nil + case agentplugin.EdgeVersions: + m.ResetVersions() + return nil + } + return fmt.Errorf("unknown AgentPlugin edge %s", name) +} + +// AgentPluginRepoMutation represents an operation that mutates the AgentPluginRepo nodes in the graph. +type AgentPluginRepoMutation struct { + config + op Op + typ string + id *uuid.UUID + name *string + scope_type *agentpluginrepo.ScopeType + scope_id *string + created_by *uuid.UUID + source_type *agentpluginrepo.SourceType + github_url *string + ref_type *agentpluginrepo.RefType + ref_value *string + last_upload_filename *string + last_upload_at *time.Time + plugin_discovery_auto_package_json *bool + plugin_manual_entries *types.PluginManualEntries + appendplugin_manual_entries types.PluginManualEntries + npm_package_name *string + npm_version_spec *string + npm_registry_url *string + is_deleted *bool + created_at *time.Time + updated_at *time.Time + clearedFields map[string]struct{} + plugins map[uuid.UUID]struct{} + removedplugins map[uuid.UUID]struct{} + clearedplugins bool + done bool + oldValue func(context.Context) (*AgentPluginRepo, error) + predicates []predicate.AgentPluginRepo +} + +var _ ent.Mutation = (*AgentPluginRepoMutation)(nil) + +// agentpluginrepoOption allows management of the mutation configuration using functional options. +type agentpluginrepoOption func(*AgentPluginRepoMutation) + +// newAgentPluginRepoMutation creates new mutation for the AgentPluginRepo entity. +func newAgentPluginRepoMutation(c config, op Op, opts ...agentpluginrepoOption) *AgentPluginRepoMutation { + m := &AgentPluginRepoMutation{ + config: c, + op: op, + typ: TypeAgentPluginRepo, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withAgentPluginRepoID sets the ID field of the mutation. +func withAgentPluginRepoID(id uuid.UUID) agentpluginrepoOption { + return func(m *AgentPluginRepoMutation) { + var ( + err error + once sync.Once + value *AgentPluginRepo + ) + m.oldValue = func(ctx context.Context) (*AgentPluginRepo, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().AgentPluginRepo.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withAgentPluginRepo sets the old AgentPluginRepo of the mutation. +func withAgentPluginRepo(node *AgentPluginRepo) agentpluginrepoOption { + return func(m *AgentPluginRepoMutation) { + m.oldValue = func(context.Context) (*AgentPluginRepo, 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 AgentPluginRepoMutation) 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 AgentPluginRepoMutation) 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 AgentPluginRepo entities. +func (m *AgentPluginRepoMutation) 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 *AgentPluginRepoMutation) 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 *AgentPluginRepoMutation) 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().AgentPluginRepo.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetName sets the "name" field. +func (m *AgentPluginRepoMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *AgentPluginRepoMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the AgentPluginRepo entity. +// If the AgentPluginRepo 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 *AgentPluginRepoMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *AgentPluginRepoMutation) ResetName() { + m.name = nil +} + +// SetScopeType sets the "scope_type" field. +func (m *AgentPluginRepoMutation) SetScopeType(at agentpluginrepo.ScopeType) { + m.scope_type = &at +} + +// ScopeType returns the value of the "scope_type" field in the mutation. +func (m *AgentPluginRepoMutation) ScopeType() (r agentpluginrepo.ScopeType, exists bool) { + v := m.scope_type + if v == nil { + return + } + return *v, true +} + +// OldScopeType returns the old "scope_type" field's value of the AgentPluginRepo entity. +// If the AgentPluginRepo 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 *AgentPluginRepoMutation) OldScopeType(ctx context.Context) (v agentpluginrepo.ScopeType, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldScopeType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldScopeType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldScopeType: %w", err) + } + return oldValue.ScopeType, nil +} + +// ResetScopeType resets all changes to the "scope_type" field. +func (m *AgentPluginRepoMutation) ResetScopeType() { + m.scope_type = nil +} + +// SetScopeID sets the "scope_id" field. +func (m *AgentPluginRepoMutation) SetScopeID(s string) { + m.scope_id = &s +} + +// ScopeID returns the value of the "scope_id" field in the mutation. +func (m *AgentPluginRepoMutation) ScopeID() (r string, exists bool) { + v := m.scope_id + if v == nil { + return + } + return *v, true +} + +// OldScopeID returns the old "scope_id" field's value of the AgentPluginRepo entity. +// If the AgentPluginRepo 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 *AgentPluginRepoMutation) OldScopeID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldScopeID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldScopeID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldScopeID: %w", err) + } + return oldValue.ScopeID, nil +} + +// ResetScopeID resets all changes to the "scope_id" field. +func (m *AgentPluginRepoMutation) ResetScopeID() { + m.scope_id = nil +} + +// SetCreatedBy sets the "created_by" field. +func (m *AgentPluginRepoMutation) SetCreatedBy(u uuid.UUID) { + m.created_by = &u +} + +// CreatedBy returns the value of the "created_by" field in the mutation. +func (m *AgentPluginRepoMutation) CreatedBy() (r uuid.UUID, exists bool) { + v := m.created_by + if v == nil { + return + } + return *v, true +} + +// OldCreatedBy returns the old "created_by" field's value of the AgentPluginRepo entity. +// If the AgentPluginRepo 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 *AgentPluginRepoMutation) OldCreatedBy(ctx context.Context) (v uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreatedBy is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreatedBy requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreatedBy: %w", err) + } + return oldValue.CreatedBy, nil +} + +// ResetCreatedBy resets all changes to the "created_by" field. +func (m *AgentPluginRepoMutation) ResetCreatedBy() { + m.created_by = nil +} + +// SetSourceType sets the "source_type" field. +func (m *AgentPluginRepoMutation) SetSourceType(at agentpluginrepo.SourceType) { + m.source_type = &at +} + +// SourceType returns the value of the "source_type" field in the mutation. +func (m *AgentPluginRepoMutation) SourceType() (r agentpluginrepo.SourceType, exists bool) { + v := m.source_type + if v == nil { + return + } + return *v, true +} + +// OldSourceType returns the old "source_type" field's value of the AgentPluginRepo entity. +// If the AgentPluginRepo 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 *AgentPluginRepoMutation) OldSourceType(ctx context.Context) (v agentpluginrepo.SourceType, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSourceType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSourceType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSourceType: %w", err) + } + return oldValue.SourceType, nil +} + +// ResetSourceType resets all changes to the "source_type" field. +func (m *AgentPluginRepoMutation) ResetSourceType() { + m.source_type = nil +} + +// SetGithubURL sets the "github_url" field. +func (m *AgentPluginRepoMutation) SetGithubURL(s string) { + m.github_url = &s +} + +// GithubURL returns the value of the "github_url" field in the mutation. +func (m *AgentPluginRepoMutation) GithubURL() (r string, exists bool) { + v := m.github_url + if v == nil { + return + } + return *v, true +} + +// OldGithubURL returns the old "github_url" field's value of the AgentPluginRepo entity. +// If the AgentPluginRepo 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 *AgentPluginRepoMutation) OldGithubURL(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldGithubURL is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldGithubURL requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldGithubURL: %w", err) + } + return oldValue.GithubURL, nil +} + +// ClearGithubURL clears the value of the "github_url" field. +func (m *AgentPluginRepoMutation) ClearGithubURL() { + m.github_url = nil + m.clearedFields[agentpluginrepo.FieldGithubURL] = struct{}{} +} + +// GithubURLCleared returns if the "github_url" field was cleared in this mutation. +func (m *AgentPluginRepoMutation) GithubURLCleared() bool { + _, ok := m.clearedFields[agentpluginrepo.FieldGithubURL] + return ok +} + +// ResetGithubURL resets all changes to the "github_url" field. +func (m *AgentPluginRepoMutation) ResetGithubURL() { + m.github_url = nil + delete(m.clearedFields, agentpluginrepo.FieldGithubURL) +} + +// SetRefType sets the "ref_type" field. +func (m *AgentPluginRepoMutation) SetRefType(at agentpluginrepo.RefType) { + m.ref_type = &at +} + +// RefType returns the value of the "ref_type" field in the mutation. +func (m *AgentPluginRepoMutation) RefType() (r agentpluginrepo.RefType, exists bool) { + v := m.ref_type + if v == nil { + return + } + return *v, true +} + +// OldRefType returns the old "ref_type" field's value of the AgentPluginRepo entity. +// If the AgentPluginRepo 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 *AgentPluginRepoMutation) OldRefType(ctx context.Context) (v *agentpluginrepo.RefType, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRefType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRefType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRefType: %w", err) + } + return oldValue.RefType, nil +} + +// ClearRefType clears the value of the "ref_type" field. +func (m *AgentPluginRepoMutation) ClearRefType() { + m.ref_type = nil + m.clearedFields[agentpluginrepo.FieldRefType] = struct{}{} +} + +// RefTypeCleared returns if the "ref_type" field was cleared in this mutation. +func (m *AgentPluginRepoMutation) RefTypeCleared() bool { + _, ok := m.clearedFields[agentpluginrepo.FieldRefType] + return ok +} + +// ResetRefType resets all changes to the "ref_type" field. +func (m *AgentPluginRepoMutation) ResetRefType() { + m.ref_type = nil + delete(m.clearedFields, agentpluginrepo.FieldRefType) +} + +// SetRefValue sets the "ref_value" field. +func (m *AgentPluginRepoMutation) SetRefValue(s string) { + m.ref_value = &s +} + +// RefValue returns the value of the "ref_value" field in the mutation. +func (m *AgentPluginRepoMutation) RefValue() (r string, exists bool) { + v := m.ref_value + if v == nil { + return + } + return *v, true +} + +// OldRefValue returns the old "ref_value" field's value of the AgentPluginRepo entity. +// If the AgentPluginRepo 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 *AgentPluginRepoMutation) OldRefValue(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRefValue is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRefValue requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRefValue: %w", err) + } + return oldValue.RefValue, nil +} + +// ClearRefValue clears the value of the "ref_value" field. +func (m *AgentPluginRepoMutation) ClearRefValue() { + m.ref_value = nil + m.clearedFields[agentpluginrepo.FieldRefValue] = struct{}{} +} + +// RefValueCleared returns if the "ref_value" field was cleared in this mutation. +func (m *AgentPluginRepoMutation) RefValueCleared() bool { + _, ok := m.clearedFields[agentpluginrepo.FieldRefValue] + return ok +} + +// ResetRefValue resets all changes to the "ref_value" field. +func (m *AgentPluginRepoMutation) ResetRefValue() { + m.ref_value = nil + delete(m.clearedFields, agentpluginrepo.FieldRefValue) +} + +// SetLastUploadFilename sets the "last_upload_filename" field. +func (m *AgentPluginRepoMutation) SetLastUploadFilename(s string) { + m.last_upload_filename = &s +} + +// LastUploadFilename returns the value of the "last_upload_filename" field in the mutation. +func (m *AgentPluginRepoMutation) LastUploadFilename() (r string, exists bool) { + v := m.last_upload_filename + if v == nil { + return + } + return *v, true +} + +// OldLastUploadFilename returns the old "last_upload_filename" field's value of the AgentPluginRepo entity. +// If the AgentPluginRepo 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 *AgentPluginRepoMutation) OldLastUploadFilename(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldLastUploadFilename is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldLastUploadFilename requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldLastUploadFilename: %w", err) + } + return oldValue.LastUploadFilename, nil +} + +// ClearLastUploadFilename clears the value of the "last_upload_filename" field. +func (m *AgentPluginRepoMutation) ClearLastUploadFilename() { + m.last_upload_filename = nil + m.clearedFields[agentpluginrepo.FieldLastUploadFilename] = struct{}{} +} + +// LastUploadFilenameCleared returns if the "last_upload_filename" field was cleared in this mutation. +func (m *AgentPluginRepoMutation) LastUploadFilenameCleared() bool { + _, ok := m.clearedFields[agentpluginrepo.FieldLastUploadFilename] + return ok +} + +// ResetLastUploadFilename resets all changes to the "last_upload_filename" field. +func (m *AgentPluginRepoMutation) ResetLastUploadFilename() { + m.last_upload_filename = nil + delete(m.clearedFields, agentpluginrepo.FieldLastUploadFilename) +} + +// SetLastUploadAt sets the "last_upload_at" field. +func (m *AgentPluginRepoMutation) SetLastUploadAt(t time.Time) { + m.last_upload_at = &t +} + +// LastUploadAt returns the value of the "last_upload_at" field in the mutation. +func (m *AgentPluginRepoMutation) LastUploadAt() (r time.Time, exists bool) { + v := m.last_upload_at + if v == nil { + return + } + return *v, true +} + +// OldLastUploadAt returns the old "last_upload_at" field's value of the AgentPluginRepo entity. +// If the AgentPluginRepo 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 *AgentPluginRepoMutation) OldLastUploadAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldLastUploadAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldLastUploadAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldLastUploadAt: %w", err) + } + return oldValue.LastUploadAt, nil +} + +// ClearLastUploadAt clears the value of the "last_upload_at" field. +func (m *AgentPluginRepoMutation) ClearLastUploadAt() { + m.last_upload_at = nil + m.clearedFields[agentpluginrepo.FieldLastUploadAt] = struct{}{} +} + +// LastUploadAtCleared returns if the "last_upload_at" field was cleared in this mutation. +func (m *AgentPluginRepoMutation) LastUploadAtCleared() bool { + _, ok := m.clearedFields[agentpluginrepo.FieldLastUploadAt] + return ok +} + +// ResetLastUploadAt resets all changes to the "last_upload_at" field. +func (m *AgentPluginRepoMutation) ResetLastUploadAt() { + m.last_upload_at = nil + delete(m.clearedFields, agentpluginrepo.FieldLastUploadAt) +} + +// SetPluginDiscoveryAutoPackageJSON sets the "plugin_discovery_auto_package_json" field. +func (m *AgentPluginRepoMutation) SetPluginDiscoveryAutoPackageJSON(b bool) { + m.plugin_discovery_auto_package_json = &b +} + +// PluginDiscoveryAutoPackageJSON returns the value of the "plugin_discovery_auto_package_json" field in the mutation. +func (m *AgentPluginRepoMutation) PluginDiscoveryAutoPackageJSON() (r bool, exists bool) { + v := m.plugin_discovery_auto_package_json + if v == nil { + return + } + return *v, true +} + +// OldPluginDiscoveryAutoPackageJSON returns the old "plugin_discovery_auto_package_json" field's value of the AgentPluginRepo entity. +// If the AgentPluginRepo 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 *AgentPluginRepoMutation) OldPluginDiscoveryAutoPackageJSON(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPluginDiscoveryAutoPackageJSON is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPluginDiscoveryAutoPackageJSON requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPluginDiscoveryAutoPackageJSON: %w", err) + } + return oldValue.PluginDiscoveryAutoPackageJSON, nil +} + +// ResetPluginDiscoveryAutoPackageJSON resets all changes to the "plugin_discovery_auto_package_json" field. +func (m *AgentPluginRepoMutation) ResetPluginDiscoveryAutoPackageJSON() { + m.plugin_discovery_auto_package_json = nil +} + +// SetPluginManualEntries sets the "plugin_manual_entries" field. +func (m *AgentPluginRepoMutation) SetPluginManualEntries(tme types.PluginManualEntries) { + m.plugin_manual_entries = &tme + m.appendplugin_manual_entries = nil +} + +// PluginManualEntries returns the value of the "plugin_manual_entries" field in the mutation. +func (m *AgentPluginRepoMutation) PluginManualEntries() (r types.PluginManualEntries, exists bool) { + v := m.plugin_manual_entries + if v == nil { + return + } + return *v, true +} + +// OldPluginManualEntries returns the old "plugin_manual_entries" field's value of the AgentPluginRepo entity. +// If the AgentPluginRepo 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 *AgentPluginRepoMutation) OldPluginManualEntries(ctx context.Context) (v types.PluginManualEntries, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPluginManualEntries is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPluginManualEntries requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPluginManualEntries: %w", err) + } + return oldValue.PluginManualEntries, nil +} + +// AppendPluginManualEntries adds tme to the "plugin_manual_entries" field. +func (m *AgentPluginRepoMutation) AppendPluginManualEntries(tme types.PluginManualEntries) { + m.appendplugin_manual_entries = append(m.appendplugin_manual_entries, tme...) +} + +// AppendedPluginManualEntries returns the list of values that were appended to the "plugin_manual_entries" field in this mutation. +func (m *AgentPluginRepoMutation) AppendedPluginManualEntries() (types.PluginManualEntries, bool) { + if len(m.appendplugin_manual_entries) == 0 { + return nil, false + } + return m.appendplugin_manual_entries, true +} + +// ClearPluginManualEntries clears the value of the "plugin_manual_entries" field. +func (m *AgentPluginRepoMutation) ClearPluginManualEntries() { + m.plugin_manual_entries = nil + m.appendplugin_manual_entries = nil + m.clearedFields[agentpluginrepo.FieldPluginManualEntries] = struct{}{} +} + +// PluginManualEntriesCleared returns if the "plugin_manual_entries" field was cleared in this mutation. +func (m *AgentPluginRepoMutation) PluginManualEntriesCleared() bool { + _, ok := m.clearedFields[agentpluginrepo.FieldPluginManualEntries] + return ok +} + +// ResetPluginManualEntries resets all changes to the "plugin_manual_entries" field. +func (m *AgentPluginRepoMutation) ResetPluginManualEntries() { + m.plugin_manual_entries = nil + m.appendplugin_manual_entries = nil + delete(m.clearedFields, agentpluginrepo.FieldPluginManualEntries) +} + +// SetNpmPackageName sets the "npm_package_name" field. +func (m *AgentPluginRepoMutation) SetNpmPackageName(s string) { + m.npm_package_name = &s +} + +// NpmPackageName returns the value of the "npm_package_name" field in the mutation. +func (m *AgentPluginRepoMutation) NpmPackageName() (r string, exists bool) { + v := m.npm_package_name + if v == nil { + return + } + return *v, true +} + +// OldNpmPackageName returns the old "npm_package_name" field's value of the AgentPluginRepo entity. +// If the AgentPluginRepo 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 *AgentPluginRepoMutation) OldNpmPackageName(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldNpmPackageName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldNpmPackageName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldNpmPackageName: %w", err) + } + return oldValue.NpmPackageName, nil +} + +// ClearNpmPackageName clears the value of the "npm_package_name" field. +func (m *AgentPluginRepoMutation) ClearNpmPackageName() { + m.npm_package_name = nil + m.clearedFields[agentpluginrepo.FieldNpmPackageName] = struct{}{} +} + +// NpmPackageNameCleared returns if the "npm_package_name" field was cleared in this mutation. +func (m *AgentPluginRepoMutation) NpmPackageNameCleared() bool { + _, ok := m.clearedFields[agentpluginrepo.FieldNpmPackageName] + return ok +} + +// ResetNpmPackageName resets all changes to the "npm_package_name" field. +func (m *AgentPluginRepoMutation) ResetNpmPackageName() { + m.npm_package_name = nil + delete(m.clearedFields, agentpluginrepo.FieldNpmPackageName) +} + +// SetNpmVersionSpec sets the "npm_version_spec" field. +func (m *AgentPluginRepoMutation) SetNpmVersionSpec(s string) { + m.npm_version_spec = &s +} + +// NpmVersionSpec returns the value of the "npm_version_spec" field in the mutation. +func (m *AgentPluginRepoMutation) NpmVersionSpec() (r string, exists bool) { + v := m.npm_version_spec + if v == nil { + return + } + return *v, true +} + +// OldNpmVersionSpec returns the old "npm_version_spec" field's value of the AgentPluginRepo entity. +// If the AgentPluginRepo 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 *AgentPluginRepoMutation) OldNpmVersionSpec(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldNpmVersionSpec is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldNpmVersionSpec requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldNpmVersionSpec: %w", err) + } + return oldValue.NpmVersionSpec, nil +} + +// ClearNpmVersionSpec clears the value of the "npm_version_spec" field. +func (m *AgentPluginRepoMutation) ClearNpmVersionSpec() { + m.npm_version_spec = nil + m.clearedFields[agentpluginrepo.FieldNpmVersionSpec] = struct{}{} +} + +// NpmVersionSpecCleared returns if the "npm_version_spec" field was cleared in this mutation. +func (m *AgentPluginRepoMutation) NpmVersionSpecCleared() bool { + _, ok := m.clearedFields[agentpluginrepo.FieldNpmVersionSpec] + return ok +} + +// ResetNpmVersionSpec resets all changes to the "npm_version_spec" field. +func (m *AgentPluginRepoMutation) ResetNpmVersionSpec() { + m.npm_version_spec = nil + delete(m.clearedFields, agentpluginrepo.FieldNpmVersionSpec) +} + +// SetNpmRegistryURL sets the "npm_registry_url" field. +func (m *AgentPluginRepoMutation) SetNpmRegistryURL(s string) { + m.npm_registry_url = &s +} + +// NpmRegistryURL returns the value of the "npm_registry_url" field in the mutation. +func (m *AgentPluginRepoMutation) NpmRegistryURL() (r string, exists bool) { + v := m.npm_registry_url + if v == nil { + return + } + return *v, true +} + +// OldNpmRegistryURL returns the old "npm_registry_url" field's value of the AgentPluginRepo entity. +// If the AgentPluginRepo 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 *AgentPluginRepoMutation) OldNpmRegistryURL(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldNpmRegistryURL is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldNpmRegistryURL requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldNpmRegistryURL: %w", err) + } + return oldValue.NpmRegistryURL, nil +} + +// ClearNpmRegistryURL clears the value of the "npm_registry_url" field. +func (m *AgentPluginRepoMutation) ClearNpmRegistryURL() { + m.npm_registry_url = nil + m.clearedFields[agentpluginrepo.FieldNpmRegistryURL] = struct{}{} +} + +// NpmRegistryURLCleared returns if the "npm_registry_url" field was cleared in this mutation. +func (m *AgentPluginRepoMutation) NpmRegistryURLCleared() bool { + _, ok := m.clearedFields[agentpluginrepo.FieldNpmRegistryURL] + return ok +} + +// ResetNpmRegistryURL resets all changes to the "npm_registry_url" field. +func (m *AgentPluginRepoMutation) ResetNpmRegistryURL() { + m.npm_registry_url = nil + delete(m.clearedFields, agentpluginrepo.FieldNpmRegistryURL) +} + +// SetIsDeleted sets the "is_deleted" field. +func (m *AgentPluginRepoMutation) SetIsDeleted(b bool) { + m.is_deleted = &b +} + +// IsDeleted returns the value of the "is_deleted" field in the mutation. +func (m *AgentPluginRepoMutation) IsDeleted() (r bool, exists bool) { + v := m.is_deleted + if v == nil { + return + } + return *v, true +} + +// OldIsDeleted returns the old "is_deleted" field's value of the AgentPluginRepo entity. +// If the AgentPluginRepo 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 *AgentPluginRepoMutation) OldIsDeleted(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldIsDeleted is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldIsDeleted requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldIsDeleted: %w", err) + } + return oldValue.IsDeleted, nil +} + +// ResetIsDeleted resets all changes to the "is_deleted" field. +func (m *AgentPluginRepoMutation) ResetIsDeleted() { + m.is_deleted = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *AgentPluginRepoMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *AgentPluginRepoMutation) 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 AgentPluginRepo entity. +// If the AgentPluginRepo 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 *AgentPluginRepoMutation) 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 *AgentPluginRepoMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *AgentPluginRepoMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *AgentPluginRepoMutation) UpdatedAt() (r time.Time, exists bool) { + v := m.updated_at + if v == nil { + return + } + return *v, true +} + +// OldUpdatedAt returns the old "updated_at" field's value of the AgentPluginRepo entity. +// If the AgentPluginRepo 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 *AgentPluginRepoMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUpdatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) + } + return oldValue.UpdatedAt, nil +} + +// ResetUpdatedAt resets all changes to the "updated_at" field. +func (m *AgentPluginRepoMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// AddPluginIDs adds the "plugins" edge to the AgentPlugin entity by ids. +func (m *AgentPluginRepoMutation) AddPluginIDs(ids ...uuid.UUID) { + if m.plugins == nil { + m.plugins = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.plugins[ids[i]] = struct{}{} + } +} + +// ClearPlugins clears the "plugins" edge to the AgentPlugin entity. +func (m *AgentPluginRepoMutation) ClearPlugins() { + m.clearedplugins = true +} + +// PluginsCleared reports if the "plugins" edge to the AgentPlugin entity was cleared. +func (m *AgentPluginRepoMutation) PluginsCleared() bool { + return m.clearedplugins +} + +// RemovePluginIDs removes the "plugins" edge to the AgentPlugin entity by IDs. +func (m *AgentPluginRepoMutation) RemovePluginIDs(ids ...uuid.UUID) { + if m.removedplugins == nil { + m.removedplugins = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.plugins, ids[i]) + m.removedplugins[ids[i]] = struct{}{} + } +} + +// RemovedPlugins returns the removed IDs of the "plugins" edge to the AgentPlugin entity. +func (m *AgentPluginRepoMutation) RemovedPluginsIDs() (ids []uuid.UUID) { + for id := range m.removedplugins { + ids = append(ids, id) + } + return +} + +// PluginsIDs returns the "plugins" edge IDs in the mutation. +func (m *AgentPluginRepoMutation) PluginsIDs() (ids []uuid.UUID) { + for id := range m.plugins { + ids = append(ids, id) + } + return +} + +// ResetPlugins resets all changes to the "plugins" edge. +func (m *AgentPluginRepoMutation) ResetPlugins() { + m.plugins = nil + m.clearedplugins = false + m.removedplugins = nil +} + +// Where appends a list predicates to the AgentPluginRepoMutation builder. +func (m *AgentPluginRepoMutation) Where(ps ...predicate.AgentPluginRepo) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the AgentPluginRepoMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *AgentPluginRepoMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.AgentPluginRepo, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *AgentPluginRepoMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *AgentPluginRepoMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (AgentPluginRepo). +func (m *AgentPluginRepoMutation) 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 *AgentPluginRepoMutation) Fields() []string { + fields := make([]string, 0, 18) + if m.name != nil { + fields = append(fields, agentpluginrepo.FieldName) + } + if m.scope_type != nil { + fields = append(fields, agentpluginrepo.FieldScopeType) + } + if m.scope_id != nil { + fields = append(fields, agentpluginrepo.FieldScopeID) + } + if m.created_by != nil { + fields = append(fields, agentpluginrepo.FieldCreatedBy) + } + if m.source_type != nil { + fields = append(fields, agentpluginrepo.FieldSourceType) + } + if m.github_url != nil { + fields = append(fields, agentpluginrepo.FieldGithubURL) + } + if m.ref_type != nil { + fields = append(fields, agentpluginrepo.FieldRefType) + } + if m.ref_value != nil { + fields = append(fields, agentpluginrepo.FieldRefValue) + } + if m.last_upload_filename != nil { + fields = append(fields, agentpluginrepo.FieldLastUploadFilename) + } + if m.last_upload_at != nil { + fields = append(fields, agentpluginrepo.FieldLastUploadAt) + } + if m.plugin_discovery_auto_package_json != nil { + fields = append(fields, agentpluginrepo.FieldPluginDiscoveryAutoPackageJSON) + } + if m.plugin_manual_entries != nil { + fields = append(fields, agentpluginrepo.FieldPluginManualEntries) + } + if m.npm_package_name != nil { + fields = append(fields, agentpluginrepo.FieldNpmPackageName) + } + if m.npm_version_spec != nil { + fields = append(fields, agentpluginrepo.FieldNpmVersionSpec) + } + if m.npm_registry_url != nil { + fields = append(fields, agentpluginrepo.FieldNpmRegistryURL) + } + if m.is_deleted != nil { + fields = append(fields, agentpluginrepo.FieldIsDeleted) + } + if m.created_at != nil { + fields = append(fields, agentpluginrepo.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, agentpluginrepo.FieldUpdatedAt) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *AgentPluginRepoMutation) Field(name string) (ent.Value, bool) { + switch name { + case agentpluginrepo.FieldName: + return m.Name() + case agentpluginrepo.FieldScopeType: + return m.ScopeType() + case agentpluginrepo.FieldScopeID: + return m.ScopeID() + case agentpluginrepo.FieldCreatedBy: + return m.CreatedBy() + case agentpluginrepo.FieldSourceType: + return m.SourceType() + case agentpluginrepo.FieldGithubURL: + return m.GithubURL() + case agentpluginrepo.FieldRefType: + return m.RefType() + case agentpluginrepo.FieldRefValue: + return m.RefValue() + case agentpluginrepo.FieldLastUploadFilename: + return m.LastUploadFilename() + case agentpluginrepo.FieldLastUploadAt: + return m.LastUploadAt() + case agentpluginrepo.FieldPluginDiscoveryAutoPackageJSON: + return m.PluginDiscoveryAutoPackageJSON() + case agentpluginrepo.FieldPluginManualEntries: + return m.PluginManualEntries() + case agentpluginrepo.FieldNpmPackageName: + return m.NpmPackageName() + case agentpluginrepo.FieldNpmVersionSpec: + return m.NpmVersionSpec() + case agentpluginrepo.FieldNpmRegistryURL: + return m.NpmRegistryURL() + case agentpluginrepo.FieldIsDeleted: + return m.IsDeleted() + case agentpluginrepo.FieldCreatedAt: + return m.CreatedAt() + case agentpluginrepo.FieldUpdatedAt: + return m.UpdatedAt() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *AgentPluginRepoMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case agentpluginrepo.FieldName: + return m.OldName(ctx) + case agentpluginrepo.FieldScopeType: + return m.OldScopeType(ctx) + case agentpluginrepo.FieldScopeID: + return m.OldScopeID(ctx) + case agentpluginrepo.FieldCreatedBy: + return m.OldCreatedBy(ctx) + case agentpluginrepo.FieldSourceType: + return m.OldSourceType(ctx) + case agentpluginrepo.FieldGithubURL: + return m.OldGithubURL(ctx) + case agentpluginrepo.FieldRefType: + return m.OldRefType(ctx) + case agentpluginrepo.FieldRefValue: + return m.OldRefValue(ctx) + case agentpluginrepo.FieldLastUploadFilename: + return m.OldLastUploadFilename(ctx) + case agentpluginrepo.FieldLastUploadAt: + return m.OldLastUploadAt(ctx) + case agentpluginrepo.FieldPluginDiscoveryAutoPackageJSON: + return m.OldPluginDiscoveryAutoPackageJSON(ctx) + case agentpluginrepo.FieldPluginManualEntries: + return m.OldPluginManualEntries(ctx) + case agentpluginrepo.FieldNpmPackageName: + return m.OldNpmPackageName(ctx) + case agentpluginrepo.FieldNpmVersionSpec: + return m.OldNpmVersionSpec(ctx) + case agentpluginrepo.FieldNpmRegistryURL: + return m.OldNpmRegistryURL(ctx) + case agentpluginrepo.FieldIsDeleted: + return m.OldIsDeleted(ctx) + case agentpluginrepo.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case agentpluginrepo.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + } + return nil, fmt.Errorf("unknown AgentPluginRepo 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 *AgentPluginRepoMutation) SetField(name string, value ent.Value) error { + switch name { + case agentpluginrepo.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case agentpluginrepo.FieldScopeType: + v, ok := value.(agentpluginrepo.ScopeType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetScopeType(v) + return nil + case agentpluginrepo.FieldScopeID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetScopeID(v) + return nil + case agentpluginrepo.FieldCreatedBy: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedBy(v) + return nil + case agentpluginrepo.FieldSourceType: + v, ok := value.(agentpluginrepo.SourceType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSourceType(v) + return nil + case agentpluginrepo.FieldGithubURL: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetGithubURL(v) + return nil + case agentpluginrepo.FieldRefType: + v, ok := value.(agentpluginrepo.RefType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRefType(v) + return nil + case agentpluginrepo.FieldRefValue: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRefValue(v) + return nil + case agentpluginrepo.FieldLastUploadFilename: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLastUploadFilename(v) + return nil + case agentpluginrepo.FieldLastUploadAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLastUploadAt(v) + return nil + case agentpluginrepo.FieldPluginDiscoveryAutoPackageJSON: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPluginDiscoveryAutoPackageJSON(v) + return nil + case agentpluginrepo.FieldPluginManualEntries: + v, ok := value.(types.PluginManualEntries) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPluginManualEntries(v) + return nil + case agentpluginrepo.FieldNpmPackageName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNpmPackageName(v) + return nil + case agentpluginrepo.FieldNpmVersionSpec: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNpmVersionSpec(v) + return nil + case agentpluginrepo.FieldNpmRegistryURL: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNpmRegistryURL(v) + return nil + case agentpluginrepo.FieldIsDeleted: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIsDeleted(v) + return nil + case agentpluginrepo.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + case agentpluginrepo.FieldUpdatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdatedAt(v) + return nil + } + return fmt.Errorf("unknown AgentPluginRepo field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *AgentPluginRepoMutation) 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 *AgentPluginRepoMutation) 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 *AgentPluginRepoMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown AgentPluginRepo numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *AgentPluginRepoMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(agentpluginrepo.FieldGithubURL) { + fields = append(fields, agentpluginrepo.FieldGithubURL) + } + if m.FieldCleared(agentpluginrepo.FieldRefType) { + fields = append(fields, agentpluginrepo.FieldRefType) + } + if m.FieldCleared(agentpluginrepo.FieldRefValue) { + fields = append(fields, agentpluginrepo.FieldRefValue) + } + if m.FieldCleared(agentpluginrepo.FieldLastUploadFilename) { + fields = append(fields, agentpluginrepo.FieldLastUploadFilename) + } + if m.FieldCleared(agentpluginrepo.FieldLastUploadAt) { + fields = append(fields, agentpluginrepo.FieldLastUploadAt) + } + if m.FieldCleared(agentpluginrepo.FieldPluginManualEntries) { + fields = append(fields, agentpluginrepo.FieldPluginManualEntries) + } + if m.FieldCleared(agentpluginrepo.FieldNpmPackageName) { + fields = append(fields, agentpluginrepo.FieldNpmPackageName) + } + if m.FieldCleared(agentpluginrepo.FieldNpmVersionSpec) { + fields = append(fields, agentpluginrepo.FieldNpmVersionSpec) + } + if m.FieldCleared(agentpluginrepo.FieldNpmRegistryURL) { + fields = append(fields, agentpluginrepo.FieldNpmRegistryURL) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *AgentPluginRepoMutation) 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 *AgentPluginRepoMutation) ClearField(name string) error { + switch name { + case agentpluginrepo.FieldGithubURL: + m.ClearGithubURL() + return nil + case agentpluginrepo.FieldRefType: + m.ClearRefType() + return nil + case agentpluginrepo.FieldRefValue: + m.ClearRefValue() + return nil + case agentpluginrepo.FieldLastUploadFilename: + m.ClearLastUploadFilename() + return nil + case agentpluginrepo.FieldLastUploadAt: + m.ClearLastUploadAt() + return nil + case agentpluginrepo.FieldPluginManualEntries: + m.ClearPluginManualEntries() + return nil + case agentpluginrepo.FieldNpmPackageName: + m.ClearNpmPackageName() + return nil + case agentpluginrepo.FieldNpmVersionSpec: + m.ClearNpmVersionSpec() + return nil + case agentpluginrepo.FieldNpmRegistryURL: + m.ClearNpmRegistryURL() + return nil + } + return fmt.Errorf("unknown AgentPluginRepo 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 *AgentPluginRepoMutation) ResetField(name string) error { + switch name { + case agentpluginrepo.FieldName: + m.ResetName() + return nil + case agentpluginrepo.FieldScopeType: + m.ResetScopeType() + return nil + case agentpluginrepo.FieldScopeID: + m.ResetScopeID() + return nil + case agentpluginrepo.FieldCreatedBy: + m.ResetCreatedBy() + return nil + case agentpluginrepo.FieldSourceType: + m.ResetSourceType() + return nil + case agentpluginrepo.FieldGithubURL: + m.ResetGithubURL() + return nil + case agentpluginrepo.FieldRefType: + m.ResetRefType() + return nil + case agentpluginrepo.FieldRefValue: + m.ResetRefValue() + return nil + case agentpluginrepo.FieldLastUploadFilename: + m.ResetLastUploadFilename() + return nil + case agentpluginrepo.FieldLastUploadAt: + m.ResetLastUploadAt() + return nil + case agentpluginrepo.FieldPluginDiscoveryAutoPackageJSON: + m.ResetPluginDiscoveryAutoPackageJSON() + return nil + case agentpluginrepo.FieldPluginManualEntries: + m.ResetPluginManualEntries() + return nil + case agentpluginrepo.FieldNpmPackageName: + m.ResetNpmPackageName() + return nil + case agentpluginrepo.FieldNpmVersionSpec: + m.ResetNpmVersionSpec() + return nil + case agentpluginrepo.FieldNpmRegistryURL: + m.ResetNpmRegistryURL() + return nil + case agentpluginrepo.FieldIsDeleted: + m.ResetIsDeleted() + return nil + case agentpluginrepo.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case agentpluginrepo.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + } + return fmt.Errorf("unknown AgentPluginRepo field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *AgentPluginRepoMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.plugins != nil { + edges = append(edges, agentpluginrepo.EdgePlugins) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *AgentPluginRepoMutation) AddedIDs(name string) []ent.Value { + switch name { + case agentpluginrepo.EdgePlugins: + ids := make([]ent.Value, 0, len(m.plugins)) + for id := range m.plugins { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *AgentPluginRepoMutation) RemovedEdges() []string { + edges := make([]string, 0, 1) + if m.removedplugins != nil { + edges = append(edges, agentpluginrepo.EdgePlugins) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *AgentPluginRepoMutation) RemovedIDs(name string) []ent.Value { + switch name { + case agentpluginrepo.EdgePlugins: + ids := make([]ent.Value, 0, len(m.removedplugins)) + for id := range m.removedplugins { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *AgentPluginRepoMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedplugins { + edges = append(edges, agentpluginrepo.EdgePlugins) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *AgentPluginRepoMutation) EdgeCleared(name string) bool { + switch name { + case agentpluginrepo.EdgePlugins: + return m.clearedplugins + } + 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 *AgentPluginRepoMutation) ClearEdge(name string) error { + switch name { + } + return fmt.Errorf("unknown AgentPluginRepo 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 *AgentPluginRepoMutation) ResetEdge(name string) error { + switch name { + case agentpluginrepo.EdgePlugins: + m.ResetPlugins() + return nil + } + return fmt.Errorf("unknown AgentPluginRepo edge %s", name) +} + +// AgentPluginVersionMutation represents an operation that mutates the AgentPluginVersion nodes in the graph. +type AgentPluginVersionMutation struct { + config + op Op + typ string + id *uuid.UUID + version *string + s3_key *string + parsed_meta *types.PluginParsedMeta + created_at *time.Time + clearedFields map[string]struct{} + plugin *uuid.UUID + clearedplugin bool + done bool + oldValue func(context.Context) (*AgentPluginVersion, error) + predicates []predicate.AgentPluginVersion +} + +var _ ent.Mutation = (*AgentPluginVersionMutation)(nil) + +// agentpluginversionOption allows management of the mutation configuration using functional options. +type agentpluginversionOption func(*AgentPluginVersionMutation) + +// newAgentPluginVersionMutation creates new mutation for the AgentPluginVersion entity. +func newAgentPluginVersionMutation(c config, op Op, opts ...agentpluginversionOption) *AgentPluginVersionMutation { + m := &AgentPluginVersionMutation{ + config: c, + op: op, + typ: TypeAgentPluginVersion, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withAgentPluginVersionID sets the ID field of the mutation. +func withAgentPluginVersionID(id uuid.UUID) agentpluginversionOption { + return func(m *AgentPluginVersionMutation) { + var ( + err error + once sync.Once + value *AgentPluginVersion + ) + m.oldValue = func(ctx context.Context) (*AgentPluginVersion, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().AgentPluginVersion.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withAgentPluginVersion sets the old AgentPluginVersion of the mutation. +func withAgentPluginVersion(node *AgentPluginVersion) agentpluginversionOption { + return func(m *AgentPluginVersionMutation) { + m.oldValue = func(context.Context) (*AgentPluginVersion, 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 AgentPluginVersionMutation) 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 AgentPluginVersionMutation) 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 AgentPluginVersion entities. +func (m *AgentPluginVersionMutation) 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 *AgentPluginVersionMutation) 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 *AgentPluginVersionMutation) 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().AgentPluginVersion.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetResourceID sets the "resource_id" field. +func (m *AgentPluginVersionMutation) SetResourceID(u uuid.UUID) { + m.plugin = &u +} + +// ResourceID returns the value of the "resource_id" field in the mutation. +func (m *AgentPluginVersionMutation) ResourceID() (r uuid.UUID, exists bool) { + v := m.plugin + if v == nil { + return + } + return *v, true +} + +// OldResourceID returns the old "resource_id" field's value of the AgentPluginVersion entity. +// If the AgentPluginVersion 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 *AgentPluginVersionMutation) OldResourceID(ctx context.Context) (v uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldResourceID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldResourceID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldResourceID: %w", err) + } + return oldValue.ResourceID, nil +} + +// ResetResourceID resets all changes to the "resource_id" field. +func (m *AgentPluginVersionMutation) ResetResourceID() { + m.plugin = nil +} + +// SetVersion sets the "version" field. +func (m *AgentPluginVersionMutation) SetVersion(s string) { + m.version = &s +} + +// Version returns the value of the "version" field in the mutation. +func (m *AgentPluginVersionMutation) 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 AgentPluginVersion entity. +// If the AgentPluginVersion 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 *AgentPluginVersionMutation) 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 *AgentPluginVersionMutation) ResetVersion() { + m.version = nil +} + +// SetS3Key sets the "s3_key" field. +func (m *AgentPluginVersionMutation) SetS3Key(s string) { + m.s3_key = &s +} + +// S3Key returns the value of the "s3_key" field in the mutation. +func (m *AgentPluginVersionMutation) S3Key() (r string, exists bool) { + v := m.s3_key + if v == nil { + return + } + return *v, true +} + +// OldS3Key returns the old "s3_key" field's value of the AgentPluginVersion entity. +// If the AgentPluginVersion 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 *AgentPluginVersionMutation) OldS3Key(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldS3Key is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldS3Key requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldS3Key: %w", err) + } + return oldValue.S3Key, nil +} + +// ResetS3Key resets all changes to the "s3_key" field. +func (m *AgentPluginVersionMutation) ResetS3Key() { + m.s3_key = nil +} + +// SetParsedMeta sets the "parsed_meta" field. +func (m *AgentPluginVersionMutation) SetParsedMeta(tpm types.PluginParsedMeta) { + m.parsed_meta = &tpm +} + +// ParsedMeta returns the value of the "parsed_meta" field in the mutation. +func (m *AgentPluginVersionMutation) ParsedMeta() (r types.PluginParsedMeta, exists bool) { + v := m.parsed_meta + if v == nil { + return + } + return *v, true +} + +// OldParsedMeta returns the old "parsed_meta" field's value of the AgentPluginVersion entity. +// If the AgentPluginVersion 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 *AgentPluginVersionMutation) OldParsedMeta(ctx context.Context) (v types.PluginParsedMeta, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldParsedMeta is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldParsedMeta requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldParsedMeta: %w", err) + } + return oldValue.ParsedMeta, nil +} + +// ClearParsedMeta clears the value of the "parsed_meta" field. +func (m *AgentPluginVersionMutation) ClearParsedMeta() { + m.parsed_meta = nil + m.clearedFields[agentpluginversion.FieldParsedMeta] = struct{}{} +} + +// ParsedMetaCleared returns if the "parsed_meta" field was cleared in this mutation. +func (m *AgentPluginVersionMutation) ParsedMetaCleared() bool { + _, ok := m.clearedFields[agentpluginversion.FieldParsedMeta] + return ok +} + +// ResetParsedMeta resets all changes to the "parsed_meta" field. +func (m *AgentPluginVersionMutation) ResetParsedMeta() { + m.parsed_meta = nil + delete(m.clearedFields, agentpluginversion.FieldParsedMeta) +} + +// SetCreatedAt sets the "created_at" field. +func (m *AgentPluginVersionMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *AgentPluginVersionMutation) 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 AgentPluginVersion entity. +// If the AgentPluginVersion 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 *AgentPluginVersionMutation) 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 *AgentPluginVersionMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetPluginID sets the "plugin" edge to the AgentPlugin entity by id. +func (m *AgentPluginVersionMutation) SetPluginID(id uuid.UUID) { + m.plugin = &id +} + +// ClearPlugin clears the "plugin" edge to the AgentPlugin entity. +func (m *AgentPluginVersionMutation) ClearPlugin() { + m.clearedplugin = true + m.clearedFields[agentpluginversion.FieldResourceID] = struct{}{} +} + +// PluginCleared reports if the "plugin" edge to the AgentPlugin entity was cleared. +func (m *AgentPluginVersionMutation) PluginCleared() bool { + return m.clearedplugin +} + +// PluginID returns the "plugin" edge ID in the mutation. +func (m *AgentPluginVersionMutation) PluginID() (id uuid.UUID, exists bool) { + if m.plugin != nil { + return *m.plugin, true + } + return +} + +// PluginIDs returns the "plugin" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// PluginID instead. It exists only for internal usage by the builders. +func (m *AgentPluginVersionMutation) PluginIDs() (ids []uuid.UUID) { + if id := m.plugin; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetPlugin resets all changes to the "plugin" edge. +func (m *AgentPluginVersionMutation) ResetPlugin() { + m.plugin = nil + m.clearedplugin = false +} + +// Where appends a list predicates to the AgentPluginVersionMutation builder. +func (m *AgentPluginVersionMutation) Where(ps ...predicate.AgentPluginVersion) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the AgentPluginVersionMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *AgentPluginVersionMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.AgentPluginVersion, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *AgentPluginVersionMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *AgentPluginVersionMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (AgentPluginVersion). +func (m *AgentPluginVersionMutation) 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 *AgentPluginVersionMutation) Fields() []string { + fields := make([]string, 0, 5) + if m.plugin != nil { + fields = append(fields, agentpluginversion.FieldResourceID) + } + if m.version != nil { + fields = append(fields, agentpluginversion.FieldVersion) + } + if m.s3_key != nil { + fields = append(fields, agentpluginversion.FieldS3Key) + } + if m.parsed_meta != nil { + fields = append(fields, agentpluginversion.FieldParsedMeta) + } + if m.created_at != nil { + fields = append(fields, agentpluginversion.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 *AgentPluginVersionMutation) Field(name string) (ent.Value, bool) { + switch name { + case agentpluginversion.FieldResourceID: + return m.ResourceID() + case agentpluginversion.FieldVersion: + return m.Version() + case agentpluginversion.FieldS3Key: + return m.S3Key() + case agentpluginversion.FieldParsedMeta: + return m.ParsedMeta() + case agentpluginversion.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 *AgentPluginVersionMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case agentpluginversion.FieldResourceID: + return m.OldResourceID(ctx) + case agentpluginversion.FieldVersion: + return m.OldVersion(ctx) + case agentpluginversion.FieldS3Key: + return m.OldS3Key(ctx) + case agentpluginversion.FieldParsedMeta: + return m.OldParsedMeta(ctx) + case agentpluginversion.FieldCreatedAt: + return m.OldCreatedAt(ctx) + } + return nil, fmt.Errorf("unknown AgentPluginVersion 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 *AgentPluginVersionMutation) SetField(name string, value ent.Value) error { + switch name { + case agentpluginversion.FieldResourceID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetResourceID(v) + return nil + case agentpluginversion.FieldVersion: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetVersion(v) + return nil + case agentpluginversion.FieldS3Key: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetS3Key(v) + return nil + case agentpluginversion.FieldParsedMeta: + v, ok := value.(types.PluginParsedMeta) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetParsedMeta(v) + return nil + case agentpluginversion.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 AgentPluginVersion field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *AgentPluginVersionMutation) 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 *AgentPluginVersionMutation) 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 *AgentPluginVersionMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown AgentPluginVersion numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *AgentPluginVersionMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(agentpluginversion.FieldParsedMeta) { + fields = append(fields, agentpluginversion.FieldParsedMeta) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *AgentPluginVersionMutation) 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 *AgentPluginVersionMutation) ClearField(name string) error { + switch name { + case agentpluginversion.FieldParsedMeta: + m.ClearParsedMeta() + return nil + } + return fmt.Errorf("unknown AgentPluginVersion 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 *AgentPluginVersionMutation) ResetField(name string) error { + switch name { + case agentpluginversion.FieldResourceID: + m.ResetResourceID() + return nil + case agentpluginversion.FieldVersion: + m.ResetVersion() + return nil + case agentpluginversion.FieldS3Key: + m.ResetS3Key() + return nil + case agentpluginversion.FieldParsedMeta: + m.ResetParsedMeta() + return nil + case agentpluginversion.FieldCreatedAt: + m.ResetCreatedAt() + return nil + } + return fmt.Errorf("unknown AgentPluginVersion field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *AgentPluginVersionMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.plugin != nil { + edges = append(edges, agentpluginversion.EdgePlugin) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *AgentPluginVersionMutation) AddedIDs(name string) []ent.Value { + switch name { + case agentpluginversion.EdgePlugin: + if id := m.plugin; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *AgentPluginVersionMutation) RemovedEdges() []string { + edges := make([]string, 0, 1) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *AgentPluginVersionMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *AgentPluginVersionMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedplugin { + edges = append(edges, agentpluginversion.EdgePlugin) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *AgentPluginVersionMutation) EdgeCleared(name string) bool { + switch name { + case agentpluginversion.EdgePlugin: + return m.clearedplugin + } + 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 *AgentPluginVersionMutation) ClearEdge(name string) error { + switch name { + case agentpluginversion.EdgePlugin: + m.ClearPlugin() + return nil + } + return fmt.Errorf("unknown AgentPluginVersion 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 *AgentPluginVersionMutation) ResetEdge(name string) error { + switch name { + case agentpluginversion.EdgePlugin: + m.ResetPlugin() + return nil + } + return fmt.Errorf("unknown AgentPluginVersion edge %s", name) +} + +// AgentRuleMutation represents an operation that mutates the AgentRule nodes in the graph. +type AgentRuleMutation struct { + config + op Op + typ string + id *uuid.UUID + name *string + description *string + scope_type *agentrule.ScopeType + scope_id *string + created_by *uuid.UUID + active_version_id *uuid.UUID + is_deleted *bool + created_at *time.Time + updated_at *time.Time + clearedFields map[string]struct{} + versions map[uuid.UUID]struct{} + removedversions map[uuid.UUID]struct{} + clearedversions bool + done bool + oldValue func(context.Context) (*AgentRule, error) + predicates []predicate.AgentRule +} + +var _ ent.Mutation = (*AgentRuleMutation)(nil) + +// agentruleOption allows management of the mutation configuration using functional options. +type agentruleOption func(*AgentRuleMutation) + +// newAgentRuleMutation creates new mutation for the AgentRule entity. +func newAgentRuleMutation(c config, op Op, opts ...agentruleOption) *AgentRuleMutation { + m := &AgentRuleMutation{ + config: c, + op: op, + typ: TypeAgentRule, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withAgentRuleID sets the ID field of the mutation. +func withAgentRuleID(id uuid.UUID) agentruleOption { + return func(m *AgentRuleMutation) { + var ( + err error + once sync.Once + value *AgentRule + ) + m.oldValue = func(ctx context.Context) (*AgentRule, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().AgentRule.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withAgentRule sets the old AgentRule of the mutation. +func withAgentRule(node *AgentRule) agentruleOption { + return func(m *AgentRuleMutation) { + m.oldValue = func(context.Context) (*AgentRule, 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 AgentRuleMutation) 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 AgentRuleMutation) 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 AgentRule entities. +func (m *AgentRuleMutation) 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 *AgentRuleMutation) 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 *AgentRuleMutation) 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().AgentRule.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetName sets the "name" field. +func (m *AgentRuleMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *AgentRuleMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the AgentRule entity. +// If the AgentRule 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 *AgentRuleMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *AgentRuleMutation) ResetName() { + m.name = nil +} + +// SetDescription sets the "description" field. +func (m *AgentRuleMutation) SetDescription(s string) { + m.description = &s +} + +// Description returns the value of the "description" field in the mutation. +func (m *AgentRuleMutation) Description() (r string, exists bool) { + v := m.description + if v == nil { + return + } + return *v, true +} + +// OldDescription returns the old "description" field's value of the AgentRule entity. +// If the AgentRule 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 *AgentRuleMutation) OldDescription(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDescription is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDescription requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDescription: %w", err) + } + return oldValue.Description, nil +} + +// ClearDescription clears the value of the "description" field. +func (m *AgentRuleMutation) ClearDescription() { + m.description = nil + m.clearedFields[agentrule.FieldDescription] = struct{}{} +} + +// DescriptionCleared returns if the "description" field was cleared in this mutation. +func (m *AgentRuleMutation) DescriptionCleared() bool { + _, ok := m.clearedFields[agentrule.FieldDescription] + return ok +} + +// ResetDescription resets all changes to the "description" field. +func (m *AgentRuleMutation) ResetDescription() { + m.description = nil + delete(m.clearedFields, agentrule.FieldDescription) +} + +// SetScopeType sets the "scope_type" field. +func (m *AgentRuleMutation) SetScopeType(at agentrule.ScopeType) { + m.scope_type = &at +} + +// ScopeType returns the value of the "scope_type" field in the mutation. +func (m *AgentRuleMutation) ScopeType() (r agentrule.ScopeType, exists bool) { + v := m.scope_type + if v == nil { + return + } + return *v, true +} + +// OldScopeType returns the old "scope_type" field's value of the AgentRule entity. +// If the AgentRule 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 *AgentRuleMutation) OldScopeType(ctx context.Context) (v agentrule.ScopeType, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldScopeType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldScopeType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldScopeType: %w", err) + } + return oldValue.ScopeType, nil +} + +// ResetScopeType resets all changes to the "scope_type" field. +func (m *AgentRuleMutation) ResetScopeType() { + m.scope_type = nil +} + +// SetScopeID sets the "scope_id" field. +func (m *AgentRuleMutation) SetScopeID(s string) { + m.scope_id = &s +} + +// ScopeID returns the value of the "scope_id" field in the mutation. +func (m *AgentRuleMutation) ScopeID() (r string, exists bool) { + v := m.scope_id + if v == nil { + return + } + return *v, true +} + +// OldScopeID returns the old "scope_id" field's value of the AgentRule entity. +// If the AgentRule 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 *AgentRuleMutation) OldScopeID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldScopeID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldScopeID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldScopeID: %w", err) + } + return oldValue.ScopeID, nil +} + +// ResetScopeID resets all changes to the "scope_id" field. +func (m *AgentRuleMutation) ResetScopeID() { + m.scope_id = nil +} + +// SetCreatedBy sets the "created_by" field. +func (m *AgentRuleMutation) SetCreatedBy(u uuid.UUID) { + m.created_by = &u +} + +// CreatedBy returns the value of the "created_by" field in the mutation. +func (m *AgentRuleMutation) CreatedBy() (r uuid.UUID, exists bool) { + v := m.created_by + if v == nil { + return + } + return *v, true +} + +// OldCreatedBy returns the old "created_by" field's value of the AgentRule entity. +// If the AgentRule 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 *AgentRuleMutation) OldCreatedBy(ctx context.Context) (v uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreatedBy is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreatedBy requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreatedBy: %w", err) + } + return oldValue.CreatedBy, nil +} + +// ResetCreatedBy resets all changes to the "created_by" field. +func (m *AgentRuleMutation) ResetCreatedBy() { + m.created_by = nil +} + +// SetActiveVersionID sets the "active_version_id" field. +func (m *AgentRuleMutation) SetActiveVersionID(u uuid.UUID) { + m.active_version_id = &u +} + +// ActiveVersionID returns the value of the "active_version_id" field in the mutation. +func (m *AgentRuleMutation) ActiveVersionID() (r uuid.UUID, exists bool) { + v := m.active_version_id + if v == nil { + return + } + return *v, true +} + +// OldActiveVersionID returns the old "active_version_id" field's value of the AgentRule entity. +// If the AgentRule 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 *AgentRuleMutation) OldActiveVersionID(ctx context.Context) (v *uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldActiveVersionID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldActiveVersionID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldActiveVersionID: %w", err) + } + return oldValue.ActiveVersionID, nil +} + +// ClearActiveVersionID clears the value of the "active_version_id" field. +func (m *AgentRuleMutation) ClearActiveVersionID() { + m.active_version_id = nil + m.clearedFields[agentrule.FieldActiveVersionID] = struct{}{} +} + +// ActiveVersionIDCleared returns if the "active_version_id" field was cleared in this mutation. +func (m *AgentRuleMutation) ActiveVersionIDCleared() bool { + _, ok := m.clearedFields[agentrule.FieldActiveVersionID] + return ok +} + +// ResetActiveVersionID resets all changes to the "active_version_id" field. +func (m *AgentRuleMutation) ResetActiveVersionID() { + m.active_version_id = nil + delete(m.clearedFields, agentrule.FieldActiveVersionID) +} + +// SetIsDeleted sets the "is_deleted" field. +func (m *AgentRuleMutation) SetIsDeleted(b bool) { + m.is_deleted = &b +} + +// IsDeleted returns the value of the "is_deleted" field in the mutation. +func (m *AgentRuleMutation) IsDeleted() (r bool, exists bool) { + v := m.is_deleted + if v == nil { + return + } + return *v, true +} + +// OldIsDeleted returns the old "is_deleted" field's value of the AgentRule entity. +// If the AgentRule 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 *AgentRuleMutation) OldIsDeleted(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldIsDeleted is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldIsDeleted requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldIsDeleted: %w", err) + } + return oldValue.IsDeleted, nil +} + +// ResetIsDeleted resets all changes to the "is_deleted" field. +func (m *AgentRuleMutation) ResetIsDeleted() { + m.is_deleted = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *AgentRuleMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *AgentRuleMutation) 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 AgentRule entity. +// If the AgentRule 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 *AgentRuleMutation) 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 *AgentRuleMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *AgentRuleMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *AgentRuleMutation) UpdatedAt() (r time.Time, exists bool) { + v := m.updated_at + if v == nil { + return + } + return *v, true +} + +// OldUpdatedAt returns the old "updated_at" field's value of the AgentRule entity. +// If the AgentRule 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 *AgentRuleMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUpdatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) + } + return oldValue.UpdatedAt, nil +} + +// ResetUpdatedAt resets all changes to the "updated_at" field. +func (m *AgentRuleMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// AddVersionIDs adds the "versions" edge to the AgentRuleVersion entity by ids. +func (m *AgentRuleMutation) AddVersionIDs(ids ...uuid.UUID) { + if m.versions == nil { + m.versions = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.versions[ids[i]] = struct{}{} + } +} + +// ClearVersions clears the "versions" edge to the AgentRuleVersion entity. +func (m *AgentRuleMutation) ClearVersions() { + m.clearedversions = true +} + +// VersionsCleared reports if the "versions" edge to the AgentRuleVersion entity was cleared. +func (m *AgentRuleMutation) VersionsCleared() bool { + return m.clearedversions +} + +// RemoveVersionIDs removes the "versions" edge to the AgentRuleVersion entity by IDs. +func (m *AgentRuleMutation) RemoveVersionIDs(ids ...uuid.UUID) { + if m.removedversions == nil { + m.removedversions = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.versions, ids[i]) + m.removedversions[ids[i]] = struct{}{} + } +} + +// RemovedVersions returns the removed IDs of the "versions" edge to the AgentRuleVersion entity. +func (m *AgentRuleMutation) RemovedVersionsIDs() (ids []uuid.UUID) { + for id := range m.removedversions { + ids = append(ids, id) + } + return +} + +// VersionsIDs returns the "versions" edge IDs in the mutation. +func (m *AgentRuleMutation) VersionsIDs() (ids []uuid.UUID) { + for id := range m.versions { + ids = append(ids, id) + } + return +} + +// ResetVersions resets all changes to the "versions" edge. +func (m *AgentRuleMutation) ResetVersions() { + m.versions = nil + m.clearedversions = false + m.removedversions = nil +} + +// Where appends a list predicates to the AgentRuleMutation builder. +func (m *AgentRuleMutation) Where(ps ...predicate.AgentRule) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the AgentRuleMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *AgentRuleMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.AgentRule, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *AgentRuleMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *AgentRuleMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (AgentRule). +func (m *AgentRuleMutation) 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 *AgentRuleMutation) Fields() []string { + fields := make([]string, 0, 9) + if m.name != nil { + fields = append(fields, agentrule.FieldName) + } + if m.description != nil { + fields = append(fields, agentrule.FieldDescription) + } + if m.scope_type != nil { + fields = append(fields, agentrule.FieldScopeType) + } + if m.scope_id != nil { + fields = append(fields, agentrule.FieldScopeID) + } + if m.created_by != nil { + fields = append(fields, agentrule.FieldCreatedBy) + } + if m.active_version_id != nil { + fields = append(fields, agentrule.FieldActiveVersionID) + } + if m.is_deleted != nil { + fields = append(fields, agentrule.FieldIsDeleted) + } + if m.created_at != nil { + fields = append(fields, agentrule.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, agentrule.FieldUpdatedAt) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *AgentRuleMutation) Field(name string) (ent.Value, bool) { + switch name { + case agentrule.FieldName: + return m.Name() + case agentrule.FieldDescription: + return m.Description() + case agentrule.FieldScopeType: + return m.ScopeType() + case agentrule.FieldScopeID: + return m.ScopeID() + case agentrule.FieldCreatedBy: + return m.CreatedBy() + case agentrule.FieldActiveVersionID: + return m.ActiveVersionID() + case agentrule.FieldIsDeleted: + return m.IsDeleted() + case agentrule.FieldCreatedAt: + return m.CreatedAt() + case agentrule.FieldUpdatedAt: + return m.UpdatedAt() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *AgentRuleMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case agentrule.FieldName: + return m.OldName(ctx) + case agentrule.FieldDescription: + return m.OldDescription(ctx) + case agentrule.FieldScopeType: + return m.OldScopeType(ctx) + case agentrule.FieldScopeID: + return m.OldScopeID(ctx) + case agentrule.FieldCreatedBy: + return m.OldCreatedBy(ctx) + case agentrule.FieldActiveVersionID: + return m.OldActiveVersionID(ctx) + case agentrule.FieldIsDeleted: + return m.OldIsDeleted(ctx) + case agentrule.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case agentrule.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + } + return nil, fmt.Errorf("unknown AgentRule 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 *AgentRuleMutation) SetField(name string, value ent.Value) error { + switch name { + case agentrule.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case agentrule.FieldDescription: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDescription(v) + return nil + case agentrule.FieldScopeType: + v, ok := value.(agentrule.ScopeType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetScopeType(v) + return nil + case agentrule.FieldScopeID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetScopeID(v) + return nil + case agentrule.FieldCreatedBy: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedBy(v) + return nil + case agentrule.FieldActiveVersionID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetActiveVersionID(v) + return nil + case agentrule.FieldIsDeleted: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIsDeleted(v) + return nil + case agentrule.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + case agentrule.FieldUpdatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdatedAt(v) + return nil + } + return fmt.Errorf("unknown AgentRule field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *AgentRuleMutation) 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 *AgentRuleMutation) 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 *AgentRuleMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown AgentRule numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *AgentRuleMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(agentrule.FieldDescription) { + fields = append(fields, agentrule.FieldDescription) + } + if m.FieldCleared(agentrule.FieldActiveVersionID) { + fields = append(fields, agentrule.FieldActiveVersionID) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *AgentRuleMutation) 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 *AgentRuleMutation) ClearField(name string) error { + switch name { + case agentrule.FieldDescription: + m.ClearDescription() + return nil + case agentrule.FieldActiveVersionID: + m.ClearActiveVersionID() + return nil + } + return fmt.Errorf("unknown AgentRule 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 *AgentRuleMutation) ResetField(name string) error { + switch name { + case agentrule.FieldName: + m.ResetName() + return nil + case agentrule.FieldDescription: + m.ResetDescription() + return nil + case agentrule.FieldScopeType: + m.ResetScopeType() + return nil + case agentrule.FieldScopeID: + m.ResetScopeID() + return nil + case agentrule.FieldCreatedBy: + m.ResetCreatedBy() + return nil + case agentrule.FieldActiveVersionID: + m.ResetActiveVersionID() + return nil + case agentrule.FieldIsDeleted: + m.ResetIsDeleted() + return nil + case agentrule.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case agentrule.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + } + return fmt.Errorf("unknown AgentRule field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *AgentRuleMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.versions != nil { + edges = append(edges, agentrule.EdgeVersions) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *AgentRuleMutation) AddedIDs(name string) []ent.Value { + switch name { + case agentrule.EdgeVersions: + ids := make([]ent.Value, 0, len(m.versions)) + for id := range m.versions { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *AgentRuleMutation) RemovedEdges() []string { + edges := make([]string, 0, 1) + if m.removedversions != nil { + edges = append(edges, agentrule.EdgeVersions) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *AgentRuleMutation) RemovedIDs(name string) []ent.Value { + switch name { + case agentrule.EdgeVersions: + ids := make([]ent.Value, 0, len(m.removedversions)) + for id := range m.removedversions { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *AgentRuleMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedversions { + edges = append(edges, agentrule.EdgeVersions) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *AgentRuleMutation) EdgeCleared(name string) bool { + switch name { + case agentrule.EdgeVersions: + return m.clearedversions + } + 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 *AgentRuleMutation) ClearEdge(name string) error { + switch name { + } + return fmt.Errorf("unknown AgentRule 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 *AgentRuleMutation) ResetEdge(name string) error { + switch name { + case agentrule.EdgeVersions: + m.ResetVersions() + return nil + } + return fmt.Errorf("unknown AgentRule edge %s", name) +} + +// AgentRuleVersionMutation represents an operation that mutates the AgentRuleVersion nodes in the graph. +type AgentRuleVersionMutation struct { + config + op Op + typ string + id *uuid.UUID + version *string + content *string + created_at *time.Time + clearedFields map[string]struct{} + rule *uuid.UUID + clearedrule bool + done bool + oldValue func(context.Context) (*AgentRuleVersion, error) + predicates []predicate.AgentRuleVersion +} + +var _ ent.Mutation = (*AgentRuleVersionMutation)(nil) + +// agentruleversionOption allows management of the mutation configuration using functional options. +type agentruleversionOption func(*AgentRuleVersionMutation) + +// newAgentRuleVersionMutation creates new mutation for the AgentRuleVersion entity. +func newAgentRuleVersionMutation(c config, op Op, opts ...agentruleversionOption) *AgentRuleVersionMutation { + m := &AgentRuleVersionMutation{ + config: c, + op: op, + typ: TypeAgentRuleVersion, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withAgentRuleVersionID sets the ID field of the mutation. +func withAgentRuleVersionID(id uuid.UUID) agentruleversionOption { + return func(m *AgentRuleVersionMutation) { + var ( + err error + once sync.Once + value *AgentRuleVersion + ) + m.oldValue = func(ctx context.Context) (*AgentRuleVersion, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().AgentRuleVersion.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withAgentRuleVersion sets the old AgentRuleVersion of the mutation. +func withAgentRuleVersion(node *AgentRuleVersion) agentruleversionOption { + return func(m *AgentRuleVersionMutation) { + m.oldValue = func(context.Context) (*AgentRuleVersion, 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 AgentRuleVersionMutation) 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 AgentRuleVersionMutation) 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 AgentRuleVersion entities. +func (m *AgentRuleVersionMutation) 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 *AgentRuleVersionMutation) 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 *AgentRuleVersionMutation) 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().AgentRuleVersion.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetRuleID sets the "rule_id" field. +func (m *AgentRuleVersionMutation) SetRuleID(u uuid.UUID) { + m.rule = &u +} + +// RuleID returns the value of the "rule_id" field in the mutation. +func (m *AgentRuleVersionMutation) RuleID() (r uuid.UUID, exists bool) { + v := m.rule + if v == nil { + return + } + return *v, true +} + +// OldRuleID returns the old "rule_id" field's value of the AgentRuleVersion entity. +// If the AgentRuleVersion 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 *AgentRuleVersionMutation) OldRuleID(ctx context.Context) (v uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRuleID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRuleID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRuleID: %w", err) + } + return oldValue.RuleID, nil +} + +// ResetRuleID resets all changes to the "rule_id" field. +func (m *AgentRuleVersionMutation) ResetRuleID() { + m.rule = nil +} + +// SetVersion sets the "version" field. +func (m *AgentRuleVersionMutation) SetVersion(s string) { + m.version = &s +} + +// Version returns the value of the "version" field in the mutation. +func (m *AgentRuleVersionMutation) 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 AgentRuleVersion entity. +// If the AgentRuleVersion 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 *AgentRuleVersionMutation) 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 *AgentRuleVersionMutation) ResetVersion() { + m.version = nil +} + +// SetContent sets the "content" field. +func (m *AgentRuleVersionMutation) SetContent(s string) { + m.content = &s +} + +// Content returns the value of the "content" field in the mutation. +func (m *AgentRuleVersionMutation) Content() (r string, exists bool) { + v := m.content + if v == nil { + return + } + return *v, true +} + +// OldContent returns the old "content" field's value of the AgentRuleVersion entity. +// If the AgentRuleVersion 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 *AgentRuleVersionMutation) OldContent(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldContent is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldContent requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldContent: %w", err) + } + return oldValue.Content, nil +} + +// ResetContent resets all changes to the "content" field. +func (m *AgentRuleVersionMutation) ResetContent() { + m.content = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *AgentRuleVersionMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *AgentRuleVersionMutation) 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 AgentRuleVersion entity. +// If the AgentRuleVersion 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 *AgentRuleVersionMutation) 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 *AgentRuleVersionMutation) ResetCreatedAt() { + m.created_at = nil +} + +// ClearRule clears the "rule" edge to the AgentRule entity. +func (m *AgentRuleVersionMutation) ClearRule() { + m.clearedrule = true + m.clearedFields[agentruleversion.FieldRuleID] = struct{}{} +} + +// RuleCleared reports if the "rule" edge to the AgentRule entity was cleared. +func (m *AgentRuleVersionMutation) RuleCleared() bool { + return m.clearedrule +} + +// RuleIDs returns the "rule" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// RuleID instead. It exists only for internal usage by the builders. +func (m *AgentRuleVersionMutation) RuleIDs() (ids []uuid.UUID) { + if id := m.rule; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetRule resets all changes to the "rule" edge. +func (m *AgentRuleVersionMutation) ResetRule() { + m.rule = nil + m.clearedrule = false +} + +// Where appends a list predicates to the AgentRuleVersionMutation builder. +func (m *AgentRuleVersionMutation) Where(ps ...predicate.AgentRuleVersion) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the AgentRuleVersionMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *AgentRuleVersionMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.AgentRuleVersion, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *AgentRuleVersionMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *AgentRuleVersionMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (AgentRuleVersion). +func (m *AgentRuleVersionMutation) 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 *AgentRuleVersionMutation) Fields() []string { + fields := make([]string, 0, 4) + if m.rule != nil { + fields = append(fields, agentruleversion.FieldRuleID) + } + if m.version != nil { + fields = append(fields, agentruleversion.FieldVersion) + } + if m.content != nil { + fields = append(fields, agentruleversion.FieldContent) + } + if m.created_at != nil { + fields = append(fields, agentruleversion.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 *AgentRuleVersionMutation) Field(name string) (ent.Value, bool) { + switch name { + case agentruleversion.FieldRuleID: + return m.RuleID() + case agentruleversion.FieldVersion: + return m.Version() + case agentruleversion.FieldContent: + return m.Content() + case agentruleversion.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 *AgentRuleVersionMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case agentruleversion.FieldRuleID: + return m.OldRuleID(ctx) + case agentruleversion.FieldVersion: + return m.OldVersion(ctx) + case agentruleversion.FieldContent: + return m.OldContent(ctx) + case agentruleversion.FieldCreatedAt: + return m.OldCreatedAt(ctx) + } + return nil, fmt.Errorf("unknown AgentRuleVersion 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 *AgentRuleVersionMutation) SetField(name string, value ent.Value) error { + switch name { + case agentruleversion.FieldRuleID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRuleID(v) + return nil + case agentruleversion.FieldVersion: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetVersion(v) + return nil + case agentruleversion.FieldContent: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetContent(v) + return nil + case agentruleversion.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 AgentRuleVersion field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *AgentRuleVersionMutation) 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 *AgentRuleVersionMutation) 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 *AgentRuleVersionMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown AgentRuleVersion numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *AgentRuleVersionMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *AgentRuleVersionMutation) 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 *AgentRuleVersionMutation) ClearField(name string) error { + return fmt.Errorf("unknown AgentRuleVersion 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 *AgentRuleVersionMutation) ResetField(name string) error { + switch name { + case agentruleversion.FieldRuleID: + m.ResetRuleID() + return nil + case agentruleversion.FieldVersion: + m.ResetVersion() + return nil + case agentruleversion.FieldContent: + m.ResetContent() + return nil + case agentruleversion.FieldCreatedAt: + m.ResetCreatedAt() + return nil + } + return fmt.Errorf("unknown AgentRuleVersion field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *AgentRuleVersionMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.rule != nil { + edges = append(edges, agentruleversion.EdgeRule) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *AgentRuleVersionMutation) AddedIDs(name string) []ent.Value { + switch name { + case agentruleversion.EdgeRule: + if id := m.rule; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *AgentRuleVersionMutation) RemovedEdges() []string { + edges := make([]string, 0, 1) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *AgentRuleVersionMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *AgentRuleVersionMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedrule { + edges = append(edges, agentruleversion.EdgeRule) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *AgentRuleVersionMutation) EdgeCleared(name string) bool { + switch name { + case agentruleversion.EdgeRule: + return m.clearedrule + } + 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 *AgentRuleVersionMutation) ClearEdge(name string) error { + switch name { + case agentruleversion.EdgeRule: + m.ClearRule() + return nil + } + return fmt.Errorf("unknown AgentRuleVersion 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 *AgentRuleVersionMutation) ResetEdge(name string) error { + switch name { + case agentruleversion.EdgeRule: + m.ResetRule() + return nil + } + return fmt.Errorf("unknown AgentRuleVersion edge %s", name) +} + +// AgentSkillMutation represents an operation that mutates the AgentSkill nodes in the graph. +type AgentSkillMutation struct { + config + op Op + typ string + id *uuid.UUID + name *string + description *string + scope_type *agentskill.ScopeType + scope_id *string + created_by *uuid.UUID + active_version_id *uuid.UUID + is_force_delivery *bool + is_orphan *bool + is_deleted *bool + created_at *time.Time + updated_at *time.Time + clearedFields map[string]struct{} + repo *uuid.UUID + clearedrepo bool + versions map[uuid.UUID]struct{} + removedversions map[uuid.UUID]struct{} + clearedversions bool + done bool + oldValue func(context.Context) (*AgentSkill, error) + predicates []predicate.AgentSkill +} + +var _ ent.Mutation = (*AgentSkillMutation)(nil) + +// agentskillOption allows management of the mutation configuration using functional options. +type agentskillOption func(*AgentSkillMutation) + +// newAgentSkillMutation creates new mutation for the AgentSkill entity. +func newAgentSkillMutation(c config, op Op, opts ...agentskillOption) *AgentSkillMutation { + m := &AgentSkillMutation{ + config: c, + op: op, + typ: TypeAgentSkill, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withAgentSkillID sets the ID field of the mutation. +func withAgentSkillID(id uuid.UUID) agentskillOption { + return func(m *AgentSkillMutation) { + var ( + err error + once sync.Once + value *AgentSkill + ) + m.oldValue = func(ctx context.Context) (*AgentSkill, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().AgentSkill.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withAgentSkill sets the old AgentSkill of the mutation. +func withAgentSkill(node *AgentSkill) agentskillOption { + return func(m *AgentSkillMutation) { + m.oldValue = func(context.Context) (*AgentSkill, 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 AgentSkillMutation) 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 AgentSkillMutation) 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 AgentSkill entities. +func (m *AgentSkillMutation) 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 *AgentSkillMutation) 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 *AgentSkillMutation) 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().AgentSkill.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetRepoID sets the "repo_id" field. +func (m *AgentSkillMutation) SetRepoID(u uuid.UUID) { + m.repo = &u +} + +// RepoID returns the value of the "repo_id" field in the mutation. +func (m *AgentSkillMutation) RepoID() (r uuid.UUID, exists bool) { + v := m.repo + if v == nil { + return + } + return *v, true +} + +// OldRepoID returns the old "repo_id" field's value of the AgentSkill entity. +// If the AgentSkill 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 *AgentSkillMutation) OldRepoID(ctx context.Context) (v uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRepoID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRepoID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRepoID: %w", err) + } + return oldValue.RepoID, nil +} + +// ResetRepoID resets all changes to the "repo_id" field. +func (m *AgentSkillMutation) ResetRepoID() { + m.repo = nil +} + +// SetName sets the "name" field. +func (m *AgentSkillMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *AgentSkillMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the AgentSkill entity. +// If the AgentSkill 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 *AgentSkillMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *AgentSkillMutation) ResetName() { + m.name = nil +} + +// SetDescription sets the "description" field. +func (m *AgentSkillMutation) SetDescription(s string) { + m.description = &s +} + +// Description returns the value of the "description" field in the mutation. +func (m *AgentSkillMutation) Description() (r string, exists bool) { + v := m.description + if v == nil { + return + } + return *v, true +} + +// OldDescription returns the old "description" field's value of the AgentSkill entity. +// If the AgentSkill 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 *AgentSkillMutation) OldDescription(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDescription is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDescription requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDescription: %w", err) + } + return oldValue.Description, nil +} + +// ClearDescription clears the value of the "description" field. +func (m *AgentSkillMutation) ClearDescription() { + m.description = nil + m.clearedFields[agentskill.FieldDescription] = struct{}{} +} + +// DescriptionCleared returns if the "description" field was cleared in this mutation. +func (m *AgentSkillMutation) DescriptionCleared() bool { + _, ok := m.clearedFields[agentskill.FieldDescription] + return ok +} + +// ResetDescription resets all changes to the "description" field. +func (m *AgentSkillMutation) ResetDescription() { + m.description = nil + delete(m.clearedFields, agentskill.FieldDescription) +} + +// SetScopeType sets the "scope_type" field. +func (m *AgentSkillMutation) SetScopeType(at agentskill.ScopeType) { + m.scope_type = &at +} + +// ScopeType returns the value of the "scope_type" field in the mutation. +func (m *AgentSkillMutation) ScopeType() (r agentskill.ScopeType, exists bool) { + v := m.scope_type + if v == nil { + return + } + return *v, true +} + +// OldScopeType returns the old "scope_type" field's value of the AgentSkill entity. +// If the AgentSkill 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 *AgentSkillMutation) OldScopeType(ctx context.Context) (v agentskill.ScopeType, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldScopeType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldScopeType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldScopeType: %w", err) + } + return oldValue.ScopeType, nil +} + +// ResetScopeType resets all changes to the "scope_type" field. +func (m *AgentSkillMutation) ResetScopeType() { + m.scope_type = nil +} + +// SetScopeID sets the "scope_id" field. +func (m *AgentSkillMutation) SetScopeID(s string) { + m.scope_id = &s +} + +// ScopeID returns the value of the "scope_id" field in the mutation. +func (m *AgentSkillMutation) ScopeID() (r string, exists bool) { + v := m.scope_id + if v == nil { + return + } + return *v, true +} + +// OldScopeID returns the old "scope_id" field's value of the AgentSkill entity. +// If the AgentSkill 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 *AgentSkillMutation) OldScopeID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldScopeID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldScopeID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldScopeID: %w", err) + } + return oldValue.ScopeID, nil +} + +// ResetScopeID resets all changes to the "scope_id" field. +func (m *AgentSkillMutation) ResetScopeID() { + m.scope_id = nil +} + +// SetCreatedBy sets the "created_by" field. +func (m *AgentSkillMutation) SetCreatedBy(u uuid.UUID) { + m.created_by = &u +} + +// CreatedBy returns the value of the "created_by" field in the mutation. +func (m *AgentSkillMutation) CreatedBy() (r uuid.UUID, exists bool) { + v := m.created_by + if v == nil { + return + } + return *v, true +} + +// OldCreatedBy returns the old "created_by" field's value of the AgentSkill entity. +// If the AgentSkill 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 *AgentSkillMutation) OldCreatedBy(ctx context.Context) (v uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreatedBy is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreatedBy requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreatedBy: %w", err) + } + return oldValue.CreatedBy, nil +} + +// ResetCreatedBy resets all changes to the "created_by" field. +func (m *AgentSkillMutation) ResetCreatedBy() { + m.created_by = nil +} + +// SetActiveVersionID sets the "active_version_id" field. +func (m *AgentSkillMutation) SetActiveVersionID(u uuid.UUID) { + m.active_version_id = &u +} + +// ActiveVersionID returns the value of the "active_version_id" field in the mutation. +func (m *AgentSkillMutation) ActiveVersionID() (r uuid.UUID, exists bool) { + v := m.active_version_id + if v == nil { + return + } + return *v, true +} + +// OldActiveVersionID returns the old "active_version_id" field's value of the AgentSkill entity. +// If the AgentSkill 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 *AgentSkillMutation) OldActiveVersionID(ctx context.Context) (v *uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldActiveVersionID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldActiveVersionID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldActiveVersionID: %w", err) + } + return oldValue.ActiveVersionID, nil +} + +// ClearActiveVersionID clears the value of the "active_version_id" field. +func (m *AgentSkillMutation) ClearActiveVersionID() { + m.active_version_id = nil + m.clearedFields[agentskill.FieldActiveVersionID] = struct{}{} +} + +// ActiveVersionIDCleared returns if the "active_version_id" field was cleared in this mutation. +func (m *AgentSkillMutation) ActiveVersionIDCleared() bool { + _, ok := m.clearedFields[agentskill.FieldActiveVersionID] + return ok +} + +// ResetActiveVersionID resets all changes to the "active_version_id" field. +func (m *AgentSkillMutation) ResetActiveVersionID() { + m.active_version_id = nil + delete(m.clearedFields, agentskill.FieldActiveVersionID) +} + +// SetIsForceDelivery sets the "is_force_delivery" field. +func (m *AgentSkillMutation) SetIsForceDelivery(b bool) { + m.is_force_delivery = &b +} + +// IsForceDelivery returns the value of the "is_force_delivery" field in the mutation. +func (m *AgentSkillMutation) IsForceDelivery() (r bool, exists bool) { + v := m.is_force_delivery + if v == nil { + return + } + return *v, true +} + +// OldIsForceDelivery returns the old "is_force_delivery" field's value of the AgentSkill entity. +// If the AgentSkill 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 *AgentSkillMutation) OldIsForceDelivery(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldIsForceDelivery is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldIsForceDelivery requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldIsForceDelivery: %w", err) + } + return oldValue.IsForceDelivery, nil +} + +// ResetIsForceDelivery resets all changes to the "is_force_delivery" field. +func (m *AgentSkillMutation) ResetIsForceDelivery() { + m.is_force_delivery = nil +} + +// SetIsOrphan sets the "is_orphan" field. +func (m *AgentSkillMutation) SetIsOrphan(b bool) { + m.is_orphan = &b +} + +// IsOrphan returns the value of the "is_orphan" field in the mutation. +func (m *AgentSkillMutation) IsOrphan() (r bool, exists bool) { + v := m.is_orphan + if v == nil { + return + } + return *v, true +} + +// OldIsOrphan returns the old "is_orphan" field's value of the AgentSkill entity. +// If the AgentSkill 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 *AgentSkillMutation) OldIsOrphan(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldIsOrphan is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldIsOrphan requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldIsOrphan: %w", err) + } + return oldValue.IsOrphan, nil +} + +// ResetIsOrphan resets all changes to the "is_orphan" field. +func (m *AgentSkillMutation) ResetIsOrphan() { + m.is_orphan = nil +} + +// SetIsDeleted sets the "is_deleted" field. +func (m *AgentSkillMutation) SetIsDeleted(b bool) { + m.is_deleted = &b +} + +// IsDeleted returns the value of the "is_deleted" field in the mutation. +func (m *AgentSkillMutation) IsDeleted() (r bool, exists bool) { + v := m.is_deleted + if v == nil { + return + } + return *v, true +} + +// OldIsDeleted returns the old "is_deleted" field's value of the AgentSkill entity. +// If the AgentSkill 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 *AgentSkillMutation) OldIsDeleted(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldIsDeleted is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldIsDeleted requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldIsDeleted: %w", err) + } + return oldValue.IsDeleted, nil +} + +// ResetIsDeleted resets all changes to the "is_deleted" field. +func (m *AgentSkillMutation) ResetIsDeleted() { + m.is_deleted = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *AgentSkillMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *AgentSkillMutation) 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 AgentSkill entity. +// If the AgentSkill 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 *AgentSkillMutation) 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 *AgentSkillMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *AgentSkillMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *AgentSkillMutation) UpdatedAt() (r time.Time, exists bool) { + v := m.updated_at + if v == nil { + return + } + return *v, true +} + +// OldUpdatedAt returns the old "updated_at" field's value of the AgentSkill entity. +// If the AgentSkill 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 *AgentSkillMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUpdatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) + } + return oldValue.UpdatedAt, nil +} + +// ResetUpdatedAt resets all changes to the "updated_at" field. +func (m *AgentSkillMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// ClearRepo clears the "repo" edge to the AgentSkillRepo entity. +func (m *AgentSkillMutation) ClearRepo() { + m.clearedrepo = true + m.clearedFields[agentskill.FieldRepoID] = struct{}{} +} + +// RepoCleared reports if the "repo" edge to the AgentSkillRepo entity was cleared. +func (m *AgentSkillMutation) RepoCleared() bool { + return m.clearedrepo +} + +// RepoIDs returns the "repo" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// RepoID instead. It exists only for internal usage by the builders. +func (m *AgentSkillMutation) RepoIDs() (ids []uuid.UUID) { + if id := m.repo; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetRepo resets all changes to the "repo" edge. +func (m *AgentSkillMutation) ResetRepo() { + m.repo = nil + m.clearedrepo = false +} + +// AddVersionIDs adds the "versions" edge to the AgentSkillVersion entity by ids. +func (m *AgentSkillMutation) AddVersionIDs(ids ...uuid.UUID) { + if m.versions == nil { + m.versions = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.versions[ids[i]] = struct{}{} + } +} + +// ClearVersions clears the "versions" edge to the AgentSkillVersion entity. +func (m *AgentSkillMutation) ClearVersions() { + m.clearedversions = true +} + +// VersionsCleared reports if the "versions" edge to the AgentSkillVersion entity was cleared. +func (m *AgentSkillMutation) VersionsCleared() bool { + return m.clearedversions +} + +// RemoveVersionIDs removes the "versions" edge to the AgentSkillVersion entity by IDs. +func (m *AgentSkillMutation) RemoveVersionIDs(ids ...uuid.UUID) { + if m.removedversions == nil { + m.removedversions = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.versions, ids[i]) + m.removedversions[ids[i]] = struct{}{} + } +} + +// RemovedVersions returns the removed IDs of the "versions" edge to the AgentSkillVersion entity. +func (m *AgentSkillMutation) RemovedVersionsIDs() (ids []uuid.UUID) { + for id := range m.removedversions { + ids = append(ids, id) + } + return +} + +// VersionsIDs returns the "versions" edge IDs in the mutation. +func (m *AgentSkillMutation) VersionsIDs() (ids []uuid.UUID) { + for id := range m.versions { + ids = append(ids, id) + } + return +} + +// ResetVersions resets all changes to the "versions" edge. +func (m *AgentSkillMutation) ResetVersions() { + m.versions = nil + m.clearedversions = false + m.removedversions = nil +} + +// Where appends a list predicates to the AgentSkillMutation builder. +func (m *AgentSkillMutation) Where(ps ...predicate.AgentSkill) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the AgentSkillMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *AgentSkillMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.AgentSkill, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *AgentSkillMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *AgentSkillMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (AgentSkill). +func (m *AgentSkillMutation) 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 *AgentSkillMutation) Fields() []string { + fields := make([]string, 0, 12) + if m.repo != nil { + fields = append(fields, agentskill.FieldRepoID) + } + if m.name != nil { + fields = append(fields, agentskill.FieldName) + } + if m.description != nil { + fields = append(fields, agentskill.FieldDescription) + } + if m.scope_type != nil { + fields = append(fields, agentskill.FieldScopeType) + } + if m.scope_id != nil { + fields = append(fields, agentskill.FieldScopeID) + } + if m.created_by != nil { + fields = append(fields, agentskill.FieldCreatedBy) + } + if m.active_version_id != nil { + fields = append(fields, agentskill.FieldActiveVersionID) + } + if m.is_force_delivery != nil { + fields = append(fields, agentskill.FieldIsForceDelivery) + } + if m.is_orphan != nil { + fields = append(fields, agentskill.FieldIsOrphan) + } + if m.is_deleted != nil { + fields = append(fields, agentskill.FieldIsDeleted) + } + if m.created_at != nil { + fields = append(fields, agentskill.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, agentskill.FieldUpdatedAt) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *AgentSkillMutation) Field(name string) (ent.Value, bool) { + switch name { + case agentskill.FieldRepoID: + return m.RepoID() + case agentskill.FieldName: + return m.Name() + case agentskill.FieldDescription: + return m.Description() + case agentskill.FieldScopeType: + return m.ScopeType() + case agentskill.FieldScopeID: + return m.ScopeID() + case agentskill.FieldCreatedBy: + return m.CreatedBy() + case agentskill.FieldActiveVersionID: + return m.ActiveVersionID() + case agentskill.FieldIsForceDelivery: + return m.IsForceDelivery() + case agentskill.FieldIsOrphan: + return m.IsOrphan() + case agentskill.FieldIsDeleted: + return m.IsDeleted() + case agentskill.FieldCreatedAt: + return m.CreatedAt() + case agentskill.FieldUpdatedAt: + return m.UpdatedAt() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *AgentSkillMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case agentskill.FieldRepoID: + return m.OldRepoID(ctx) + case agentskill.FieldName: + return m.OldName(ctx) + case agentskill.FieldDescription: + return m.OldDescription(ctx) + case agentskill.FieldScopeType: + return m.OldScopeType(ctx) + case agentskill.FieldScopeID: + return m.OldScopeID(ctx) + case agentskill.FieldCreatedBy: + return m.OldCreatedBy(ctx) + case agentskill.FieldActiveVersionID: + return m.OldActiveVersionID(ctx) + case agentskill.FieldIsForceDelivery: + return m.OldIsForceDelivery(ctx) + case agentskill.FieldIsOrphan: + return m.OldIsOrphan(ctx) + case agentskill.FieldIsDeleted: + return m.OldIsDeleted(ctx) + case agentskill.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case agentskill.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + } + return nil, fmt.Errorf("unknown AgentSkill 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 *AgentSkillMutation) SetField(name string, value ent.Value) error { + switch name { + case agentskill.FieldRepoID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRepoID(v) + return nil + case agentskill.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case agentskill.FieldDescription: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDescription(v) + return nil + case agentskill.FieldScopeType: + v, ok := value.(agentskill.ScopeType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetScopeType(v) + return nil + case agentskill.FieldScopeID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetScopeID(v) + return nil + case agentskill.FieldCreatedBy: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedBy(v) + return nil + case agentskill.FieldActiveVersionID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetActiveVersionID(v) + return nil + case agentskill.FieldIsForceDelivery: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIsForceDelivery(v) + return nil + case agentskill.FieldIsOrphan: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIsOrphan(v) + return nil + case agentskill.FieldIsDeleted: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIsDeleted(v) + return nil + case agentskill.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + case agentskill.FieldUpdatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdatedAt(v) + return nil + } + return fmt.Errorf("unknown AgentSkill field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *AgentSkillMutation) 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 *AgentSkillMutation) 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 *AgentSkillMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown AgentSkill numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *AgentSkillMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(agentskill.FieldDescription) { + fields = append(fields, agentskill.FieldDescription) + } + if m.FieldCleared(agentskill.FieldActiveVersionID) { + fields = append(fields, agentskill.FieldActiveVersionID) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *AgentSkillMutation) 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 *AgentSkillMutation) ClearField(name string) error { + switch name { + case agentskill.FieldDescription: + m.ClearDescription() + return nil + case agentskill.FieldActiveVersionID: + m.ClearActiveVersionID() + return nil + } + return fmt.Errorf("unknown AgentSkill 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 *AgentSkillMutation) ResetField(name string) error { + switch name { + case agentskill.FieldRepoID: + m.ResetRepoID() + return nil + case agentskill.FieldName: + m.ResetName() + return nil + case agentskill.FieldDescription: + m.ResetDescription() + return nil + case agentskill.FieldScopeType: + m.ResetScopeType() + return nil + case agentskill.FieldScopeID: + m.ResetScopeID() + return nil + case agentskill.FieldCreatedBy: + m.ResetCreatedBy() + return nil + case agentskill.FieldActiveVersionID: + m.ResetActiveVersionID() + return nil + case agentskill.FieldIsForceDelivery: + m.ResetIsForceDelivery() + return nil + case agentskill.FieldIsOrphan: + m.ResetIsOrphan() + return nil + case agentskill.FieldIsDeleted: + m.ResetIsDeleted() + return nil + case agentskill.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case agentskill.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + } + return fmt.Errorf("unknown AgentSkill field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *AgentSkillMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.repo != nil { + edges = append(edges, agentskill.EdgeRepo) + } + if m.versions != nil { + edges = append(edges, agentskill.EdgeVersions) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *AgentSkillMutation) AddedIDs(name string) []ent.Value { + switch name { + case agentskill.EdgeRepo: + if id := m.repo; id != nil { + return []ent.Value{*id} + } + case agentskill.EdgeVersions: + ids := make([]ent.Value, 0, len(m.versions)) + for id := range m.versions { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *AgentSkillMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + if m.removedversions != nil { + edges = append(edges, agentskill.EdgeVersions) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *AgentSkillMutation) RemovedIDs(name string) []ent.Value { + switch name { + case agentskill.EdgeVersions: + ids := make([]ent.Value, 0, len(m.removedversions)) + for id := range m.removedversions { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *AgentSkillMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedrepo { + edges = append(edges, agentskill.EdgeRepo) + } + if m.clearedversions { + edges = append(edges, agentskill.EdgeVersions) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *AgentSkillMutation) EdgeCleared(name string) bool { + switch name { + case agentskill.EdgeRepo: + return m.clearedrepo + case agentskill.EdgeVersions: + return m.clearedversions + } + 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 *AgentSkillMutation) ClearEdge(name string) error { + switch name { + case agentskill.EdgeRepo: + m.ClearRepo() + return nil + } + return fmt.Errorf("unknown AgentSkill 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 *AgentSkillMutation) ResetEdge(name string) error { + switch name { + case agentskill.EdgeRepo: + m.ResetRepo() + return nil + case agentskill.EdgeVersions: + m.ResetVersions() + return nil + } + return fmt.Errorf("unknown AgentSkill edge %s", name) +} + +// AgentSkillRepoMutation represents an operation that mutates the AgentSkillRepo nodes in the graph. +type AgentSkillRepoMutation struct { + config + op Op + typ string + id *uuid.UUID + name *string + scope_type *agentskillrepo.ScopeType + scope_id *string + created_by *uuid.UUID + source_type *agentskillrepo.SourceType + github_url *string + ref_type *agentskillrepo.RefType + ref_value *string + last_upload_filename *string + last_upload_at *time.Time + is_deleted *bool + created_at *time.Time + updated_at *time.Time + clearedFields map[string]struct{} + skills map[uuid.UUID]struct{} + removedskills map[uuid.UUID]struct{} + clearedskills bool + done bool + oldValue func(context.Context) (*AgentSkillRepo, error) + predicates []predicate.AgentSkillRepo +} + +var _ ent.Mutation = (*AgentSkillRepoMutation)(nil) + +// agentskillrepoOption allows management of the mutation configuration using functional options. +type agentskillrepoOption func(*AgentSkillRepoMutation) + +// newAgentSkillRepoMutation creates new mutation for the AgentSkillRepo entity. +func newAgentSkillRepoMutation(c config, op Op, opts ...agentskillrepoOption) *AgentSkillRepoMutation { + m := &AgentSkillRepoMutation{ + config: c, + op: op, + typ: TypeAgentSkillRepo, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withAgentSkillRepoID sets the ID field of the mutation. +func withAgentSkillRepoID(id uuid.UUID) agentskillrepoOption { + return func(m *AgentSkillRepoMutation) { + var ( + err error + once sync.Once + value *AgentSkillRepo + ) + m.oldValue = func(ctx context.Context) (*AgentSkillRepo, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().AgentSkillRepo.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withAgentSkillRepo sets the old AgentSkillRepo of the mutation. +func withAgentSkillRepo(node *AgentSkillRepo) agentskillrepoOption { + return func(m *AgentSkillRepoMutation) { + m.oldValue = func(context.Context) (*AgentSkillRepo, 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 AgentSkillRepoMutation) 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 AgentSkillRepoMutation) 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 AgentSkillRepo entities. +func (m *AgentSkillRepoMutation) 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 *AgentSkillRepoMutation) 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 *AgentSkillRepoMutation) 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().AgentSkillRepo.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetName sets the "name" field. +func (m *AgentSkillRepoMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *AgentSkillRepoMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the AgentSkillRepo entity. +// If the AgentSkillRepo 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 *AgentSkillRepoMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *AgentSkillRepoMutation) ResetName() { + m.name = nil +} + +// SetScopeType sets the "scope_type" field. +func (m *AgentSkillRepoMutation) SetScopeType(at agentskillrepo.ScopeType) { + m.scope_type = &at +} + +// ScopeType returns the value of the "scope_type" field in the mutation. +func (m *AgentSkillRepoMutation) ScopeType() (r agentskillrepo.ScopeType, exists bool) { + v := m.scope_type + if v == nil { + return + } + return *v, true +} + +// OldScopeType returns the old "scope_type" field's value of the AgentSkillRepo entity. +// If the AgentSkillRepo 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 *AgentSkillRepoMutation) OldScopeType(ctx context.Context) (v agentskillrepo.ScopeType, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldScopeType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldScopeType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldScopeType: %w", err) + } + return oldValue.ScopeType, nil +} + +// ResetScopeType resets all changes to the "scope_type" field. +func (m *AgentSkillRepoMutation) ResetScopeType() { + m.scope_type = nil +} + +// SetScopeID sets the "scope_id" field. +func (m *AgentSkillRepoMutation) SetScopeID(s string) { + m.scope_id = &s +} + +// ScopeID returns the value of the "scope_id" field in the mutation. +func (m *AgentSkillRepoMutation) ScopeID() (r string, exists bool) { + v := m.scope_id + if v == nil { + return + } + return *v, true +} + +// OldScopeID returns the old "scope_id" field's value of the AgentSkillRepo entity. +// If the AgentSkillRepo 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 *AgentSkillRepoMutation) OldScopeID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldScopeID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldScopeID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldScopeID: %w", err) + } + return oldValue.ScopeID, nil +} + +// ResetScopeID resets all changes to the "scope_id" field. +func (m *AgentSkillRepoMutation) ResetScopeID() { + m.scope_id = nil +} + +// SetCreatedBy sets the "created_by" field. +func (m *AgentSkillRepoMutation) SetCreatedBy(u uuid.UUID) { + m.created_by = &u +} + +// CreatedBy returns the value of the "created_by" field in the mutation. +func (m *AgentSkillRepoMutation) CreatedBy() (r uuid.UUID, exists bool) { + v := m.created_by + if v == nil { + return + } + return *v, true +} + +// OldCreatedBy returns the old "created_by" field's value of the AgentSkillRepo entity. +// If the AgentSkillRepo 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 *AgentSkillRepoMutation) OldCreatedBy(ctx context.Context) (v uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreatedBy is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreatedBy requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreatedBy: %w", err) + } + return oldValue.CreatedBy, nil +} + +// ResetCreatedBy resets all changes to the "created_by" field. +func (m *AgentSkillRepoMutation) ResetCreatedBy() { + m.created_by = nil +} + +// SetSourceType sets the "source_type" field. +func (m *AgentSkillRepoMutation) SetSourceType(at agentskillrepo.SourceType) { + m.source_type = &at +} + +// SourceType returns the value of the "source_type" field in the mutation. +func (m *AgentSkillRepoMutation) SourceType() (r agentskillrepo.SourceType, exists bool) { + v := m.source_type + if v == nil { + return + } + return *v, true +} + +// OldSourceType returns the old "source_type" field's value of the AgentSkillRepo entity. +// If the AgentSkillRepo 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 *AgentSkillRepoMutation) OldSourceType(ctx context.Context) (v agentskillrepo.SourceType, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSourceType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSourceType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSourceType: %w", err) + } + return oldValue.SourceType, nil +} + +// ResetSourceType resets all changes to the "source_type" field. +func (m *AgentSkillRepoMutation) ResetSourceType() { + m.source_type = nil +} + +// SetGithubURL sets the "github_url" field. +func (m *AgentSkillRepoMutation) SetGithubURL(s string) { + m.github_url = &s +} + +// GithubURL returns the value of the "github_url" field in the mutation. +func (m *AgentSkillRepoMutation) GithubURL() (r string, exists bool) { + v := m.github_url + if v == nil { + return + } + return *v, true +} + +// OldGithubURL returns the old "github_url" field's value of the AgentSkillRepo entity. +// If the AgentSkillRepo 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 *AgentSkillRepoMutation) OldGithubURL(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldGithubURL is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldGithubURL requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldGithubURL: %w", err) + } + return oldValue.GithubURL, nil +} + +// ClearGithubURL clears the value of the "github_url" field. +func (m *AgentSkillRepoMutation) ClearGithubURL() { + m.github_url = nil + m.clearedFields[agentskillrepo.FieldGithubURL] = struct{}{} +} + +// GithubURLCleared returns if the "github_url" field was cleared in this mutation. +func (m *AgentSkillRepoMutation) GithubURLCleared() bool { + _, ok := m.clearedFields[agentskillrepo.FieldGithubURL] + return ok +} + +// ResetGithubURL resets all changes to the "github_url" field. +func (m *AgentSkillRepoMutation) ResetGithubURL() { + m.github_url = nil + delete(m.clearedFields, agentskillrepo.FieldGithubURL) +} + +// SetRefType sets the "ref_type" field. +func (m *AgentSkillRepoMutation) SetRefType(at agentskillrepo.RefType) { + m.ref_type = &at +} + +// RefType returns the value of the "ref_type" field in the mutation. +func (m *AgentSkillRepoMutation) RefType() (r agentskillrepo.RefType, exists bool) { + v := m.ref_type + if v == nil { + return + } + return *v, true +} + +// OldRefType returns the old "ref_type" field's value of the AgentSkillRepo entity. +// If the AgentSkillRepo 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 *AgentSkillRepoMutation) OldRefType(ctx context.Context) (v *agentskillrepo.RefType, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRefType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRefType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRefType: %w", err) + } + return oldValue.RefType, nil +} + +// ClearRefType clears the value of the "ref_type" field. +func (m *AgentSkillRepoMutation) ClearRefType() { + m.ref_type = nil + m.clearedFields[agentskillrepo.FieldRefType] = struct{}{} +} + +// RefTypeCleared returns if the "ref_type" field was cleared in this mutation. +func (m *AgentSkillRepoMutation) RefTypeCleared() bool { + _, ok := m.clearedFields[agentskillrepo.FieldRefType] + return ok +} + +// ResetRefType resets all changes to the "ref_type" field. +func (m *AgentSkillRepoMutation) ResetRefType() { + m.ref_type = nil + delete(m.clearedFields, agentskillrepo.FieldRefType) +} + +// SetRefValue sets the "ref_value" field. +func (m *AgentSkillRepoMutation) SetRefValue(s string) { + m.ref_value = &s +} + +// RefValue returns the value of the "ref_value" field in the mutation. +func (m *AgentSkillRepoMutation) RefValue() (r string, exists bool) { + v := m.ref_value + if v == nil { + return + } + return *v, true +} + +// OldRefValue returns the old "ref_value" field's value of the AgentSkillRepo entity. +// If the AgentSkillRepo 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 *AgentSkillRepoMutation) OldRefValue(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRefValue is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRefValue requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRefValue: %w", err) + } + return oldValue.RefValue, nil +} + +// ClearRefValue clears the value of the "ref_value" field. +func (m *AgentSkillRepoMutation) ClearRefValue() { + m.ref_value = nil + m.clearedFields[agentskillrepo.FieldRefValue] = struct{}{} +} + +// RefValueCleared returns if the "ref_value" field was cleared in this mutation. +func (m *AgentSkillRepoMutation) RefValueCleared() bool { + _, ok := m.clearedFields[agentskillrepo.FieldRefValue] + return ok +} + +// ResetRefValue resets all changes to the "ref_value" field. +func (m *AgentSkillRepoMutation) ResetRefValue() { + m.ref_value = nil + delete(m.clearedFields, agentskillrepo.FieldRefValue) +} + +// SetLastUploadFilename sets the "last_upload_filename" field. +func (m *AgentSkillRepoMutation) SetLastUploadFilename(s string) { + m.last_upload_filename = &s +} + +// LastUploadFilename returns the value of the "last_upload_filename" field in the mutation. +func (m *AgentSkillRepoMutation) LastUploadFilename() (r string, exists bool) { + v := m.last_upload_filename + if v == nil { + return + } + return *v, true +} + +// OldLastUploadFilename returns the old "last_upload_filename" field's value of the AgentSkillRepo entity. +// If the AgentSkillRepo 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 *AgentSkillRepoMutation) OldLastUploadFilename(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldLastUploadFilename is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldLastUploadFilename requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldLastUploadFilename: %w", err) + } + return oldValue.LastUploadFilename, nil +} + +// ClearLastUploadFilename clears the value of the "last_upload_filename" field. +func (m *AgentSkillRepoMutation) ClearLastUploadFilename() { + m.last_upload_filename = nil + m.clearedFields[agentskillrepo.FieldLastUploadFilename] = struct{}{} +} + +// LastUploadFilenameCleared returns if the "last_upload_filename" field was cleared in this mutation. +func (m *AgentSkillRepoMutation) LastUploadFilenameCleared() bool { + _, ok := m.clearedFields[agentskillrepo.FieldLastUploadFilename] + return ok +} + +// ResetLastUploadFilename resets all changes to the "last_upload_filename" field. +func (m *AgentSkillRepoMutation) ResetLastUploadFilename() { + m.last_upload_filename = nil + delete(m.clearedFields, agentskillrepo.FieldLastUploadFilename) +} + +// SetLastUploadAt sets the "last_upload_at" field. +func (m *AgentSkillRepoMutation) SetLastUploadAt(t time.Time) { + m.last_upload_at = &t +} + +// LastUploadAt returns the value of the "last_upload_at" field in the mutation. +func (m *AgentSkillRepoMutation) LastUploadAt() (r time.Time, exists bool) { + v := m.last_upload_at + if v == nil { + return + } + return *v, true +} + +// OldLastUploadAt returns the old "last_upload_at" field's value of the AgentSkillRepo entity. +// If the AgentSkillRepo 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 *AgentSkillRepoMutation) OldLastUploadAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldLastUploadAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldLastUploadAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldLastUploadAt: %w", err) + } + return oldValue.LastUploadAt, nil +} + +// ClearLastUploadAt clears the value of the "last_upload_at" field. +func (m *AgentSkillRepoMutation) ClearLastUploadAt() { + m.last_upload_at = nil + m.clearedFields[agentskillrepo.FieldLastUploadAt] = struct{}{} +} + +// LastUploadAtCleared returns if the "last_upload_at" field was cleared in this mutation. +func (m *AgentSkillRepoMutation) LastUploadAtCleared() bool { + _, ok := m.clearedFields[agentskillrepo.FieldLastUploadAt] + return ok +} + +// ResetLastUploadAt resets all changes to the "last_upload_at" field. +func (m *AgentSkillRepoMutation) ResetLastUploadAt() { + m.last_upload_at = nil + delete(m.clearedFields, agentskillrepo.FieldLastUploadAt) +} + +// SetIsDeleted sets the "is_deleted" field. +func (m *AgentSkillRepoMutation) SetIsDeleted(b bool) { + m.is_deleted = &b +} + +// IsDeleted returns the value of the "is_deleted" field in the mutation. +func (m *AgentSkillRepoMutation) IsDeleted() (r bool, exists bool) { + v := m.is_deleted + if v == nil { + return + } + return *v, true +} + +// OldIsDeleted returns the old "is_deleted" field's value of the AgentSkillRepo entity. +// If the AgentSkillRepo 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 *AgentSkillRepoMutation) OldIsDeleted(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldIsDeleted is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldIsDeleted requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldIsDeleted: %w", err) + } + return oldValue.IsDeleted, nil +} + +// ResetIsDeleted resets all changes to the "is_deleted" field. +func (m *AgentSkillRepoMutation) ResetIsDeleted() { + m.is_deleted = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *AgentSkillRepoMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *AgentSkillRepoMutation) 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 AgentSkillRepo entity. +// If the AgentSkillRepo 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 *AgentSkillRepoMutation) 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 *AgentSkillRepoMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *AgentSkillRepoMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *AgentSkillRepoMutation) UpdatedAt() (r time.Time, exists bool) { + v := m.updated_at + if v == nil { + return + } + return *v, true +} + +// OldUpdatedAt returns the old "updated_at" field's value of the AgentSkillRepo entity. +// If the AgentSkillRepo 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 *AgentSkillRepoMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUpdatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) + } + return oldValue.UpdatedAt, nil +} + +// ResetUpdatedAt resets all changes to the "updated_at" field. +func (m *AgentSkillRepoMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// AddSkillIDs adds the "skills" edge to the AgentSkill entity by ids. +func (m *AgentSkillRepoMutation) AddSkillIDs(ids ...uuid.UUID) { + if m.skills == nil { + m.skills = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.skills[ids[i]] = struct{}{} + } +} + +// ClearSkills clears the "skills" edge to the AgentSkill entity. +func (m *AgentSkillRepoMutation) ClearSkills() { + m.clearedskills = true +} + +// SkillsCleared reports if the "skills" edge to the AgentSkill entity was cleared. +func (m *AgentSkillRepoMutation) SkillsCleared() bool { + return m.clearedskills +} + +// RemoveSkillIDs removes the "skills" edge to the AgentSkill entity by IDs. +func (m *AgentSkillRepoMutation) RemoveSkillIDs(ids ...uuid.UUID) { + if m.removedskills == nil { + m.removedskills = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.skills, ids[i]) + m.removedskills[ids[i]] = struct{}{} + } +} + +// RemovedSkills returns the removed IDs of the "skills" edge to the AgentSkill entity. +func (m *AgentSkillRepoMutation) RemovedSkillsIDs() (ids []uuid.UUID) { + for id := range m.removedskills { + ids = append(ids, id) + } + return +} + +// SkillsIDs returns the "skills" edge IDs in the mutation. +func (m *AgentSkillRepoMutation) SkillsIDs() (ids []uuid.UUID) { + for id := range m.skills { + ids = append(ids, id) + } + return +} + +// ResetSkills resets all changes to the "skills" edge. +func (m *AgentSkillRepoMutation) ResetSkills() { + m.skills = nil + m.clearedskills = false + m.removedskills = nil +} + +// Where appends a list predicates to the AgentSkillRepoMutation builder. +func (m *AgentSkillRepoMutation) Where(ps ...predicate.AgentSkillRepo) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the AgentSkillRepoMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *AgentSkillRepoMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.AgentSkillRepo, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *AgentSkillRepoMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *AgentSkillRepoMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (AgentSkillRepo). +func (m *AgentSkillRepoMutation) 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 *AgentSkillRepoMutation) Fields() []string { + fields := make([]string, 0, 13) + if m.name != nil { + fields = append(fields, agentskillrepo.FieldName) + } + if m.scope_type != nil { + fields = append(fields, agentskillrepo.FieldScopeType) + } + if m.scope_id != nil { + fields = append(fields, agentskillrepo.FieldScopeID) + } + if m.created_by != nil { + fields = append(fields, agentskillrepo.FieldCreatedBy) + } + if m.source_type != nil { + fields = append(fields, agentskillrepo.FieldSourceType) + } + if m.github_url != nil { + fields = append(fields, agentskillrepo.FieldGithubURL) + } + if m.ref_type != nil { + fields = append(fields, agentskillrepo.FieldRefType) + } + if m.ref_value != nil { + fields = append(fields, agentskillrepo.FieldRefValue) + } + if m.last_upload_filename != nil { + fields = append(fields, agentskillrepo.FieldLastUploadFilename) + } + if m.last_upload_at != nil { + fields = append(fields, agentskillrepo.FieldLastUploadAt) + } + if m.is_deleted != nil { + fields = append(fields, agentskillrepo.FieldIsDeleted) + } + if m.created_at != nil { + fields = append(fields, agentskillrepo.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, agentskillrepo.FieldUpdatedAt) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *AgentSkillRepoMutation) Field(name string) (ent.Value, bool) { + switch name { + case agentskillrepo.FieldName: + return m.Name() + case agentskillrepo.FieldScopeType: + return m.ScopeType() + case agentskillrepo.FieldScopeID: + return m.ScopeID() + case agentskillrepo.FieldCreatedBy: + return m.CreatedBy() + case agentskillrepo.FieldSourceType: + return m.SourceType() + case agentskillrepo.FieldGithubURL: + return m.GithubURL() + case agentskillrepo.FieldRefType: + return m.RefType() + case agentskillrepo.FieldRefValue: + return m.RefValue() + case agentskillrepo.FieldLastUploadFilename: + return m.LastUploadFilename() + case agentskillrepo.FieldLastUploadAt: + return m.LastUploadAt() + case agentskillrepo.FieldIsDeleted: + return m.IsDeleted() + case agentskillrepo.FieldCreatedAt: + return m.CreatedAt() + case agentskillrepo.FieldUpdatedAt: + return m.UpdatedAt() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *AgentSkillRepoMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case agentskillrepo.FieldName: + return m.OldName(ctx) + case agentskillrepo.FieldScopeType: + return m.OldScopeType(ctx) + case agentskillrepo.FieldScopeID: + return m.OldScopeID(ctx) + case agentskillrepo.FieldCreatedBy: + return m.OldCreatedBy(ctx) + case agentskillrepo.FieldSourceType: + return m.OldSourceType(ctx) + case agentskillrepo.FieldGithubURL: + return m.OldGithubURL(ctx) + case agentskillrepo.FieldRefType: + return m.OldRefType(ctx) + case agentskillrepo.FieldRefValue: + return m.OldRefValue(ctx) + case agentskillrepo.FieldLastUploadFilename: + return m.OldLastUploadFilename(ctx) + case agentskillrepo.FieldLastUploadAt: + return m.OldLastUploadAt(ctx) + case agentskillrepo.FieldIsDeleted: + return m.OldIsDeleted(ctx) + case agentskillrepo.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case agentskillrepo.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + } + return nil, fmt.Errorf("unknown AgentSkillRepo 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 *AgentSkillRepoMutation) SetField(name string, value ent.Value) error { + switch name { + case agentskillrepo.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case agentskillrepo.FieldScopeType: + v, ok := value.(agentskillrepo.ScopeType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetScopeType(v) + return nil + case agentskillrepo.FieldScopeID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetScopeID(v) + return nil + case agentskillrepo.FieldCreatedBy: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedBy(v) + return nil + case agentskillrepo.FieldSourceType: + v, ok := value.(agentskillrepo.SourceType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSourceType(v) + return nil + case agentskillrepo.FieldGithubURL: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetGithubURL(v) + return nil + case agentskillrepo.FieldRefType: + v, ok := value.(agentskillrepo.RefType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRefType(v) + return nil + case agentskillrepo.FieldRefValue: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRefValue(v) + return nil + case agentskillrepo.FieldLastUploadFilename: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLastUploadFilename(v) + return nil + case agentskillrepo.FieldLastUploadAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLastUploadAt(v) + return nil + case agentskillrepo.FieldIsDeleted: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIsDeleted(v) + return nil + case agentskillrepo.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + case agentskillrepo.FieldUpdatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdatedAt(v) + return nil + } + return fmt.Errorf("unknown AgentSkillRepo field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *AgentSkillRepoMutation) 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 *AgentSkillRepoMutation) 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 *AgentSkillRepoMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown AgentSkillRepo numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *AgentSkillRepoMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(agentskillrepo.FieldGithubURL) { + fields = append(fields, agentskillrepo.FieldGithubURL) + } + if m.FieldCleared(agentskillrepo.FieldRefType) { + fields = append(fields, agentskillrepo.FieldRefType) + } + if m.FieldCleared(agentskillrepo.FieldRefValue) { + fields = append(fields, agentskillrepo.FieldRefValue) + } + if m.FieldCleared(agentskillrepo.FieldLastUploadFilename) { + fields = append(fields, agentskillrepo.FieldLastUploadFilename) + } + if m.FieldCleared(agentskillrepo.FieldLastUploadAt) { + fields = append(fields, agentskillrepo.FieldLastUploadAt) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *AgentSkillRepoMutation) 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 *AgentSkillRepoMutation) ClearField(name string) error { + switch name { + case agentskillrepo.FieldGithubURL: + m.ClearGithubURL() + return nil + case agentskillrepo.FieldRefType: + m.ClearRefType() + return nil + case agentskillrepo.FieldRefValue: + m.ClearRefValue() + return nil + case agentskillrepo.FieldLastUploadFilename: + m.ClearLastUploadFilename() + return nil + case agentskillrepo.FieldLastUploadAt: + m.ClearLastUploadAt() + return nil + } + return fmt.Errorf("unknown AgentSkillRepo 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 *AgentSkillRepoMutation) ResetField(name string) error { + switch name { + case agentskillrepo.FieldName: + m.ResetName() + return nil + case agentskillrepo.FieldScopeType: + m.ResetScopeType() + return nil + case agentskillrepo.FieldScopeID: + m.ResetScopeID() + return nil + case agentskillrepo.FieldCreatedBy: + m.ResetCreatedBy() + return nil + case agentskillrepo.FieldSourceType: + m.ResetSourceType() + return nil + case agentskillrepo.FieldGithubURL: + m.ResetGithubURL() + return nil + case agentskillrepo.FieldRefType: + m.ResetRefType() + return nil + case agentskillrepo.FieldRefValue: + m.ResetRefValue() + return nil + case agentskillrepo.FieldLastUploadFilename: + m.ResetLastUploadFilename() + return nil + case agentskillrepo.FieldLastUploadAt: + m.ResetLastUploadAt() + return nil + case agentskillrepo.FieldIsDeleted: + m.ResetIsDeleted() + return nil + case agentskillrepo.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case agentskillrepo.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + } + return fmt.Errorf("unknown AgentSkillRepo field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *AgentSkillRepoMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.skills != nil { + edges = append(edges, agentskillrepo.EdgeSkills) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *AgentSkillRepoMutation) AddedIDs(name string) []ent.Value { + switch name { + case agentskillrepo.EdgeSkills: + ids := make([]ent.Value, 0, len(m.skills)) + for id := range m.skills { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *AgentSkillRepoMutation) RemovedEdges() []string { + edges := make([]string, 0, 1) + if m.removedskills != nil { + edges = append(edges, agentskillrepo.EdgeSkills) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *AgentSkillRepoMutation) RemovedIDs(name string) []ent.Value { + switch name { + case agentskillrepo.EdgeSkills: + ids := make([]ent.Value, 0, len(m.removedskills)) + for id := range m.removedskills { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *AgentSkillRepoMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedskills { + edges = append(edges, agentskillrepo.EdgeSkills) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *AgentSkillRepoMutation) EdgeCleared(name string) bool { + switch name { + case agentskillrepo.EdgeSkills: + return m.clearedskills + } + 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 *AgentSkillRepoMutation) ClearEdge(name string) error { + switch name { + } + return fmt.Errorf("unknown AgentSkillRepo 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 *AgentSkillRepoMutation) ResetEdge(name string) error { + switch name { + case agentskillrepo.EdgeSkills: + m.ResetSkills() + return nil + } + return fmt.Errorf("unknown AgentSkillRepo edge %s", name) +} + +// AgentSkillVersionMutation represents an operation that mutates the AgentSkillVersion nodes in the graph. +type AgentSkillVersionMutation struct { + config + op Op + typ string + id *uuid.UUID + version *string + s3_key *string + parsed_meta *types.SkillParsedMeta + created_at *time.Time + clearedFields map[string]struct{} + skill *uuid.UUID + clearedskill bool + done bool + oldValue func(context.Context) (*AgentSkillVersion, error) + predicates []predicate.AgentSkillVersion +} + +var _ ent.Mutation = (*AgentSkillVersionMutation)(nil) + +// agentskillversionOption allows management of the mutation configuration using functional options. +type agentskillversionOption func(*AgentSkillVersionMutation) + +// newAgentSkillVersionMutation creates new mutation for the AgentSkillVersion entity. +func newAgentSkillVersionMutation(c config, op Op, opts ...agentskillversionOption) *AgentSkillVersionMutation { + m := &AgentSkillVersionMutation{ + config: c, + op: op, + typ: TypeAgentSkillVersion, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withAgentSkillVersionID sets the ID field of the mutation. +func withAgentSkillVersionID(id uuid.UUID) agentskillversionOption { + return func(m *AgentSkillVersionMutation) { + var ( + err error + once sync.Once + value *AgentSkillVersion + ) + m.oldValue = func(ctx context.Context) (*AgentSkillVersion, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().AgentSkillVersion.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withAgentSkillVersion sets the old AgentSkillVersion of the mutation. +func withAgentSkillVersion(node *AgentSkillVersion) agentskillversionOption { + return func(m *AgentSkillVersionMutation) { + m.oldValue = func(context.Context) (*AgentSkillVersion, 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 AgentSkillVersionMutation) 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 AgentSkillVersionMutation) 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 AgentSkillVersion entities. +func (m *AgentSkillVersionMutation) 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 *AgentSkillVersionMutation) 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 *AgentSkillVersionMutation) 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().AgentSkillVersion.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetResourceID sets the "resource_id" field. +func (m *AgentSkillVersionMutation) SetResourceID(u uuid.UUID) { + m.skill = &u +} + +// ResourceID returns the value of the "resource_id" field in the mutation. +func (m *AgentSkillVersionMutation) ResourceID() (r uuid.UUID, exists bool) { + v := m.skill + if v == nil { + return + } + return *v, true +} + +// OldResourceID returns the old "resource_id" field's value of the AgentSkillVersion entity. +// If the AgentSkillVersion 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 *AgentSkillVersionMutation) OldResourceID(ctx context.Context) (v uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldResourceID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldResourceID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldResourceID: %w", err) + } + return oldValue.ResourceID, nil +} + +// ResetResourceID resets all changes to the "resource_id" field. +func (m *AgentSkillVersionMutation) ResetResourceID() { + m.skill = nil +} + +// SetVersion sets the "version" field. +func (m *AgentSkillVersionMutation) SetVersion(s string) { + m.version = &s +} + +// Version returns the value of the "version" field in the mutation. +func (m *AgentSkillVersionMutation) 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 AgentSkillVersion entity. +// If the AgentSkillVersion 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 *AgentSkillVersionMutation) 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 *AgentSkillVersionMutation) ResetVersion() { + m.version = nil +} + +// SetS3Key sets the "s3_key" field. +func (m *AgentSkillVersionMutation) SetS3Key(s string) { + m.s3_key = &s +} + +// S3Key returns the value of the "s3_key" field in the mutation. +func (m *AgentSkillVersionMutation) S3Key() (r string, exists bool) { + v := m.s3_key + if v == nil { + return + } + return *v, true +} + +// OldS3Key returns the old "s3_key" field's value of the AgentSkillVersion entity. +// If the AgentSkillVersion 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 *AgentSkillVersionMutation) OldS3Key(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldS3Key is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldS3Key requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldS3Key: %w", err) + } + return oldValue.S3Key, nil +} + +// ResetS3Key resets all changes to the "s3_key" field. +func (m *AgentSkillVersionMutation) ResetS3Key() { + m.s3_key = nil +} + +// SetParsedMeta sets the "parsed_meta" field. +func (m *AgentSkillVersionMutation) SetParsedMeta(tpm types.SkillParsedMeta) { + m.parsed_meta = &tpm +} + +// ParsedMeta returns the value of the "parsed_meta" field in the mutation. +func (m *AgentSkillVersionMutation) ParsedMeta() (r types.SkillParsedMeta, exists bool) { + v := m.parsed_meta + if v == nil { + return + } + return *v, true +} + +// OldParsedMeta returns the old "parsed_meta" field's value of the AgentSkillVersion entity. +// If the AgentSkillVersion 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 *AgentSkillVersionMutation) OldParsedMeta(ctx context.Context) (v types.SkillParsedMeta, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldParsedMeta is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldParsedMeta requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldParsedMeta: %w", err) + } + return oldValue.ParsedMeta, nil +} + +// ClearParsedMeta clears the value of the "parsed_meta" field. +func (m *AgentSkillVersionMutation) ClearParsedMeta() { + m.parsed_meta = nil + m.clearedFields[agentskillversion.FieldParsedMeta] = struct{}{} +} + +// ParsedMetaCleared returns if the "parsed_meta" field was cleared in this mutation. +func (m *AgentSkillVersionMutation) ParsedMetaCleared() bool { + _, ok := m.clearedFields[agentskillversion.FieldParsedMeta] + return ok +} + +// ResetParsedMeta resets all changes to the "parsed_meta" field. +func (m *AgentSkillVersionMutation) ResetParsedMeta() { + m.parsed_meta = nil + delete(m.clearedFields, agentskillversion.FieldParsedMeta) +} + +// SetCreatedAt sets the "created_at" field. +func (m *AgentSkillVersionMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *AgentSkillVersionMutation) 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 AgentSkillVersion entity. +// If the AgentSkillVersion 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 *AgentSkillVersionMutation) 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 *AgentSkillVersionMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetSkillID sets the "skill" edge to the AgentSkill entity by id. +func (m *AgentSkillVersionMutation) SetSkillID(id uuid.UUID) { + m.skill = &id +} + +// ClearSkill clears the "skill" edge to the AgentSkill entity. +func (m *AgentSkillVersionMutation) ClearSkill() { + m.clearedskill = true + m.clearedFields[agentskillversion.FieldResourceID] = struct{}{} +} + +// SkillCleared reports if the "skill" edge to the AgentSkill entity was cleared. +func (m *AgentSkillVersionMutation) SkillCleared() bool { + return m.clearedskill +} + +// SkillID returns the "skill" edge ID in the mutation. +func (m *AgentSkillVersionMutation) SkillID() (id uuid.UUID, exists bool) { + if m.skill != nil { + return *m.skill, true + } + return +} + +// SkillIDs returns the "skill" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// SkillID instead. It exists only for internal usage by the builders. +func (m *AgentSkillVersionMutation) SkillIDs() (ids []uuid.UUID) { + if id := m.skill; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetSkill resets all changes to the "skill" edge. +func (m *AgentSkillVersionMutation) ResetSkill() { + m.skill = nil + m.clearedskill = false +} + +// Where appends a list predicates to the AgentSkillVersionMutation builder. +func (m *AgentSkillVersionMutation) Where(ps ...predicate.AgentSkillVersion) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the AgentSkillVersionMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *AgentSkillVersionMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.AgentSkillVersion, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *AgentSkillVersionMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *AgentSkillVersionMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (AgentSkillVersion). +func (m *AgentSkillVersionMutation) 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 *AgentSkillVersionMutation) Fields() []string { + fields := make([]string, 0, 5) + if m.skill != nil { + fields = append(fields, agentskillversion.FieldResourceID) + } + if m.version != nil { + fields = append(fields, agentskillversion.FieldVersion) + } + if m.s3_key != nil { + fields = append(fields, agentskillversion.FieldS3Key) + } + if m.parsed_meta != nil { + fields = append(fields, agentskillversion.FieldParsedMeta) + } + if m.created_at != nil { + fields = append(fields, agentskillversion.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 *AgentSkillVersionMutation) Field(name string) (ent.Value, bool) { + switch name { + case agentskillversion.FieldResourceID: + return m.ResourceID() + case agentskillversion.FieldVersion: + return m.Version() + case agentskillversion.FieldS3Key: + return m.S3Key() + case agentskillversion.FieldParsedMeta: + return m.ParsedMeta() + case agentskillversion.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 *AgentSkillVersionMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case agentskillversion.FieldResourceID: + return m.OldResourceID(ctx) + case agentskillversion.FieldVersion: + return m.OldVersion(ctx) + case agentskillversion.FieldS3Key: + return m.OldS3Key(ctx) + case agentskillversion.FieldParsedMeta: + return m.OldParsedMeta(ctx) + case agentskillversion.FieldCreatedAt: + return m.OldCreatedAt(ctx) + } + return nil, fmt.Errorf("unknown AgentSkillVersion 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 *AgentSkillVersionMutation) SetField(name string, value ent.Value) error { + switch name { + case agentskillversion.FieldResourceID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetResourceID(v) + return nil + case agentskillversion.FieldVersion: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetVersion(v) + return nil + case agentskillversion.FieldS3Key: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetS3Key(v) + return nil + case agentskillversion.FieldParsedMeta: + v, ok := value.(types.SkillParsedMeta) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetParsedMeta(v) + return nil + case agentskillversion.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 AgentSkillVersion field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *AgentSkillVersionMutation) 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 *AgentSkillVersionMutation) 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 *AgentSkillVersionMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown AgentSkillVersion numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *AgentSkillVersionMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(agentskillversion.FieldParsedMeta) { + fields = append(fields, agentskillversion.FieldParsedMeta) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *AgentSkillVersionMutation) 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 *AgentSkillVersionMutation) ClearField(name string) error { + switch name { + case agentskillversion.FieldParsedMeta: + m.ClearParsedMeta() + return nil + } + return fmt.Errorf("unknown AgentSkillVersion 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 *AgentSkillVersionMutation) ResetField(name string) error { + switch name { + case agentskillversion.FieldResourceID: + m.ResetResourceID() + return nil + case agentskillversion.FieldVersion: + m.ResetVersion() + return nil + case agentskillversion.FieldS3Key: + m.ResetS3Key() + return nil + case agentskillversion.FieldParsedMeta: + m.ResetParsedMeta() + return nil + case agentskillversion.FieldCreatedAt: + m.ResetCreatedAt() + return nil + } + return fmt.Errorf("unknown AgentSkillVersion field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *AgentSkillVersionMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.skill != nil { + edges = append(edges, agentskillversion.EdgeSkill) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *AgentSkillVersionMutation) AddedIDs(name string) []ent.Value { + switch name { + case agentskillversion.EdgeSkill: + if id := m.skill; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *AgentSkillVersionMutation) RemovedEdges() []string { + edges := make([]string, 0, 1) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *AgentSkillVersionMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *AgentSkillVersionMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedskill { + edges = append(edges, agentskillversion.EdgeSkill) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *AgentSkillVersionMutation) EdgeCleared(name string) bool { + switch name { + case agentskillversion.EdgeSkill: + return m.clearedskill + } + 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 *AgentSkillVersionMutation) ClearEdge(name string) error { + switch name { + case agentskillversion.EdgeSkill: + m.ClearSkill() + return nil + } + return fmt.Errorf("unknown AgentSkillVersion 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 *AgentSkillVersionMutation) ResetEdge(name string) error { + switch name { + case agentskillversion.EdgeSkill: + m.ResetSkill() + return nil + } + return fmt.Errorf("unknown AgentSkillVersion edge %s", name) +} + +// AgentSyncJobMutation represents an operation that mutates the AgentSyncJob nodes in the graph. +type AgentSyncJobMutation struct { + config + op Op + typ string + id *uuid.UUID + resource_kind *agentsyncjob.ResourceKind + rule_id *uuid.UUID + repo_id *uuid.UUID + source_type *agentsyncjob.SourceType + status *agentsyncjob.Status + trigger_type *agentsyncjob.TriggerType + triggered_by *uuid.UUID + started_at *time.Time + finished_at *time.Time + errors *types.SyncJobErrors + appenderrors types.SyncJobErrors + result_summary *types.SyncJobResultSummary + created_at *time.Time + updated_at *time.Time + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*AgentSyncJob, error) + predicates []predicate.AgentSyncJob +} + +var _ ent.Mutation = (*AgentSyncJobMutation)(nil) + +// agentsyncjobOption allows management of the mutation configuration using functional options. +type agentsyncjobOption func(*AgentSyncJobMutation) + +// newAgentSyncJobMutation creates new mutation for the AgentSyncJob entity. +func newAgentSyncJobMutation(c config, op Op, opts ...agentsyncjobOption) *AgentSyncJobMutation { + m := &AgentSyncJobMutation{ + config: c, + op: op, + typ: TypeAgentSyncJob, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withAgentSyncJobID sets the ID field of the mutation. +func withAgentSyncJobID(id uuid.UUID) agentsyncjobOption { + return func(m *AgentSyncJobMutation) { + var ( + err error + once sync.Once + value *AgentSyncJob + ) + m.oldValue = func(ctx context.Context) (*AgentSyncJob, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().AgentSyncJob.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withAgentSyncJob sets the old AgentSyncJob of the mutation. +func withAgentSyncJob(node *AgentSyncJob) agentsyncjobOption { + return func(m *AgentSyncJobMutation) { + m.oldValue = func(context.Context) (*AgentSyncJob, 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 AgentSyncJobMutation) 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 AgentSyncJobMutation) 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 AgentSyncJob entities. +func (m *AgentSyncJobMutation) 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 *AgentSyncJobMutation) 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 *AgentSyncJobMutation) 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().AgentSyncJob.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetResourceKind sets the "resource_kind" field. +func (m *AgentSyncJobMutation) SetResourceKind(ak agentsyncjob.ResourceKind) { + m.resource_kind = &ak +} + +// ResourceKind returns the value of the "resource_kind" field in the mutation. +func (m *AgentSyncJobMutation) ResourceKind() (r agentsyncjob.ResourceKind, exists bool) { + v := m.resource_kind + if v == nil { + return + } + return *v, true +} + +// OldResourceKind returns the old "resource_kind" field's value of the AgentSyncJob entity. +// If the AgentSyncJob 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 *AgentSyncJobMutation) OldResourceKind(ctx context.Context) (v agentsyncjob.ResourceKind, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldResourceKind is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldResourceKind requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldResourceKind: %w", err) + } + return oldValue.ResourceKind, nil +} + +// ResetResourceKind resets all changes to the "resource_kind" field. +func (m *AgentSyncJobMutation) ResetResourceKind() { + m.resource_kind = nil +} + +// SetRuleID sets the "rule_id" field. +func (m *AgentSyncJobMutation) SetRuleID(u uuid.UUID) { + m.rule_id = &u +} + +// RuleID returns the value of the "rule_id" field in the mutation. +func (m *AgentSyncJobMutation) RuleID() (r uuid.UUID, exists bool) { + v := m.rule_id + if v == nil { + return + } + return *v, true +} + +// OldRuleID returns the old "rule_id" field's value of the AgentSyncJob entity. +// If the AgentSyncJob 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 *AgentSyncJobMutation) OldRuleID(ctx context.Context) (v *uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRuleID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRuleID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRuleID: %w", err) + } + return oldValue.RuleID, nil +} + +// ClearRuleID clears the value of the "rule_id" field. +func (m *AgentSyncJobMutation) ClearRuleID() { + m.rule_id = nil + m.clearedFields[agentsyncjob.FieldRuleID] = struct{}{} +} + +// RuleIDCleared returns if the "rule_id" field was cleared in this mutation. +func (m *AgentSyncJobMutation) RuleIDCleared() bool { + _, ok := m.clearedFields[agentsyncjob.FieldRuleID] + return ok +} + +// ResetRuleID resets all changes to the "rule_id" field. +func (m *AgentSyncJobMutation) ResetRuleID() { + m.rule_id = nil + delete(m.clearedFields, agentsyncjob.FieldRuleID) +} + +// SetRepoID sets the "repo_id" field. +func (m *AgentSyncJobMutation) SetRepoID(u uuid.UUID) { + m.repo_id = &u +} + +// RepoID returns the value of the "repo_id" field in the mutation. +func (m *AgentSyncJobMutation) RepoID() (r uuid.UUID, exists bool) { + v := m.repo_id + if v == nil { + return + } + return *v, true +} + +// OldRepoID returns the old "repo_id" field's value of the AgentSyncJob entity. +// If the AgentSyncJob 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 *AgentSyncJobMutation) OldRepoID(ctx context.Context) (v *uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRepoID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRepoID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRepoID: %w", err) + } + return oldValue.RepoID, nil +} + +// ClearRepoID clears the value of the "repo_id" field. +func (m *AgentSyncJobMutation) ClearRepoID() { + m.repo_id = nil + m.clearedFields[agentsyncjob.FieldRepoID] = struct{}{} +} + +// RepoIDCleared returns if the "repo_id" field was cleared in this mutation. +func (m *AgentSyncJobMutation) RepoIDCleared() bool { + _, ok := m.clearedFields[agentsyncjob.FieldRepoID] + return ok +} + +// ResetRepoID resets all changes to the "repo_id" field. +func (m *AgentSyncJobMutation) ResetRepoID() { + m.repo_id = nil + delete(m.clearedFields, agentsyncjob.FieldRepoID) +} + +// SetSourceType sets the "source_type" field. +func (m *AgentSyncJobMutation) SetSourceType(at agentsyncjob.SourceType) { + m.source_type = &at +} + +// SourceType returns the value of the "source_type" field in the mutation. +func (m *AgentSyncJobMutation) SourceType() (r agentsyncjob.SourceType, exists bool) { + v := m.source_type + if v == nil { + return + } + return *v, true +} + +// OldSourceType returns the old "source_type" field's value of the AgentSyncJob entity. +// If the AgentSyncJob 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 *AgentSyncJobMutation) OldSourceType(ctx context.Context) (v agentsyncjob.SourceType, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSourceType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSourceType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSourceType: %w", err) + } + return oldValue.SourceType, nil +} + +// ResetSourceType resets all changes to the "source_type" field. +func (m *AgentSyncJobMutation) ResetSourceType() { + m.source_type = nil +} + +// SetStatus sets the "status" field. +func (m *AgentSyncJobMutation) SetStatus(a agentsyncjob.Status) { + m.status = &a +} + +// Status returns the value of the "status" field in the mutation. +func (m *AgentSyncJobMutation) Status() (r agentsyncjob.Status, exists bool) { + v := m.status + if v == nil { + return + } + return *v, true +} + +// OldStatus returns the old "status" field's value of the AgentSyncJob entity. +// If the AgentSyncJob 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 *AgentSyncJobMutation) OldStatus(ctx context.Context) (v agentsyncjob.Status, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldStatus is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldStatus requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldStatus: %w", err) + } + return oldValue.Status, nil +} + +// ResetStatus resets all changes to the "status" field. +func (m *AgentSyncJobMutation) ResetStatus() { + m.status = nil +} + +// SetTriggerType sets the "trigger_type" field. +func (m *AgentSyncJobMutation) SetTriggerType(at agentsyncjob.TriggerType) { + m.trigger_type = &at +} + +// TriggerType returns the value of the "trigger_type" field in the mutation. +func (m *AgentSyncJobMutation) TriggerType() (r agentsyncjob.TriggerType, exists bool) { + v := m.trigger_type + if v == nil { + return + } + return *v, true +} + +// OldTriggerType returns the old "trigger_type" field's value of the AgentSyncJob entity. +// If the AgentSyncJob 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 *AgentSyncJobMutation) OldTriggerType(ctx context.Context) (v agentsyncjob.TriggerType, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTriggerType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTriggerType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTriggerType: %w", err) + } + return oldValue.TriggerType, nil +} + +// ResetTriggerType resets all changes to the "trigger_type" field. +func (m *AgentSyncJobMutation) ResetTriggerType() { + m.trigger_type = nil +} + +// SetTriggeredBy sets the "triggered_by" field. +func (m *AgentSyncJobMutation) SetTriggeredBy(u uuid.UUID) { + m.triggered_by = &u +} + +// TriggeredBy returns the value of the "triggered_by" field in the mutation. +func (m *AgentSyncJobMutation) TriggeredBy() (r uuid.UUID, exists bool) { + v := m.triggered_by + if v == nil { + return + } + return *v, true +} + +// OldTriggeredBy returns the old "triggered_by" field's value of the AgentSyncJob entity. +// If the AgentSyncJob 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 *AgentSyncJobMutation) OldTriggeredBy(ctx context.Context) (v *uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTriggeredBy is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTriggeredBy requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTriggeredBy: %w", err) + } + return oldValue.TriggeredBy, nil +} + +// ClearTriggeredBy clears the value of the "triggered_by" field. +func (m *AgentSyncJobMutation) ClearTriggeredBy() { + m.triggered_by = nil + m.clearedFields[agentsyncjob.FieldTriggeredBy] = struct{}{} +} + +// TriggeredByCleared returns if the "triggered_by" field was cleared in this mutation. +func (m *AgentSyncJobMutation) TriggeredByCleared() bool { + _, ok := m.clearedFields[agentsyncjob.FieldTriggeredBy] + return ok +} + +// ResetTriggeredBy resets all changes to the "triggered_by" field. +func (m *AgentSyncJobMutation) ResetTriggeredBy() { + m.triggered_by = nil + delete(m.clearedFields, agentsyncjob.FieldTriggeredBy) +} + +// SetStartedAt sets the "started_at" field. +func (m *AgentSyncJobMutation) SetStartedAt(t time.Time) { + m.started_at = &t +} + +// StartedAt returns the value of the "started_at" field in the mutation. +func (m *AgentSyncJobMutation) StartedAt() (r time.Time, exists bool) { + v := m.started_at + if v == nil { + return + } + return *v, true +} + +// OldStartedAt returns the old "started_at" field's value of the AgentSyncJob entity. +// If the AgentSyncJob 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 *AgentSyncJobMutation) OldStartedAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldStartedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldStartedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldStartedAt: %w", err) + } + return oldValue.StartedAt, nil +} + +// ClearStartedAt clears the value of the "started_at" field. +func (m *AgentSyncJobMutation) ClearStartedAt() { + m.started_at = nil + m.clearedFields[agentsyncjob.FieldStartedAt] = struct{}{} +} + +// StartedAtCleared returns if the "started_at" field was cleared in this mutation. +func (m *AgentSyncJobMutation) StartedAtCleared() bool { + _, ok := m.clearedFields[agentsyncjob.FieldStartedAt] + return ok +} + +// ResetStartedAt resets all changes to the "started_at" field. +func (m *AgentSyncJobMutation) ResetStartedAt() { + m.started_at = nil + delete(m.clearedFields, agentsyncjob.FieldStartedAt) +} + +// SetFinishedAt sets the "finished_at" field. +func (m *AgentSyncJobMutation) SetFinishedAt(t time.Time) { + m.finished_at = &t +} + +// FinishedAt returns the value of the "finished_at" field in the mutation. +func (m *AgentSyncJobMutation) FinishedAt() (r time.Time, exists bool) { + v := m.finished_at + if v == nil { + return + } + return *v, true +} + +// OldFinishedAt returns the old "finished_at" field's value of the AgentSyncJob entity. +// If the AgentSyncJob 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 *AgentSyncJobMutation) OldFinishedAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFinishedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFinishedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFinishedAt: %w", err) + } + return oldValue.FinishedAt, nil +} + +// ClearFinishedAt clears the value of the "finished_at" field. +func (m *AgentSyncJobMutation) ClearFinishedAt() { + m.finished_at = nil + m.clearedFields[agentsyncjob.FieldFinishedAt] = struct{}{} +} + +// FinishedAtCleared returns if the "finished_at" field was cleared in this mutation. +func (m *AgentSyncJobMutation) FinishedAtCleared() bool { + _, ok := m.clearedFields[agentsyncjob.FieldFinishedAt] + return ok +} + +// ResetFinishedAt resets all changes to the "finished_at" field. +func (m *AgentSyncJobMutation) ResetFinishedAt() { + m.finished_at = nil + delete(m.clearedFields, agentsyncjob.FieldFinishedAt) +} + +// SetErrors sets the "errors" field. +func (m *AgentSyncJobMutation) SetErrors(tje types.SyncJobErrors) { + m.errors = &tje + m.appenderrors = nil +} + +// Errors returns the value of the "errors" field in the mutation. +func (m *AgentSyncJobMutation) Errors() (r types.SyncJobErrors, exists bool) { + v := m.errors + if v == nil { + return + } + return *v, true +} + +// OldErrors returns the old "errors" field's value of the AgentSyncJob entity. +// If the AgentSyncJob 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 *AgentSyncJobMutation) OldErrors(ctx context.Context) (v types.SyncJobErrors, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldErrors is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldErrors requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldErrors: %w", err) + } + return oldValue.Errors, nil +} + +// AppendErrors adds tje to the "errors" field. +func (m *AgentSyncJobMutation) AppendErrors(tje types.SyncJobErrors) { + m.appenderrors = append(m.appenderrors, tje...) +} + +// AppendedErrors returns the list of values that were appended to the "errors" field in this mutation. +func (m *AgentSyncJobMutation) AppendedErrors() (types.SyncJobErrors, bool) { + if len(m.appenderrors) == 0 { + return nil, false + } + return m.appenderrors, true +} + +// ClearErrors clears the value of the "errors" field. +func (m *AgentSyncJobMutation) ClearErrors() { + m.errors = nil + m.appenderrors = nil + m.clearedFields[agentsyncjob.FieldErrors] = struct{}{} +} + +// ErrorsCleared returns if the "errors" field was cleared in this mutation. +func (m *AgentSyncJobMutation) ErrorsCleared() bool { + _, ok := m.clearedFields[agentsyncjob.FieldErrors] + return ok +} + +// ResetErrors resets all changes to the "errors" field. +func (m *AgentSyncJobMutation) ResetErrors() { + m.errors = nil + m.appenderrors = nil + delete(m.clearedFields, agentsyncjob.FieldErrors) +} + +// SetResultSummary sets the "result_summary" field. +func (m *AgentSyncJobMutation) SetResultSummary(tjrs types.SyncJobResultSummary) { + m.result_summary = &tjrs +} + +// ResultSummary returns the value of the "result_summary" field in the mutation. +func (m *AgentSyncJobMutation) ResultSummary() (r types.SyncJobResultSummary, exists bool) { + v := m.result_summary + if v == nil { + return + } + return *v, true +} + +// OldResultSummary returns the old "result_summary" field's value of the AgentSyncJob entity. +// If the AgentSyncJob 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 *AgentSyncJobMutation) OldResultSummary(ctx context.Context) (v types.SyncJobResultSummary, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldResultSummary is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldResultSummary requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldResultSummary: %w", err) + } + return oldValue.ResultSummary, nil +} + +// ClearResultSummary clears the value of the "result_summary" field. +func (m *AgentSyncJobMutation) ClearResultSummary() { + m.result_summary = nil + m.clearedFields[agentsyncjob.FieldResultSummary] = struct{}{} +} + +// ResultSummaryCleared returns if the "result_summary" field was cleared in this mutation. +func (m *AgentSyncJobMutation) ResultSummaryCleared() bool { + _, ok := m.clearedFields[agentsyncjob.FieldResultSummary] + return ok +} + +// ResetResultSummary resets all changes to the "result_summary" field. +func (m *AgentSyncJobMutation) ResetResultSummary() { + m.result_summary = nil + delete(m.clearedFields, agentsyncjob.FieldResultSummary) +} + +// SetCreatedAt sets the "created_at" field. +func (m *AgentSyncJobMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *AgentSyncJobMutation) 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 AgentSyncJob entity. +// If the AgentSyncJob 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 *AgentSyncJobMutation) 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 *AgentSyncJobMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *AgentSyncJobMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *AgentSyncJobMutation) UpdatedAt() (r time.Time, exists bool) { + v := m.updated_at + if v == nil { + return + } + return *v, true +} + +// OldUpdatedAt returns the old "updated_at" field's value of the AgentSyncJob entity. +// If the AgentSyncJob 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 *AgentSyncJobMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUpdatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) + } + return oldValue.UpdatedAt, nil +} + +// ResetUpdatedAt resets all changes to the "updated_at" field. +func (m *AgentSyncJobMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// Where appends a list predicates to the AgentSyncJobMutation builder. +func (m *AgentSyncJobMutation) Where(ps ...predicate.AgentSyncJob) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the AgentSyncJobMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *AgentSyncJobMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.AgentSyncJob, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *AgentSyncJobMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *AgentSyncJobMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (AgentSyncJob). +func (m *AgentSyncJobMutation) 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 *AgentSyncJobMutation) Fields() []string { + fields := make([]string, 0, 13) + if m.resource_kind != nil { + fields = append(fields, agentsyncjob.FieldResourceKind) + } + if m.rule_id != nil { + fields = append(fields, agentsyncjob.FieldRuleID) + } + if m.repo_id != nil { + fields = append(fields, agentsyncjob.FieldRepoID) + } + if m.source_type != nil { + fields = append(fields, agentsyncjob.FieldSourceType) + } + if m.status != nil { + fields = append(fields, agentsyncjob.FieldStatus) + } + if m.trigger_type != nil { + fields = append(fields, agentsyncjob.FieldTriggerType) + } + if m.triggered_by != nil { + fields = append(fields, agentsyncjob.FieldTriggeredBy) + } + if m.started_at != nil { + fields = append(fields, agentsyncjob.FieldStartedAt) + } + if m.finished_at != nil { + fields = append(fields, agentsyncjob.FieldFinishedAt) + } + if m.errors != nil { + fields = append(fields, agentsyncjob.FieldErrors) + } + if m.result_summary != nil { + fields = append(fields, agentsyncjob.FieldResultSummary) + } + if m.created_at != nil { + fields = append(fields, agentsyncjob.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, agentsyncjob.FieldUpdatedAt) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *AgentSyncJobMutation) Field(name string) (ent.Value, bool) { + switch name { + case agentsyncjob.FieldResourceKind: + return m.ResourceKind() + case agentsyncjob.FieldRuleID: + return m.RuleID() + case agentsyncjob.FieldRepoID: + return m.RepoID() + case agentsyncjob.FieldSourceType: + return m.SourceType() + case agentsyncjob.FieldStatus: + return m.Status() + case agentsyncjob.FieldTriggerType: + return m.TriggerType() + case agentsyncjob.FieldTriggeredBy: + return m.TriggeredBy() + case agentsyncjob.FieldStartedAt: + return m.StartedAt() + case agentsyncjob.FieldFinishedAt: + return m.FinishedAt() + case agentsyncjob.FieldErrors: + return m.Errors() + case agentsyncjob.FieldResultSummary: + return m.ResultSummary() + case agentsyncjob.FieldCreatedAt: + return m.CreatedAt() + case agentsyncjob.FieldUpdatedAt: + return m.UpdatedAt() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *AgentSyncJobMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case agentsyncjob.FieldResourceKind: + return m.OldResourceKind(ctx) + case agentsyncjob.FieldRuleID: + return m.OldRuleID(ctx) + case agentsyncjob.FieldRepoID: + return m.OldRepoID(ctx) + case agentsyncjob.FieldSourceType: + return m.OldSourceType(ctx) + case agentsyncjob.FieldStatus: + return m.OldStatus(ctx) + case agentsyncjob.FieldTriggerType: + return m.OldTriggerType(ctx) + case agentsyncjob.FieldTriggeredBy: + return m.OldTriggeredBy(ctx) + case agentsyncjob.FieldStartedAt: + return m.OldStartedAt(ctx) + case agentsyncjob.FieldFinishedAt: + return m.OldFinishedAt(ctx) + case agentsyncjob.FieldErrors: + return m.OldErrors(ctx) + case agentsyncjob.FieldResultSummary: + return m.OldResultSummary(ctx) + case agentsyncjob.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case agentsyncjob.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + } + return nil, fmt.Errorf("unknown AgentSyncJob 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 *AgentSyncJobMutation) SetField(name string, value ent.Value) error { + switch name { + case agentsyncjob.FieldResourceKind: + v, ok := value.(agentsyncjob.ResourceKind) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetResourceKind(v) + return nil + case agentsyncjob.FieldRuleID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRuleID(v) + return nil + case agentsyncjob.FieldRepoID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRepoID(v) + return nil + case agentsyncjob.FieldSourceType: + v, ok := value.(agentsyncjob.SourceType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSourceType(v) + return nil + case agentsyncjob.FieldStatus: + v, ok := value.(agentsyncjob.Status) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStatus(v) + return nil + case agentsyncjob.FieldTriggerType: + v, ok := value.(agentsyncjob.TriggerType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTriggerType(v) + return nil + case agentsyncjob.FieldTriggeredBy: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTriggeredBy(v) + return nil + case agentsyncjob.FieldStartedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStartedAt(v) + return nil + case agentsyncjob.FieldFinishedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFinishedAt(v) + return nil + case agentsyncjob.FieldErrors: + v, ok := value.(types.SyncJobErrors) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetErrors(v) + return nil + case agentsyncjob.FieldResultSummary: + v, ok := value.(types.SyncJobResultSummary) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetResultSummary(v) + return nil + case agentsyncjob.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + case agentsyncjob.FieldUpdatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdatedAt(v) + return nil + } + return fmt.Errorf("unknown AgentSyncJob field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *AgentSyncJobMutation) 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 *AgentSyncJobMutation) 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 *AgentSyncJobMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown AgentSyncJob numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *AgentSyncJobMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(agentsyncjob.FieldRuleID) { + fields = append(fields, agentsyncjob.FieldRuleID) + } + if m.FieldCleared(agentsyncjob.FieldRepoID) { + fields = append(fields, agentsyncjob.FieldRepoID) + } + if m.FieldCleared(agentsyncjob.FieldTriggeredBy) { + fields = append(fields, agentsyncjob.FieldTriggeredBy) + } + if m.FieldCleared(agentsyncjob.FieldStartedAt) { + fields = append(fields, agentsyncjob.FieldStartedAt) + } + if m.FieldCleared(agentsyncjob.FieldFinishedAt) { + fields = append(fields, agentsyncjob.FieldFinishedAt) + } + if m.FieldCleared(agentsyncjob.FieldErrors) { + fields = append(fields, agentsyncjob.FieldErrors) + } + if m.FieldCleared(agentsyncjob.FieldResultSummary) { + fields = append(fields, agentsyncjob.FieldResultSummary) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *AgentSyncJobMutation) 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 *AgentSyncJobMutation) ClearField(name string) error { + switch name { + case agentsyncjob.FieldRuleID: + m.ClearRuleID() + return nil + case agentsyncjob.FieldRepoID: + m.ClearRepoID() + return nil + case agentsyncjob.FieldTriggeredBy: + m.ClearTriggeredBy() + return nil + case agentsyncjob.FieldStartedAt: + m.ClearStartedAt() + return nil + case agentsyncjob.FieldFinishedAt: + m.ClearFinishedAt() + return nil + case agentsyncjob.FieldErrors: + m.ClearErrors() + return nil + case agentsyncjob.FieldResultSummary: + m.ClearResultSummary() + return nil + } + return fmt.Errorf("unknown AgentSyncJob 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 *AgentSyncJobMutation) ResetField(name string) error { + switch name { + case agentsyncjob.FieldResourceKind: + m.ResetResourceKind() + return nil + case agentsyncjob.FieldRuleID: + m.ResetRuleID() + return nil + case agentsyncjob.FieldRepoID: + m.ResetRepoID() + return nil + case agentsyncjob.FieldSourceType: + m.ResetSourceType() + return nil + case agentsyncjob.FieldStatus: + m.ResetStatus() + return nil + case agentsyncjob.FieldTriggerType: + m.ResetTriggerType() + return nil + case agentsyncjob.FieldTriggeredBy: + m.ResetTriggeredBy() + return nil + case agentsyncjob.FieldStartedAt: + m.ResetStartedAt() + return nil + case agentsyncjob.FieldFinishedAt: + m.ResetFinishedAt() + return nil + case agentsyncjob.FieldErrors: + m.ResetErrors() + return nil + case agentsyncjob.FieldResultSummary: + m.ResetResultSummary() + return nil + case agentsyncjob.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case agentsyncjob.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + } + return fmt.Errorf("unknown AgentSyncJob field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *AgentSyncJobMutation) 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 *AgentSyncJobMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *AgentSyncJobMutation) 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 *AgentSyncJobMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *AgentSyncJobMutation) 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 *AgentSyncJobMutation) 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 *AgentSyncJobMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown AgentSyncJob 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 *AgentSyncJobMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown AgentSyncJob edge %s", name) +} + // AuditMutation represents an operation that mutates the Audit nodes in the graph. type AuditMutation struct { config diff --git a/backend/db/page.go b/backend/db/page.go index d5eed556..ddcfdee8 100644 --- a/backend/db/page.go +++ b/backend/db/page.go @@ -11,6 +11,132 @@ type PageInfo struct { TotalCount int64 `json:"total_count"` } +func (_m *AgentPluginQuery) Page(ctx context.Context, page, size int) ([]*AgentPlugin, *PageInfo, error) { + cnt, err := _m.Count(ctx) + if err != nil { + return nil, nil, err + } + offset := size * (page - 1) + rs, err := _m.Offset(offset).Limit(size).All(ctx) + if err != nil { + return nil, nil, err + } + has := (page * size) < cnt + return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil +} + +func (_m *AgentPluginRepoQuery) Page(ctx context.Context, page, size int) ([]*AgentPluginRepo, *PageInfo, error) { + cnt, err := _m.Count(ctx) + if err != nil { + return nil, nil, err + } + offset := size * (page - 1) + rs, err := _m.Offset(offset).Limit(size).All(ctx) + if err != nil { + return nil, nil, err + } + has := (page * size) < cnt + return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil +} + +func (_m *AgentPluginVersionQuery) Page(ctx context.Context, page, size int) ([]*AgentPluginVersion, *PageInfo, error) { + cnt, err := _m.Count(ctx) + if err != nil { + return nil, nil, err + } + offset := size * (page - 1) + rs, err := _m.Offset(offset).Limit(size).All(ctx) + if err != nil { + return nil, nil, err + } + has := (page * size) < cnt + return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil +} + +func (_m *AgentRuleQuery) Page(ctx context.Context, page, size int) ([]*AgentRule, *PageInfo, error) { + cnt, err := _m.Count(ctx) + if err != nil { + return nil, nil, err + } + offset := size * (page - 1) + rs, err := _m.Offset(offset).Limit(size).All(ctx) + if err != nil { + return nil, nil, err + } + has := (page * size) < cnt + return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil +} + +func (_m *AgentRuleVersionQuery) Page(ctx context.Context, page, size int) ([]*AgentRuleVersion, *PageInfo, error) { + cnt, err := _m.Count(ctx) + if err != nil { + return nil, nil, err + } + offset := size * (page - 1) + rs, err := _m.Offset(offset).Limit(size).All(ctx) + if err != nil { + return nil, nil, err + } + has := (page * size) < cnt + return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil +} + +func (_m *AgentSkillQuery) Page(ctx context.Context, page, size int) ([]*AgentSkill, *PageInfo, error) { + cnt, err := _m.Count(ctx) + if err != nil { + return nil, nil, err + } + offset := size * (page - 1) + rs, err := _m.Offset(offset).Limit(size).All(ctx) + if err != nil { + return nil, nil, err + } + has := (page * size) < cnt + return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil +} + +func (_m *AgentSkillRepoQuery) Page(ctx context.Context, page, size int) ([]*AgentSkillRepo, *PageInfo, error) { + cnt, err := _m.Count(ctx) + if err != nil { + return nil, nil, err + } + offset := size * (page - 1) + rs, err := _m.Offset(offset).Limit(size).All(ctx) + if err != nil { + return nil, nil, err + } + has := (page * size) < cnt + return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil +} + +func (_m *AgentSkillVersionQuery) Page(ctx context.Context, page, size int) ([]*AgentSkillVersion, *PageInfo, error) { + cnt, err := _m.Count(ctx) + if err != nil { + return nil, nil, err + } + offset := size * (page - 1) + rs, err := _m.Offset(offset).Limit(size).All(ctx) + if err != nil { + return nil, nil, err + } + has := (page * size) < cnt + return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil +} + +func (_m *AgentSyncJobQuery) Page(ctx context.Context, page, size int) ([]*AgentSyncJob, *PageInfo, error) { + cnt, err := _m.Count(ctx) + if err != nil { + return nil, nil, err + } + offset := size * (page - 1) + rs, err := _m.Offset(offset).Limit(size).All(ctx) + if err != nil { + return nil, nil, err + } + has := (page * size) < cnt + return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil +} + func (_m *AuditQuery) Page(ctx context.Context, page, size int) ([]*Audit, *PageInfo, error) { cnt, err := _m.Count(ctx) if err != nil { diff --git a/backend/db/predicate/predicate.go b/backend/db/predicate/predicate.go index 6764d5bb..082c733d 100644 --- a/backend/db/predicate/predicate.go +++ b/backend/db/predicate/predicate.go @@ -6,6 +6,33 @@ import ( "entgo.io/ent/dialect/sql" ) +// AgentPlugin is the predicate function for agentplugin builders. +type AgentPlugin func(*sql.Selector) + +// AgentPluginRepo is the predicate function for agentpluginrepo builders. +type AgentPluginRepo func(*sql.Selector) + +// AgentPluginVersion is the predicate function for agentpluginversion builders. +type AgentPluginVersion func(*sql.Selector) + +// AgentRule is the predicate function for agentrule builders. +type AgentRule func(*sql.Selector) + +// AgentRuleVersion is the predicate function for agentruleversion builders. +type AgentRuleVersion func(*sql.Selector) + +// AgentSkill is the predicate function for agentskill builders. +type AgentSkill func(*sql.Selector) + +// AgentSkillRepo is the predicate function for agentskillrepo builders. +type AgentSkillRepo func(*sql.Selector) + +// AgentSkillVersion is the predicate function for agentskillversion builders. +type AgentSkillVersion func(*sql.Selector) + +// AgentSyncJob is the predicate function for agentsyncjob builders. +type AgentSyncJob func(*sql.Selector) + // Audit is the predicate function for audit builders. type Audit func(*sql.Selector) diff --git a/backend/db/runtime/runtime.go b/backend/db/runtime/runtime.go index 36b4ede0..1046fec7 100644 --- a/backend/db/runtime/runtime.go +++ b/backend/db/runtime/runtime.go @@ -6,6 +6,15 @@ import ( "time" "github.com/chaitin/MonkeyCode/backend/consts" + "github.com/chaitin/MonkeyCode/backend/db/agentplugin" + "github.com/chaitin/MonkeyCode/backend/db/agentpluginrepo" + "github.com/chaitin/MonkeyCode/backend/db/agentpluginversion" + "github.com/chaitin/MonkeyCode/backend/db/agentrule" + "github.com/chaitin/MonkeyCode/backend/db/agentruleversion" + "github.com/chaitin/MonkeyCode/backend/db/agentskill" + "github.com/chaitin/MonkeyCode/backend/db/agentskillrepo" + "github.com/chaitin/MonkeyCode/backend/db/agentskillversion" + "github.com/chaitin/MonkeyCode/backend/db/agentsyncjob" "github.com/chaitin/MonkeyCode/backend/db/audit" "github.com/chaitin/MonkeyCode/backend/db/gitbot" "github.com/chaitin/MonkeyCode/backend/db/gitbottask" @@ -54,6 +63,246 @@ import ( // (default values, validators, hooks and policies) and stitches it // to their package variables. func init() { + agentpluginFields := schema.AgentPlugin{}.Fields() + _ = agentpluginFields + // agentpluginDescName is the schema descriptor for name field. + agentpluginDescName := agentpluginFields[2].Descriptor() + // agentplugin.NameValidator is a validator for the "name" field. It is called by the builders before save. + agentplugin.NameValidator = agentpluginDescName.Validators[0].(func(string) error) + // agentpluginDescScopeID is the schema descriptor for scope_id field. + agentpluginDescScopeID := agentpluginFields[5].Descriptor() + // agentplugin.DefaultScopeID holds the default value on creation for the scope_id field. + agentplugin.DefaultScopeID = agentpluginDescScopeID.Default.(string) + // agentpluginDescIsForceDelivery is the schema descriptor for is_force_delivery field. + agentpluginDescIsForceDelivery := agentpluginFields[8].Descriptor() + // agentplugin.DefaultIsForceDelivery holds the default value on creation for the is_force_delivery field. + agentplugin.DefaultIsForceDelivery = agentpluginDescIsForceDelivery.Default.(bool) + // agentpluginDescIsOrphan is the schema descriptor for is_orphan field. + agentpluginDescIsOrphan := agentpluginFields[9].Descriptor() + // agentplugin.DefaultIsOrphan holds the default value on creation for the is_orphan field. + agentplugin.DefaultIsOrphan = agentpluginDescIsOrphan.Default.(bool) + // agentpluginDescIsDeleted is the schema descriptor for is_deleted field. + agentpluginDescIsDeleted := agentpluginFields[10].Descriptor() + // agentplugin.DefaultIsDeleted holds the default value on creation for the is_deleted field. + agentplugin.DefaultIsDeleted = agentpluginDescIsDeleted.Default.(bool) + // agentpluginDescCreatedAt is the schema descriptor for created_at field. + agentpluginDescCreatedAt := agentpluginFields[11].Descriptor() + // agentplugin.DefaultCreatedAt holds the default value on creation for the created_at field. + agentplugin.DefaultCreatedAt = agentpluginDescCreatedAt.Default.(func() time.Time) + // agentpluginDescUpdatedAt is the schema descriptor for updated_at field. + agentpluginDescUpdatedAt := agentpluginFields[12].Descriptor() + // agentplugin.DefaultUpdatedAt holds the default value on creation for the updated_at field. + agentplugin.DefaultUpdatedAt = agentpluginDescUpdatedAt.Default.(func() time.Time) + // agentplugin.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. + agentplugin.UpdateDefaultUpdatedAt = agentpluginDescUpdatedAt.UpdateDefault.(func() time.Time) + // agentpluginDescID is the schema descriptor for id field. + agentpluginDescID := agentpluginFields[0].Descriptor() + // agentplugin.DefaultID holds the default value on creation for the id field. + agentplugin.DefaultID = agentpluginDescID.Default.(func() uuid.UUID) + agentpluginrepoFields := schema.AgentPluginRepo{}.Fields() + _ = agentpluginrepoFields + // agentpluginrepoDescName is the schema descriptor for name field. + agentpluginrepoDescName := agentpluginrepoFields[1].Descriptor() + // agentpluginrepo.NameValidator is a validator for the "name" field. It is called by the builders before save. + agentpluginrepo.NameValidator = agentpluginrepoDescName.Validators[0].(func(string) error) + // agentpluginrepoDescScopeID is the schema descriptor for scope_id field. + agentpluginrepoDescScopeID := agentpluginrepoFields[3].Descriptor() + // agentpluginrepo.DefaultScopeID holds the default value on creation for the scope_id field. + agentpluginrepo.DefaultScopeID = agentpluginrepoDescScopeID.Default.(string) + // agentpluginrepoDescPluginDiscoveryAutoPackageJSON is the schema descriptor for plugin_discovery_auto_package_json field. + agentpluginrepoDescPluginDiscoveryAutoPackageJSON := agentpluginrepoFields[11].Descriptor() + // agentpluginrepo.DefaultPluginDiscoveryAutoPackageJSON holds the default value on creation for the plugin_discovery_auto_package_json field. + agentpluginrepo.DefaultPluginDiscoveryAutoPackageJSON = agentpluginrepoDescPluginDiscoveryAutoPackageJSON.Default.(bool) + // agentpluginrepoDescIsDeleted is the schema descriptor for is_deleted field. + agentpluginrepoDescIsDeleted := agentpluginrepoFields[16].Descriptor() + // agentpluginrepo.DefaultIsDeleted holds the default value on creation for the is_deleted field. + agentpluginrepo.DefaultIsDeleted = agentpluginrepoDescIsDeleted.Default.(bool) + // agentpluginrepoDescCreatedAt is the schema descriptor for created_at field. + agentpluginrepoDescCreatedAt := agentpluginrepoFields[17].Descriptor() + // agentpluginrepo.DefaultCreatedAt holds the default value on creation for the created_at field. + agentpluginrepo.DefaultCreatedAt = agentpluginrepoDescCreatedAt.Default.(func() time.Time) + // agentpluginrepoDescUpdatedAt is the schema descriptor for updated_at field. + agentpluginrepoDescUpdatedAt := agentpluginrepoFields[18].Descriptor() + // agentpluginrepo.DefaultUpdatedAt holds the default value on creation for the updated_at field. + agentpluginrepo.DefaultUpdatedAt = agentpluginrepoDescUpdatedAt.Default.(func() time.Time) + // agentpluginrepo.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. + agentpluginrepo.UpdateDefaultUpdatedAt = agentpluginrepoDescUpdatedAt.UpdateDefault.(func() time.Time) + // agentpluginrepoDescID is the schema descriptor for id field. + agentpluginrepoDescID := agentpluginrepoFields[0].Descriptor() + // agentpluginrepo.DefaultID holds the default value on creation for the id field. + agentpluginrepo.DefaultID = agentpluginrepoDescID.Default.(func() uuid.UUID) + agentpluginversionFields := schema.AgentPluginVersion{}.Fields() + _ = agentpluginversionFields + // agentpluginversionDescVersion is the schema descriptor for version field. + agentpluginversionDescVersion := agentpluginversionFields[2].Descriptor() + // agentpluginversion.VersionValidator is a validator for the "version" field. It is called by the builders before save. + agentpluginversion.VersionValidator = agentpluginversionDescVersion.Validators[0].(func(string) error) + // agentpluginversionDescS3Key is the schema descriptor for s3_key field. + agentpluginversionDescS3Key := agentpluginversionFields[3].Descriptor() + // agentpluginversion.S3KeyValidator is a validator for the "s3_key" field. It is called by the builders before save. + agentpluginversion.S3KeyValidator = agentpluginversionDescS3Key.Validators[0].(func(string) error) + // agentpluginversionDescCreatedAt is the schema descriptor for created_at field. + agentpluginversionDescCreatedAt := agentpluginversionFields[5].Descriptor() + // agentpluginversion.DefaultCreatedAt holds the default value on creation for the created_at field. + agentpluginversion.DefaultCreatedAt = agentpluginversionDescCreatedAt.Default.(func() time.Time) + // agentpluginversionDescID is the schema descriptor for id field. + agentpluginversionDescID := agentpluginversionFields[0].Descriptor() + // agentpluginversion.DefaultID holds the default value on creation for the id field. + agentpluginversion.DefaultID = agentpluginversionDescID.Default.(func() uuid.UUID) + agentruleFields := schema.AgentRule{}.Fields() + _ = agentruleFields + // agentruleDescName is the schema descriptor for name field. + agentruleDescName := agentruleFields[1].Descriptor() + // agentrule.NameValidator is a validator for the "name" field. It is called by the builders before save. + agentrule.NameValidator = agentruleDescName.Validators[0].(func(string) error) + // agentruleDescScopeID is the schema descriptor for scope_id field. + agentruleDescScopeID := agentruleFields[4].Descriptor() + // agentrule.DefaultScopeID holds the default value on creation for the scope_id field. + agentrule.DefaultScopeID = agentruleDescScopeID.Default.(string) + // agentruleDescIsDeleted is the schema descriptor for is_deleted field. + agentruleDescIsDeleted := agentruleFields[7].Descriptor() + // agentrule.DefaultIsDeleted holds the default value on creation for the is_deleted field. + agentrule.DefaultIsDeleted = agentruleDescIsDeleted.Default.(bool) + // agentruleDescCreatedAt is the schema descriptor for created_at field. + agentruleDescCreatedAt := agentruleFields[8].Descriptor() + // agentrule.DefaultCreatedAt holds the default value on creation for the created_at field. + agentrule.DefaultCreatedAt = agentruleDescCreatedAt.Default.(func() time.Time) + // agentruleDescUpdatedAt is the schema descriptor for updated_at field. + agentruleDescUpdatedAt := agentruleFields[9].Descriptor() + // agentrule.DefaultUpdatedAt holds the default value on creation for the updated_at field. + agentrule.DefaultUpdatedAt = agentruleDescUpdatedAt.Default.(func() time.Time) + // agentrule.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. + agentrule.UpdateDefaultUpdatedAt = agentruleDescUpdatedAt.UpdateDefault.(func() time.Time) + // agentruleDescID is the schema descriptor for id field. + agentruleDescID := agentruleFields[0].Descriptor() + // agentrule.DefaultID holds the default value on creation for the id field. + agentrule.DefaultID = agentruleDescID.Default.(func() uuid.UUID) + agentruleversionFields := schema.AgentRuleVersion{}.Fields() + _ = agentruleversionFields + // agentruleversionDescVersion is the schema descriptor for version field. + agentruleversionDescVersion := agentruleversionFields[2].Descriptor() + // agentruleversion.VersionValidator is a validator for the "version" field. It is called by the builders before save. + agentruleversion.VersionValidator = func() func(string) error { + validators := agentruleversionDescVersion.Validators + fns := [...]func(string) error{ + validators[0].(func(string) error), + validators[1].(func(string) error), + } + return func(version string) error { + for _, fn := range fns { + if err := fn(version); err != nil { + return err + } + } + return nil + } + }() + // agentruleversionDescCreatedAt is the schema descriptor for created_at field. + agentruleversionDescCreatedAt := agentruleversionFields[4].Descriptor() + // agentruleversion.DefaultCreatedAt holds the default value on creation for the created_at field. + agentruleversion.DefaultCreatedAt = agentruleversionDescCreatedAt.Default.(func() time.Time) + // agentruleversionDescID is the schema descriptor for id field. + agentruleversionDescID := agentruleversionFields[0].Descriptor() + // agentruleversion.DefaultID holds the default value on creation for the id field. + agentruleversion.DefaultID = agentruleversionDescID.Default.(func() uuid.UUID) + agentskillFields := schema.AgentSkill{}.Fields() + _ = agentskillFields + // agentskillDescName is the schema descriptor for name field. + agentskillDescName := agentskillFields[2].Descriptor() + // agentskill.NameValidator is a validator for the "name" field. It is called by the builders before save. + agentskill.NameValidator = agentskillDescName.Validators[0].(func(string) error) + // agentskillDescScopeID is the schema descriptor for scope_id field. + agentskillDescScopeID := agentskillFields[5].Descriptor() + // agentskill.DefaultScopeID holds the default value on creation for the scope_id field. + agentskill.DefaultScopeID = agentskillDescScopeID.Default.(string) + // agentskillDescIsForceDelivery is the schema descriptor for is_force_delivery field. + agentskillDescIsForceDelivery := agentskillFields[8].Descriptor() + // agentskill.DefaultIsForceDelivery holds the default value on creation for the is_force_delivery field. + agentskill.DefaultIsForceDelivery = agentskillDescIsForceDelivery.Default.(bool) + // agentskillDescIsOrphan is the schema descriptor for is_orphan field. + agentskillDescIsOrphan := agentskillFields[9].Descriptor() + // agentskill.DefaultIsOrphan holds the default value on creation for the is_orphan field. + agentskill.DefaultIsOrphan = agentskillDescIsOrphan.Default.(bool) + // agentskillDescIsDeleted is the schema descriptor for is_deleted field. + agentskillDescIsDeleted := agentskillFields[10].Descriptor() + // agentskill.DefaultIsDeleted holds the default value on creation for the is_deleted field. + agentskill.DefaultIsDeleted = agentskillDescIsDeleted.Default.(bool) + // agentskillDescCreatedAt is the schema descriptor for created_at field. + agentskillDescCreatedAt := agentskillFields[11].Descriptor() + // agentskill.DefaultCreatedAt holds the default value on creation for the created_at field. + agentskill.DefaultCreatedAt = agentskillDescCreatedAt.Default.(func() time.Time) + // agentskillDescUpdatedAt is the schema descriptor for updated_at field. + agentskillDescUpdatedAt := agentskillFields[12].Descriptor() + // agentskill.DefaultUpdatedAt holds the default value on creation for the updated_at field. + agentskill.DefaultUpdatedAt = agentskillDescUpdatedAt.Default.(func() time.Time) + // agentskill.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. + agentskill.UpdateDefaultUpdatedAt = agentskillDescUpdatedAt.UpdateDefault.(func() time.Time) + // agentskillDescID is the schema descriptor for id field. + agentskillDescID := agentskillFields[0].Descriptor() + // agentskill.DefaultID holds the default value on creation for the id field. + agentskill.DefaultID = agentskillDescID.Default.(func() uuid.UUID) + agentskillrepoFields := schema.AgentSkillRepo{}.Fields() + _ = agentskillrepoFields + // agentskillrepoDescName is the schema descriptor for name field. + agentskillrepoDescName := agentskillrepoFields[1].Descriptor() + // agentskillrepo.NameValidator is a validator for the "name" field. It is called by the builders before save. + agentskillrepo.NameValidator = agentskillrepoDescName.Validators[0].(func(string) error) + // agentskillrepoDescScopeID is the schema descriptor for scope_id field. + agentskillrepoDescScopeID := agentskillrepoFields[3].Descriptor() + // agentskillrepo.DefaultScopeID holds the default value on creation for the scope_id field. + agentskillrepo.DefaultScopeID = agentskillrepoDescScopeID.Default.(string) + // agentskillrepoDescIsDeleted is the schema descriptor for is_deleted field. + agentskillrepoDescIsDeleted := agentskillrepoFields[11].Descriptor() + // agentskillrepo.DefaultIsDeleted holds the default value on creation for the is_deleted field. + agentskillrepo.DefaultIsDeleted = agentskillrepoDescIsDeleted.Default.(bool) + // agentskillrepoDescCreatedAt is the schema descriptor for created_at field. + agentskillrepoDescCreatedAt := agentskillrepoFields[12].Descriptor() + // agentskillrepo.DefaultCreatedAt holds the default value on creation for the created_at field. + agentskillrepo.DefaultCreatedAt = agentskillrepoDescCreatedAt.Default.(func() time.Time) + // agentskillrepoDescUpdatedAt is the schema descriptor for updated_at field. + agentskillrepoDescUpdatedAt := agentskillrepoFields[13].Descriptor() + // agentskillrepo.DefaultUpdatedAt holds the default value on creation for the updated_at field. + agentskillrepo.DefaultUpdatedAt = agentskillrepoDescUpdatedAt.Default.(func() time.Time) + // agentskillrepo.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. + agentskillrepo.UpdateDefaultUpdatedAt = agentskillrepoDescUpdatedAt.UpdateDefault.(func() time.Time) + // agentskillrepoDescID is the schema descriptor for id field. + agentskillrepoDescID := agentskillrepoFields[0].Descriptor() + // agentskillrepo.DefaultID holds the default value on creation for the id field. + agentskillrepo.DefaultID = agentskillrepoDescID.Default.(func() uuid.UUID) + agentskillversionFields := schema.AgentSkillVersion{}.Fields() + _ = agentskillversionFields + // agentskillversionDescVersion is the schema descriptor for version field. + agentskillversionDescVersion := agentskillversionFields[2].Descriptor() + // agentskillversion.VersionValidator is a validator for the "version" field. It is called by the builders before save. + agentskillversion.VersionValidator = agentskillversionDescVersion.Validators[0].(func(string) error) + // agentskillversionDescS3Key is the schema descriptor for s3_key field. + agentskillversionDescS3Key := agentskillversionFields[3].Descriptor() + // agentskillversion.S3KeyValidator is a validator for the "s3_key" field. It is called by the builders before save. + agentskillversion.S3KeyValidator = agentskillversionDescS3Key.Validators[0].(func(string) error) + // agentskillversionDescCreatedAt is the schema descriptor for created_at field. + agentskillversionDescCreatedAt := agentskillversionFields[5].Descriptor() + // agentskillversion.DefaultCreatedAt holds the default value on creation for the created_at field. + agentskillversion.DefaultCreatedAt = agentskillversionDescCreatedAt.Default.(func() time.Time) + // agentskillversionDescID is the schema descriptor for id field. + agentskillversionDescID := agentskillversionFields[0].Descriptor() + // agentskillversion.DefaultID holds the default value on creation for the id field. + agentskillversion.DefaultID = agentskillversionDescID.Default.(func() uuid.UUID) + agentsyncjobFields := schema.AgentSyncJob{}.Fields() + _ = agentsyncjobFields + // agentsyncjobDescCreatedAt is the schema descriptor for created_at field. + agentsyncjobDescCreatedAt := agentsyncjobFields[12].Descriptor() + // agentsyncjob.DefaultCreatedAt holds the default value on creation for the created_at field. + agentsyncjob.DefaultCreatedAt = agentsyncjobDescCreatedAt.Default.(func() time.Time) + // agentsyncjobDescUpdatedAt is the schema descriptor for updated_at field. + agentsyncjobDescUpdatedAt := agentsyncjobFields[13].Descriptor() + // agentsyncjob.DefaultUpdatedAt holds the default value on creation for the updated_at field. + agentsyncjob.DefaultUpdatedAt = agentsyncjobDescUpdatedAt.Default.(func() time.Time) + // agentsyncjob.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. + agentsyncjob.UpdateDefaultUpdatedAt = agentsyncjobDescUpdatedAt.UpdateDefault.(func() time.Time) + // agentsyncjobDescID is the schema descriptor for id field. + agentsyncjobDescID := agentsyncjobFields[0].Descriptor() + // agentsyncjob.DefaultID holds the default value on creation for the id field. + agentsyncjob.DefaultID = agentsyncjobDescID.Default.(func() uuid.UUID) auditFields := schema.Audit{}.Fields() _ = auditFields // auditDescCreatedAt is the schema descriptor for created_at field. diff --git a/backend/db/tx.go b/backend/db/tx.go index ac423775..8313ddba 100644 --- a/backend/db/tx.go +++ b/backend/db/tx.go @@ -14,6 +14,24 @@ import ( // Tx is a transactional client that is created by calling Client.Tx(). type Tx struct { config + // AgentPlugin is the client for interacting with the AgentPlugin builders. + AgentPlugin *AgentPluginClient + // AgentPluginRepo is the client for interacting with the AgentPluginRepo builders. + AgentPluginRepo *AgentPluginRepoClient + // AgentPluginVersion is the client for interacting with the AgentPluginVersion builders. + AgentPluginVersion *AgentPluginVersionClient + // AgentRule is the client for interacting with the AgentRule builders. + AgentRule *AgentRuleClient + // AgentRuleVersion is the client for interacting with the AgentRuleVersion builders. + AgentRuleVersion *AgentRuleVersionClient + // AgentSkill is the client for interacting with the AgentSkill builders. + AgentSkill *AgentSkillClient + // AgentSkillRepo is the client for interacting with the AgentSkillRepo builders. + AgentSkillRepo *AgentSkillRepoClient + // AgentSkillVersion is the client for interacting with the AgentSkillVersion builders. + AgentSkillVersion *AgentSkillVersionClient + // AgentSyncJob is the client for interacting with the AgentSyncJob builders. + AgentSyncJob *AgentSyncJobClient // Audit is the client for interacting with the Audit builders. Audit *AuditClient // GitBot is the client for interacting with the GitBot builders. @@ -225,6 +243,15 @@ func (tx *Tx) Client() *Client { } func (tx *Tx) init() { + tx.AgentPlugin = NewAgentPluginClient(tx.config) + tx.AgentPluginRepo = NewAgentPluginRepoClient(tx.config) + tx.AgentPluginVersion = NewAgentPluginVersionClient(tx.config) + tx.AgentRule = NewAgentRuleClient(tx.config) + tx.AgentRuleVersion = NewAgentRuleVersionClient(tx.config) + tx.AgentSkill = NewAgentSkillClient(tx.config) + tx.AgentSkillRepo = NewAgentSkillRepoClient(tx.config) + tx.AgentSkillVersion = NewAgentSkillVersionClient(tx.config) + tx.AgentSyncJob = NewAgentSyncJobClient(tx.config) tx.Audit = NewAuditClient(tx.config) tx.GitBot = NewGitBotClient(tx.config) tx.GitBotTask = NewGitBotTaskClient(tx.config) @@ -274,7 +301,7 @@ func (tx *Tx) init() { // of them in order to commit or rollback the transaction. // // If a closed transaction is embedded in one of the generated entities, and the entity -// applies a query, for example: Audit.QueryXXX(), the query will be executed +// applies a query, for example: AgentPlugin.QueryXXX(), the query will be executed // through the driver which created this transaction. // // Note that txDriver is not goroutine safe. diff --git a/backend/ent/schema/agent_plugin.go b/backend/ent/schema/agent_plugin.go new file mode 100644 index 00000000..93784bff --- /dev/null +++ b/backend/ent/schema/agent_plugin.go @@ -0,0 +1,99 @@ +package schema + +import ( + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/schema" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/index" + "github.com/google/uuid" + + "github.com/chaitin/MonkeyCode/backend/ent/types" +) + +// AgentPlugin holds the schema definition for the agent_plugins entity. +type AgentPlugin struct { + ent.Schema +} + +func (AgentPlugin) Annotations() []schema.Annotation { + return []schema.Annotation{ + entsql.Table("agent_plugins"), + } +} + +// Fields of the AgentPlugin. +func (AgentPlugin) Fields() []ent.Field { + return []ent.Field{ + field.UUID("id", uuid.UUID{}).Default(uuid.New), + field.UUID("repo_id", uuid.UUID{}), + field.String("name").NotEmpty(), + field.Text("description").Optional(), + field.Enum("scope_type").Values("global").Default("global"), + field.String("scope_id").Default("global"), + field.UUID("created_by", uuid.UUID{}), + field.UUID("active_version_id", uuid.UUID{}).Optional().Nillable(), + field.Bool("is_force_delivery").Default(false), + field.Bool("is_orphan").Default(false), + field.Bool("is_deleted").Default(false), + field.Time("created_at").Default(time.Now), + field.Time("updated_at").Default(time.Now).UpdateDefault(time.Now), + } +} + +// Edges of the AgentPlugin. +func (AgentPlugin) Edges() []ent.Edge { + return []ent.Edge{ + edge.From("repo", AgentPluginRepo.Type).Ref("plugins").Field("repo_id").Unique().Required(), + edge.To("versions", AgentPluginVersion.Type), + } +} + +// Indexes of the AgentPlugin. +func (AgentPlugin) Indexes() []ent.Index { + return []ent.Index{ + index.Fields("repo_id", "name").Unique(), + index.Fields("scope_type", "scope_id"), + index.Fields("active_version_id"), + } +} + +// AgentPluginVersion holds the schema definition for the agent_plugin_versions entity. +type AgentPluginVersion struct { + ent.Schema +} + +func (AgentPluginVersion) Annotations() []schema.Annotation { + return []schema.Annotation{ + entsql.Table("agent_plugin_versions"), + } +} + +// Fields of the AgentPluginVersion. +func (AgentPluginVersion) Fields() []ent.Field { + return []ent.Field{ + field.UUID("id", uuid.UUID{}).Default(uuid.New), + field.UUID("resource_id", uuid.UUID{}), + field.String("version").NotEmpty(), + field.String("s3_key").NotEmpty(), + field.JSON("parsed_meta", types.PluginParsedMeta{}).Optional(), + field.Time("created_at").Default(time.Now), + } +} + +// Edges of the AgentPluginVersion. +func (AgentPluginVersion) Edges() []ent.Edge { + return []ent.Edge{ + edge.From("plugin", AgentPlugin.Type).Ref("versions").Field("resource_id").Unique().Required(), + } +} + +// Indexes of the AgentPluginVersion. +func (AgentPluginVersion) Indexes() []ent.Index { + return []ent.Index{ + index.Fields("resource_id"), + } +} diff --git a/backend/ent/schema/agent_plugin_repo.go b/backend/ent/schema/agent_plugin_repo.go new file mode 100644 index 00000000..3ff2f2cf --- /dev/null +++ b/backend/ent/schema/agent_plugin_repo.go @@ -0,0 +1,70 @@ +package schema + +import ( + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/schema" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/index" + "github.com/google/uuid" + + "github.com/chaitin/MonkeyCode/backend/ent/types" +) + +// AgentPluginRepo holds the schema definition for the agent_plugin_repos entity. +type AgentPluginRepo struct { + ent.Schema +} + +func (AgentPluginRepo) Annotations() []schema.Annotation { + return []schema.Annotation{ + entsql.Table("agent_plugin_repos"), + } +} + +// Fields of the AgentPluginRepo. +func (AgentPluginRepo) Fields() []ent.Field { + return []ent.Field{ + field.UUID("id", uuid.UUID{}).Default(uuid.New), + field.String("name").NotEmpty(), + field.Enum("scope_type").Values("global").Default("global"), + field.String("scope_id").Default("global"), + field.UUID("created_by", uuid.UUID{}), + field.Enum("source_type").Values("github", "upload", "npm"), + // github + field.String("github_url").Optional().Nillable(), + field.Enum("ref_type").Values("branch", "tag", "commit").Optional().Nillable(), + field.String("ref_value").Optional().Nillable(), + // upload + field.String("last_upload_filename").Optional().Nillable(), + field.Time("last_upload_at").Optional().Nillable(), + // plugin discovery / manual entries + field.Bool("plugin_discovery_auto_package_json").Default(true), + field.JSON("plugin_manual_entries", types.PluginManualEntries{}).Optional(), + // npm + field.String("npm_package_name").Optional().Nillable(), + field.String("npm_version_spec").Optional().Nillable(), + field.String("npm_registry_url").Optional().Nillable(), + + field.Bool("is_deleted").Default(false), + field.Time("created_at").Default(time.Now), + field.Time("updated_at").Default(time.Now).UpdateDefault(time.Now), + } +} + +// Edges of the AgentPluginRepo. +func (AgentPluginRepo) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("plugins", AgentPlugin.Type), + } +} + +// Indexes of the AgentPluginRepo. +func (AgentPluginRepo) Indexes() []ent.Index { + return []ent.Index{ + index.Fields("scope_type", "scope_id"), + } +} diff --git a/backend/ent/schema/agent_rule.go b/backend/ent/schema/agent_rule.go new file mode 100644 index 00000000..e2d9bc64 --- /dev/null +++ b/backend/ent/schema/agent_rule.go @@ -0,0 +1,91 @@ +package schema + +import ( + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/schema" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/index" + "github.com/google/uuid" +) + +// AgentRule holds the schema definition for the agent_rules entity. +type AgentRule struct { + ent.Schema +} + +func (AgentRule) Annotations() []schema.Annotation { + return []schema.Annotation{ + entsql.Table("agent_rules"), + } +} + +// Fields of the AgentRule. +func (AgentRule) Fields() []ent.Field { + return []ent.Field{ + field.UUID("id", uuid.UUID{}).Default(uuid.New), + field.String("name").NotEmpty(), + field.Text("description").Optional(), + field.Enum("scope_type").Values("global").Default("global"), + field.String("scope_id").Default("global"), + field.UUID("created_by", uuid.UUID{}), + field.UUID("active_version_id", uuid.UUID{}).Optional().Nillable(), + field.Bool("is_deleted").Default(false), + field.Time("created_at").Default(time.Now), + field.Time("updated_at").Default(time.Now).UpdateDefault(time.Now), + } +} + +// Edges of the AgentRule. +func (AgentRule) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("versions", AgentRuleVersion.Type), + } +} + +// Indexes of the AgentRule. +func (AgentRule) Indexes() []ent.Index { + return []ent.Index{ + index.Fields("scope_type", "scope_id"), + index.Fields("active_version_id"), + } +} + +// AgentRuleVersion holds the schema definition for the agent_rule_versions entity. +type AgentRuleVersion struct { + ent.Schema +} + +func (AgentRuleVersion) Annotations() []schema.Annotation { + return []schema.Annotation{ + entsql.Table("agent_rule_versions"), + } +} + +// Fields of the AgentRuleVersion. +func (AgentRuleVersion) Fields() []ent.Field { + return []ent.Field{ + field.UUID("id", uuid.UUID{}).Default(uuid.New), + field.UUID("rule_id", uuid.UUID{}), + field.String("version").MaxLen(14).NotEmpty(), + field.Text("content"), + field.Time("created_at").Default(time.Now), + } +} + +// Edges of the AgentRuleVersion. +func (AgentRuleVersion) Edges() []ent.Edge { + return []ent.Edge{ + edge.From("rule", AgentRule.Type).Ref("versions").Field("rule_id").Unique().Required(), + } +} + +// Indexes of the AgentRuleVersion. +func (AgentRuleVersion) Indexes() []ent.Index { + return []ent.Index{ + index.Fields("rule_id"), + } +} diff --git a/backend/ent/schema/agent_skill.go b/backend/ent/schema/agent_skill.go new file mode 100644 index 00000000..bf822d4f --- /dev/null +++ b/backend/ent/schema/agent_skill.go @@ -0,0 +1,99 @@ +package schema + +import ( + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/schema" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/index" + "github.com/google/uuid" + + "github.com/chaitin/MonkeyCode/backend/ent/types" +) + +// AgentSkill holds the schema definition for the agent_skills entity. +type AgentSkill struct { + ent.Schema +} + +func (AgentSkill) Annotations() []schema.Annotation { + return []schema.Annotation{ + entsql.Table("agent_skills"), + } +} + +// Fields of the AgentSkill. +func (AgentSkill) Fields() []ent.Field { + return []ent.Field{ + field.UUID("id", uuid.UUID{}).Default(uuid.New), + field.UUID("repo_id", uuid.UUID{}), + field.String("name").NotEmpty(), + field.Text("description").Optional(), + field.Enum("scope_type").Values("global").Default("global"), + field.String("scope_id").Default("global"), + field.UUID("created_by", uuid.UUID{}), + field.UUID("active_version_id", uuid.UUID{}).Optional().Nillable(), + field.Bool("is_force_delivery").Default(false), + field.Bool("is_orphan").Default(false), + field.Bool("is_deleted").Default(false), + field.Time("created_at").Default(time.Now), + field.Time("updated_at").Default(time.Now).UpdateDefault(time.Now), + } +} + +// Edges of the AgentSkill. +func (AgentSkill) Edges() []ent.Edge { + return []ent.Edge{ + edge.From("repo", AgentSkillRepo.Type).Ref("skills").Field("repo_id").Unique().Required(), + edge.To("versions", AgentSkillVersion.Type), + } +} + +// Indexes of the AgentSkill. +func (AgentSkill) Indexes() []ent.Index { + return []ent.Index{ + index.Fields("repo_id", "name").Unique(), + index.Fields("scope_type", "scope_id"), + index.Fields("active_version_id"), + } +} + +// AgentSkillVersion holds the schema definition for the agent_skill_versions entity. +type AgentSkillVersion struct { + ent.Schema +} + +func (AgentSkillVersion) Annotations() []schema.Annotation { + return []schema.Annotation{ + entsql.Table("agent_skill_versions"), + } +} + +// Fields of the AgentSkillVersion. +func (AgentSkillVersion) Fields() []ent.Field { + return []ent.Field{ + field.UUID("id", uuid.UUID{}).Default(uuid.New), + field.UUID("resource_id", uuid.UUID{}), + field.String("version").NotEmpty(), + field.String("s3_key").NotEmpty(), + field.JSON("parsed_meta", types.SkillParsedMeta{}).Optional(), + field.Time("created_at").Default(time.Now), + } +} + +// Edges of the AgentSkillVersion. +func (AgentSkillVersion) Edges() []ent.Edge { + return []ent.Edge{ + edge.From("skill", AgentSkill.Type).Ref("versions").Field("resource_id").Unique().Required(), + } +} + +// Indexes of the AgentSkillVersion. +func (AgentSkillVersion) Indexes() []ent.Index { + return []ent.Index{ + index.Fields("resource_id"), + } +} diff --git a/backend/ent/schema/agent_skill_repo.go b/backend/ent/schema/agent_skill_repo.go new file mode 100644 index 00000000..114831ea --- /dev/null +++ b/backend/ent/schema/agent_skill_repo.go @@ -0,0 +1,61 @@ +package schema + +import ( + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/schema" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/index" + "github.com/google/uuid" +) + +// AgentSkillRepo holds the schema definition for the agent_skill_repos entity. +type AgentSkillRepo struct { + ent.Schema +} + +func (AgentSkillRepo) Annotations() []schema.Annotation { + return []schema.Annotation{ + entsql.Table("agent_skill_repos"), + } +} + +// Fields of the AgentSkillRepo. +func (AgentSkillRepo) Fields() []ent.Field { + return []ent.Field{ + field.UUID("id", uuid.UUID{}).Default(uuid.New), + field.String("name").NotEmpty(), + field.Enum("scope_type").Values("global").Default("global"), + field.String("scope_id").Default("global"), + field.UUID("created_by", uuid.UUID{}), + field.Enum("source_type").Values("github", "upload"), + // github + field.String("github_url").Optional().Nillable(), + field.Enum("ref_type").Values("branch", "tag", "commit").Optional().Nillable(), + field.String("ref_value").Optional().Nillable(), + // upload + field.String("last_upload_filename").Optional().Nillable(), + field.Time("last_upload_at").Optional().Nillable(), + + field.Bool("is_deleted").Default(false), + field.Time("created_at").Default(time.Now), + field.Time("updated_at").Default(time.Now).UpdateDefault(time.Now), + } +} + +// Edges of the AgentSkillRepo. +func (AgentSkillRepo) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("skills", AgentSkill.Type), + } +} + +// Indexes of the AgentSkillRepo. +func (AgentSkillRepo) Indexes() []ent.Index { + return []ent.Index{ + index.Fields("scope_type", "scope_id"), + } +} diff --git a/backend/ent/schema/agent_sync_job.go b/backend/ent/schema/agent_sync_job.go new file mode 100644 index 00000000..07f94a72 --- /dev/null +++ b/backend/ent/schema/agent_sync_job.go @@ -0,0 +1,59 @@ +package schema + +import ( + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/schema" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/index" + "github.com/google/uuid" + + "github.com/chaitin/MonkeyCode/backend/ent/types" +) + +// AgentSyncJob holds the schema definition for the agent_sync_jobs entity. +// +// sync_jobs references rule / repo via plain UUID columns (no ent edge), +// because resource_kind decides whether rule_id or repo_id is populated. +type AgentSyncJob struct { + ent.Schema +} + +func (AgentSyncJob) Annotations() []schema.Annotation { + return []schema.Annotation{ + entsql.Table("agent_sync_jobs"), + } +} + +// Fields of the AgentSyncJob. +func (AgentSyncJob) Fields() []ent.Field { + return []ent.Field{ + field.UUID("id", uuid.UUID{}).Default(uuid.New), + field.Enum("resource_kind").Values("rule", "skill", "plugin"), + field.UUID("rule_id", uuid.UUID{}).Optional().Nillable(), + field.UUID("repo_id", uuid.UUID{}).Optional().Nillable(), + field.Enum("source_type").Values("github", "upload", "npm", "rule_inline"), + field.Enum("status"). + Values("pending", "fetching", "parsing", "uploading", "done", "failed"). + Default("pending"), + field.Enum("trigger_type").Values("manual", "upload", "rule_save"), + field.UUID("triggered_by", uuid.UUID{}).Optional().Nillable(), + field.Time("started_at").Optional().Nillable(), + field.Time("finished_at").Optional().Nillable(), + field.JSON("errors", types.SyncJobErrors{}).Optional(), + field.JSON("result_summary", types.SyncJobResultSummary{}).Optional(), + field.Time("created_at").Default(time.Now), + field.Time("updated_at").Default(time.Now).UpdateDefault(time.Now), + } +} + +// Indexes of the AgentSyncJob. +func (AgentSyncJob) Indexes() []ent.Index { + return []ent.Index{ + index.Fields("status", "created_at"), + index.Fields("rule_id"), + index.Fields("repo_id"), + } +} diff --git a/backend/ent/types/agent_resources.go b/backend/ent/types/agent_resources.go new file mode 100644 index 00000000..0f2d9679 --- /dev/null +++ b/backend/ent/types/agent_resources.go @@ -0,0 +1,40 @@ +package types + +// SkillParsedMeta is the parsed_meta jsonb payload for agent_skill_versions. +// It mirrors the SKILL.md frontmatter. +type SkillParsedMeta struct { + Description string `json:"description,omitempty"` + Categories []string `json:"categories,omitempty"` + Tags []string `json:"tags,omitempty"` +} + +// PluginParsedMeta is the parsed_meta jsonb payload for agent_plugin_versions. +type PluginParsedMeta struct { + Entry string `json:"entry"` +} + +// PluginManualEntry is one item in agent_plugin_repos.plugin_manual_entries. +type PluginManualEntry struct { + Name string `json:"name"` + Entrypoint string `json:"entrypoint"` +} + +// PluginManualEntries is the jsonb array stored on agent_plugin_repos. +type PluginManualEntries []PluginManualEntry + +// SyncJobError describes a single failure entry recorded on agent_sync_jobs.errors. +type SyncJobError struct { + Dir string `json:"dir,omitempty"` + Reason string `json:"reason"` + Detail string `json:"detail,omitempty"` +} + +// SyncJobErrors is the jsonb array stored on agent_sync_jobs.errors. +type SyncJobErrors []SyncJobError + +// SyncJobResultSummary is the jsonb payload stored on agent_sync_jobs.result_summary. +type SyncJobResultSummary struct { + Created []string `json:"created,omitempty"` + Updated []string `json:"updated,omitempty"` + Orphaned []string `json:"orphaned,omitempty"` +} diff --git a/backend/migration/000011_agent_resources.down.sql b/backend/migration/000011_agent_resources.down.sql new file mode 100644 index 00000000..5fc4c14c --- /dev/null +++ b/backend/migration/000011_agent_resources.down.sql @@ -0,0 +1,21 @@ +BEGIN; + +-- 反向 FK 先 drop +ALTER TABLE IF EXISTS agent_plugins + DROP CONSTRAINT IF EXISTS agent_plugins_active_version_fk; +ALTER TABLE IF EXISTS agent_skills + DROP CONSTRAINT IF EXISTS agent_skills_active_version_fk; +ALTER TABLE IF EXISTS agent_rules + DROP CONSTRAINT IF EXISTS agent_rules_active_version_fk; + +DROP TABLE IF EXISTS agent_sync_jobs; +DROP TABLE IF EXISTS agent_plugin_versions; +DROP TABLE IF EXISTS agent_skill_versions; +DROP TABLE IF EXISTS agent_plugins; +DROP TABLE IF EXISTS agent_skills; +DROP TABLE IF EXISTS agent_plugin_repos; +DROP TABLE IF EXISTS agent_skill_repos; +DROP TABLE IF EXISTS agent_rule_versions; +DROP TABLE IF EXISTS agent_rules; + +COMMIT; diff --git a/backend/migration/000011_agent_resources.up.sql b/backend/migration/000011_agent_resources.up.sql new file mode 100644 index 00000000..015dde0e --- /dev/null +++ b/backend/migration/000011_agent_resources.up.sql @@ -0,0 +1,286 @@ +BEGIN; + +-- ===================================================================== +-- agent_rules: 全局规则资源(Markdown 全量内容由 DB 权威) +-- ===================================================================== +CREATE TABLE IF NOT EXISTS agent_rules ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + name VARCHAR(255) NOT NULL, + description TEXT, + scope_type VARCHAR(32) NOT NULL DEFAULT 'global' + CHECK (scope_type = 'global'), + scope_id VARCHAR(64) NOT NULL DEFAULT 'global' + CHECK (scope_id = 'global'), + active_version_id UUID, + created_by UUID NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + updated_at TIMESTAMP NOT NULL DEFAULT NOW(), + is_deleted BOOLEAN NOT NULL DEFAULT FALSE +); + +CREATE INDEX IF NOT EXISTS idx_agent_rules_scope + ON agent_rules (scope_type, scope_id); +CREATE INDEX IF NOT EXISTS idx_agent_rules_active_version + ON agent_rules (active_version_id); +CREATE UNIQUE INDEX IF NOT EXISTS uniq_agent_rules_name_scope + ON agent_rules (name, scope_type, scope_id) + WHERE is_deleted = FALSE; + +-- ===================================================================== +-- agent_rule_versions: rule 历史版本(content 是唯一权威源;rule 不上 S3) +-- ===================================================================== +CREATE TABLE IF NOT EXISTS agent_rule_versions ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + rule_id UUID NOT NULL REFERENCES agent_rules(id), + version VARCHAR(14) NOT NULL, -- yyyymmddhhmmss + content TEXT NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT NOW() +); + +CREATE INDEX IF NOT EXISTS idx_agent_rule_versions_rule + ON agent_rule_versions (rule_id); + +-- ===================================================================== +-- agent_skill_repos: skill 源仓库(github / upload) +-- ===================================================================== +CREATE TABLE IF NOT EXISTS agent_skill_repos ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + name VARCHAR(255) NOT NULL, + scope_type VARCHAR(32) NOT NULL DEFAULT 'global' + CHECK (scope_type = 'global'), + scope_id VARCHAR(64) NOT NULL DEFAULT 'global' + CHECK (scope_id = 'global'), + created_by UUID NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + updated_at TIMESTAMP NOT NULL DEFAULT NOW(), + is_deleted BOOLEAN NOT NULL DEFAULT FALSE, + source_type VARCHAR(16) NOT NULL + CHECK (source_type IN ('github', 'upload')), + github_url VARCHAR(512), + ref_type VARCHAR(16) + CHECK (ref_type IS NULL OR ref_type IN ('branch', 'tag', 'commit')), + ref_value VARCHAR(255), + last_upload_filename VARCHAR(512), + last_upload_at TIMESTAMP, + -- source_type 与字段对应(§3.3) + CONSTRAINT agent_skill_repos_source_fields_chk CHECK ( + (source_type = 'github' + AND github_url IS NOT NULL + AND ref_type IS NOT NULL + AND ref_value IS NOT NULL + AND last_upload_filename IS NULL + AND last_upload_at IS NULL) + OR + (source_type = 'upload' + AND github_url IS NULL + AND ref_type IS NULL + AND ref_value IS NULL) + ) +); + +CREATE INDEX IF NOT EXISTS idx_agent_skill_repos_scope + ON agent_skill_repos (scope_type, scope_id); + +-- ===================================================================== +-- agent_plugin_repos: plugin 源仓库(github / upload / npm) +-- ===================================================================== +CREATE TABLE IF NOT EXISTS agent_plugin_repos ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + name VARCHAR(255) NOT NULL, + scope_type VARCHAR(32) NOT NULL DEFAULT 'global' + CHECK (scope_type = 'global'), + scope_id VARCHAR(64) NOT NULL DEFAULT 'global' + CHECK (scope_id = 'global'), + created_by UUID NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + updated_at TIMESTAMP NOT NULL DEFAULT NOW(), + is_deleted BOOLEAN NOT NULL DEFAULT FALSE, + source_type VARCHAR(16) NOT NULL + CHECK (source_type IN ('github', 'upload', 'npm')), + github_url VARCHAR(512), + ref_type VARCHAR(16) + CHECK (ref_type IS NULL OR ref_type IN ('branch', 'tag', 'commit')), + ref_value VARCHAR(255), + last_upload_filename VARCHAR(512), + last_upload_at TIMESTAMP, + plugin_discovery_auto_package_json BOOLEAN NOT NULL DEFAULT TRUE, + plugin_manual_entries JSONB, + npm_package_name VARCHAR(255), + npm_version_spec VARCHAR(64), + npm_registry_url VARCHAR(512), + -- source_type 与字段对应(§3.3) + CONSTRAINT agent_plugin_repos_source_fields_chk CHECK ( + (source_type = 'github' + AND github_url IS NOT NULL + AND ref_type IS NOT NULL + AND ref_value IS NOT NULL + AND last_upload_filename IS NULL + AND last_upload_at IS NULL + AND npm_package_name IS NULL + AND npm_version_spec IS NULL + AND npm_registry_url IS NULL) + OR + (source_type = 'upload' + AND github_url IS NULL + AND ref_type IS NULL + AND ref_value IS NULL + AND npm_package_name IS NULL + AND npm_version_spec IS NULL + AND npm_registry_url IS NULL) + OR + (source_type = 'npm' + AND npm_package_name IS NOT NULL + AND github_url IS NULL + AND ref_type IS NULL + AND ref_value IS NULL + AND last_upload_filename IS NULL + AND last_upload_at IS NULL + AND plugin_discovery_auto_package_json = TRUE + AND plugin_manual_entries IS NULL) + ) +); + +CREATE INDEX IF NOT EXISTS idx_agent_plugin_repos_scope + ON agent_plugin_repos (scope_type, scope_id); + +-- ===================================================================== +-- agent_skills: skill 资源(指向 skill_repo) +-- ===================================================================== +CREATE TABLE IF NOT EXISTS agent_skills ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + name VARCHAR(255) NOT NULL, + description TEXT, + scope_type VARCHAR(32) NOT NULL DEFAULT 'global' + CHECK (scope_type = 'global'), + scope_id VARCHAR(64) NOT NULL DEFAULT 'global' + CHECK (scope_id = 'global'), + repo_id UUID NOT NULL REFERENCES agent_skill_repos(id), + created_by UUID NOT NULL, + is_force_delivery BOOLEAN NOT NULL DEFAULT FALSE, + is_orphan BOOLEAN NOT NULL DEFAULT FALSE, + is_deleted BOOLEAN NOT NULL DEFAULT FALSE, + active_version_id UUID, + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + updated_at TIMESTAMP NOT NULL DEFAULT NOW() +); + +CREATE INDEX IF NOT EXISTS idx_agent_skills_scope + ON agent_skills (scope_type, scope_id); +CREATE INDEX IF NOT EXISTS idx_agent_skills_repo + ON agent_skills (repo_id); +CREATE INDEX IF NOT EXISTS idx_agent_skills_active_version + ON agent_skills (active_version_id); +CREATE UNIQUE INDEX IF NOT EXISTS uniq_agent_skills_repo_name + ON agent_skills (repo_id, name); + +-- ===================================================================== +-- agent_plugins: plugin 资源(指向 plugin_repo) +-- ===================================================================== +CREATE TABLE IF NOT EXISTS agent_plugins ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + name VARCHAR(255) NOT NULL, + description TEXT, + scope_type VARCHAR(32) NOT NULL DEFAULT 'global' + CHECK (scope_type = 'global'), + scope_id VARCHAR(64) NOT NULL DEFAULT 'global' + CHECK (scope_id = 'global'), + repo_id UUID NOT NULL REFERENCES agent_plugin_repos(id), + created_by UUID NOT NULL, + is_force_delivery BOOLEAN NOT NULL DEFAULT FALSE, + is_orphan BOOLEAN NOT NULL DEFAULT FALSE, + is_deleted BOOLEAN NOT NULL DEFAULT FALSE, + active_version_id UUID, + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + updated_at TIMESTAMP NOT NULL DEFAULT NOW() +); + +CREATE INDEX IF NOT EXISTS idx_agent_plugins_scope + ON agent_plugins (scope_type, scope_id); +CREATE INDEX IF NOT EXISTS idx_agent_plugins_repo + ON agent_plugins (repo_id); +CREATE INDEX IF NOT EXISTS idx_agent_plugins_active_version + ON agent_plugins (active_version_id); +CREATE UNIQUE INDEX IF NOT EXISTS uniq_agent_plugins_repo_name + ON agent_plugins (repo_id, name); + +-- ===================================================================== +-- agent_skill_versions / agent_plugin_versions +-- ===================================================================== +CREATE TABLE IF NOT EXISTS agent_skill_versions ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + resource_id UUID NOT NULL REFERENCES agent_skills(id), + version VARCHAR(64) NOT NULL, + s3_key VARCHAR(512) NOT NULL, + parsed_meta JSONB, + created_at TIMESTAMP NOT NULL DEFAULT NOW() +); + +CREATE INDEX IF NOT EXISTS idx_agent_skill_versions_resource + ON agent_skill_versions (resource_id); + +CREATE TABLE IF NOT EXISTS agent_plugin_versions ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + resource_id UUID NOT NULL REFERENCES agent_plugins(id), + version VARCHAR(64) NOT NULL, + s3_key VARCHAR(512) NOT NULL, + parsed_meta JSONB, + created_at TIMESTAMP NOT NULL DEFAULT NOW() +); + +CREATE INDEX IF NOT EXISTS idx_agent_plugin_versions_resource + ON agent_plugin_versions (resource_id); + +-- ===================================================================== +-- agent_sync_jobs: 同步任务流水(rule / skill / plugin 共用) +-- ===================================================================== +CREATE TABLE IF NOT EXISTS agent_sync_jobs ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + resource_kind VARCHAR(16) NOT NULL + CHECK (resource_kind IN ('rule', 'skill', 'plugin')), + rule_id UUID, + repo_id UUID, + source_type VARCHAR(16) NOT NULL + CHECK (source_type IN ('github', 'upload', 'npm', 'rule_inline')), + status VARCHAR(16) NOT NULL + CHECK (status IN ('pending', 'fetching', 'parsing', 'uploading', 'done', 'failed')), + trigger_type VARCHAR(16) NOT NULL + CHECK (trigger_type IN ('manual', 'upload', 'rule_save')), + triggered_by UUID, + started_at TIMESTAMP, + finished_at TIMESTAMP, + errors JSONB, + result_summary JSONB, + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + -- resource_kind 与 rule_id / repo_id 的对应 + CONSTRAINT agent_sync_jobs_resource_ref_chk CHECK ( + (resource_kind = 'rule' + AND rule_id IS NOT NULL + AND repo_id IS NULL) + OR + (resource_kind IN ('skill', 'plugin') + AND repo_id IS NOT NULL + AND rule_id IS NULL) + ) +); + +CREATE INDEX IF NOT EXISTS idx_agent_sync_jobs_status_created + ON agent_sync_jobs (status, created_at); +CREATE INDEX IF NOT EXISTS idx_agent_sync_jobs_resource_kind + ON agent_sync_jobs (resource_kind); + +-- ===================================================================== +-- active_version_id 反向 FK(版本表已建好后追加) +-- ===================================================================== +ALTER TABLE agent_rules + ADD CONSTRAINT agent_rules_active_version_fk + FOREIGN KEY (active_version_id) REFERENCES agent_rule_versions(id); + +ALTER TABLE agent_skills + ADD CONSTRAINT agent_skills_active_version_fk + FOREIGN KEY (active_version_id) REFERENCES agent_skill_versions(id); + +ALTER TABLE agent_plugins + ADD CONSTRAINT agent_plugins_active_version_fk + FOREIGN KEY (active_version_id) REFERENCES agent_plugin_versions(id); + +COMMIT; From 2b0504585c4362456f40d7e2ad79f67ee96bbf8d Mon Sep 17 00:00:00 2001 From: xmv97 Date: Fri, 5 Jun 2026 08:47:45 +0000 Subject: [PATCH 02/11] feat(oss): add GetObject + fix Aliyun OSS aws-chunked compat --- backend/pkg/oss/oss.go | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/backend/pkg/oss/oss.go b/backend/pkg/oss/oss.go index 12dec82a..0e0ade0d 100644 --- a/backend/pkg/oss/oss.go +++ b/backend/pkg/oss/oss.go @@ -12,6 +12,7 @@ import ( "time" "github.com/aws/aws-sdk-go-v2/aws" + v4 "github.com/aws/aws-sdk-go-v2/aws/signer/v4" awsconfig "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/credentials" "github.com/aws/aws-sdk-go-v2/service/s3" @@ -58,6 +59,16 @@ func NewS3Compatible(ctx context.Context, cfg config.ObjectStorageConfig, opt S3 client := s3.NewFromConfig(awsCfg, func(o *s3.Options) { o.BaseEndpoint = aws.String(cfg.Endpoint) o.UsePathStyle = opt.ForcePathStyle + // Aliyun OSS compatibility for aws-sdk-go-v2 >= v1.66: + // disable the default CRC32 trailer (which forces aws-chunked + // Content-Encoding) and switch the x-amz-content-sha256 header + // from the streaming STREAMING-AWS4-HMAC-SHA256-PAYLOAD value + // to UNSIGNED-PAYLOAD, both of which Aliyun OSS rejects with + // 400 "aws-chunked encoding is not supported with the specified + // x-amz-content-sha256 value". + o.RequestChecksumCalculation = aws.RequestChecksumCalculationWhenRequired + o.ResponseChecksumValidation = aws.ResponseChecksumValidationWhenRequired + o.APIOptions = append(o.APIOptions, v4.SwapComputePayloadSHA256ForUnsignedPayloadMiddleware) }) c := &Client{ cfg: cfg, @@ -163,6 +174,23 @@ func (c *Client) HeadFile(ctx context.Context, prefix, filename string) (bool, e return false, err } +// GetObject fetches the object body at the given key (relative to the bucket). +// Used by the agent-resources read path (skill / plugin zip download). +// The key is passed through verbatim — callers already build the full path +// (e.g. "agent-resources/skills/global/global/{repoID}/{name}/{version}.zip") +// and no implicit prefix is added. +// Caller must close the returned io.ReadCloser. +func (c *Client) GetObject(ctx context.Context, key string) (io.ReadCloser, error) { + out, err := c.s3.GetObject(ctx, &s3.GetObjectInput{ + Bucket: aws.String(c.cfg.Bucket), + Key: aws.String(key), + }) + if err != nil { + return nil, fmt.Errorf("oss: get %q: %w", key, err) + } + return out.Body, nil +} + func (c *Client) WithAccessEndpoint(endpoint string) *Client { endpoint = strings.TrimSpace(endpoint) if c == nil || endpoint == "" { From 3a5b6b8cccbec2a479b4dc6d596cba8d22adb517 Mon Sep 17 00:00:00 2001 From: xmv97 Date: Fri, 5 Jun 2026 08:55:52 +0000 Subject: [PATCH 03/11] feat(domain): add Extra.PluginIDs for OpenCode plugin downstream --- backend/docs/swagger.json | 7 +++++++ backend/domain/task.go | 1 + 2 files changed, 8 insertions(+) diff --git a/backend/docs/swagger.json b/backend/docs/swagger.json index 2c5412ef..f4a7c6eb 100644 --- a/backend/docs/swagger.json +++ b/backend/docs/swagger.json @@ -11144,6 +11144,13 @@ "issue_id": { "type": "string" }, + "plugin_ids": { + "description": "Plugin IDs 数组(仅 OpenCode 真正下发)", + "type": "array", + "items": { + "type": "string" + } + }, "project_id": { "type": "string" }, diff --git a/backend/domain/task.go b/backend/domain/task.go index 8325e4cf..a768780f 100644 --- a/backend/domain/task.go +++ b/backend/domain/task.go @@ -77,6 +77,7 @@ type TaskExtraConfig struct { ProjectID uuid.UUID `json:"project_id" validate:"omitempty"` IssueID uuid.UUID `json:"issue_id" validate:"omitempty"` SkillIDs []string `json:"skill_ids" validate:"omitempty"` + PluginIDs []string `json:"plugin_ids" validate:"omitempty"` // Plugin IDs 数组(仅 OpenCode 真正下发) } // CreateTaskReq 创建任务请求 From e133cd21393f8cad6fadc37c1ea83fc921f3642e Mon Sep 17 00:00:00 2001 From: xmv97 Date: Fri, 5 Jun 2026 08:56:05 +0000 Subject: [PATCH 04/11] feat(biz/agentresource): read-only repo + resolver for OSS-backed assets Mirror the mcai-backend agentresource package onto the gh backend so the task dispatch path and the public skill/plugin pickers can read shared agent resources without depending on admin BFF mutations. - repo: two-step queries over agent_rule/skill/plugin + their active version rows. Rules read content straight from DB; skills/plugins surface s3_key + parsed_meta for downstream materialization. - resolver: pulls each skill/plugin zip via a minimal ObjectStore interface (pkg/oss.Client satisfies it implicitly) and unzips in memory with zip-bomb / zip-slip guards. Per-asset fetch/unzip errors are logged and skipped so one bad asset can't break dispatch. - tests: sqlite-backed ent tests for the repo (union, orphan, deleted, no-active-version) plus fake-driven resolver tests covering rules, unzip safety, and user/force union forwarding. --- backend/biz/agentresource/repo.go | 363 +++++++++++++++++ backend/biz/agentresource/repo_test.go | 442 +++++++++++++++++++++ backend/biz/agentresource/resolver.go | 153 +++++++ backend/biz/agentresource/resolver_test.go | 280 +++++++++++++ backend/biz/agentresource/types.go | 97 +++++ backend/biz/agentresource/unpack.go | 127 ++++++ backend/biz/agentresource/unpack_test.go | 134 +++++++ 7 files changed, 1596 insertions(+) create mode 100644 backend/biz/agentresource/repo.go create mode 100644 backend/biz/agentresource/repo_test.go create mode 100644 backend/biz/agentresource/resolver.go create mode 100644 backend/biz/agentresource/resolver_test.go create mode 100644 backend/biz/agentresource/types.go create mode 100644 backend/biz/agentresource/unpack.go create mode 100644 backend/biz/agentresource/unpack_test.go diff --git a/backend/biz/agentresource/repo.go b/backend/biz/agentresource/repo.go new file mode 100644 index 00000000..95af3381 --- /dev/null +++ b/backend/biz/agentresource/repo.go @@ -0,0 +1,363 @@ +package agentresource + +import ( + "context" + "fmt" + + "github.com/google/uuid" + + "github.com/chaitin/MonkeyCode/backend/db" + "github.com/chaitin/MonkeyCode/backend/db/agentplugin" + "github.com/chaitin/MonkeyCode/backend/db/agentpluginversion" + "github.com/chaitin/MonkeyCode/backend/db/agentrule" + "github.com/chaitin/MonkeyCode/backend/db/agentruleversion" + "github.com/chaitin/MonkeyCode/backend/db/agentskill" + "github.com/chaitin/MonkeyCode/backend/db/agentskillversion" +) + +// Repo is the read-only surface used by the task dispatch path and by the +// public listing endpoints. All methods are safe to call concurrently. +type Repo interface { + // ListActiveRules returns every non-deleted rule whose active version + // row exists. Used by getCodingConfigs. Rule content comes straight from + // the DB; there is no S3 indirection for rules. + ListActiveRules(ctx context.Context) ([]*RuleWithVersion, error) + + // ListActiveSkills returns the union of {userSelectedIDs} and + // {is_force_delivery=true} skills. Orphan skills are kept so the agent + // keeps shipping whatever was previously active. Deleted skills and + // skills without an active_version_id are skipped. + ListActiveSkills(ctx context.Context, userSelectedIDs []uuid.UUID) ([]*SkillWithVersion, error) + + // ListActivePlugins mirrors ListActiveSkills for plugins. + ListActivePlugins(ctx context.Context, userSelectedIDs []uuid.UUID) ([]*PluginWithVersion, error) + + // ListSkillsForListing powers the /api/v1/skills picker. Orphans are + // hidden because users should not pick a resource that is no longer + // in the upstream repo. + ListSkillsForListing(ctx context.Context) ([]*ResourceListItem, error) + + // ListPluginsForListing powers the /api/v1/plugins picker. + ListPluginsForListing(ctx context.Context) ([]*ResourceListItem, error) +} + +type repoImpl struct { + db *db.Client +} + +// NewRepo wires a Repo backed by the given ent client. +func NewRepo(client *db.Client) Repo { + return &repoImpl{db: client} +} + +// ---- rules ---- + +func (r *repoImpl) ListActiveRules(ctx context.Context) ([]*RuleWithVersion, error) { + rules, err := r.db.AgentRule.Query(). + Where( + agentrule.IsDeletedEQ(false), + agentrule.ActiveVersionIDNotNil(), + ). + Order(db.Asc(agentrule.FieldName)). + All(ctx) + if err != nil { + return nil, fmt.Errorf("agentresource: list rules: %w", err) + } + if len(rules) == 0 { + return nil, nil + } + + versionIDs := make([]uuid.UUID, 0, len(rules)) + for _, ru := range rules { + if ru.ActiveVersionID != nil { + versionIDs = append(versionIDs, *ru.ActiveVersionID) + } + } + + versions, err := r.db.AgentRuleVersion.Query(). + Where(agentruleversion.IDIn(versionIDs...)). + All(ctx) + if err != nil { + return nil, fmt.Errorf("agentresource: list rule versions: %w", err) + } + + versionByID := make(map[uuid.UUID]*db.AgentRuleVersion, len(versions)) + for _, v := range versions { + versionByID[v.ID] = v + } + + out := make([]*RuleWithVersion, 0, len(rules)) + for _, ru := range rules { + if ru.ActiveVersionID == nil { + continue + } + v, ok := versionByID[*ru.ActiveVersionID] + if !ok { + // Active version dangling — should not happen in practice but + // skip rather than crash task creation. + continue + } + out = append(out, &RuleWithVersion{ + ID: ru.ID, + Name: ru.Name, + Version: v.Version, + Content: v.Content, + UpdatedAt: ru.UpdatedAt, + }) + } + return out, nil +} + +// ---- skills ---- + +func (r *repoImpl) ListActiveSkills(ctx context.Context, userSelectedIDs []uuid.UUID) ([]*SkillWithVersion, error) { + // Base filter: not deleted + has an active version. We then OR together + // (id in user-selected) and (is_force_delivery = true). + q := r.db.AgentSkill.Query(). + Where( + agentskill.IsDeletedEQ(false), + agentskill.ActiveVersionIDNotNil(), + ) + + if len(userSelectedIDs) == 0 { + // Only force-delivery skills matter when the caller selected none. + q = q.Where(agentskill.IsForceDeliveryEQ(true)) + } else { + q = q.Where(agentskill.Or( + agentskill.IDIn(userSelectedIDs...), + agentskill.IsForceDeliveryEQ(true), + )) + } + + skills, err := q.Order(db.Asc(agentskill.FieldName)).All(ctx) + if err != nil { + return nil, fmt.Errorf("agentresource: list skills: %w", err) + } + if len(skills) == 0 { + return nil, nil + } + + versionIDs := make([]uuid.UUID, 0, len(skills)) + for _, s := range skills { + if s.ActiveVersionID != nil { + versionIDs = append(versionIDs, *s.ActiveVersionID) + } + } + + versions, err := r.db.AgentSkillVersion.Query(). + Where(agentskillversion.IDIn(versionIDs...)). + All(ctx) + if err != nil { + return nil, fmt.Errorf("agentresource: list skill versions: %w", err) + } + + versionByID := make(map[uuid.UUID]*db.AgentSkillVersion, len(versions)) + for _, v := range versions { + versionByID[v.ID] = v + } + + out := make([]*SkillWithVersion, 0, len(skills)) + for _, s := range skills { + if s.ActiveVersionID == nil { + continue + } + v, ok := versionByID[*s.ActiveVersionID] + if !ok { + continue + } + out = append(out, &SkillWithVersion{ + ID: s.ID, + Name: s.Name, + Description: s.Description, + Version: v.Version, + S3Key: v.S3Key, + IsForceDelivery: s.IsForceDelivery, + IsOrphan: s.IsOrphan, + ParsedMeta: v.ParsedMeta, + UpdatedAt: s.UpdatedAt, + }) + } + return out, nil +} + +// ---- plugins ---- + +func (r *repoImpl) ListActivePlugins(ctx context.Context, userSelectedIDs []uuid.UUID) ([]*PluginWithVersion, error) { + q := r.db.AgentPlugin.Query(). + Where( + agentplugin.IsDeletedEQ(false), + agentplugin.ActiveVersionIDNotNil(), + ) + + if len(userSelectedIDs) == 0 { + q = q.Where(agentplugin.IsForceDeliveryEQ(true)) + } else { + q = q.Where(agentplugin.Or( + agentplugin.IDIn(userSelectedIDs...), + agentplugin.IsForceDeliveryEQ(true), + )) + } + + plugins, err := q.Order(db.Asc(agentplugin.FieldName)).All(ctx) + if err != nil { + return nil, fmt.Errorf("agentresource: list plugins: %w", err) + } + if len(plugins) == 0 { + return nil, nil + } + + versionIDs := make([]uuid.UUID, 0, len(plugins)) + for _, p := range plugins { + if p.ActiveVersionID != nil { + versionIDs = append(versionIDs, *p.ActiveVersionID) + } + } + + versions, err := r.db.AgentPluginVersion.Query(). + Where(agentpluginversion.IDIn(versionIDs...)). + All(ctx) + if err != nil { + return nil, fmt.Errorf("agentresource: list plugin versions: %w", err) + } + + versionByID := make(map[uuid.UUID]*db.AgentPluginVersion, len(versions)) + for _, v := range versions { + versionByID[v.ID] = v + } + + out := make([]*PluginWithVersion, 0, len(plugins)) + for _, p := range plugins { + if p.ActiveVersionID == nil { + continue + } + v, ok := versionByID[*p.ActiveVersionID] + if !ok { + continue + } + out = append(out, &PluginWithVersion{ + ID: p.ID, + Name: p.Name, + Description: p.Description, + Version: v.Version, + S3Key: v.S3Key, + IsForceDelivery: p.IsForceDelivery, + IsOrphan: p.IsOrphan, + Entry: v.ParsedMeta.Entry, + UpdatedAt: p.UpdatedAt, + }) + } + return out, nil +} + +// ---- listing endpoints ---- + +func (r *repoImpl) ListSkillsForListing(ctx context.Context) ([]*ResourceListItem, error) { + skills, err := r.db.AgentSkill.Query(). + Where( + agentskill.IsDeletedEQ(false), + agentskill.IsOrphanEQ(false), + agentskill.ActiveVersionIDNotNil(), + ). + Order(db.Asc(agentskill.FieldName)). + All(ctx) + if err != nil { + return nil, fmt.Errorf("agentresource: list skills for listing: %w", err) + } + if len(skills) == 0 { + return nil, nil + } + + versionIDs := make([]uuid.UUID, 0, len(skills)) + for _, s := range skills { + if s.ActiveVersionID != nil { + versionIDs = append(versionIDs, *s.ActiveVersionID) + } + } + + versions, err := r.db.AgentSkillVersion.Query(). + Where(agentskillversion.IDIn(versionIDs...)). + All(ctx) + if err != nil { + return nil, fmt.Errorf("agentresource: list skill versions for listing: %w", err) + } + + versionByID := make(map[uuid.UUID]*db.AgentSkillVersion, len(versions)) + for _, v := range versions { + versionByID[v.ID] = v + } + + out := make([]*ResourceListItem, 0, len(skills)) + for _, s := range skills { + if s.ActiveVersionID == nil { + continue + } + v, ok := versionByID[*s.ActiveVersionID] + if !ok { + continue + } + out = append(out, &ResourceListItem{ + ID: s.ID, + Name: s.Name, + Description: s.Description, + Version: v.Version, + IsForceDelivery: s.IsForceDelivery, + }) + } + return out, nil +} + +func (r *repoImpl) ListPluginsForListing(ctx context.Context) ([]*ResourceListItem, error) { + plugins, err := r.db.AgentPlugin.Query(). + Where( + agentplugin.IsDeletedEQ(false), + agentplugin.IsOrphanEQ(false), + agentplugin.ActiveVersionIDNotNil(), + ). + Order(db.Asc(agentplugin.FieldName)). + All(ctx) + if err != nil { + return nil, fmt.Errorf("agentresource: list plugins for listing: %w", err) + } + if len(plugins) == 0 { + return nil, nil + } + + versionIDs := make([]uuid.UUID, 0, len(plugins)) + for _, p := range plugins { + if p.ActiveVersionID != nil { + versionIDs = append(versionIDs, *p.ActiveVersionID) + } + } + + versions, err := r.db.AgentPluginVersion.Query(). + Where(agentpluginversion.IDIn(versionIDs...)). + All(ctx) + if err != nil { + return nil, fmt.Errorf("agentresource: list plugin versions for listing: %w", err) + } + + versionByID := make(map[uuid.UUID]*db.AgentPluginVersion, len(versions)) + for _, v := range versions { + versionByID[v.ID] = v + } + + out := make([]*ResourceListItem, 0, len(plugins)) + for _, p := range plugins { + if p.ActiveVersionID == nil { + continue + } + v, ok := versionByID[*p.ActiveVersionID] + if !ok { + continue + } + out = append(out, &ResourceListItem{ + ID: p.ID, + Name: p.Name, + Description: p.Description, + Version: v.Version, + IsForceDelivery: p.IsForceDelivery, + Entry: v.ParsedMeta.Entry, + }) + } + return out, nil +} diff --git a/backend/biz/agentresource/repo_test.go b/backend/biz/agentresource/repo_test.go new file mode 100644 index 00000000..95482808 --- /dev/null +++ b/backend/biz/agentresource/repo_test.go @@ -0,0 +1,442 @@ +package agentresource + +import ( + "context" + "testing" + + "github.com/google/uuid" + _ "github.com/mattn/go-sqlite3" + + "github.com/chaitin/MonkeyCode/backend/db" + "github.com/chaitin/MonkeyCode/backend/db/agentpluginrepo" + "github.com/chaitin/MonkeyCode/backend/db/agentskillrepo" + "github.com/chaitin/MonkeyCode/backend/db/enttest" + enttypes "github.com/chaitin/MonkeyCode/backend/ent/types" +) + +func newTestDB(t *testing.T, name string) *db.Client { + t.Helper() + dsn := "file:" + name + "?mode=memory&cache=shared&_fk=1" + client := enttest.Open(t, "sqlite3", dsn) + t.Cleanup(func() { _ = client.Close() }) + return client +} + +// seedRule creates a rule + (optionally) a single version, and points +// active_version_id at it. The content argument is the seed value placed in +// agent_rule_versions.content (rule content lives entirely in the DB; no S3 +// involvement for rules). +func seedRule(t *testing.T, ctx context.Context, client *db.Client, name string, isDeleted bool, content string, withVersion bool) (ruleID, versionID uuid.UUID) { + t.Helper() + creator := uuid.New() + rule, err := client.AgentRule.Create(). + SetName(name). + SetCreatedBy(creator). + SetIsDeleted(isDeleted). + Save(ctx) + if err != nil { + t.Fatalf("seed rule %s: %v", name, err) + } + if !withVersion { + return rule.ID, uuid.Nil + } + v, err := client.AgentRuleVersion.Create(). + SetRuleID(rule.ID). + SetVersion("v1"). + SetContent(content). + Save(ctx) + if err != nil { + t.Fatalf("seed rule version %s: %v", name, err) + } + if _, err := client.AgentRule.UpdateOneID(rule.ID).SetActiveVersionID(v.ID).Save(ctx); err != nil { + t.Fatalf("set active version for rule %s: %v", name, err) + } + return rule.ID, v.ID +} + +type skillSeed struct { + name string + isDeleted bool + isOrphan bool + isForceDelivery bool + withVersion bool // if false, active_version_id stays nil +} + +func seedSkill(t *testing.T, ctx context.Context, client *db.Client, repoID uuid.UUID, s skillSeed) uuid.UUID { + t.Helper() + creator := uuid.New() + sk, err := client.AgentSkill.Create(). + SetRepoID(repoID). + SetName(s.name). + SetCreatedBy(creator). + SetIsDeleted(s.isDeleted). + SetIsOrphan(s.isOrphan). + SetIsForceDelivery(s.isForceDelivery). + Save(ctx) + if err != nil { + t.Fatalf("seed skill %s: %v", s.name, err) + } + if !s.withVersion { + return sk.ID + } + v, err := client.AgentSkillVersion.Create(). + SetResourceID(sk.ID). + SetVersion("v1"). + SetS3Key("skills/" + s.name + ".tgz"). + SetParsedMeta(enttypes.SkillParsedMeta{Description: s.name + " desc"}). + Save(ctx) + if err != nil { + t.Fatalf("seed skill version %s: %v", s.name, err) + } + if _, err := client.AgentSkill.UpdateOneID(sk.ID).SetActiveVersionID(v.ID).Save(ctx); err != nil { + t.Fatalf("set active version for skill %s: %v", s.name, err) + } + return sk.ID +} + +func seedSkillRepo(t *testing.T, ctx context.Context, client *db.Client) uuid.UUID { + t.Helper() + r, err := client.AgentSkillRepo.Create(). + SetName("default"). + SetSourceType(agentskillrepo.SourceTypeGithub). + SetGithubURL("https://example.com/skills.git"). + SetCreatedBy(uuid.New()). + Save(ctx) + if err != nil { + t.Fatalf("seed skill repo: %v", err) + } + return r.ID +} + +func seedPluginRepo(t *testing.T, ctx context.Context, client *db.Client) uuid.UUID { + t.Helper() + r, err := client.AgentPluginRepo.Create(). + SetName("default"). + SetSourceType(agentpluginrepo.SourceTypeGithub). + SetGithubURL("https://example.com/plugins.git"). + SetCreatedBy(uuid.New()). + Save(ctx) + if err != nil { + t.Fatalf("seed plugin repo: %v", err) + } + return r.ID +} + +type pluginSeed struct { + name string + isDeleted bool + isOrphan bool + isForceDelivery bool + withVersion bool + entry string +} + +func seedPlugin(t *testing.T, ctx context.Context, client *db.Client, repoID uuid.UUID, p pluginSeed) uuid.UUID { + t.Helper() + creator := uuid.New() + pl, err := client.AgentPlugin.Create(). + SetRepoID(repoID). + SetName(p.name). + SetCreatedBy(creator). + SetIsDeleted(p.isDeleted). + SetIsOrphan(p.isOrphan). + SetIsForceDelivery(p.isForceDelivery). + Save(ctx) + if err != nil { + t.Fatalf("seed plugin %s: %v", p.name, err) + } + if !p.withVersion { + return pl.ID + } + entry := p.entry + if entry == "" { + entry = "index.js" + } + v, err := client.AgentPluginVersion.Create(). + SetResourceID(pl.ID). + SetVersion("v1"). + SetS3Key("plugins/" + p.name + ".tgz"). + SetParsedMeta(enttypes.PluginParsedMeta{Entry: entry}). + Save(ctx) + if err != nil { + t.Fatalf("seed plugin version %s: %v", p.name, err) + } + if _, err := client.AgentPlugin.UpdateOneID(pl.ID).SetActiveVersionID(v.ID).Save(ctx); err != nil { + t.Fatalf("set active version for plugin %s: %v", p.name, err) + } + return pl.ID +} + +// ---- ListActiveRules ---- + +func TestListActiveRules_ReturnsContent(t *testing.T) { + ctx := context.Background() + client := newTestDB(t, "agentresource-rules-content") + + seedRule(t, ctx, client, "rule-a", false, "hello", true) + + repo := NewRepo(client) + out, err := repo.ListActiveRules(ctx) + if err != nil { + t.Fatalf("ListActiveRules: %v", err) + } + if len(out) != 1 || out[0].Name != "rule-a" { + t.Fatalf("expected rule-a only, got %+v", out) + } + if out[0].Content != "hello" { + t.Fatalf("expected content %q, got %q", "hello", out[0].Content) + } +} + +func TestListActiveRules_SkipsDeleted(t *testing.T) { + ctx := context.Background() + client := newTestDB(t, "agentresource-rules-deleted") + + seedRule(t, ctx, client, "alive", false, "a", true) + seedRule(t, ctx, client, "tombstone", true, "b", true) + + repo := NewRepo(client) + out, err := repo.ListActiveRules(ctx) + if err != nil { + t.Fatalf("ListActiveRules: %v", err) + } + if len(out) != 1 || out[0].Name != "alive" { + t.Fatalf("expected only alive rule, got %+v", out) + } +} + +func TestListActiveRules_SkipsRuleWithoutActiveVersion(t *testing.T) { + ctx := context.Background() + client := newTestDB(t, "agentresource-rules-nover") + + seedRule(t, ctx, client, "no-active", false, "", false) + + repo := NewRepo(client) + out, err := repo.ListActiveRules(ctx) + if err != nil { + t.Fatalf("ListActiveRules: %v", err) + } + if len(out) != 0 { + t.Fatalf("expected no rules, got %+v", out) + } +} + +// ---- ListActiveSkills ---- + +func TestListActiveSkills_UnionWithForceDelivery(t *testing.T) { + ctx := context.Background() + client := newTestDB(t, "agentresource-skills-union") + repoID := seedSkillRepo(t, ctx, client) + + picked := seedSkill(t, ctx, client, repoID, skillSeed{name: "picked", withVersion: true}) + _ = seedSkill(t, ctx, client, repoID, skillSeed{name: "force", isForceDelivery: true, withVersion: true}) + _ = seedSkill(t, ctx, client, repoID, skillSeed{name: "ignored", withVersion: true}) // not selected, not forced + + repo := NewRepo(client) + out, err := repo.ListActiveSkills(ctx, []uuid.UUID{picked}) + if err != nil { + t.Fatalf("ListActiveSkills: %v", err) + } + names := skillNames(out) + if !equalStringSet(names, []string{"force", "picked"}) { + t.Fatalf("expected {force, picked}, got %v", names) + } +} + +func TestListActiveSkills_FilterDeleted(t *testing.T) { + ctx := context.Background() + client := newTestDB(t, "agentresource-skills-deleted") + repoID := seedSkillRepo(t, ctx, client) + + gone := seedSkill(t, ctx, client, repoID, skillSeed{name: "gone", isDeleted: true, withVersion: true}) + _ = seedSkill(t, ctx, client, repoID, skillSeed{name: "force-gone", isDeleted: true, isForceDelivery: true, withVersion: true}) + + repo := NewRepo(client) + out, err := repo.ListActiveSkills(ctx, []uuid.UUID{gone}) + if err != nil { + t.Fatalf("ListActiveSkills: %v", err) + } + if len(out) != 0 { + t.Fatalf("expected no skills (all deleted), got %+v", out) + } +} + +func TestListActiveSkills_KeepsOrphans(t *testing.T) { + ctx := context.Background() + client := newTestDB(t, "agentresource-skills-orphan") + repoID := seedSkillRepo(t, ctx, client) + + orphan := seedSkill(t, ctx, client, repoID, skillSeed{name: "orphan", isOrphan: true, withVersion: true}) + + repo := NewRepo(client) + out, err := repo.ListActiveSkills(ctx, []uuid.UUID{orphan}) + if err != nil { + t.Fatalf("ListActiveSkills: %v", err) + } + if len(out) != 1 || out[0].Name != "orphan" || !out[0].IsOrphan { + t.Fatalf("expected single orphan skill kept, got %+v", out) + } +} + +func TestListActiveSkills_EmptyUserIDs_OnlyForce(t *testing.T) { + ctx := context.Background() + client := newTestDB(t, "agentresource-skills-emptyuser") + repoID := seedSkillRepo(t, ctx, client) + + _ = seedSkill(t, ctx, client, repoID, skillSeed{name: "force-1", isForceDelivery: true, withVersion: true}) + _ = seedSkill(t, ctx, client, repoID, skillSeed{name: "not-force", withVersion: true}) + + repo := NewRepo(client) + out, err := repo.ListActiveSkills(ctx, nil) + if err != nil { + t.Fatalf("ListActiveSkills: %v", err) + } + if len(out) != 1 || out[0].Name != "force-1" { + t.Fatalf("expected only force-1, got %+v", out) + } +} + +func TestListActiveSkills_SkipsNoActiveVersion(t *testing.T) { + ctx := context.Background() + client := newTestDB(t, "agentresource-skills-nover") + repoID := seedSkillRepo(t, ctx, client) + + _ = seedSkill(t, ctx, client, repoID, skillSeed{name: "force-noversion", isForceDelivery: true, withVersion: false}) + + repo := NewRepo(client) + out, err := repo.ListActiveSkills(ctx, nil) + if err != nil { + t.Fatalf("ListActiveSkills: %v", err) + } + if len(out) != 0 { + t.Fatalf("expected no skills, got %+v", out) + } +} + +// ---- ListActivePlugins ---- + +func TestListActivePlugins_UnionAndEntry(t *testing.T) { + ctx := context.Background() + client := newTestDB(t, "agentresource-plugins-union") + repoID := seedPluginRepo(t, ctx, client) + + picked := seedPlugin(t, ctx, client, repoID, pluginSeed{name: "picked", withVersion: true, entry: "main.js"}) + _ = seedPlugin(t, ctx, client, repoID, pluginSeed{name: "force", isForceDelivery: true, withVersion: true, entry: "force.js"}) + _ = seedPlugin(t, ctx, client, repoID, pluginSeed{name: "ignored", withVersion: true}) + + repo := NewRepo(client) + out, err := repo.ListActivePlugins(ctx, []uuid.UUID{picked}) + if err != nil { + t.Fatalf("ListActivePlugins: %v", err) + } + got := map[string]string{} + for _, p := range out { + got[p.Name] = p.Entry + } + if len(got) != 2 || got["picked"] != "main.js" || got["force"] != "force.js" { + t.Fatalf("expected picked/main.js + force/force.js, got %+v", got) + } +} + +// ---- ListSkillsForListing ---- + +func TestListSkillsForListing_ExcludesOrphans(t *testing.T) { + ctx := context.Background() + client := newTestDB(t, "agentresource-skills-listing") + repoID := seedSkillRepo(t, ctx, client) + + _ = seedSkill(t, ctx, client, repoID, skillSeed{name: "active", withVersion: true}) + _ = seedSkill(t, ctx, client, repoID, skillSeed{name: "orphan", isOrphan: true, withVersion: true}) + _ = seedSkill(t, ctx, client, repoID, skillSeed{name: "deleted", isDeleted: true, withVersion: true}) + _ = seedSkill(t, ctx, client, repoID, skillSeed{name: "no-active", withVersion: false}) + + repo := NewRepo(client) + out, err := repo.ListSkillsForListing(ctx) + if err != nil { + t.Fatalf("ListSkillsForListing: %v", err) + } + names := listingNames(out) + if !equalStringSet(names, []string{"active"}) { + t.Fatalf("expected only {active}, got %v", names) + } + if out[0].Version != "v1" { + t.Fatalf("expected version v1, got %q", out[0].Version) + } +} + +// ---- ListPluginsForListing ---- + +func TestListPluginsForListing_ExcludesDeleted(t *testing.T) { + ctx := context.Background() + client := newTestDB(t, "agentresource-plugins-listing") + repoID := seedPluginRepo(t, ctx, client) + + _ = seedPlugin(t, ctx, client, repoID, pluginSeed{name: "active", withVersion: true}) + _ = seedPlugin(t, ctx, client, repoID, pluginSeed{name: "orphan", isOrphan: true, withVersion: true}) + _ = seedPlugin(t, ctx, client, repoID, pluginSeed{name: "deleted", isDeleted: true, withVersion: true}) + + repo := NewRepo(client) + out, err := repo.ListPluginsForListing(ctx) + if err != nil { + t.Fatalf("ListPluginsForListing: %v", err) + } + names := listingNames(out) + if !equalStringSet(names, []string{"active"}) { + t.Fatalf("expected only {active}, got %v", names) + } +} + +func TestListPluginsForListing_CarriesEntry(t *testing.T) { + ctx := context.Background() + client := newTestDB(t, "agentresource-plugins-listing-entry") + repoID := seedPluginRepo(t, ctx, client) + + _ = seedPlugin(t, ctx, client, repoID, pluginSeed{name: "alpha", withVersion: true, entry: "dist/index.js"}) + + repo := NewRepo(client) + out, err := repo.ListPluginsForListing(ctx) + if err != nil { + t.Fatalf("ListPluginsForListing: %v", err) + } + if len(out) != 1 || out[0].Name != "alpha" { + t.Fatalf("expected one plugin alpha, got %+v", out) + } + if out[0].Entry != "dist/index.js" { + t.Fatalf("expected entry dist/index.js, got %q", out[0].Entry) + } +} + +// ---- helpers ---- + +func skillNames(items []*SkillWithVersion) []string { + out := make([]string, 0, len(items)) + for _, it := range items { + out = append(out, it.Name) + } + return out +} + +func listingNames(items []*ResourceListItem) []string { + out := make([]string, 0, len(items)) + for _, it := range items { + out = append(out, it.Name) + } + return out +} + +func equalStringSet(a, b []string) bool { + if len(a) != len(b) { + return false + } + set := map[string]int{} + for _, x := range a { + set[x]++ + } + for _, x := range b { + set[x]-- + if set[x] < 0 { + return false + } + } + return true +} diff --git a/backend/biz/agentresource/resolver.go b/backend/biz/agentresource/resolver.go new file mode 100644 index 00000000..fc28c27b --- /dev/null +++ b/backend/biz/agentresource/resolver.go @@ -0,0 +1,153 @@ +package agentresource + +import ( + "context" + "fmt" + "io" + "log/slog" + + "github.com/google/uuid" +) + +// ObjectStore is the minimal read-only surface the Resolver needs from an +// object store. *pkg/oss.Client implements this implicitly, but the interface +// is declared here so tests can inject in-memory fakes without pulling AWS +// SDK dependencies. +type ObjectStore interface { + GetObject(ctx context.Context, key string) (io.ReadCloser, error) +} + +// ResolverInterface is the abstract surface consumed by the task dispatch +// path. It exists so callers (notably the task usecase) can depend on a +// minimal contract and inject fakes in tests. +type ResolverInterface interface { + Rules(ctx context.Context) ([]MaterializedRule, error) + Skills(ctx context.Context, userSelectedIDs []uuid.UUID) ([]MaterializedAsset, error) + Plugins(ctx context.Context, userSelectedIDs []uuid.UUID) ([]MaterializedAsset, error) +} + +// Resolver glues the read-only Repo together with the read-only ObjectStore. +// It is the single seam used by the task dispatch path to turn DB rows + S3 +// keys into actual byte payloads. +// +// All methods are safe for concurrent use as long as the underlying Repo and +// ObjectStore implementations are; the resolver itself is stateless. +type Resolver struct { + repo Repo + objstore ObjectStore + logger *slog.Logger +} + +// NewResolver wires a Resolver. A nil logger falls back to slog.Default so +// the resolver is safe to construct without explicit wiring in tests. +func NewResolver(repo Repo, objstore ObjectStore, logger *slog.Logger) *Resolver { + if logger == nil { + logger = slog.Default() + } + return &Resolver{repo: repo, objstore: objstore, logger: logger} +} + +// Rules materializes every active rule by reading content directly from the +// shared DB (the admin BFF writes rule content into agent_rule_versions.content; +// no S3 round-trip is involved for rules). +func (r *Resolver) Rules(ctx context.Context) ([]MaterializedRule, error) { + rules, err := r.repo.ListActiveRules(ctx) + if err != nil { + return nil, fmt.Errorf("agentresource: list rules: %w", err) + } + out := make([]MaterializedRule, 0, len(rules)) + for _, ru := range rules { + out = append(out, MaterializedRule{Name: ru.Name, Content: ru.Content}) + } + return out, nil +} + +// Skills materializes the union of {userSelectedIDs} and force-delivery +// skills. Each skill's S3 object is expected to be a zip; per-skill failures +// (download, unzip, zip-bomb, zip-slip) are logged + skipped so a single bad +// skill never breaks the dispatch path. +func (r *Resolver) Skills(ctx context.Context, userSelectedIDs []uuid.UUID) ([]MaterializedAsset, error) { + skills, err := r.repo.ListActiveSkills(ctx, userSelectedIDs) + if err != nil { + return nil, fmt.Errorf("agentresource: list skills: %w", err) + } + out := make([]MaterializedAsset, 0, len(skills)) + for _, s := range skills { + body, err := r.fetch(ctx, s.S3Key) + if err != nil { + r.logger.WarnContext(ctx, "agentresource: skip skill, fetch failed", + slog.String("skill", s.Name), + slog.String("s3_key", s.S3Key), + slog.Any("err", err), + ) + continue + } + files, err := unzipToMemory(body, DefaultUnzipLimits) + if err != nil { + r.logger.WarnContext(ctx, "agentresource: skip skill, unzip failed", + slog.String("skill", s.Name), + slog.String("s3_key", s.S3Key), + slog.Any("err", err), + ) + continue + } + r.logger.InfoContext(ctx, "agentresource: skill resolved", + slog.String("skill", s.Name), + slog.String("version", s.Version), + slog.String("s3_key", s.S3Key), + slog.Int("files", len(files)), + ) + out = append(out, MaterializedAsset{Name: s.Name, Files: files}) + } + return out, nil +} + +// Plugins mirrors Skills but also carries the plugin entrypoint (already +// hoisted out of parsed_meta by the repo layer). +func (r *Resolver) Plugins(ctx context.Context, userSelectedIDs []uuid.UUID) ([]MaterializedAsset, error) { + plugins, err := r.repo.ListActivePlugins(ctx, userSelectedIDs) + if err != nil { + return nil, fmt.Errorf("agentresource: list plugins: %w", err) + } + out := make([]MaterializedAsset, 0, len(plugins)) + for _, p := range plugins { + body, err := r.fetch(ctx, p.S3Key) + if err != nil { + r.logger.WarnContext(ctx, "agentresource: skip plugin, fetch failed", + slog.String("plugin", p.Name), + slog.String("s3_key", p.S3Key), + slog.Any("err", err), + ) + continue + } + files, err := unzipToMemory(body, DefaultUnzipLimits) + if err != nil { + r.logger.WarnContext(ctx, "agentresource: skip plugin, unzip failed", + slog.String("plugin", p.Name), + slog.String("s3_key", p.S3Key), + slog.Any("err", err), + ) + continue + } + r.logger.InfoContext(ctx, "agentresource: plugin resolved", + slog.String("plugin", p.Name), + slog.String("version", p.Version), + slog.String("entry", p.Entry), + slog.String("s3_key", p.S3Key), + slog.Int("files", len(files)), + ) + out = append(out, MaterializedAsset{Name: p.Name, Entry: p.Entry, Files: files}) + } + return out, nil +} + +// fetch pulls a single object body fully into memory. The body is always +// closed before returning, even on error. +func (r *Resolver) fetch(ctx context.Context, key string) ([]byte, error) { + rc, err := r.objstore.GetObject(ctx, key) + if err != nil { + return nil, err + } + defer rc.Close() + return io.ReadAll(rc) +} diff --git a/backend/biz/agentresource/resolver_test.go b/backend/biz/agentresource/resolver_test.go new file mode 100644 index 00000000..df9c24b2 --- /dev/null +++ b/backend/biz/agentresource/resolver_test.go @@ -0,0 +1,280 @@ +package agentresource + +import ( + "bytes" + "context" + "errors" + "io" + "sort" + "sync" + "testing" + + "github.com/google/uuid" +) + +// ---- fake ObjectStore ----------------------------------------------------- + +// fakeObjectStore is a thread-safe in-memory ObjectStore. Keys mapped in +// errFor return that error; otherwise the byte slice under data is wrapped +// in an io.NopCloser. +type fakeObjectStore struct { + mu sync.Mutex + data map[string][]byte + errFor map[string]error +} + +func newFakeObjectStore() *fakeObjectStore { + return &fakeObjectStore{ + data: map[string][]byte{}, + errFor: map[string]error{}, + } +} + +func (f *fakeObjectStore) put(key string, body []byte) { + f.mu.Lock() + defer f.mu.Unlock() + f.data[key] = body +} + +func (f *fakeObjectStore) GetObject(_ context.Context, key string) (io.ReadCloser, error) { + f.mu.Lock() + defer f.mu.Unlock() + if err, ok := f.errFor[key]; ok { + return nil, err + } + body, ok := f.data[key] + if !ok { + return nil, errors.New("fake: key not found: " + key) + } + return io.NopCloser(bytes.NewReader(body)), nil +} + +// ---- fake Repo ------------------------------------------------------------ + +type fakeRepo struct { + rules []*RuleWithVersion + rulesErr error + skills []*SkillWithVersion + skillsErr error + plugins []*PluginWithVersion + pluginsErr error + lastSkillIDs []uuid.UUID + lastPlugIDs []uuid.UUID +} + +func (f *fakeRepo) ListActiveRules(_ context.Context) ([]*RuleWithVersion, error) { + return f.rules, f.rulesErr +} +func (f *fakeRepo) ListActiveSkills(_ context.Context, ids []uuid.UUID) ([]*SkillWithVersion, error) { + f.lastSkillIDs = ids + return f.skills, f.skillsErr +} +func (f *fakeRepo) ListActivePlugins(_ context.Context, ids []uuid.UUID) ([]*PluginWithVersion, error) { + f.lastPlugIDs = ids + return f.plugins, f.pluginsErr +} +func (f *fakeRepo) ListSkillsForListing(_ context.Context) ([]*ResourceListItem, error) { + return nil, nil +} +func (f *fakeRepo) ListPluginsForListing(_ context.Context) ([]*ResourceListItem, error) { + return nil, nil +} + +// ---- rules ---------------------------------------------------------------- + +func TestRules_HappyPath_TwoRules(t *testing.T) { + // Rule resolver reads content directly from the repo (DB) — no S3 fetch + // is performed, so we don't seed the fake objectstore here. + repo := &fakeRepo{rules: []*RuleWithVersion{ + {Name: "a", Content: "body-a"}, + {Name: "b", Content: "body-b"}, + }} + r := NewResolver(repo, newFakeObjectStore(), nil) + + got, err := r.Rules(context.Background()) + if err != nil { + t.Fatalf("unexpected err: %v", err) + } + if len(got) != 2 { + t.Fatalf("want 2 rules, got %d", len(got)) + } + if got[0].Name != "a" || got[0].Content != "body-a" { + t.Errorf("rule[0] = %+v", got[0]) + } + if got[1].Name != "b" || got[1].Content != "body-b" { + t.Errorf("rule[1] = %+v", got[1]) + } +} + +func TestRules_RepoErrorPropagates(t *testing.T) { + repo := &fakeRepo{rulesErr: errors.New("db down")} + r := NewResolver(repo, newFakeObjectStore(), nil) + _, err := r.Rules(context.Background()) + if err == nil { + t.Fatal("expected error") + } +} + +// ---- skills --------------------------------------------------------------- + +func TestSkills_UnzipPreservesRelPaths(t *testing.T) { + zipBytes := buildZip(t, map[string]string{ + "skill.md": "S", + "scripts/run.sh": "R", + }) + os := newFakeObjectStore() + os.put("skills/k.zip", zipBytes) + + repo := &fakeRepo{skills: []*SkillWithVersion{ + {Name: "k", S3Key: "skills/k.zip"}, + }} + r := NewResolver(repo, os, nil) + + got, err := r.Skills(context.Background(), nil) + if err != nil { + t.Fatalf("unexpected err: %v", err) + } + if len(got) != 1 || got[0].Name != "k" { + t.Fatalf("unexpected assets: %+v", got) + } + rel := map[string]string{} + for _, f := range got[0].Files { + rel[f.RelPath] = string(f.Content) + } + if rel["skill.md"] != "S" || rel["scripts/run.sh"] != "R" { + t.Errorf("relpaths = %+v", rel) + } +} + +func TestSkills_ZipBombGuard_FileTooBig_SkipsAsset(t *testing.T) { + // good skill is fine; bad skill has one entry > MaxFileSize. + good := buildZip(t, map[string]string{"ok.md": "ok"}) + + // 33 MiB of data — just over the 32 MiB default. + huge := bytes.Repeat([]byte("A"), int(DefaultUnzipLimits.MaxFileSize)+1024) + bad := buildZip(t, map[string]string{"big.bin": string(huge)}) + + os := newFakeObjectStore() + os.put("skills/good.zip", good) + os.put("skills/bad.zip", bad) + + repo := &fakeRepo{skills: []*SkillWithVersion{ + {Name: "good", S3Key: "skills/good.zip"}, + {Name: "bad", S3Key: "skills/bad.zip"}, + }} + r := NewResolver(repo, os, nil) + + got, err := r.Skills(context.Background(), nil) + if err != nil { + t.Fatalf("unexpected err: %v", err) + } + if len(got) != 1 || got[0].Name != "good" { + t.Fatalf("want only good skill, got %+v", got) + } +} + +func TestSkills_ZipSlip_Reject(t *testing.T) { + bad := buildZip(t, map[string]string{"../evil": "x"}) + good := buildZip(t, map[string]string{"a.md": "a"}) + + os := newFakeObjectStore() + os.put("skills/bad.zip", bad) + os.put("skills/good.zip", good) + + repo := &fakeRepo{skills: []*SkillWithVersion{ + {Name: "bad", S3Key: "skills/bad.zip"}, + {Name: "good", S3Key: "skills/good.zip"}, + }} + r := NewResolver(repo, os, nil) + + got, err := r.Skills(context.Background(), nil) + if err != nil { + t.Fatalf("unexpected err: %v", err) + } + if len(got) != 1 || got[0].Name != "good" { + t.Fatalf("want only good skill, got %+v", got) + } +} + +func TestSkills_UserSelectedUnion(t *testing.T) { + // Repo simulates the union itself; the resolver just needs to forward + // the IDs verbatim and materialize whatever the repo returned. + userID := uuid.New() + forceID := uuid.New() + + zipBytes := buildZip(t, map[string]string{"x.md": "x"}) + os := newFakeObjectStore() + os.put("u.zip", zipBytes) + os.put("f.zip", zipBytes) + + repo := &fakeRepo{skills: []*SkillWithVersion{ + {ID: userID, Name: "user-skill", S3Key: "u.zip"}, + {ID: forceID, Name: "force-skill", S3Key: "f.zip", IsForceDelivery: true}, + }} + r := NewResolver(repo, os, nil) + + got, err := r.Skills(context.Background(), []uuid.UUID{userID}) + if err != nil { + t.Fatalf("unexpected err: %v", err) + } + if len(got) != 2 { + t.Fatalf("want 2 skills, got %d", len(got)) + } + names := []string{got[0].Name, got[1].Name} + sort.Strings(names) + if names[0] != "force-skill" || names[1] != "user-skill" { + t.Errorf("names = %v", names) + } + if len(repo.lastSkillIDs) != 1 || repo.lastSkillIDs[0] != userID { + t.Errorf("repo received IDs = %v, want [%v]", repo.lastSkillIDs, userID) + } +} + +// ---- plugins -------------------------------------------------------------- + +func TestPlugins_EntryFieldPreserved(t *testing.T) { + zipBytes := buildZip(t, map[string]string{"main.js": "console.log(1)"}) + os := newFakeObjectStore() + os.put("plugins/p.zip", zipBytes) + + repo := &fakeRepo{plugins: []*PluginWithVersion{ + {Name: "p", S3Key: "plugins/p.zip", Entry: "main.js"}, + }} + r := NewResolver(repo, os, nil) + + got, err := r.Plugins(context.Background(), nil) + if err != nil { + t.Fatalf("unexpected err: %v", err) + } + if len(got) != 1 { + t.Fatalf("want 1 plugin, got %d", len(got)) + } + if got[0].Entry != "main.js" { + t.Errorf("entry = %q", got[0].Entry) + } + if len(got[0].Files) != 1 || got[0].Files[0].RelPath != "main.js" { + t.Errorf("files = %+v", got[0].Files) + } +} + +func TestPlugins_EmptyIDs_OnlyForce(t *testing.T) { + zipBytes := buildZip(t, map[string]string{"m.js": "x"}) + os := newFakeObjectStore() + os.put("only.zip", zipBytes) + + repo := &fakeRepo{plugins: []*PluginWithVersion{ + {Name: "force-only", S3Key: "only.zip", IsForceDelivery: true, Entry: "m.js"}, + }} + r := NewResolver(repo, os, nil) + + got, err := r.Plugins(context.Background(), nil) + if err != nil { + t.Fatalf("unexpected err: %v", err) + } + if len(got) != 1 || got[0].Name != "force-only" { + t.Fatalf("got %+v", got) + } + if len(repo.lastPlugIDs) != 0 { + t.Errorf("repo received IDs = %v, want empty", repo.lastPlugIDs) + } +} diff --git a/backend/biz/agentresource/types.go b/backend/biz/agentresource/types.go new file mode 100644 index 00000000..f8eafb95 --- /dev/null +++ b/backend/biz/agentresource/types.go @@ -0,0 +1,97 @@ +// Package agentresource exposes read-only repository helpers for the agent +// rule / skill / plugin resources consumed by the task dispatch path. +// +// The package is intentionally narrow: it only surfaces the data needed by +// (a) the task usecase when assembling getCodingConfigs, and (b) the public +// list endpoints under /api/v1/skills + /api/v1/plugins. Mutations live in +// the admin BFF, not here. +package agentresource + +import ( + "time" + + "github.com/google/uuid" + + enttypes "github.com/chaitin/MonkeyCode/backend/ent/types" +) + +// RuleWithVersion is an agent rule joined with the row referenced by its +// active_version_id. Rule content is sourced directly from the +// agent_rule_versions.content column — there is no S3 indirection for rules +// (unlike skill / plugin which still go through S3-backed zip artifacts). +type RuleWithVersion struct { + ID uuid.UUID + Name string + Version string + Content string + UpdatedAt time.Time +} + +// SkillWithVersion is an agent skill joined with the row referenced by its +// active_version_id. Orphaned skills (is_orphan=true) are kept on purpose +// so that previously active versions remain deliverable until the operator +// explicitly deletes them. +type SkillWithVersion struct { + ID uuid.UUID + Name string + Description string + Version string + S3Key string + IsForceDelivery bool + IsOrphan bool + ParsedMeta enttypes.SkillParsedMeta + UpdatedAt time.Time +} + +// PluginWithVersion mirrors SkillWithVersion but for plugins. The Entry +// field is hoisted out of parsed_meta because the task dispatch path needs +// it as a flat string. +type PluginWithVersion struct { + ID uuid.UUID + Name string + Description string + Version string + S3Key string + IsForceDelivery bool + IsOrphan bool + Entry string + UpdatedAt time.Time +} + +// ResourceListItem is the lightweight projection returned to the public +// listing endpoints (skills / plugins). It deliberately omits S3 keys and +// orphan markers because those are dispatch-time concerns. +// +// Entry is only meaningful for plugins (taken from parsed_meta.entry) so +// the picker UI can preview where the plugin will be mounted; it is left +// empty for skills. +type ResourceListItem struct { + ID uuid.UUID + Name string + Description string + Version string + IsForceDelivery bool + Entry string +} + +// MaterializedRule is a fully fetched rule body, ready to be embedded into +// the getCodingConfigs response. +type MaterializedRule struct { + Name string + Content string +} + +// MaterializedFile is one entry inside an unzipped skill or plugin asset. +// RelPath is the path inside the archive (e.g. "skill.md", "scripts/run.sh"). +type MaterializedFile struct { + RelPath string + Content []byte +} + +// MaterializedAsset is a skill or plugin after S3 fetch + in-memory unzip. +// Entry is only populated for plugins (it is taken from parsed_meta.entry). +type MaterializedAsset struct { + Name string + Entry string + Files []MaterializedFile +} diff --git a/backend/biz/agentresource/unpack.go b/backend/biz/agentresource/unpack.go new file mode 100644 index 00000000..c611837c --- /dev/null +++ b/backend/biz/agentresource/unpack.go @@ -0,0 +1,127 @@ +package agentresource + +import ( + "archive/zip" + "bytes" + "fmt" + "io" + "path" + "strings" +) + +// UnzipLimits guards the in-memory unzipper against zip bombs and overly +// large archives. All limits are inclusive of the value (size == limit is OK). +type UnzipLimits struct { + MaxFileSize int64 // per-entry uncompressed size + MaxTotalSize int64 // sum of all entries' uncompressed sizes + MaxFiles int // max number of file entries +} + +// DefaultUnzipLimits is the policy used by the Resolver. +var DefaultUnzipLimits = UnzipLimits{ + MaxFileSize: 32 << 20, // 32 MiB + MaxTotalSize: 256 << 20, // 256 MiB + MaxFiles: 1000, +} + +// unzipToMemory reads a zip archive entirely from memory and returns its +// regular file entries. Directories are skipped. Paths are validated to +// reject zip-slip ("../..") and absolute paths. Entries that exceed the +// limits cause the entire archive to be rejected so callers can fall back +// to skipping the whole asset (matching the Resolver's per-skill policy). +func unzipToMemory(data []byte, limits UnzipLimits) ([]MaterializedFile, error) { + zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data))) + if err != nil { + return nil, fmt.Errorf("agentresource: open zip: %w", err) + } + + // Pre-flight file count + declared uncompressed size. + fileCount := 0 + var totalDeclared uint64 + for _, f := range zr.File { + if f.FileInfo().IsDir() { + continue + } + fileCount++ + totalDeclared += f.UncompressedSize64 + } + if fileCount > limits.MaxFiles { + return nil, fmt.Errorf("agentresource: zip has %d files, max %d", fileCount, limits.MaxFiles) + } + if totalDeclared > uint64(limits.MaxTotalSize) { + return nil, fmt.Errorf("agentresource: zip declares %d bytes total, max %d", totalDeclared, limits.MaxTotalSize) + } + + out := make([]MaterializedFile, 0, fileCount) + var totalRead int64 + for _, f := range zr.File { + if f.FileInfo().IsDir() { + continue + } + + rel, err := sanitizeZipPath(f.Name) + if err != nil { + return nil, err + } + + // Trust-but-verify: even if UncompressedSize64 looks fine, cap + // per-entry reads to MaxFileSize via io.LimitReader. + if int64(f.UncompressedSize64) > limits.MaxFileSize { + return nil, fmt.Errorf("agentresource: zip entry %q declares %d bytes, max %d", + f.Name, f.UncompressedSize64, limits.MaxFileSize) + } + + rc, err := f.Open() + if err != nil { + return nil, fmt.Errorf("agentresource: open zip entry %q: %w", f.Name, err) + } + // limit + 1 so a file exactly at the limit reads cleanly but anything + // larger trips the over-cap check below. + limited := io.LimitReader(rc, limits.MaxFileSize+1) + buf, err := io.ReadAll(limited) + _ = rc.Close() + if err != nil { + return nil, fmt.Errorf("agentresource: read zip entry %q: %w", f.Name, err) + } + if int64(len(buf)) > limits.MaxFileSize { + return nil, fmt.Errorf("agentresource: zip entry %q exceeds per-file limit %d", + f.Name, limits.MaxFileSize) + } + totalRead += int64(len(buf)) + if totalRead > limits.MaxTotalSize { + return nil, fmt.Errorf("agentresource: zip exceeds total limit %d after entry %q", + limits.MaxTotalSize, f.Name) + } + + out = append(out, MaterializedFile{RelPath: rel, Content: buf}) + } + return out, nil +} + +// sanitizeZipPath rejects entries that try to escape the archive root via +// "..", absolute paths, or backslash separators. Forward-slash separators +// are preserved as-is so callers can write them out as relative paths. +func sanitizeZipPath(name string) (string, error) { + if name == "" { + return "", fmt.Errorf("agentresource: empty zip entry name") + } + // Reject Windows-style separators outright — Skill/Plugin packagers + // must use POSIX paths. + if strings.Contains(name, `\`) { + return "", fmt.Errorf("agentresource: zip entry %q uses backslash separator", name) + } + // Reject absolute paths. + if strings.HasPrefix(name, "/") { + return "", fmt.Errorf("agentresource: zip entry %q is absolute", name) + } + // path.Clean collapses ".." segments; if the result starts with ".." + // or equals "..", it tried to escape. + cleaned := path.Clean(name) + if cleaned == ".." || strings.HasPrefix(cleaned, "../") { + return "", fmt.Errorf("agentresource: zip-slip rejected for entry %q", name) + } + if cleaned == "." { + return "", fmt.Errorf("agentresource: zip entry %q resolves to root", name) + } + return cleaned, nil +} diff --git a/backend/biz/agentresource/unpack_test.go b/backend/biz/agentresource/unpack_test.go new file mode 100644 index 00000000..bf55f5ee --- /dev/null +++ b/backend/biz/agentresource/unpack_test.go @@ -0,0 +1,134 @@ +package agentresource + +import ( + "archive/zip" + "bytes" + "strings" + "testing" +) + +// buildZip is a tiny helper that produces an in-memory zip with the given +// entries. Used by both unpack_test.go and resolver_test.go. +func buildZip(t *testing.T, entries map[string]string) []byte { + t.Helper() + var buf bytes.Buffer + zw := zip.NewWriter(&buf) + for name, content := range entries { + w, err := zw.Create(name) + if err != nil { + t.Fatalf("zip create %s: %v", name, err) + } + if _, err := w.Write([]byte(content)); err != nil { + t.Fatalf("zip write %s: %v", name, err) + } + } + if err := zw.Close(); err != nil { + t.Fatalf("zip close: %v", err) + } + return buf.Bytes() +} + +func TestUnzipToMemory_HappyPath(t *testing.T) { + data := buildZip(t, map[string]string{ + "skill.md": "# hello", + "scripts/run.sh": "#!/bin/sh", + "docs/notes.txt": "n", + }) + files, err := unzipToMemory(data, DefaultUnzipLimits) + if err != nil { + t.Fatalf("unexpected err: %v", err) + } + if len(files) != 3 { + t.Fatalf("want 3 files, got %d", len(files)) + } + got := map[string]string{} + for _, f := range files { + got[f.RelPath] = string(f.Content) + } + if got["skill.md"] != "# hello" { + t.Errorf("skill.md content = %q", got["skill.md"]) + } + if got["scripts/run.sh"] != "#!/bin/sh" { + t.Errorf("scripts/run.sh content = %q", got["scripts/run.sh"]) + } +} + +func TestUnzipToMemory_RejectsZipSlip(t *testing.T) { + data := buildZip(t, map[string]string{ + "../evil.sh": "rm -rf /", + }) + _, err := unzipToMemory(data, DefaultUnzipLimits) + if err == nil { + t.Fatal("expected zip-slip rejection, got nil") + } + if !strings.Contains(err.Error(), "zip-slip") { + t.Errorf("err = %v, want zip-slip", err) + } +} + +func TestUnzipToMemory_RejectsAbsolutePath(t *testing.T) { + data := buildZip(t, map[string]string{ + "/etc/passwd": "x", + }) + _, err := unzipToMemory(data, DefaultUnzipLimits) + if err == nil { + t.Fatal("expected absolute-path rejection") + } +} + +func TestUnzipToMemory_FileTooBig(t *testing.T) { + big := strings.Repeat("A", 100) + data := buildZip(t, map[string]string{"a.txt": big}) + limits := UnzipLimits{MaxFileSize: 10, MaxTotalSize: 1000, MaxFiles: 10} + _, err := unzipToMemory(data, limits) + if err == nil { + t.Fatal("expected per-file limit rejection") + } +} + +func TestUnzipToMemory_TooManyFiles(t *testing.T) { + entries := map[string]string{} + for i := 0; i < 5; i++ { + entries[string(rune('a'+i))+".txt"] = "x" + } + data := buildZip(t, entries) + limits := UnzipLimits{MaxFileSize: 1000, MaxTotalSize: 1000, MaxFiles: 3} + _, err := unzipToMemory(data, limits) + if err == nil { + t.Fatal("expected file-count rejection") + } +} + +func TestUnzipToMemory_SkipsDirectories(t *testing.T) { + // Use a raw zip writer to add an explicit directory entry, which the + // helper map can't easily represent. + var buf bytes.Buffer + zw := zip.NewWriter(&buf) + if _, err := zw.Create("subdir/"); err != nil { + t.Fatalf("create dir: %v", err) + } + w, err := zw.Create("subdir/file.txt") + if err != nil { + t.Fatalf("create file: %v", err) + } + _, _ = w.Write([]byte("ok")) + _ = zw.Close() + + files, err := unzipToMemory(buf.Bytes(), DefaultUnzipLimits) + if err != nil { + t.Fatalf("unexpected err: %v", err) + } + if len(files) != 1 || files[0].RelPath != "subdir/file.txt" { + t.Fatalf("unexpected files: %+v", files) + } +} + +func TestUnzipToMemory_RejectsBackslash(t *testing.T) { + data := buildZip(t, map[string]string{ + `win\path.txt`: "x", + }) + _, err := unzipToMemory(data, DefaultUnzipLimits) + if err == nil { + t.Fatal("expected backslash rejection") + } +} From 4fa062b36078971dfb2e2916bd31ab3c2d30da4c Mon Sep 17 00:00:00 2001 From: xmv97 Date: Fri, 5 Jun 2026 17:29:26 +0800 Subject: [PATCH 05/11] feat(task): inject rule/skill/plugin from agentresource + DB-sourced /api/v1/skills + /api/v1/plugins MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - task usecase: getCodingConfigs 改签名为 (ctx, cli, m, skillIDs, pluginIDs), 接入 agentresource.ResolverInterface,按 spec §6.3 注入 rule(三 CLI)/ skill (三 CLI、resolver 并集 force_delivery)/ plugin(仅 OpenCode、注入 opencode.json plugin 数组);resolver==nil 时 nil-safe 跳过供单元测试 - 删除老 /app/skills 文件系统 walk + consts.SkillBaseDir 常量 - 新增 /api/v1/skills(biz/skill)和 /api/v1/plugins(biz/plugin)handler, 从 agentresource.Repo.ListSkillsForListing / ListPluginsForListing 读 DB - 新增 domain.SkillListItem / PluginListItem DTO - biz/agentresource/register.go 落 DI(Repo / *oss.Client / ResolverInterface), ObjectStorage 关闭时降级到 noopObjectStore;object_storage 未启用时 回退到 aliyun.public_oss 配置块 - biz/register.go 接线 agentresource / skill / plugin Provide+Invoke - task handler: 非 uuid 的 skill/plugin id 记日志后跳过,不再整任务 reject - 单元测试适配新签名(ctx + pluginIDs),resolver nil-safe 路径无需 fake --- backend/biz/agentresource/noop_objectstore.go | 17 ++ backend/biz/agentresource/register.go | 81 ++++++++ backend/biz/plugin/handler/v1/plugin.go | 65 +++++++ backend/biz/plugin/register.go | 15 ++ backend/biz/register.go | 8 + backend/biz/skill/handler/v1/skill.go | 64 ++++++ backend/biz/skill/register.go | 15 ++ backend/biz/task/handler/v1/task.go | 31 +-- backend/biz/task/usecase/task.go | 182 +++++++++++++++--- .../task/usecase/task_model_config_test.go | 13 +- backend/config/config.go | 29 +++ backend/consts/task.go | 3 - backend/domain/plugin.go | 11 ++ backend/domain/skill.go | 11 ++ 14 files changed, 478 insertions(+), 67 deletions(-) create mode 100644 backend/biz/agentresource/noop_objectstore.go create mode 100644 backend/biz/agentresource/register.go create mode 100644 backend/biz/plugin/handler/v1/plugin.go create mode 100644 backend/biz/plugin/register.go create mode 100644 backend/biz/skill/handler/v1/skill.go create mode 100644 backend/biz/skill/register.go create mode 100644 backend/domain/plugin.go create mode 100644 backend/domain/skill.go diff --git a/backend/biz/agentresource/noop_objectstore.go b/backend/biz/agentresource/noop_objectstore.go new file mode 100644 index 00000000..e0448309 --- /dev/null +++ b/backend/biz/agentresource/noop_objectstore.go @@ -0,0 +1,17 @@ +package agentresource + +import ( + "context" + "fmt" + "io" +) + +// noopObjectStore is used when ObjectStorage is disabled in config. Every +// fetch fails with a stable sentinel-ish error so resolver-level warn logs +// stay informative ("skill skipped: object storage disabled") rather than +// crashing with a nil deref. +type noopObjectStore struct{} + +func (noopObjectStore) GetObject(_ context.Context, _ string) (io.ReadCloser, error) { + return nil, fmt.Errorf("object storage disabled") +} diff --git a/backend/biz/agentresource/register.go b/backend/biz/agentresource/register.go new file mode 100644 index 00000000..7660a674 --- /dev/null +++ b/backend/biz/agentresource/register.go @@ -0,0 +1,81 @@ +// Package agentresource — DI wiring for the agent-resource read-only stack. +// +// The Repo / Resolver pair is consumed by: +// - biz/task/usecase (rule + skill + plugin injection into ConfigFile slice) +// - biz/skill/handler/v1 (/api/v1/skills picker) +// - biz/plugin/handler/v1 (/api/v1/plugins picker) +package agentresource + +import ( + "context" + "log/slog" + + "github.com/samber/do" + + "github.com/chaitin/MonkeyCode/backend/config" + "github.com/chaitin/MonkeyCode/backend/db" + "github.com/chaitin/MonkeyCode/backend/pkg/oss" +) + +// ProvideAgentResource 注册 agentresource 模块。oss.Client 仅在 ObjectStorage +// 已启用时构造;未启用时 Resolver 会拿到 nil ObjectStore,调用 Skills/Plugins +// 时各自返回的 fetch 错误会被 resolver 内部 warn-and-skip 掉,dispatch 不会失败。 +func ProvideAgentResource(i *do.Injector) { + do.Provide(i, func(i *do.Injector) (Repo, error) { + return NewRepo(do.MustInvoke[*db.Client](i)), nil + }) + + do.Provide(i, func(i *do.Injector) (*oss.Client, error) { + cfg := do.MustInvoke[*config.Config](i) + logger := do.MustInvoke[*slog.Logger](i) + + // Primary: ObjectStorage block (shared with avatar/repo/spec/temp). + if cfg.ObjectStorage.Enabled { + opt := oss.S3Option{ + ForcePathStyle: cfg.ObjectStorage.ForcePathStyle, + InitBucket: cfg.ObjectStorage.InitBucket, + } + return oss.NewS3Compatible(context.Background(), cfg.ObjectStorage, opt) + } + + // Fallback: aliyun.public_oss block — same shape mcai-backend + + // admin-new use. Lets ops paste a single OSS block into all three + // deploys rather than duplicating credentials. + if pub := cfg.Aliyun.PublicOSS; pub.Bucket != "" && pub.Endpoint != "" { + logger.Info("agentresource: ObjectStorage disabled, falling back to aliyun.public_oss", + "endpoint", pub.Endpoint, "bucket", pub.Bucket) + return oss.NewS3Compatible(context.Background(), config.ObjectStorageConfig{ + Enabled: true, + Endpoint: pub.Endpoint, + AccessEndpoint: pub.AccessEndpoint, + AccessKey: pub.AccessKey, + AccessKeySecret: pub.AccessKeySecret, + Bucket: pub.Bucket, + Region: pub.Region, + // Aliyun OSS uses virtual-hosted style; not path style. + ForcePathStyle: false, + MaxSize: pub.MaxSize, + }, oss.S3Option{}) + } + + // Neither block configured — Resolver will downgrade to noopObjectStore. + return nil, nil + }) + + do.Provide(i, func(i *do.Injector) (ResolverInterface, error) { + repo := do.MustInvoke[Repo](i) + client, _ := do.Invoke[*oss.Client](i) + logger := do.MustInvoke[*slog.Logger](i) + // *oss.Client 隐式实现 ObjectStore(有 GetObject(ctx, key) 方法)。 + // 当 client==nil 时 wrap 一个 nil store 即可;resolver fetch 时会 + // 走到 nil-deref 之前已被外层 err 捕获——但为避免 panic,统一在这 + // 里把 nil 显式包成 noopObjectStore。 + var store ObjectStore + if client != nil { + store = client + } else { + store = noopObjectStore{} + } + return NewResolver(repo, store, logger), nil + }) +} diff --git a/backend/biz/plugin/handler/v1/plugin.go b/backend/biz/plugin/handler/v1/plugin.go new file mode 100644 index 00000000..1fc07eb4 --- /dev/null +++ b/backend/biz/plugin/handler/v1/plugin.go @@ -0,0 +1,65 @@ +// Package v1 暴露 /api/v1/plugins 端点,从 agentresource.Repo 读 DB。仅 +// OpenCode CLI 会真正下发 plugin 资产,但列表端点对所有任务创建器可见。 +package v1 + +import ( + "log/slog" + + "github.com/GoYoko/web" + "github.com/samber/do" + + "github.com/chaitin/MonkeyCode/backend/biz/agentresource" + "github.com/chaitin/MonkeyCode/backend/domain" + "github.com/chaitin/MonkeyCode/backend/middleware" +) + +// PluginHandler plugin 列表处理器 +type PluginHandler struct { + repo agentresource.Repo + logger *slog.Logger +} + +// NewPluginHandler 创建 plugin handler +func NewPluginHandler(i *do.Injector) (*PluginHandler, error) { + w := do.MustInvoke[*web.Web](i) + repo := do.MustInvoke[agentresource.Repo](i) + auth := do.MustInvoke[*middleware.AuthMiddleware](i) + targetActive := do.MustInvoke[*middleware.TargetActiveMiddleware](i) + logger := do.MustInvoke[*slog.Logger](i).With("handler", "plugin.handler") + + h := &PluginHandler{repo: repo, logger: logger} + g := w.Group("/api/v1/plugins") + g.Use(auth.Auth(), targetActive.TargetActive()) + g.GET("", web.BaseHandler(h.ListEnabled)) + return h, nil +} + +// ListEnabled 获取已启用的 Plugins 列表 +// +// @Summary 获取已启用的 Plugins 列表 +// @Description 获取所有未删除、非孤儿且具备 active_version 的 Plugins,供任务创建器选用(仅 OpenCode 真正下发) +// @Tags 【公共】plugin +// @Security MonkeyCodeAIAuth +// @Accept json +// @Produce json +// @Success 200 {object} web.Resp{data=[]domain.PluginListItem} "获取成功" +// @Failure 500 {object} web.Resp "服务器内部错误" +// @Router /api/v1/plugins [get] +func (h *PluginHandler) ListEnabled(c *web.Context) error { + items, err := h.repo.ListPluginsForListing(c.Request().Context()) + if err != nil { + return err + } + resp := make([]*domain.PluginListItem, 0, len(items)) + for _, it := range items { + resp = append(resp, &domain.PluginListItem{ + ID: it.ID.String(), + Name: it.Name, + Description: it.Description, + Entry: it.Entry, + ActiveVersion: it.Version, + IsForceDelivery: it.IsForceDelivery, + }) + } + return c.Success(resp) +} diff --git a/backend/biz/plugin/register.go b/backend/biz/plugin/register.go new file mode 100644 index 00000000..279b57db --- /dev/null +++ b/backend/biz/plugin/register.go @@ -0,0 +1,15 @@ +package plugin + +import ( + "github.com/samber/do" + + v1 "github.com/chaitin/MonkeyCode/backend/biz/plugin/handler/v1" +) + +func ProvidePlugin(i *do.Injector) { + do.Provide(i, v1.NewPluginHandler) +} + +func InvokePlugin(i *do.Injector) { + do.MustInvoke[*v1.PluginHandler](i) +} diff --git a/backend/biz/register.go b/backend/biz/register.go index 62222b2b..2adfaf8f 100644 --- a/backend/biz/register.go +++ b/backend/biz/register.go @@ -6,14 +6,17 @@ import ( "github.com/google/uuid" "github.com/samber/do" + "github.com/chaitin/MonkeyCode/backend/biz/agentresource" "github.com/chaitin/MonkeyCode/backend/biz/file" "github.com/chaitin/MonkeyCode/backend/biz/git" "github.com/chaitin/MonkeyCode/backend/biz/host" "github.com/chaitin/MonkeyCode/backend/biz/llmproxy" "github.com/chaitin/MonkeyCode/backend/biz/notify" + "github.com/chaitin/MonkeyCode/backend/biz/plugin" "github.com/chaitin/MonkeyCode/backend/biz/project" "github.com/chaitin/MonkeyCode/backend/biz/public" "github.com/chaitin/MonkeyCode/backend/biz/setting" + "github.com/chaitin/MonkeyCode/backend/biz/skill" "github.com/chaitin/MonkeyCode/backend/biz/static" "github.com/chaitin/MonkeyCode/backend/biz/subscription" "github.com/chaitin/MonkeyCode/backend/biz/task" @@ -34,11 +37,14 @@ func RegisterAll(i *do.Injector) error { setting.ProvideSetting(i) team.ProvideTeam(i) host.ProvideHost(i) + agentresource.ProvideAgentResource(i) task.ProvideTask(i) git.ProvideGit(i) project.ProvideProject(i) file.ProvideFile(i) vmidle.ProvideVMIdle(i) + skill.ProvideSkill(i) + plugin.ProvidePlugin(i) return nil } @@ -54,6 +60,8 @@ func InvokeAll(i *do.Injector) { project.InvokeProject(i) file.InvokeFile(i) vmidle.InvokeVMIdle(i) + skill.InvokeSkill(i) + plugin.InvokePlugin(i) } // RegisterOpenSource 注册仅在开源项目中使用的模块 diff --git a/backend/biz/skill/handler/v1/skill.go b/backend/biz/skill/handler/v1/skill.go new file mode 100644 index 00000000..ab45b9ef --- /dev/null +++ b/backend/biz/skill/handler/v1/skill.go @@ -0,0 +1,64 @@ +// Package v1 暴露 /api/v1/skills 端点,从 agentresource.Repo 读 DB(agent_skills +// + agent_skill_versions),不再扫描 /app/skills 文件系统。 +package v1 + +import ( + "log/slog" + + "github.com/GoYoko/web" + "github.com/samber/do" + + "github.com/chaitin/MonkeyCode/backend/biz/agentresource" + "github.com/chaitin/MonkeyCode/backend/domain" + "github.com/chaitin/MonkeyCode/backend/middleware" +) + +// SkillHandler skill 列表处理器 +type SkillHandler struct { + repo agentresource.Repo + logger *slog.Logger +} + +// NewSkillHandler 创建 skill handler +func NewSkillHandler(i *do.Injector) (*SkillHandler, error) { + w := do.MustInvoke[*web.Web](i) + repo := do.MustInvoke[agentresource.Repo](i) + auth := do.MustInvoke[*middleware.AuthMiddleware](i) + targetActive := do.MustInvoke[*middleware.TargetActiveMiddleware](i) + logger := do.MustInvoke[*slog.Logger](i).With("handler", "skill.handler") + + h := &SkillHandler{repo: repo, logger: logger} + g := w.Group("/api/v1/skills") + g.Use(auth.Auth(), targetActive.TargetActive()) + g.GET("", web.BaseHandler(h.ListEnabled)) + return h, nil +} + +// ListEnabled 获取已启用的 Skills 列表 +// +// @Summary 获取已启用的 Skills 列表 +// @Description 获取所有未删除、非孤儿且具备 active_version 的 Skills,供任务创建器选用 +// @Tags 【公共】skill +// @Security MonkeyCodeAIAuth +// @Accept json +// @Produce json +// @Success 200 {object} web.Resp{data=[]domain.SkillListItem} "获取成功" +// @Failure 500 {object} web.Resp "服务器内部错误" +// @Router /api/v1/skills [get] +func (h *SkillHandler) ListEnabled(c *web.Context) error { + items, err := h.repo.ListSkillsForListing(c.Request().Context()) + if err != nil { + return err + } + resp := make([]*domain.SkillListItem, 0, len(items)) + for _, it := range items { + resp = append(resp, &domain.SkillListItem{ + ID: it.ID.String(), + Name: it.Name, + Description: it.Description, + ActiveVersion: it.Version, + IsForceDelivery: it.IsForceDelivery, + }) + } + return c.Success(resp) +} diff --git a/backend/biz/skill/register.go b/backend/biz/skill/register.go new file mode 100644 index 00000000..76383432 --- /dev/null +++ b/backend/biz/skill/register.go @@ -0,0 +1,15 @@ +package skill + +import ( + "github.com/samber/do" + + v1 "github.com/chaitin/MonkeyCode/backend/biz/skill/handler/v1" +) + +func ProvideSkill(i *do.Injector) { + do.Provide(i, v1.NewSkillHandler) +} + +func InvokeSkill(i *do.Injector) { + do.MustInvoke[*v1.SkillHandler](i) +} diff --git a/backend/biz/task/handler/v1/task.go b/backend/biz/task/handler/v1/task.go index 8983358d..0d3921c1 100644 --- a/backend/biz/task/handler/v1/task.go +++ b/backend/biz/task/handler/v1/task.go @@ -6,9 +6,6 @@ import ( "errors" "fmt" "log/slog" - "os" - "path/filepath" - "strings" "time" "github.com/GoYoko/web" @@ -40,8 +37,8 @@ type TaskHandler struct { logger *slog.Logger taskflow taskflow.Clienter tasklog *tasklog.Gateway - nls *nls.NLS // 一段录音的 POST 接口 (SpeechToText) 仍走阿里云 NLS - asr asr.Transcriber // 流式 WS 接口 (SpeechToTextStream) 走豆包等中性 ASR + nls *nls.NLS // 一段录音的 POST 接口 (SpeechToText) 仍走阿里云 NLS + asr asr.Transcriber // 流式 WS 接口 (SpeechToTextStream) 走豆包等中性 ASR taskConns *ws.TaskConn controlConns *ws.ControlConn taskSummary *service.TaskSummaryService @@ -257,12 +254,8 @@ func (h *TaskHandler) Info(c *web.Context, req domain.IDReq[uuid.UUID]) error { func (h *TaskHandler) Create(c *web.Context, req domain.CreateTaskReq) error { user := middleware.GetUser(c) - // 校验 skill_ids - for _, skillID := range req.Extra.SkillIDs { - if err := validateSkillID(skillID); err != nil { - return errcode.ErrBadRequest.Wrap(err) - } - } + // skill_ids / plugin_ids 的 UUID 校验放到 usecase 层做,单条非法时跳过 + // 该 ID 并打 WARN 日志,避免脏数据把整个任务创建打挂。 // 公共主机处理 if req.HostID == consts.PUBLIC_HOST_ID { @@ -830,19 +823,3 @@ func (h *TaskHandler) ping( } } -// validateSkillID 验证 skillID 是否安全,防止路径遍历攻击 -func validateSkillID(skillID string) error { - if skillID == "" { - return fmt.Errorf("skill id cannot be empty") - } - cleanID := filepath.Clean(skillID) - if strings.Contains(cleanID, "..") || strings.HasPrefix(cleanID, "/") { - return fmt.Errorf("invalid skill id") - } - skilldir := filepath.Join(consts.SkillBaseDir, cleanID) - if !strings.HasPrefix(skilldir, consts.SkillBaseDir+string(os.PathSeparator)) { - return fmt.Errorf("skill path escape") - } - return nil -} - diff --git a/backend/biz/task/usecase/task.go b/backend/biz/task/usecase/task.go index f56be27d..8dbdae64 100644 --- a/backend/biz/task/usecase/task.go +++ b/backend/biz/task/usecase/task.go @@ -7,7 +7,6 @@ import ( "encoding/json" "fmt" "log/slog" - "os" "path/filepath" "strings" "text/template" @@ -18,6 +17,7 @@ import ( "github.com/redis/go-redis/v9" "github.com/samber/do" + "github.com/chaitin/MonkeyCode/backend/biz/agentresource" gituc "github.com/chaitin/MonkeyCode/backend/biz/git/usecase" "github.com/chaitin/MonkeyCode/backend/biz/task/service" vmidle "github.com/chaitin/MonkeyCode/backend/biz/vmidle/usecase" @@ -58,6 +58,7 @@ type TaskUsecase struct { projectRepo domain.ProjectRepo taskActivityRefresher service.TaskActivityRefresher idleRefresher vmidle.VMIdleRefresher + resolver agentresource.ResolverInterface } // NewTaskUsecase 创建任务业务逻辑实例 @@ -80,6 +81,12 @@ func NewTaskUsecase(i *do.Injector) (domain.TaskUsecase, error) { idleRefresher: do.MustInvoke[vmidle.VMIdleRefresher](i), } + // agentresource.ResolverInterface 注入失败时降级为 nil — getCodingConfigs + // 内部 nil-check,跳过 rule/skill/plugin 注入,并打 warn 日志。 + if r, err := do.Invoke[agentresource.ResolverInterface](i); err == nil { + u.resolver = r + } + // 可选注入 TaskHook if hook, err := do.Invoke[domain.TaskHook](i); err == nil { u.taskHook = hook @@ -162,7 +169,7 @@ func (a *TaskUsecase) SwitchModel(ctx context.Context, user *domain.User, taskID } } - coding, configs, err := a.getCodingConfigs(t.CliName, model, nil) + coding, configs, err := a.getCodingConfigs(ctx, t.CliName, model, nil, nil) if err != nil { return nil, err } @@ -513,7 +520,7 @@ func (a *TaskUsecase) Create(ctx context.Context, user *domain.User, req domain. token = keys[0].APIKey } - coding, configs, err := a.getCodingConfigs(req.CliName, m, req.Extra.SkillIDs) + coding, configs, err := a.getCodingConfigs(ctx, req.CliName, m, req.Extra.SkillIDs, req.Extra.PluginIDs) if err != nil { return nil, err } @@ -549,7 +556,22 @@ func (a *TaskUsecase) Create(ctx context.Context, user *domain.User, req domain. mcps := a.buildMCPConfigs(t.ID, token) - // 存储 CreateTaskReq 到 Redis,供 Lifecycle Manager 消费 + // DEBUG: 把准备透传给 taskflow → codingmatrix 的 ConfigFile 全量打日志 + // (含原始 content),仅在 DEBUG 级别开启,生产无噪声。 + if a.logger.Enabled(ctx, slog.LevelDebug) { + for i, cf := range configs { + a.logger.DebugContext(ctx, "tasker config file", + slog.String("task_id", t.ID.String()), + slog.Int("idx", i), + slog.Int("total", len(configs)), + slog.String("path", cf.Path), + slog.Int("size", len(cf.Content)), + slog.String("content", cf.Content), + ) + } + } + + // 存储 CreateTaskReq 到 Redis(10 分钟过期),供 Lifecycle Manager 消费 createTaskReq := &taskflow.CreateTaskReq{ ID: t.ID, VMID: vm.ID, @@ -696,7 +718,66 @@ func modelRuntimeDefaults(m *db.Model) (thinking bool, contextLimit int, outputL return thinking, contextLimit, outputLimit } -func (a *TaskUsecase) getCodingConfigs(cli consts.CliName, m *db.Model, skillIDs []string) (taskflow.CodingAgent, []taskflow.ConfigFile, error) { +// agentRuleBaseDir / agentSkillBaseDir / agentPluginBaseDir 是 codingmatrix 在 +// VM 内部约定的 .ai-ready/ 投放路径。rule 走 .md 平铺;skill / plugin 解 zip +// 后按目录结构展开;plugin 的 entry 字段再以 file:// 注入到 opencode.json 的 +// `plugin` 数组里。Claude / Codex 不消费 plugin(spec §6.3)。 +const ( + agentRuleBaseDir = "/tmp/codingmatrix-project-tpl/.ai-ready/rules/" + agentSkillBaseDir = "/tmp/codingmatrix-project-tpl/.ai-ready/skills/" + agentPluginBaseDir = "/tmp/codingmatrix-project-tpl/.ai-ready/plugins/" +) + +// parseStringUUIDs 把字符串切片解析成 uuid.UUID 切片。单条解析失败时打一条 +// WARN 日志后跳过,避免一个脏 ID 把整个 task 创建打挂(resolver 内部对 +// per-resource fetch 失败也是 skip-and-log 的策略,这里保持一致)。 +// +// kind 用来在日志里区分是 skill_ids 还是 plugin_ids。 +func (a *TaskUsecase) parseStringUUIDs(ctx context.Context, kind string, raw []string) []uuid.UUID { + if len(raw) == 0 { + return nil + } + out := make([]uuid.UUID, 0, len(raw)) + for _, s := range raw { + trimmed := strings.TrimSpace(s) + id, err := uuid.Parse(trimmed) + if err != nil { + a.logger.WarnContext(ctx, "getCodingConfigs: skip invalid uuid", + slog.String("kind", kind), + slog.String("value", s), + slog.Any("err", err)) + continue + } + out = append(out, id) + } + return out +} + +// injectOpenCodePlugins 重写 cfs 中 path==opencodePath 的那个 ConfigFile, +// 把 file:// URL 列表注入到 JSON 的 `plugin` 数组。opencode.json 模板里 +// 没有 plugin 字段是有意为之(plugin 列表是运行时动态的),所以这里走渲染后 +// 后置处理而不是 fork 模板。 +func injectOpenCodePlugins(cfs []taskflow.ConfigFile, opencodePath string, pluginURLs []string) ([]taskflow.ConfigFile, error) { + for i, c := range cfs { + if c.Path != opencodePath { + continue + } + var obj map[string]any + if err := json.Unmarshal([]byte(c.Content), &obj); err != nil { + return nil, fmt.Errorf("unmarshal opencode.json: %w", err) + } + obj["plugin"] = pluginURLs + out, err := json.MarshalIndent(obj, "", " ") + if err != nil { + return nil, fmt.Errorf("marshal opencode.json: %w", err) + } + cfs[i].Content = string(out) + return cfs, nil + } + return nil, fmt.Errorf("opencode.json ConfigFile not found at %s", opencodePath) +} + +func (a *TaskUsecase) getCodingConfigs(ctx context.Context, cli consts.CliName, m *db.Model, skillIDs []string, pluginIDs []string) (taskflow.CodingAgent, []taskflow.ConfigFile, error) { var tmp string var path string var coding taskflow.CodingAgent @@ -776,40 +857,79 @@ func (a *TaskUsecase) getCodingConfigs(cli consts.CliName, m *db.Model, skillIDs Content: buf.String(), }) - if len(skillIDs) == 0 { + // 注入 agent-resource:rule(所有 CLI)/ skill(所有 CLI,resolver 内部 + // 并集 force_delivery)/ plugin(仅 OpenCode)。resolver==nil 时(例如 + // 单元测试用 zero-value TaskUsecase{})整个块跳过,并打 warn 日志。 + if a.resolver == nil { + if a.logger != nil { + a.logger.WarnContext(ctx, "getCodingConfigs: resolver is nil, skipping rule/skill/plugin injection") + } return coding, cfs, nil } - for _, skillID := range skillIDs { - skilldir := filepath.Join(consts.SkillBaseDir, skillID) - if _, err := os.Stat(skilldir); os.IsNotExist(err) { - continue + // rule — 三种 CLI 都下发 + if materializedRules, err := a.resolver.Rules(ctx); err != nil { + a.logger.WarnContext(ctx, "getCodingConfigs: list rules failed, continuing without rules", + slog.Any("err", err)) + } else { + for _, r := range materializedRules { + cfs = append(cfs, taskflow.ConfigFile{ + Path: filepath.Join(agentRuleBaseDir, r.Name+".md"), + Content: r.Content, + }) } - filepath.Walk(skilldir, func(path string, info os.FileInfo, err error) error { - if err != nil { - return err - } - if info.IsDir() { - return nil + } + + // skill — 三种 CLI 都下发;resolver 内部把用户选中和 force_delivery 求并集 + skillUUIDs := a.parseStringUUIDs(ctx, "skill_ids", skillIDs) + if materializedSkills, err := a.resolver.Skills(ctx, skillUUIDs); err != nil { + a.logger.WarnContext(ctx, "getCodingConfigs: list skills failed, continuing without skills", + slog.Any("err", err)) + } else { + for _, asset := range materializedSkills { + for _, f := range asset.Files { + cfs = append(cfs, taskflow.ConfigFile{ + Path: filepath.Join(agentSkillBaseDir, asset.Name, f.RelPath), + Content: string(f.Content), + }) } - content, err := os.ReadFile(path) - if err != nil { - return err + } + } + + // plugin — 仅 OpenCode 下发;其它 CLI 跳过省一次 S3 round-trip + if cli == consts.CliNameOpencode { + pluginUUIDs := a.parseStringUUIDs(ctx, "plugin_ids", pluginIDs) + if materializedPlugins, err := a.resolver.Plugins(ctx, pluginUUIDs); err != nil { + a.logger.WarnContext(ctx, "getCodingConfigs: list plugins failed, continuing without plugins", + slog.Any("err", err)) + } else if len(materializedPlugins) > 0 { + pluginURLs := make([]string, 0, len(materializedPlugins)) + for _, asset := range materializedPlugins { + for _, f := range asset.Files { + cfs = append(cfs, taskflow.ConfigFile{ + Path: filepath.Join(agentPluginBaseDir, asset.Name, f.RelPath), + Content: string(f.Content), + }) + } + if asset.Entry == "" { + a.logger.WarnContext(ctx, "getCodingConfigs: plugin missing entry, skipping opencode.json registration", + slog.String("plugin", asset.Name)) + continue + } + pluginURLs = append(pluginURLs, + "file://"+filepath.Join(agentPluginBaseDir, asset.Name, asset.Entry)) } - // 获取相对于 skilldir 的相对路径,保留目录结构 - relPath, err := filepath.Rel(skilldir, path) - if err != nil { - return err + if len(pluginURLs) > 0 { + if patched, err := injectOpenCodePlugins(cfs, path, pluginURLs); err != nil { + a.logger.WarnContext(ctx, "getCodingConfigs: inject plugin array into opencode.json failed", + slog.Any("err", err)) + } else { + cfs = patched + } } - realSkillID := filepath.Base(skilldir) - agentSkillDir := "/tmp/codingmatrix-project-tpl/.ai-ready/skills/" - cfs = append(cfs, taskflow.ConfigFile{ - Path: filepath.Join(agentSkillDir, realSkillID, relPath), - Content: string(content), - }) - return nil - }) + } } + return coding, cfs, nil } diff --git a/backend/biz/task/usecase/task_model_config_test.go b/backend/biz/task/usecase/task_model_config_test.go index 8e11f928..cc971f81 100644 --- a/backend/biz/task/usecase/task_model_config_test.go +++ b/backend/biz/task/usecase/task_model_config_test.go @@ -1,6 +1,7 @@ package usecase import ( + "context" "encoding/json" "strings" "testing" @@ -101,7 +102,7 @@ func TestGetCodingConfigsOpenCodeRendersRuntimeConfigEnabled(t *testing.T) { OutputLimit: 16000, } - coding, cfs, err := uc.getCodingConfigs(consts.CliNameOpencode, model, nil) + coding, cfs, err := uc.getCodingConfigs(context.Background(), consts.CliNameOpencode, model, nil, nil) if err != nil { t.Fatalf("getCodingConfigs() error = %v", err) } @@ -141,7 +142,7 @@ func TestGetCodingConfigsOpenCodeRendersThinkingDisabled(t *testing.T) { ThinkingEnabled: false, } - _, cfs, err := uc.getCodingConfigs(consts.CliNameOpencode, model, nil) + _, cfs, err := uc.getCodingConfigs(context.Background(), consts.CliNameOpencode, model, nil, nil) if err != nil { t.Fatalf("getCodingConfigs() error = %v", err) } @@ -177,7 +178,7 @@ func TestGetCodingConfigsOpenCodeRendersUltraForceReasoning(t *testing.T) { ThinkingEnabled: true, } - _, cfs, err := uc.getCodingConfigs(consts.CliNameOpencode, model, nil) + _, cfs, err := uc.getCodingConfigs(context.Background(), consts.CliNameOpencode, model, nil, nil) if err != nil { t.Fatalf("getCodingConfigs() error = %v", err) } @@ -207,7 +208,7 @@ func TestGetCodingConfigsOpenCodeRendersSupportImage(t *testing.T) { SupportImage: true, } - _, cfs, err := uc.getCodingConfigs(consts.CliNameOpencode, model, nil) + _, cfs, err := uc.getCodingConfigs(context.Background(), consts.CliNameOpencode, model, nil, nil) if err != nil { t.Fatalf("getCodingConfigs() error = %v", err) } @@ -226,7 +227,7 @@ func TestGetCodingConfigsOpenCodeRendersSupportImage(t *testing.T) { assertStringSlice(t, modalities["output"], []string{"text"}) model.SupportImage = false - _, cfs, err = uc.getCodingConfigs(consts.CliNameOpencode, model, nil) + _, cfs, err = uc.getCodingConfigs(context.Background(), consts.CliNameOpencode, model, nil, nil) if err != nil { t.Fatalf("getCodingConfigs() error = %v", err) } @@ -243,7 +244,7 @@ func TestGetCodingConfigsOpenCodeRendersSupportImage(t *testing.T) { func TestGetCodingConfigsNilModel(t *testing.T) { uc := &TaskUsecase{} - _, _, err := uc.getCodingConfigs(consts.CliNameOpencode, nil, nil) + _, _, err := uc.getCodingConfigs(context.Background(), consts.CliNameOpencode, nil, nil, nil) if err == nil { t.Fatal("getCodingConfigs() error is nil") } diff --git a/backend/config/config.go b/backend/config/config.go index 4683e8af..9a9a1ffa 100644 --- a/backend/config/config.go +++ b/backend/config/config.go @@ -57,6 +57,10 @@ type Config struct { VMIdle VMIdle `mapstructure:"vm_idle"` Attachment Attachment `mapstructure:"attachment"` ObjectStorage ObjectStorageConfig `mapstructure:"object_storage"` + // Aliyun mirrors mcai-backend's aliyun.public_oss block so the agent- + // resources Resolver can fall back to that bucket when ObjectStorage is + // disabled (the same OSS that admin-new writes assets into). Optional. + Aliyun AliyunConfig `mapstructure:"aliyun"` StaticFiles StaticFilesConfig `mapstructure:"static_files"` HostInstaller HostInstaller `mapstructure:"host_installer"` @@ -88,6 +92,31 @@ type ReviewAgent struct { Image string `mapstructure:"image"` } +// AliyunOSSConfig is structurally identical to mcai-backend's config.OSSConfig +// so the same aliyun.public_oss yaml block can be pasted into mcai-gh/backend +// deploys. Only Endpoint / Bucket / AccessKey / AccessKeySecret / Region are +// read by the agent-resources Resolver; the *Prefix fields are accepted for +// shape parity but unused on this side. +type AliyunOSSConfig struct { + AvatarPrefix string `mapstructure:"avatar_prefix"` + SpecPrefix string `mapstructure:"spec_prefix"` + RepoPrefix string `mapstructure:"repo_prefix"` + TempPrefix string `mapstructure:"temp_prefix"` + Endpoint string `mapstructure:"endpoint"` + AccessEndpoint string `mapstructure:"access_endpoint"` + AccessKey string `mapstructure:"access_key"` + AccessKeySecret string `mapstructure:"access_key_secret"` + Bucket string `mapstructure:"bucket"` + Region string `mapstructure:"region"` + MaxSize int64 `mapstructure:"max_size"` +} + +// AliyunConfig mirrors mcai-backend's config.AliyunConfig. +type AliyunConfig struct { + PublicOSS AliyunOSSConfig `mapstructure:"public_oss"` + PrivateOSS AliyunOSSConfig `mapstructure:"private_oss"` +} + // NLS 阿里云语音识别配置 type NLS struct { AppKey string `mapstructure:"app_key"` diff --git a/backend/consts/task.go b/backend/consts/task.go index ebe0b341..9b6c4f81 100644 --- a/backend/consts/task.go +++ b/backend/consts/task.go @@ -63,6 +63,3 @@ const ( // TaskSummaryQueueKey 任务摘要队列 Redis key const TaskSummaryQueueKey = "tasksummary:queue" - -// SkillBaseDir 技能文件存储基目录 -const SkillBaseDir = "/app/skills" diff --git a/backend/domain/plugin.go b/backend/domain/plugin.go new file mode 100644 index 00000000..c3a06ea1 --- /dev/null +++ b/backend/domain/plugin.go @@ -0,0 +1,11 @@ +package domain + +// PluginListItem 公共 plugin 列表项(/api/v1/plugins),仅 OpenCode 任务真正下发。 +type PluginListItem struct { + ID string `json:"id"` + Name string `json:"name"` + Description string `json:"description"` + Entry string `json:"entry"` + ActiveVersion string `json:"active_version,omitempty"` + IsForceDelivery bool `json:"is_force_delivery"` +} diff --git a/backend/domain/skill.go b/backend/domain/skill.go new file mode 100644 index 00000000..a9d4ab31 --- /dev/null +++ b/backend/domain/skill.go @@ -0,0 +1,11 @@ +package domain + +// SkillListItem 公共 skill 列表项(/api/v1/skills),由 agentresource.Repo +// 从 DB 读取,无文件系统依赖。 +type SkillListItem struct { + ID string `json:"id"` + Name string `json:"name"` + Description string `json:"description"` + ActiveVersion string `json:"active_version,omitempty"` + IsForceDelivery bool `json:"is_force_delivery"` +} From e4aacb4945b8cf634eafb79cec02ac16439fbaba Mon Sep 17 00:00:00 2001 From: xmv97 Date: Fri, 5 Jun 2026 11:28:49 +0000 Subject: [PATCH 06/11] feat(task): switch skill/plugin to presigned URL via AgentResources proto MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Skill/plugin zips were being downloaded server-side, unzipped in memory, then re-shipped as per-file ConfigFile entries through the taskflow gRPC PushTasks call. With ~64 files in scope this blew past the 4MiB gRPC message limit. Switch the dispatch path to hand the codingmatrix agent presigned GET URLs instead — the agent already had DownloadAndExtractAssets wired up for AgentResources.AssetRef, the publisher side was just unhooked since the slim port. Changes: - pkg/oss.PresignGet: new helper that presigns a GET URL against a full S3 key (existing Presign uses prefix+filename for uploads) - biz/agentresource: SkillRef / PluginRef types + Resolver.SkillRefs / Resolver.PluginRefs that call ObjectStore.PresignGet; resolved log includes zip_url for diagnosability - biz/task/usecase: forward AgentResources.{Skills,Plugins} on TaskExecutionConfig instead of inlining ConfigFile bytes - single-line JSON dump of ConfigFile slice kept for debug visibility --- backend/biz/agentresource/noop_objectstore.go | 6 + backend/biz/agentresource/resolver.go | 92 ++++++++++++++ backend/biz/agentresource/resolver_test.go | 13 ++ backend/biz/agentresource/types.go | 21 ++++ backend/biz/task/usecase/task.go | 115 ++++++++++-------- .../task/usecase/task_model_config_test.go | 12 +- backend/pkg/oss/oss.go | 17 +++ backend/pkg/taskflow/types.go | 68 +++++++++-- 8 files changed, 275 insertions(+), 69 deletions(-) diff --git a/backend/biz/agentresource/noop_objectstore.go b/backend/biz/agentresource/noop_objectstore.go index e0448309..b696db91 100644 --- a/backend/biz/agentresource/noop_objectstore.go +++ b/backend/biz/agentresource/noop_objectstore.go @@ -2,8 +2,10 @@ package agentresource import ( "context" + "errors" "fmt" "io" + "time" ) // noopObjectStore is used when ObjectStorage is disabled in config. Every @@ -15,3 +17,7 @@ type noopObjectStore struct{} func (noopObjectStore) GetObject(_ context.Context, _ string) (io.ReadCloser, error) { return nil, fmt.Errorf("object storage disabled") } + +func (noopObjectStore) PresignGet(_ context.Context, _ string, _ time.Duration) (string, error) { + return "", errors.New("object storage disabled") +} diff --git a/backend/biz/agentresource/resolver.go b/backend/biz/agentresource/resolver.go index fc28c27b..701f8f5d 100644 --- a/backend/biz/agentresource/resolver.go +++ b/backend/biz/agentresource/resolver.go @@ -5,16 +5,28 @@ import ( "fmt" "io" "log/slog" + "time" "github.com/google/uuid" ) +// defaultPresignTTL is the lifetime baked into skill / plugin presigned GET +// URLs we hand off to the codingmatrix agent. 24h is the ceiling on task +// VM lifetime, so any URL minted at task-create time stays usable for the +// entire task run. +const defaultPresignTTL = 24 * time.Hour + // ObjectStore is the minimal read-only surface the Resolver needs from an // object store. *pkg/oss.Client implements this implicitly, but the interface // is declared here so tests can inject in-memory fakes without pulling AWS // SDK dependencies. type ObjectStore interface { GetObject(ctx context.Context, key string) (io.ReadCloser, error) + // PresignGet returns a presigned GET URL for the given full object key. + // Used by SkillRefs / PluginRefs so the dispatch path can hand the URL + // down to the codingmatrix agent (which fetches + unzips in-VM) + // instead of round-tripping the zip through the gRPC PushTasks call. + PresignGet(ctx context.Context, key string, expires time.Duration) (string, error) } // ResolverInterface is the abstract surface consumed by the task dispatch @@ -24,6 +36,11 @@ type ResolverInterface interface { Rules(ctx context.Context) ([]MaterializedRule, error) Skills(ctx context.Context, userSelectedIDs []uuid.UUID) ([]MaterializedAsset, error) Plugins(ctx context.Context, userSelectedIDs []uuid.UUID) ([]MaterializedAsset, error) + // SkillRefs / PluginRefs are the presigned-URL counterparts used by + // the AgentResources dispatch path. The legacy MaterializedAsset + // methods stay so callers we have not migrated keep compiling. + SkillRefs(ctx context.Context, userSelectedIDs []uuid.UUID) ([]SkillRef, error) + PluginRefs(ctx context.Context, userSelectedIDs []uuid.UUID) ([]PluginRef, error) } // Resolver glues the read-only Repo together with the read-only ObjectStore. @@ -141,6 +158,81 @@ func (r *Resolver) Plugins(ctx context.Context, userSelectedIDs []uuid.UUID) ([] return out, nil } +// SkillRefs is the presigned-URL alternative to Skills. The repo query and +// {user-selected ∪ force-delivery} union logic are identical; only the +// per-skill payload differs: instead of downloading + unzipping in-process, +// the resolver presigns the S3 key so the codingmatrix agent fetches the +// zip itself inside the task VM. +// +// Per-skill presign failures are warn-logged and skipped to preserve the +// "one bad skill never breaks dispatch" contract that Skills() upholds. +func (r *Resolver) SkillRefs(ctx context.Context, userSelectedIDs []uuid.UUID) ([]SkillRef, error) { + skills, err := r.repo.ListActiveSkills(ctx, userSelectedIDs) + if err != nil { + return nil, fmt.Errorf("agentresource: list skills: %w", err) + } + out := make([]SkillRef, 0, len(skills)) + for _, s := range skills { + url, err := r.objstore.PresignGet(ctx, s.S3Key, defaultPresignTTL) + if err != nil { + r.logger.WarnContext(ctx, "agentresource: skip skill, presign failed", + slog.String("skill", s.Name), + slog.String("s3_key", s.S3Key), + slog.Any("err", err), + ) + continue + } + r.logger.InfoContext(ctx, "agentresource: skill ref resolved", + slog.String("skill", s.Name), + slog.String("version", s.Version), + slog.String("s3_key", s.S3Key), + slog.String("zip_url", url), + ) + out = append(out, SkillRef{ + Name: s.Name, + Version: s.Version, + ZipURL: url, + }) + } + return out, nil +} + +// PluginRefs mirrors SkillRefs for plugins and additionally carries the +// plugin entry filename — the mcai-backend task dispatcher needs that to +// patch the opencode.json `plugin` array with the right file:// URL. +func (r *Resolver) PluginRefs(ctx context.Context, userSelectedIDs []uuid.UUID) ([]PluginRef, error) { + plugins, err := r.repo.ListActivePlugins(ctx, userSelectedIDs) + if err != nil { + return nil, fmt.Errorf("agentresource: list plugins: %w", err) + } + out := make([]PluginRef, 0, len(plugins)) + for _, p := range plugins { + url, err := r.objstore.PresignGet(ctx, p.S3Key, defaultPresignTTL) + if err != nil { + r.logger.WarnContext(ctx, "agentresource: skip plugin, presign failed", + slog.String("plugin", p.Name), + slog.String("s3_key", p.S3Key), + slog.Any("err", err), + ) + continue + } + r.logger.InfoContext(ctx, "agentresource: plugin ref resolved", + slog.String("plugin", p.Name), + slog.String("version", p.Version), + slog.String("entry", p.Entry), + slog.String("s3_key", p.S3Key), + slog.String("zip_url", url), + ) + out = append(out, PluginRef{ + Name: p.Name, + Version: p.Version, + ZipURL: url, + EntryFilename: p.Entry, + }) + } + return out, nil +} + // fetch pulls a single object body fully into memory. The body is always // closed before returning, even on error. func (r *Resolver) fetch(ctx context.Context, key string) ([]byte, error) { diff --git a/backend/biz/agentresource/resolver_test.go b/backend/biz/agentresource/resolver_test.go index df9c24b2..89ac476d 100644 --- a/backend/biz/agentresource/resolver_test.go +++ b/backend/biz/agentresource/resolver_test.go @@ -8,6 +8,7 @@ import ( "sort" "sync" "testing" + "time" "github.com/google/uuid" ) @@ -49,6 +50,18 @@ func (f *fakeObjectStore) GetObject(_ context.Context, key string) (io.ReadClose return io.NopCloser(bytes.NewReader(body)), nil } +// PresignGet returns a deterministic fake URL ("https://fake/") so +// SkillRefs / PluginRefs tests can assert without touching real S3. Keys +// registered in errFor return that error instead. +func (f *fakeObjectStore) PresignGet(_ context.Context, key string, _ time.Duration) (string, error) { + f.mu.Lock() + defer f.mu.Unlock() + if err, ok := f.errFor[key]; ok { + return "", err + } + return "https://fake/" + key, nil +} + // ---- fake Repo ------------------------------------------------------------ type fakeRepo struct { diff --git a/backend/biz/agentresource/types.go b/backend/biz/agentresource/types.go index f8eafb95..69ccf398 100644 --- a/backend/biz/agentresource/types.go +++ b/backend/biz/agentresource/types.go @@ -95,3 +95,24 @@ type MaterializedAsset struct { Entry string Files []MaterializedFile } + +// SkillRef is a skill addressed by a presigned GET URL — the resolver no +// longer downloads + unzips the skill itself; the codingmatrix agent does +// that inside the task VM. This is the replacement for MaterializedAsset on +// the skill dispatch path and exists to keep the gRPC PushTasks payload +// under the 4MiB ceiling regardless of how many skills are in scope. +type SkillRef struct { + Name string + Version string + ZipURL string // presigned GET URL (TTL bound by the resolver) +} + +// PluginRef is the plugin counterpart of SkillRef. EntryFilename comes from +// parsed_meta.entry and is needed by mcai-backend to write the +// opencode.json `plugin` array — the agent itself does not consume it. +type PluginRef struct { + Name string + Version string + ZipURL string + EntryFilename string +} diff --git a/backend/biz/task/usecase/task.go b/backend/biz/task/usecase/task.go index 8dbdae64..45aeb6f2 100644 --- a/backend/biz/task/usecase/task.go +++ b/backend/biz/task/usecase/task.go @@ -169,13 +169,14 @@ func (a *TaskUsecase) SwitchModel(ctx context.Context, user *domain.User, taskID } } - coding, configs, err := a.getCodingConfigs(ctx, t.CliName, model, nil, nil) + coding, configs, agentRes, err := a.getCodingConfigs(ctx, t.CliName, model, nil, nil) if err != nil { return nil, err } if coding != taskflow.CodingAgentOpenCode { return nil, fmt.Errorf("switch model only supports opencode runtime") } + _ = agentRes // switch-model path does not currently forward AgentResources to taskflow. envs := map[string]string{ "OPENAI_API_KEY": model.APIKey, @@ -520,7 +521,7 @@ func (a *TaskUsecase) Create(ctx context.Context, user *domain.User, req domain. token = keys[0].APIKey } - coding, configs, err := a.getCodingConfigs(ctx, req.CliName, m, req.Extra.SkillIDs, req.Extra.PluginIDs) + coding, configs, agentRes, err := a.getCodingConfigs(ctx, req.CliName, m, req.Extra.SkillIDs, req.Extra.PluginIDs) if err != nil { return nil, err } @@ -556,17 +557,19 @@ func (a *TaskUsecase) Create(ctx context.Context, user *domain.User, req domain. mcps := a.buildMCPConfigs(t.ID, token) - // DEBUG: 把准备透传给 taskflow → codingmatrix 的 ConfigFile 全量打日志 - // (含原始 content),仅在 DEBUG 级别开启,生产无噪声。 + // DEBUG: 把准备透传给 taskflow → codingmatrix 的整组 ConfigFile + // marshal 成一个 JSON 串、一行日志打出来。仅在 DEBUG 级别开启, + // 生产无噪声。 if a.logger.Enabled(ctx, slog.LevelDebug) { - for i, cf := range configs { - a.logger.DebugContext(ctx, "tasker config file", + if payload, err := json.Marshal(configs); err != nil { + a.logger.WarnContext(ctx, "tasker configs marshal failed", slog.String("task_id", t.ID.String()), - slog.Int("idx", i), - slog.Int("total", len(configs)), - slog.String("path", cf.Path), - slog.Int("size", len(cf.Content)), - slog.String("content", cf.Content), + slog.Any("err", err)) + } else { + a.logger.DebugContext(ctx, "tasker configs", + slog.String("task_id", t.ID.String()), + slog.Int("count", len(configs)), + slog.String("configs", string(payload)), ) } } @@ -585,9 +588,10 @@ func (a *TaskUsecase) Create(ctx context.Context, user *domain.User, req domain. Model: m.Model, ApiType: m.InterfaceType, }, - Configs: configs, - McpConfigs: mcps, - LogStore: normalizeTaskLogStore(t.LogStore), + Configs: configs, + McpConfigs: mcps, + LogStore: normalizeTaskLogStore(t.LogStore), + AgentResources: agentRes, } b, err := json.Marshal(createTaskReq) if err != nil { @@ -777,12 +781,12 @@ func injectOpenCodePlugins(cfs []taskflow.ConfigFile, opencodePath string, plugi return nil, fmt.Errorf("opencode.json ConfigFile not found at %s", opencodePath) } -func (a *TaskUsecase) getCodingConfigs(ctx context.Context, cli consts.CliName, m *db.Model, skillIDs []string, pluginIDs []string) (taskflow.CodingAgent, []taskflow.ConfigFile, error) { +func (a *TaskUsecase) getCodingConfigs(ctx context.Context, cli consts.CliName, m *db.Model, skillIDs []string, pluginIDs []string) (taskflow.CodingAgent, []taskflow.ConfigFile, *taskflow.AgentResources, error) { var tmp string var path string var coding taskflow.CodingAgent if m == nil { - return coding, nil, fmt.Errorf("model is nil") + return coding, nil, nil, fmt.Errorf("model is nil") } npmPackage := "@ai-sdk/openai-compatible" thinkingEnabled, contextLimit, outputLimit := modelRuntimeDefaults(m) @@ -807,19 +811,19 @@ func (a *TaskUsecase) getCodingConfigs(ctx context.Context, cli consts.CliName, var err error npmPackage, err = opencodeNpmPackage(m.InterfaceType) if err != nil { - return coding, nil, err + return coding, nil, nil, err } authtemp, err := template.New("auth").Parse(string(templates.OpenCodeAuth)) if err != nil { - return coding, nil, err + return coding, nil, nil, err } var authBuf bytes.Buffer if err := authtemp.Execute(&authBuf, map[string]any{ "api_key": m.APIKey, }); err != nil { - return coding, nil, err + return coding, nil, nil, err } authMode := uint32(0o600) cfs = append(cfs, taskflow.ConfigFile{ @@ -829,12 +833,12 @@ func (a *TaskUsecase) getCodingConfigs(ctx context.Context, cli consts.CliName, }) default: - return coding, nil, fmt.Errorf("unexpected consts.CliName: %#v", cli) + return coding, nil, nil, fmt.Errorf("unexpected consts.CliName: %#v", cli) } temp, err := template.New("config").Parse(tmp) if err != nil { - return coding, nil, err + return coding, nil, nil, err } var buf bytes.Buffer @@ -849,7 +853,7 @@ func (a *TaskUsecase) getCodingConfigs(ctx context.Context, cli consts.CliName, "context_limit": contextLimit, "output_limit": outputLimit, }); err != nil { - return coding, nil, err + return coding, nil, nil, err } cfs = append(cfs, taskflow.ConfigFile{ @@ -857,17 +861,19 @@ func (a *TaskUsecase) getCodingConfigs(ctx context.Context, cli consts.CliName, Content: buf.String(), }) - // 注入 agent-resource:rule(所有 CLI)/ skill(所有 CLI,resolver 内部 - // 并集 force_delivery)/ plugin(仅 OpenCode)。resolver==nil 时(例如 - // 单元测试用 zero-value TaskUsecase{})整个块跳过,并打 warn 日志。 + // 注入 agent-resource:rule 仍走 ConfigFile inline(DB content 小,对 + // gRPC 4MiB ceiling 不构成压力);skill / plugin 走 AgentResources + // presigned URL,由 codingmatrix agent 在 VM 内 HTTP GET + 解压。 + // resolver==nil 时(zero-value TaskUsecase{} 单测)整个块跳过。 + var agentRes *taskflow.AgentResources if a.resolver == nil { if a.logger != nil { a.logger.WarnContext(ctx, "getCodingConfigs: resolver is nil, skipping rule/skill/plugin injection") } - return coding, cfs, nil + return coding, cfs, nil, nil } - // rule — 三种 CLI 都下发 + // rule — 三种 CLI 都下发(仍走 inline ConfigFile) if materializedRules, err := a.resolver.Rules(ctx); err != nil { a.logger.WarnContext(ctx, "getCodingConfigs: list rules failed, continuing without rules", slog.Any("err", err)) @@ -882,42 +888,47 @@ func (a *TaskUsecase) getCodingConfigs(ctx context.Context, cli consts.CliName, // skill — 三种 CLI 都下发;resolver 内部把用户选中和 force_delivery 求并集 skillUUIDs := a.parseStringUUIDs(ctx, "skill_ids", skillIDs) - if materializedSkills, err := a.resolver.Skills(ctx, skillUUIDs); err != nil { - a.logger.WarnContext(ctx, "getCodingConfigs: list skills failed, continuing without skills", + if skillRefs, err := a.resolver.SkillRefs(ctx, skillUUIDs); err != nil { + a.logger.WarnContext(ctx, "getCodingConfigs: list skill refs failed, continuing without skills", slog.Any("err", err)) - } else { - for _, asset := range materializedSkills { - for _, f := range asset.Files { - cfs = append(cfs, taskflow.ConfigFile{ - Path: filepath.Join(agentSkillBaseDir, asset.Name, f.RelPath), - Content: string(f.Content), - }) - } + } else if len(skillRefs) > 0 { + if agentRes == nil { + agentRes = &taskflow.AgentResources{} + } + for _, s := range skillRefs { + agentRes.Skills = append(agentRes.Skills, &taskflow.AgentResourceAssetRef{ + Name: s.Name, + Version: s.Version, + ZipURL: s.ZipURL, + }) } } // plugin — 仅 OpenCode 下发;其它 CLI 跳过省一次 S3 round-trip if cli == consts.CliNameOpencode { pluginUUIDs := a.parseStringUUIDs(ctx, "plugin_ids", pluginIDs) - if materializedPlugins, err := a.resolver.Plugins(ctx, pluginUUIDs); err != nil { - a.logger.WarnContext(ctx, "getCodingConfigs: list plugins failed, continuing without plugins", + if pluginRefs, err := a.resolver.PluginRefs(ctx, pluginUUIDs); err != nil { + a.logger.WarnContext(ctx, "getCodingConfigs: list plugin refs failed, continuing without plugins", slog.Any("err", err)) - } else if len(materializedPlugins) > 0 { - pluginURLs := make([]string, 0, len(materializedPlugins)) - for _, asset := range materializedPlugins { - for _, f := range asset.Files { - cfs = append(cfs, taskflow.ConfigFile{ - Path: filepath.Join(agentPluginBaseDir, asset.Name, f.RelPath), - Content: string(f.Content), - }) - } - if asset.Entry == "" { + } else if len(pluginRefs) > 0 { + pluginURLs := make([]string, 0, len(pluginRefs)) + if agentRes == nil { + agentRes = &taskflow.AgentResources{} + } + for _, p := range pluginRefs { + agentRes.Plugins = append(agentRes.Plugins, &taskflow.AgentResourceAssetRef{ + Name: p.Name, + Version: p.Version, + ZipURL: p.ZipURL, + EntryFilename: p.EntryFilename, + }) + if p.EntryFilename == "" { a.logger.WarnContext(ctx, "getCodingConfigs: plugin missing entry, skipping opencode.json registration", - slog.String("plugin", asset.Name)) + slog.String("plugin", p.Name)) continue } pluginURLs = append(pluginURLs, - "file://"+filepath.Join(agentPluginBaseDir, asset.Name, asset.Entry)) + "file://"+filepath.Join(agentPluginBaseDir, p.Name, p.EntryFilename)) } if len(pluginURLs) > 0 { if patched, err := injectOpenCodePlugins(cfs, path, pluginURLs); err != nil { @@ -930,7 +941,7 @@ func (a *TaskUsecase) getCodingConfigs(ctx context.Context, cli consts.CliName, } } - return coding, cfs, nil + return coding, cfs, agentRes, nil } // Update implements domain.TaskUsecase. diff --git a/backend/biz/task/usecase/task_model_config_test.go b/backend/biz/task/usecase/task_model_config_test.go index cc971f81..3a1ea95b 100644 --- a/backend/biz/task/usecase/task_model_config_test.go +++ b/backend/biz/task/usecase/task_model_config_test.go @@ -102,7 +102,7 @@ func TestGetCodingConfigsOpenCodeRendersRuntimeConfigEnabled(t *testing.T) { OutputLimit: 16000, } - coding, cfs, err := uc.getCodingConfigs(context.Background(), consts.CliNameOpencode, model, nil, nil) + coding, cfs, _, err := uc.getCodingConfigs(context.Background(), consts.CliNameOpencode, model, nil, nil) if err != nil { t.Fatalf("getCodingConfigs() error = %v", err) } @@ -142,7 +142,7 @@ func TestGetCodingConfigsOpenCodeRendersThinkingDisabled(t *testing.T) { ThinkingEnabled: false, } - _, cfs, err := uc.getCodingConfigs(context.Background(), consts.CliNameOpencode, model, nil, nil) + _, cfs, _, err := uc.getCodingConfigs(context.Background(), consts.CliNameOpencode, model, nil, nil) if err != nil { t.Fatalf("getCodingConfigs() error = %v", err) } @@ -178,7 +178,7 @@ func TestGetCodingConfigsOpenCodeRendersUltraForceReasoning(t *testing.T) { ThinkingEnabled: true, } - _, cfs, err := uc.getCodingConfigs(context.Background(), consts.CliNameOpencode, model, nil, nil) + _, cfs, _, err := uc.getCodingConfigs(context.Background(), consts.CliNameOpencode, model, nil, nil) if err != nil { t.Fatalf("getCodingConfigs() error = %v", err) } @@ -208,7 +208,7 @@ func TestGetCodingConfigsOpenCodeRendersSupportImage(t *testing.T) { SupportImage: true, } - _, cfs, err := uc.getCodingConfigs(context.Background(), consts.CliNameOpencode, model, nil, nil) + _, cfs, _, err := uc.getCodingConfigs(context.Background(), consts.CliNameOpencode, model, nil, nil) if err != nil { t.Fatalf("getCodingConfigs() error = %v", err) } @@ -227,7 +227,7 @@ func TestGetCodingConfigsOpenCodeRendersSupportImage(t *testing.T) { assertStringSlice(t, modalities["output"], []string{"text"}) model.SupportImage = false - _, cfs, err = uc.getCodingConfigs(context.Background(), consts.CliNameOpencode, model, nil, nil) + _, cfs, _, err = uc.getCodingConfigs(context.Background(), consts.CliNameOpencode, model, nil, nil) if err != nil { t.Fatalf("getCodingConfigs() error = %v", err) } @@ -244,7 +244,7 @@ func TestGetCodingConfigsOpenCodeRendersSupportImage(t *testing.T) { func TestGetCodingConfigsNilModel(t *testing.T) { uc := &TaskUsecase{} - _, _, err := uc.getCodingConfigs(context.Background(), consts.CliNameOpencode, nil, nil, nil) + _, _, _, err := uc.getCodingConfigs(context.Background(), consts.CliNameOpencode, nil, nil, nil) if err == nil { t.Fatal("getCodingConfigs() error is nil") } diff --git a/backend/pkg/oss/oss.go b/backend/pkg/oss/oss.go index 0e0ade0d..a884dc74 100644 --- a/backend/pkg/oss/oss.go +++ b/backend/pkg/oss/oss.go @@ -212,6 +212,23 @@ func (c *Client) GetURL(prefix, filename string) string { return appendURLPath(base, objectKey(prefix, filename)) } +// PresignGet returns a presigned GET URL for the given object key. Unlike +// Presign() (which presigns under a {prefix,filename} pair tied to upload +// flows), PresignGet takes the full object key verbatim — callers building +// agent-resource references already have the full S3 key from the version +// row (e.g. "agent-resources/skills/global/global/{repoID}/{name}/{ver}.zip"). +func (c *Client) PresignGet(ctx context.Context, key string, expires time.Duration) (string, error) { + expires = normalizeExpires(expires) + getURL, err := c.presigner.PresignGetObject(ctx, &s3.GetObjectInput{ + Bucket: aws.String(c.cfg.Bucket), + Key: aws.String(key), + }, s3.WithPresignExpires(expires)) + if err != nil { + return "", fmt.Errorf("presign get %q: %w", key, err) + } + return c.publicPresignURL(getURL.URL, key), nil +} + func (c *Client) Presign(ctx context.Context, prefix, filename string, expires time.Duration) (*Presign, error) { expires = normalizeExpires(expires) key := objectKey(prefix, filename) diff --git a/backend/pkg/taskflow/types.go b/backend/pkg/taskflow/types.go index e3f4ec35..fe861178 100644 --- a/backend/pkg/taskflow/types.go +++ b/backend/pkg/taskflow/types.go @@ -601,19 +601,65 @@ type McpServerConfig struct { Env map[string]string `json:"env,omitempty"` } +// AgentResourceRuleSource mirrors codingmatrix proto +// agent.AgentResources_Rule_Source. We do not import the proto package here +// because mcai-gh/backend keeps a local taskflow client mirror; the integer +// values must stay aligned with the proto enum below (UNSPECIFIED=0, SYSTEM=1, +// AGENT=2). +type AgentResourceRuleSource int32 + +const ( + AgentResourceRuleSourceUnspecified AgentResourceRuleSource = 0 + AgentResourceRuleSourceSystem AgentResourceRuleSource = 1 + AgentResourceRuleSourceAgent AgentResourceRuleSource = 2 +) + +// AgentResourceRule is the JSON-tag mirror of codingmatrix proto +// agent.AgentResources_Rule. Field order + json tags MUST stay in lock-step +// with the proto generated struct because mcai-taskflow unmarshals our HTTP +// body directly into that proto type. +type AgentResourceRule struct { + Name string `json:"name,omitempty"` + Version string `json:"version,omitempty"` + Content string `json:"content,omitempty"` + Filename string `json:"filename,omitempty"` + Source AgentResourceRuleSource `json:"source,omitempty"` +} + +// AgentResourceAssetRef mirrors codingmatrix proto +// agent.AgentResources_AssetRef. Skills + plugins share the same shape. +type AgentResourceAssetRef struct { + Name string `json:"name,omitempty"` + Version string `json:"version,omitempty"` + ZipURL string `json:"zip_url,omitempty"` + EntryFilename string `json:"entry_filename,omitempty"` +} + +// AgentResources mirrors codingmatrix proto agent.AgentResources. Only the +// fields mcai-gh/backend actually populates are serialized. Rules / Skills / +// Plugins are pointer slices so a nil AgentResources or nil sub-slice +// serializes as JSON null / "absent" — matching the proto wire behaviour. +type AgentResources struct { + Rules []*AgentResourceRule `json:"rules,omitempty"` + Skills []*AgentResourceAssetRef `json:"skills,omitempty"` + Plugins []*AgentResourceAssetRef `json:"plugins,omitempty"` + OpencodeConfig string `json:"opencode_config,omitempty"` +} + // CreateTaskReq 创建任务请求 type CreateTaskReq struct { - ID uuid.UUID `json:"id"` - VMID string `json:"vm_id"` - SystemPrompt string `json:"system_prompt,omitempty"` - Text string `json:"text,omitempty"` - Attachments []Attachment `json:"attachments,omitempty"` - LLM LLM `json:"llm,omitzero"` - CodingAgent CodingAgent `json:"coding_agent,omitempty"` - Configs []ConfigFile `json:"configs,omitzero"` - McpConfigs []McpServerConfig `json:"mcp_configs,omitzero"` - Env map[string]string `json:"env,omitempty"` - LogStore string `json:"log_store,omitempty"` + ID uuid.UUID `json:"id"` + VMID string `json:"vm_id"` + SystemPrompt string `json:"system_prompt,omitempty"` + Text string `json:"text,omitempty"` + Attachments []Attachment `json:"attachments,omitempty"` + LLM LLM `json:"llm,omitzero"` + CodingAgent CodingAgent `json:"coding_agent,omitempty"` + Configs []ConfigFile `json:"configs,omitzero"` + McpConfigs []McpServerConfig `json:"mcp_configs,omitzero"` + Env map[string]string `json:"env,omitempty"` + LogStore string `json:"log_store,omitempty"` + AgentResources *AgentResources `json:"agent_resources,omitempty"` // skill/plugin presigned URLs + rule content forwarded to codingmatrix agent } // ==================== VirtualMachine 查询类型 ==================== From 0d08324299740d990a13ef4fa4505ef64fbc9cdc Mon Sep 17 00:00:00 2001 From: xmv97 Date: Sat, 6 Jun 2026 11:12:42 +0000 Subject: [PATCH 07/11] feat(oss): native aliyun-oss-go-sdk client for OSS bucket presigning MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit AWS-SDK-v2's SigV4 signer is incompatible with Aliyun OSS: - SignatureDoesNotMatch (OSS uses its own OSS4-HMAC-SHA256 / V1 sigs) - With ForcePathStyle and a virtual-host endpoint (oss.foo.com style), the bucket gets prefixed in the path → bucket.oss.foo.com/bucket/key instead of bucket.oss.foo.com/key Adds pkg/oss.AliyunClient backed by aliyun-oss-go-sdk that implements just GetObject + PresignGet (enough for agentresource.Resolver). The existing *pkg/oss.Client stays untouched — avatar / repo / spec / temp uploads keep going through the AWS SDK path when object_storage is enabled. agentresource/register.go now picks the client by config block: - object_storage.enabled = true → existing AWS-SDK client - aliyun.public_oss.bucket set → new aliyun-oss-go-sdk client - neither → noopObjectStore (skip-and-log) --- backend/biz/agentresource/register.go | 66 +++++++++++------------ backend/go.mod | 1 + backend/go.sum | 6 +++ backend/pkg/oss/aliyun.go | 77 +++++++++++++++++++++++++++ 4 files changed, 115 insertions(+), 35 deletions(-) create mode 100644 backend/pkg/oss/aliyun.go diff --git a/backend/biz/agentresource/register.go b/backend/biz/agentresource/register.go index 7660a674..aa0b056a 100644 --- a/backend/biz/agentresource/register.go +++ b/backend/biz/agentresource/register.go @@ -17,65 +17,61 @@ import ( "github.com/chaitin/MonkeyCode/backend/pkg/oss" ) -// ProvideAgentResource 注册 agentresource 模块。oss.Client 仅在 ObjectStorage -// 已启用时构造;未启用时 Resolver 会拿到 nil ObjectStore,调用 Skills/Plugins -// 时各自返回的 fetch 错误会被 resolver 内部 warn-and-skip 掉,dispatch 不会失败。 +// ProvideAgentResource wires the agent-resource module. The ObjectStore is +// picked from whichever bucket block is configured: +// +// - object_storage.enabled = true → AWS-SDK-v2 client (any S3-compatible +// store: MinIO, RustFS, real AWS). Reuses the same client avatar / repo / +// spec / temp uploads use, so single SDK in the binary. +// - aliyun.public_oss.bucket set → aliyun-oss-go-sdk client. AWS SDK's +// SigV4 signer is incompatible with Aliyun OSS (SignatureDoesNotMatch + +// bucket double-prefix in path-style URLs), so we wire a native client +// just for this code path. Existing pkg/oss.Client is untouched; avatar +// etc. still go through the AWS SDK path when object_storage is on. +// - neither configured → nil ObjectStore. Resolver downgrades +// to noopObjectStore; fetch/presign each fail and the per-asset skip +// pipeline keeps the task creating without rule/skill/plugin assets. func ProvideAgentResource(i *do.Injector) { do.Provide(i, func(i *do.Injector) (Repo, error) { return NewRepo(do.MustInvoke[*db.Client](i)), nil }) - do.Provide(i, func(i *do.Injector) (*oss.Client, error) { + do.Provide(i, func(i *do.Injector) (ObjectStore, error) { cfg := do.MustInvoke[*config.Config](i) logger := do.MustInvoke[*slog.Logger](i) - // Primary: ObjectStorage block (shared with avatar/repo/spec/temp). + // Primary: ObjectStorage block — AWS-SDK-v2 client. if cfg.ObjectStorage.Enabled { opt := oss.S3Option{ ForcePathStyle: cfg.ObjectStorage.ForcePathStyle, InitBucket: cfg.ObjectStorage.InitBucket, } - return oss.NewS3Compatible(context.Background(), cfg.ObjectStorage, opt) + client, err := oss.NewS3Compatible(context.Background(), cfg.ObjectStorage, opt) + if err != nil { + return nil, err + } + return client, nil } - // Fallback: aliyun.public_oss block — same shape mcai-backend + - // admin-new use. Lets ops paste a single OSS block into all three - // deploys rather than duplicating credentials. + // Fallback: aliyun.public_oss — native aliyun-oss-go-sdk client. if pub := cfg.Aliyun.PublicOSS; pub.Bucket != "" && pub.Endpoint != "" { - logger.Info("agentresource: ObjectStorage disabled, falling back to aliyun.public_oss", + logger.Info("agentresource: using aliyun.public_oss (native SDK)", "endpoint", pub.Endpoint, "bucket", pub.Bucket) - return oss.NewS3Compatible(context.Background(), config.ObjectStorageConfig{ - Enabled: true, - Endpoint: pub.Endpoint, - AccessEndpoint: pub.AccessEndpoint, - AccessKey: pub.AccessKey, - AccessKeySecret: pub.AccessKeySecret, - Bucket: pub.Bucket, - Region: pub.Region, - // Aliyun OSS uses virtual-hosted style; not path style. - ForcePathStyle: false, - MaxSize: pub.MaxSize, - }, oss.S3Option{}) + client, err := oss.NewAliyunOSS(pub) + if err != nil { + return nil, err + } + return client, nil } - // Neither block configured — Resolver will downgrade to noopObjectStore. - return nil, nil + // Neither block configured — Resolver downgrades to noopObjectStore. + return noopObjectStore{}, nil }) do.Provide(i, func(i *do.Injector) (ResolverInterface, error) { repo := do.MustInvoke[Repo](i) - client, _ := do.Invoke[*oss.Client](i) + store := do.MustInvoke[ObjectStore](i) logger := do.MustInvoke[*slog.Logger](i) - // *oss.Client 隐式实现 ObjectStore(有 GetObject(ctx, key) 方法)。 - // 当 client==nil 时 wrap 一个 nil store 即可;resolver fetch 时会 - // 走到 nil-deref 之前已被外层 err 捕获——但为避免 panic,统一在这 - // 里把 nil 显式包成 noopObjectStore。 - var store ObjectStore - if client != nil { - store = client - } else { - store = noopObjectStore{} - } return NewResolver(repo, store, logger), nil }) } diff --git a/backend/go.mod b/backend/go.mod index bddda496..4055b691 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -10,6 +10,7 @@ require ( github.com/ackcoder/go-cap v1.1.3 github.com/alicebob/miniredis/v2 v2.35.0 github.com/aliyun/alibabacloud-nls-go-sdk v1.1.1 + github.com/aliyun/aliyun-oss-go-sdk v3.0.2+incompatible github.com/anthropics/anthropic-sdk-go v1.40.0 github.com/aws/aws-sdk-go-v2 v1.41.7 github.com/aws/aws-sdk-go-v2/config v1.32.17 diff --git a/backend/go.sum b/backend/go.sum index 2a055005..4d2ac6a4 100644 --- a/backend/go.sum +++ b/backend/go.sum @@ -8,6 +8,8 @@ github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= github.com/ClickHouse/ch-go v0.71.0 h1:bUdZ/EZj/LcVHsMqaRUP2holqygrPWQKeMjc6nZoyRM= github.com/ClickHouse/ch-go v0.71.0/go.mod h1:NwbNc+7jaqfY58dmdDUbG4Jl22vThgx1cYjBw0vtgXw= +github.com/ClickHouse/clickhouse-go v1.4.3 h1:iAFMa2UrQdR5bHJ2/yaSLffZkxpcOYQMCUuKeNXGdqc= +github.com/ClickHouse/clickhouse-go v1.4.3/go.mod h1:EaI/sW7Azgz9UATzd5ZdZHRUhHgv5+JMS9NSr2smCJI= github.com/ClickHouse/clickhouse-go/v2 v2.45.0 h1:iHt15nA4iYhfde5bDQAcLAat9BAh7B5ksPRNRa4UI7s= github.com/ClickHouse/clickhouse-go/v2 v2.45.0/go.mod h1:giJfUVlMkcfUEPVfRpt51zZaGEx9i17gCos8gBl392c= github.com/DATA-DOG/go-sqlmock v1.5.2 h1:OcvFkGmslmlZibjAjaHm3L//6LiuBgolP7OputlJIzU= @@ -26,6 +28,8 @@ github.com/aliyun/alibaba-cloud-sdk-go v1.61.1376 h1:lExo7heZgdFn5AbaNJEllbA0KSJ github.com/aliyun/alibaba-cloud-sdk-go v1.61.1376/go.mod h1:9CMdKNL3ynIGPpfTcdwTvIm8SGuAZYYC4jFVSSvE1YQ= github.com/aliyun/alibabacloud-nls-go-sdk v1.1.1 h1:LjItoNZuu5xHlsByFo+kr3nGa4LRIESCGWhfurayxBg= github.com/aliyun/alibabacloud-nls-go-sdk v1.1.1/go.mod h1:4BDMUKpEaP/Ct79w0ozR0nbnEj49g1k3mrgX/IKG5I4= +github.com/aliyun/aliyun-oss-go-sdk v3.0.2+incompatible h1:8psS8a+wKfiLt1iVDX79F7Y6wUM49Lcha2FMXt4UM8g= +github.com/aliyun/aliyun-oss-go-sdk v3.0.2+incompatible/go.mod h1:T/Aws4fEfogEE9v+HPhhw+CntffsBHJ8nXQCwKr0/g8= github.com/andybalholm/brotli v1.2.0 h1:ukwgCxwYrmACq68yiUqwIWnGY0cTPox/M94sVwToPjQ= github.com/andybalholm/brotli v1.2.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY= github.com/anthropics/anthropic-sdk-go v1.40.0 h1:+lhHU2LdeRlVsazVXHswFMpWr2Q11ShL+gjBNzX36Rw= @@ -82,6 +86,8 @@ github.com/buger/jsonparser v1.1.2 h1:frqHqw7otoVbk5M8LlE/L7HTnIq2v9RX6EJ48i9AxJ github.com/buger/jsonparser v1.1.2/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/cloudflare/golz4 v0.0.0-20150217214814-ef862a3cdc58 h1:F1EaeKL/ta07PY/k9Os/UFtwERei2/XzGemhpGnBKNg= +github.com/cloudflare/golz4 v0.0.0-20150217214814-ef862a3cdc58/go.mod h1:EOBUe0h4xcZ5GoxqC5SDxFQ8gwyZPKQoEzownBlhI80= github.com/coder/websocket v1.8.14 h1:9L0p0iKiNOibykf283eHkKUHHrpG7f65OE3BhhO7v9g= github.com/coder/websocket v1.8.14/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg= github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI= diff --git a/backend/pkg/oss/aliyun.go b/backend/pkg/oss/aliyun.go new file mode 100644 index 00000000..0670b93f --- /dev/null +++ b/backend/pkg/oss/aliyun.go @@ -0,0 +1,77 @@ +package oss + +import ( + "context" + "errors" + "fmt" + "io" + "time" + + "github.com/aliyun/aliyun-oss-go-sdk/oss" + + "github.com/chaitin/MonkeyCode/backend/config" +) + +// AliyunClient is a narrow OSS client backed by aliyun-oss-go-sdk. It exists +// alongside the AWS-SDK-v2 backed Client so the agent-resources read path can +// hit Aliyun OSS without going through the AWS S3 SigV4 signer (Aliyun rejects +// SigV4 with SignatureDoesNotMatch and the path-style URL it produces double- +// prefixes the bucket). +// +// Implements just GetObject + PresignGet — the surface agentresource.Resolver +// needs. Existing avatar/repo/spec/temp upload flows keep using the AWS-SDK +// backed *Client. +type AliyunClient struct { + bucket *oss.Bucket +} + +// NewAliyunOSS builds an AliyunClient from the shared aliyun.public_oss block. +// Empty Endpoint / Bucket / AccessKey / AccessKeySecret is a hard error so +// misconfigured deploys fail fast at DI resolution time rather than at first +// presign attempt. +func NewAliyunOSS(cfg config.AliyunOSSConfig) (*AliyunClient, error) { + if cfg.Endpoint == "" { + return nil, errors.New("aliyun oss: empty Endpoint") + } + if cfg.Bucket == "" { + return nil, errors.New("aliyun oss: empty Bucket") + } + if cfg.AccessKey == "" || cfg.AccessKeySecret == "" { + return nil, errors.New("aliyun oss: empty AccessKey/AccessKeySecret") + } + client, err := oss.New(cfg.Endpoint, cfg.AccessKey, cfg.AccessKeySecret) + if err != nil { + return nil, fmt.Errorf("aliyun oss: new client: %w", err) + } + bucket, err := client.Bucket(cfg.Bucket) + if err != nil { + return nil, fmt.Errorf("aliyun oss: open bucket %q: %w", cfg.Bucket, err) + } + return &AliyunClient{bucket: bucket}, nil +} + +// GetObject downloads the object body at the given key (relative to the +// bucket — no extra prefix is applied). Caller closes the ReadCloser. +func (c *AliyunClient) GetObject(_ context.Context, key string) (io.ReadCloser, error) { + body, err := c.bucket.GetObject(key) + if err != nil { + return nil, fmt.Errorf("aliyun oss: get %q: %w", key, err) + } + return body, nil +} + +// PresignGet returns a presigned GET URL valid for `expires`. The aliyun SDK +// signs with `OSS4-HMAC-SHA256` (or v1 depending on endpoint), which OSS +// accepts. Aliyun SDK takes expiry as seconds; we floor sub-second values to 1 +// so a defensively-zero ttl doesn't break. +func (c *AliyunClient) PresignGet(_ context.Context, key string, expires time.Duration) (string, error) { + seconds := int64(expires.Seconds()) + if seconds < 1 { + seconds = 1 + } + url, err := c.bucket.SignURL(key, oss.HTTPGet, seconds) + if err != nil { + return "", fmt.Errorf("aliyun oss: presign %q: %w", key, err) + } + return url, nil +} From 16d850ad771cb4dca6d9705bcf6f34db1e4fccfb Mon Sep 17 00:00:00 2001 From: xmv97 Date: Sat, 6 Jun 2026 13:44:54 +0000 Subject: [PATCH 08/11] feat(taskflow): drop AgentResources.Rules/OpencodeConfig from request types --- backend/pkg/taskflow/types.go | 36 +++++------------------------------ 1 file changed, 5 insertions(+), 31 deletions(-) diff --git a/backend/pkg/taskflow/types.go b/backend/pkg/taskflow/types.go index fe861178..2d34e997 100644 --- a/backend/pkg/taskflow/types.go +++ b/backend/pkg/taskflow/types.go @@ -601,31 +601,6 @@ type McpServerConfig struct { Env map[string]string `json:"env,omitempty"` } -// AgentResourceRuleSource mirrors codingmatrix proto -// agent.AgentResources_Rule_Source. We do not import the proto package here -// because mcai-gh/backend keeps a local taskflow client mirror; the integer -// values must stay aligned with the proto enum below (UNSPECIFIED=0, SYSTEM=1, -// AGENT=2). -type AgentResourceRuleSource int32 - -const ( - AgentResourceRuleSourceUnspecified AgentResourceRuleSource = 0 - AgentResourceRuleSourceSystem AgentResourceRuleSource = 1 - AgentResourceRuleSourceAgent AgentResourceRuleSource = 2 -) - -// AgentResourceRule is the JSON-tag mirror of codingmatrix proto -// agent.AgentResources_Rule. Field order + json tags MUST stay in lock-step -// with the proto generated struct because mcai-taskflow unmarshals our HTTP -// body directly into that proto type. -type AgentResourceRule struct { - Name string `json:"name,omitempty"` - Version string `json:"version,omitempty"` - Content string `json:"content,omitempty"` - Filename string `json:"filename,omitempty"` - Source AgentResourceRuleSource `json:"source,omitempty"` -} - // AgentResourceAssetRef mirrors codingmatrix proto // agent.AgentResources_AssetRef. Skills + plugins share the same shape. type AgentResourceAssetRef struct { @@ -635,15 +610,14 @@ type AgentResourceAssetRef struct { EntryFilename string `json:"entry_filename,omitempty"` } -// AgentResources mirrors codingmatrix proto agent.AgentResources. Only the -// fields mcai-gh/backend actually populates are serialized. Rules / Skills / +// AgentResources mirrors codingmatrix proto agent.AgentResources. Skills / // Plugins are pointer slices so a nil AgentResources or nil sub-slice // serializes as JSON null / "absent" — matching the proto wire behaviour. +// Rules and opencode.json travel on the legacy ConfigFile inline channel, +// not here. type AgentResources struct { - Rules []*AgentResourceRule `json:"rules,omitempty"` - Skills []*AgentResourceAssetRef `json:"skills,omitempty"` - Plugins []*AgentResourceAssetRef `json:"plugins,omitempty"` - OpencodeConfig string `json:"opencode_config,omitempty"` + Skills []*AgentResourceAssetRef `json:"skills,omitempty"` + Plugins []*AgentResourceAssetRef `json:"plugins,omitempty"` } // CreateTaskReq 创建任务请求 From 00719d69cdf4a5619c9d77728a527b59c40aa255 Mon Sep 17 00:00:00 2001 From: xmv97 Date: Thu, 4 Jun 2026 09:32:52 +0000 Subject: [PATCH 09/11] feat(gh/ui): plugin picker + force-delivery chip in skill/plugin pickers --- .../task/create-default-task-dialog.tsx | 56 +++++-- .../components/console/task/task-input.tsx | 40 +++++ .../console/task/task-plugin-selector.tsx | 142 ++++++++++++++++++ .../console/task/task-skill-selector.tsx | 64 +++++++- frontend/src/lib/agent-resources-api.ts | 79 ++++++++++ 5 files changed, 364 insertions(+), 17 deletions(-) create mode 100644 frontend/src/components/console/task/task-plugin-selector.tsx create mode 100644 frontend/src/lib/agent-resources-api.ts diff --git a/frontend/src/components/console/task/create-default-task-dialog.tsx b/frontend/src/components/console/task/create-default-task-dialog.tsx index bf613fec..798e0733 100644 --- a/frontend/src/components/console/task/create-default-task-dialog.tsx +++ b/frontend/src/components/console/task/create-default-task-dialog.tsx @@ -75,6 +75,8 @@ import { toast } from "sonner" import { TaskConcurrentLimitDialog } from "./task-concurrent-limit-dialog" import ModelSelect from "./model-select" import { TaskSkillSelector } from "./task-skill-selector" +import { TaskPluginSelector } from "./task-plugin-selector" +import { fetchPluginListing, type PluginListItem } from "@/lib/agent-resources-api" interface CreateDefaultTaskDialogProps { open: boolean @@ -118,6 +120,9 @@ export default function CreateDefaultTaskDialog({ const [selectedSkill, setSelectedSkill] = useState(defaultSkills) const [skillList, setSkillList] = useState([]) const [activeSkillTag, setActiveSkillTag] = useState("全部") + const [pluginPopoverOpen, setPluginPopoverOpen] = useState(false) + const [pluginList, setPluginList] = useState([]) + const [selectedPlugin, setSelectedPlugin] = useState([]) const [advancedOptionsOpen, setAdvancedOptionsOpen] = useState(false) const [selectedModelId, setSelectedModelId] = useState("") const [selectedHostId, setSelectedHostId] = useState("") @@ -156,6 +161,8 @@ export default function CreateDefaultTaskDialog({ setIdentitySearch({}) setSelectedSkill(defaultSkills) setActiveSkillTag("全部") + setPluginPopoverOpen(false) + setSelectedPlugin([]) setAdvancedOptionsOpen(false) setSelectedModelId("") setSelectedHostId("") @@ -165,18 +172,29 @@ export default function CreateDefaultTaskDialog({ return } - if (IS_OFFLINE_EDITION || skillList.length > 0) { + if (IS_OFFLINE_EDITION) { return } - apiRequest("v1SkillsList", {}, [], (resp) => { - if (resp.code === 0) { - setSkillList(resp.data || []) - } else { - toast.error(resp.message || "获取技能列表失败") - } - }) - }, [open, skillList.length]) + if (skillList.length === 0) { + apiRequest("v1SkillsList", {}, [], (resp) => { + if (resp.code === 0) { + setSkillList(resp.data || []) + } else { + toast.error(resp.message || "获取技能列表失败") + } + }) + } + + if (pluginList.length === 0) { + // Plugin picker is best-effort — surface but do not block the dialog. + fetchPluginListing() + .then((items) => setPluginList(items)) + .catch((err: Error) => { + toast.error(err.message || "获取插件列表失败") + }) + } + }, [open, skillList.length, pluginList.length]) useEffect(() => { if (!open) { @@ -303,6 +321,15 @@ export default function CreateDefaultTaskDialog({ }) } + const handlePluginChange = (pluginId: string, checked: boolean) => { + setSelectedPlugin((prev) => { + if (checked) { + return prev.includes(pluginId) ? prev : [...prev, pluginId] + } + return prev.filter((id) => id !== pluginId) + }) + } + const setDefaultConfig = () => { const storedParams = readStoredTaskDialogParams() setSelectedModelId(selectPreferredTaskModel(models, subscription)) @@ -423,6 +450,7 @@ export default function CreateDefaultTaskDialog({ }, extra: { skill_ids: selectedSkill, + plugin_ids: selectedPlugin, }, resource: { core: 2, @@ -757,6 +785,16 @@ export default function CreateDefaultTaskDialog({ triggerClassName="rounded-md" /> )} + {!IS_OFFLINE_EDITION && ( + + )} diff --git a/frontend/src/components/console/task/task-input.tsx b/frontend/src/components/console/task/task-input.tsx index b709f3da..6169c79e 100644 --- a/frontend/src/components/console/task/task-input.tsx +++ b/frontend/src/components/console/task/task-input.tsx @@ -30,6 +30,8 @@ import { IS_OFFLINE_EDITION } from "@/utils/edition"; import { readStoredTaskDialogParams, writeStoredTaskDialogParams } from "./task-dialog-params-storage"; import ModelSelect from "./model-select"; import { TaskSkillSelector } from "./task-skill-selector"; +import { TaskPluginSelector } from "./task-plugin-selector"; +import { fetchPluginListing, type PluginListItem } from "@/lib/agent-resources-api"; import { getTaskContentLimitErrorMessage, MAX_TASK_CONTENT_LENGTH } from "./task-content-limit"; interface RepoOption { @@ -70,6 +72,9 @@ export function TaskInput({ repos, onTaskCreated }: TaskInputProps) { const [selectedSkill, setSelectedSkill] = useState(defaultSkills); const [skillList, setSkillList] = useState([]); const [activeSkillTag, setActiveSkillTag] = useState("全部"); + const [pluginPopoverOpen, setPluginPopoverOpen] = useState(false); + const [pluginList, setPluginList] = useState([]); + const [selectedPlugin, setSelectedPlugin] = useState([]); // 运行参数状态(工具固定为 opencode) const [selectedModelId, setSelectedModelId] = useState(""); @@ -110,6 +115,7 @@ export function TaskInput({ repos, onTaskCreated }: TaskInputProps) { useEffect(() => { fetchSkillList(); + fetchPluginList(); }, []); @@ -127,6 +133,28 @@ export function TaskInput({ repos, onTaskCreated }: TaskInputProps) { }); }; + const fetchPluginList = async () => { + if (IS_OFFLINE_EDITION) { + return; + } + try { + const items = await fetchPluginListing(); + setPluginList(items); + } catch (err) { + // Plugin picker is optional/best-effort; warn rather than block the form. + toast.error((err as Error).message || '获取插件列表失败'); + } + }; + + const handlePluginChange = (pluginId: string, checked: boolean) => { + setSelectedPlugin(prev => { + if (checked) { + return prev.includes(pluginId) ? prev : [...prev, pluginId]; + } + return prev.filter(id => id !== pluginId); + }); + }; + const loadReposForAllIdentities = async (flush = false, targetIdentityId?: string) => { const targetIdentities = selectableIdentities.filter((identity) => { if (!identity.id) return false; @@ -295,6 +323,7 @@ export function TaskInput({ repos, onTaskCreated }: TaskInputProps) { }, extra: { skill_ids: selectedSkill, + plugin_ids: selectedPlugin, }, resource: { core: 2, @@ -647,6 +676,17 @@ export function TaskInput({ repos, onTaskCreated }: TaskInputProps) { labelClassName="hidden sm:block" /> )} + {!IS_OFFLINE_EDITION && ( + + )}
{!IS_OFFLINE_EDITION && ( diff --git a/frontend/src/components/console/task/task-plugin-selector.tsx b/frontend/src/components/console/task/task-plugin-selector.tsx new file mode 100644 index 00000000..65b88d30 --- /dev/null +++ b/frontend/src/components/console/task/task-plugin-selector.tsx @@ -0,0 +1,142 @@ +// TaskPluginSelector mirrors TaskSkillSelector but targets the plugin +// listing endpoint (GET /api/v1/plugins, see agent-resources slim spec §7.4). +// +// Plugins use a flat list (no tag tabs) because the listing surface is much +// smaller than skills and the backend does not group them by tag. Like the +// skill picker, plugins flagged `is_force_delivery=true` render as +// checked-and-disabled chips with a 强制下发 badge — the backend re-injects +// these IDs so the form does not submit them. + +import { Badge } from "@/components/ui/badge" +import { Button } from "@/components/ui/button" +import { Checkbox } from "@/components/ui/checkbox" +import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover" +import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip" +import type { PluginListItem } from "@/lib/agent-resources-api" +import { cn } from "@/lib/utils" +import { IconPlug } from "@tabler/icons-react" + +interface TaskPluginSelectorProps { + open: boolean + onOpenChange: (open: boolean) => void + /** Plugin IDs currently selected by the user (excludes force-delivered ones). */ + selectedPlugins: string[] + plugins: PluginListItem[] + /** Called with the toggled plugin id and the new checked state. */ + onPluginChange: (pluginId: string, checked: boolean) => void + triggerClassName?: string + labelClassName?: string +} + +interface PluginRowProps { + plugin: PluginListItem + selectedPlugins: string[] + onPluginChange: (pluginId: string, checked: boolean) => void +} + +function PluginRow({ plugin, selectedPlugins, onPluginChange }: PluginRowProps) { + if (!plugin.id) { + return null + } + + const isForceDelivery = plugin.is_force_delivery + const isChecked = isForceDelivery || selectedPlugins.includes(plugin.id) + + return ( +
{ + if (isForceDelivery) { + return + } + onPluginChange(plugin.id, !isChecked) + }} + > + +
+
+ {plugin.name} + {isForceDelivery && ( + + + + 强制下发 + + + 由管理员强制下发,无需选择 + + )} +
+ {plugin.description && ( +
+ {plugin.description} +
+ )} +
+
+ ) +} + +export function TaskPluginSelector({ + open, + onOpenChange, + selectedPlugins, + plugins, + onPluginChange, + triggerClassName, + labelClassName, +}: TaskPluginSelectorProps) { + // Hide force-delivery plugins entirely — backend injects them server-side + // regardless of user selection, so showing them in the picker is just noise. + const visiblePlugins = plugins.filter((p) => !p.is_force_delivery) + return ( + + + + + +
+ {visiblePlugins.length === 0 ? ( +
+ 暂无可用插件 +
+ ) : ( + visiblePlugins.map((plugin) => ( + + )) + )} +
+
+
+ ) +} diff --git a/frontend/src/components/console/task/task-skill-selector.tsx b/frontend/src/components/console/task/task-skill-selector.tsx index c9e22f24..3bc5d83e 100644 --- a/frontend/src/components/console/task/task-skill-selector.tsx +++ b/frontend/src/components/console/task/task-skill-selector.tsx @@ -1,19 +1,31 @@ import type { DomainSkill } from "@/api/Api" +import { Badge } from "@/components/ui/badge" import { Button } from "@/components/ui/button" import { Checkbox } from "@/components/ui/checkbox" import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover" import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs" +import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip" import { cn } from "@/lib/utils" import { getSkillTagIcon } from "@/utils/common" import { defaultSkills } from "@/utils/config" import { IconChevronLeft, IconChevronRight, IconPuzzle } from "@tabler/icons-react" import { useCallback, useEffect, useRef, useState } from "react" +/** + * SkillForPicker augments the swagger-generated DomainSkill with the + * `is_force_delivery` flag returned by /api/v1/skills (see + * lib/agent-resources-api.ts SkillListItem). The picker treats + * force-delivered skills as visible-but-disabled chips so the user + * knows about the admin-mandated dependency without being able to + * un-tick it (the backend re-injects these IDs server-side). + */ +type SkillForPicker = DomainSkill & { is_force_delivery?: boolean } + interface TaskSkillSelectorProps { open: boolean onOpenChange: (open: boolean) => void selectedSkills: string[] - skills: DomainSkill[] + skills: SkillForPicker[] skillTags: string[] activeSkillTag: string onActiveSkillTagChange: (tag: string) => void @@ -23,7 +35,7 @@ interface TaskSkillSelectorProps { } interface SkillItemProps { - skill: DomainSkill + skill: SkillForPicker selectedSkills: string[] onSkillChange: (skillId: string, checked: boolean) => void } @@ -33,16 +45,51 @@ function SkillItem({ skill, selectedSkills, onSkillChange }: SkillItemProps) { return null } - const isChecked = selectedSkills.includes(skill.id) + const isForceDelivery = !!skill.is_force_delivery + // Force-delivered + hard-coded legacy default skills are both shown as + // checked-and-disabled. Force-delivered skills are presented as "checked" + // regardless of the parent's selectedSkills state because the backend + // injects them server-side and we do not want users to see an unchecked + // tickbox for something they cannot opt out of. + const isLegacyDefault = defaultSkills.includes(skill.id) + const isDisabled = isLegacyDefault || isForceDelivery + const isChecked = isForceDelivery || selectedSkills.includes(skill.id) return (
onSkillChange(skill.id!, !isChecked)} + className={cn( + "flex flex-row items-center gap-2 rounded-md px-2 py-1", + isDisabled + ? "cursor-not-allowed opacity-80" + : "cursor-pointer hover:bg-accent" + )} + onClick={() => { + if (isDisabled) { + return + } + onSkillChange(skill.id!, !isChecked) + }} > - -
-
{skill.name}
+ +
+
+ {skill.name} + {isForceDelivery && ( + + + + 强制下发 + + + + 由管理员强制下发,无需选择 + + + )} +
{skill.description}
@@ -176,6 +223,7 @@ export function TaskSkillSelector({ className="mt-0 min-h-0 flex-1 overflow-y-auto rounded-md border bg-background p-1" > {skills + .filter((skill) => !skill.is_force_delivery) .filter((skill) => tag === "全部" || (skill.tags || []).includes(tag)) .map((skill) => ( = { + code: number + message: string + data: T +} + +async function request(url: string, init?: RequestInit): Promise { + const res = await fetch(url, { + credentials: "include", + ...(init ?? {}), + headers: { + ...(init?.body && typeof init.body === "string" + ? { "Content-Type": "application/json" } + : {}), + ...(init?.headers ?? {}), + }, + }) + if (res.status === 401) { + if ( + window.location.pathname.includes("/console") || + window.location.pathname.includes("/manager") + ) { + window.location.href = "/login" + } + throw new Error("未登录") + } + if (!res.ok) { + throw new Error(`HTTP ${res.status}: ${res.statusText}`) + } + const json = (await res.json()) as ApiResponse + if (json.code !== 0) { + throw new Error(json.message || "请求失败") + } + return json.data +} + +// ---- Task-creation pickers (skills / plugins listing) ---- +// +// The /api/v1/skills and /api/v1/plugins listing endpoints (mcai-backend, see +// agent-resources slim spec §7.4) return a flat array of "ready-to-pick" +// items: only active, non-orphan resources. + +/** Item returned by GET /api/v1/plugins (task-creation picker). */ +export type PluginListItem = { + id: string + name: string + description: string + entry: string + active_version?: string + is_force_delivery: boolean +} + +export function fetchPluginListing(): Promise { + return request(`/api/v1/plugins`).then( + (data) => data ?? [] + ) +} + +/** Item returned by GET /api/v1/skills (task-creation picker). */ +export type SkillListItem = { + id: string + name: string + description?: string + tags?: string[] + categories?: string[] + args_schema?: Record + content?: string + /** Skill ID surfaced by the swagger model — kept for backward compatibility. */ + skill_id?: string + is_force_delivery?: boolean +} From eda7d60e4f3616b431842b1e098ae99519b5e84a Mon Sep 17 00:00:00 2001 From: xmv97 Date: Fri, 5 Jun 2026 17:29:48 +0800 Subject: [PATCH 10/11] chore(swagger+misc): regen swagger plus drive-by edits Mixed commit: regenerated swagger.json alongside unrelated small edits in adjacent packages (team_dashboard / asr / clickhouse / speech / doubao / config). Preserved as-is because splitting would require touching the generated swagger blob. --- backend/docs/swagger.json | 142 +++++++++++++++++++++++++++++++ backend/domain/team_dashboard.go | 26 +++--- backend/pkg/asr/type.go | 2 +- backend/pkg/clickhouse/client.go | 12 +-- 4 files changed, 162 insertions(+), 20 deletions(-) diff --git a/backend/docs/swagger.json b/backend/docs/swagger.json index f4a7c6eb..e9e2c9c3 100644 --- a/backend/docs/swagger.json +++ b/backend/docs/swagger.json @@ -4,6 +4,55 @@ "contact": {} }, "paths": { + "/api/v1/plugins": { + "get": { + "security": [ + { + "MonkeyCodeAIAuth": [] + } + ], + "description": "获取所有未删除、非孤儿且具备 active_version 的 Plugins,供任务创建器选用(仅 OpenCode 真正下发)", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "【公共】plugin" + ], + "summary": "获取已启用的 Plugins 列表", + "responses": { + "200": { + "description": "获取成功", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.PluginListItem" + } + } + } + } + ] + } + }, + "500": { + "description": "服务器内部错误", + "schema": { + "$ref": "#/definitions/web.Resp" + } + } + } + } + }, "/api/v1/public/captcha/challenge": { "post": { "description": "CreateCaptcha", @@ -61,6 +110,55 @@ } } }, + "/api/v1/skills": { + "get": { + "security": [ + { + "MonkeyCodeAIAuth": [] + } + ], + "description": "获取所有未删除、非孤儿且具备 active_version 的 Skills,供任务创建器选用", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "【公共】skill" + ], + "summary": "获取已启用的 Skills 列表", + "responses": { + "200": { + "description": "获取成功", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.SkillListItem" + } + } + } + } + ] + } + }, + "500": { + "description": "服务器内部错误", + "schema": { + "$ref": "#/definitions/web.Resp" + } + } + } + } + }, "/api/v1/teams/admin": { "post": { "security": [ @@ -10420,6 +10518,29 @@ } } }, + "domain.PluginListItem": { + "type": "object", + "properties": { + "active_version": { + "type": "string" + }, + "description": { + "type": "string" + }, + "entry": { + "type": "string" + }, + "id": { + "type": "string" + }, + "is_force_delivery": { + "type": "boolean" + }, + "name": { + "type": "string" + } + } + }, "domain.Project": { "type": "object", "properties": { @@ -10862,6 +10983,26 @@ } } }, + "domain.SkillListItem": { + "type": "object", + "properties": { + "active_version": { + "type": "string" + }, + "description": { + "type": "string" + }, + "id": { + "type": "string" + }, + "is_force_delivery": { + "type": "boolean" + }, + "name": { + "type": "string" + } + } + }, "domain.SpeechRecognitionData": { "type": "object", "properties": { @@ -12608,6 +12749,7 @@ }, "types.ConditionStatus": { "type": "integer", + "format": "int32", "enum": [ 0, 1, diff --git a/backend/domain/team_dashboard.go b/backend/domain/team_dashboard.go index acdb5734..c62185ff 100644 --- a/backend/domain/team_dashboard.go +++ b/backend/domain/team_dashboard.go @@ -134,19 +134,19 @@ type TeamDashboardListReq struct { type TeamProjectListResp struct { Projects []*TeamProjectItem `json:"projects"` - Page *db.Cursor `json:"page"` + Page *db.Cursor `json:"page"` } type TeamProjectItem struct { - ID uuid.UUID `json:"id"` - Name string `json:"name"` - RepoURL string `json:"repo_url"` - Branch string `json:"branch"` - Creator *User `json:"creator"` - TaskCount int `json:"task_count"` - IssueCount int `json:"issue_count"` - CreatedAt int64 `json:"created_at"` - UpdatedAt int64 `json:"updated_at"` + ID uuid.UUID `json:"id"` + Name string `json:"name"` + RepoURL string `json:"repo_url"` + Branch string `json:"branch"` + Creator *User `json:"creator"` + TaskCount int `json:"task_count"` + IssueCount int `json:"issue_count"` + CreatedAt int64 `json:"created_at"` + UpdatedAt int64 `json:"updated_at"` } type TeamTaskListResp struct { @@ -169,7 +169,7 @@ type TeamTaskItem struct { type TeamConversationListResp struct { Conversations []*TeamConversationItem `json:"conversations"` - Page *db.Cursor `json:"page"` + Page *db.Cursor `json:"page"` } type TeamConversationItem struct { @@ -178,8 +178,8 @@ type TeamConversationItem struct { TaskTitle string `json:"task_title"` ProjectID uuid.UUID `json:"project_id"` ProjectName string `json:"project_name"` - Creator *User `json:"creator"` - Content string `json:"content"` + Creator *User `json:"creator"` + Content string `json:"content"` AttachmentCount int `json:"attachment_count"` CreatedAt int64 `json:"created_at"` } diff --git a/backend/pkg/asr/type.go b/backend/pkg/asr/type.go index 3e64a2c9..0998c6b0 100644 --- a/backend/pkg/asr/type.go +++ b/backend/pkg/asr/type.go @@ -19,7 +19,7 @@ type Event struct { Type EventType Index int // partial / final 携带,句子序号,从 1 开始 Text string // partial / final 携带 - Logid string // ready / error 携带,远端 trace id,排障必备 + Logid string // ready / error 携带,远端 trace id,排障必备 Error *Error // error 携带 Timestamp int64 // 服务端时间(ms) } diff --git a/backend/pkg/clickhouse/client.go b/backend/pkg/clickhouse/client.go index 286ccca1..d344bc29 100644 --- a/backend/pkg/clickhouse/client.go +++ b/backend/pkg/clickhouse/client.go @@ -221,12 +221,12 @@ type TeamConversationListQuery struct { } type TeamConversationRow struct { - TaskID string - TS time.Time - Event string - Kind string - TurnSeq uint32 - Data string + TaskID string + TS time.Time + Event string + Kind string + TurnSeq uint32 + Data string MsgSeqStart uint64 MsgSeqEnd uint64 } From 031573e9e03025597ffd9d748a7d56a8d22b4ba7 Mon Sep 17 00:00:00 2001 From: xmv97 Date: Sat, 6 Jun 2026 17:32:01 +0800 Subject: [PATCH 11/11] chore(swagger+misc): regen swagger plus drive-by edits Mixed commit: regenerated swagger.json alongside unrelated small edits in adjacent packages (team_dashboard / asr / clickhouse / speech / doubao / config). Preserved as-is because splitting would require touching the generated swagger blob. --- backend/biz/task/handler/v1/speech.go | 14 +++++++------- backend/biz/task/handler/v1/task.go | 1 - backend/config/config.go | 6 +++--- backend/pkg/doubao/frame.go | 18 +++++++++++------- 4 files changed, 21 insertions(+), 18 deletions(-) diff --git a/backend/biz/task/handler/v1/speech.go b/backend/biz/task/handler/v1/speech.go index 63e91c0a..cbd5b37c 100644 --- a/backend/biz/task/handler/v1/speech.go +++ b/backend/biz/task/handler/v1/speech.go @@ -281,13 +281,13 @@ var speechStreamAllowedFormats = map[string]struct{}{ // @Description - POST /speech-to-text:整段录音 → SSE 单段结果,适合短语音 ≤60s // @Description - 本接口:WS 双向实时流,支持长语音、句级 final、可被打断,适合 Web/移动端边说边显示 // @Description -// @Tags 【用户】任务管理 -// @Security MonkeyCodeAIAuth -// @Param start body domain.SpeechStreamStartReq false "[WS 协议] 客户端连接后首帧 JSON Text 控制消息 schema;不是 HTTP body,仅供前端代码生成 TS 类型,实际通过 WS Text 帧发送" -// @Success 101 {object} domain.SpeechStreamEvent "WebSocket 升级成功;此后通过 WS 帧通信,事件结构见上方说明" -// @Failure 401 {object} web.Resp "未授权" -// @Failure 500 {object} web.Resp "服务器内部错误(ASR 服务未配置等)" -// @Router /api/v1/users/tasks/speech-to-text-stream [get] +// @Tags 【用户】任务管理 +// @Security MonkeyCodeAIAuth +// @Param start body domain.SpeechStreamStartReq false "[WS 协议] 客户端连接后首帧 JSON Text 控制消息 schema;不是 HTTP body,仅供前端代码生成 TS 类型,实际通过 WS Text 帧发送" +// @Success 101 {object} domain.SpeechStreamEvent "WebSocket 升级成功;此后通过 WS 帧通信,事件结构见上方说明" +// @Failure 401 {object} web.Resp "未授权" +// @Failure 500 {object} web.Resp "服务器内部错误(ASR 服务未配置等)" +// @Router /api/v1/users/tasks/speech-to-text-stream [get] func (h *TaskHandler) SpeechToTextStream(c *web.Context) error { logger := h.logger.With("fn", "task.speech_to_text_stream") diff --git a/backend/biz/task/handler/v1/task.go b/backend/biz/task/handler/v1/task.go index 0d3921c1..3b8ac321 100644 --- a/backend/biz/task/handler/v1/task.go +++ b/backend/biz/task/handler/v1/task.go @@ -822,4 +822,3 @@ func (h *TaskHandler) ping( } } } - diff --git a/backend/config/config.go b/backend/config/config.go index 9a9a1ffa..91ed1044 100644 --- a/backend/config/config.go +++ b/backend/config/config.go @@ -60,9 +60,9 @@ type Config struct { // Aliyun mirrors mcai-backend's aliyun.public_oss block so the agent- // resources Resolver can fall back to that bucket when ObjectStorage is // disabled (the same OSS that admin-new writes assets into). Optional. - Aliyun AliyunConfig `mapstructure:"aliyun"` - StaticFiles StaticFilesConfig `mapstructure:"static_files"` - HostInstaller HostInstaller `mapstructure:"host_installer"` + Aliyun AliyunConfig `mapstructure:"aliyun"` + StaticFiles StaticFilesConfig `mapstructure:"static_files"` + HostInstaller HostInstaller `mapstructure:"host_installer"` // Context7 API 配置 Context7ApiKey string `mapstructure:"context7_api_key"` diff --git a/backend/pkg/doubao/frame.go b/backend/pkg/doubao/frame.go index c54bff22..be1bb4e1 100644 --- a/backend/pkg/doubao/frame.go +++ b/backend/pkg/doubao/frame.go @@ -32,10 +32,11 @@ func gzipDecompress(in []byte) ([]byte, error) { } // buildHeader 拼装 4 字节固定头。 -// byte0: ProtocolVersion(4b) | HeaderSize(4b) -// byte1: MessageType(4b) | MessageTypeSpecificFlags(4b) -// byte2: Serialization(4b) | Compression(4b) -// byte3: Reserved (0x00) +// +// byte0: ProtocolVersion(4b) | HeaderSize(4b) +// byte1: MessageType(4b) | MessageTypeSpecificFlags(4b) +// byte2: Serialization(4b) | Compression(4b) +// byte3: Reserved (0x00) func buildHeader(msgType, flags byte) []byte { return []byte{ (protocolVersion << 4) | headerSizeValue, @@ -79,11 +80,14 @@ func encodeAudioRequest(seq int32, audio []byte) []byte { // parseFrame 解析服务端下发的 frame。 // // 通用 frame 结构: -// header(4) + [sequence(4)?] + payload_size_or_error_code(4) + [error_size(4)?] + payload +// +// header(4) + [sequence(4)?] + payload_size_or_error_code(4) + [error_size(4)?] + payload // // flag 位决定后续字段: -// bit0 set → 有 sequence (4B int32 BE) -// bit1 set → 是最后一包 +// +// bit0 set → 有 sequence (4B int32 BE) +// bit1 set → 是最后一包 +// // messageType=msgTypeServerError 时 payload 之前先有 error_code(4) + error_size(4)。 func parseFrame(msg []byte) (*parsedFrame, error) { if len(msg) < 4 {