diff --git a/backend/Makefile b/backend/Makefile index 45a13a64..190b7d4f 100644 --- a/backend/Makefile +++ b/backend/Makefile @@ -9,7 +9,7 @@ BUILD_TIME=${shell date -u +"%Y-%m-%dT%H:%M:%SZ"} GIT_COMMIT=${shell git rev-parse HEAD} # make build PLATFORM= TAG= OUTPUT= GOCACHE= -image: +image: swag wire docker buildx build \ -f build/Dockerfile \ --build-arg GOCACHE=${GOCACHE} \ diff --git a/backend/cmd/server/wire_gen.go b/backend/cmd/server/wire_gen.go index 534d64c1..64bf52ff 100644 --- a/backend/cmd/server/wire_gen.go +++ b/backend/cmd/server/wire_gen.go @@ -1,6 +1,6 @@ // Code generated by Wire. DO NOT EDIT. -//go:generate go run -mod=mod github.com/google/wire/cmd/wire +//go:generate go run github.com/google/wire/cmd/wire //go:build !wireinject // +build !wireinject @@ -89,7 +89,7 @@ func newServer() (*Server, error) { activeMiddleware := middleware.NewActiveMiddleware(redisClient, slogLogger) v1Handler := v1.NewV1Handler(slogLogger, web, llmProxy, proxyUsecase, openAIUsecase, extensionUsecase, userUsecase, proxyMiddleware, activeMiddleware, configConfig) modelUsecase := usecase4.NewModelUsecase(slogLogger, modelRepo, configConfig) - authMiddleware := middleware.NewAuthMiddleware(sessionSession, slogLogger) + authMiddleware := middleware.NewAuthMiddleware(userUsecase, sessionSession, slogLogger) readOnlyMiddleware := middleware.NewReadOnlyMiddleware(configConfig) modelHandler := v1_2.NewModelHandler(web, modelUsecase, authMiddleware, activeMiddleware, readOnlyMiddleware, slogLogger) securityScanningUsecase := usecase5.NewSecurityScanningUsecase(securityScanningRepo) diff --git a/backend/db/admin.go b/backend/db/admin.go index 8d7eca2f..a64bb1b0 100644 --- a/backend/db/admin.go +++ b/backend/db/admin.go @@ -41,9 +41,19 @@ type Admin struct { type AdminEdges struct { // LoginHistories holds the value of the login_histories edge. LoginHistories []*AdminLoginHistory `json:"login_histories,omitempty"` + // Myusergroups holds the value of the myusergroups edge. + Myusergroups []*UserGroup `json:"myusergroups,omitempty"` + // Usergroups holds the value of the usergroups edge. + Usergroups []*UserGroup `json:"usergroups,omitempty"` + // Roles holds the value of the roles edge. + Roles []*Role `json:"roles,omitempty"` + // UserGroupAdmins holds the value of the user_group_admins edge. + UserGroupAdmins []*UserGroupAdmin `json:"user_group_admins,omitempty"` + // AdminRoles holds the value of the admin_roles edge. + AdminRoles []*AdminRole `json:"admin_roles,omitempty"` // loadedTypes holds the information for reporting if a // type was loaded (or requested) in eager-loading or not. - loadedTypes [1]bool + loadedTypes [6]bool } // LoginHistoriesOrErr returns the LoginHistories value or an error if the edge @@ -55,6 +65,51 @@ func (e AdminEdges) LoginHistoriesOrErr() ([]*AdminLoginHistory, error) { return nil, &NotLoadedError{edge: "login_histories"} } +// MyusergroupsOrErr returns the Myusergroups value or an error if the edge +// was not loaded in eager-loading. +func (e AdminEdges) MyusergroupsOrErr() ([]*UserGroup, error) { + if e.loadedTypes[1] { + return e.Myusergroups, nil + } + return nil, &NotLoadedError{edge: "myusergroups"} +} + +// UsergroupsOrErr returns the Usergroups value or an error if the edge +// was not loaded in eager-loading. +func (e AdminEdges) UsergroupsOrErr() ([]*UserGroup, error) { + if e.loadedTypes[2] { + return e.Usergroups, nil + } + return nil, &NotLoadedError{edge: "usergroups"} +} + +// RolesOrErr returns the Roles value or an error if the edge +// was not loaded in eager-loading. +func (e AdminEdges) RolesOrErr() ([]*Role, error) { + if e.loadedTypes[3] { + return e.Roles, nil + } + return nil, &NotLoadedError{edge: "roles"} +} + +// UserGroupAdminsOrErr returns the UserGroupAdmins value or an error if the edge +// was not loaded in eager-loading. +func (e AdminEdges) UserGroupAdminsOrErr() ([]*UserGroupAdmin, error) { + if e.loadedTypes[4] { + return e.UserGroupAdmins, nil + } + return nil, &NotLoadedError{edge: "user_group_admins"} +} + +// AdminRolesOrErr returns the AdminRoles value or an error if the edge +// was not loaded in eager-loading. +func (e AdminEdges) AdminRolesOrErr() ([]*AdminRole, error) { + if e.loadedTypes[5] { + return e.AdminRoles, nil + } + return nil, &NotLoadedError{edge: "admin_roles"} +} + // scanValues returns the types for scanning values from sql.Rows. func (*Admin) scanValues(columns []string) ([]any, error) { values := make([]any, len(columns)) @@ -141,6 +196,31 @@ func (a *Admin) QueryLoginHistories() *AdminLoginHistoryQuery { return NewAdminClient(a.config).QueryLoginHistories(a) } +// QueryMyusergroups queries the "myusergroups" edge of the Admin entity. +func (a *Admin) QueryMyusergroups() *UserGroupQuery { + return NewAdminClient(a.config).QueryMyusergroups(a) +} + +// QueryUsergroups queries the "usergroups" edge of the Admin entity. +func (a *Admin) QueryUsergroups() *UserGroupQuery { + return NewAdminClient(a.config).QueryUsergroups(a) +} + +// QueryRoles queries the "roles" edge of the Admin entity. +func (a *Admin) QueryRoles() *RoleQuery { + return NewAdminClient(a.config).QueryRoles(a) +} + +// QueryUserGroupAdmins queries the "user_group_admins" edge of the Admin entity. +func (a *Admin) QueryUserGroupAdmins() *UserGroupAdminQuery { + return NewAdminClient(a.config).QueryUserGroupAdmins(a) +} + +// QueryAdminRoles queries the "admin_roles" edge of the Admin entity. +func (a *Admin) QueryAdminRoles() *AdminRoleQuery { + return NewAdminClient(a.config).QueryAdminRoles(a) +} + // Update returns a builder for updating this Admin. // Note that you need to call Admin.Unwrap() before calling this method if this Admin // was returned from a transaction, and the transaction was committed or rolled back. diff --git a/backend/db/admin/admin.go b/backend/db/admin/admin.go index d89672a5..2fbf139e 100644 --- a/backend/db/admin/admin.go +++ b/backend/db/admin/admin.go @@ -28,6 +28,16 @@ const ( FieldUpdatedAt = "updated_at" // EdgeLoginHistories holds the string denoting the login_histories edge name in mutations. EdgeLoginHistories = "login_histories" + // EdgeMyusergroups holds the string denoting the myusergroups edge name in mutations. + EdgeMyusergroups = "myusergroups" + // EdgeUsergroups holds the string denoting the usergroups edge name in mutations. + EdgeUsergroups = "usergroups" + // EdgeRoles holds the string denoting the roles edge name in mutations. + EdgeRoles = "roles" + // EdgeUserGroupAdmins holds the string denoting the user_group_admins edge name in mutations. + EdgeUserGroupAdmins = "user_group_admins" + // EdgeAdminRoles holds the string denoting the admin_roles edge name in mutations. + EdgeAdminRoles = "admin_roles" // Table holds the table name of the admin in the database. Table = "admins" // LoginHistoriesTable is the table that holds the login_histories relation/edge. @@ -37,6 +47,37 @@ const ( LoginHistoriesInverseTable = "admin_login_histories" // LoginHistoriesColumn is the table column denoting the login_histories relation/edge. LoginHistoriesColumn = "admin_id" + // MyusergroupsTable is the table that holds the myusergroups relation/edge. + MyusergroupsTable = "user_groups" + // MyusergroupsInverseTable is the table name for the UserGroup entity. + // It exists in this package in order to avoid circular dependency with the "usergroup" package. + MyusergroupsInverseTable = "user_groups" + // MyusergroupsColumn is the table column denoting the myusergroups relation/edge. + MyusergroupsColumn = "admin_id" + // UsergroupsTable is the table that holds the usergroups relation/edge. The primary key declared below. + UsergroupsTable = "user_group_admins" + // UsergroupsInverseTable is the table name for the UserGroup entity. + // It exists in this package in order to avoid circular dependency with the "usergroup" package. + UsergroupsInverseTable = "user_groups" + // RolesTable is the table that holds the roles relation/edge. The primary key declared below. + RolesTable = "admin_roles" + // RolesInverseTable is the table name for the Role entity. + // It exists in this package in order to avoid circular dependency with the "role" package. + RolesInverseTable = "roles" + // UserGroupAdminsTable is the table that holds the user_group_admins relation/edge. + UserGroupAdminsTable = "user_group_admins" + // UserGroupAdminsInverseTable is the table name for the UserGroupAdmin entity. + // It exists in this package in order to avoid circular dependency with the "usergroupadmin" package. + UserGroupAdminsInverseTable = "user_group_admins" + // UserGroupAdminsColumn is the table column denoting the user_group_admins relation/edge. + UserGroupAdminsColumn = "admin_id" + // AdminRolesTable is the table that holds the admin_roles relation/edge. + AdminRolesTable = "admin_roles" + // AdminRolesInverseTable is the table name for the AdminRole entity. + // It exists in this package in order to avoid circular dependency with the "adminrole" package. + AdminRolesInverseTable = "admin_roles" + // AdminRolesColumn is the table column denoting the admin_roles relation/edge. + AdminRolesColumn = "admin_id" ) // Columns holds all SQL columns for admin fields. @@ -50,6 +91,15 @@ var Columns = []string{ FieldUpdatedAt, } +var ( + // UsergroupsPrimaryKey and UsergroupsColumn2 are the table columns denoting the + // primary key for the usergroups relation (M2M). + UsergroupsPrimaryKey = []string{"user_group_id", "admin_id"} + // RolesPrimaryKey and RolesColumn2 are the table columns denoting the + // primary key for the roles relation (M2M). + RolesPrimaryKey = []string{"role_id", "admin_id"} +) + // ValidColumn reports if the column name is valid (part of the table columns). func ValidColumn(column string) bool { for i := range Columns { @@ -122,6 +172,76 @@ func ByLoginHistories(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { sqlgraph.OrderByNeighborTerms(s, newLoginHistoriesStep(), append([]sql.OrderTerm{term}, terms...)...) } } + +// ByMyusergroupsCount orders the results by myusergroups count. +func ByMyusergroupsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newMyusergroupsStep(), opts...) + } +} + +// ByMyusergroups orders the results by myusergroups terms. +func ByMyusergroups(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newMyusergroupsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByUsergroupsCount orders the results by usergroups count. +func ByUsergroupsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newUsergroupsStep(), opts...) + } +} + +// ByUsergroups orders the results by usergroups terms. +func ByUsergroups(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newUsergroupsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByRolesCount orders the results by roles count. +func ByRolesCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newRolesStep(), opts...) + } +} + +// ByRoles orders the results by roles terms. +func ByRoles(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newRolesStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByUserGroupAdminsCount orders the results by user_group_admins count. +func ByUserGroupAdminsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newUserGroupAdminsStep(), opts...) + } +} + +// ByUserGroupAdmins orders the results by user_group_admins terms. +func ByUserGroupAdmins(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newUserGroupAdminsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByAdminRolesCount orders the results by admin_roles count. +func ByAdminRolesCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newAdminRolesStep(), opts...) + } +} + +// ByAdminRoles orders the results by admin_roles terms. +func ByAdminRoles(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newAdminRolesStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} func newLoginHistoriesStep() *sqlgraph.Step { return sqlgraph.NewStep( sqlgraph.From(Table, FieldID), @@ -129,3 +249,38 @@ func newLoginHistoriesStep() *sqlgraph.Step { sqlgraph.Edge(sqlgraph.O2M, false, LoginHistoriesTable, LoginHistoriesColumn), ) } +func newMyusergroupsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(MyusergroupsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, MyusergroupsTable, MyusergroupsColumn), + ) +} +func newUsergroupsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(UsergroupsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, UsergroupsTable, UsergroupsPrimaryKey...), + ) +} +func newRolesStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(RolesInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, RolesTable, RolesPrimaryKey...), + ) +} +func newUserGroupAdminsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(UserGroupAdminsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, UserGroupAdminsTable, UserGroupAdminsColumn), + ) +} +func newAdminRolesStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(AdminRolesInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, AdminRolesTable, AdminRolesColumn), + ) +} diff --git a/backend/db/admin/where.go b/backend/db/admin/where.go index cfc3cafd..8f424bd3 100644 --- a/backend/db/admin/where.go +++ b/backend/db/admin/where.go @@ -445,6 +445,121 @@ func HasLoginHistoriesWith(preds ...predicate.AdminLoginHistory) predicate.Admin }) } +// HasMyusergroups applies the HasEdge predicate on the "myusergroups" edge. +func HasMyusergroups() predicate.Admin { + return predicate.Admin(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, MyusergroupsTable, MyusergroupsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasMyusergroupsWith applies the HasEdge predicate on the "myusergroups" edge with a given conditions (other predicates). +func HasMyusergroupsWith(preds ...predicate.UserGroup) predicate.Admin { + return predicate.Admin(func(s *sql.Selector) { + step := newMyusergroupsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasUsergroups applies the HasEdge predicate on the "usergroups" edge. +func HasUsergroups() predicate.Admin { + return predicate.Admin(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, UsergroupsTable, UsergroupsPrimaryKey...), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasUsergroupsWith applies the HasEdge predicate on the "usergroups" edge with a given conditions (other predicates). +func HasUsergroupsWith(preds ...predicate.UserGroup) predicate.Admin { + return predicate.Admin(func(s *sql.Selector) { + step := newUsergroupsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasRoles applies the HasEdge predicate on the "roles" edge. +func HasRoles() predicate.Admin { + return predicate.Admin(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, RolesTable, RolesPrimaryKey...), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasRolesWith applies the HasEdge predicate on the "roles" edge with a given conditions (other predicates). +func HasRolesWith(preds ...predicate.Role) predicate.Admin { + return predicate.Admin(func(s *sql.Selector) { + step := newRolesStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasUserGroupAdmins applies the HasEdge predicate on the "user_group_admins" edge. +func HasUserGroupAdmins() predicate.Admin { + return predicate.Admin(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, UserGroupAdminsTable, UserGroupAdminsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasUserGroupAdminsWith applies the HasEdge predicate on the "user_group_admins" edge with a given conditions (other predicates). +func HasUserGroupAdminsWith(preds ...predicate.UserGroupAdmin) predicate.Admin { + return predicate.Admin(func(s *sql.Selector) { + step := newUserGroupAdminsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasAdminRoles applies the HasEdge predicate on the "admin_roles" edge. +func HasAdminRoles() predicate.Admin { + return predicate.Admin(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, AdminRolesTable, AdminRolesColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasAdminRolesWith applies the HasEdge predicate on the "admin_roles" edge with a given conditions (other predicates). +func HasAdminRolesWith(preds ...predicate.AdminRole) predicate.Admin { + return predicate.Admin(func(s *sql.Selector) { + step := newAdminRolesStep() + 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.Admin) predicate.Admin { return predicate.Admin(sql.AndPredicates(predicates...)) diff --git a/backend/db/admin_create.go b/backend/db/admin_create.go index f84718f4..0c562903 100644 --- a/backend/db/admin_create.go +++ b/backend/db/admin_create.go @@ -15,6 +15,10 @@ import ( "github.com/chaitin/MonkeyCode/backend/consts" "github.com/chaitin/MonkeyCode/backend/db/admin" "github.com/chaitin/MonkeyCode/backend/db/adminloginhistory" + "github.com/chaitin/MonkeyCode/backend/db/adminrole" + "github.com/chaitin/MonkeyCode/backend/db/role" + "github.com/chaitin/MonkeyCode/backend/db/usergroup" + "github.com/chaitin/MonkeyCode/backend/db/usergroupadmin" "github.com/google/uuid" ) @@ -107,6 +111,81 @@ func (ac *AdminCreate) AddLoginHistories(a ...*AdminLoginHistory) *AdminCreate { return ac.AddLoginHistoryIDs(ids...) } +// AddMyusergroupIDs adds the "myusergroups" edge to the UserGroup entity by IDs. +func (ac *AdminCreate) AddMyusergroupIDs(ids ...uuid.UUID) *AdminCreate { + ac.mutation.AddMyusergroupIDs(ids...) + return ac +} + +// AddMyusergroups adds the "myusergroups" edges to the UserGroup entity. +func (ac *AdminCreate) AddMyusergroups(u ...*UserGroup) *AdminCreate { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return ac.AddMyusergroupIDs(ids...) +} + +// AddUsergroupIDs adds the "usergroups" edge to the UserGroup entity by IDs. +func (ac *AdminCreate) AddUsergroupIDs(ids ...uuid.UUID) *AdminCreate { + ac.mutation.AddUsergroupIDs(ids...) + return ac +} + +// AddUsergroups adds the "usergroups" edges to the UserGroup entity. +func (ac *AdminCreate) AddUsergroups(u ...*UserGroup) *AdminCreate { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return ac.AddUsergroupIDs(ids...) +} + +// AddRoleIDs adds the "roles" edge to the Role entity by IDs. +func (ac *AdminCreate) AddRoleIDs(ids ...int64) *AdminCreate { + ac.mutation.AddRoleIDs(ids...) + return ac +} + +// AddRoles adds the "roles" edges to the Role entity. +func (ac *AdminCreate) AddRoles(r ...*Role) *AdminCreate { + ids := make([]int64, len(r)) + for i := range r { + ids[i] = r[i].ID + } + return ac.AddRoleIDs(ids...) +} + +// AddUserGroupAdminIDs adds the "user_group_admins" edge to the UserGroupAdmin entity by IDs. +func (ac *AdminCreate) AddUserGroupAdminIDs(ids ...uuid.UUID) *AdminCreate { + ac.mutation.AddUserGroupAdminIDs(ids...) + return ac +} + +// AddUserGroupAdmins adds the "user_group_admins" edges to the UserGroupAdmin entity. +func (ac *AdminCreate) AddUserGroupAdmins(u ...*UserGroupAdmin) *AdminCreate { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return ac.AddUserGroupAdminIDs(ids...) +} + +// AddAdminRoleIDs adds the "admin_roles" edge to the AdminRole entity by IDs. +func (ac *AdminCreate) AddAdminRoleIDs(ids ...uuid.UUID) *AdminCreate { + ac.mutation.AddAdminRoleIDs(ids...) + return ac +} + +// AddAdminRoles adds the "admin_roles" edges to the AdminRole entity. +func (ac *AdminCreate) AddAdminRoles(a ...*AdminRole) *AdminCreate { + ids := make([]uuid.UUID, len(a)) + for i := range a { + ids[i] = a[i].ID + } + return ac.AddAdminRoleIDs(ids...) +} + // Mutation returns the AdminMutation object of the builder. func (ac *AdminCreate) Mutation() *AdminMutation { return ac.mutation @@ -252,6 +331,86 @@ func (ac *AdminCreate) createSpec() (*Admin, *sqlgraph.CreateSpec) { } _spec.Edges = append(_spec.Edges, edge) } + if nodes := ac.mutation.MyusergroupsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: admin.MyusergroupsTable, + Columns: []string{admin.MyusergroupsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroup.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := ac.mutation.UsergroupsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: admin.UsergroupsTable, + Columns: admin.UsergroupsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroup.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := ac.mutation.RolesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: admin.RolesTable, + Columns: admin.RolesPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(role.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := ac.mutation.UserGroupAdminsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: admin.UserGroupAdminsTable, + Columns: []string{admin.UserGroupAdminsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroupadmin.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := ac.mutation.AdminRolesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: admin.AdminRolesTable, + Columns: []string{admin.AdminRolesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(adminrole.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } return _node, _spec } diff --git a/backend/db/admin_query.go b/backend/db/admin_query.go index 7e3558c2..967aba0e 100644 --- a/backend/db/admin_query.go +++ b/backend/db/admin_query.go @@ -15,19 +15,28 @@ import ( "entgo.io/ent/schema/field" "github.com/chaitin/MonkeyCode/backend/db/admin" "github.com/chaitin/MonkeyCode/backend/db/adminloginhistory" + "github.com/chaitin/MonkeyCode/backend/db/adminrole" "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/role" + "github.com/chaitin/MonkeyCode/backend/db/usergroup" + "github.com/chaitin/MonkeyCode/backend/db/usergroupadmin" "github.com/google/uuid" ) // AdminQuery is the builder for querying Admin entities. type AdminQuery struct { config - ctx *QueryContext - order []admin.OrderOption - inters []Interceptor - predicates []predicate.Admin - withLoginHistories *AdminLoginHistoryQuery - modifiers []func(*sql.Selector) + ctx *QueryContext + order []admin.OrderOption + inters []Interceptor + predicates []predicate.Admin + withLoginHistories *AdminLoginHistoryQuery + withMyusergroups *UserGroupQuery + withUsergroups *UserGroupQuery + withRoles *RoleQuery + withUserGroupAdmins *UserGroupAdminQuery + withAdminRoles *AdminRoleQuery + modifiers []func(*sql.Selector) // intermediate query (i.e. traversal path). sql *sql.Selector path func(context.Context) (*sql.Selector, error) @@ -86,6 +95,116 @@ func (aq *AdminQuery) QueryLoginHistories() *AdminLoginHistoryQuery { return query } +// QueryMyusergroups chains the current query on the "myusergroups" edge. +func (aq *AdminQuery) QueryMyusergroups() *UserGroupQuery { + query := (&UserGroupClient{config: aq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := aq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := aq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(admin.Table, admin.FieldID, selector), + sqlgraph.To(usergroup.Table, usergroup.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, admin.MyusergroupsTable, admin.MyusergroupsColumn), + ) + fromU = sqlgraph.SetNeighbors(aq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryUsergroups chains the current query on the "usergroups" edge. +func (aq *AdminQuery) QueryUsergroups() *UserGroupQuery { + query := (&UserGroupClient{config: aq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := aq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := aq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(admin.Table, admin.FieldID, selector), + sqlgraph.To(usergroup.Table, usergroup.FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, admin.UsergroupsTable, admin.UsergroupsPrimaryKey...), + ) + fromU = sqlgraph.SetNeighbors(aq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryRoles chains the current query on the "roles" edge. +func (aq *AdminQuery) QueryRoles() *RoleQuery { + query := (&RoleClient{config: aq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := aq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := aq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(admin.Table, admin.FieldID, selector), + sqlgraph.To(role.Table, role.FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, admin.RolesTable, admin.RolesPrimaryKey...), + ) + fromU = sqlgraph.SetNeighbors(aq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryUserGroupAdmins chains the current query on the "user_group_admins" edge. +func (aq *AdminQuery) QueryUserGroupAdmins() *UserGroupAdminQuery { + query := (&UserGroupAdminClient{config: aq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := aq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := aq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(admin.Table, admin.FieldID, selector), + sqlgraph.To(usergroupadmin.Table, usergroupadmin.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, admin.UserGroupAdminsTable, admin.UserGroupAdminsColumn), + ) + fromU = sqlgraph.SetNeighbors(aq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryAdminRoles chains the current query on the "admin_roles" edge. +func (aq *AdminQuery) QueryAdminRoles() *AdminRoleQuery { + query := (&AdminRoleClient{config: aq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := aq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := aq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(admin.Table, admin.FieldID, selector), + sqlgraph.To(adminrole.Table, adminrole.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, admin.AdminRolesTable, admin.AdminRolesColumn), + ) + fromU = sqlgraph.SetNeighbors(aq.driver.Dialect(), step) + return fromU, nil + } + return query +} + // First returns the first Admin entity from the query. // Returns a *NotFoundError when no Admin was found. func (aq *AdminQuery) First(ctx context.Context) (*Admin, error) { @@ -273,12 +392,17 @@ func (aq *AdminQuery) Clone() *AdminQuery { return nil } return &AdminQuery{ - config: aq.config, - ctx: aq.ctx.Clone(), - order: append([]admin.OrderOption{}, aq.order...), - inters: append([]Interceptor{}, aq.inters...), - predicates: append([]predicate.Admin{}, aq.predicates...), - withLoginHistories: aq.withLoginHistories.Clone(), + config: aq.config, + ctx: aq.ctx.Clone(), + order: append([]admin.OrderOption{}, aq.order...), + inters: append([]Interceptor{}, aq.inters...), + predicates: append([]predicate.Admin{}, aq.predicates...), + withLoginHistories: aq.withLoginHistories.Clone(), + withMyusergroups: aq.withMyusergroups.Clone(), + withUsergroups: aq.withUsergroups.Clone(), + withRoles: aq.withRoles.Clone(), + withUserGroupAdmins: aq.withUserGroupAdmins.Clone(), + withAdminRoles: aq.withAdminRoles.Clone(), // clone intermediate query. sql: aq.sql.Clone(), path: aq.path, @@ -297,6 +421,61 @@ func (aq *AdminQuery) WithLoginHistories(opts ...func(*AdminLoginHistoryQuery)) return aq } +// WithMyusergroups tells the query-builder to eager-load the nodes that are connected to +// the "myusergroups" edge. The optional arguments are used to configure the query builder of the edge. +func (aq *AdminQuery) WithMyusergroups(opts ...func(*UserGroupQuery)) *AdminQuery { + query := (&UserGroupClient{config: aq.config}).Query() + for _, opt := range opts { + opt(query) + } + aq.withMyusergroups = query + return aq +} + +// WithUsergroups tells the query-builder to eager-load the nodes that are connected to +// the "usergroups" edge. The optional arguments are used to configure the query builder of the edge. +func (aq *AdminQuery) WithUsergroups(opts ...func(*UserGroupQuery)) *AdminQuery { + query := (&UserGroupClient{config: aq.config}).Query() + for _, opt := range opts { + opt(query) + } + aq.withUsergroups = query + return aq +} + +// WithRoles tells the query-builder to eager-load the nodes that are connected to +// the "roles" edge. The optional arguments are used to configure the query builder of the edge. +func (aq *AdminQuery) WithRoles(opts ...func(*RoleQuery)) *AdminQuery { + query := (&RoleClient{config: aq.config}).Query() + for _, opt := range opts { + opt(query) + } + aq.withRoles = query + return aq +} + +// WithUserGroupAdmins tells the query-builder to eager-load the nodes that are connected to +// the "user_group_admins" edge. The optional arguments are used to configure the query builder of the edge. +func (aq *AdminQuery) WithUserGroupAdmins(opts ...func(*UserGroupAdminQuery)) *AdminQuery { + query := (&UserGroupAdminClient{config: aq.config}).Query() + for _, opt := range opts { + opt(query) + } + aq.withUserGroupAdmins = query + return aq +} + +// WithAdminRoles tells the query-builder to eager-load the nodes that are connected to +// the "admin_roles" edge. The optional arguments are used to configure the query builder of the edge. +func (aq *AdminQuery) WithAdminRoles(opts ...func(*AdminRoleQuery)) *AdminQuery { + query := (&AdminRoleClient{config: aq.config}).Query() + for _, opt := range opts { + opt(query) + } + aq.withAdminRoles = query + return aq +} + // 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. // @@ -375,8 +554,13 @@ func (aq *AdminQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Admin, var ( nodes = []*Admin{} _spec = aq.querySpec() - loadedTypes = [1]bool{ + loadedTypes = [6]bool{ aq.withLoginHistories != nil, + aq.withMyusergroups != nil, + aq.withUsergroups != nil, + aq.withRoles != nil, + aq.withUserGroupAdmins != nil, + aq.withAdminRoles != nil, } ) _spec.ScanValues = func(columns []string) ([]any, error) { @@ -407,6 +591,41 @@ func (aq *AdminQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Admin, return nil, err } } + if query := aq.withMyusergroups; query != nil { + if err := aq.loadMyusergroups(ctx, query, nodes, + func(n *Admin) { n.Edges.Myusergroups = []*UserGroup{} }, + func(n *Admin, e *UserGroup) { n.Edges.Myusergroups = append(n.Edges.Myusergroups, e) }); err != nil { + return nil, err + } + } + if query := aq.withUsergroups; query != nil { + if err := aq.loadUsergroups(ctx, query, nodes, + func(n *Admin) { n.Edges.Usergroups = []*UserGroup{} }, + func(n *Admin, e *UserGroup) { n.Edges.Usergroups = append(n.Edges.Usergroups, e) }); err != nil { + return nil, err + } + } + if query := aq.withRoles; query != nil { + if err := aq.loadRoles(ctx, query, nodes, + func(n *Admin) { n.Edges.Roles = []*Role{} }, + func(n *Admin, e *Role) { n.Edges.Roles = append(n.Edges.Roles, e) }); err != nil { + return nil, err + } + } + if query := aq.withUserGroupAdmins; query != nil { + if err := aq.loadUserGroupAdmins(ctx, query, nodes, + func(n *Admin) { n.Edges.UserGroupAdmins = []*UserGroupAdmin{} }, + func(n *Admin, e *UserGroupAdmin) { n.Edges.UserGroupAdmins = append(n.Edges.UserGroupAdmins, e) }); err != nil { + return nil, err + } + } + if query := aq.withAdminRoles; query != nil { + if err := aq.loadAdminRoles(ctx, query, nodes, + func(n *Admin) { n.Edges.AdminRoles = []*AdminRole{} }, + func(n *Admin, e *AdminRole) { n.Edges.AdminRoles = append(n.Edges.AdminRoles, e) }); err != nil { + return nil, err + } + } return nodes, nil } @@ -440,6 +659,218 @@ func (aq *AdminQuery) loadLoginHistories(ctx context.Context, query *AdminLoginH } return nil } +func (aq *AdminQuery) loadMyusergroups(ctx context.Context, query *UserGroupQuery, nodes []*Admin, init func(*Admin), assign func(*Admin, *UserGroup)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[uuid.UUID]*Admin) + 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(usergroup.FieldAdminID) + } + query.Where(predicate.UserGroup(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(admin.MyusergroupsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.AdminID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "admin_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} +func (aq *AdminQuery) loadUsergroups(ctx context.Context, query *UserGroupQuery, nodes []*Admin, init func(*Admin), assign func(*Admin, *UserGroup)) error { + edgeIDs := make([]driver.Value, len(nodes)) + byID := make(map[uuid.UUID]*Admin) + nids := make(map[uuid.UUID]map[*Admin]struct{}) + for i, node := range nodes { + edgeIDs[i] = node.ID + byID[node.ID] = node + if init != nil { + init(node) + } + } + query.Where(func(s *sql.Selector) { + joinT := sql.Table(admin.UsergroupsTable) + s.Join(joinT).On(s.C(usergroup.FieldID), joinT.C(admin.UsergroupsPrimaryKey[0])) + s.Where(sql.InValues(joinT.C(admin.UsergroupsPrimaryKey[1]), edgeIDs...)) + columns := s.SelectedColumns() + s.Select(joinT.C(admin.UsergroupsPrimaryKey[1])) + s.AppendSelect(columns...) + s.SetDistinct(false) + }) + if err := query.prepareQuery(ctx); err != nil { + return err + } + qr := QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + return query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) { + assign := spec.Assign + values := spec.ScanValues + spec.ScanValues = func(columns []string) ([]any, error) { + values, err := values(columns[1:]) + if err != nil { + return nil, err + } + return append([]any{new(uuid.UUID)}, values...), nil + } + spec.Assign = func(columns []string, values []any) error { + outValue := *values[0].(*uuid.UUID) + inValue := *values[1].(*uuid.UUID) + if nids[inValue] == nil { + nids[inValue] = map[*Admin]struct{}{byID[outValue]: {}} + return assign(columns[1:], values[1:]) + } + nids[inValue][byID[outValue]] = struct{}{} + return nil + } + }) + }) + neighbors, err := withInterceptors[[]*UserGroup](ctx, query, qr, query.inters) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nids[n.ID] + if !ok { + return fmt.Errorf(`unexpected "usergroups" node returned %v`, n.ID) + } + for kn := range nodes { + assign(kn, n) + } + } + return nil +} +func (aq *AdminQuery) loadRoles(ctx context.Context, query *RoleQuery, nodes []*Admin, init func(*Admin), assign func(*Admin, *Role)) error { + edgeIDs := make([]driver.Value, len(nodes)) + byID := make(map[uuid.UUID]*Admin) + nids := make(map[int64]map[*Admin]struct{}) + for i, node := range nodes { + edgeIDs[i] = node.ID + byID[node.ID] = node + if init != nil { + init(node) + } + } + query.Where(func(s *sql.Selector) { + joinT := sql.Table(admin.RolesTable) + s.Join(joinT).On(s.C(role.FieldID), joinT.C(admin.RolesPrimaryKey[0])) + s.Where(sql.InValues(joinT.C(admin.RolesPrimaryKey[1]), edgeIDs...)) + columns := s.SelectedColumns() + s.Select(joinT.C(admin.RolesPrimaryKey[1])) + s.AppendSelect(columns...) + s.SetDistinct(false) + }) + if err := query.prepareQuery(ctx); err != nil { + return err + } + qr := QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + return query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) { + assign := spec.Assign + values := spec.ScanValues + spec.ScanValues = func(columns []string) ([]any, error) { + values, err := values(columns[1:]) + if err != nil { + return nil, err + } + return append([]any{new(uuid.UUID)}, values...), nil + } + spec.Assign = func(columns []string, values []any) error { + outValue := *values[0].(*uuid.UUID) + inValue := values[1].(*sql.NullInt64).Int64 + if nids[inValue] == nil { + nids[inValue] = map[*Admin]struct{}{byID[outValue]: {}} + return assign(columns[1:], values[1:]) + } + nids[inValue][byID[outValue]] = struct{}{} + return nil + } + }) + }) + neighbors, err := withInterceptors[[]*Role](ctx, query, qr, query.inters) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nids[n.ID] + if !ok { + return fmt.Errorf(`unexpected "roles" node returned %v`, n.ID) + } + for kn := range nodes { + assign(kn, n) + } + } + return nil +} +func (aq *AdminQuery) loadUserGroupAdmins(ctx context.Context, query *UserGroupAdminQuery, nodes []*Admin, init func(*Admin), assign func(*Admin, *UserGroupAdmin)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[uuid.UUID]*Admin) + 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(usergroupadmin.FieldAdminID) + } + query.Where(predicate.UserGroupAdmin(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(admin.UserGroupAdminsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.AdminID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "admin_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} +func (aq *AdminQuery) loadAdminRoles(ctx context.Context, query *AdminRoleQuery, nodes []*Admin, init func(*Admin), assign func(*Admin, *AdminRole)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[uuid.UUID]*Admin) + 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(adminrole.FieldAdminID) + } + query.Where(predicate.AdminRole(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(admin.AdminRolesColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.AdminID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "admin_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} func (aq *AdminQuery) sqlCount(ctx context.Context) (int, error) { _spec := aq.querySpec() diff --git a/backend/db/admin_update.go b/backend/db/admin_update.go index 91280e22..9f642ca6 100644 --- a/backend/db/admin_update.go +++ b/backend/db/admin_update.go @@ -14,7 +14,11 @@ import ( "github.com/chaitin/MonkeyCode/backend/consts" "github.com/chaitin/MonkeyCode/backend/db/admin" "github.com/chaitin/MonkeyCode/backend/db/adminloginhistory" + "github.com/chaitin/MonkeyCode/backend/db/adminrole" "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/role" + "github.com/chaitin/MonkeyCode/backend/db/usergroup" + "github.com/chaitin/MonkeyCode/backend/db/usergroupadmin" "github.com/google/uuid" ) @@ -123,6 +127,81 @@ func (au *AdminUpdate) AddLoginHistories(a ...*AdminLoginHistory) *AdminUpdate { return au.AddLoginHistoryIDs(ids...) } +// AddMyusergroupIDs adds the "myusergroups" edge to the UserGroup entity by IDs. +func (au *AdminUpdate) AddMyusergroupIDs(ids ...uuid.UUID) *AdminUpdate { + au.mutation.AddMyusergroupIDs(ids...) + return au +} + +// AddMyusergroups adds the "myusergroups" edges to the UserGroup entity. +func (au *AdminUpdate) AddMyusergroups(u ...*UserGroup) *AdminUpdate { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return au.AddMyusergroupIDs(ids...) +} + +// AddUsergroupIDs adds the "usergroups" edge to the UserGroup entity by IDs. +func (au *AdminUpdate) AddUsergroupIDs(ids ...uuid.UUID) *AdminUpdate { + au.mutation.AddUsergroupIDs(ids...) + return au +} + +// AddUsergroups adds the "usergroups" edges to the UserGroup entity. +func (au *AdminUpdate) AddUsergroups(u ...*UserGroup) *AdminUpdate { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return au.AddUsergroupIDs(ids...) +} + +// AddRoleIDs adds the "roles" edge to the Role entity by IDs. +func (au *AdminUpdate) AddRoleIDs(ids ...int64) *AdminUpdate { + au.mutation.AddRoleIDs(ids...) + return au +} + +// AddRoles adds the "roles" edges to the Role entity. +func (au *AdminUpdate) AddRoles(r ...*Role) *AdminUpdate { + ids := make([]int64, len(r)) + for i := range r { + ids[i] = r[i].ID + } + return au.AddRoleIDs(ids...) +} + +// AddUserGroupAdminIDs adds the "user_group_admins" edge to the UserGroupAdmin entity by IDs. +func (au *AdminUpdate) AddUserGroupAdminIDs(ids ...uuid.UUID) *AdminUpdate { + au.mutation.AddUserGroupAdminIDs(ids...) + return au +} + +// AddUserGroupAdmins adds the "user_group_admins" edges to the UserGroupAdmin entity. +func (au *AdminUpdate) AddUserGroupAdmins(u ...*UserGroupAdmin) *AdminUpdate { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return au.AddUserGroupAdminIDs(ids...) +} + +// AddAdminRoleIDs adds the "admin_roles" edge to the AdminRole entity by IDs. +func (au *AdminUpdate) AddAdminRoleIDs(ids ...uuid.UUID) *AdminUpdate { + au.mutation.AddAdminRoleIDs(ids...) + return au +} + +// AddAdminRoles adds the "admin_roles" edges to the AdminRole entity. +func (au *AdminUpdate) AddAdminRoles(a ...*AdminRole) *AdminUpdate { + ids := make([]uuid.UUID, len(a)) + for i := range a { + ids[i] = a[i].ID + } + return au.AddAdminRoleIDs(ids...) +} + // Mutation returns the AdminMutation object of the builder. func (au *AdminUpdate) Mutation() *AdminMutation { return au.mutation @@ -149,6 +228,111 @@ func (au *AdminUpdate) RemoveLoginHistories(a ...*AdminLoginHistory) *AdminUpdat return au.RemoveLoginHistoryIDs(ids...) } +// ClearMyusergroups clears all "myusergroups" edges to the UserGroup entity. +func (au *AdminUpdate) ClearMyusergroups() *AdminUpdate { + au.mutation.ClearMyusergroups() + return au +} + +// RemoveMyusergroupIDs removes the "myusergroups" edge to UserGroup entities by IDs. +func (au *AdminUpdate) RemoveMyusergroupIDs(ids ...uuid.UUID) *AdminUpdate { + au.mutation.RemoveMyusergroupIDs(ids...) + return au +} + +// RemoveMyusergroups removes "myusergroups" edges to UserGroup entities. +func (au *AdminUpdate) RemoveMyusergroups(u ...*UserGroup) *AdminUpdate { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return au.RemoveMyusergroupIDs(ids...) +} + +// ClearUsergroups clears all "usergroups" edges to the UserGroup entity. +func (au *AdminUpdate) ClearUsergroups() *AdminUpdate { + au.mutation.ClearUsergroups() + return au +} + +// RemoveUsergroupIDs removes the "usergroups" edge to UserGroup entities by IDs. +func (au *AdminUpdate) RemoveUsergroupIDs(ids ...uuid.UUID) *AdminUpdate { + au.mutation.RemoveUsergroupIDs(ids...) + return au +} + +// RemoveUsergroups removes "usergroups" edges to UserGroup entities. +func (au *AdminUpdate) RemoveUsergroups(u ...*UserGroup) *AdminUpdate { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return au.RemoveUsergroupIDs(ids...) +} + +// ClearRoles clears all "roles" edges to the Role entity. +func (au *AdminUpdate) ClearRoles() *AdminUpdate { + au.mutation.ClearRoles() + return au +} + +// RemoveRoleIDs removes the "roles" edge to Role entities by IDs. +func (au *AdminUpdate) RemoveRoleIDs(ids ...int64) *AdminUpdate { + au.mutation.RemoveRoleIDs(ids...) + return au +} + +// RemoveRoles removes "roles" edges to Role entities. +func (au *AdminUpdate) RemoveRoles(r ...*Role) *AdminUpdate { + ids := make([]int64, len(r)) + for i := range r { + ids[i] = r[i].ID + } + return au.RemoveRoleIDs(ids...) +} + +// ClearUserGroupAdmins clears all "user_group_admins" edges to the UserGroupAdmin entity. +func (au *AdminUpdate) ClearUserGroupAdmins() *AdminUpdate { + au.mutation.ClearUserGroupAdmins() + return au +} + +// RemoveUserGroupAdminIDs removes the "user_group_admins" edge to UserGroupAdmin entities by IDs. +func (au *AdminUpdate) RemoveUserGroupAdminIDs(ids ...uuid.UUID) *AdminUpdate { + au.mutation.RemoveUserGroupAdminIDs(ids...) + return au +} + +// RemoveUserGroupAdmins removes "user_group_admins" edges to UserGroupAdmin entities. +func (au *AdminUpdate) RemoveUserGroupAdmins(u ...*UserGroupAdmin) *AdminUpdate { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return au.RemoveUserGroupAdminIDs(ids...) +} + +// ClearAdminRoles clears all "admin_roles" edges to the AdminRole entity. +func (au *AdminUpdate) ClearAdminRoles() *AdminUpdate { + au.mutation.ClearAdminRoles() + return au +} + +// RemoveAdminRoleIDs removes the "admin_roles" edge to AdminRole entities by IDs. +func (au *AdminUpdate) RemoveAdminRoleIDs(ids ...uuid.UUID) *AdminUpdate { + au.mutation.RemoveAdminRoleIDs(ids...) + return au +} + +// RemoveAdminRoles removes "admin_roles" edges to AdminRole entities. +func (au *AdminUpdate) RemoveAdminRoles(a ...*AdminRole) *AdminUpdate { + ids := make([]uuid.UUID, len(a)) + for i := range a { + ids[i] = a[i].ID + } + return au.RemoveAdminRoleIDs(ids...) +} + // Save executes the query and returns the number of nodes affected by the update operation. func (au *AdminUpdate) Save(ctx context.Context) (int, error) { au.defaults() @@ -263,6 +447,231 @@ func (au *AdminUpdate) sqlSave(ctx context.Context) (n int, err error) { } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if au.mutation.MyusergroupsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: admin.MyusergroupsTable, + Columns: []string{admin.MyusergroupsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroup.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := au.mutation.RemovedMyusergroupsIDs(); len(nodes) > 0 && !au.mutation.MyusergroupsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: admin.MyusergroupsTable, + Columns: []string{admin.MyusergroupsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroup.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 := au.mutation.MyusergroupsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: admin.MyusergroupsTable, + Columns: []string{admin.MyusergroupsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroup.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if au.mutation.UsergroupsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: admin.UsergroupsTable, + Columns: admin.UsergroupsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroup.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := au.mutation.RemovedUsergroupsIDs(); len(nodes) > 0 && !au.mutation.UsergroupsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: admin.UsergroupsTable, + Columns: admin.UsergroupsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroup.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 := au.mutation.UsergroupsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: admin.UsergroupsTable, + Columns: admin.UsergroupsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroup.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if au.mutation.RolesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: admin.RolesTable, + Columns: admin.RolesPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(role.FieldID, field.TypeInt64), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := au.mutation.RemovedRolesIDs(); len(nodes) > 0 && !au.mutation.RolesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: admin.RolesTable, + Columns: admin.RolesPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(role.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := au.mutation.RolesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: admin.RolesTable, + Columns: admin.RolesPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(role.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if au.mutation.UserGroupAdminsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: admin.UserGroupAdminsTable, + Columns: []string{admin.UserGroupAdminsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroupadmin.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := au.mutation.RemovedUserGroupAdminsIDs(); len(nodes) > 0 && !au.mutation.UserGroupAdminsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: admin.UserGroupAdminsTable, + Columns: []string{admin.UserGroupAdminsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroupadmin.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 := au.mutation.UserGroupAdminsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: admin.UserGroupAdminsTable, + Columns: []string{admin.UserGroupAdminsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroupadmin.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if au.mutation.AdminRolesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: admin.AdminRolesTable, + Columns: []string{admin.AdminRolesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(adminrole.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := au.mutation.RemovedAdminRolesIDs(); len(nodes) > 0 && !au.mutation.AdminRolesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: admin.AdminRolesTable, + Columns: []string{admin.AdminRolesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(adminrole.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 := au.mutation.AdminRolesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: admin.AdminRolesTable, + Columns: []string{admin.AdminRolesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(adminrole.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(au.modifiers...) if n, err = sqlgraph.UpdateNodes(ctx, au.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { @@ -376,6 +785,81 @@ func (auo *AdminUpdateOne) AddLoginHistories(a ...*AdminLoginHistory) *AdminUpda return auo.AddLoginHistoryIDs(ids...) } +// AddMyusergroupIDs adds the "myusergroups" edge to the UserGroup entity by IDs. +func (auo *AdminUpdateOne) AddMyusergroupIDs(ids ...uuid.UUID) *AdminUpdateOne { + auo.mutation.AddMyusergroupIDs(ids...) + return auo +} + +// AddMyusergroups adds the "myusergroups" edges to the UserGroup entity. +func (auo *AdminUpdateOne) AddMyusergroups(u ...*UserGroup) *AdminUpdateOne { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return auo.AddMyusergroupIDs(ids...) +} + +// AddUsergroupIDs adds the "usergroups" edge to the UserGroup entity by IDs. +func (auo *AdminUpdateOne) AddUsergroupIDs(ids ...uuid.UUID) *AdminUpdateOne { + auo.mutation.AddUsergroupIDs(ids...) + return auo +} + +// AddUsergroups adds the "usergroups" edges to the UserGroup entity. +func (auo *AdminUpdateOne) AddUsergroups(u ...*UserGroup) *AdminUpdateOne { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return auo.AddUsergroupIDs(ids...) +} + +// AddRoleIDs adds the "roles" edge to the Role entity by IDs. +func (auo *AdminUpdateOne) AddRoleIDs(ids ...int64) *AdminUpdateOne { + auo.mutation.AddRoleIDs(ids...) + return auo +} + +// AddRoles adds the "roles" edges to the Role entity. +func (auo *AdminUpdateOne) AddRoles(r ...*Role) *AdminUpdateOne { + ids := make([]int64, len(r)) + for i := range r { + ids[i] = r[i].ID + } + return auo.AddRoleIDs(ids...) +} + +// AddUserGroupAdminIDs adds the "user_group_admins" edge to the UserGroupAdmin entity by IDs. +func (auo *AdminUpdateOne) AddUserGroupAdminIDs(ids ...uuid.UUID) *AdminUpdateOne { + auo.mutation.AddUserGroupAdminIDs(ids...) + return auo +} + +// AddUserGroupAdmins adds the "user_group_admins" edges to the UserGroupAdmin entity. +func (auo *AdminUpdateOne) AddUserGroupAdmins(u ...*UserGroupAdmin) *AdminUpdateOne { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return auo.AddUserGroupAdminIDs(ids...) +} + +// AddAdminRoleIDs adds the "admin_roles" edge to the AdminRole entity by IDs. +func (auo *AdminUpdateOne) AddAdminRoleIDs(ids ...uuid.UUID) *AdminUpdateOne { + auo.mutation.AddAdminRoleIDs(ids...) + return auo +} + +// AddAdminRoles adds the "admin_roles" edges to the AdminRole entity. +func (auo *AdminUpdateOne) AddAdminRoles(a ...*AdminRole) *AdminUpdateOne { + ids := make([]uuid.UUID, len(a)) + for i := range a { + ids[i] = a[i].ID + } + return auo.AddAdminRoleIDs(ids...) +} + // Mutation returns the AdminMutation object of the builder. func (auo *AdminUpdateOne) Mutation() *AdminMutation { return auo.mutation @@ -402,6 +886,111 @@ func (auo *AdminUpdateOne) RemoveLoginHistories(a ...*AdminLoginHistory) *AdminU return auo.RemoveLoginHistoryIDs(ids...) } +// ClearMyusergroups clears all "myusergroups" edges to the UserGroup entity. +func (auo *AdminUpdateOne) ClearMyusergroups() *AdminUpdateOne { + auo.mutation.ClearMyusergroups() + return auo +} + +// RemoveMyusergroupIDs removes the "myusergroups" edge to UserGroup entities by IDs. +func (auo *AdminUpdateOne) RemoveMyusergroupIDs(ids ...uuid.UUID) *AdminUpdateOne { + auo.mutation.RemoveMyusergroupIDs(ids...) + return auo +} + +// RemoveMyusergroups removes "myusergroups" edges to UserGroup entities. +func (auo *AdminUpdateOne) RemoveMyusergroups(u ...*UserGroup) *AdminUpdateOne { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return auo.RemoveMyusergroupIDs(ids...) +} + +// ClearUsergroups clears all "usergroups" edges to the UserGroup entity. +func (auo *AdminUpdateOne) ClearUsergroups() *AdminUpdateOne { + auo.mutation.ClearUsergroups() + return auo +} + +// RemoveUsergroupIDs removes the "usergroups" edge to UserGroup entities by IDs. +func (auo *AdminUpdateOne) RemoveUsergroupIDs(ids ...uuid.UUID) *AdminUpdateOne { + auo.mutation.RemoveUsergroupIDs(ids...) + return auo +} + +// RemoveUsergroups removes "usergroups" edges to UserGroup entities. +func (auo *AdminUpdateOne) RemoveUsergroups(u ...*UserGroup) *AdminUpdateOne { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return auo.RemoveUsergroupIDs(ids...) +} + +// ClearRoles clears all "roles" edges to the Role entity. +func (auo *AdminUpdateOne) ClearRoles() *AdminUpdateOne { + auo.mutation.ClearRoles() + return auo +} + +// RemoveRoleIDs removes the "roles" edge to Role entities by IDs. +func (auo *AdminUpdateOne) RemoveRoleIDs(ids ...int64) *AdminUpdateOne { + auo.mutation.RemoveRoleIDs(ids...) + return auo +} + +// RemoveRoles removes "roles" edges to Role entities. +func (auo *AdminUpdateOne) RemoveRoles(r ...*Role) *AdminUpdateOne { + ids := make([]int64, len(r)) + for i := range r { + ids[i] = r[i].ID + } + return auo.RemoveRoleIDs(ids...) +} + +// ClearUserGroupAdmins clears all "user_group_admins" edges to the UserGroupAdmin entity. +func (auo *AdminUpdateOne) ClearUserGroupAdmins() *AdminUpdateOne { + auo.mutation.ClearUserGroupAdmins() + return auo +} + +// RemoveUserGroupAdminIDs removes the "user_group_admins" edge to UserGroupAdmin entities by IDs. +func (auo *AdminUpdateOne) RemoveUserGroupAdminIDs(ids ...uuid.UUID) *AdminUpdateOne { + auo.mutation.RemoveUserGroupAdminIDs(ids...) + return auo +} + +// RemoveUserGroupAdmins removes "user_group_admins" edges to UserGroupAdmin entities. +func (auo *AdminUpdateOne) RemoveUserGroupAdmins(u ...*UserGroupAdmin) *AdminUpdateOne { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return auo.RemoveUserGroupAdminIDs(ids...) +} + +// ClearAdminRoles clears all "admin_roles" edges to the AdminRole entity. +func (auo *AdminUpdateOne) ClearAdminRoles() *AdminUpdateOne { + auo.mutation.ClearAdminRoles() + return auo +} + +// RemoveAdminRoleIDs removes the "admin_roles" edge to AdminRole entities by IDs. +func (auo *AdminUpdateOne) RemoveAdminRoleIDs(ids ...uuid.UUID) *AdminUpdateOne { + auo.mutation.RemoveAdminRoleIDs(ids...) + return auo +} + +// RemoveAdminRoles removes "admin_roles" edges to AdminRole entities. +func (auo *AdminUpdateOne) RemoveAdminRoles(a ...*AdminRole) *AdminUpdateOne { + ids := make([]uuid.UUID, len(a)) + for i := range a { + ids[i] = a[i].ID + } + return auo.RemoveAdminRoleIDs(ids...) +} + // Where appends a list predicates to the AdminUpdate builder. func (auo *AdminUpdateOne) Where(ps ...predicate.Admin) *AdminUpdateOne { auo.mutation.Where(ps...) @@ -546,6 +1135,231 @@ func (auo *AdminUpdateOne) sqlSave(ctx context.Context) (_node *Admin, err error } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if auo.mutation.MyusergroupsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: admin.MyusergroupsTable, + Columns: []string{admin.MyusergroupsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroup.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := auo.mutation.RemovedMyusergroupsIDs(); len(nodes) > 0 && !auo.mutation.MyusergroupsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: admin.MyusergroupsTable, + Columns: []string{admin.MyusergroupsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroup.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 := auo.mutation.MyusergroupsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: admin.MyusergroupsTable, + Columns: []string{admin.MyusergroupsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroup.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if auo.mutation.UsergroupsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: admin.UsergroupsTable, + Columns: admin.UsergroupsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroup.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := auo.mutation.RemovedUsergroupsIDs(); len(nodes) > 0 && !auo.mutation.UsergroupsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: admin.UsergroupsTable, + Columns: admin.UsergroupsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroup.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 := auo.mutation.UsergroupsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: admin.UsergroupsTable, + Columns: admin.UsergroupsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroup.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if auo.mutation.RolesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: admin.RolesTable, + Columns: admin.RolesPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(role.FieldID, field.TypeInt64), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := auo.mutation.RemovedRolesIDs(); len(nodes) > 0 && !auo.mutation.RolesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: admin.RolesTable, + Columns: admin.RolesPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(role.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := auo.mutation.RolesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: admin.RolesTable, + Columns: admin.RolesPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(role.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if auo.mutation.UserGroupAdminsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: admin.UserGroupAdminsTable, + Columns: []string{admin.UserGroupAdminsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroupadmin.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := auo.mutation.RemovedUserGroupAdminsIDs(); len(nodes) > 0 && !auo.mutation.UserGroupAdminsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: admin.UserGroupAdminsTable, + Columns: []string{admin.UserGroupAdminsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroupadmin.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 := auo.mutation.UserGroupAdminsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: admin.UserGroupAdminsTable, + Columns: []string{admin.UserGroupAdminsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroupadmin.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if auo.mutation.AdminRolesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: admin.AdminRolesTable, + Columns: []string{admin.AdminRolesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(adminrole.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := auo.mutation.RemovedAdminRolesIDs(); len(nodes) > 0 && !auo.mutation.AdminRolesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: admin.AdminRolesTable, + Columns: []string{admin.AdminRolesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(adminrole.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 := auo.mutation.AdminRolesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: admin.AdminRolesTable, + Columns: []string{admin.AdminRolesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(adminrole.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(auo.modifiers...) _node = &Admin{config: auo.config} _spec.Assign = _node.assignValues diff --git a/backend/db/adminrole.go b/backend/db/adminrole.go new file mode 100644 index 00000000..fba06f5c --- /dev/null +++ b/backend/db/adminrole.go @@ -0,0 +1,163 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "fmt" + "strings" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/chaitin/MonkeyCode/backend/db/admin" + "github.com/chaitin/MonkeyCode/backend/db/adminrole" + "github.com/chaitin/MonkeyCode/backend/db/role" + "github.com/google/uuid" +) + +// AdminRole is the model entity for the AdminRole schema. +type AdminRole struct { + config `json:"-"` + // ID of the ent. + ID uuid.UUID `json:"id,omitempty"` + // AdminID holds the value of the "admin_id" field. + AdminID uuid.UUID `json:"admin_id,omitempty"` + // RoleID holds the value of the "role_id" field. + RoleID int64 `json:"role_id,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the AdminRoleQuery when eager-loading is set. + Edges AdminRoleEdges `json:"edges"` + selectValues sql.SelectValues +} + +// AdminRoleEdges holds the relations/edges for other nodes in the graph. +type AdminRoleEdges struct { + // Admin holds the value of the admin edge. + Admin *Admin `json:"admin,omitempty"` + // Role holds the value of the role edge. + Role *Role `json:"role,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool +} + +// AdminOrErr returns the Admin value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e AdminRoleEdges) AdminOrErr() (*Admin, error) { + if e.Admin != nil { + return e.Admin, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: admin.Label} + } + return nil, &NotLoadedError{edge: "admin"} +} + +// RoleOrErr returns the Role value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e AdminRoleEdges) RoleOrErr() (*Role, error) { + if e.Role != nil { + return e.Role, nil + } else if e.loadedTypes[1] { + return nil, &NotFoundError{label: role.Label} + } + return nil, &NotLoadedError{edge: "role"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*AdminRole) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case adminrole.FieldRoleID: + values[i] = new(sql.NullInt64) + case adminrole.FieldID, adminrole.FieldAdminID: + 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 AdminRole fields. +func (ar *AdminRole) 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 adminrole.FieldID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value != nil { + ar.ID = *value + } + case adminrole.FieldAdminID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field admin_id", values[i]) + } else if value != nil { + ar.AdminID = *value + } + case adminrole.FieldRoleID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field role_id", values[i]) + } else if value.Valid { + ar.RoleID = value.Int64 + } + default: + ar.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the AdminRole. +// This includes values selected through modifiers, order, etc. +func (ar *AdminRole) Value(name string) (ent.Value, error) { + return ar.selectValues.Get(name) +} + +// QueryAdmin queries the "admin" edge of the AdminRole entity. +func (ar *AdminRole) QueryAdmin() *AdminQuery { + return NewAdminRoleClient(ar.config).QueryAdmin(ar) +} + +// QueryRole queries the "role" edge of the AdminRole entity. +func (ar *AdminRole) QueryRole() *RoleQuery { + return NewAdminRoleClient(ar.config).QueryRole(ar) +} + +// Update returns a builder for updating this AdminRole. +// Note that you need to call AdminRole.Unwrap() before calling this method if this AdminRole +// was returned from a transaction, and the transaction was committed or rolled back. +func (ar *AdminRole) Update() *AdminRoleUpdateOne { + return NewAdminRoleClient(ar.config).UpdateOne(ar) +} + +// Unwrap unwraps the AdminRole 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 (ar *AdminRole) Unwrap() *AdminRole { + _tx, ok := ar.config.driver.(*txDriver) + if !ok { + panic("db: AdminRole is not a transactional entity") + } + ar.config.driver = _tx.drv + return ar +} + +// String implements the fmt.Stringer. +func (ar *AdminRole) String() string { + var builder strings.Builder + builder.WriteString("AdminRole(") + builder.WriteString(fmt.Sprintf("id=%v, ", ar.ID)) + builder.WriteString("admin_id=") + builder.WriteString(fmt.Sprintf("%v", ar.AdminID)) + builder.WriteString(", ") + builder.WriteString("role_id=") + builder.WriteString(fmt.Sprintf("%v", ar.RoleID)) + builder.WriteByte(')') + return builder.String() +} + +// AdminRoles is a parsable slice of AdminRole. +type AdminRoles []*AdminRole diff --git a/backend/db/adminrole/adminrole.go b/backend/db/adminrole/adminrole.go new file mode 100644 index 00000000..806a46f6 --- /dev/null +++ b/backend/db/adminrole/adminrole.go @@ -0,0 +1,102 @@ +// Code generated by ent, DO NOT EDIT. + +package adminrole + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the adminrole type in the database. + Label = "admin_role" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldAdminID holds the string denoting the admin_id field in the database. + FieldAdminID = "admin_id" + // FieldRoleID holds the string denoting the role_id field in the database. + FieldRoleID = "role_id" + // EdgeAdmin holds the string denoting the admin edge name in mutations. + EdgeAdmin = "admin" + // EdgeRole holds the string denoting the role edge name in mutations. + EdgeRole = "role" + // Table holds the table name of the adminrole in the database. + Table = "admin_roles" + // AdminTable is the table that holds the admin relation/edge. + AdminTable = "admin_roles" + // AdminInverseTable is the table name for the Admin entity. + // It exists in this package in order to avoid circular dependency with the "admin" package. + AdminInverseTable = "admins" + // AdminColumn is the table column denoting the admin relation/edge. + AdminColumn = "admin_id" + // RoleTable is the table that holds the role relation/edge. + RoleTable = "admin_roles" + // RoleInverseTable is the table name for the Role entity. + // It exists in this package in order to avoid circular dependency with the "role" package. + RoleInverseTable = "roles" + // RoleColumn is the table column denoting the role relation/edge. + RoleColumn = "role_id" +) + +// Columns holds all SQL columns for adminrole fields. +var Columns = []string{ + FieldID, + FieldAdminID, + FieldRoleID, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +// OrderOption defines the ordering options for the AdminRole 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() +} + +// ByAdminID orders the results by the admin_id field. +func ByAdminID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAdminID, opts...).ToFunc() +} + +// ByRoleID orders the results by the role_id field. +func ByRoleID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRoleID, opts...).ToFunc() +} + +// ByAdminField orders the results by admin field. +func ByAdminField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newAdminStep(), sql.OrderByField(field, opts...)) + } +} + +// ByRoleField orders the results by role field. +func ByRoleField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newRoleStep(), sql.OrderByField(field, opts...)) + } +} +func newAdminStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(AdminInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, AdminTable, AdminColumn), + ) +} +func newRoleStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(RoleInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, RoleTable, RoleColumn), + ) +} diff --git a/backend/db/adminrole/where.go b/backend/db/adminrole/where.go new file mode 100644 index 00000000..d3fb0d72 --- /dev/null +++ b/backend/db/adminrole/where.go @@ -0,0 +1,166 @@ +// Code generated by ent, DO NOT EDIT. + +package adminrole + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/google/uuid" +) + +// ID filters vertices based on their ID field. +func ID(id uuid.UUID) predicate.AdminRole { + return predicate.AdminRole(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id uuid.UUID) predicate.AdminRole { + return predicate.AdminRole(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id uuid.UUID) predicate.AdminRole { + return predicate.AdminRole(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...uuid.UUID) predicate.AdminRole { + return predicate.AdminRole(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...uuid.UUID) predicate.AdminRole { + return predicate.AdminRole(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id uuid.UUID) predicate.AdminRole { + return predicate.AdminRole(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id uuid.UUID) predicate.AdminRole { + return predicate.AdminRole(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id uuid.UUID) predicate.AdminRole { + return predicate.AdminRole(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id uuid.UUID) predicate.AdminRole { + return predicate.AdminRole(sql.FieldLTE(FieldID, id)) +} + +// AdminID applies equality check predicate on the "admin_id" field. It's identical to AdminIDEQ. +func AdminID(v uuid.UUID) predicate.AdminRole { + return predicate.AdminRole(sql.FieldEQ(FieldAdminID, v)) +} + +// RoleID applies equality check predicate on the "role_id" field. It's identical to RoleIDEQ. +func RoleID(v int64) predicate.AdminRole { + return predicate.AdminRole(sql.FieldEQ(FieldRoleID, v)) +} + +// AdminIDEQ applies the EQ predicate on the "admin_id" field. +func AdminIDEQ(v uuid.UUID) predicate.AdminRole { + return predicate.AdminRole(sql.FieldEQ(FieldAdminID, v)) +} + +// AdminIDNEQ applies the NEQ predicate on the "admin_id" field. +func AdminIDNEQ(v uuid.UUID) predicate.AdminRole { + return predicate.AdminRole(sql.FieldNEQ(FieldAdminID, v)) +} + +// AdminIDIn applies the In predicate on the "admin_id" field. +func AdminIDIn(vs ...uuid.UUID) predicate.AdminRole { + return predicate.AdminRole(sql.FieldIn(FieldAdminID, vs...)) +} + +// AdminIDNotIn applies the NotIn predicate on the "admin_id" field. +func AdminIDNotIn(vs ...uuid.UUID) predicate.AdminRole { + return predicate.AdminRole(sql.FieldNotIn(FieldAdminID, vs...)) +} + +// RoleIDEQ applies the EQ predicate on the "role_id" field. +func RoleIDEQ(v int64) predicate.AdminRole { + return predicate.AdminRole(sql.FieldEQ(FieldRoleID, v)) +} + +// RoleIDNEQ applies the NEQ predicate on the "role_id" field. +func RoleIDNEQ(v int64) predicate.AdminRole { + return predicate.AdminRole(sql.FieldNEQ(FieldRoleID, v)) +} + +// RoleIDIn applies the In predicate on the "role_id" field. +func RoleIDIn(vs ...int64) predicate.AdminRole { + return predicate.AdminRole(sql.FieldIn(FieldRoleID, vs...)) +} + +// RoleIDNotIn applies the NotIn predicate on the "role_id" field. +func RoleIDNotIn(vs ...int64) predicate.AdminRole { + return predicate.AdminRole(sql.FieldNotIn(FieldRoleID, vs...)) +} + +// HasAdmin applies the HasEdge predicate on the "admin" edge. +func HasAdmin() predicate.AdminRole { + return predicate.AdminRole(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, AdminTable, AdminColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasAdminWith applies the HasEdge predicate on the "admin" edge with a given conditions (other predicates). +func HasAdminWith(preds ...predicate.Admin) predicate.AdminRole { + return predicate.AdminRole(func(s *sql.Selector) { + step := newAdminStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasRole applies the HasEdge predicate on the "role" edge. +func HasRole() predicate.AdminRole { + return predicate.AdminRole(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, RoleTable, RoleColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasRoleWith applies the HasEdge predicate on the "role" edge with a given conditions (other predicates). +func HasRoleWith(preds ...predicate.Role) predicate.AdminRole { + return predicate.AdminRole(func(s *sql.Selector) { + step := newRoleStep() + 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.AdminRole) predicate.AdminRole { + return predicate.AdminRole(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.AdminRole) predicate.AdminRole { + return predicate.AdminRole(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.AdminRole) predicate.AdminRole { + return predicate.AdminRole(sql.NotPredicates(p)) +} diff --git a/backend/db/adminrole_create.go b/backend/db/adminrole_create.go new file mode 100644 index 00000000..ebd929f4 --- /dev/null +++ b/backend/db/adminrole_create.go @@ -0,0 +1,587 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/admin" + "github.com/chaitin/MonkeyCode/backend/db/adminrole" + "github.com/chaitin/MonkeyCode/backend/db/role" + "github.com/google/uuid" +) + +// AdminRoleCreate is the builder for creating a AdminRole entity. +type AdminRoleCreate struct { + config + mutation *AdminRoleMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetAdminID sets the "admin_id" field. +func (arc *AdminRoleCreate) SetAdminID(u uuid.UUID) *AdminRoleCreate { + arc.mutation.SetAdminID(u) + return arc +} + +// SetRoleID sets the "role_id" field. +func (arc *AdminRoleCreate) SetRoleID(i int64) *AdminRoleCreate { + arc.mutation.SetRoleID(i) + return arc +} + +// SetID sets the "id" field. +func (arc *AdminRoleCreate) SetID(u uuid.UUID) *AdminRoleCreate { + arc.mutation.SetID(u) + return arc +} + +// SetAdmin sets the "admin" edge to the Admin entity. +func (arc *AdminRoleCreate) SetAdmin(a *Admin) *AdminRoleCreate { + return arc.SetAdminID(a.ID) +} + +// SetRole sets the "role" edge to the Role entity. +func (arc *AdminRoleCreate) SetRole(r *Role) *AdminRoleCreate { + return arc.SetRoleID(r.ID) +} + +// Mutation returns the AdminRoleMutation object of the builder. +func (arc *AdminRoleCreate) Mutation() *AdminRoleMutation { + return arc.mutation +} + +// Save creates the AdminRole in the database. +func (arc *AdminRoleCreate) Save(ctx context.Context) (*AdminRole, error) { + return withHooks(ctx, arc.sqlSave, arc.mutation, arc.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (arc *AdminRoleCreate) SaveX(ctx context.Context) *AdminRole { + v, err := arc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (arc *AdminRoleCreate) Exec(ctx context.Context) error { + _, err := arc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (arc *AdminRoleCreate) ExecX(ctx context.Context) { + if err := arc.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (arc *AdminRoleCreate) check() error { + if _, ok := arc.mutation.AdminID(); !ok { + return &ValidationError{Name: "admin_id", err: errors.New(`db: missing required field "AdminRole.admin_id"`)} + } + if _, ok := arc.mutation.RoleID(); !ok { + return &ValidationError{Name: "role_id", err: errors.New(`db: missing required field "AdminRole.role_id"`)} + } + if len(arc.mutation.AdminIDs()) == 0 { + return &ValidationError{Name: "admin", err: errors.New(`db: missing required edge "AdminRole.admin"`)} + } + if len(arc.mutation.RoleIDs()) == 0 { + return &ValidationError{Name: "role", err: errors.New(`db: missing required edge "AdminRole.role"`)} + } + return nil +} + +func (arc *AdminRoleCreate) sqlSave(ctx context.Context) (*AdminRole, error) { + if err := arc.check(); err != nil { + return nil, err + } + _node, _spec := arc.createSpec() + if err := sqlgraph.CreateNode(ctx, arc.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 + } + } + arc.mutation.id = &_node.ID + arc.mutation.done = true + return _node, nil +} + +func (arc *AdminRoleCreate) createSpec() (*AdminRole, *sqlgraph.CreateSpec) { + var ( + _node = &AdminRole{config: arc.config} + _spec = sqlgraph.NewCreateSpec(adminrole.Table, sqlgraph.NewFieldSpec(adminrole.FieldID, field.TypeUUID)) + ) + _spec.OnConflict = arc.conflict + if id, ok := arc.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = &id + } + if nodes := arc.mutation.AdminIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: adminrole.AdminTable, + Columns: []string{adminrole.AdminColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(admin.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.AdminID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := arc.mutation.RoleIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: adminrole.RoleTable, + Columns: []string{adminrole.RoleColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(role.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.RoleID = 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.AdminRole.Create(). +// SetAdminID(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.AdminRoleUpsert) { +// SetAdminID(v+v). +// }). +// Exec(ctx) +func (arc *AdminRoleCreate) OnConflict(opts ...sql.ConflictOption) *AdminRoleUpsertOne { + arc.conflict = opts + return &AdminRoleUpsertOne{ + create: arc, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.AdminRole.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (arc *AdminRoleCreate) OnConflictColumns(columns ...string) *AdminRoleUpsertOne { + arc.conflict = append(arc.conflict, sql.ConflictColumns(columns...)) + return &AdminRoleUpsertOne{ + create: arc, + } +} + +type ( + // AdminRoleUpsertOne is the builder for "upsert"-ing + // one AdminRole node. + AdminRoleUpsertOne struct { + create *AdminRoleCreate + } + + // AdminRoleUpsert is the "OnConflict" setter. + AdminRoleUpsert struct { + *sql.UpdateSet + } +) + +// SetAdminID sets the "admin_id" field. +func (u *AdminRoleUpsert) SetAdminID(v uuid.UUID) *AdminRoleUpsert { + u.Set(adminrole.FieldAdminID, v) + return u +} + +// UpdateAdminID sets the "admin_id" field to the value that was provided on create. +func (u *AdminRoleUpsert) UpdateAdminID() *AdminRoleUpsert { + u.SetExcluded(adminrole.FieldAdminID) + return u +} + +// SetRoleID sets the "role_id" field. +func (u *AdminRoleUpsert) SetRoleID(v int64) *AdminRoleUpsert { + u.Set(adminrole.FieldRoleID, v) + return u +} + +// UpdateRoleID sets the "role_id" field to the value that was provided on create. +func (u *AdminRoleUpsert) UpdateRoleID() *AdminRoleUpsert { + u.SetExcluded(adminrole.FieldRoleID) + 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.AdminRole.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(adminrole.FieldID) +// }), +// ). +// Exec(ctx) +func (u *AdminRoleUpsertOne) UpdateNewValues() *AdminRoleUpsertOne { + 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(adminrole.FieldID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.AdminRole.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *AdminRoleUpsertOne) Ignore() *AdminRoleUpsertOne { + 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 *AdminRoleUpsertOne) DoNothing() *AdminRoleUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the AdminRoleCreate.OnConflict +// documentation for more info. +func (u *AdminRoleUpsertOne) Update(set func(*AdminRoleUpsert)) *AdminRoleUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&AdminRoleUpsert{UpdateSet: update}) + })) + return u +} + +// SetAdminID sets the "admin_id" field. +func (u *AdminRoleUpsertOne) SetAdminID(v uuid.UUID) *AdminRoleUpsertOne { + return u.Update(func(s *AdminRoleUpsert) { + s.SetAdminID(v) + }) +} + +// UpdateAdminID sets the "admin_id" field to the value that was provided on create. +func (u *AdminRoleUpsertOne) UpdateAdminID() *AdminRoleUpsertOne { + return u.Update(func(s *AdminRoleUpsert) { + s.UpdateAdminID() + }) +} + +// SetRoleID sets the "role_id" field. +func (u *AdminRoleUpsertOne) SetRoleID(v int64) *AdminRoleUpsertOne { + return u.Update(func(s *AdminRoleUpsert) { + s.SetRoleID(v) + }) +} + +// UpdateRoleID sets the "role_id" field to the value that was provided on create. +func (u *AdminRoleUpsertOne) UpdateRoleID() *AdminRoleUpsertOne { + return u.Update(func(s *AdminRoleUpsert) { + s.UpdateRoleID() + }) +} + +// Exec executes the query. +func (u *AdminRoleUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for AdminRoleCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *AdminRoleUpsertOne) 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 *AdminRoleUpsertOne) 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: AdminRoleUpsertOne.ID is not supported by MySQL driver. Use AdminRoleUpsertOne.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 *AdminRoleUpsertOne) IDX(ctx context.Context) uuid.UUID { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// AdminRoleCreateBulk is the builder for creating many AdminRole entities in bulk. +type AdminRoleCreateBulk struct { + config + err error + builders []*AdminRoleCreate + conflict []sql.ConflictOption +} + +// Save creates the AdminRole entities in the database. +func (arcb *AdminRoleCreateBulk) Save(ctx context.Context) ([]*AdminRole, error) { + if arcb.err != nil { + return nil, arcb.err + } + specs := make([]*sqlgraph.CreateSpec, len(arcb.builders)) + nodes := make([]*AdminRole, len(arcb.builders)) + mutators := make([]Mutator, len(arcb.builders)) + for i := range arcb.builders { + func(i int, root context.Context) { + builder := arcb.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*AdminRoleMutation) + 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, arcb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = arcb.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, arcb.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, arcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (arcb *AdminRoleCreateBulk) SaveX(ctx context.Context) []*AdminRole { + v, err := arcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (arcb *AdminRoleCreateBulk) Exec(ctx context.Context) error { + _, err := arcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (arcb *AdminRoleCreateBulk) ExecX(ctx context.Context) { + if err := arcb.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.AdminRole.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.AdminRoleUpsert) { +// SetAdminID(v+v). +// }). +// Exec(ctx) +func (arcb *AdminRoleCreateBulk) OnConflict(opts ...sql.ConflictOption) *AdminRoleUpsertBulk { + arcb.conflict = opts + return &AdminRoleUpsertBulk{ + create: arcb, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.AdminRole.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (arcb *AdminRoleCreateBulk) OnConflictColumns(columns ...string) *AdminRoleUpsertBulk { + arcb.conflict = append(arcb.conflict, sql.ConflictColumns(columns...)) + return &AdminRoleUpsertBulk{ + create: arcb, + } +} + +// AdminRoleUpsertBulk is the builder for "upsert"-ing +// a bulk of AdminRole nodes. +type AdminRoleUpsertBulk struct { + create *AdminRoleCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.AdminRole.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(adminrole.FieldID) +// }), +// ). +// Exec(ctx) +func (u *AdminRoleUpsertBulk) UpdateNewValues() *AdminRoleUpsertBulk { + 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(adminrole.FieldID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.AdminRole.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *AdminRoleUpsertBulk) Ignore() *AdminRoleUpsertBulk { + 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 *AdminRoleUpsertBulk) DoNothing() *AdminRoleUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the AdminRoleCreateBulk.OnConflict +// documentation for more info. +func (u *AdminRoleUpsertBulk) Update(set func(*AdminRoleUpsert)) *AdminRoleUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&AdminRoleUpsert{UpdateSet: update}) + })) + return u +} + +// SetAdminID sets the "admin_id" field. +func (u *AdminRoleUpsertBulk) SetAdminID(v uuid.UUID) *AdminRoleUpsertBulk { + return u.Update(func(s *AdminRoleUpsert) { + s.SetAdminID(v) + }) +} + +// UpdateAdminID sets the "admin_id" field to the value that was provided on create. +func (u *AdminRoleUpsertBulk) UpdateAdminID() *AdminRoleUpsertBulk { + return u.Update(func(s *AdminRoleUpsert) { + s.UpdateAdminID() + }) +} + +// SetRoleID sets the "role_id" field. +func (u *AdminRoleUpsertBulk) SetRoleID(v int64) *AdminRoleUpsertBulk { + return u.Update(func(s *AdminRoleUpsert) { + s.SetRoleID(v) + }) +} + +// UpdateRoleID sets the "role_id" field to the value that was provided on create. +func (u *AdminRoleUpsertBulk) UpdateRoleID() *AdminRoleUpsertBulk { + return u.Update(func(s *AdminRoleUpsert) { + s.UpdateRoleID() + }) +} + +// Exec executes the query. +func (u *AdminRoleUpsertBulk) 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 AdminRoleCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for AdminRoleCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *AdminRoleUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/adminrole_delete.go b/backend/db/adminrole_delete.go new file mode 100644 index 00000000..49726185 --- /dev/null +++ b/backend/db/adminrole_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/adminrole" + "github.com/chaitin/MonkeyCode/backend/db/predicate" +) + +// AdminRoleDelete is the builder for deleting a AdminRole entity. +type AdminRoleDelete struct { + config + hooks []Hook + mutation *AdminRoleMutation +} + +// Where appends a list predicates to the AdminRoleDelete builder. +func (ard *AdminRoleDelete) Where(ps ...predicate.AdminRole) *AdminRoleDelete { + ard.mutation.Where(ps...) + return ard +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (ard *AdminRoleDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, ard.sqlExec, ard.mutation, ard.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (ard *AdminRoleDelete) ExecX(ctx context.Context) int { + n, err := ard.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (ard *AdminRoleDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(adminrole.Table, sqlgraph.NewFieldSpec(adminrole.FieldID, field.TypeUUID)) + if ps := ard.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, ard.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + ard.mutation.done = true + return affected, err +} + +// AdminRoleDeleteOne is the builder for deleting a single AdminRole entity. +type AdminRoleDeleteOne struct { + ard *AdminRoleDelete +} + +// Where appends a list predicates to the AdminRoleDelete builder. +func (ardo *AdminRoleDeleteOne) Where(ps ...predicate.AdminRole) *AdminRoleDeleteOne { + ardo.ard.mutation.Where(ps...) + return ardo +} + +// Exec executes the deletion query. +func (ardo *AdminRoleDeleteOne) Exec(ctx context.Context) error { + n, err := ardo.ard.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{adminrole.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (ardo *AdminRoleDeleteOne) ExecX(ctx context.Context) { + if err := ardo.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/adminrole_query.go b/backend/db/adminrole_query.go new file mode 100644 index 00000000..e8b2f6d1 --- /dev/null +++ b/backend/db/adminrole_query.go @@ -0,0 +1,732 @@ +// 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/admin" + "github.com/chaitin/MonkeyCode/backend/db/adminrole" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/role" + "github.com/google/uuid" +) + +// AdminRoleQuery is the builder for querying AdminRole entities. +type AdminRoleQuery struct { + config + ctx *QueryContext + order []adminrole.OrderOption + inters []Interceptor + predicates []predicate.AdminRole + withAdmin *AdminQuery + withRole *RoleQuery + 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 AdminRoleQuery builder. +func (arq *AdminRoleQuery) Where(ps ...predicate.AdminRole) *AdminRoleQuery { + arq.predicates = append(arq.predicates, ps...) + return arq +} + +// Limit the number of records to be returned by this query. +func (arq *AdminRoleQuery) Limit(limit int) *AdminRoleQuery { + arq.ctx.Limit = &limit + return arq +} + +// Offset to start from. +func (arq *AdminRoleQuery) Offset(offset int) *AdminRoleQuery { + arq.ctx.Offset = &offset + return arq +} + +// 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 (arq *AdminRoleQuery) Unique(unique bool) *AdminRoleQuery { + arq.ctx.Unique = &unique + return arq +} + +// Order specifies how the records should be ordered. +func (arq *AdminRoleQuery) Order(o ...adminrole.OrderOption) *AdminRoleQuery { + arq.order = append(arq.order, o...) + return arq +} + +// QueryAdmin chains the current query on the "admin" edge. +func (arq *AdminRoleQuery) QueryAdmin() *AdminQuery { + query := (&AdminClient{config: arq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := arq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := arq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(adminrole.Table, adminrole.FieldID, selector), + sqlgraph.To(admin.Table, admin.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, adminrole.AdminTable, adminrole.AdminColumn), + ) + fromU = sqlgraph.SetNeighbors(arq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryRole chains the current query on the "role" edge. +func (arq *AdminRoleQuery) QueryRole() *RoleQuery { + query := (&RoleClient{config: arq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := arq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := arq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(adminrole.Table, adminrole.FieldID, selector), + sqlgraph.To(role.Table, role.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, adminrole.RoleTable, adminrole.RoleColumn), + ) + fromU = sqlgraph.SetNeighbors(arq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first AdminRole entity from the query. +// Returns a *NotFoundError when no AdminRole was found. +func (arq *AdminRoleQuery) First(ctx context.Context) (*AdminRole, error) { + nodes, err := arq.Limit(1).All(setContextOp(ctx, arq.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{adminrole.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (arq *AdminRoleQuery) FirstX(ctx context.Context) *AdminRole { + node, err := arq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first AdminRole ID from the query. +// Returns a *NotFoundError when no AdminRole ID was found. +func (arq *AdminRoleQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = arq.Limit(1).IDs(setContextOp(ctx, arq.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{adminrole.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (arq *AdminRoleQuery) FirstIDX(ctx context.Context) uuid.UUID { + id, err := arq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single AdminRole entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one AdminRole entity is found. +// Returns a *NotFoundError when no AdminRole entities are found. +func (arq *AdminRoleQuery) Only(ctx context.Context) (*AdminRole, error) { + nodes, err := arq.Limit(2).All(setContextOp(ctx, arq.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{adminrole.Label} + default: + return nil, &NotSingularError{adminrole.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (arq *AdminRoleQuery) OnlyX(ctx context.Context) *AdminRole { + node, err := arq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only AdminRole ID in the query. +// Returns a *NotSingularError when more than one AdminRole ID is found. +// Returns a *NotFoundError when no entities are found. +func (arq *AdminRoleQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = arq.Limit(2).IDs(setContextOp(ctx, arq.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{adminrole.Label} + default: + err = &NotSingularError{adminrole.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (arq *AdminRoleQuery) OnlyIDX(ctx context.Context) uuid.UUID { + id, err := arq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of AdminRoles. +func (arq *AdminRoleQuery) All(ctx context.Context) ([]*AdminRole, error) { + ctx = setContextOp(ctx, arq.ctx, ent.OpQueryAll) + if err := arq.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*AdminRole, *AdminRoleQuery]() + return withInterceptors[[]*AdminRole](ctx, arq, qr, arq.inters) +} + +// AllX is like All, but panics if an error occurs. +func (arq *AdminRoleQuery) AllX(ctx context.Context) []*AdminRole { + nodes, err := arq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of AdminRole IDs. +func (arq *AdminRoleQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) { + if arq.ctx.Unique == nil && arq.path != nil { + arq.Unique(true) + } + ctx = setContextOp(ctx, arq.ctx, ent.OpQueryIDs) + if err = arq.Select(adminrole.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (arq *AdminRoleQuery) IDsX(ctx context.Context) []uuid.UUID { + ids, err := arq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (arq *AdminRoleQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, arq.ctx, ent.OpQueryCount) + if err := arq.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, arq, querierCount[*AdminRoleQuery](), arq.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (arq *AdminRoleQuery) CountX(ctx context.Context) int { + count, err := arq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (arq *AdminRoleQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, arq.ctx, ent.OpQueryExist) + switch _, err := arq.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 (arq *AdminRoleQuery) ExistX(ctx context.Context) bool { + exist, err := arq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the AdminRoleQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (arq *AdminRoleQuery) Clone() *AdminRoleQuery { + if arq == nil { + return nil + } + return &AdminRoleQuery{ + config: arq.config, + ctx: arq.ctx.Clone(), + order: append([]adminrole.OrderOption{}, arq.order...), + inters: append([]Interceptor{}, arq.inters...), + predicates: append([]predicate.AdminRole{}, arq.predicates...), + withAdmin: arq.withAdmin.Clone(), + withRole: arq.withRole.Clone(), + // clone intermediate query. + sql: arq.sql.Clone(), + path: arq.path, + modifiers: append([]func(*sql.Selector){}, arq.modifiers...), + } +} + +// WithAdmin tells the query-builder to eager-load the nodes that are connected to +// the "admin" edge. The optional arguments are used to configure the query builder of the edge. +func (arq *AdminRoleQuery) WithAdmin(opts ...func(*AdminQuery)) *AdminRoleQuery { + query := (&AdminClient{config: arq.config}).Query() + for _, opt := range opts { + opt(query) + } + arq.withAdmin = query + return arq +} + +// WithRole tells the query-builder to eager-load the nodes that are connected to +// the "role" edge. The optional arguments are used to configure the query builder of the edge. +func (arq *AdminRoleQuery) WithRole(opts ...func(*RoleQuery)) *AdminRoleQuery { + query := (&RoleClient{config: arq.config}).Query() + for _, opt := range opts { + opt(query) + } + arq.withRole = query + return arq +} + +// 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 { +// AdminID uuid.UUID `json:"admin_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.AdminRole.Query(). +// GroupBy(adminrole.FieldAdminID). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (arq *AdminRoleQuery) GroupBy(field string, fields ...string) *AdminRoleGroupBy { + arq.ctx.Fields = append([]string{field}, fields...) + grbuild := &AdminRoleGroupBy{build: arq} + grbuild.flds = &arq.ctx.Fields + grbuild.label = adminrole.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 { +// AdminID uuid.UUID `json:"admin_id,omitempty"` +// } +// +// client.AdminRole.Query(). +// Select(adminrole.FieldAdminID). +// Scan(ctx, &v) +func (arq *AdminRoleQuery) Select(fields ...string) *AdminRoleSelect { + arq.ctx.Fields = append(arq.ctx.Fields, fields...) + sbuild := &AdminRoleSelect{AdminRoleQuery: arq} + sbuild.label = adminrole.Label + sbuild.flds, sbuild.scan = &arq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a AdminRoleSelect configured with the given aggregations. +func (arq *AdminRoleQuery) Aggregate(fns ...AggregateFunc) *AdminRoleSelect { + return arq.Select().Aggregate(fns...) +} + +func (arq *AdminRoleQuery) prepareQuery(ctx context.Context) error { + for _, inter := range arq.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, arq); err != nil { + return err + } + } + } + for _, f := range arq.ctx.Fields { + if !adminrole.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + } + if arq.path != nil { + prev, err := arq.path(ctx) + if err != nil { + return err + } + arq.sql = prev + } + return nil +} + +func (arq *AdminRoleQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*AdminRole, error) { + var ( + nodes = []*AdminRole{} + _spec = arq.querySpec() + loadedTypes = [2]bool{ + arq.withAdmin != nil, + arq.withRole != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*AdminRole).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &AdminRole{config: arq.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(arq.modifiers) > 0 { + _spec.Modifiers = arq.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, arq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := arq.withAdmin; query != nil { + if err := arq.loadAdmin(ctx, query, nodes, nil, + func(n *AdminRole, e *Admin) { n.Edges.Admin = e }); err != nil { + return nil, err + } + } + if query := arq.withRole; query != nil { + if err := arq.loadRole(ctx, query, nodes, nil, + func(n *AdminRole, e *Role) { n.Edges.Role = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (arq *AdminRoleQuery) loadAdmin(ctx context.Context, query *AdminQuery, nodes []*AdminRole, init func(*AdminRole), assign func(*AdminRole, *Admin)) error { + ids := make([]uuid.UUID, 0, len(nodes)) + nodeids := make(map[uuid.UUID][]*AdminRole) + for i := range nodes { + fk := nodes[i].AdminID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(admin.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 "admin_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (arq *AdminRoleQuery) loadRole(ctx context.Context, query *RoleQuery, nodes []*AdminRole, init func(*AdminRole), assign func(*AdminRole, *Role)) error { + ids := make([]int64, 0, len(nodes)) + nodeids := make(map[int64][]*AdminRole) + for i := range nodes { + fk := nodes[i].RoleID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(role.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 "role_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (arq *AdminRoleQuery) sqlCount(ctx context.Context) (int, error) { + _spec := arq.querySpec() + if len(arq.modifiers) > 0 { + _spec.Modifiers = arq.modifiers + } + _spec.Node.Columns = arq.ctx.Fields + if len(arq.ctx.Fields) > 0 { + _spec.Unique = arq.ctx.Unique != nil && *arq.ctx.Unique + } + return sqlgraph.CountNodes(ctx, arq.driver, _spec) +} + +func (arq *AdminRoleQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(adminrole.Table, adminrole.Columns, sqlgraph.NewFieldSpec(adminrole.FieldID, field.TypeUUID)) + _spec.From = arq.sql + if unique := arq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if arq.path != nil { + _spec.Unique = true + } + if fields := arq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, adminrole.FieldID) + for i := range fields { + if fields[i] != adminrole.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if arq.withAdmin != nil { + _spec.Node.AddColumnOnce(adminrole.FieldAdminID) + } + if arq.withRole != nil { + _spec.Node.AddColumnOnce(adminrole.FieldRoleID) + } + } + if ps := arq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := arq.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := arq.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := arq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (arq *AdminRoleQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(arq.driver.Dialect()) + t1 := builder.Table(adminrole.Table) + columns := arq.ctx.Fields + if len(columns) == 0 { + columns = adminrole.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if arq.sql != nil { + selector = arq.sql + selector.Select(selector.Columns(columns...)...) + } + if arq.ctx.Unique != nil && *arq.ctx.Unique { + selector.Distinct() + } + for _, m := range arq.modifiers { + m(selector) + } + for _, p := range arq.predicates { + p(selector) + } + for _, p := range arq.order { + p(selector) + } + if offset := arq.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 := arq.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 (arq *AdminRoleQuery) ForUpdate(opts ...sql.LockOption) *AdminRoleQuery { + if arq.driver.Dialect() == dialect.Postgres { + arq.Unique(false) + } + arq.modifiers = append(arq.modifiers, func(s *sql.Selector) { + s.ForUpdate(opts...) + }) + return arq +} + +// 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 (arq *AdminRoleQuery) ForShare(opts ...sql.LockOption) *AdminRoleQuery { + if arq.driver.Dialect() == dialect.Postgres { + arq.Unique(false) + } + arq.modifiers = append(arq.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return arq +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (arq *AdminRoleQuery) Modify(modifiers ...func(s *sql.Selector)) *AdminRoleSelect { + arq.modifiers = append(arq.modifiers, modifiers...) + return arq.Select() +} + +// AdminRoleGroupBy is the group-by builder for AdminRole entities. +type AdminRoleGroupBy struct { + selector + build *AdminRoleQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (argb *AdminRoleGroupBy) Aggregate(fns ...AggregateFunc) *AdminRoleGroupBy { + argb.fns = append(argb.fns, fns...) + return argb +} + +// Scan applies the selector query and scans the result into the given value. +func (argb *AdminRoleGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, argb.build.ctx, ent.OpQueryGroupBy) + if err := argb.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*AdminRoleQuery, *AdminRoleGroupBy](ctx, argb.build, argb, argb.build.inters, v) +} + +func (argb *AdminRoleGroupBy) sqlScan(ctx context.Context, root *AdminRoleQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(argb.fns)) + for _, fn := range argb.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*argb.flds)+len(argb.fns)) + for _, f := range *argb.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*argb.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := argb.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// AdminRoleSelect is the builder for selecting fields of AdminRole entities. +type AdminRoleSelect struct { + *AdminRoleQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (ars *AdminRoleSelect) Aggregate(fns ...AggregateFunc) *AdminRoleSelect { + ars.fns = append(ars.fns, fns...) + return ars +} + +// Scan applies the selector query and scans the result into the given value. +func (ars *AdminRoleSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, ars.ctx, ent.OpQuerySelect) + if err := ars.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*AdminRoleQuery, *AdminRoleSelect](ctx, ars.AdminRoleQuery, ars, ars.inters, v) +} + +func (ars *AdminRoleSelect) sqlScan(ctx context.Context, root *AdminRoleQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(ars.fns)) + for _, fn := range ars.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*ars.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 := ars.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 (ars *AdminRoleSelect) Modify(modifiers ...func(s *sql.Selector)) *AdminRoleSelect { + ars.modifiers = append(ars.modifiers, modifiers...) + return ars +} diff --git a/backend/db/adminrole_update.go b/backend/db/adminrole_update.go new file mode 100644 index 00000000..1566e79c --- /dev/null +++ b/backend/db/adminrole_update.go @@ -0,0 +1,438 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/admin" + "github.com/chaitin/MonkeyCode/backend/db/adminrole" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/role" + "github.com/google/uuid" +) + +// AdminRoleUpdate is the builder for updating AdminRole entities. +type AdminRoleUpdate struct { + config + hooks []Hook + mutation *AdminRoleMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the AdminRoleUpdate builder. +func (aru *AdminRoleUpdate) Where(ps ...predicate.AdminRole) *AdminRoleUpdate { + aru.mutation.Where(ps...) + return aru +} + +// SetAdminID sets the "admin_id" field. +func (aru *AdminRoleUpdate) SetAdminID(u uuid.UUID) *AdminRoleUpdate { + aru.mutation.SetAdminID(u) + return aru +} + +// SetNillableAdminID sets the "admin_id" field if the given value is not nil. +func (aru *AdminRoleUpdate) SetNillableAdminID(u *uuid.UUID) *AdminRoleUpdate { + if u != nil { + aru.SetAdminID(*u) + } + return aru +} + +// SetRoleID sets the "role_id" field. +func (aru *AdminRoleUpdate) SetRoleID(i int64) *AdminRoleUpdate { + aru.mutation.SetRoleID(i) + return aru +} + +// SetNillableRoleID sets the "role_id" field if the given value is not nil. +func (aru *AdminRoleUpdate) SetNillableRoleID(i *int64) *AdminRoleUpdate { + if i != nil { + aru.SetRoleID(*i) + } + return aru +} + +// SetAdmin sets the "admin" edge to the Admin entity. +func (aru *AdminRoleUpdate) SetAdmin(a *Admin) *AdminRoleUpdate { + return aru.SetAdminID(a.ID) +} + +// SetRole sets the "role" edge to the Role entity. +func (aru *AdminRoleUpdate) SetRole(r *Role) *AdminRoleUpdate { + return aru.SetRoleID(r.ID) +} + +// Mutation returns the AdminRoleMutation object of the builder. +func (aru *AdminRoleUpdate) Mutation() *AdminRoleMutation { + return aru.mutation +} + +// ClearAdmin clears the "admin" edge to the Admin entity. +func (aru *AdminRoleUpdate) ClearAdmin() *AdminRoleUpdate { + aru.mutation.ClearAdmin() + return aru +} + +// ClearRole clears the "role" edge to the Role entity. +func (aru *AdminRoleUpdate) ClearRole() *AdminRoleUpdate { + aru.mutation.ClearRole() + return aru +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (aru *AdminRoleUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, aru.sqlSave, aru.mutation, aru.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (aru *AdminRoleUpdate) SaveX(ctx context.Context) int { + affected, err := aru.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (aru *AdminRoleUpdate) Exec(ctx context.Context) error { + _, err := aru.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (aru *AdminRoleUpdate) ExecX(ctx context.Context) { + if err := aru.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (aru *AdminRoleUpdate) check() error { + if aru.mutation.AdminCleared() && len(aru.mutation.AdminIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "AdminRole.admin"`) + } + if aru.mutation.RoleCleared() && len(aru.mutation.RoleIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "AdminRole.role"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (aru *AdminRoleUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *AdminRoleUpdate { + aru.modifiers = append(aru.modifiers, modifiers...) + return aru +} + +func (aru *AdminRoleUpdate) sqlSave(ctx context.Context) (n int, err error) { + if err := aru.check(); err != nil { + return n, err + } + _spec := sqlgraph.NewUpdateSpec(adminrole.Table, adminrole.Columns, sqlgraph.NewFieldSpec(adminrole.FieldID, field.TypeUUID)) + if ps := aru.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if aru.mutation.AdminCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: adminrole.AdminTable, + Columns: []string{adminrole.AdminColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(admin.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := aru.mutation.AdminIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: adminrole.AdminTable, + Columns: []string{adminrole.AdminColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(admin.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if aru.mutation.RoleCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: adminrole.RoleTable, + Columns: []string{adminrole.RoleColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(role.FieldID, field.TypeInt64), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := aru.mutation.RoleIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: adminrole.RoleTable, + Columns: []string{adminrole.RoleColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(role.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(aru.modifiers...) + if n, err = sqlgraph.UpdateNodes(ctx, aru.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{adminrole.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + aru.mutation.done = true + return n, nil +} + +// AdminRoleUpdateOne is the builder for updating a single AdminRole entity. +type AdminRoleUpdateOne struct { + config + fields []string + hooks []Hook + mutation *AdminRoleMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetAdminID sets the "admin_id" field. +func (aruo *AdminRoleUpdateOne) SetAdminID(u uuid.UUID) *AdminRoleUpdateOne { + aruo.mutation.SetAdminID(u) + return aruo +} + +// SetNillableAdminID sets the "admin_id" field if the given value is not nil. +func (aruo *AdminRoleUpdateOne) SetNillableAdminID(u *uuid.UUID) *AdminRoleUpdateOne { + if u != nil { + aruo.SetAdminID(*u) + } + return aruo +} + +// SetRoleID sets the "role_id" field. +func (aruo *AdminRoleUpdateOne) SetRoleID(i int64) *AdminRoleUpdateOne { + aruo.mutation.SetRoleID(i) + return aruo +} + +// SetNillableRoleID sets the "role_id" field if the given value is not nil. +func (aruo *AdminRoleUpdateOne) SetNillableRoleID(i *int64) *AdminRoleUpdateOne { + if i != nil { + aruo.SetRoleID(*i) + } + return aruo +} + +// SetAdmin sets the "admin" edge to the Admin entity. +func (aruo *AdminRoleUpdateOne) SetAdmin(a *Admin) *AdminRoleUpdateOne { + return aruo.SetAdminID(a.ID) +} + +// SetRole sets the "role" edge to the Role entity. +func (aruo *AdminRoleUpdateOne) SetRole(r *Role) *AdminRoleUpdateOne { + return aruo.SetRoleID(r.ID) +} + +// Mutation returns the AdminRoleMutation object of the builder. +func (aruo *AdminRoleUpdateOne) Mutation() *AdminRoleMutation { + return aruo.mutation +} + +// ClearAdmin clears the "admin" edge to the Admin entity. +func (aruo *AdminRoleUpdateOne) ClearAdmin() *AdminRoleUpdateOne { + aruo.mutation.ClearAdmin() + return aruo +} + +// ClearRole clears the "role" edge to the Role entity. +func (aruo *AdminRoleUpdateOne) ClearRole() *AdminRoleUpdateOne { + aruo.mutation.ClearRole() + return aruo +} + +// Where appends a list predicates to the AdminRoleUpdate builder. +func (aruo *AdminRoleUpdateOne) Where(ps ...predicate.AdminRole) *AdminRoleUpdateOne { + aruo.mutation.Where(ps...) + return aruo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (aruo *AdminRoleUpdateOne) Select(field string, fields ...string) *AdminRoleUpdateOne { + aruo.fields = append([]string{field}, fields...) + return aruo +} + +// Save executes the query and returns the updated AdminRole entity. +func (aruo *AdminRoleUpdateOne) Save(ctx context.Context) (*AdminRole, error) { + return withHooks(ctx, aruo.sqlSave, aruo.mutation, aruo.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (aruo *AdminRoleUpdateOne) SaveX(ctx context.Context) *AdminRole { + node, err := aruo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (aruo *AdminRoleUpdateOne) Exec(ctx context.Context) error { + _, err := aruo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (aruo *AdminRoleUpdateOne) ExecX(ctx context.Context) { + if err := aruo.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (aruo *AdminRoleUpdateOne) check() error { + if aruo.mutation.AdminCleared() && len(aruo.mutation.AdminIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "AdminRole.admin"`) + } + if aruo.mutation.RoleCleared() && len(aruo.mutation.RoleIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "AdminRole.role"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (aruo *AdminRoleUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *AdminRoleUpdateOne { + aruo.modifiers = append(aruo.modifiers, modifiers...) + return aruo +} + +func (aruo *AdminRoleUpdateOne) sqlSave(ctx context.Context) (_node *AdminRole, err error) { + if err := aruo.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(adminrole.Table, adminrole.Columns, sqlgraph.NewFieldSpec(adminrole.FieldID, field.TypeUUID)) + id, ok := aruo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "AdminRole.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := aruo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, adminrole.FieldID) + for _, f := range fields { + if !adminrole.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != adminrole.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := aruo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if aruo.mutation.AdminCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: adminrole.AdminTable, + Columns: []string{adminrole.AdminColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(admin.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := aruo.mutation.AdminIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: adminrole.AdminTable, + Columns: []string{adminrole.AdminColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(admin.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if aruo.mutation.RoleCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: adminrole.RoleTable, + Columns: []string{adminrole.RoleColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(role.FieldID, field.TypeInt64), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := aruo.mutation.RoleIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: adminrole.RoleTable, + Columns: []string{adminrole.RoleColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(role.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(aruo.modifiers...) + _node = &AdminRole{config: aruo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, aruo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{adminrole.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + aruo.mutation.done = true + return _node, nil +} diff --git a/backend/db/client.go b/backend/db/client.go index 6d0e7396..cd3d1c96 100644 --- a/backend/db/client.go +++ b/backend/db/client.go @@ -18,6 +18,7 @@ import ( "entgo.io/ent/dialect/sql/sqlgraph" "github.com/chaitin/MonkeyCode/backend/db/admin" "github.com/chaitin/MonkeyCode/backend/db/adminloginhistory" + "github.com/chaitin/MonkeyCode/backend/db/adminrole" "github.com/chaitin/MonkeyCode/backend/db/apikey" "github.com/chaitin/MonkeyCode/backend/db/billingplan" "github.com/chaitin/MonkeyCode/backend/db/billingquota" @@ -30,12 +31,16 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/model" "github.com/chaitin/MonkeyCode/backend/db/modelprovider" "github.com/chaitin/MonkeyCode/backend/db/modelprovidermodel" + "github.com/chaitin/MonkeyCode/backend/db/role" "github.com/chaitin/MonkeyCode/backend/db/securityscanning" "github.com/chaitin/MonkeyCode/backend/db/securityscanningresult" "github.com/chaitin/MonkeyCode/backend/db/setting" "github.com/chaitin/MonkeyCode/backend/db/task" "github.com/chaitin/MonkeyCode/backend/db/taskrecord" "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/usergroup" + "github.com/chaitin/MonkeyCode/backend/db/usergroupadmin" + "github.com/chaitin/MonkeyCode/backend/db/usergroupuser" "github.com/chaitin/MonkeyCode/backend/db/useridentity" "github.com/chaitin/MonkeyCode/backend/db/userloginhistory" "github.com/chaitin/MonkeyCode/backend/db/workspace" @@ -53,6 +58,8 @@ type Client struct { Admin *AdminClient // AdminLoginHistory is the client for interacting with the AdminLoginHistory builders. AdminLoginHistory *AdminLoginHistoryClient + // AdminRole is the client for interacting with the AdminRole builders. + AdminRole *AdminRoleClient // ApiKey is the client for interacting with the ApiKey builders. ApiKey *ApiKeyClient // BillingPlan is the client for interacting with the BillingPlan builders. @@ -77,6 +84,8 @@ type Client struct { ModelProvider *ModelProviderClient // ModelProviderModel is the client for interacting with the ModelProviderModel builders. ModelProviderModel *ModelProviderModelClient + // Role is the client for interacting with the Role builders. + Role *RoleClient // SecurityScanning is the client for interacting with the SecurityScanning builders. SecurityScanning *SecurityScanningClient // SecurityScanningResult is the client for interacting with the SecurityScanningResult builders. @@ -89,6 +98,12 @@ type Client struct { TaskRecord *TaskRecordClient // User is the client for interacting with the User builders. User *UserClient + // UserGroup is the client for interacting with the UserGroup builders. + UserGroup *UserGroupClient + // UserGroupAdmin is the client for interacting with the UserGroupAdmin builders. + UserGroupAdmin *UserGroupAdminClient + // UserGroupUser is the client for interacting with the UserGroupUser builders. + UserGroupUser *UserGroupUserClient // UserIdentity is the client for interacting with the UserIdentity builders. UserIdentity *UserIdentityClient // UserLoginHistory is the client for interacting with the UserLoginHistory builders. @@ -110,6 +125,7 @@ func (c *Client) init() { c.Schema = migrate.NewSchema(c.driver) c.Admin = NewAdminClient(c.config) c.AdminLoginHistory = NewAdminLoginHistoryClient(c.config) + c.AdminRole = NewAdminRoleClient(c.config) c.ApiKey = NewApiKeyClient(c.config) c.BillingPlan = NewBillingPlanClient(c.config) c.BillingQuota = NewBillingQuotaClient(c.config) @@ -122,12 +138,16 @@ func (c *Client) init() { c.Model = NewModelClient(c.config) c.ModelProvider = NewModelProviderClient(c.config) c.ModelProviderModel = NewModelProviderModelClient(c.config) + c.Role = NewRoleClient(c.config) c.SecurityScanning = NewSecurityScanningClient(c.config) c.SecurityScanningResult = NewSecurityScanningResultClient(c.config) c.Setting = NewSettingClient(c.config) c.Task = NewTaskClient(c.config) c.TaskRecord = NewTaskRecordClient(c.config) c.User = NewUserClient(c.config) + c.UserGroup = NewUserGroupClient(c.config) + c.UserGroupAdmin = NewUserGroupAdminClient(c.config) + c.UserGroupUser = NewUserGroupUserClient(c.config) c.UserIdentity = NewUserIdentityClient(c.config) c.UserLoginHistory = NewUserLoginHistoryClient(c.config) c.Workspace = NewWorkspaceClient(c.config) @@ -226,6 +246,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { config: cfg, Admin: NewAdminClient(cfg), AdminLoginHistory: NewAdminLoginHistoryClient(cfg), + AdminRole: NewAdminRoleClient(cfg), ApiKey: NewApiKeyClient(cfg), BillingPlan: NewBillingPlanClient(cfg), BillingQuota: NewBillingQuotaClient(cfg), @@ -238,12 +259,16 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { Model: NewModelClient(cfg), ModelProvider: NewModelProviderClient(cfg), ModelProviderModel: NewModelProviderModelClient(cfg), + Role: NewRoleClient(cfg), SecurityScanning: NewSecurityScanningClient(cfg), SecurityScanningResult: NewSecurityScanningResultClient(cfg), Setting: NewSettingClient(cfg), Task: NewTaskClient(cfg), TaskRecord: NewTaskRecordClient(cfg), User: NewUserClient(cfg), + UserGroup: NewUserGroupClient(cfg), + UserGroupAdmin: NewUserGroupAdminClient(cfg), + UserGroupUser: NewUserGroupUserClient(cfg), UserIdentity: NewUserIdentityClient(cfg), UserLoginHistory: NewUserLoginHistoryClient(cfg), Workspace: NewWorkspaceClient(cfg), @@ -269,6 +294,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) config: cfg, Admin: NewAdminClient(cfg), AdminLoginHistory: NewAdminLoginHistoryClient(cfg), + AdminRole: NewAdminRoleClient(cfg), ApiKey: NewApiKeyClient(cfg), BillingPlan: NewBillingPlanClient(cfg), BillingQuota: NewBillingQuotaClient(cfg), @@ -281,12 +307,16 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) Model: NewModelClient(cfg), ModelProvider: NewModelProviderClient(cfg), ModelProviderModel: NewModelProviderModelClient(cfg), + Role: NewRoleClient(cfg), SecurityScanning: NewSecurityScanningClient(cfg), SecurityScanningResult: NewSecurityScanningResultClient(cfg), Setting: NewSettingClient(cfg), Task: NewTaskClient(cfg), TaskRecord: NewTaskRecordClient(cfg), User: NewUserClient(cfg), + UserGroup: NewUserGroupClient(cfg), + UserGroupAdmin: NewUserGroupAdminClient(cfg), + UserGroupUser: NewUserGroupUserClient(cfg), UserIdentity: NewUserIdentityClient(cfg), UserLoginHistory: NewUserLoginHistoryClient(cfg), Workspace: NewWorkspaceClient(cfg), @@ -320,10 +350,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.Admin, c.AdminLoginHistory, c.ApiKey, c.BillingPlan, c.BillingQuota, - c.BillingRecord, c.BillingUsage, c.CodeSnippet, c.Extension, c.InviteCode, - c.License, c.Model, c.ModelProvider, c.ModelProviderModel, c.SecurityScanning, - c.SecurityScanningResult, c.Setting, c.Task, c.TaskRecord, c.User, + c.Admin, c.AdminLoginHistory, c.AdminRole, c.ApiKey, c.BillingPlan, + c.BillingQuota, c.BillingRecord, c.BillingUsage, c.CodeSnippet, c.Extension, + c.InviteCode, c.License, c.Model, c.ModelProvider, c.ModelProviderModel, + c.Role, c.SecurityScanning, c.SecurityScanningResult, c.Setting, c.Task, + c.TaskRecord, c.User, c.UserGroup, c.UserGroupAdmin, c.UserGroupUser, c.UserIdentity, c.UserLoginHistory, c.Workspace, c.WorkspaceFile, } { n.Use(hooks...) @@ -334,10 +365,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.Admin, c.AdminLoginHistory, c.ApiKey, c.BillingPlan, c.BillingQuota, - c.BillingRecord, c.BillingUsage, c.CodeSnippet, c.Extension, c.InviteCode, - c.License, c.Model, c.ModelProvider, c.ModelProviderModel, c.SecurityScanning, - c.SecurityScanningResult, c.Setting, c.Task, c.TaskRecord, c.User, + c.Admin, c.AdminLoginHistory, c.AdminRole, c.ApiKey, c.BillingPlan, + c.BillingQuota, c.BillingRecord, c.BillingUsage, c.CodeSnippet, c.Extension, + c.InviteCode, c.License, c.Model, c.ModelProvider, c.ModelProviderModel, + c.Role, c.SecurityScanning, c.SecurityScanningResult, c.Setting, c.Task, + c.TaskRecord, c.User, c.UserGroup, c.UserGroupAdmin, c.UserGroupUser, c.UserIdentity, c.UserLoginHistory, c.Workspace, c.WorkspaceFile, } { n.Intercept(interceptors...) @@ -351,6 +383,8 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { return c.Admin.mutate(ctx, m) case *AdminLoginHistoryMutation: return c.AdminLoginHistory.mutate(ctx, m) + case *AdminRoleMutation: + return c.AdminRole.mutate(ctx, m) case *ApiKeyMutation: return c.ApiKey.mutate(ctx, m) case *BillingPlanMutation: @@ -375,6 +409,8 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { return c.ModelProvider.mutate(ctx, m) case *ModelProviderModelMutation: return c.ModelProviderModel.mutate(ctx, m) + case *RoleMutation: + return c.Role.mutate(ctx, m) case *SecurityScanningMutation: return c.SecurityScanning.mutate(ctx, m) case *SecurityScanningResultMutation: @@ -387,6 +423,12 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { return c.TaskRecord.mutate(ctx, m) case *UserMutation: return c.User.mutate(ctx, m) + case *UserGroupMutation: + return c.UserGroup.mutate(ctx, m) + case *UserGroupAdminMutation: + return c.UserGroupAdmin.mutate(ctx, m) + case *UserGroupUserMutation: + return c.UserGroupUser.mutate(ctx, m) case *UserIdentityMutation: return c.UserIdentity.mutate(ctx, m) case *UserLoginHistoryMutation: @@ -524,6 +566,86 @@ func (c *AdminClient) QueryLoginHistories(a *Admin) *AdminLoginHistoryQuery { return query } +// QueryMyusergroups queries the myusergroups edge of a Admin. +func (c *AdminClient) QueryMyusergroups(a *Admin) *UserGroupQuery { + query := (&UserGroupClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := a.ID + step := sqlgraph.NewStep( + sqlgraph.From(admin.Table, admin.FieldID, id), + sqlgraph.To(usergroup.Table, usergroup.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, admin.MyusergroupsTable, admin.MyusergroupsColumn), + ) + fromV = sqlgraph.Neighbors(a.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryUsergroups queries the usergroups edge of a Admin. +func (c *AdminClient) QueryUsergroups(a *Admin) *UserGroupQuery { + query := (&UserGroupClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := a.ID + step := sqlgraph.NewStep( + sqlgraph.From(admin.Table, admin.FieldID, id), + sqlgraph.To(usergroup.Table, usergroup.FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, admin.UsergroupsTable, admin.UsergroupsPrimaryKey...), + ) + fromV = sqlgraph.Neighbors(a.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryRoles queries the roles edge of a Admin. +func (c *AdminClient) QueryRoles(a *Admin) *RoleQuery { + query := (&RoleClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := a.ID + step := sqlgraph.NewStep( + sqlgraph.From(admin.Table, admin.FieldID, id), + sqlgraph.To(role.Table, role.FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, admin.RolesTable, admin.RolesPrimaryKey...), + ) + fromV = sqlgraph.Neighbors(a.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryUserGroupAdmins queries the user_group_admins edge of a Admin. +func (c *AdminClient) QueryUserGroupAdmins(a *Admin) *UserGroupAdminQuery { + query := (&UserGroupAdminClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := a.ID + step := sqlgraph.NewStep( + sqlgraph.From(admin.Table, admin.FieldID, id), + sqlgraph.To(usergroupadmin.Table, usergroupadmin.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, admin.UserGroupAdminsTable, admin.UserGroupAdminsColumn), + ) + fromV = sqlgraph.Neighbors(a.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryAdminRoles queries the admin_roles edge of a Admin. +func (c *AdminClient) QueryAdminRoles(a *Admin) *AdminRoleQuery { + query := (&AdminRoleClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := a.ID + step := sqlgraph.NewStep( + sqlgraph.From(admin.Table, admin.FieldID, id), + sqlgraph.To(adminrole.Table, adminrole.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, admin.AdminRolesTable, admin.AdminRolesColumn), + ) + fromV = sqlgraph.Neighbors(a.driver.Dialect(), step) + return fromV, nil + } + return query +} + // Hooks returns the client hooks. func (c *AdminClient) Hooks() []Hook { return c.hooks.Admin @@ -698,6 +820,171 @@ func (c *AdminLoginHistoryClient) mutate(ctx context.Context, m *AdminLoginHisto } } +// AdminRoleClient is a client for the AdminRole schema. +type AdminRoleClient struct { + config +} + +// NewAdminRoleClient returns a client for the AdminRole from the given config. +func NewAdminRoleClient(c config) *AdminRoleClient { + return &AdminRoleClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `adminrole.Hooks(f(g(h())))`. +func (c *AdminRoleClient) Use(hooks ...Hook) { + c.hooks.AdminRole = append(c.hooks.AdminRole, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `adminrole.Intercept(f(g(h())))`. +func (c *AdminRoleClient) Intercept(interceptors ...Interceptor) { + c.inters.AdminRole = append(c.inters.AdminRole, interceptors...) +} + +// Create returns a builder for creating a AdminRole entity. +func (c *AdminRoleClient) Create() *AdminRoleCreate { + mutation := newAdminRoleMutation(c.config, OpCreate) + return &AdminRoleCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of AdminRole entities. +func (c *AdminRoleClient) CreateBulk(builders ...*AdminRoleCreate) *AdminRoleCreateBulk { + return &AdminRoleCreateBulk{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 *AdminRoleClient) MapCreateBulk(slice any, setFunc func(*AdminRoleCreate, int)) *AdminRoleCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &AdminRoleCreateBulk{err: fmt.Errorf("calling to AdminRoleClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*AdminRoleCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &AdminRoleCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for AdminRole. +func (c *AdminRoleClient) Update() *AdminRoleUpdate { + mutation := newAdminRoleMutation(c.config, OpUpdate) + return &AdminRoleUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *AdminRoleClient) UpdateOne(ar *AdminRole) *AdminRoleUpdateOne { + mutation := newAdminRoleMutation(c.config, OpUpdateOne, withAdminRole(ar)) + return &AdminRoleUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *AdminRoleClient) UpdateOneID(id uuid.UUID) *AdminRoleUpdateOne { + mutation := newAdminRoleMutation(c.config, OpUpdateOne, withAdminRoleID(id)) + return &AdminRoleUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for AdminRole. +func (c *AdminRoleClient) Delete() *AdminRoleDelete { + mutation := newAdminRoleMutation(c.config, OpDelete) + return &AdminRoleDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *AdminRoleClient) DeleteOne(ar *AdminRole) *AdminRoleDeleteOne { + return c.DeleteOneID(ar.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *AdminRoleClient) DeleteOneID(id uuid.UUID) *AdminRoleDeleteOne { + builder := c.Delete().Where(adminrole.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &AdminRoleDeleteOne{builder} +} + +// Query returns a query builder for AdminRole. +func (c *AdminRoleClient) Query() *AdminRoleQuery { + return &AdminRoleQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeAdminRole}, + inters: c.Interceptors(), + } +} + +// Get returns a AdminRole entity by its id. +func (c *AdminRoleClient) Get(ctx context.Context, id uuid.UUID) (*AdminRole, error) { + return c.Query().Where(adminrole.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *AdminRoleClient) GetX(ctx context.Context, id uuid.UUID) *AdminRole { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryAdmin queries the admin edge of a AdminRole. +func (c *AdminRoleClient) QueryAdmin(ar *AdminRole) *AdminQuery { + query := (&AdminClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := ar.ID + step := sqlgraph.NewStep( + sqlgraph.From(adminrole.Table, adminrole.FieldID, id), + sqlgraph.To(admin.Table, admin.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, adminrole.AdminTable, adminrole.AdminColumn), + ) + fromV = sqlgraph.Neighbors(ar.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryRole queries the role edge of a AdminRole. +func (c *AdminRoleClient) QueryRole(ar *AdminRole) *RoleQuery { + query := (&RoleClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := ar.ID + step := sqlgraph.NewStep( + sqlgraph.From(adminrole.Table, adminrole.FieldID, id), + sqlgraph.To(role.Table, role.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, adminrole.RoleTable, adminrole.RoleColumn), + ) + fromV = sqlgraph.Neighbors(ar.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *AdminRoleClient) Hooks() []Hook { + return c.hooks.AdminRole +} + +// Interceptors returns the client interceptors. +func (c *AdminRoleClient) Interceptors() []Interceptor { + return c.inters.AdminRole +} + +func (c *AdminRoleClient) mutate(ctx context.Context, m *AdminRoleMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&AdminRoleCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&AdminRoleUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&AdminRoleUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&AdminRoleDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown AdminRole mutation op: %q", m.Op()) + } +} + // ApiKeyClient is a client for the ApiKey schema. type ApiKeyClient struct { config @@ -2394,6 +2681,171 @@ func (c *ModelProviderModelClient) mutate(ctx context.Context, m *ModelProviderM } } +// RoleClient is a client for the Role schema. +type RoleClient struct { + config +} + +// NewRoleClient returns a client for the Role from the given config. +func NewRoleClient(c config) *RoleClient { + return &RoleClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `role.Hooks(f(g(h())))`. +func (c *RoleClient) Use(hooks ...Hook) { + c.hooks.Role = append(c.hooks.Role, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `role.Intercept(f(g(h())))`. +func (c *RoleClient) Intercept(interceptors ...Interceptor) { + c.inters.Role = append(c.inters.Role, interceptors...) +} + +// Create returns a builder for creating a Role entity. +func (c *RoleClient) Create() *RoleCreate { + mutation := newRoleMutation(c.config, OpCreate) + return &RoleCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Role entities. +func (c *RoleClient) CreateBulk(builders ...*RoleCreate) *RoleCreateBulk { + return &RoleCreateBulk{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 *RoleClient) MapCreateBulk(slice any, setFunc func(*RoleCreate, int)) *RoleCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &RoleCreateBulk{err: fmt.Errorf("calling to RoleClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*RoleCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &RoleCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Role. +func (c *RoleClient) Update() *RoleUpdate { + mutation := newRoleMutation(c.config, OpUpdate) + return &RoleUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *RoleClient) UpdateOne(r *Role) *RoleUpdateOne { + mutation := newRoleMutation(c.config, OpUpdateOne, withRole(r)) + return &RoleUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *RoleClient) UpdateOneID(id int64) *RoleUpdateOne { + mutation := newRoleMutation(c.config, OpUpdateOne, withRoleID(id)) + return &RoleUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Role. +func (c *RoleClient) Delete() *RoleDelete { + mutation := newRoleMutation(c.config, OpDelete) + return &RoleDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *RoleClient) DeleteOne(r *Role) *RoleDeleteOne { + return c.DeleteOneID(r.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *RoleClient) DeleteOneID(id int64) *RoleDeleteOne { + builder := c.Delete().Where(role.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &RoleDeleteOne{builder} +} + +// Query returns a query builder for Role. +func (c *RoleClient) Query() *RoleQuery { + return &RoleQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeRole}, + inters: c.Interceptors(), + } +} + +// Get returns a Role entity by its id. +func (c *RoleClient) Get(ctx context.Context, id int64) (*Role, error) { + return c.Query().Where(role.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *RoleClient) GetX(ctx context.Context, id int64) *Role { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryAdmins queries the admins edge of a Role. +func (c *RoleClient) QueryAdmins(r *Role) *AdminQuery { + query := (&AdminClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := r.ID + step := sqlgraph.NewStep( + sqlgraph.From(role.Table, role.FieldID, id), + sqlgraph.To(admin.Table, admin.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, role.AdminsTable, role.AdminsPrimaryKey...), + ) + fromV = sqlgraph.Neighbors(r.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryAdminRoles queries the admin_roles edge of a Role. +func (c *RoleClient) QueryAdminRoles(r *Role) *AdminRoleQuery { + query := (&AdminRoleClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := r.ID + step := sqlgraph.NewStep( + sqlgraph.From(role.Table, role.FieldID, id), + sqlgraph.To(adminrole.Table, adminrole.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, role.AdminRolesTable, role.AdminRolesColumn), + ) + fromV = sqlgraph.Neighbors(r.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *RoleClient) Hooks() []Hook { + return c.hooks.Role +} + +// Interceptors returns the client interceptors. +func (c *RoleClient) Interceptors() []Interceptor { + return c.inters.Role +} + +func (c *RoleClient) mutate(ctx context.Context, m *RoleMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&RoleCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&RoleUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&RoleUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&RoleDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown Role mutation op: %q", m.Op()) + } +} + // SecurityScanningClient is a client for the SecurityScanning schema. type SecurityScanningClient struct { config @@ -3423,16 +3875,48 @@ func (c *UserClient) QuerySecurityScannings(u *User) *SecurityScanningQuery { return query } -// Hooks returns the client hooks. -func (c *UserClient) Hooks() []Hook { - hooks := c.hooks.User - return append(hooks[:len(hooks):len(hooks)], user.Hooks[:]...) +// QueryGroups queries the groups edge of a User. +func (c *UserClient) QueryGroups(u *User) *UserGroupQuery { + query := (&UserGroupClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := u.ID + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, id), + sqlgraph.To(usergroup.Table, usergroup.FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, user.GroupsTable, user.GroupsPrimaryKey...), + ) + fromV = sqlgraph.Neighbors(u.driver.Dialect(), step) + return fromV, nil + } + return query } -// Interceptors returns the client interceptors. -func (c *UserClient) Interceptors() []Interceptor { - inters := c.inters.User - return append(inters[:len(inters):len(inters)], user.Interceptors[:]...) +// QueryUserGroups queries the user_groups edge of a User. +func (c *UserClient) QueryUserGroups(u *User) *UserGroupUserQuery { + query := (&UserGroupUserClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := u.ID + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, id), + sqlgraph.To(usergroupuser.Table, usergroupuser.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, user.UserGroupsTable, user.UserGroupsColumn), + ) + fromV = sqlgraph.Neighbors(u.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *UserClient) Hooks() []Hook { + hooks := c.hooks.User + return append(hooks[:len(hooks):len(hooks)], user.Hooks[:]...) +} + +// Interceptors returns the client interceptors. +func (c *UserClient) Interceptors() []Interceptor { + inters := c.inters.User + return append(inters[:len(inters):len(inters)], user.Interceptors[:]...) } func (c *UserClient) mutate(ctx context.Context, m *UserMutation) (Value, error) { @@ -3450,6 +3934,549 @@ func (c *UserClient) mutate(ctx context.Context, m *UserMutation) (Value, error) } } +// UserGroupClient is a client for the UserGroup schema. +type UserGroupClient struct { + config +} + +// NewUserGroupClient returns a client for the UserGroup from the given config. +func NewUserGroupClient(c config) *UserGroupClient { + return &UserGroupClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `usergroup.Hooks(f(g(h())))`. +func (c *UserGroupClient) Use(hooks ...Hook) { + c.hooks.UserGroup = append(c.hooks.UserGroup, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `usergroup.Intercept(f(g(h())))`. +func (c *UserGroupClient) Intercept(interceptors ...Interceptor) { + c.inters.UserGroup = append(c.inters.UserGroup, interceptors...) +} + +// Create returns a builder for creating a UserGroup entity. +func (c *UserGroupClient) Create() *UserGroupCreate { + mutation := newUserGroupMutation(c.config, OpCreate) + return &UserGroupCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of UserGroup entities. +func (c *UserGroupClient) CreateBulk(builders ...*UserGroupCreate) *UserGroupCreateBulk { + return &UserGroupCreateBulk{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 *UserGroupClient) MapCreateBulk(slice any, setFunc func(*UserGroupCreate, int)) *UserGroupCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &UserGroupCreateBulk{err: fmt.Errorf("calling to UserGroupClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*UserGroupCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &UserGroupCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for UserGroup. +func (c *UserGroupClient) Update() *UserGroupUpdate { + mutation := newUserGroupMutation(c.config, OpUpdate) + return &UserGroupUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *UserGroupClient) UpdateOne(ug *UserGroup) *UserGroupUpdateOne { + mutation := newUserGroupMutation(c.config, OpUpdateOne, withUserGroup(ug)) + return &UserGroupUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *UserGroupClient) UpdateOneID(id uuid.UUID) *UserGroupUpdateOne { + mutation := newUserGroupMutation(c.config, OpUpdateOne, withUserGroupID(id)) + return &UserGroupUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for UserGroup. +func (c *UserGroupClient) Delete() *UserGroupDelete { + mutation := newUserGroupMutation(c.config, OpDelete) + return &UserGroupDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *UserGroupClient) DeleteOne(ug *UserGroup) *UserGroupDeleteOne { + return c.DeleteOneID(ug.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *UserGroupClient) DeleteOneID(id uuid.UUID) *UserGroupDeleteOne { + builder := c.Delete().Where(usergroup.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &UserGroupDeleteOne{builder} +} + +// Query returns a query builder for UserGroup. +func (c *UserGroupClient) Query() *UserGroupQuery { + return &UserGroupQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeUserGroup}, + inters: c.Interceptors(), + } +} + +// Get returns a UserGroup entity by its id. +func (c *UserGroupClient) Get(ctx context.Context, id uuid.UUID) (*UserGroup, error) { + return c.Query().Where(usergroup.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *UserGroupClient) GetX(ctx context.Context, id uuid.UUID) *UserGroup { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryOwner queries the owner edge of a UserGroup. +func (c *UserGroupClient) QueryOwner(ug *UserGroup) *AdminQuery { + query := (&AdminClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := ug.ID + step := sqlgraph.NewStep( + sqlgraph.From(usergroup.Table, usergroup.FieldID, id), + sqlgraph.To(admin.Table, admin.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, usergroup.OwnerTable, usergroup.OwnerColumn), + ) + fromV = sqlgraph.Neighbors(ug.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryUsers queries the users edge of a UserGroup. +func (c *UserGroupClient) QueryUsers(ug *UserGroup) *UserQuery { + query := (&UserClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := ug.ID + step := sqlgraph.NewStep( + sqlgraph.From(usergroup.Table, usergroup.FieldID, id), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, usergroup.UsersTable, usergroup.UsersPrimaryKey...), + ) + fromV = sqlgraph.Neighbors(ug.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryAdmins queries the admins edge of a UserGroup. +func (c *UserGroupClient) QueryAdmins(ug *UserGroup) *AdminQuery { + query := (&AdminClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := ug.ID + step := sqlgraph.NewStep( + sqlgraph.From(usergroup.Table, usergroup.FieldID, id), + sqlgraph.To(admin.Table, admin.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, usergroup.AdminsTable, usergroup.AdminsPrimaryKey...), + ) + fromV = sqlgraph.Neighbors(ug.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryUserGroups queries the user_groups edge of a UserGroup. +func (c *UserGroupClient) QueryUserGroups(ug *UserGroup) *UserGroupUserQuery { + query := (&UserGroupUserClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := ug.ID + step := sqlgraph.NewStep( + sqlgraph.From(usergroup.Table, usergroup.FieldID, id), + sqlgraph.To(usergroupuser.Table, usergroupuser.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, usergroup.UserGroupsTable, usergroup.UserGroupsColumn), + ) + fromV = sqlgraph.Neighbors(ug.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryUserGroupAdmins queries the user_group_admins edge of a UserGroup. +func (c *UserGroupClient) QueryUserGroupAdmins(ug *UserGroup) *UserGroupAdminQuery { + query := (&UserGroupAdminClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := ug.ID + step := sqlgraph.NewStep( + sqlgraph.From(usergroup.Table, usergroup.FieldID, id), + sqlgraph.To(usergroupadmin.Table, usergroupadmin.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, usergroup.UserGroupAdminsTable, usergroup.UserGroupAdminsColumn), + ) + fromV = sqlgraph.Neighbors(ug.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *UserGroupClient) Hooks() []Hook { + return c.hooks.UserGroup +} + +// Interceptors returns the client interceptors. +func (c *UserGroupClient) Interceptors() []Interceptor { + return c.inters.UserGroup +} + +func (c *UserGroupClient) mutate(ctx context.Context, m *UserGroupMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&UserGroupCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&UserGroupUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&UserGroupUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&UserGroupDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown UserGroup mutation op: %q", m.Op()) + } +} + +// UserGroupAdminClient is a client for the UserGroupAdmin schema. +type UserGroupAdminClient struct { + config +} + +// NewUserGroupAdminClient returns a client for the UserGroupAdmin from the given config. +func NewUserGroupAdminClient(c config) *UserGroupAdminClient { + return &UserGroupAdminClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `usergroupadmin.Hooks(f(g(h())))`. +func (c *UserGroupAdminClient) Use(hooks ...Hook) { + c.hooks.UserGroupAdmin = append(c.hooks.UserGroupAdmin, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `usergroupadmin.Intercept(f(g(h())))`. +func (c *UserGroupAdminClient) Intercept(interceptors ...Interceptor) { + c.inters.UserGroupAdmin = append(c.inters.UserGroupAdmin, interceptors...) +} + +// Create returns a builder for creating a UserGroupAdmin entity. +func (c *UserGroupAdminClient) Create() *UserGroupAdminCreate { + mutation := newUserGroupAdminMutation(c.config, OpCreate) + return &UserGroupAdminCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of UserGroupAdmin entities. +func (c *UserGroupAdminClient) CreateBulk(builders ...*UserGroupAdminCreate) *UserGroupAdminCreateBulk { + return &UserGroupAdminCreateBulk{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 *UserGroupAdminClient) MapCreateBulk(slice any, setFunc func(*UserGroupAdminCreate, int)) *UserGroupAdminCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &UserGroupAdminCreateBulk{err: fmt.Errorf("calling to UserGroupAdminClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*UserGroupAdminCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &UserGroupAdminCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for UserGroupAdmin. +func (c *UserGroupAdminClient) Update() *UserGroupAdminUpdate { + mutation := newUserGroupAdminMutation(c.config, OpUpdate) + return &UserGroupAdminUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *UserGroupAdminClient) UpdateOne(uga *UserGroupAdmin) *UserGroupAdminUpdateOne { + mutation := newUserGroupAdminMutation(c.config, OpUpdateOne, withUserGroupAdmin(uga)) + return &UserGroupAdminUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *UserGroupAdminClient) UpdateOneID(id uuid.UUID) *UserGroupAdminUpdateOne { + mutation := newUserGroupAdminMutation(c.config, OpUpdateOne, withUserGroupAdminID(id)) + return &UserGroupAdminUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for UserGroupAdmin. +func (c *UserGroupAdminClient) Delete() *UserGroupAdminDelete { + mutation := newUserGroupAdminMutation(c.config, OpDelete) + return &UserGroupAdminDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *UserGroupAdminClient) DeleteOne(uga *UserGroupAdmin) *UserGroupAdminDeleteOne { + return c.DeleteOneID(uga.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *UserGroupAdminClient) DeleteOneID(id uuid.UUID) *UserGroupAdminDeleteOne { + builder := c.Delete().Where(usergroupadmin.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &UserGroupAdminDeleteOne{builder} +} + +// Query returns a query builder for UserGroupAdmin. +func (c *UserGroupAdminClient) Query() *UserGroupAdminQuery { + return &UserGroupAdminQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeUserGroupAdmin}, + inters: c.Interceptors(), + } +} + +// Get returns a UserGroupAdmin entity by its id. +func (c *UserGroupAdminClient) Get(ctx context.Context, id uuid.UUID) (*UserGroupAdmin, error) { + return c.Query().Where(usergroupadmin.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *UserGroupAdminClient) GetX(ctx context.Context, id uuid.UUID) *UserGroupAdmin { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryUserGroup queries the user_group edge of a UserGroupAdmin. +func (c *UserGroupAdminClient) QueryUserGroup(uga *UserGroupAdmin) *UserGroupQuery { + query := (&UserGroupClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := uga.ID + step := sqlgraph.NewStep( + sqlgraph.From(usergroupadmin.Table, usergroupadmin.FieldID, id), + sqlgraph.To(usergroup.Table, usergroup.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, usergroupadmin.UserGroupTable, usergroupadmin.UserGroupColumn), + ) + fromV = sqlgraph.Neighbors(uga.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryAdmin queries the admin edge of a UserGroupAdmin. +func (c *UserGroupAdminClient) QueryAdmin(uga *UserGroupAdmin) *AdminQuery { + query := (&AdminClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := uga.ID + step := sqlgraph.NewStep( + sqlgraph.From(usergroupadmin.Table, usergroupadmin.FieldID, id), + sqlgraph.To(admin.Table, admin.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, usergroupadmin.AdminTable, usergroupadmin.AdminColumn), + ) + fromV = sqlgraph.Neighbors(uga.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *UserGroupAdminClient) Hooks() []Hook { + return c.hooks.UserGroupAdmin +} + +// Interceptors returns the client interceptors. +func (c *UserGroupAdminClient) Interceptors() []Interceptor { + return c.inters.UserGroupAdmin +} + +func (c *UserGroupAdminClient) mutate(ctx context.Context, m *UserGroupAdminMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&UserGroupAdminCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&UserGroupAdminUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&UserGroupAdminUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&UserGroupAdminDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown UserGroupAdmin mutation op: %q", m.Op()) + } +} + +// UserGroupUserClient is a client for the UserGroupUser schema. +type UserGroupUserClient struct { + config +} + +// NewUserGroupUserClient returns a client for the UserGroupUser from the given config. +func NewUserGroupUserClient(c config) *UserGroupUserClient { + return &UserGroupUserClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `usergroupuser.Hooks(f(g(h())))`. +func (c *UserGroupUserClient) Use(hooks ...Hook) { + c.hooks.UserGroupUser = append(c.hooks.UserGroupUser, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `usergroupuser.Intercept(f(g(h())))`. +func (c *UserGroupUserClient) Intercept(interceptors ...Interceptor) { + c.inters.UserGroupUser = append(c.inters.UserGroupUser, interceptors...) +} + +// Create returns a builder for creating a UserGroupUser entity. +func (c *UserGroupUserClient) Create() *UserGroupUserCreate { + mutation := newUserGroupUserMutation(c.config, OpCreate) + return &UserGroupUserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of UserGroupUser entities. +func (c *UserGroupUserClient) CreateBulk(builders ...*UserGroupUserCreate) *UserGroupUserCreateBulk { + return &UserGroupUserCreateBulk{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 *UserGroupUserClient) MapCreateBulk(slice any, setFunc func(*UserGroupUserCreate, int)) *UserGroupUserCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &UserGroupUserCreateBulk{err: fmt.Errorf("calling to UserGroupUserClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*UserGroupUserCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &UserGroupUserCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for UserGroupUser. +func (c *UserGroupUserClient) Update() *UserGroupUserUpdate { + mutation := newUserGroupUserMutation(c.config, OpUpdate) + return &UserGroupUserUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *UserGroupUserClient) UpdateOne(ugu *UserGroupUser) *UserGroupUserUpdateOne { + mutation := newUserGroupUserMutation(c.config, OpUpdateOne, withUserGroupUser(ugu)) + return &UserGroupUserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *UserGroupUserClient) UpdateOneID(id uuid.UUID) *UserGroupUserUpdateOne { + mutation := newUserGroupUserMutation(c.config, OpUpdateOne, withUserGroupUserID(id)) + return &UserGroupUserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for UserGroupUser. +func (c *UserGroupUserClient) Delete() *UserGroupUserDelete { + mutation := newUserGroupUserMutation(c.config, OpDelete) + return &UserGroupUserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *UserGroupUserClient) DeleteOne(ugu *UserGroupUser) *UserGroupUserDeleteOne { + return c.DeleteOneID(ugu.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *UserGroupUserClient) DeleteOneID(id uuid.UUID) *UserGroupUserDeleteOne { + builder := c.Delete().Where(usergroupuser.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &UserGroupUserDeleteOne{builder} +} + +// Query returns a query builder for UserGroupUser. +func (c *UserGroupUserClient) Query() *UserGroupUserQuery { + return &UserGroupUserQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeUserGroupUser}, + inters: c.Interceptors(), + } +} + +// Get returns a UserGroupUser entity by its id. +func (c *UserGroupUserClient) Get(ctx context.Context, id uuid.UUID) (*UserGroupUser, error) { + return c.Query().Where(usergroupuser.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *UserGroupUserClient) GetX(ctx context.Context, id uuid.UUID) *UserGroupUser { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryUserGroup queries the user_group edge of a UserGroupUser. +func (c *UserGroupUserClient) QueryUserGroup(ugu *UserGroupUser) *UserGroupQuery { + query := (&UserGroupClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := ugu.ID + step := sqlgraph.NewStep( + sqlgraph.From(usergroupuser.Table, usergroupuser.FieldID, id), + sqlgraph.To(usergroup.Table, usergroup.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, usergroupuser.UserGroupTable, usergroupuser.UserGroupColumn), + ) + fromV = sqlgraph.Neighbors(ugu.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryUser queries the user edge of a UserGroupUser. +func (c *UserGroupUserClient) QueryUser(ugu *UserGroupUser) *UserQuery { + query := (&UserClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := ugu.ID + step := sqlgraph.NewStep( + sqlgraph.From(usergroupuser.Table, usergroupuser.FieldID, id), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, usergroupuser.UserTable, usergroupuser.UserColumn), + ) + fromV = sqlgraph.Neighbors(ugu.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *UserGroupUserClient) Hooks() []Hook { + return c.hooks.UserGroupUser +} + +// Interceptors returns the client interceptors. +func (c *UserGroupUserClient) Interceptors() []Interceptor { + return c.inters.UserGroupUser +} + +func (c *UserGroupUserClient) mutate(ctx context.Context, m *UserGroupUserMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&UserGroupUserCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&UserGroupUserUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&UserGroupUserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&UserGroupUserDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown UserGroupUser mutation op: %q", m.Op()) + } +} + // UserIdentityClient is a client for the UserIdentity schema. type UserIdentityClient struct { config @@ -4115,17 +5142,19 @@ func (c *WorkspaceFileClient) mutate(ctx context.Context, m *WorkspaceFileMutati // hooks and interceptors per client, for fast access. type ( hooks struct { - Admin, AdminLoginHistory, ApiKey, BillingPlan, BillingQuota, BillingRecord, - BillingUsage, CodeSnippet, Extension, InviteCode, License, Model, - ModelProvider, ModelProviderModel, SecurityScanning, SecurityScanningResult, - Setting, Task, TaskRecord, User, UserIdentity, UserLoginHistory, Workspace, + Admin, AdminLoginHistory, AdminRole, ApiKey, BillingPlan, BillingQuota, + BillingRecord, BillingUsage, CodeSnippet, Extension, InviteCode, License, + Model, ModelProvider, ModelProviderModel, Role, SecurityScanning, + SecurityScanningResult, Setting, Task, TaskRecord, User, UserGroup, + UserGroupAdmin, UserGroupUser, UserIdentity, UserLoginHistory, Workspace, WorkspaceFile []ent.Hook } inters struct { - Admin, AdminLoginHistory, ApiKey, BillingPlan, BillingQuota, BillingRecord, - BillingUsage, CodeSnippet, Extension, InviteCode, License, Model, - ModelProvider, ModelProviderModel, SecurityScanning, SecurityScanningResult, - Setting, Task, TaskRecord, User, UserIdentity, UserLoginHistory, Workspace, + Admin, AdminLoginHistory, AdminRole, ApiKey, BillingPlan, BillingQuota, + BillingRecord, BillingUsage, CodeSnippet, Extension, InviteCode, License, + Model, ModelProvider, ModelProviderModel, Role, SecurityScanning, + SecurityScanningResult, Setting, Task, TaskRecord, User, UserGroup, + UserGroupAdmin, UserGroupUser, UserIdentity, UserLoginHistory, Workspace, WorkspaceFile []ent.Interceptor } ) diff --git a/backend/db/ent.go b/backend/db/ent.go index 9a1f4c74..b8714059 100644 --- a/backend/db/ent.go +++ b/backend/db/ent.go @@ -14,6 +14,7 @@ import ( "entgo.io/ent/dialect/sql/sqlgraph" "github.com/chaitin/MonkeyCode/backend/db/admin" "github.com/chaitin/MonkeyCode/backend/db/adminloginhistory" + "github.com/chaitin/MonkeyCode/backend/db/adminrole" "github.com/chaitin/MonkeyCode/backend/db/apikey" "github.com/chaitin/MonkeyCode/backend/db/billingplan" "github.com/chaitin/MonkeyCode/backend/db/billingquota" @@ -26,12 +27,16 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/model" "github.com/chaitin/MonkeyCode/backend/db/modelprovider" "github.com/chaitin/MonkeyCode/backend/db/modelprovidermodel" + "github.com/chaitin/MonkeyCode/backend/db/role" "github.com/chaitin/MonkeyCode/backend/db/securityscanning" "github.com/chaitin/MonkeyCode/backend/db/securityscanningresult" "github.com/chaitin/MonkeyCode/backend/db/setting" "github.com/chaitin/MonkeyCode/backend/db/task" "github.com/chaitin/MonkeyCode/backend/db/taskrecord" "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/usergroup" + "github.com/chaitin/MonkeyCode/backend/db/usergroupadmin" + "github.com/chaitin/MonkeyCode/backend/db/usergroupuser" "github.com/chaitin/MonkeyCode/backend/db/useridentity" "github.com/chaitin/MonkeyCode/backend/db/userloginhistory" "github.com/chaitin/MonkeyCode/backend/db/workspace" @@ -98,6 +103,7 @@ func checkColumn(table, column string) error { columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ admin.Table: admin.ValidColumn, adminloginhistory.Table: adminloginhistory.ValidColumn, + adminrole.Table: adminrole.ValidColumn, apikey.Table: apikey.ValidColumn, billingplan.Table: billingplan.ValidColumn, billingquota.Table: billingquota.ValidColumn, @@ -110,12 +116,16 @@ func checkColumn(table, column string) error { model.Table: model.ValidColumn, modelprovider.Table: modelprovider.ValidColumn, modelprovidermodel.Table: modelprovidermodel.ValidColumn, + role.Table: role.ValidColumn, securityscanning.Table: securityscanning.ValidColumn, securityscanningresult.Table: securityscanningresult.ValidColumn, setting.Table: setting.ValidColumn, task.Table: task.ValidColumn, taskrecord.Table: taskrecord.ValidColumn, user.Table: user.ValidColumn, + usergroup.Table: usergroup.ValidColumn, + usergroupadmin.Table: usergroupadmin.ValidColumn, + usergroupuser.Table: usergroupuser.ValidColumn, useridentity.Table: useridentity.ValidColumn, userloginhistory.Table: userloginhistory.ValidColumn, workspace.Table: workspace.ValidColumn, diff --git a/backend/db/hook/hook.go b/backend/db/hook/hook.go index 16263b75..00add62e 100644 --- a/backend/db/hook/hook.go +++ b/backend/db/hook/hook.go @@ -33,6 +33,18 @@ func (f AdminLoginHistoryFunc) Mutate(ctx context.Context, m db.Mutation) (db.Va return nil, fmt.Errorf("unexpected mutation type %T. expect *db.AdminLoginHistoryMutation", m) } +// The AdminRoleFunc type is an adapter to allow the use of ordinary +// function as AdminRole mutator. +type AdminRoleFunc func(context.Context, *db.AdminRoleMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f AdminRoleFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.AdminRoleMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.AdminRoleMutation", m) +} + // The ApiKeyFunc type is an adapter to allow the use of ordinary // function as ApiKey mutator. type ApiKeyFunc func(context.Context, *db.ApiKeyMutation) (db.Value, error) @@ -177,6 +189,18 @@ func (f ModelProviderModelFunc) Mutate(ctx context.Context, m db.Mutation) (db.V return nil, fmt.Errorf("unexpected mutation type %T. expect *db.ModelProviderModelMutation", m) } +// The RoleFunc type is an adapter to allow the use of ordinary +// function as Role mutator. +type RoleFunc func(context.Context, *db.RoleMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f RoleFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.RoleMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.RoleMutation", m) +} + // The SecurityScanningFunc type is an adapter to allow the use of ordinary // function as SecurityScanning mutator. type SecurityScanningFunc func(context.Context, *db.SecurityScanningMutation) (db.Value, error) @@ -249,6 +273,42 @@ func (f UserFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { return nil, fmt.Errorf("unexpected mutation type %T. expect *db.UserMutation", m) } +// The UserGroupFunc type is an adapter to allow the use of ordinary +// function as UserGroup mutator. +type UserGroupFunc func(context.Context, *db.UserGroupMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f UserGroupFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.UserGroupMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.UserGroupMutation", m) +} + +// The UserGroupAdminFunc type is an adapter to allow the use of ordinary +// function as UserGroupAdmin mutator. +type UserGroupAdminFunc func(context.Context, *db.UserGroupAdminMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f UserGroupAdminFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.UserGroupAdminMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.UserGroupAdminMutation", m) +} + +// The UserGroupUserFunc type is an adapter to allow the use of ordinary +// function as UserGroupUser mutator. +type UserGroupUserFunc func(context.Context, *db.UserGroupUserMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f UserGroupUserFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.UserGroupUserMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.UserGroupUserMutation", m) +} + // The UserIdentityFunc type is an adapter to allow the use of ordinary // function as UserIdentity mutator. type UserIdentityFunc func(context.Context, *db.UserIdentityMutation) (db.Value, error) diff --git a/backend/db/intercept/intercept.go b/backend/db/intercept/intercept.go index 54a61ff0..7aa988dc 100644 --- a/backend/db/intercept/intercept.go +++ b/backend/db/intercept/intercept.go @@ -10,6 +10,7 @@ import ( "github.com/chaitin/MonkeyCode/backend/db" "github.com/chaitin/MonkeyCode/backend/db/admin" "github.com/chaitin/MonkeyCode/backend/db/adminloginhistory" + "github.com/chaitin/MonkeyCode/backend/db/adminrole" "github.com/chaitin/MonkeyCode/backend/db/apikey" "github.com/chaitin/MonkeyCode/backend/db/billingplan" "github.com/chaitin/MonkeyCode/backend/db/billingquota" @@ -23,12 +24,16 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/modelprovider" "github.com/chaitin/MonkeyCode/backend/db/modelprovidermodel" "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/role" "github.com/chaitin/MonkeyCode/backend/db/securityscanning" "github.com/chaitin/MonkeyCode/backend/db/securityscanningresult" "github.com/chaitin/MonkeyCode/backend/db/setting" "github.com/chaitin/MonkeyCode/backend/db/task" "github.com/chaitin/MonkeyCode/backend/db/taskrecord" "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/usergroup" + "github.com/chaitin/MonkeyCode/backend/db/usergroupadmin" + "github.com/chaitin/MonkeyCode/backend/db/usergroupuser" "github.com/chaitin/MonkeyCode/backend/db/useridentity" "github.com/chaitin/MonkeyCode/backend/db/userloginhistory" "github.com/chaitin/MonkeyCode/backend/db/workspace" @@ -145,6 +150,33 @@ func (f TraverseAdminLoginHistory) Traverse(ctx context.Context, q db.Query) err return fmt.Errorf("unexpected query type %T. expect *db.AdminLoginHistoryQuery", q) } +// The AdminRoleFunc type is an adapter to allow the use of ordinary function as a Querier. +type AdminRoleFunc func(context.Context, *db.AdminRoleQuery) (db.Value, error) + +// Query calls f(ctx, q). +func (f AdminRoleFunc) Query(ctx context.Context, q db.Query) (db.Value, error) { + if q, ok := q.(*db.AdminRoleQuery); ok { + return f(ctx, q) + } + return nil, fmt.Errorf("unexpected query type %T. expect *db.AdminRoleQuery", q) +} + +// The TraverseAdminRole type is an adapter to allow the use of ordinary function as Traverser. +type TraverseAdminRole func(context.Context, *db.AdminRoleQuery) error + +// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline. +func (f TraverseAdminRole) Intercept(next db.Querier) db.Querier { + return next +} + +// Traverse calls f(ctx, q). +func (f TraverseAdminRole) Traverse(ctx context.Context, q db.Query) error { + if q, ok := q.(*db.AdminRoleQuery); ok { + return f(ctx, q) + } + return fmt.Errorf("unexpected query type %T. expect *db.AdminRoleQuery", q) +} + // The ApiKeyFunc type is an adapter to allow the use of ordinary function as a Querier. type ApiKeyFunc func(context.Context, *db.ApiKeyQuery) (db.Value, error) @@ -469,6 +501,33 @@ func (f TraverseModelProviderModel) Traverse(ctx context.Context, q db.Query) er return fmt.Errorf("unexpected query type %T. expect *db.ModelProviderModelQuery", q) } +// The RoleFunc type is an adapter to allow the use of ordinary function as a Querier. +type RoleFunc func(context.Context, *db.RoleQuery) (db.Value, error) + +// Query calls f(ctx, q). +func (f RoleFunc) Query(ctx context.Context, q db.Query) (db.Value, error) { + if q, ok := q.(*db.RoleQuery); ok { + return f(ctx, q) + } + return nil, fmt.Errorf("unexpected query type %T. expect *db.RoleQuery", q) +} + +// The TraverseRole type is an adapter to allow the use of ordinary function as Traverser. +type TraverseRole func(context.Context, *db.RoleQuery) error + +// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline. +func (f TraverseRole) Intercept(next db.Querier) db.Querier { + return next +} + +// Traverse calls f(ctx, q). +func (f TraverseRole) Traverse(ctx context.Context, q db.Query) error { + if q, ok := q.(*db.RoleQuery); ok { + return f(ctx, q) + } + return fmt.Errorf("unexpected query type %T. expect *db.RoleQuery", q) +} + // The SecurityScanningFunc type is an adapter to allow the use of ordinary function as a Querier. type SecurityScanningFunc func(context.Context, *db.SecurityScanningQuery) (db.Value, error) @@ -631,6 +690,87 @@ func (f TraverseUser) Traverse(ctx context.Context, q db.Query) error { return fmt.Errorf("unexpected query type %T. expect *db.UserQuery", q) } +// The UserGroupFunc type is an adapter to allow the use of ordinary function as a Querier. +type UserGroupFunc func(context.Context, *db.UserGroupQuery) (db.Value, error) + +// Query calls f(ctx, q). +func (f UserGroupFunc) Query(ctx context.Context, q db.Query) (db.Value, error) { + if q, ok := q.(*db.UserGroupQuery); ok { + return f(ctx, q) + } + return nil, fmt.Errorf("unexpected query type %T. expect *db.UserGroupQuery", q) +} + +// The TraverseUserGroup type is an adapter to allow the use of ordinary function as Traverser. +type TraverseUserGroup func(context.Context, *db.UserGroupQuery) error + +// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline. +func (f TraverseUserGroup) Intercept(next db.Querier) db.Querier { + return next +} + +// Traverse calls f(ctx, q). +func (f TraverseUserGroup) Traverse(ctx context.Context, q db.Query) error { + if q, ok := q.(*db.UserGroupQuery); ok { + return f(ctx, q) + } + return fmt.Errorf("unexpected query type %T. expect *db.UserGroupQuery", q) +} + +// The UserGroupAdminFunc type is an adapter to allow the use of ordinary function as a Querier. +type UserGroupAdminFunc func(context.Context, *db.UserGroupAdminQuery) (db.Value, error) + +// Query calls f(ctx, q). +func (f UserGroupAdminFunc) Query(ctx context.Context, q db.Query) (db.Value, error) { + if q, ok := q.(*db.UserGroupAdminQuery); ok { + return f(ctx, q) + } + return nil, fmt.Errorf("unexpected query type %T. expect *db.UserGroupAdminQuery", q) +} + +// The TraverseUserGroupAdmin type is an adapter to allow the use of ordinary function as Traverser. +type TraverseUserGroupAdmin func(context.Context, *db.UserGroupAdminQuery) error + +// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline. +func (f TraverseUserGroupAdmin) Intercept(next db.Querier) db.Querier { + return next +} + +// Traverse calls f(ctx, q). +func (f TraverseUserGroupAdmin) Traverse(ctx context.Context, q db.Query) error { + if q, ok := q.(*db.UserGroupAdminQuery); ok { + return f(ctx, q) + } + return fmt.Errorf("unexpected query type %T. expect *db.UserGroupAdminQuery", q) +} + +// The UserGroupUserFunc type is an adapter to allow the use of ordinary function as a Querier. +type UserGroupUserFunc func(context.Context, *db.UserGroupUserQuery) (db.Value, error) + +// Query calls f(ctx, q). +func (f UserGroupUserFunc) Query(ctx context.Context, q db.Query) (db.Value, error) { + if q, ok := q.(*db.UserGroupUserQuery); ok { + return f(ctx, q) + } + return nil, fmt.Errorf("unexpected query type %T. expect *db.UserGroupUserQuery", q) +} + +// The TraverseUserGroupUser type is an adapter to allow the use of ordinary function as Traverser. +type TraverseUserGroupUser func(context.Context, *db.UserGroupUserQuery) error + +// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline. +func (f TraverseUserGroupUser) Intercept(next db.Querier) db.Querier { + return next +} + +// Traverse calls f(ctx, q). +func (f TraverseUserGroupUser) Traverse(ctx context.Context, q db.Query) error { + if q, ok := q.(*db.UserGroupUserQuery); ok { + return f(ctx, q) + } + return fmt.Errorf("unexpected query type %T. expect *db.UserGroupUserQuery", q) +} + // The UserIdentityFunc type is an adapter to allow the use of ordinary function as a Querier. type UserIdentityFunc func(context.Context, *db.UserIdentityQuery) (db.Value, error) @@ -746,6 +886,8 @@ func NewQuery(q db.Query) (Query, error) { return &query[*db.AdminQuery, predicate.Admin, admin.OrderOption]{typ: db.TypeAdmin, tq: q}, nil case *db.AdminLoginHistoryQuery: return &query[*db.AdminLoginHistoryQuery, predicate.AdminLoginHistory, adminloginhistory.OrderOption]{typ: db.TypeAdminLoginHistory, tq: q}, nil + case *db.AdminRoleQuery: + return &query[*db.AdminRoleQuery, predicate.AdminRole, adminrole.OrderOption]{typ: db.TypeAdminRole, tq: q}, nil case *db.ApiKeyQuery: return &query[*db.ApiKeyQuery, predicate.ApiKey, apikey.OrderOption]{typ: db.TypeApiKey, tq: q}, nil case *db.BillingPlanQuery: @@ -770,6 +912,8 @@ func NewQuery(q db.Query) (Query, error) { return &query[*db.ModelProviderQuery, predicate.ModelProvider, modelprovider.OrderOption]{typ: db.TypeModelProvider, tq: q}, nil case *db.ModelProviderModelQuery: return &query[*db.ModelProviderModelQuery, predicate.ModelProviderModel, modelprovidermodel.OrderOption]{typ: db.TypeModelProviderModel, tq: q}, nil + case *db.RoleQuery: + return &query[*db.RoleQuery, predicate.Role, role.OrderOption]{typ: db.TypeRole, tq: q}, nil case *db.SecurityScanningQuery: return &query[*db.SecurityScanningQuery, predicate.SecurityScanning, securityscanning.OrderOption]{typ: db.TypeSecurityScanning, tq: q}, nil case *db.SecurityScanningResultQuery: @@ -782,6 +926,12 @@ func NewQuery(q db.Query) (Query, error) { return &query[*db.TaskRecordQuery, predicate.TaskRecord, taskrecord.OrderOption]{typ: db.TypeTaskRecord, tq: q}, nil case *db.UserQuery: return &query[*db.UserQuery, predicate.User, user.OrderOption]{typ: db.TypeUser, tq: q}, nil + case *db.UserGroupQuery: + return &query[*db.UserGroupQuery, predicate.UserGroup, usergroup.OrderOption]{typ: db.TypeUserGroup, tq: q}, nil + case *db.UserGroupAdminQuery: + return &query[*db.UserGroupAdminQuery, predicate.UserGroupAdmin, usergroupadmin.OrderOption]{typ: db.TypeUserGroupAdmin, tq: q}, nil + case *db.UserGroupUserQuery: + return &query[*db.UserGroupUserQuery, predicate.UserGroupUser, usergroupuser.OrderOption]{typ: db.TypeUserGroupUser, tq: q}, nil case *db.UserIdentityQuery: return &query[*db.UserIdentityQuery, predicate.UserIdentity, useridentity.OrderOption]{typ: db.TypeUserIdentity, tq: q}, nil case *db.UserLoginHistoryQuery: diff --git a/backend/db/migrate/schema.go b/backend/db/migrate/schema.go index c0183714..0bae29d9 100644 --- a/backend/db/migrate/schema.go +++ b/backend/db/migrate/schema.go @@ -53,6 +53,39 @@ var ( }, }, } + // AdminRolesColumns holds the columns for the "admin_roles" table. + AdminRolesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeUUID}, + {Name: "admin_id", Type: field.TypeUUID}, + {Name: "role_id", Type: field.TypeInt64}, + } + // AdminRolesTable holds the schema information for the "admin_roles" table. + AdminRolesTable = &schema.Table{ + Name: "admin_roles", + Columns: AdminRolesColumns, + PrimaryKey: []*schema.Column{AdminRolesColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "admin_roles_admins_admin", + Columns: []*schema.Column{AdminRolesColumns[1]}, + RefColumns: []*schema.Column{AdminsColumns[0]}, + OnDelete: schema.NoAction, + }, + { + Symbol: "admin_roles_roles_role", + Columns: []*schema.Column{AdminRolesColumns[2]}, + RefColumns: []*schema.Column{RolesColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + Indexes: []*schema.Index{ + { + Name: "adminrole_role_id_admin_id", + Unique: true, + Columns: []*schema.Column{AdminRolesColumns[2], AdminRolesColumns[1]}, + }, + }, + } // APIKeysColumns holds the columns for the "api_keys" table. APIKeysColumns = []*schema.Column{ {Name: "id", Type: field.TypeUUID}, @@ -336,6 +369,19 @@ var ( }, }, } + // RolesColumns holds the columns for the "roles" table. + RolesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt64, Increment: true}, + {Name: "name", Type: field.TypeString}, + {Name: "description", Type: field.TypeString, Size: 2147483647}, + {Name: "created_at", Type: field.TypeTime}, + } + // RolesTable holds the schema information for the "roles" table. + RolesTable = &schema.Table{ + Name: "roles", + Columns: RolesColumns, + PrimaryKey: []*schema.Column{RolesColumns[0]}, + } // SecurityScanningsColumns holds the columns for the "security_scannings" table. SecurityScanningsColumns = []*schema.Column{ {Name: "id", Type: field.TypeUUID}, @@ -515,6 +561,93 @@ var ( Columns: UsersColumns, PrimaryKey: []*schema.Column{UsersColumns[0]}, } + // UserGroupsColumns holds the columns for the "user_groups" table. + UserGroupsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeUUID}, + {Name: "name", Type: field.TypeString}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "admin_id", Type: field.TypeUUID}, + } + // UserGroupsTable holds the schema information for the "user_groups" table. + UserGroupsTable = &schema.Table{ + Name: "user_groups", + Columns: UserGroupsColumns, + PrimaryKey: []*schema.Column{UserGroupsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "user_groups_admins_myusergroups", + Columns: []*schema.Column{UserGroupsColumns[3]}, + RefColumns: []*schema.Column{AdminsColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + } + // UserGroupAdminsColumns holds the columns for the "user_group_admins" table. + UserGroupAdminsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeUUID}, + {Name: "user_group_id", Type: field.TypeUUID}, + {Name: "admin_id", Type: field.TypeUUID}, + } + // UserGroupAdminsTable holds the schema information for the "user_group_admins" table. + UserGroupAdminsTable = &schema.Table{ + Name: "user_group_admins", + Columns: UserGroupAdminsColumns, + PrimaryKey: []*schema.Column{UserGroupAdminsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "user_group_admins_user_groups_user_group", + Columns: []*schema.Column{UserGroupAdminsColumns[1]}, + RefColumns: []*schema.Column{UserGroupsColumns[0]}, + OnDelete: schema.NoAction, + }, + { + Symbol: "user_group_admins_admins_admin", + Columns: []*schema.Column{UserGroupAdminsColumns[2]}, + RefColumns: []*schema.Column{AdminsColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + Indexes: []*schema.Index{ + { + Name: "usergroupadmin_user_group_id_admin_id", + Unique: true, + Columns: []*schema.Column{UserGroupAdminsColumns[1], UserGroupAdminsColumns[2]}, + }, + }, + } + // UserGroupUsersColumns holds the columns for the "user_group_users" table. + UserGroupUsersColumns = []*schema.Column{ + {Name: "id", Type: field.TypeUUID}, + {Name: "user_group_id", Type: field.TypeUUID}, + {Name: "user_id", Type: field.TypeUUID}, + } + // UserGroupUsersTable holds the schema information for the "user_group_users" table. + UserGroupUsersTable = &schema.Table{ + Name: "user_group_users", + Columns: UserGroupUsersColumns, + PrimaryKey: []*schema.Column{UserGroupUsersColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "user_group_users_user_groups_user_group", + Columns: []*schema.Column{UserGroupUsersColumns[1]}, + RefColumns: []*schema.Column{UserGroupsColumns[0]}, + OnDelete: schema.NoAction, + }, + { + Symbol: "user_group_users_users_user", + Columns: []*schema.Column{UserGroupUsersColumns[2]}, + RefColumns: []*schema.Column{UsersColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + Indexes: []*schema.Index{ + { + Name: "usergroupuser_user_group_id_user_id", + Unique: true, + Columns: []*schema.Column{UserGroupUsersColumns[1], UserGroupUsersColumns[2]}, + }, + }, + } // UserIdentitiesColumns holds the columns for the "user_identities" table. UserIdentitiesColumns = []*schema.Column{ {Name: "id", Type: field.TypeUUID}, @@ -700,6 +833,7 @@ var ( Tables = []*schema.Table{ AdminsTable, AdminLoginHistoriesTable, + AdminRolesTable, APIKeysTable, BillingPlansTable, BillingQuotasTable, @@ -712,12 +846,16 @@ var ( ModelsTable, ModelProvidersTable, ModelProviderModelsTable, + RolesTable, SecurityScanningsTable, SecurityScanningResultsTable, SettingsTable, TasksTable, TaskRecordsTable, UsersTable, + UserGroupsTable, + UserGroupAdminsTable, + UserGroupUsersTable, UserIdentitiesTable, UserLoginHistoriesTable, WorkspacesTable, @@ -733,6 +871,11 @@ func init() { AdminLoginHistoriesTable.Annotation = &entsql.Annotation{ Table: "admin_login_histories", } + AdminRolesTable.ForeignKeys[0].RefTable = AdminsTable + AdminRolesTable.ForeignKeys[1].RefTable = RolesTable + AdminRolesTable.Annotation = &entsql.Annotation{ + Table: "admin_roles", + } APIKeysTable.ForeignKeys[0].RefTable = UsersTable APIKeysTable.Annotation = &entsql.Annotation{ Table: "api_keys", @@ -773,6 +916,9 @@ func init() { ModelProviderModelsTable.Annotation = &entsql.Annotation{ Table: "model_provider_models", } + RolesTable.Annotation = &entsql.Annotation{ + Table: "roles", + } SecurityScanningsTable.ForeignKeys[0].RefTable = UsersTable SecurityScanningsTable.ForeignKeys[1].RefTable = WorkspacesTable SecurityScanningsTable.Annotation = &entsql.Annotation{ @@ -797,6 +943,20 @@ func init() { UsersTable.Annotation = &entsql.Annotation{ Table: "users", } + UserGroupsTable.ForeignKeys[0].RefTable = AdminsTable + UserGroupsTable.Annotation = &entsql.Annotation{ + Table: "user_groups", + } + UserGroupAdminsTable.ForeignKeys[0].RefTable = UserGroupsTable + UserGroupAdminsTable.ForeignKeys[1].RefTable = AdminsTable + UserGroupAdminsTable.Annotation = &entsql.Annotation{ + Table: "user_group_admins", + } + UserGroupUsersTable.ForeignKeys[0].RefTable = UserGroupsTable + UserGroupUsersTable.ForeignKeys[1].RefTable = UsersTable + UserGroupUsersTable.Annotation = &entsql.Annotation{ + Table: "user_group_users", + } UserIdentitiesTable.ForeignKeys[0].RefTable = UsersTable UserIdentitiesTable.Annotation = &entsql.Annotation{ Table: "user_identities", diff --git a/backend/db/mutation.go b/backend/db/mutation.go index 03b74475..7046f0b1 100644 --- a/backend/db/mutation.go +++ b/backend/db/mutation.go @@ -14,6 +14,7 @@ import ( "github.com/chaitin/MonkeyCode/backend/consts" "github.com/chaitin/MonkeyCode/backend/db/admin" "github.com/chaitin/MonkeyCode/backend/db/adminloginhistory" + "github.com/chaitin/MonkeyCode/backend/db/adminrole" "github.com/chaitin/MonkeyCode/backend/db/apikey" "github.com/chaitin/MonkeyCode/backend/db/billingplan" "github.com/chaitin/MonkeyCode/backend/db/billingquota" @@ -27,12 +28,16 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/modelprovider" "github.com/chaitin/MonkeyCode/backend/db/modelprovidermodel" "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/role" "github.com/chaitin/MonkeyCode/backend/db/securityscanning" "github.com/chaitin/MonkeyCode/backend/db/securityscanningresult" "github.com/chaitin/MonkeyCode/backend/db/setting" "github.com/chaitin/MonkeyCode/backend/db/task" "github.com/chaitin/MonkeyCode/backend/db/taskrecord" "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/usergroup" + "github.com/chaitin/MonkeyCode/backend/db/usergroupadmin" + "github.com/chaitin/MonkeyCode/backend/db/usergroupuser" "github.com/chaitin/MonkeyCode/backend/db/useridentity" "github.com/chaitin/MonkeyCode/backend/db/userloginhistory" "github.com/chaitin/MonkeyCode/backend/db/workspace" @@ -53,6 +58,7 @@ const ( // Node types. TypeAdmin = "Admin" TypeAdminLoginHistory = "AdminLoginHistory" + TypeAdminRole = "AdminRole" TypeApiKey = "ApiKey" TypeBillingPlan = "BillingPlan" TypeBillingQuota = "BillingQuota" @@ -65,12 +71,16 @@ const ( TypeModel = "Model" TypeModelProvider = "ModelProvider" TypeModelProviderModel = "ModelProviderModel" + TypeRole = "Role" TypeSecurityScanning = "SecurityScanning" TypeSecurityScanningResult = "SecurityScanningResult" TypeSetting = "Setting" TypeTask = "Task" TypeTaskRecord = "TaskRecord" TypeUser = "User" + TypeUserGroup = "UserGroup" + TypeUserGroupAdmin = "UserGroupAdmin" + TypeUserGroupUser = "UserGroupUser" TypeUserIdentity = "UserIdentity" TypeUserLoginHistory = "UserLoginHistory" TypeWorkspace = "Workspace" @@ -80,22 +90,37 @@ const ( // AdminMutation represents an operation that mutates the Admin nodes in the graph. type AdminMutation struct { config - op Op - typ string - id *uuid.UUID - username *string - password *string - status *consts.AdminStatus - last_active_at *time.Time - created_at *time.Time - updated_at *time.Time - clearedFields map[string]struct{} - login_histories map[uuid.UUID]struct{} - removedlogin_histories map[uuid.UUID]struct{} - clearedlogin_histories bool - done bool - oldValue func(context.Context) (*Admin, error) - predicates []predicate.Admin + op Op + typ string + id *uuid.UUID + username *string + password *string + status *consts.AdminStatus + last_active_at *time.Time + created_at *time.Time + updated_at *time.Time + clearedFields map[string]struct{} + login_histories map[uuid.UUID]struct{} + removedlogin_histories map[uuid.UUID]struct{} + clearedlogin_histories bool + myusergroups map[uuid.UUID]struct{} + removedmyusergroups map[uuid.UUID]struct{} + clearedmyusergroups bool + usergroups map[uuid.UUID]struct{} + removedusergroups map[uuid.UUID]struct{} + clearedusergroups bool + roles map[int64]struct{} + removedroles map[int64]struct{} + clearedroles bool + user_group_admins map[uuid.UUID]struct{} + removeduser_group_admins map[uuid.UUID]struct{} + cleareduser_group_admins bool + admin_roles map[uuid.UUID]struct{} + removedadmin_roles map[uuid.UUID]struct{} + clearedadmin_roles bool + done bool + oldValue func(context.Context) (*Admin, error) + predicates []predicate.Admin } var _ ent.Mutation = (*AdminMutation)(nil) @@ -472,6 +497,276 @@ func (m *AdminMutation) ResetLoginHistories() { m.removedlogin_histories = nil } +// AddMyusergroupIDs adds the "myusergroups" edge to the UserGroup entity by ids. +func (m *AdminMutation) AddMyusergroupIDs(ids ...uuid.UUID) { + if m.myusergroups == nil { + m.myusergroups = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.myusergroups[ids[i]] = struct{}{} + } +} + +// ClearMyusergroups clears the "myusergroups" edge to the UserGroup entity. +func (m *AdminMutation) ClearMyusergroups() { + m.clearedmyusergroups = true +} + +// MyusergroupsCleared reports if the "myusergroups" edge to the UserGroup entity was cleared. +func (m *AdminMutation) MyusergroupsCleared() bool { + return m.clearedmyusergroups +} + +// RemoveMyusergroupIDs removes the "myusergroups" edge to the UserGroup entity by IDs. +func (m *AdminMutation) RemoveMyusergroupIDs(ids ...uuid.UUID) { + if m.removedmyusergroups == nil { + m.removedmyusergroups = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.myusergroups, ids[i]) + m.removedmyusergroups[ids[i]] = struct{}{} + } +} + +// RemovedMyusergroups returns the removed IDs of the "myusergroups" edge to the UserGroup entity. +func (m *AdminMutation) RemovedMyusergroupsIDs() (ids []uuid.UUID) { + for id := range m.removedmyusergroups { + ids = append(ids, id) + } + return +} + +// MyusergroupsIDs returns the "myusergroups" edge IDs in the mutation. +func (m *AdminMutation) MyusergroupsIDs() (ids []uuid.UUID) { + for id := range m.myusergroups { + ids = append(ids, id) + } + return +} + +// ResetMyusergroups resets all changes to the "myusergroups" edge. +func (m *AdminMutation) ResetMyusergroups() { + m.myusergroups = nil + m.clearedmyusergroups = false + m.removedmyusergroups = nil +} + +// AddUsergroupIDs adds the "usergroups" edge to the UserGroup entity by ids. +func (m *AdminMutation) AddUsergroupIDs(ids ...uuid.UUID) { + if m.usergroups == nil { + m.usergroups = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.usergroups[ids[i]] = struct{}{} + } +} + +// ClearUsergroups clears the "usergroups" edge to the UserGroup entity. +func (m *AdminMutation) ClearUsergroups() { + m.clearedusergroups = true +} + +// UsergroupsCleared reports if the "usergroups" edge to the UserGroup entity was cleared. +func (m *AdminMutation) UsergroupsCleared() bool { + return m.clearedusergroups +} + +// RemoveUsergroupIDs removes the "usergroups" edge to the UserGroup entity by IDs. +func (m *AdminMutation) RemoveUsergroupIDs(ids ...uuid.UUID) { + if m.removedusergroups == nil { + m.removedusergroups = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.usergroups, ids[i]) + m.removedusergroups[ids[i]] = struct{}{} + } +} + +// RemovedUsergroups returns the removed IDs of the "usergroups" edge to the UserGroup entity. +func (m *AdminMutation) RemovedUsergroupsIDs() (ids []uuid.UUID) { + for id := range m.removedusergroups { + ids = append(ids, id) + } + return +} + +// UsergroupsIDs returns the "usergroups" edge IDs in the mutation. +func (m *AdminMutation) UsergroupsIDs() (ids []uuid.UUID) { + for id := range m.usergroups { + ids = append(ids, id) + } + return +} + +// ResetUsergroups resets all changes to the "usergroups" edge. +func (m *AdminMutation) ResetUsergroups() { + m.usergroups = nil + m.clearedusergroups = false + m.removedusergroups = nil +} + +// AddRoleIDs adds the "roles" edge to the Role entity by ids. +func (m *AdminMutation) AddRoleIDs(ids ...int64) { + if m.roles == nil { + m.roles = make(map[int64]struct{}) + } + for i := range ids { + m.roles[ids[i]] = struct{}{} + } +} + +// ClearRoles clears the "roles" edge to the Role entity. +func (m *AdminMutation) ClearRoles() { + m.clearedroles = true +} + +// RolesCleared reports if the "roles" edge to the Role entity was cleared. +func (m *AdminMutation) RolesCleared() bool { + return m.clearedroles +} + +// RemoveRoleIDs removes the "roles" edge to the Role entity by IDs. +func (m *AdminMutation) RemoveRoleIDs(ids ...int64) { + if m.removedroles == nil { + m.removedroles = make(map[int64]struct{}) + } + for i := range ids { + delete(m.roles, ids[i]) + m.removedroles[ids[i]] = struct{}{} + } +} + +// RemovedRoles returns the removed IDs of the "roles" edge to the Role entity. +func (m *AdminMutation) RemovedRolesIDs() (ids []int64) { + for id := range m.removedroles { + ids = append(ids, id) + } + return +} + +// RolesIDs returns the "roles" edge IDs in the mutation. +func (m *AdminMutation) RolesIDs() (ids []int64) { + for id := range m.roles { + ids = append(ids, id) + } + return +} + +// ResetRoles resets all changes to the "roles" edge. +func (m *AdminMutation) ResetRoles() { + m.roles = nil + m.clearedroles = false + m.removedroles = nil +} + +// AddUserGroupAdminIDs adds the "user_group_admins" edge to the UserGroupAdmin entity by ids. +func (m *AdminMutation) AddUserGroupAdminIDs(ids ...uuid.UUID) { + if m.user_group_admins == nil { + m.user_group_admins = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.user_group_admins[ids[i]] = struct{}{} + } +} + +// ClearUserGroupAdmins clears the "user_group_admins" edge to the UserGroupAdmin entity. +func (m *AdminMutation) ClearUserGroupAdmins() { + m.cleareduser_group_admins = true +} + +// UserGroupAdminsCleared reports if the "user_group_admins" edge to the UserGroupAdmin entity was cleared. +func (m *AdminMutation) UserGroupAdminsCleared() bool { + return m.cleareduser_group_admins +} + +// RemoveUserGroupAdminIDs removes the "user_group_admins" edge to the UserGroupAdmin entity by IDs. +func (m *AdminMutation) RemoveUserGroupAdminIDs(ids ...uuid.UUID) { + if m.removeduser_group_admins == nil { + m.removeduser_group_admins = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.user_group_admins, ids[i]) + m.removeduser_group_admins[ids[i]] = struct{}{} + } +} + +// RemovedUserGroupAdmins returns the removed IDs of the "user_group_admins" edge to the UserGroupAdmin entity. +func (m *AdminMutation) RemovedUserGroupAdminsIDs() (ids []uuid.UUID) { + for id := range m.removeduser_group_admins { + ids = append(ids, id) + } + return +} + +// UserGroupAdminsIDs returns the "user_group_admins" edge IDs in the mutation. +func (m *AdminMutation) UserGroupAdminsIDs() (ids []uuid.UUID) { + for id := range m.user_group_admins { + ids = append(ids, id) + } + return +} + +// ResetUserGroupAdmins resets all changes to the "user_group_admins" edge. +func (m *AdminMutation) ResetUserGroupAdmins() { + m.user_group_admins = nil + m.cleareduser_group_admins = false + m.removeduser_group_admins = nil +} + +// AddAdminRoleIDs adds the "admin_roles" edge to the AdminRole entity by ids. +func (m *AdminMutation) AddAdminRoleIDs(ids ...uuid.UUID) { + if m.admin_roles == nil { + m.admin_roles = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.admin_roles[ids[i]] = struct{}{} + } +} + +// ClearAdminRoles clears the "admin_roles" edge to the AdminRole entity. +func (m *AdminMutation) ClearAdminRoles() { + m.clearedadmin_roles = true +} + +// AdminRolesCleared reports if the "admin_roles" edge to the AdminRole entity was cleared. +func (m *AdminMutation) AdminRolesCleared() bool { + return m.clearedadmin_roles +} + +// RemoveAdminRoleIDs removes the "admin_roles" edge to the AdminRole entity by IDs. +func (m *AdminMutation) RemoveAdminRoleIDs(ids ...uuid.UUID) { + if m.removedadmin_roles == nil { + m.removedadmin_roles = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.admin_roles, ids[i]) + m.removedadmin_roles[ids[i]] = struct{}{} + } +} + +// RemovedAdminRoles returns the removed IDs of the "admin_roles" edge to the AdminRole entity. +func (m *AdminMutation) RemovedAdminRolesIDs() (ids []uuid.UUID) { + for id := range m.removedadmin_roles { + ids = append(ids, id) + } + return +} + +// AdminRolesIDs returns the "admin_roles" edge IDs in the mutation. +func (m *AdminMutation) AdminRolesIDs() (ids []uuid.UUID) { + for id := range m.admin_roles { + ids = append(ids, id) + } + return +} + +// ResetAdminRoles resets all changes to the "admin_roles" edge. +func (m *AdminMutation) ResetAdminRoles() { + m.admin_roles = nil + m.clearedadmin_roles = false + m.removedadmin_roles = nil +} + // Where appends a list predicates to the AdminMutation builder. func (m *AdminMutation) Where(ps ...predicate.Admin) { m.predicates = append(m.predicates, ps...) @@ -690,10 +985,25 @@ func (m *AdminMutation) ResetField(name string) error { // AddedEdges returns all edge names that were set/added in this mutation. func (m *AdminMutation) AddedEdges() []string { - edges := make([]string, 0, 1) + edges := make([]string, 0, 6) if m.login_histories != nil { edges = append(edges, admin.EdgeLoginHistories) } + if m.myusergroups != nil { + edges = append(edges, admin.EdgeMyusergroups) + } + if m.usergroups != nil { + edges = append(edges, admin.EdgeUsergroups) + } + if m.roles != nil { + edges = append(edges, admin.EdgeRoles) + } + if m.user_group_admins != nil { + edges = append(edges, admin.EdgeUserGroupAdmins) + } + if m.admin_roles != nil { + edges = append(edges, admin.EdgeAdminRoles) + } return edges } @@ -707,16 +1017,61 @@ func (m *AdminMutation) AddedIDs(name string) []ent.Value { ids = append(ids, id) } return ids + case admin.EdgeMyusergroups: + ids := make([]ent.Value, 0, len(m.myusergroups)) + for id := range m.myusergroups { + ids = append(ids, id) + } + return ids + case admin.EdgeUsergroups: + ids := make([]ent.Value, 0, len(m.usergroups)) + for id := range m.usergroups { + ids = append(ids, id) + } + return ids + case admin.EdgeRoles: + ids := make([]ent.Value, 0, len(m.roles)) + for id := range m.roles { + ids = append(ids, id) + } + return ids + case admin.EdgeUserGroupAdmins: + ids := make([]ent.Value, 0, len(m.user_group_admins)) + for id := range m.user_group_admins { + ids = append(ids, id) + } + return ids + case admin.EdgeAdminRoles: + ids := make([]ent.Value, 0, len(m.admin_roles)) + for id := range m.admin_roles { + ids = append(ids, id) + } + return ids } return nil } // RemovedEdges returns all edge names that were removed in this mutation. func (m *AdminMutation) RemovedEdges() []string { - edges := make([]string, 0, 1) + edges := make([]string, 0, 6) if m.removedlogin_histories != nil { edges = append(edges, admin.EdgeLoginHistories) } + if m.removedmyusergroups != nil { + edges = append(edges, admin.EdgeMyusergroups) + } + if m.removedusergroups != nil { + edges = append(edges, admin.EdgeUsergroups) + } + if m.removedroles != nil { + edges = append(edges, admin.EdgeRoles) + } + if m.removeduser_group_admins != nil { + edges = append(edges, admin.EdgeUserGroupAdmins) + } + if m.removedadmin_roles != nil { + edges = append(edges, admin.EdgeAdminRoles) + } return edges } @@ -730,16 +1085,61 @@ func (m *AdminMutation) RemovedIDs(name string) []ent.Value { ids = append(ids, id) } return ids + case admin.EdgeMyusergroups: + ids := make([]ent.Value, 0, len(m.removedmyusergroups)) + for id := range m.removedmyusergroups { + ids = append(ids, id) + } + return ids + case admin.EdgeUsergroups: + ids := make([]ent.Value, 0, len(m.removedusergroups)) + for id := range m.removedusergroups { + ids = append(ids, id) + } + return ids + case admin.EdgeRoles: + ids := make([]ent.Value, 0, len(m.removedroles)) + for id := range m.removedroles { + ids = append(ids, id) + } + return ids + case admin.EdgeUserGroupAdmins: + ids := make([]ent.Value, 0, len(m.removeduser_group_admins)) + for id := range m.removeduser_group_admins { + ids = append(ids, id) + } + return ids + case admin.EdgeAdminRoles: + ids := make([]ent.Value, 0, len(m.removedadmin_roles)) + for id := range m.removedadmin_roles { + ids = append(ids, id) + } + return ids } return nil } // ClearedEdges returns all edge names that were cleared in this mutation. func (m *AdminMutation) ClearedEdges() []string { - edges := make([]string, 0, 1) + edges := make([]string, 0, 6) if m.clearedlogin_histories { edges = append(edges, admin.EdgeLoginHistories) } + if m.clearedmyusergroups { + edges = append(edges, admin.EdgeMyusergroups) + } + if m.clearedusergroups { + edges = append(edges, admin.EdgeUsergroups) + } + if m.clearedroles { + edges = append(edges, admin.EdgeRoles) + } + if m.cleareduser_group_admins { + edges = append(edges, admin.EdgeUserGroupAdmins) + } + if m.clearedadmin_roles { + edges = append(edges, admin.EdgeAdminRoles) + } return edges } @@ -749,6 +1149,16 @@ func (m *AdminMutation) EdgeCleared(name string) bool { switch name { case admin.EdgeLoginHistories: return m.clearedlogin_histories + case admin.EdgeMyusergroups: + return m.clearedmyusergroups + case admin.EdgeUsergroups: + return m.clearedusergroups + case admin.EdgeRoles: + return m.clearedroles + case admin.EdgeUserGroupAdmins: + return m.cleareduser_group_admins + case admin.EdgeAdminRoles: + return m.clearedadmin_roles } return false } @@ -768,6 +1178,21 @@ func (m *AdminMutation) ResetEdge(name string) error { case admin.EdgeLoginHistories: m.ResetLoginHistories() return nil + case admin.EdgeMyusergroups: + m.ResetMyusergroups() + return nil + case admin.EdgeUsergroups: + m.ResetUsergroups() + return nil + case admin.EdgeRoles: + m.ResetRoles() + return nil + case admin.EdgeUserGroupAdmins: + m.ResetUserGroupAdmins() + return nil + case admin.EdgeAdminRoles: + m.ResetAdminRoles() + return nil } return fmt.Errorf("unknown Admin edge %s", name) } @@ -1755,37 +2180,33 @@ func (m *AdminLoginHistoryMutation) ResetEdge(name string) error { return fmt.Errorf("unknown AdminLoginHistory edge %s", name) } -// ApiKeyMutation represents an operation that mutates the ApiKey nodes in the graph. -type ApiKeyMutation struct { +// AdminRoleMutation represents an operation that mutates the AdminRole nodes in the graph. +type AdminRoleMutation struct { config op Op typ string id *uuid.UUID - key *string - name *string - status *consts.ApiKeyStatus - last_used *time.Time - created_at *time.Time - updated_at *time.Time clearedFields map[string]struct{} - user *uuid.UUID - cleareduser bool + admin *uuid.UUID + clearedadmin bool + role *int64 + clearedrole bool done bool - oldValue func(context.Context) (*ApiKey, error) - predicates []predicate.ApiKey + oldValue func(context.Context) (*AdminRole, error) + predicates []predicate.AdminRole } -var _ ent.Mutation = (*ApiKeyMutation)(nil) +var _ ent.Mutation = (*AdminRoleMutation)(nil) -// apikeyOption allows management of the mutation configuration using functional options. -type apikeyOption func(*ApiKeyMutation) +// adminroleOption allows management of the mutation configuration using functional options. +type adminroleOption func(*AdminRoleMutation) -// newApiKeyMutation creates new mutation for the ApiKey entity. -func newApiKeyMutation(c config, op Op, opts ...apikeyOption) *ApiKeyMutation { - m := &ApiKeyMutation{ +// newAdminRoleMutation creates new mutation for the AdminRole entity. +func newAdminRoleMutation(c config, op Op, opts ...adminroleOption) *AdminRoleMutation { + m := &AdminRoleMutation{ config: c, op: op, - typ: TypeApiKey, + typ: TypeAdminRole, clearedFields: make(map[string]struct{}), } for _, opt := range opts { @@ -1794,20 +2215,20 @@ func newApiKeyMutation(c config, op Op, opts ...apikeyOption) *ApiKeyMutation { return m } -// withApiKeyID sets the ID field of the mutation. -func withApiKeyID(id uuid.UUID) apikeyOption { - return func(m *ApiKeyMutation) { +// withAdminRoleID sets the ID field of the mutation. +func withAdminRoleID(id uuid.UUID) adminroleOption { + return func(m *AdminRoleMutation) { var ( err error once sync.Once - value *ApiKey + value *AdminRole ) - m.oldValue = func(ctx context.Context) (*ApiKey, error) { + m.oldValue = func(ctx context.Context) (*AdminRole, error) { once.Do(func() { if m.done { err = errors.New("querying old values post mutation is not allowed") } else { - value, err = m.Client().ApiKey.Get(ctx, id) + value, err = m.Client().AdminRole.Get(ctx, id) } }) return value, err @@ -1816,10 +2237,10 @@ func withApiKeyID(id uuid.UUID) apikeyOption { } } -// withApiKey sets the old ApiKey of the mutation. -func withApiKey(node *ApiKey) apikeyOption { - return func(m *ApiKeyMutation) { - m.oldValue = func(context.Context) (*ApiKey, error) { +// withAdminRole sets the old AdminRole of the mutation. +func withAdminRole(node *AdminRole) adminroleOption { + return func(m *AdminRoleMutation) { + m.oldValue = func(context.Context) (*AdminRole, error) { return node, nil } m.id = &node.ID @@ -1828,7 +2249,7 @@ func withApiKey(node *ApiKey) apikeyOption { // 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 ApiKeyMutation) Client() *Client { +func (m AdminRoleMutation) Client() *Client { client := &Client{config: m.config} client.init() return client @@ -1836,7 +2257,7 @@ func (m ApiKeyMutation) Client() *Client { // Tx returns an `ent.Tx` for mutations that were executed in transactions; // it returns an error otherwise. -func (m ApiKeyMutation) Tx() (*Tx, error) { +func (m AdminRoleMutation) Tx() (*Tx, error) { if _, ok := m.driver.(*txDriver); !ok { return nil, errors.New("db: mutation is not running in a transaction") } @@ -1846,14 +2267,14 @@ func (m ApiKeyMutation) Tx() (*Tx, error) { } // SetID sets the value of the id field. Note that this -// operation is only accepted on creation of ApiKey entities. -func (m *ApiKeyMutation) SetID(id uuid.UUID) { +// operation is only accepted on creation of AdminRole entities. +func (m *AdminRoleMutation) 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 *ApiKeyMutation) ID() (id uuid.UUID, exists bool) { +func (m *AdminRoleMutation) ID() (id uuid.UUID, exists bool) { if m.id == nil { return } @@ -1864,7 +2285,7 @@ func (m *ApiKeyMutation) ID() (id uuid.UUID, exists bool) { // 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 *ApiKeyMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { +func (m *AdminRoleMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { switch { case m.op.Is(OpUpdateOne | OpDeleteOne): id, exists := m.ID() @@ -1873,691 +2294,455 @@ func (m *ApiKeyMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { } fallthrough case m.op.Is(OpUpdate | OpDelete): - return m.Client().ApiKey.Query().Where(m.predicates...).IDs(ctx) + return m.Client().AdminRole.Query().Where(m.predicates...).IDs(ctx) default: return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) } } -// SetUserID sets the "user_id" field. -func (m *ApiKeyMutation) SetUserID(u uuid.UUID) { - m.user = &u +// SetAdminID sets the "admin_id" field. +func (m *AdminRoleMutation) SetAdminID(u uuid.UUID) { + m.admin = &u } -// UserID returns the value of the "user_id" field in the mutation. -func (m *ApiKeyMutation) UserID() (r uuid.UUID, exists bool) { - v := m.user +// AdminID returns the value of the "admin_id" field in the mutation. +func (m *AdminRoleMutation) AdminID() (r uuid.UUID, exists bool) { + v := m.admin if v == nil { return } return *v, true } -// OldUserID returns the old "user_id" field's value of the ApiKey entity. -// If the ApiKey object wasn't provided to the builder, the object is fetched from the database. +// OldAdminID returns the old "admin_id" field's value of the AdminRole entity. +// If the AdminRole 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 *ApiKeyMutation) OldUserID(ctx context.Context) (v uuid.UUID, err error) { +func (m *AdminRoleMutation) OldAdminID(ctx context.Context) (v uuid.UUID, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldUserID is only allowed on UpdateOne operations") + return v, errors.New("OldAdminID is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldUserID requires an ID field in the mutation") + return v, errors.New("OldAdminID requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldUserID: %w", err) + return v, fmt.Errorf("querying old value for OldAdminID: %w", err) } - return oldValue.UserID, nil + return oldValue.AdminID, nil } -// ResetUserID resets all changes to the "user_id" field. -func (m *ApiKeyMutation) ResetUserID() { - m.user = nil +// ResetAdminID resets all changes to the "admin_id" field. +func (m *AdminRoleMutation) ResetAdminID() { + m.admin = nil } -// SetKey sets the "key" field. -func (m *ApiKeyMutation) SetKey(s string) { - m.key = &s +// SetRoleID sets the "role_id" field. +func (m *AdminRoleMutation) SetRoleID(i int64) { + m.role = &i } -// Key returns the value of the "key" field in the mutation. -func (m *ApiKeyMutation) Key() (r string, exists bool) { - v := m.key +// RoleID returns the value of the "role_id" field in the mutation. +func (m *AdminRoleMutation) RoleID() (r int64, exists bool) { + v := m.role if v == nil { return } return *v, true } -// OldKey returns the old "key" field's value of the ApiKey entity. -// If the ApiKey object wasn't provided to the builder, the object is fetched from the database. +// OldRoleID returns the old "role_id" field's value of the AdminRole entity. +// If the AdminRole 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 *ApiKeyMutation) OldKey(ctx context.Context) (v string, err error) { +func (m *AdminRoleMutation) OldRoleID(ctx context.Context) (v int64, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldKey is only allowed on UpdateOne operations") + return v, errors.New("OldRoleID is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldKey requires an ID field in the mutation") + return v, errors.New("OldRoleID requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldKey: %w", err) + return v, fmt.Errorf("querying old value for OldRoleID: %w", err) } - return oldValue.Key, nil + return oldValue.RoleID, nil } -// ResetKey resets all changes to the "key" field. -func (m *ApiKeyMutation) ResetKey() { - m.key = nil +// ResetRoleID resets all changes to the "role_id" field. +func (m *AdminRoleMutation) ResetRoleID() { + m.role = nil } -// SetName sets the "name" field. -func (m *ApiKeyMutation) SetName(s string) { - m.name = &s +// ClearAdmin clears the "admin" edge to the Admin entity. +func (m *AdminRoleMutation) ClearAdmin() { + m.clearedadmin = true + m.clearedFields[adminrole.FieldAdminID] = struct{}{} } -// Name returns the value of the "name" field in the mutation. -func (m *ApiKeyMutation) Name() (r string, exists bool) { - v := m.name - if v == nil { - return - } - return *v, true +// AdminCleared reports if the "admin" edge to the Admin entity was cleared. +func (m *AdminRoleMutation) AdminCleared() bool { + return m.clearedadmin } -// OldName returns the old "name" field's value of the ApiKey entity. -// If the ApiKey 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 *ApiKeyMutation) 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) +// AdminIDs returns the "admin" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// AdminID instead. It exists only for internal usage by the builders. +func (m *AdminRoleMutation) AdminIDs() (ids []uuid.UUID) { + if id := m.admin; id != nil { + ids = append(ids, *id) } - return oldValue.Name, nil + return } -// ResetName resets all changes to the "name" field. -func (m *ApiKeyMutation) ResetName() { - m.name = nil +// ResetAdmin resets all changes to the "admin" edge. +func (m *AdminRoleMutation) ResetAdmin() { + m.admin = nil + m.clearedadmin = false } -// SetStatus sets the "status" field. -func (m *ApiKeyMutation) SetStatus(cks consts.ApiKeyStatus) { - m.status = &cks +// ClearRole clears the "role" edge to the Role entity. +func (m *AdminRoleMutation) ClearRole() { + m.clearedrole = true + m.clearedFields[adminrole.FieldRoleID] = struct{}{} } -// Status returns the value of the "status" field in the mutation. -func (m *ApiKeyMutation) Status() (r consts.ApiKeyStatus, exists bool) { - v := m.status - if v == nil { - return - } - return *v, true +// RoleCleared reports if the "role" edge to the Role entity was cleared. +func (m *AdminRoleMutation) RoleCleared() bool { + return m.clearedrole } -// OldStatus returns the old "status" field's value of the ApiKey entity. -// If the ApiKey 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 *ApiKeyMutation) OldStatus(ctx context.Context) (v consts.ApiKeyStatus, 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) +// RoleIDs returns the "role" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// RoleID instead. It exists only for internal usage by the builders. +func (m *AdminRoleMutation) RoleIDs() (ids []int64) { + if id := m.role; id != nil { + ids = append(ids, *id) } - return oldValue.Status, nil -} - -// ResetStatus resets all changes to the "status" field. -func (m *ApiKeyMutation) ResetStatus() { - m.status = nil + return } -// SetLastUsed sets the "last_used" field. -func (m *ApiKeyMutation) SetLastUsed(t time.Time) { - m.last_used = &t +// ResetRole resets all changes to the "role" edge. +func (m *AdminRoleMutation) ResetRole() { + m.role = nil + m.clearedrole = false } -// LastUsed returns the value of the "last_used" field in the mutation. -func (m *ApiKeyMutation) LastUsed() (r time.Time, exists bool) { - v := m.last_used - if v == nil { - return - } - return *v, true +// Where appends a list predicates to the AdminRoleMutation builder. +func (m *AdminRoleMutation) Where(ps ...predicate.AdminRole) { + m.predicates = append(m.predicates, ps...) } -// OldLastUsed returns the old "last_used" field's value of the ApiKey entity. -// If the ApiKey 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 *ApiKeyMutation) OldLastUsed(ctx context.Context) (v time.Time, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldLastUsed is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldLastUsed requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldLastUsed: %w", err) +// WhereP appends storage-level predicates to the AdminRoleMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *AdminRoleMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.AdminRole, len(ps)) + for i := range ps { + p[i] = ps[i] } - return oldValue.LastUsed, nil + m.Where(p...) } -// ClearLastUsed clears the value of the "last_used" field. -func (m *ApiKeyMutation) ClearLastUsed() { - m.last_used = nil - m.clearedFields[apikey.FieldLastUsed] = struct{}{} +// Op returns the operation name. +func (m *AdminRoleMutation) Op() Op { + return m.op } -// LastUsedCleared returns if the "last_used" field was cleared in this mutation. -func (m *ApiKeyMutation) LastUsedCleared() bool { - _, ok := m.clearedFields[apikey.FieldLastUsed] - return ok +// SetOp allows setting the mutation operation. +func (m *AdminRoleMutation) SetOp(op Op) { + m.op = op } -// ResetLastUsed resets all changes to the "last_used" field. -func (m *ApiKeyMutation) ResetLastUsed() { - m.last_used = nil - delete(m.clearedFields, apikey.FieldLastUsed) +// Type returns the node type of this mutation (AdminRole). +func (m *AdminRoleMutation) Type() string { + return m.typ } -// SetCreatedAt sets the "created_at" field. -func (m *ApiKeyMutation) SetCreatedAt(t time.Time) { - m.created_at = &t +// 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 *AdminRoleMutation) Fields() []string { + fields := make([]string, 0, 2) + if m.admin != nil { + fields = append(fields, adminrole.FieldAdminID) + } + if m.role != nil { + fields = append(fields, adminrole.FieldRoleID) + } + return fields } -// CreatedAt returns the value of the "created_at" field in the mutation. -func (m *ApiKeyMutation) CreatedAt() (r time.Time, exists bool) { - v := m.created_at - if v == nil { - return +// 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 *AdminRoleMutation) Field(name string) (ent.Value, bool) { + switch name { + case adminrole.FieldAdminID: + return m.AdminID() + case adminrole.FieldRoleID: + return m.RoleID() } - return *v, true + return nil, false } -// OldCreatedAt returns the old "created_at" field's value of the ApiKey entity. -// If the ApiKey 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 *ApiKeyMutation) 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) +// 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 *AdminRoleMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case adminrole.FieldAdminID: + return m.OldAdminID(ctx) + case adminrole.FieldRoleID: + return m.OldRoleID(ctx) } - return oldValue.CreatedAt, nil + return nil, fmt.Errorf("unknown AdminRole field %s", name) } -// ResetCreatedAt resets all changes to the "created_at" field. -func (m *ApiKeyMutation) ResetCreatedAt() { - m.created_at = nil +// 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 *AdminRoleMutation) SetField(name string, value ent.Value) error { + switch name { + case adminrole.FieldAdminID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAdminID(v) + return nil + case adminrole.FieldRoleID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRoleID(v) + return nil + } + return fmt.Errorf("unknown AdminRole field %s", name) } -// SetUpdatedAt sets the "updated_at" field. -func (m *ApiKeyMutation) SetUpdatedAt(t time.Time) { - m.updated_at = &t +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *AdminRoleMutation) AddedFields() []string { + var fields []string + return fields } -// UpdatedAt returns the value of the "updated_at" field in the mutation. -func (m *ApiKeyMutation) UpdatedAt() (r time.Time, exists bool) { - v := m.updated_at - if v == nil { - return +// 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 *AdminRoleMutation) AddedField(name string) (ent.Value, bool) { + switch name { } - return *v, true + return nil, false } -// OldUpdatedAt returns the old "updated_at" field's value of the ApiKey entity. -// If the ApiKey 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 *ApiKeyMutation) 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) +// 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 *AdminRoleMutation) AddField(name string, value ent.Value) error { + switch name { } - return oldValue.UpdatedAt, nil + return fmt.Errorf("unknown AdminRole numeric field %s", name) } -// ResetUpdatedAt resets all changes to the "updated_at" field. -func (m *ApiKeyMutation) ResetUpdatedAt() { - m.updated_at = nil +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *AdminRoleMutation) ClearedFields() []string { + return nil } -// ClearUser clears the "user" edge to the User entity. -func (m *ApiKeyMutation) ClearUser() { - m.cleareduser = true - m.clearedFields[apikey.FieldUserID] = struct{}{} +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *AdminRoleMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok } -// UserCleared reports if the "user" edge to the User entity was cleared. -func (m *ApiKeyMutation) UserCleared() bool { - return m.cleareduser +// 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 *AdminRoleMutation) ClearField(name string) error { + return fmt.Errorf("unknown AdminRole nullable field %s", name) } -// UserIDs returns the "user" edge IDs in the mutation. -// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// UserID instead. It exists only for internal usage by the builders. -func (m *ApiKeyMutation) UserIDs() (ids []uuid.UUID) { - if id := m.user; id != nil { - ids = append(ids, *id) +// 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 *AdminRoleMutation) ResetField(name string) error { + switch name { + case adminrole.FieldAdminID: + m.ResetAdminID() + return nil + case adminrole.FieldRoleID: + m.ResetRoleID() + return nil } - return + return fmt.Errorf("unknown AdminRole field %s", name) } -// ResetUser resets all changes to the "user" edge. -func (m *ApiKeyMutation) ResetUser() { - m.user = nil - m.cleareduser = false -} - -// Where appends a list predicates to the ApiKeyMutation builder. -func (m *ApiKeyMutation) Where(ps ...predicate.ApiKey) { - m.predicates = append(m.predicates, ps...) -} - -// WhereP appends storage-level predicates to the ApiKeyMutation builder. Using this method, -// users can use type-assertion to append predicates that do not depend on any generated package. -func (m *ApiKeyMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.ApiKey, len(ps)) - for i := range ps { - p[i] = ps[i] +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *AdminRoleMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.admin != nil { + edges = append(edges, adminrole.EdgeAdmin) } - m.Where(p...) + if m.role != nil { + edges = append(edges, adminrole.EdgeRole) + } + return edges } -// Op returns the operation name. -func (m *ApiKeyMutation) Op() Op { - return m.op +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *AdminRoleMutation) AddedIDs(name string) []ent.Value { + switch name { + case adminrole.EdgeAdmin: + if id := m.admin; id != nil { + return []ent.Value{*id} + } + case adminrole.EdgeRole: + if id := m.role; id != nil { + return []ent.Value{*id} + } + } + return nil } -// SetOp allows setting the mutation operation. -func (m *ApiKeyMutation) SetOp(op Op) { - m.op = op +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *AdminRoleMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + return edges } -// Type returns the node type of this mutation (ApiKey). -func (m *ApiKeyMutation) Type() string { - return m.typ +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *AdminRoleMutation) RemovedIDs(name string) []ent.Value { + return nil } -// 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 *ApiKeyMutation) Fields() []string { - fields := make([]string, 0, 7) - if m.user != nil { - fields = append(fields, apikey.FieldUserID) - } - if m.key != nil { - fields = append(fields, apikey.FieldKey) - } - if m.name != nil { - fields = append(fields, apikey.FieldName) - } - if m.status != nil { - fields = append(fields, apikey.FieldStatus) - } - if m.last_used != nil { - fields = append(fields, apikey.FieldLastUsed) - } - if m.created_at != nil { - fields = append(fields, apikey.FieldCreatedAt) +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *AdminRoleMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedadmin { + edges = append(edges, adminrole.EdgeAdmin) } - if m.updated_at != nil { - fields = append(fields, apikey.FieldUpdatedAt) + if m.clearedrole { + edges = append(edges, adminrole.EdgeRole) } - return fields + return edges } -// 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 *ApiKeyMutation) Field(name string) (ent.Value, bool) { +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *AdminRoleMutation) EdgeCleared(name string) bool { switch name { - case apikey.FieldUserID: - return m.UserID() - case apikey.FieldKey: - return m.Key() - case apikey.FieldName: - return m.Name() - case apikey.FieldStatus: - return m.Status() - case apikey.FieldLastUsed: - return m.LastUsed() - case apikey.FieldCreatedAt: - return m.CreatedAt() - case apikey.FieldUpdatedAt: - return m.UpdatedAt() + case adminrole.EdgeAdmin: + return m.clearedadmin + case adminrole.EdgeRole: + return m.clearedrole } - return nil, false + return 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 *ApiKeyMutation) OldField(ctx context.Context, name string) (ent.Value, error) { +// 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 *AdminRoleMutation) ClearEdge(name string) error { switch name { - case apikey.FieldUserID: - return m.OldUserID(ctx) - case apikey.FieldKey: - return m.OldKey(ctx) - case apikey.FieldName: - return m.OldName(ctx) - case apikey.FieldStatus: - return m.OldStatus(ctx) - case apikey.FieldLastUsed: - return m.OldLastUsed(ctx) - case apikey.FieldCreatedAt: - return m.OldCreatedAt(ctx) - case apikey.FieldUpdatedAt: - return m.OldUpdatedAt(ctx) + case adminrole.EdgeAdmin: + m.ClearAdmin() + return nil + case adminrole.EdgeRole: + m.ClearRole() + return nil } - return nil, fmt.Errorf("unknown ApiKey field %s", name) + return fmt.Errorf("unknown AdminRole unique edge %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 *ApiKeyMutation) SetField(name string, value ent.Value) error { +// 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 *AdminRoleMutation) ResetEdge(name string) error { switch name { - case apikey.FieldUserID: - v, ok := value.(uuid.UUID) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetUserID(v) - return nil - case apikey.FieldKey: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetKey(v) - return nil - case apikey.FieldName: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetName(v) - return nil - case apikey.FieldStatus: - v, ok := value.(consts.ApiKeyStatus) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetStatus(v) - return nil - case apikey.FieldLastUsed: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetLastUsed(v) - return nil - case apikey.FieldCreatedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetCreatedAt(v) + case adminrole.EdgeAdmin: + m.ResetAdmin() return nil - case apikey.FieldUpdatedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetUpdatedAt(v) + case adminrole.EdgeRole: + m.ResetRole() return nil } - return fmt.Errorf("unknown ApiKey field %s", name) + return fmt.Errorf("unknown AdminRole edge %s", name) } -// AddedFields returns all numeric fields that were incremented/decremented during -// this mutation. -func (m *ApiKeyMutation) AddedFields() []string { - return nil +// ApiKeyMutation represents an operation that mutates the ApiKey nodes in the graph. +type ApiKeyMutation struct { + config + op Op + typ string + id *uuid.UUID + key *string + name *string + status *consts.ApiKeyStatus + last_used *time.Time + created_at *time.Time + updated_at *time.Time + clearedFields map[string]struct{} + user *uuid.UUID + cleareduser bool + done bool + oldValue func(context.Context) (*ApiKey, error) + predicates []predicate.ApiKey } -// 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 *ApiKeyMutation) AddedField(name string) (ent.Value, bool) { - return nil, false +var _ ent.Mutation = (*ApiKeyMutation)(nil) + +// apikeyOption allows management of the mutation configuration using functional options. +type apikeyOption func(*ApiKeyMutation) + +// newApiKeyMutation creates new mutation for the ApiKey entity. +func newApiKeyMutation(c config, op Op, opts ...apikeyOption) *ApiKeyMutation { + m := &ApiKeyMutation{ + config: c, + op: op, + typ: TypeApiKey, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m } -// 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 *ApiKeyMutation) AddField(name string, value ent.Value) error { - switch name { +// withApiKeyID sets the ID field of the mutation. +func withApiKeyID(id uuid.UUID) apikeyOption { + return func(m *ApiKeyMutation) { + var ( + err error + once sync.Once + value *ApiKey + ) + m.oldValue = func(ctx context.Context) (*ApiKey, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().ApiKey.Get(ctx, id) + } + }) + return value, err + } + m.id = &id } - return fmt.Errorf("unknown ApiKey numeric field %s", name) } -// ClearedFields returns all nullable fields that were cleared during this -// mutation. -func (m *ApiKeyMutation) ClearedFields() []string { - var fields []string - if m.FieldCleared(apikey.FieldLastUsed) { - fields = append(fields, apikey.FieldLastUsed) - } - return fields -} - -// FieldCleared returns a boolean indicating if a field with the given name was -// cleared in this mutation. -func (m *ApiKeyMutation) 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 *ApiKeyMutation) ClearField(name string) error { - switch name { - case apikey.FieldLastUsed: - m.ClearLastUsed() - return nil - } - return fmt.Errorf("unknown ApiKey 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 *ApiKeyMutation) ResetField(name string) error { - switch name { - case apikey.FieldUserID: - m.ResetUserID() - return nil - case apikey.FieldKey: - m.ResetKey() - return nil - case apikey.FieldName: - m.ResetName() - return nil - case apikey.FieldStatus: - m.ResetStatus() - return nil - case apikey.FieldLastUsed: - m.ResetLastUsed() - return nil - case apikey.FieldCreatedAt: - m.ResetCreatedAt() - return nil - case apikey.FieldUpdatedAt: - m.ResetUpdatedAt() - return nil - } - return fmt.Errorf("unknown ApiKey field %s", name) -} - -// AddedEdges returns all edge names that were set/added in this mutation. -func (m *ApiKeyMutation) AddedEdges() []string { - edges := make([]string, 0, 1) - if m.user != nil { - edges = append(edges, apikey.EdgeUser) - } - return edges -} - -// AddedIDs returns all IDs (to other nodes) that were added for the given edge -// name in this mutation. -func (m *ApiKeyMutation) AddedIDs(name string) []ent.Value { - switch name { - case apikey.EdgeUser: - if id := m.user; id != nil { - return []ent.Value{*id} - } - } - return nil -} - -// RemovedEdges returns all edge names that were removed in this mutation. -func (m *ApiKeyMutation) 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 *ApiKeyMutation) RemovedIDs(name string) []ent.Value { - return nil -} - -// ClearedEdges returns all edge names that were cleared in this mutation. -func (m *ApiKeyMutation) ClearedEdges() []string { - edges := make([]string, 0, 1) - if m.cleareduser { - edges = append(edges, apikey.EdgeUser) - } - return edges -} - -// EdgeCleared returns a boolean which indicates if the edge with the given name -// was cleared in this mutation. -func (m *ApiKeyMutation) EdgeCleared(name string) bool { - switch name { - case apikey.EdgeUser: - return m.cleareduser - } - 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 *ApiKeyMutation) ClearEdge(name string) error { - switch name { - case apikey.EdgeUser: - m.ClearUser() - return nil - } - return fmt.Errorf("unknown ApiKey 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 *ApiKeyMutation) ResetEdge(name string) error { - switch name { - case apikey.EdgeUser: - m.ResetUser() - return nil - } - return fmt.Errorf("unknown ApiKey edge %s", name) -} - -// BillingPlanMutation represents an operation that mutates the BillingPlan nodes in the graph. -type BillingPlanMutation struct { - config - op Op - typ string - id *string - name *string - description *string - rules *map[string]interface{} - created_at *time.Time - updated_at *time.Time - clearedFields map[string]struct{} - done bool - oldValue func(context.Context) (*BillingPlan, error) - predicates []predicate.BillingPlan -} - -var _ ent.Mutation = (*BillingPlanMutation)(nil) - -// billingplanOption allows management of the mutation configuration using functional options. -type billingplanOption func(*BillingPlanMutation) - -// newBillingPlanMutation creates new mutation for the BillingPlan entity. -func newBillingPlanMutation(c config, op Op, opts ...billingplanOption) *BillingPlanMutation { - m := &BillingPlanMutation{ - config: c, - op: op, - typ: TypeBillingPlan, - clearedFields: make(map[string]struct{}), - } - for _, opt := range opts { - opt(m) - } - return m -} - -// withBillingPlanID sets the ID field of the mutation. -func withBillingPlanID(id string) billingplanOption { - return func(m *BillingPlanMutation) { - var ( - err error - once sync.Once - value *BillingPlan - ) - m.oldValue = func(ctx context.Context) (*BillingPlan, error) { - once.Do(func() { - if m.done { - err = errors.New("querying old values post mutation is not allowed") - } else { - value, err = m.Client().BillingPlan.Get(ctx, id) - } - }) - return value, err - } - m.id = &id - } -} - -// withBillingPlan sets the old BillingPlan of the mutation. -func withBillingPlan(node *BillingPlan) billingplanOption { - return func(m *BillingPlanMutation) { - m.oldValue = func(context.Context) (*BillingPlan, error) { - return node, nil - } - m.id = &node.ID +// withApiKey sets the old ApiKey of the mutation. +func withApiKey(node *ApiKey) apikeyOption { + return func(m *ApiKeyMutation) { + m.oldValue = func(context.Context) (*ApiKey, 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 BillingPlanMutation) Client() *Client { +func (m ApiKeyMutation) Client() *Client { client := &Client{config: m.config} client.init() return client @@ -2565,7 +2750,7 @@ func (m BillingPlanMutation) Client() *Client { // Tx returns an `ent.Tx` for mutations that were executed in transactions; // it returns an error otherwise. -func (m BillingPlanMutation) Tx() (*Tx, error) { +func (m ApiKeyMutation) Tx() (*Tx, error) { if _, ok := m.driver.(*txDriver); !ok { return nil, errors.New("db: mutation is not running in a transaction") } @@ -2575,14 +2760,14 @@ func (m BillingPlanMutation) Tx() (*Tx, error) { } // SetID sets the value of the id field. Note that this -// operation is only accepted on creation of BillingPlan entities. -func (m *BillingPlanMutation) SetID(id string) { +// operation is only accepted on creation of ApiKey entities. +func (m *ApiKeyMutation) 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 *BillingPlanMutation) ID() (id string, exists bool) { +func (m *ApiKeyMutation) ID() (id uuid.UUID, exists bool) { if m.id == nil { return } @@ -2593,136 +2778,221 @@ func (m *BillingPlanMutation) ID() (id string, exists bool) { // 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 *BillingPlanMutation) IDs(ctx context.Context) ([]string, error) { +func (m *ApiKeyMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { switch { case m.op.Is(OpUpdateOne | OpDeleteOne): id, exists := m.ID() if exists { - return []string{id}, nil + return []uuid.UUID{id}, nil } fallthrough case m.op.Is(OpUpdate | OpDelete): - return m.Client().BillingPlan.Query().Where(m.predicates...).IDs(ctx) + return m.Client().ApiKey.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 *BillingPlanMutation) SetName(s string) { - m.name = &s +// SetUserID sets the "user_id" field. +func (m *ApiKeyMutation) SetUserID(u uuid.UUID) { + m.user = &u } -// Name returns the value of the "name" field in the mutation. -func (m *BillingPlanMutation) Name() (r string, exists bool) { - v := m.name +// UserID returns the value of the "user_id" field in the mutation. +func (m *ApiKeyMutation) UserID() (r uuid.UUID, exists bool) { + v := m.user if v == nil { return } return *v, true } -// OldName returns the old "name" field's value of the BillingPlan entity. -// If the BillingPlan object wasn't provided to the builder, the object is fetched from the database. +// OldUserID returns the old "user_id" field's value of the ApiKey entity. +// If the ApiKey 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 *BillingPlanMutation) OldName(ctx context.Context) (v string, err error) { +func (m *ApiKeyMutation) OldUserID(ctx context.Context) (v uuid.UUID, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldName is only allowed on UpdateOne operations") + return v, errors.New("OldUserID 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") + return v, errors.New("OldUserID requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldName: %w", err) + return v, fmt.Errorf("querying old value for OldUserID: %w", err) } - return oldValue.Name, nil + return oldValue.UserID, nil } -// ResetName resets all changes to the "name" field. -func (m *BillingPlanMutation) ResetName() { - m.name = nil +// ResetUserID resets all changes to the "user_id" field. +func (m *ApiKeyMutation) ResetUserID() { + m.user = nil } -// SetDescription sets the "description" field. -func (m *BillingPlanMutation) SetDescription(s string) { - m.description = &s +// SetKey sets the "key" field. +func (m *ApiKeyMutation) SetKey(s string) { + m.key = &s } -// Description returns the value of the "description" field in the mutation. -func (m *BillingPlanMutation) Description() (r string, exists bool) { - v := m.description +// Key returns the value of the "key" field in the mutation. +func (m *ApiKeyMutation) Key() (r string, exists bool) { + v := m.key if v == nil { return } return *v, true } -// OldDescription returns the old "description" field's value of the BillingPlan entity. -// If the BillingPlan object wasn't provided to the builder, the object is fetched from the database. +// OldKey returns the old "key" field's value of the ApiKey entity. +// If the ApiKey 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 *BillingPlanMutation) OldDescription(ctx context.Context) (v string, err error) { +func (m *ApiKeyMutation) OldKey(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldDescription is only allowed on UpdateOne operations") + return v, errors.New("OldKey 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") + return v, errors.New("OldKey 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 v, fmt.Errorf("querying old value for OldKey: %w", err) } - return oldValue.Description, nil + return oldValue.Key, nil } -// ResetDescription resets all changes to the "description" field. -func (m *BillingPlanMutation) ResetDescription() { - m.description = nil +// ResetKey resets all changes to the "key" field. +func (m *ApiKeyMutation) ResetKey() { + m.key = nil } -// SetRules sets the "rules" field. -func (m *BillingPlanMutation) SetRules(value map[string]interface{}) { - m.rules = &value +// SetName sets the "name" field. +func (m *ApiKeyMutation) SetName(s string) { + m.name = &s } -// Rules returns the value of the "rules" field in the mutation. -func (m *BillingPlanMutation) Rules() (r map[string]interface{}, exists bool) { - v := m.rules +// Name returns the value of the "name" field in the mutation. +func (m *ApiKeyMutation) Name() (r string, exists bool) { + v := m.name if v == nil { return } return *v, true } -// OldRules returns the old "rules" field's value of the BillingPlan entity. -// If the BillingPlan object wasn't provided to the builder, the object is fetched from the database. +// OldName returns the old "name" field's value of the ApiKey entity. +// If the ApiKey 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 *BillingPlanMutation) OldRules(ctx context.Context) (v map[string]interface{}, err error) { +func (m *ApiKeyMutation) OldName(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldRules is only allowed on UpdateOne operations") + return v, errors.New("OldName is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldRules requires an ID field in the mutation") + 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 OldRules: %w", err) + return v, fmt.Errorf("querying old value for OldName: %w", err) } - return oldValue.Rules, nil + return oldValue.Name, nil } -// ResetRules resets all changes to the "rules" field. -func (m *BillingPlanMutation) ResetRules() { - m.rules = nil +// ResetName resets all changes to the "name" field. +func (m *ApiKeyMutation) ResetName() { + m.name = nil +} + +// SetStatus sets the "status" field. +func (m *ApiKeyMutation) SetStatus(cks consts.ApiKeyStatus) { + m.status = &cks +} + +// Status returns the value of the "status" field in the mutation. +func (m *ApiKeyMutation) Status() (r consts.ApiKeyStatus, exists bool) { + v := m.status + if v == nil { + return + } + return *v, true +} + +// OldStatus returns the old "status" field's value of the ApiKey entity. +// If the ApiKey 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 *ApiKeyMutation) OldStatus(ctx context.Context) (v consts.ApiKeyStatus, 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 *ApiKeyMutation) ResetStatus() { + m.status = nil +} + +// SetLastUsed sets the "last_used" field. +func (m *ApiKeyMutation) SetLastUsed(t time.Time) { + m.last_used = &t +} + +// LastUsed returns the value of the "last_used" field in the mutation. +func (m *ApiKeyMutation) LastUsed() (r time.Time, exists bool) { + v := m.last_used + if v == nil { + return + } + return *v, true +} + +// OldLastUsed returns the old "last_used" field's value of the ApiKey entity. +// If the ApiKey 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 *ApiKeyMutation) OldLastUsed(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldLastUsed is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldLastUsed requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldLastUsed: %w", err) + } + return oldValue.LastUsed, nil +} + +// ClearLastUsed clears the value of the "last_used" field. +func (m *ApiKeyMutation) ClearLastUsed() { + m.last_used = nil + m.clearedFields[apikey.FieldLastUsed] = struct{}{} +} + +// LastUsedCleared returns if the "last_used" field was cleared in this mutation. +func (m *ApiKeyMutation) LastUsedCleared() bool { + _, ok := m.clearedFields[apikey.FieldLastUsed] + return ok +} + +// ResetLastUsed resets all changes to the "last_used" field. +func (m *ApiKeyMutation) ResetLastUsed() { + m.last_used = nil + delete(m.clearedFields, apikey.FieldLastUsed) } // SetCreatedAt sets the "created_at" field. -func (m *BillingPlanMutation) SetCreatedAt(t time.Time) { +func (m *ApiKeyMutation) SetCreatedAt(t time.Time) { m.created_at = &t } // CreatedAt returns the value of the "created_at" field in the mutation. -func (m *BillingPlanMutation) CreatedAt() (r time.Time, exists bool) { +func (m *ApiKeyMutation) CreatedAt() (r time.Time, exists bool) { v := m.created_at if v == nil { return @@ -2730,10 +3000,10 @@ func (m *BillingPlanMutation) CreatedAt() (r time.Time, exists bool) { return *v, true } -// OldCreatedAt returns the old "created_at" field's value of the BillingPlan entity. -// If the BillingPlan object wasn't provided to the builder, the object is fetched from the database. +// OldCreatedAt returns the old "created_at" field's value of the ApiKey entity. +// If the ApiKey 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 *BillingPlanMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { +func (m *ApiKeyMutation) 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") } @@ -2748,17 +3018,17 @@ func (m *BillingPlanMutation) OldCreatedAt(ctx context.Context) (v time.Time, er } // ResetCreatedAt resets all changes to the "created_at" field. -func (m *BillingPlanMutation) ResetCreatedAt() { +func (m *ApiKeyMutation) ResetCreatedAt() { m.created_at = nil } // SetUpdatedAt sets the "updated_at" field. -func (m *BillingPlanMutation) SetUpdatedAt(t time.Time) { +func (m *ApiKeyMutation) SetUpdatedAt(t time.Time) { m.updated_at = &t } // UpdatedAt returns the value of the "updated_at" field in the mutation. -func (m *BillingPlanMutation) UpdatedAt() (r time.Time, exists bool) { +func (m *ApiKeyMutation) UpdatedAt() (r time.Time, exists bool) { v := m.updated_at if v == nil { return @@ -2766,10 +3036,10 @@ func (m *BillingPlanMutation) UpdatedAt() (r time.Time, exists bool) { return *v, true } -// OldUpdatedAt returns the old "updated_at" field's value of the BillingPlan entity. -// If the BillingPlan object wasn't provided to the builder, the object is fetched from the database. +// OldUpdatedAt returns the old "updated_at" field's value of the ApiKey entity. +// If the ApiKey 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 *BillingPlanMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { +func (m *ApiKeyMutation) 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") } @@ -2784,19 +3054,46 @@ func (m *BillingPlanMutation) OldUpdatedAt(ctx context.Context) (v time.Time, er } // ResetUpdatedAt resets all changes to the "updated_at" field. -func (m *BillingPlanMutation) ResetUpdatedAt() { +func (m *ApiKeyMutation) ResetUpdatedAt() { m.updated_at = nil } -// Where appends a list predicates to the BillingPlanMutation builder. -func (m *BillingPlanMutation) Where(ps ...predicate.BillingPlan) { +// ClearUser clears the "user" edge to the User entity. +func (m *ApiKeyMutation) ClearUser() { + m.cleareduser = true + m.clearedFields[apikey.FieldUserID] = struct{}{} +} + +// UserCleared reports if the "user" edge to the User entity was cleared. +func (m *ApiKeyMutation) UserCleared() bool { + return m.cleareduser +} + +// UserIDs returns the "user" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// UserID instead. It exists only for internal usage by the builders. +func (m *ApiKeyMutation) UserIDs() (ids []uuid.UUID) { + if id := m.user; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetUser resets all changes to the "user" edge. +func (m *ApiKeyMutation) ResetUser() { + m.user = nil + m.cleareduser = false +} + +// Where appends a list predicates to the ApiKeyMutation builder. +func (m *ApiKeyMutation) Where(ps ...predicate.ApiKey) { m.predicates = append(m.predicates, ps...) } -// WhereP appends storage-level predicates to the BillingPlanMutation builder. Using this method, +// WhereP appends storage-level predicates to the ApiKeyMutation builder. Using this method, // users can use type-assertion to append predicates that do not depend on any generated package. -func (m *BillingPlanMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.BillingPlan, len(ps)) +func (m *ApiKeyMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.ApiKey, len(ps)) for i := range ps { p[i] = ps[i] } @@ -2804,39 +3101,45 @@ func (m *BillingPlanMutation) WhereP(ps ...func(*sql.Selector)) { } // Op returns the operation name. -func (m *BillingPlanMutation) Op() Op { +func (m *ApiKeyMutation) Op() Op { return m.op } // SetOp allows setting the mutation operation. -func (m *BillingPlanMutation) SetOp(op Op) { +func (m *ApiKeyMutation) SetOp(op Op) { m.op = op } -// Type returns the node type of this mutation (BillingPlan). -func (m *BillingPlanMutation) Type() string { +// Type returns the node type of this mutation (ApiKey). +func (m *ApiKeyMutation) 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 *BillingPlanMutation) Fields() []string { - fields := make([]string, 0, 5) +func (m *ApiKeyMutation) Fields() []string { + fields := make([]string, 0, 7) + if m.user != nil { + fields = append(fields, apikey.FieldUserID) + } + if m.key != nil { + fields = append(fields, apikey.FieldKey) + } if m.name != nil { - fields = append(fields, billingplan.FieldName) + fields = append(fields, apikey.FieldName) } - if m.description != nil { - fields = append(fields, billingplan.FieldDescription) + if m.status != nil { + fields = append(fields, apikey.FieldStatus) } - if m.rules != nil { - fields = append(fields, billingplan.FieldRules) + if m.last_used != nil { + fields = append(fields, apikey.FieldLastUsed) } if m.created_at != nil { - fields = append(fields, billingplan.FieldCreatedAt) + fields = append(fields, apikey.FieldCreatedAt) } if m.updated_at != nil { - fields = append(fields, billingplan.FieldUpdatedAt) + fields = append(fields, apikey.FieldUpdatedAt) } return fields } @@ -2844,17 +3147,21 @@ func (m *BillingPlanMutation) Fields() []string { // 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 *BillingPlanMutation) Field(name string) (ent.Value, bool) { +func (m *ApiKeyMutation) Field(name string) (ent.Value, bool) { switch name { - case billingplan.FieldName: + case apikey.FieldUserID: + return m.UserID() + case apikey.FieldKey: + return m.Key() + case apikey.FieldName: return m.Name() - case billingplan.FieldDescription: - return m.Description() - case billingplan.FieldRules: - return m.Rules() - case billingplan.FieldCreatedAt: + case apikey.FieldStatus: + return m.Status() + case apikey.FieldLastUsed: + return m.LastUsed() + case apikey.FieldCreatedAt: return m.CreatedAt() - case billingplan.FieldUpdatedAt: + case apikey.FieldUpdatedAt: return m.UpdatedAt() } return nil, false @@ -2863,56 +3170,74 @@ func (m *BillingPlanMutation) Field(name string) (ent.Value, bool) { // 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 *BillingPlanMutation) OldField(ctx context.Context, name string) (ent.Value, error) { +func (m *ApiKeyMutation) OldField(ctx context.Context, name string) (ent.Value, error) { switch name { - case billingplan.FieldName: + case apikey.FieldUserID: + return m.OldUserID(ctx) + case apikey.FieldKey: + return m.OldKey(ctx) + case apikey.FieldName: return m.OldName(ctx) - case billingplan.FieldDescription: - return m.OldDescription(ctx) - case billingplan.FieldRules: - return m.OldRules(ctx) - case billingplan.FieldCreatedAt: + case apikey.FieldStatus: + return m.OldStatus(ctx) + case apikey.FieldLastUsed: + return m.OldLastUsed(ctx) + case apikey.FieldCreatedAt: return m.OldCreatedAt(ctx) - case billingplan.FieldUpdatedAt: + case apikey.FieldUpdatedAt: return m.OldUpdatedAt(ctx) } - return nil, fmt.Errorf("unknown BillingPlan field %s", name) + return nil, fmt.Errorf("unknown ApiKey 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 *BillingPlanMutation) SetField(name string, value ent.Value) error { +func (m *ApiKeyMutation) SetField(name string, value ent.Value) error { switch name { - case billingplan.FieldName: + case apikey.FieldUserID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUserID(v) + return nil + case apikey.FieldKey: v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetName(v) + m.SetKey(v) return nil - case billingplan.FieldDescription: + case apikey.FieldName: v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetDescription(v) + m.SetName(v) return nil - case billingplan.FieldRules: - v, ok := value.(map[string]interface{}) + case apikey.FieldStatus: + v, ok := value.(consts.ApiKeyStatus) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetRules(v) + m.SetStatus(v) return nil - case billingplan.FieldCreatedAt: + case apikey.FieldLastUsed: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLastUsed(v) + return nil + case apikey.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 billingplan.FieldUpdatedAt: + case apikey.FieldUpdatedAt: v, ok := value.(time.Time) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) @@ -2920,154 +3245,190 @@ func (m *BillingPlanMutation) SetField(name string, value ent.Value) error { m.SetUpdatedAt(v) return nil } - return fmt.Errorf("unknown BillingPlan field %s", name) + return fmt.Errorf("unknown ApiKey field %s", name) } // AddedFields returns all numeric fields that were incremented/decremented during // this mutation. -func (m *BillingPlanMutation) AddedFields() []string { +func (m *ApiKeyMutation) 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 *BillingPlanMutation) AddedField(name string) (ent.Value, bool) { +func (m *ApiKeyMutation) 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 *BillingPlanMutation) AddField(name string, value ent.Value) error { +func (m *ApiKeyMutation) AddField(name string, value ent.Value) error { switch name { } - return fmt.Errorf("unknown BillingPlan numeric field %s", name) + return fmt.Errorf("unknown ApiKey numeric field %s", name) } // ClearedFields returns all nullable fields that were cleared during this // mutation. -func (m *BillingPlanMutation) ClearedFields() []string { - return nil +func (m *ApiKeyMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(apikey.FieldLastUsed) { + fields = append(fields, apikey.FieldLastUsed) + } + return fields } // FieldCleared returns a boolean indicating if a field with the given name was // cleared in this mutation. -func (m *BillingPlanMutation) FieldCleared(name string) bool { +func (m *ApiKeyMutation) 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 *BillingPlanMutation) ClearField(name string) error { - return fmt.Errorf("unknown BillingPlan nullable field %s", name) +func (m *ApiKeyMutation) ClearField(name string) error { + switch name { + case apikey.FieldLastUsed: + m.ClearLastUsed() + return nil + } + return fmt.Errorf("unknown ApiKey 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 *BillingPlanMutation) ResetField(name string) error { +func (m *ApiKeyMutation) ResetField(name string) error { switch name { - case billingplan.FieldName: + case apikey.FieldUserID: + m.ResetUserID() + return nil + case apikey.FieldKey: + m.ResetKey() + return nil + case apikey.FieldName: m.ResetName() return nil - case billingplan.FieldDescription: - m.ResetDescription() + case apikey.FieldStatus: + m.ResetStatus() return nil - case billingplan.FieldRules: - m.ResetRules() + case apikey.FieldLastUsed: + m.ResetLastUsed() return nil - case billingplan.FieldCreatedAt: + case apikey.FieldCreatedAt: m.ResetCreatedAt() return nil - case billingplan.FieldUpdatedAt: + case apikey.FieldUpdatedAt: m.ResetUpdatedAt() return nil } - return fmt.Errorf("unknown BillingPlan field %s", name) + return fmt.Errorf("unknown ApiKey field %s", name) } // AddedEdges returns all edge names that were set/added in this mutation. -func (m *BillingPlanMutation) AddedEdges() []string { - edges := make([]string, 0, 0) +func (m *ApiKeyMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.user != nil { + edges = append(edges, apikey.EdgeUser) + } return edges } // AddedIDs returns all IDs (to other nodes) that were added for the given edge // name in this mutation. -func (m *BillingPlanMutation) AddedIDs(name string) []ent.Value { +func (m *ApiKeyMutation) AddedIDs(name string) []ent.Value { + switch name { + case apikey.EdgeUser: + if id := m.user; id != nil { + return []ent.Value{*id} + } + } return nil } // RemovedEdges returns all edge names that were removed in this mutation. -func (m *BillingPlanMutation) RemovedEdges() []string { - edges := make([]string, 0, 0) +func (m *ApiKeyMutation) 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 *BillingPlanMutation) RemovedIDs(name string) []ent.Value { +func (m *ApiKeyMutation) RemovedIDs(name string) []ent.Value { return nil } // ClearedEdges returns all edge names that were cleared in this mutation. -func (m *BillingPlanMutation) ClearedEdges() []string { - edges := make([]string, 0, 0) +func (m *ApiKeyMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.cleareduser { + edges = append(edges, apikey.EdgeUser) + } return edges } // EdgeCleared returns a boolean which indicates if the edge with the given name // was cleared in this mutation. -func (m *BillingPlanMutation) EdgeCleared(name string) bool { +func (m *ApiKeyMutation) EdgeCleared(name string) bool { + switch name { + case apikey.EdgeUser: + return m.cleareduser + } 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 *BillingPlanMutation) ClearEdge(name string) error { - return fmt.Errorf("unknown BillingPlan unique edge %s", name) +func (m *ApiKeyMutation) ClearEdge(name string) error { + switch name { + case apikey.EdgeUser: + m.ClearUser() + return nil + } + return fmt.Errorf("unknown ApiKey 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 *BillingPlanMutation) ResetEdge(name string) error { - return fmt.Errorf("unknown BillingPlan edge %s", name) +func (m *ApiKeyMutation) ResetEdge(name string) error { + switch name { + case apikey.EdgeUser: + m.ResetUser() + return nil + } + return fmt.Errorf("unknown ApiKey edge %s", name) } -// BillingQuotaMutation represents an operation that mutates the BillingQuota nodes in the graph. -type BillingQuotaMutation struct { +// BillingPlanMutation represents an operation that mutates the BillingPlan nodes in the graph. +type BillingPlanMutation struct { config op Op typ string id *string - deleted_at *time.Time - user_id *string - total *int64 - addtotal *int64 - used *int64 - addused *int64 - remain *int64 - addremain *int64 + name *string + description *string + rules *map[string]interface{} created_at *time.Time updated_at *time.Time clearedFields map[string]struct{} done bool - oldValue func(context.Context) (*BillingQuota, error) - predicates []predicate.BillingQuota + oldValue func(context.Context) (*BillingPlan, error) + predicates []predicate.BillingPlan } -var _ ent.Mutation = (*BillingQuotaMutation)(nil) +var _ ent.Mutation = (*BillingPlanMutation)(nil) -// billingquotaOption allows management of the mutation configuration using functional options. -type billingquotaOption func(*BillingQuotaMutation) +// billingplanOption allows management of the mutation configuration using functional options. +type billingplanOption func(*BillingPlanMutation) -// newBillingQuotaMutation creates new mutation for the BillingQuota entity. -func newBillingQuotaMutation(c config, op Op, opts ...billingquotaOption) *BillingQuotaMutation { - m := &BillingQuotaMutation{ +// newBillingPlanMutation creates new mutation for the BillingPlan entity. +func newBillingPlanMutation(c config, op Op, opts ...billingplanOption) *BillingPlanMutation { + m := &BillingPlanMutation{ config: c, op: op, - typ: TypeBillingQuota, + typ: TypeBillingPlan, clearedFields: make(map[string]struct{}), } for _, opt := range opts { @@ -3076,20 +3437,20 @@ func newBillingQuotaMutation(c config, op Op, opts ...billingquotaOption) *Billi return m } -// withBillingQuotaID sets the ID field of the mutation. -func withBillingQuotaID(id string) billingquotaOption { - return func(m *BillingQuotaMutation) { +// withBillingPlanID sets the ID field of the mutation. +func withBillingPlanID(id string) billingplanOption { + return func(m *BillingPlanMutation) { var ( err error once sync.Once - value *BillingQuota + value *BillingPlan ) - m.oldValue = func(ctx context.Context) (*BillingQuota, error) { + m.oldValue = func(ctx context.Context) (*BillingPlan, error) { once.Do(func() { if m.done { err = errors.New("querying old values post mutation is not allowed") } else { - value, err = m.Client().BillingQuota.Get(ctx, id) + value, err = m.Client().BillingPlan.Get(ctx, id) } }) return value, err @@ -3098,10 +3459,10 @@ func withBillingQuotaID(id string) billingquotaOption { } } -// withBillingQuota sets the old BillingQuota of the mutation. -func withBillingQuota(node *BillingQuota) billingquotaOption { - return func(m *BillingQuotaMutation) { - m.oldValue = func(context.Context) (*BillingQuota, error) { +// withBillingPlan sets the old BillingPlan of the mutation. +func withBillingPlan(node *BillingPlan) billingplanOption { + return func(m *BillingPlanMutation) { + m.oldValue = func(context.Context) (*BillingPlan, error) { return node, nil } m.id = &node.ID @@ -3110,7 +3471,7 @@ func withBillingQuota(node *BillingQuota) billingquotaOption { // 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 BillingQuotaMutation) Client() *Client { +func (m BillingPlanMutation) Client() *Client { client := &Client{config: m.config} client.init() return client @@ -3118,7 +3479,7 @@ func (m BillingQuotaMutation) Client() *Client { // Tx returns an `ent.Tx` for mutations that were executed in transactions; // it returns an error otherwise. -func (m BillingQuotaMutation) Tx() (*Tx, error) { +func (m BillingPlanMutation) Tx() (*Tx, error) { if _, ok := m.driver.(*txDriver); !ok { return nil, errors.New("db: mutation is not running in a transaction") } @@ -3128,14 +3489,14 @@ func (m BillingQuotaMutation) Tx() (*Tx, error) { } // SetID sets the value of the id field. Note that this -// operation is only accepted on creation of BillingQuota entities. -func (m *BillingQuotaMutation) SetID(id string) { +// operation is only accepted on creation of BillingPlan entities. +func (m *BillingPlanMutation) SetID(id string) { 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 *BillingQuotaMutation) ID() (id string, exists bool) { +func (m *BillingPlanMutation) ID() (id string, exists bool) { if m.id == nil { return } @@ -3146,7 +3507,7 @@ func (m *BillingQuotaMutation) ID() (id string, exists bool) { // 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 *BillingQuotaMutation) IDs(ctx context.Context) ([]string, error) { +func (m *BillingPlanMutation) IDs(ctx context.Context) ([]string, error) { switch { case m.op.Is(OpUpdateOne | OpDeleteOne): id, exists := m.ID() @@ -3155,272 +3516,127 @@ func (m *BillingQuotaMutation) IDs(ctx context.Context) ([]string, error) { } fallthrough case m.op.Is(OpUpdate | OpDelete): - return m.Client().BillingQuota.Query().Where(m.predicates...).IDs(ctx) + return m.Client().BillingPlan.Query().Where(m.predicates...).IDs(ctx) default: return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) } } -// SetDeletedAt sets the "deleted_at" field. -func (m *BillingQuotaMutation) SetDeletedAt(t time.Time) { - m.deleted_at = &t +// SetName sets the "name" field. +func (m *BillingPlanMutation) SetName(s string) { + m.name = &s } -// DeletedAt returns the value of the "deleted_at" field in the mutation. -func (m *BillingQuotaMutation) DeletedAt() (r time.Time, exists bool) { - v := m.deleted_at +// Name returns the value of the "name" field in the mutation. +func (m *BillingPlanMutation) Name() (r string, exists bool) { + v := m.name if v == nil { return } return *v, true } -// OldDeletedAt returns the old "deleted_at" field's value of the BillingQuota entity. -// If the BillingQuota object wasn't provided to the builder, the object is fetched from the database. +// OldName returns the old "name" field's value of the BillingPlan entity. +// If the BillingPlan 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 *BillingQuotaMutation) OldDeletedAt(ctx context.Context) (v time.Time, err error) { +func (m *BillingPlanMutation) OldName(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldDeletedAt is only allowed on UpdateOne operations") + return v, errors.New("OldName is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldDeletedAt requires an ID field in the mutation") + 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 OldDeletedAt: %w", err) + return v, fmt.Errorf("querying old value for OldName: %w", err) } - return oldValue.DeletedAt, nil + return oldValue.Name, nil } -// ClearDeletedAt clears the value of the "deleted_at" field. -func (m *BillingQuotaMutation) ClearDeletedAt() { - m.deleted_at = nil - m.clearedFields[billingquota.FieldDeletedAt] = struct{}{} +// ResetName resets all changes to the "name" field. +func (m *BillingPlanMutation) ResetName() { + m.name = nil } -// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. -func (m *BillingQuotaMutation) DeletedAtCleared() bool { - _, ok := m.clearedFields[billingquota.FieldDeletedAt] - return ok +// SetDescription sets the "description" field. +func (m *BillingPlanMutation) SetDescription(s string) { + m.description = &s } -// ResetDeletedAt resets all changes to the "deleted_at" field. -func (m *BillingQuotaMutation) ResetDeletedAt() { - m.deleted_at = nil - delete(m.clearedFields, billingquota.FieldDeletedAt) -} - -// SetUserID sets the "user_id" field. -func (m *BillingQuotaMutation) SetUserID(s string) { - m.user_id = &s -} - -// UserID returns the value of the "user_id" field in the mutation. -func (m *BillingQuotaMutation) UserID() (r string, exists bool) { - v := m.user_id - if v == nil { - return - } - return *v, true -} - -// OldUserID returns the old "user_id" field's value of the BillingQuota entity. -// If the BillingQuota 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 *BillingQuotaMutation) OldUserID(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldUserID is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldUserID requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldUserID: %w", err) - } - return oldValue.UserID, nil -} - -// ResetUserID resets all changes to the "user_id" field. -func (m *BillingQuotaMutation) ResetUserID() { - m.user_id = nil -} - -// SetTotal sets the "total" field. -func (m *BillingQuotaMutation) SetTotal(i int64) { - m.total = &i - m.addtotal = nil -} - -// Total returns the value of the "total" field in the mutation. -func (m *BillingQuotaMutation) Total() (r int64, exists bool) { - v := m.total - if v == nil { - return - } - return *v, true -} - -// OldTotal returns the old "total" field's value of the BillingQuota entity. -// If the BillingQuota 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 *BillingQuotaMutation) OldTotal(ctx context.Context) (v int64, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldTotal is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldTotal requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldTotal: %w", err) - } - return oldValue.Total, nil -} - -// AddTotal adds i to the "total" field. -func (m *BillingQuotaMutation) AddTotal(i int64) { - if m.addtotal != nil { - *m.addtotal += i - } else { - m.addtotal = &i - } -} - -// AddedTotal returns the value that was added to the "total" field in this mutation. -func (m *BillingQuotaMutation) AddedTotal() (r int64, exists bool) { - v := m.addtotal - if v == nil { - return - } - return *v, true -} - -// ResetTotal resets all changes to the "total" field. -func (m *BillingQuotaMutation) ResetTotal() { - m.total = nil - m.addtotal = nil -} - -// SetUsed sets the "used" field. -func (m *BillingQuotaMutation) SetUsed(i int64) { - m.used = &i - m.addused = nil -} - -// Used returns the value of the "used" field in the mutation. -func (m *BillingQuotaMutation) Used() (r int64, exists bool) { - v := m.used +// Description returns the value of the "description" field in the mutation. +func (m *BillingPlanMutation) Description() (r string, exists bool) { + v := m.description if v == nil { return } return *v, true } -// OldUsed returns the old "used" field's value of the BillingQuota entity. -// If the BillingQuota object wasn't provided to the builder, the object is fetched from the database. +// OldDescription returns the old "description" field's value of the BillingPlan entity. +// If the BillingPlan 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 *BillingQuotaMutation) OldUsed(ctx context.Context) (v int64, err error) { +func (m *BillingPlanMutation) OldDescription(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldUsed is only allowed on UpdateOne operations") + return v, errors.New("OldDescription is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldUsed requires an ID field in the mutation") + 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 OldUsed: %w", err) - } - return oldValue.Used, nil -} - -// AddUsed adds i to the "used" field. -func (m *BillingQuotaMutation) AddUsed(i int64) { - if m.addused != nil { - *m.addused += i - } else { - m.addused = &i - } -} - -// AddedUsed returns the value that was added to the "used" field in this mutation. -func (m *BillingQuotaMutation) AddedUsed() (r int64, exists bool) { - v := m.addused - if v == nil { - return + return v, fmt.Errorf("querying old value for OldDescription: %w", err) } - return *v, true + return oldValue.Description, nil } -// ResetUsed resets all changes to the "used" field. -func (m *BillingQuotaMutation) ResetUsed() { - m.used = nil - m.addused = nil +// ResetDescription resets all changes to the "description" field. +func (m *BillingPlanMutation) ResetDescription() { + m.description = nil } -// SetRemain sets the "remain" field. -func (m *BillingQuotaMutation) SetRemain(i int64) { - m.remain = &i - m.addremain = nil +// SetRules sets the "rules" field. +func (m *BillingPlanMutation) SetRules(value map[string]interface{}) { + m.rules = &value } -// Remain returns the value of the "remain" field in the mutation. -func (m *BillingQuotaMutation) Remain() (r int64, exists bool) { - v := m.remain +// Rules returns the value of the "rules" field in the mutation. +func (m *BillingPlanMutation) Rules() (r map[string]interface{}, exists bool) { + v := m.rules if v == nil { return } return *v, true } -// OldRemain returns the old "remain" field's value of the BillingQuota entity. -// If the BillingQuota object wasn't provided to the builder, the object is fetched from the database. +// OldRules returns the old "rules" field's value of the BillingPlan entity. +// If the BillingPlan 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 *BillingQuotaMutation) OldRemain(ctx context.Context) (v int64, err error) { +func (m *BillingPlanMutation) OldRules(ctx context.Context) (v map[string]interface{}, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldRemain is only allowed on UpdateOne operations") + return v, errors.New("OldRules is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldRemain requires an ID field in the mutation") + return v, errors.New("OldRules requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldRemain: %w", err) - } - return oldValue.Remain, nil -} - -// AddRemain adds i to the "remain" field. -func (m *BillingQuotaMutation) AddRemain(i int64) { - if m.addremain != nil { - *m.addremain += i - } else { - m.addremain = &i - } -} - -// AddedRemain returns the value that was added to the "remain" field in this mutation. -func (m *BillingQuotaMutation) AddedRemain() (r int64, exists bool) { - v := m.addremain - if v == nil { - return + return v, fmt.Errorf("querying old value for OldRules: %w", err) } - return *v, true + return oldValue.Rules, nil } -// ResetRemain resets all changes to the "remain" field. -func (m *BillingQuotaMutation) ResetRemain() { - m.remain = nil - m.addremain = nil +// ResetRules resets all changes to the "rules" field. +func (m *BillingPlanMutation) ResetRules() { + m.rules = nil } // SetCreatedAt sets the "created_at" field. -func (m *BillingQuotaMutation) SetCreatedAt(t time.Time) { +func (m *BillingPlanMutation) SetCreatedAt(t time.Time) { m.created_at = &t } // CreatedAt returns the value of the "created_at" field in the mutation. -func (m *BillingQuotaMutation) CreatedAt() (r time.Time, exists bool) { +func (m *BillingPlanMutation) CreatedAt() (r time.Time, exists bool) { v := m.created_at if v == nil { return @@ -3428,10 +3644,10 @@ func (m *BillingQuotaMutation) CreatedAt() (r time.Time, exists bool) { return *v, true } -// OldCreatedAt returns the old "created_at" field's value of the BillingQuota entity. -// If the BillingQuota object wasn't provided to the builder, the object is fetched from the database. +// OldCreatedAt returns the old "created_at" field's value of the BillingPlan entity. +// If the BillingPlan 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 *BillingQuotaMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { +func (m *BillingPlanMutation) 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") } @@ -3446,17 +3662,17 @@ func (m *BillingQuotaMutation) OldCreatedAt(ctx context.Context) (v time.Time, e } // ResetCreatedAt resets all changes to the "created_at" field. -func (m *BillingQuotaMutation) ResetCreatedAt() { +func (m *BillingPlanMutation) ResetCreatedAt() { m.created_at = nil } // SetUpdatedAt sets the "updated_at" field. -func (m *BillingQuotaMutation) SetUpdatedAt(t time.Time) { +func (m *BillingPlanMutation) SetUpdatedAt(t time.Time) { m.updated_at = &t } // UpdatedAt returns the value of the "updated_at" field in the mutation. -func (m *BillingQuotaMutation) UpdatedAt() (r time.Time, exists bool) { +func (m *BillingPlanMutation) UpdatedAt() (r time.Time, exists bool) { v := m.updated_at if v == nil { return @@ -3464,10 +3680,10 @@ func (m *BillingQuotaMutation) UpdatedAt() (r time.Time, exists bool) { return *v, true } -// OldUpdatedAt returns the old "updated_at" field's value of the BillingQuota entity. -// If the BillingQuota object wasn't provided to the builder, the object is fetched from the database. +// OldUpdatedAt returns the old "updated_at" field's value of the BillingPlan entity. +// If the BillingPlan 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 *BillingQuotaMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { +func (m *BillingPlanMutation) 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") } @@ -3482,19 +3698,19 @@ func (m *BillingQuotaMutation) OldUpdatedAt(ctx context.Context) (v time.Time, e } // ResetUpdatedAt resets all changes to the "updated_at" field. -func (m *BillingQuotaMutation) ResetUpdatedAt() { +func (m *BillingPlanMutation) ResetUpdatedAt() { m.updated_at = nil } -// Where appends a list predicates to the BillingQuotaMutation builder. -func (m *BillingQuotaMutation) Where(ps ...predicate.BillingQuota) { +// Where appends a list predicates to the BillingPlanMutation builder. +func (m *BillingPlanMutation) Where(ps ...predicate.BillingPlan) { m.predicates = append(m.predicates, ps...) } -// WhereP appends storage-level predicates to the BillingQuotaMutation builder. Using this method, +// WhereP appends storage-level predicates to the BillingPlanMutation builder. Using this method, // users can use type-assertion to append predicates that do not depend on any generated package. -func (m *BillingQuotaMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.BillingQuota, len(ps)) +func (m *BillingPlanMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.BillingPlan, len(ps)) for i := range ps { p[i] = ps[i] } @@ -3502,45 +3718,39 @@ func (m *BillingQuotaMutation) WhereP(ps ...func(*sql.Selector)) { } // Op returns the operation name. -func (m *BillingQuotaMutation) Op() Op { +func (m *BillingPlanMutation) Op() Op { return m.op } // SetOp allows setting the mutation operation. -func (m *BillingQuotaMutation) SetOp(op Op) { +func (m *BillingPlanMutation) SetOp(op Op) { m.op = op } -// Type returns the node type of this mutation (BillingQuota). -func (m *BillingQuotaMutation) Type() string { +// Type returns the node type of this mutation (BillingPlan). +func (m *BillingPlanMutation) 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 *BillingQuotaMutation) Fields() []string { - fields := make([]string, 0, 7) - if m.deleted_at != nil { - fields = append(fields, billingquota.FieldDeletedAt) +func (m *BillingPlanMutation) Fields() []string { + fields := make([]string, 0, 5) + if m.name != nil { + fields = append(fields, billingplan.FieldName) } - if m.user_id != nil { - fields = append(fields, billingquota.FieldUserID) + if m.description != nil { + fields = append(fields, billingplan.FieldDescription) } - if m.total != nil { - fields = append(fields, billingquota.FieldTotal) - } - if m.used != nil { - fields = append(fields, billingquota.FieldUsed) - } - if m.remain != nil { - fields = append(fields, billingquota.FieldRemain) + if m.rules != nil { + fields = append(fields, billingplan.FieldRules) } if m.created_at != nil { - fields = append(fields, billingquota.FieldCreatedAt) + fields = append(fields, billingplan.FieldCreatedAt) } if m.updated_at != nil { - fields = append(fields, billingquota.FieldUpdatedAt) + fields = append(fields, billingplan.FieldUpdatedAt) } return fields } @@ -3548,21 +3758,17 @@ func (m *BillingQuotaMutation) Fields() []string { // 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 *BillingQuotaMutation) Field(name string) (ent.Value, bool) { +func (m *BillingPlanMutation) Field(name string) (ent.Value, bool) { switch name { - case billingquota.FieldDeletedAt: - return m.DeletedAt() - case billingquota.FieldUserID: - return m.UserID() - case billingquota.FieldTotal: - return m.Total() - case billingquota.FieldUsed: - return m.Used() - case billingquota.FieldRemain: - return m.Remain() - case billingquota.FieldCreatedAt: + case billingplan.FieldName: + return m.Name() + case billingplan.FieldDescription: + return m.Description() + case billingplan.FieldRules: + return m.Rules() + case billingplan.FieldCreatedAt: return m.CreatedAt() - case billingquota.FieldUpdatedAt: + case billingplan.FieldUpdatedAt: return m.UpdatedAt() } return nil, false @@ -3571,74 +3777,56 @@ func (m *BillingQuotaMutation) Field(name string) (ent.Value, bool) { // 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 *BillingQuotaMutation) OldField(ctx context.Context, name string) (ent.Value, error) { +func (m *BillingPlanMutation) OldField(ctx context.Context, name string) (ent.Value, error) { switch name { - case billingquota.FieldDeletedAt: - return m.OldDeletedAt(ctx) - case billingquota.FieldUserID: - return m.OldUserID(ctx) - case billingquota.FieldTotal: - return m.OldTotal(ctx) - case billingquota.FieldUsed: - return m.OldUsed(ctx) - case billingquota.FieldRemain: - return m.OldRemain(ctx) - case billingquota.FieldCreatedAt: + case billingplan.FieldName: + return m.OldName(ctx) + case billingplan.FieldDescription: + return m.OldDescription(ctx) + case billingplan.FieldRules: + return m.OldRules(ctx) + case billingplan.FieldCreatedAt: return m.OldCreatedAt(ctx) - case billingquota.FieldUpdatedAt: + case billingplan.FieldUpdatedAt: return m.OldUpdatedAt(ctx) } - return nil, fmt.Errorf("unknown BillingQuota field %s", name) + return nil, fmt.Errorf("unknown BillingPlan 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 *BillingQuotaMutation) SetField(name string, value ent.Value) error { +func (m *BillingPlanMutation) SetField(name string, value ent.Value) error { switch name { - case billingquota.FieldDeletedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetDeletedAt(v) - return nil - case billingquota.FieldUserID: + case billingplan.FieldName: v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetUserID(v) - return nil - case billingquota.FieldTotal: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetTotal(v) + m.SetName(v) return nil - case billingquota.FieldUsed: - v, ok := value.(int64) + case billingplan.FieldDescription: + v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetUsed(v) + m.SetDescription(v) return nil - case billingquota.FieldRemain: - v, ok := value.(int64) + case billingplan.FieldRules: + v, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetRemain(v) + m.SetRules(v) return nil - case billingquota.FieldCreatedAt: + case billingplan.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 billingquota.FieldUpdatedAt: + case billingplan.FieldUpdatedAt: v, ok := value.(time.Time) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) @@ -3646,212 +3834,154 @@ func (m *BillingQuotaMutation) SetField(name string, value ent.Value) error { m.SetUpdatedAt(v) return nil } - return fmt.Errorf("unknown BillingQuota field %s", name) + return fmt.Errorf("unknown BillingPlan field %s", name) } // AddedFields returns all numeric fields that were incremented/decremented during // this mutation. -func (m *BillingQuotaMutation) AddedFields() []string { - var fields []string - if m.addtotal != nil { - fields = append(fields, billingquota.FieldTotal) - } - if m.addused != nil { - fields = append(fields, billingquota.FieldUsed) - } - if m.addremain != nil { - fields = append(fields, billingquota.FieldRemain) - } - return fields +func (m *BillingPlanMutation) 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 *BillingQuotaMutation) AddedField(name string) (ent.Value, bool) { - switch name { - case billingquota.FieldTotal: - return m.AddedTotal() - case billingquota.FieldUsed: - return m.AddedUsed() - case billingquota.FieldRemain: - return m.AddedRemain() - } +func (m *BillingPlanMutation) 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 *BillingQuotaMutation) AddField(name string, value ent.Value) error { +func (m *BillingPlanMutation) AddField(name string, value ent.Value) error { switch name { - case billingquota.FieldTotal: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddTotal(v) - return nil - case billingquota.FieldUsed: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddUsed(v) - return nil - case billingquota.FieldRemain: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddRemain(v) - return nil } - return fmt.Errorf("unknown BillingQuota numeric field %s", name) + return fmt.Errorf("unknown BillingPlan numeric field %s", name) } // ClearedFields returns all nullable fields that were cleared during this // mutation. -func (m *BillingQuotaMutation) ClearedFields() []string { - var fields []string - if m.FieldCleared(billingquota.FieldDeletedAt) { - fields = append(fields, billingquota.FieldDeletedAt) - } - return fields +func (m *BillingPlanMutation) ClearedFields() []string { + return nil } // FieldCleared returns a boolean indicating if a field with the given name was // cleared in this mutation. -func (m *BillingQuotaMutation) FieldCleared(name string) bool { +func (m *BillingPlanMutation) 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 *BillingQuotaMutation) ClearField(name string) error { - switch name { - case billingquota.FieldDeletedAt: - m.ClearDeletedAt() - return nil - } - return fmt.Errorf("unknown BillingQuota nullable field %s", name) +func (m *BillingPlanMutation) ClearField(name string) error { + return fmt.Errorf("unknown BillingPlan 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 *BillingQuotaMutation) ResetField(name string) error { +func (m *BillingPlanMutation) ResetField(name string) error { switch name { - case billingquota.FieldDeletedAt: - m.ResetDeletedAt() - return nil - case billingquota.FieldUserID: - m.ResetUserID() - return nil - case billingquota.FieldTotal: - m.ResetTotal() + case billingplan.FieldName: + m.ResetName() return nil - case billingquota.FieldUsed: - m.ResetUsed() + case billingplan.FieldDescription: + m.ResetDescription() return nil - case billingquota.FieldRemain: - m.ResetRemain() + case billingplan.FieldRules: + m.ResetRules() return nil - case billingquota.FieldCreatedAt: + case billingplan.FieldCreatedAt: m.ResetCreatedAt() return nil - case billingquota.FieldUpdatedAt: + case billingplan.FieldUpdatedAt: m.ResetUpdatedAt() return nil } - return fmt.Errorf("unknown BillingQuota field %s", name) + return fmt.Errorf("unknown BillingPlan field %s", name) } // AddedEdges returns all edge names that were set/added in this mutation. -func (m *BillingQuotaMutation) AddedEdges() []string { +func (m *BillingPlanMutation) 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 *BillingQuotaMutation) AddedIDs(name string) []ent.Value { +func (m *BillingPlanMutation) AddedIDs(name string) []ent.Value { return nil } // RemovedEdges returns all edge names that were removed in this mutation. -func (m *BillingQuotaMutation) RemovedEdges() []string { +func (m *BillingPlanMutation) 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 *BillingQuotaMutation) RemovedIDs(name string) []ent.Value { +func (m *BillingPlanMutation) RemovedIDs(name string) []ent.Value { return nil } // ClearedEdges returns all edge names that were cleared in this mutation. -func (m *BillingQuotaMutation) ClearedEdges() []string { +func (m *BillingPlanMutation) 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 *BillingQuotaMutation) EdgeCleared(name string) bool { +func (m *BillingPlanMutation) 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 *BillingQuotaMutation) ClearEdge(name string) error { - return fmt.Errorf("unknown BillingQuota unique edge %s", name) +func (m *BillingPlanMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown BillingPlan 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 *BillingQuotaMutation) ResetEdge(name string) error { - return fmt.Errorf("unknown BillingQuota edge %s", name) +func (m *BillingPlanMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown BillingPlan edge %s", name) } -// BillingRecordMutation represents an operation that mutates the BillingRecord nodes in the graph. -type BillingRecordMutation struct { +// BillingQuotaMutation represents an operation that mutates the BillingQuota nodes in the graph. +type BillingQuotaMutation struct { config - op Op - typ string - id *string - tenant_id *string - user_id *string - model *string - operation *string - input_tokens *int64 - addinput_tokens *int64 - output_tokens *int64 - addoutput_tokens *int64 - cost *int64 - addcost *int64 - request_time *time.Time - metadata *map[string]interface{} - created_at *time.Time - updated_at *time.Time - clearedFields map[string]struct{} - done bool - oldValue func(context.Context) (*BillingRecord, error) - predicates []predicate.BillingRecord + op Op + typ string + id *string + deleted_at *time.Time + user_id *string + total *int64 + addtotal *int64 + used *int64 + addused *int64 + remain *int64 + addremain *int64 + created_at *time.Time + updated_at *time.Time + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*BillingQuota, error) + predicates []predicate.BillingQuota } -var _ ent.Mutation = (*BillingRecordMutation)(nil) +var _ ent.Mutation = (*BillingQuotaMutation)(nil) -// billingrecordOption allows management of the mutation configuration using functional options. -type billingrecordOption func(*BillingRecordMutation) +// billingquotaOption allows management of the mutation configuration using functional options. +type billingquotaOption func(*BillingQuotaMutation) -// newBillingRecordMutation creates new mutation for the BillingRecord entity. -func newBillingRecordMutation(c config, op Op, opts ...billingrecordOption) *BillingRecordMutation { - m := &BillingRecordMutation{ +// newBillingQuotaMutation creates new mutation for the BillingQuota entity. +func newBillingQuotaMutation(c config, op Op, opts ...billingquotaOption) *BillingQuotaMutation { + m := &BillingQuotaMutation{ config: c, op: op, - typ: TypeBillingRecord, + typ: TypeBillingQuota, clearedFields: make(map[string]struct{}), } for _, opt := range opts { @@ -3860,20 +3990,20 @@ func newBillingRecordMutation(c config, op Op, opts ...billingrecordOption) *Bil return m } -// withBillingRecordID sets the ID field of the mutation. -func withBillingRecordID(id string) billingrecordOption { - return func(m *BillingRecordMutation) { +// withBillingQuotaID sets the ID field of the mutation. +func withBillingQuotaID(id string) billingquotaOption { + return func(m *BillingQuotaMutation) { var ( err error once sync.Once - value *BillingRecord + value *BillingQuota ) - m.oldValue = func(ctx context.Context) (*BillingRecord, error) { + m.oldValue = func(ctx context.Context) (*BillingQuota, error) { once.Do(func() { if m.done { err = errors.New("querying old values post mutation is not allowed") } else { - value, err = m.Client().BillingRecord.Get(ctx, id) + value, err = m.Client().BillingQuota.Get(ctx, id) } }) return value, err @@ -3882,10 +4012,10 @@ func withBillingRecordID(id string) billingrecordOption { } } -// withBillingRecord sets the old BillingRecord of the mutation. -func withBillingRecord(node *BillingRecord) billingrecordOption { - return func(m *BillingRecordMutation) { - m.oldValue = func(context.Context) (*BillingRecord, error) { +// withBillingQuota sets the old BillingQuota of the mutation. +func withBillingQuota(node *BillingQuota) billingquotaOption { + return func(m *BillingQuotaMutation) { + m.oldValue = func(context.Context) (*BillingQuota, error) { return node, nil } m.id = &node.ID @@ -3894,7 +4024,7 @@ func withBillingRecord(node *BillingRecord) billingrecordOption { // 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 BillingRecordMutation) Client() *Client { +func (m BillingQuotaMutation) Client() *Client { client := &Client{config: m.config} client.init() return client @@ -3902,7 +4032,7 @@ func (m BillingRecordMutation) Client() *Client { // Tx returns an `ent.Tx` for mutations that were executed in transactions; // it returns an error otherwise. -func (m BillingRecordMutation) Tx() (*Tx, error) { +func (m BillingQuotaMutation) Tx() (*Tx, error) { if _, ok := m.driver.(*txDriver); !ok { return nil, errors.New("db: mutation is not running in a transaction") } @@ -3912,14 +4042,14 @@ func (m BillingRecordMutation) Tx() (*Tx, error) { } // SetID sets the value of the id field. Note that this -// operation is only accepted on creation of BillingRecord entities. -func (m *BillingRecordMutation) SetID(id string) { +// operation is only accepted on creation of BillingQuota entities. +func (m *BillingQuotaMutation) SetID(id string) { 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 *BillingRecordMutation) ID() (id string, exists bool) { +func (m *BillingQuotaMutation) ID() (id string, exists bool) { if m.id == nil { return } @@ -3930,7 +4060,7 @@ func (m *BillingRecordMutation) ID() (id string, exists bool) { // 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 *BillingRecordMutation) IDs(ctx context.Context) ([]string, error) { +func (m *BillingQuotaMutation) IDs(ctx context.Context) ([]string, error) { switch { case m.op.Is(OpUpdateOne | OpDeleteOne): id, exists := m.ID() @@ -3939,55 +4069,68 @@ func (m *BillingRecordMutation) IDs(ctx context.Context) ([]string, error) { } fallthrough case m.op.Is(OpUpdate | OpDelete): - return m.Client().BillingRecord.Query().Where(m.predicates...).IDs(ctx) + return m.Client().BillingQuota.Query().Where(m.predicates...).IDs(ctx) default: return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) } } -// SetTenantID sets the "tenant_id" field. -func (m *BillingRecordMutation) SetTenantID(s string) { - m.tenant_id = &s +// SetDeletedAt sets the "deleted_at" field. +func (m *BillingQuotaMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t } -// TenantID returns the value of the "tenant_id" field in the mutation. -func (m *BillingRecordMutation) TenantID() (r string, exists bool) { - v := m.tenant_id +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *BillingQuotaMutation) DeletedAt() (r time.Time, exists bool) { + v := m.deleted_at if v == nil { return } return *v, true } -// OldTenantID returns the old "tenant_id" field's value of the BillingRecord entity. -// If the BillingRecord object wasn't provided to the builder, the object is fetched from the database. +// OldDeletedAt returns the old "deleted_at" field's value of the BillingQuota entity. +// If the BillingQuota 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 *BillingRecordMutation) OldTenantID(ctx context.Context) (v string, err error) { +func (m *BillingQuotaMutation) OldDeletedAt(ctx context.Context) (v time.Time, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldTenantID is only allowed on UpdateOne operations") + return v, errors.New("OldDeletedAt is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldTenantID requires an ID field in the mutation") + return v, errors.New("OldDeletedAt requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldTenantID: %w", err) + return v, fmt.Errorf("querying old value for OldDeletedAt: %w", err) } - return oldValue.TenantID, nil + return oldValue.DeletedAt, nil } -// ResetTenantID resets all changes to the "tenant_id" field. -func (m *BillingRecordMutation) ResetTenantID() { - m.tenant_id = nil +// ClearDeletedAt clears the value of the "deleted_at" field. +func (m *BillingQuotaMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[billingquota.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *BillingQuotaMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[billingquota.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *BillingQuotaMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, billingquota.FieldDeletedAt) } // SetUserID sets the "user_id" field. -func (m *BillingRecordMutation) SetUserID(s string) { +func (m *BillingQuotaMutation) SetUserID(s string) { m.user_id = &s } // UserID returns the value of the "user_id" field in the mutation. -func (m *BillingRecordMutation) UserID() (r string, exists bool) { +func (m *BillingQuotaMutation) UserID() (r string, exists bool) { v := m.user_id if v == nil { return @@ -3995,10 +4138,10 @@ func (m *BillingRecordMutation) UserID() (r string, exists bool) { return *v, true } -// OldUserID returns the old "user_id" field's value of the BillingRecord entity. -// If the BillingRecord object wasn't provided to the builder, the object is fetched from the database. +// OldUserID returns the old "user_id" field's value of the BillingQuota entity. +// If the BillingQuota 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 *BillingRecordMutation) OldUserID(ctx context.Context) (v string, err error) { +func (m *BillingQuotaMutation) OldUserID(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { return v, errors.New("OldUserID is only allowed on UpdateOne operations") } @@ -4013,329 +4156,185 @@ func (m *BillingRecordMutation) OldUserID(ctx context.Context) (v string, err er } // ResetUserID resets all changes to the "user_id" field. -func (m *BillingRecordMutation) ResetUserID() { +func (m *BillingQuotaMutation) ResetUserID() { m.user_id = nil } -// SetModel sets the "model" field. -func (m *BillingRecordMutation) SetModel(s string) { - m.model = &s +// SetTotal sets the "total" field. +func (m *BillingQuotaMutation) SetTotal(i int64) { + m.total = &i + m.addtotal = nil } -// Model returns the value of the "model" field in the mutation. -func (m *BillingRecordMutation) Model() (r string, exists bool) { - v := m.model +// Total returns the value of the "total" field in the mutation. +func (m *BillingQuotaMutation) Total() (r int64, exists bool) { + v := m.total if v == nil { return } return *v, true } -// OldModel returns the old "model" field's value of the BillingRecord entity. -// If the BillingRecord object wasn't provided to the builder, the object is fetched from the database. +// OldTotal returns the old "total" field's value of the BillingQuota entity. +// If the BillingQuota 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 *BillingRecordMutation) OldModel(ctx context.Context) (v string, err error) { +func (m *BillingQuotaMutation) OldTotal(ctx context.Context) (v int64, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldModel is only allowed on UpdateOne operations") + return v, errors.New("OldTotal is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldModel requires an ID field in the mutation") + return v, errors.New("OldTotal requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldModel: %w", err) + return v, fmt.Errorf("querying old value for OldTotal: %w", err) } - return oldValue.Model, nil -} - -// ResetModel resets all changes to the "model" field. -func (m *BillingRecordMutation) ResetModel() { - m.model = nil + return oldValue.Total, nil } -// SetOperation sets the "operation" field. -func (m *BillingRecordMutation) SetOperation(s string) { - m.operation = &s +// AddTotal adds i to the "total" field. +func (m *BillingQuotaMutation) AddTotal(i int64) { + if m.addtotal != nil { + *m.addtotal += i + } else { + m.addtotal = &i + } } -// Operation returns the value of the "operation" field in the mutation. -func (m *BillingRecordMutation) Operation() (r string, exists bool) { - v := m.operation +// AddedTotal returns the value that was added to the "total" field in this mutation. +func (m *BillingQuotaMutation) AddedTotal() (r int64, exists bool) { + v := m.addtotal if v == nil { return } return *v, true } -// OldOperation returns the old "operation" field's value of the BillingRecord entity. -// If the BillingRecord 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 *BillingRecordMutation) OldOperation(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldOperation is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldOperation requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldOperation: %w", err) - } - return oldValue.Operation, nil -} - -// ResetOperation resets all changes to the "operation" field. -func (m *BillingRecordMutation) ResetOperation() { - m.operation = nil +// ResetTotal resets all changes to the "total" field. +func (m *BillingQuotaMutation) ResetTotal() { + m.total = nil + m.addtotal = nil } -// SetInputTokens sets the "input_tokens" field. -func (m *BillingRecordMutation) SetInputTokens(i int64) { - m.input_tokens = &i - m.addinput_tokens = nil +// SetUsed sets the "used" field. +func (m *BillingQuotaMutation) SetUsed(i int64) { + m.used = &i + m.addused = nil } -// InputTokens returns the value of the "input_tokens" field in the mutation. -func (m *BillingRecordMutation) InputTokens() (r int64, exists bool) { - v := m.input_tokens +// Used returns the value of the "used" field in the mutation. +func (m *BillingQuotaMutation) Used() (r int64, exists bool) { + v := m.used if v == nil { return } return *v, true } -// OldInputTokens returns the old "input_tokens" field's value of the BillingRecord entity. -// If the BillingRecord object wasn't provided to the builder, the object is fetched from the database. +// OldUsed returns the old "used" field's value of the BillingQuota entity. +// If the BillingQuota 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 *BillingRecordMutation) OldInputTokens(ctx context.Context) (v int64, err error) { +func (m *BillingQuotaMutation) OldUsed(ctx context.Context) (v int64, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldInputTokens is only allowed on UpdateOne operations") + return v, errors.New("OldUsed is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldInputTokens requires an ID field in the mutation") + return v, errors.New("OldUsed requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldInputTokens: %w", err) + return v, fmt.Errorf("querying old value for OldUsed: %w", err) } - return oldValue.InputTokens, nil + return oldValue.Used, nil } -// AddInputTokens adds i to the "input_tokens" field. -func (m *BillingRecordMutation) AddInputTokens(i int64) { - if m.addinput_tokens != nil { - *m.addinput_tokens += i +// AddUsed adds i to the "used" field. +func (m *BillingQuotaMutation) AddUsed(i int64) { + if m.addused != nil { + *m.addused += i } else { - m.addinput_tokens = &i + m.addused = &i } } -// AddedInputTokens returns the value that was added to the "input_tokens" field in this mutation. -func (m *BillingRecordMutation) AddedInputTokens() (r int64, exists bool) { - v := m.addinput_tokens +// AddedUsed returns the value that was added to the "used" field in this mutation. +func (m *BillingQuotaMutation) AddedUsed() (r int64, exists bool) { + v := m.addused if v == nil { return } return *v, true } -// ResetInputTokens resets all changes to the "input_tokens" field. -func (m *BillingRecordMutation) ResetInputTokens() { - m.input_tokens = nil - m.addinput_tokens = nil +// ResetUsed resets all changes to the "used" field. +func (m *BillingQuotaMutation) ResetUsed() { + m.used = nil + m.addused = nil } -// SetOutputTokens sets the "output_tokens" field. -func (m *BillingRecordMutation) SetOutputTokens(i int64) { - m.output_tokens = &i - m.addoutput_tokens = nil +// SetRemain sets the "remain" field. +func (m *BillingQuotaMutation) SetRemain(i int64) { + m.remain = &i + m.addremain = nil } -// OutputTokens returns the value of the "output_tokens" field in the mutation. -func (m *BillingRecordMutation) OutputTokens() (r int64, exists bool) { - v := m.output_tokens +// Remain returns the value of the "remain" field in the mutation. +func (m *BillingQuotaMutation) Remain() (r int64, exists bool) { + v := m.remain if v == nil { return } return *v, true } -// OldOutputTokens returns the old "output_tokens" field's value of the BillingRecord entity. -// If the BillingRecord object wasn't provided to the builder, the object is fetched from the database. +// OldRemain returns the old "remain" field's value of the BillingQuota entity. +// If the BillingQuota 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 *BillingRecordMutation) OldOutputTokens(ctx context.Context) (v int64, err error) { +func (m *BillingQuotaMutation) OldRemain(ctx context.Context) (v int64, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldOutputTokens is only allowed on UpdateOne operations") + return v, errors.New("OldRemain is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldOutputTokens requires an ID field in the mutation") + return v, errors.New("OldRemain requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldOutputTokens: %w", err) + return v, fmt.Errorf("querying old value for OldRemain: %w", err) } - return oldValue.OutputTokens, nil + return oldValue.Remain, nil } -// AddOutputTokens adds i to the "output_tokens" field. -func (m *BillingRecordMutation) AddOutputTokens(i int64) { - if m.addoutput_tokens != nil { - *m.addoutput_tokens += i - } else { - m.addoutput_tokens = &i - } -} - -// AddedOutputTokens returns the value that was added to the "output_tokens" field in this mutation. -func (m *BillingRecordMutation) AddedOutputTokens() (r int64, exists bool) { - v := m.addoutput_tokens - if v == nil { - return - } - return *v, true -} - -// ResetOutputTokens resets all changes to the "output_tokens" field. -func (m *BillingRecordMutation) ResetOutputTokens() { - m.output_tokens = nil - m.addoutput_tokens = nil -} - -// SetCost sets the "cost" field. -func (m *BillingRecordMutation) SetCost(i int64) { - m.cost = &i - m.addcost = nil -} - -// Cost returns the value of the "cost" field in the mutation. -func (m *BillingRecordMutation) Cost() (r int64, exists bool) { - v := m.cost - if v == nil { - return - } - return *v, true -} - -// OldCost returns the old "cost" field's value of the BillingRecord entity. -// If the BillingRecord 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 *BillingRecordMutation) OldCost(ctx context.Context) (v int64, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCost is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCost requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldCost: %w", err) - } - return oldValue.Cost, nil -} - -// AddCost adds i to the "cost" field. -func (m *BillingRecordMutation) AddCost(i int64) { - if m.addcost != nil { - *m.addcost += i +// AddRemain adds i to the "remain" field. +func (m *BillingQuotaMutation) AddRemain(i int64) { + if m.addremain != nil { + *m.addremain += i } else { - m.addcost = &i - } -} - -// AddedCost returns the value that was added to the "cost" field in this mutation. -func (m *BillingRecordMutation) AddedCost() (r int64, exists bool) { - v := m.addcost - if v == nil { - return - } - return *v, true -} - -// ResetCost resets all changes to the "cost" field. -func (m *BillingRecordMutation) ResetCost() { - m.cost = nil - m.addcost = nil -} - -// SetRequestTime sets the "request_time" field. -func (m *BillingRecordMutation) SetRequestTime(t time.Time) { - m.request_time = &t -} - -// RequestTime returns the value of the "request_time" field in the mutation. -func (m *BillingRecordMutation) RequestTime() (r time.Time, exists bool) { - v := m.request_time - if v == nil { - return - } - return *v, true -} - -// OldRequestTime returns the old "request_time" field's value of the BillingRecord entity. -// If the BillingRecord 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 *BillingRecordMutation) OldRequestTime(ctx context.Context) (v time.Time, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldRequestTime is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldRequestTime requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldRequestTime: %w", err) + m.addremain = &i } - return oldValue.RequestTime, nil -} - -// ResetRequestTime resets all changes to the "request_time" field. -func (m *BillingRecordMutation) ResetRequestTime() { - m.request_time = nil -} - -// SetMetadata sets the "metadata" field. -func (m *BillingRecordMutation) SetMetadata(value map[string]interface{}) { - m.metadata = &value } -// Metadata returns the value of the "metadata" field in the mutation. -func (m *BillingRecordMutation) Metadata() (r map[string]interface{}, exists bool) { - v := m.metadata +// AddedRemain returns the value that was added to the "remain" field in this mutation. +func (m *BillingQuotaMutation) AddedRemain() (r int64, exists bool) { + v := m.addremain if v == nil { return } return *v, true } -// OldMetadata returns the old "metadata" field's value of the BillingRecord entity. -// If the BillingRecord 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 *BillingRecordMutation) OldMetadata(ctx context.Context) (v map[string]interface{}, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldMetadata is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldMetadata requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldMetadata: %w", err) - } - return oldValue.Metadata, nil -} - -// ResetMetadata resets all changes to the "metadata" field. -func (m *BillingRecordMutation) ResetMetadata() { - m.metadata = nil +// ResetRemain resets all changes to the "remain" field. +func (m *BillingQuotaMutation) ResetRemain() { + m.remain = nil + m.addremain = nil } // SetCreatedAt sets the "created_at" field. -func (m *BillingRecordMutation) SetCreatedAt(t time.Time) { +func (m *BillingQuotaMutation) SetCreatedAt(t time.Time) { m.created_at = &t } // CreatedAt returns the value of the "created_at" field in the mutation. -func (m *BillingRecordMutation) CreatedAt() (r time.Time, exists bool) { +func (m *BillingQuotaMutation) CreatedAt() (r time.Time, exists bool) { v := m.created_at if v == nil { return @@ -4343,10 +4342,10 @@ func (m *BillingRecordMutation) CreatedAt() (r time.Time, exists bool) { return *v, true } -// OldCreatedAt returns the old "created_at" field's value of the BillingRecord entity. -// If the BillingRecord object wasn't provided to the builder, the object is fetched from the database. +// OldCreatedAt returns the old "created_at" field's value of the BillingQuota entity. +// If the BillingQuota 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 *BillingRecordMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { +func (m *BillingQuotaMutation) 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") } @@ -4361,17 +4360,17 @@ func (m *BillingRecordMutation) OldCreatedAt(ctx context.Context) (v time.Time, } // ResetCreatedAt resets all changes to the "created_at" field. -func (m *BillingRecordMutation) ResetCreatedAt() { +func (m *BillingQuotaMutation) ResetCreatedAt() { m.created_at = nil } // SetUpdatedAt sets the "updated_at" field. -func (m *BillingRecordMutation) SetUpdatedAt(t time.Time) { +func (m *BillingQuotaMutation) SetUpdatedAt(t time.Time) { m.updated_at = &t } // UpdatedAt returns the value of the "updated_at" field in the mutation. -func (m *BillingRecordMutation) UpdatedAt() (r time.Time, exists bool) { +func (m *BillingQuotaMutation) UpdatedAt() (r time.Time, exists bool) { v := m.updated_at if v == nil { return @@ -4379,10 +4378,10 @@ func (m *BillingRecordMutation) UpdatedAt() (r time.Time, exists bool) { return *v, true } -// OldUpdatedAt returns the old "updated_at" field's value of the BillingRecord entity. -// If the BillingRecord object wasn't provided to the builder, the object is fetched from the database. +// OldUpdatedAt returns the old "updated_at" field's value of the BillingQuota entity. +// If the BillingQuota 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 *BillingRecordMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { +func (m *BillingQuotaMutation) 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") } @@ -4397,19 +4396,19 @@ func (m *BillingRecordMutation) OldUpdatedAt(ctx context.Context) (v time.Time, } // ResetUpdatedAt resets all changes to the "updated_at" field. -func (m *BillingRecordMutation) ResetUpdatedAt() { +func (m *BillingQuotaMutation) ResetUpdatedAt() { m.updated_at = nil } -// Where appends a list predicates to the BillingRecordMutation builder. -func (m *BillingRecordMutation) Where(ps ...predicate.BillingRecord) { +// Where appends a list predicates to the BillingQuotaMutation builder. +func (m *BillingQuotaMutation) Where(ps ...predicate.BillingQuota) { m.predicates = append(m.predicates, ps...) } -// WhereP appends storage-level predicates to the BillingRecordMutation builder. Using this method, +// WhereP appends storage-level predicates to the BillingQuotaMutation builder. Using this method, // users can use type-assertion to append predicates that do not depend on any generated package. -func (m *BillingRecordMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.BillingRecord, len(ps)) +func (m *BillingQuotaMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.BillingQuota, len(ps)) for i := range ps { p[i] = ps[i] } @@ -4417,57 +4416,45 @@ func (m *BillingRecordMutation) WhereP(ps ...func(*sql.Selector)) { } // Op returns the operation name. -func (m *BillingRecordMutation) Op() Op { +func (m *BillingQuotaMutation) Op() Op { return m.op } // SetOp allows setting the mutation operation. -func (m *BillingRecordMutation) SetOp(op Op) { +func (m *BillingQuotaMutation) SetOp(op Op) { m.op = op } -// Type returns the node type of this mutation (BillingRecord). -func (m *BillingRecordMutation) Type() string { +// Type returns the node type of this mutation (BillingQuota). +func (m *BillingQuotaMutation) 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 *BillingRecordMutation) Fields() []string { - fields := make([]string, 0, 11) - if m.tenant_id != nil { - fields = append(fields, billingrecord.FieldTenantID) +func (m *BillingQuotaMutation) Fields() []string { + fields := make([]string, 0, 7) + if m.deleted_at != nil { + fields = append(fields, billingquota.FieldDeletedAt) } if m.user_id != nil { - fields = append(fields, billingrecord.FieldUserID) - } - if m.model != nil { - fields = append(fields, billingrecord.FieldModel) - } - if m.operation != nil { - fields = append(fields, billingrecord.FieldOperation) - } - if m.input_tokens != nil { - fields = append(fields, billingrecord.FieldInputTokens) - } - if m.output_tokens != nil { - fields = append(fields, billingrecord.FieldOutputTokens) + fields = append(fields, billingquota.FieldUserID) } - if m.cost != nil { - fields = append(fields, billingrecord.FieldCost) + if m.total != nil { + fields = append(fields, billingquota.FieldTotal) } - if m.request_time != nil { - fields = append(fields, billingrecord.FieldRequestTime) + if m.used != nil { + fields = append(fields, billingquota.FieldUsed) } - if m.metadata != nil { - fields = append(fields, billingrecord.FieldMetadata) + if m.remain != nil { + fields = append(fields, billingquota.FieldRemain) } if m.created_at != nil { - fields = append(fields, billingrecord.FieldCreatedAt) + fields = append(fields, billingquota.FieldCreatedAt) } if m.updated_at != nil { - fields = append(fields, billingrecord.FieldUpdatedAt) + fields = append(fields, billingquota.FieldUpdatedAt) } return fields } @@ -4475,141 +4462,97 @@ func (m *BillingRecordMutation) Fields() []string { // 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 *BillingRecordMutation) Field(name string) (ent.Value, bool) { +func (m *BillingQuotaMutation) Field(name string) (ent.Value, bool) { switch name { - case billingrecord.FieldTenantID: - return m.TenantID() - case billingrecord.FieldUserID: + case billingquota.FieldDeletedAt: + return m.DeletedAt() + case billingquota.FieldUserID: return m.UserID() - case billingrecord.FieldModel: - return m.Model() - case billingrecord.FieldOperation: - return m.Operation() - case billingrecord.FieldInputTokens: - return m.InputTokens() - case billingrecord.FieldOutputTokens: - return m.OutputTokens() - case billingrecord.FieldCost: - return m.Cost() - case billingrecord.FieldRequestTime: - return m.RequestTime() - case billingrecord.FieldMetadata: - return m.Metadata() - case billingrecord.FieldCreatedAt: - return m.CreatedAt() - case billingrecord.FieldUpdatedAt: - return m.UpdatedAt() - } + case billingquota.FieldTotal: + return m.Total() + case billingquota.FieldUsed: + return m.Used() + case billingquota.FieldRemain: + return m.Remain() + case billingquota.FieldCreatedAt: + return m.CreatedAt() + case billingquota.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 *BillingRecordMutation) OldField(ctx context.Context, name string) (ent.Value, error) { +func (m *BillingQuotaMutation) OldField(ctx context.Context, name string) (ent.Value, error) { switch name { - case billingrecord.FieldTenantID: - return m.OldTenantID(ctx) - case billingrecord.FieldUserID: + case billingquota.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case billingquota.FieldUserID: return m.OldUserID(ctx) - case billingrecord.FieldModel: - return m.OldModel(ctx) - case billingrecord.FieldOperation: - return m.OldOperation(ctx) - case billingrecord.FieldInputTokens: - return m.OldInputTokens(ctx) - case billingrecord.FieldOutputTokens: - return m.OldOutputTokens(ctx) - case billingrecord.FieldCost: - return m.OldCost(ctx) - case billingrecord.FieldRequestTime: - return m.OldRequestTime(ctx) - case billingrecord.FieldMetadata: - return m.OldMetadata(ctx) - case billingrecord.FieldCreatedAt: + case billingquota.FieldTotal: + return m.OldTotal(ctx) + case billingquota.FieldUsed: + return m.OldUsed(ctx) + case billingquota.FieldRemain: + return m.OldRemain(ctx) + case billingquota.FieldCreatedAt: return m.OldCreatedAt(ctx) - case billingrecord.FieldUpdatedAt: + case billingquota.FieldUpdatedAt: return m.OldUpdatedAt(ctx) } - return nil, fmt.Errorf("unknown BillingRecord field %s", name) + return nil, fmt.Errorf("unknown BillingQuota 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 *BillingRecordMutation) SetField(name string, value ent.Value) error { +func (m *BillingQuotaMutation) SetField(name string, value ent.Value) error { switch name { - case billingrecord.FieldTenantID: - v, ok := value.(string) + case billingquota.FieldDeletedAt: + v, ok := value.(time.Time) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetTenantID(v) + m.SetDeletedAt(v) return nil - case billingrecord.FieldUserID: + case billingquota.FieldUserID: v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } m.SetUserID(v) return nil - case billingrecord.FieldModel: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetModel(v) - return nil - case billingrecord.FieldOperation: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetOperation(v) - return nil - case billingrecord.FieldInputTokens: + case billingquota.FieldTotal: v, ok := value.(int64) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetInputTokens(v) + m.SetTotal(v) return nil - case billingrecord.FieldOutputTokens: + case billingquota.FieldUsed: v, ok := value.(int64) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetOutputTokens(v) + m.SetUsed(v) return nil - case billingrecord.FieldCost: + case billingquota.FieldRemain: v, ok := value.(int64) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetCost(v) - return nil - case billingrecord.FieldRequestTime: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetRequestTime(v) - return nil - case billingrecord.FieldMetadata: - v, ok := value.(map[string]interface{}) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetMetadata(v) + m.SetRemain(v) return nil - case billingrecord.FieldCreatedAt: + case billingquota.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 billingrecord.FieldUpdatedAt: + case billingquota.FieldUpdatedAt: v, ok := value.(time.Time) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) @@ -4617,21 +4560,21 @@ func (m *BillingRecordMutation) SetField(name string, value ent.Value) error { m.SetUpdatedAt(v) return nil } - return fmt.Errorf("unknown BillingRecord field %s", name) + return fmt.Errorf("unknown BillingQuota field %s", name) } // AddedFields returns all numeric fields that were incremented/decremented during // this mutation. -func (m *BillingRecordMutation) AddedFields() []string { +func (m *BillingQuotaMutation) AddedFields() []string { var fields []string - if m.addinput_tokens != nil { - fields = append(fields, billingrecord.FieldInputTokens) + if m.addtotal != nil { + fields = append(fields, billingquota.FieldTotal) } - if m.addoutput_tokens != nil { - fields = append(fields, billingrecord.FieldOutputTokens) + if m.addused != nil { + fields = append(fields, billingquota.FieldUsed) } - if m.addcost != nil { - fields = append(fields, billingrecord.FieldCost) + if m.addremain != nil { + fields = append(fields, billingquota.FieldRemain) } return fields } @@ -4639,14 +4582,14 @@ func (m *BillingRecordMutation) AddedFields() []string { // 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 *BillingRecordMutation) AddedField(name string) (ent.Value, bool) { +func (m *BillingQuotaMutation) AddedField(name string) (ent.Value, bool) { switch name { - case billingrecord.FieldInputTokens: - return m.AddedInputTokens() - case billingrecord.FieldOutputTokens: - return m.AddedOutputTokens() - case billingrecord.FieldCost: - return m.AddedCost() + case billingquota.FieldTotal: + return m.AddedTotal() + case billingquota.FieldUsed: + return m.AddedUsed() + case billingquota.FieldRemain: + return m.AddedRemain() } return nil, false } @@ -4654,194 +4597,197 @@ func (m *BillingRecordMutation) AddedField(name string) (ent.Value, bool) { // 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 *BillingRecordMutation) AddField(name string, value ent.Value) error { +func (m *BillingQuotaMutation) AddField(name string, value ent.Value) error { switch name { - case billingrecord.FieldInputTokens: + case billingquota.FieldTotal: v, ok := value.(int64) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.AddInputTokens(v) + m.AddTotal(v) return nil - case billingrecord.FieldOutputTokens: + case billingquota.FieldUsed: v, ok := value.(int64) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.AddOutputTokens(v) + m.AddUsed(v) return nil - case billingrecord.FieldCost: + case billingquota.FieldRemain: v, ok := value.(int64) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.AddCost(v) + m.AddRemain(v) return nil } - return fmt.Errorf("unknown BillingRecord numeric field %s", name) + return fmt.Errorf("unknown BillingQuota numeric field %s", name) } // ClearedFields returns all nullable fields that were cleared during this // mutation. -func (m *BillingRecordMutation) ClearedFields() []string { - return nil +func (m *BillingQuotaMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(billingquota.FieldDeletedAt) { + fields = append(fields, billingquota.FieldDeletedAt) + } + return fields } // FieldCleared returns a boolean indicating if a field with the given name was // cleared in this mutation. -func (m *BillingRecordMutation) FieldCleared(name string) bool { +func (m *BillingQuotaMutation) 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 *BillingRecordMutation) ClearField(name string) error { - return fmt.Errorf("unknown BillingRecord nullable field %s", name) +func (m *BillingQuotaMutation) ClearField(name string) error { + switch name { + case billingquota.FieldDeletedAt: + m.ClearDeletedAt() + return nil + } + return fmt.Errorf("unknown BillingQuota 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 *BillingRecordMutation) ResetField(name string) error { +func (m *BillingQuotaMutation) ResetField(name string) error { switch name { - case billingrecord.FieldTenantID: - m.ResetTenantID() + case billingquota.FieldDeletedAt: + m.ResetDeletedAt() return nil - case billingrecord.FieldUserID: + case billingquota.FieldUserID: m.ResetUserID() return nil - case billingrecord.FieldModel: - m.ResetModel() - return nil - case billingrecord.FieldOperation: - m.ResetOperation() - return nil - case billingrecord.FieldInputTokens: - m.ResetInputTokens() - return nil - case billingrecord.FieldOutputTokens: - m.ResetOutputTokens() - return nil - case billingrecord.FieldCost: - m.ResetCost() + case billingquota.FieldTotal: + m.ResetTotal() return nil - case billingrecord.FieldRequestTime: - m.ResetRequestTime() + case billingquota.FieldUsed: + m.ResetUsed() return nil - case billingrecord.FieldMetadata: - m.ResetMetadata() + case billingquota.FieldRemain: + m.ResetRemain() return nil - case billingrecord.FieldCreatedAt: + case billingquota.FieldCreatedAt: m.ResetCreatedAt() return nil - case billingrecord.FieldUpdatedAt: + case billingquota.FieldUpdatedAt: m.ResetUpdatedAt() return nil } - return fmt.Errorf("unknown BillingRecord field %s", name) + return fmt.Errorf("unknown BillingQuota field %s", name) } // AddedEdges returns all edge names that were set/added in this mutation. -func (m *BillingRecordMutation) AddedEdges() []string { +func (m *BillingQuotaMutation) 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 *BillingRecordMutation) AddedIDs(name string) []ent.Value { +func (m *BillingQuotaMutation) AddedIDs(name string) []ent.Value { return nil } // RemovedEdges returns all edge names that were removed in this mutation. -func (m *BillingRecordMutation) RemovedEdges() []string { +func (m *BillingQuotaMutation) 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 *BillingRecordMutation) RemovedIDs(name string) []ent.Value { +func (m *BillingQuotaMutation) RemovedIDs(name string) []ent.Value { return nil } // ClearedEdges returns all edge names that were cleared in this mutation. -func (m *BillingRecordMutation) ClearedEdges() []string { +func (m *BillingQuotaMutation) 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 *BillingRecordMutation) EdgeCleared(name string) bool { +func (m *BillingQuotaMutation) 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 *BillingRecordMutation) ClearEdge(name string) error { - return fmt.Errorf("unknown BillingRecord unique edge %s", name) +func (m *BillingQuotaMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown BillingQuota 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 *BillingRecordMutation) ResetEdge(name string) error { - return fmt.Errorf("unknown BillingRecord edge %s", name) +func (m *BillingQuotaMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown BillingQuota edge %s", name) } -// BillingUsageMutation represents an operation that mutates the BillingUsage nodes in the graph. -type BillingUsageMutation struct { +// BillingRecordMutation represents an operation that mutates the BillingRecord nodes in the graph. +type BillingRecordMutation struct { config - op Op - typ string - id *string - deleted_at *time.Time - user_id *string - model_name *string - tokens *int64 - addtokens *int64 - operation *string - created_at *time.Time - updated_at *time.Time - clearedFields map[string]struct{} - done bool - oldValue func(context.Context) (*BillingUsage, error) - predicates []predicate.BillingUsage -} - -var _ ent.Mutation = (*BillingUsageMutation)(nil) - -// billingusageOption allows management of the mutation configuration using functional options. -type billingusageOption func(*BillingUsageMutation) - -// newBillingUsageMutation creates new mutation for the BillingUsage entity. -func newBillingUsageMutation(c config, op Op, opts ...billingusageOption) *BillingUsageMutation { - m := &BillingUsageMutation{ - config: c, - op: op, - typ: TypeBillingUsage, - clearedFields: make(map[string]struct{}), - } + op Op + typ string + id *string + tenant_id *string + user_id *string + model *string + operation *string + input_tokens *int64 + addinput_tokens *int64 + output_tokens *int64 + addoutput_tokens *int64 + cost *int64 + addcost *int64 + request_time *time.Time + metadata *map[string]interface{} + created_at *time.Time + updated_at *time.Time + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*BillingRecord, error) + predicates []predicate.BillingRecord +} + +var _ ent.Mutation = (*BillingRecordMutation)(nil) + +// billingrecordOption allows management of the mutation configuration using functional options. +type billingrecordOption func(*BillingRecordMutation) + +// newBillingRecordMutation creates new mutation for the BillingRecord entity. +func newBillingRecordMutation(c config, op Op, opts ...billingrecordOption) *BillingRecordMutation { + m := &BillingRecordMutation{ + config: c, + op: op, + typ: TypeBillingRecord, + clearedFields: make(map[string]struct{}), + } for _, opt := range opts { opt(m) } return m } -// withBillingUsageID sets the ID field of the mutation. -func withBillingUsageID(id string) billingusageOption { - return func(m *BillingUsageMutation) { +// withBillingRecordID sets the ID field of the mutation. +func withBillingRecordID(id string) billingrecordOption { + return func(m *BillingRecordMutation) { var ( err error once sync.Once - value *BillingUsage + value *BillingRecord ) - m.oldValue = func(ctx context.Context) (*BillingUsage, error) { + m.oldValue = func(ctx context.Context) (*BillingRecord, error) { once.Do(func() { if m.done { err = errors.New("querying old values post mutation is not allowed") } else { - value, err = m.Client().BillingUsage.Get(ctx, id) + value, err = m.Client().BillingRecord.Get(ctx, id) } }) return value, err @@ -4850,10 +4796,10 @@ func withBillingUsageID(id string) billingusageOption { } } -// withBillingUsage sets the old BillingUsage of the mutation. -func withBillingUsage(node *BillingUsage) billingusageOption { - return func(m *BillingUsageMutation) { - m.oldValue = func(context.Context) (*BillingUsage, error) { +// withBillingRecord sets the old BillingRecord of the mutation. +func withBillingRecord(node *BillingRecord) billingrecordOption { + return func(m *BillingRecordMutation) { + m.oldValue = func(context.Context) (*BillingRecord, error) { return node, nil } m.id = &node.ID @@ -4862,7 +4808,7 @@ func withBillingUsage(node *BillingUsage) billingusageOption { // 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 BillingUsageMutation) Client() *Client { +func (m BillingRecordMutation) Client() *Client { client := &Client{config: m.config} client.init() return client @@ -4870,7 +4816,7 @@ func (m BillingUsageMutation) Client() *Client { // Tx returns an `ent.Tx` for mutations that were executed in transactions; // it returns an error otherwise. -func (m BillingUsageMutation) Tx() (*Tx, error) { +func (m BillingRecordMutation) Tx() (*Tx, error) { if _, ok := m.driver.(*txDriver); !ok { return nil, errors.New("db: mutation is not running in a transaction") } @@ -4880,14 +4826,14 @@ func (m BillingUsageMutation) Tx() (*Tx, error) { } // SetID sets the value of the id field. Note that this -// operation is only accepted on creation of BillingUsage entities. -func (m *BillingUsageMutation) SetID(id string) { +// operation is only accepted on creation of BillingRecord entities. +func (m *BillingRecordMutation) SetID(id string) { 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 *BillingUsageMutation) ID() (id string, exists bool) { +func (m *BillingRecordMutation) ID() (id string, exists bool) { if m.id == nil { return } @@ -4898,7 +4844,7 @@ func (m *BillingUsageMutation) ID() (id string, exists bool) { // 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 *BillingUsageMutation) IDs(ctx context.Context) ([]string, error) { +func (m *BillingRecordMutation) IDs(ctx context.Context) ([]string, error) { switch { case m.op.Is(OpUpdateOne | OpDeleteOne): id, exists := m.ID() @@ -4907,68 +4853,55 @@ func (m *BillingUsageMutation) IDs(ctx context.Context) ([]string, error) { } fallthrough case m.op.Is(OpUpdate | OpDelete): - return m.Client().BillingUsage.Query().Where(m.predicates...).IDs(ctx) + return m.Client().BillingRecord.Query().Where(m.predicates...).IDs(ctx) default: return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) } } -// SetDeletedAt sets the "deleted_at" field. -func (m *BillingUsageMutation) SetDeletedAt(t time.Time) { - m.deleted_at = &t +// SetTenantID sets the "tenant_id" field. +func (m *BillingRecordMutation) SetTenantID(s string) { + m.tenant_id = &s } -// DeletedAt returns the value of the "deleted_at" field in the mutation. -func (m *BillingUsageMutation) DeletedAt() (r time.Time, exists bool) { - v := m.deleted_at +// TenantID returns the value of the "tenant_id" field in the mutation. +func (m *BillingRecordMutation) TenantID() (r string, exists bool) { + v := m.tenant_id if v == nil { return } return *v, true } -// OldDeletedAt returns the old "deleted_at" field's value of the BillingUsage entity. -// If the BillingUsage object wasn't provided to the builder, the object is fetched from the database. +// OldTenantID returns the old "tenant_id" field's value of the BillingRecord entity. +// If the BillingRecord 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 *BillingUsageMutation) OldDeletedAt(ctx context.Context) (v time.Time, err error) { +func (m *BillingRecordMutation) OldTenantID(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldDeletedAt is only allowed on UpdateOne operations") + return v, errors.New("OldTenantID is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldDeletedAt requires an ID field in the mutation") + return v, errors.New("OldTenantID requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldDeletedAt: %w", err) + return v, fmt.Errorf("querying old value for OldTenantID: %w", err) } - return oldValue.DeletedAt, nil -} - -// ClearDeletedAt clears the value of the "deleted_at" field. -func (m *BillingUsageMutation) ClearDeletedAt() { - m.deleted_at = nil - m.clearedFields[billingusage.FieldDeletedAt] = struct{}{} -} - -// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. -func (m *BillingUsageMutation) DeletedAtCleared() bool { - _, ok := m.clearedFields[billingusage.FieldDeletedAt] - return ok + return oldValue.TenantID, nil } -// ResetDeletedAt resets all changes to the "deleted_at" field. -func (m *BillingUsageMutation) ResetDeletedAt() { - m.deleted_at = nil - delete(m.clearedFields, billingusage.FieldDeletedAt) +// ResetTenantID resets all changes to the "tenant_id" field. +func (m *BillingRecordMutation) ResetTenantID() { + m.tenant_id = nil } // SetUserID sets the "user_id" field. -func (m *BillingUsageMutation) SetUserID(s string) { +func (m *BillingRecordMutation) SetUserID(s string) { m.user_id = &s } // UserID returns the value of the "user_id" field in the mutation. -func (m *BillingUsageMutation) UserID() (r string, exists bool) { +func (m *BillingRecordMutation) UserID() (r string, exists bool) { v := m.user_id if v == nil { return @@ -4976,10 +4909,10 @@ func (m *BillingUsageMutation) UserID() (r string, exists bool) { return *v, true } -// OldUserID returns the old "user_id" field's value of the BillingUsage entity. -// If the BillingUsage object wasn't provided to the builder, the object is fetched from the database. +// OldUserID returns the old "user_id" field's value of the BillingRecord entity. +// If the BillingRecord 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 *BillingUsageMutation) OldUserID(ctx context.Context) (v string, err error) { +func (m *BillingRecordMutation) OldUserID(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { return v, errors.New("OldUserID is only allowed on UpdateOne operations") } @@ -4994,109 +4927,53 @@ func (m *BillingUsageMutation) OldUserID(ctx context.Context) (v string, err err } // ResetUserID resets all changes to the "user_id" field. -func (m *BillingUsageMutation) ResetUserID() { +func (m *BillingRecordMutation) ResetUserID() { m.user_id = nil } -// SetModelName sets the "model_name" field. -func (m *BillingUsageMutation) SetModelName(s string) { - m.model_name = &s -} - -// ModelName returns the value of the "model_name" field in the mutation. -func (m *BillingUsageMutation) ModelName() (r string, exists bool) { - v := m.model_name - if v == nil { - return - } - return *v, true -} - -// OldModelName returns the old "model_name" field's value of the BillingUsage entity. -// If the BillingUsage 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 *BillingUsageMutation) OldModelName(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldModelName is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldModelName requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldModelName: %w", err) - } - return oldValue.ModelName, nil -} - -// ResetModelName resets all changes to the "model_name" field. -func (m *BillingUsageMutation) ResetModelName() { - m.model_name = nil -} - -// SetTokens sets the "tokens" field. -func (m *BillingUsageMutation) SetTokens(i int64) { - m.tokens = &i - m.addtokens = nil +// SetModel sets the "model" field. +func (m *BillingRecordMutation) SetModel(s string) { + m.model = &s } -// Tokens returns the value of the "tokens" field in the mutation. -func (m *BillingUsageMutation) Tokens() (r int64, exists bool) { - v := m.tokens +// Model returns the value of the "model" field in the mutation. +func (m *BillingRecordMutation) Model() (r string, exists bool) { + v := m.model if v == nil { return } return *v, true } -// OldTokens returns the old "tokens" field's value of the BillingUsage entity. -// If the BillingUsage object wasn't provided to the builder, the object is fetched from the database. +// OldModel returns the old "model" field's value of the BillingRecord entity. +// If the BillingRecord 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 *BillingUsageMutation) OldTokens(ctx context.Context) (v int64, err error) { +func (m *BillingRecordMutation) OldModel(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldTokens is only allowed on UpdateOne operations") + return v, errors.New("OldModel is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldTokens requires an ID field in the mutation") + return v, errors.New("OldModel requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldTokens: %w", err) - } - return oldValue.Tokens, nil -} - -// AddTokens adds i to the "tokens" field. -func (m *BillingUsageMutation) AddTokens(i int64) { - if m.addtokens != nil { - *m.addtokens += i - } else { - m.addtokens = &i - } -} - -// AddedTokens returns the value that was added to the "tokens" field in this mutation. -func (m *BillingUsageMutation) AddedTokens() (r int64, exists bool) { - v := m.addtokens - if v == nil { - return + return v, fmt.Errorf("querying old value for OldModel: %w", err) } - return *v, true + return oldValue.Model, nil } -// ResetTokens resets all changes to the "tokens" field. -func (m *BillingUsageMutation) ResetTokens() { - m.tokens = nil - m.addtokens = nil +// ResetModel resets all changes to the "model" field. +func (m *BillingRecordMutation) ResetModel() { + m.model = nil } // SetOperation sets the "operation" field. -func (m *BillingUsageMutation) SetOperation(s string) { +func (m *BillingRecordMutation) SetOperation(s string) { m.operation = &s } // Operation returns the value of the "operation" field in the mutation. -func (m *BillingUsageMutation) Operation() (r string, exists bool) { +func (m *BillingRecordMutation) Operation() (r string, exists bool) { v := m.operation if v == nil { return @@ -5104,10 +4981,10 @@ func (m *BillingUsageMutation) Operation() (r string, exists bool) { return *v, true } -// OldOperation returns the old "operation" field's value of the BillingUsage entity. -// If the BillingUsage object wasn't provided to the builder, the object is fetched from the database. +// OldOperation returns the old "operation" field's value of the BillingRecord entity. +// If the BillingRecord 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 *BillingUsageMutation) OldOperation(ctx context.Context) (v string, err error) { +func (m *BillingRecordMutation) OldOperation(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { return v, errors.New("OldOperation is only allowed on UpdateOne operations") } @@ -5122,251 +4999,553 @@ func (m *BillingUsageMutation) OldOperation(ctx context.Context) (v string, err } // ResetOperation resets all changes to the "operation" field. -func (m *BillingUsageMutation) ResetOperation() { +func (m *BillingRecordMutation) ResetOperation() { m.operation = nil } -// SetCreatedAt sets the "created_at" field. -func (m *BillingUsageMutation) SetCreatedAt(t time.Time) { - m.created_at = &t +// SetInputTokens sets the "input_tokens" field. +func (m *BillingRecordMutation) SetInputTokens(i int64) { + m.input_tokens = &i + m.addinput_tokens = nil } -// CreatedAt returns the value of the "created_at" field in the mutation. -func (m *BillingUsageMutation) CreatedAt() (r time.Time, exists bool) { - v := m.created_at +// InputTokens returns the value of the "input_tokens" field in the mutation. +func (m *BillingRecordMutation) InputTokens() (r int64, exists bool) { + v := m.input_tokens if v == nil { return } return *v, true } -// OldCreatedAt returns the old "created_at" field's value of the BillingUsage entity. -// If the BillingUsage object wasn't provided to the builder, the object is fetched from the database. +// OldInputTokens returns the old "input_tokens" field's value of the BillingRecord entity. +// If the BillingRecord 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 *BillingUsageMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { +func (m *BillingRecordMutation) OldInputTokens(ctx context.Context) (v int64, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") + return v, errors.New("OldInputTokens 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") + return v, errors.New("OldInputTokens requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) + return v, fmt.Errorf("querying old value for OldInputTokens: %w", err) } - return oldValue.CreatedAt, nil + return oldValue.InputTokens, nil } -// ResetCreatedAt resets all changes to the "created_at" field. -func (m *BillingUsageMutation) ResetCreatedAt() { - m.created_at = nil +// AddInputTokens adds i to the "input_tokens" field. +func (m *BillingRecordMutation) AddInputTokens(i int64) { + if m.addinput_tokens != nil { + *m.addinput_tokens += i + } else { + m.addinput_tokens = &i + } } -// SetUpdatedAt sets the "updated_at" field. -func (m *BillingUsageMutation) SetUpdatedAt(t time.Time) { - m.updated_at = &t +// AddedInputTokens returns the value that was added to the "input_tokens" field in this mutation. +func (m *BillingRecordMutation) AddedInputTokens() (r int64, exists bool) { + v := m.addinput_tokens + if v == nil { + return + } + return *v, true } -// UpdatedAt returns the value of the "updated_at" field in the mutation. -func (m *BillingUsageMutation) UpdatedAt() (r time.Time, exists bool) { - v := m.updated_at +// ResetInputTokens resets all changes to the "input_tokens" field. +func (m *BillingRecordMutation) ResetInputTokens() { + m.input_tokens = nil + m.addinput_tokens = nil +} + +// SetOutputTokens sets the "output_tokens" field. +func (m *BillingRecordMutation) SetOutputTokens(i int64) { + m.output_tokens = &i + m.addoutput_tokens = nil +} + +// OutputTokens returns the value of the "output_tokens" field in the mutation. +func (m *BillingRecordMutation) OutputTokens() (r int64, exists bool) { + v := m.output_tokens if v == nil { return } return *v, true } -// OldUpdatedAt returns the old "updated_at" field's value of the BillingUsage entity. -// If the BillingUsage object wasn't provided to the builder, the object is fetched from the database. +// OldOutputTokens returns the old "output_tokens" field's value of the BillingRecord entity. +// If the BillingRecord 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 *BillingUsageMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { +func (m *BillingRecordMutation) OldOutputTokens(ctx context.Context) (v int64, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") + return v, errors.New("OldOutputTokens 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") + return v, errors.New("OldOutputTokens requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) + return v, fmt.Errorf("querying old value for OldOutputTokens: %w", err) } - return oldValue.UpdatedAt, nil -} - -// ResetUpdatedAt resets all changes to the "updated_at" field. -func (m *BillingUsageMutation) ResetUpdatedAt() { - m.updated_at = nil + return oldValue.OutputTokens, nil } -// Where appends a list predicates to the BillingUsageMutation builder. -func (m *BillingUsageMutation) Where(ps ...predicate.BillingUsage) { - m.predicates = append(m.predicates, ps...) +// AddOutputTokens adds i to the "output_tokens" field. +func (m *BillingRecordMutation) AddOutputTokens(i int64) { + if m.addoutput_tokens != nil { + *m.addoutput_tokens += i + } else { + m.addoutput_tokens = &i + } } -// WhereP appends storage-level predicates to the BillingUsageMutation builder. Using this method, -// users can use type-assertion to append predicates that do not depend on any generated package. -func (m *BillingUsageMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.BillingUsage, len(ps)) - for i := range ps { - p[i] = ps[i] +// AddedOutputTokens returns the value that was added to the "output_tokens" field in this mutation. +func (m *BillingRecordMutation) AddedOutputTokens() (r int64, exists bool) { + v := m.addoutput_tokens + if v == nil { + return } - m.Where(p...) + return *v, true } -// Op returns the operation name. -func (m *BillingUsageMutation) Op() Op { - return m.op +// ResetOutputTokens resets all changes to the "output_tokens" field. +func (m *BillingRecordMutation) ResetOutputTokens() { + m.output_tokens = nil + m.addoutput_tokens = nil } -// SetOp allows setting the mutation operation. -func (m *BillingUsageMutation) SetOp(op Op) { - m.op = op +// SetCost sets the "cost" field. +func (m *BillingRecordMutation) SetCost(i int64) { + m.cost = &i + m.addcost = nil } -// Type returns the node type of this mutation (BillingUsage). -func (m *BillingUsageMutation) Type() string { - return m.typ +// Cost returns the value of the "cost" field in the mutation. +func (m *BillingRecordMutation) Cost() (r int64, exists bool) { + v := m.cost + if v == nil { + return + } + return *v, true } -// 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 *BillingUsageMutation) Fields() []string { - fields := make([]string, 0, 7) - if m.deleted_at != nil { - fields = append(fields, billingusage.FieldDeletedAt) +// OldCost returns the old "cost" field's value of the BillingRecord entity. +// If the BillingRecord 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 *BillingRecordMutation) OldCost(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCost is only allowed on UpdateOne operations") } - if m.user_id != nil { - fields = append(fields, billingusage.FieldUserID) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCost requires an ID field in the mutation") } - if m.model_name != nil { - fields = append(fields, billingusage.FieldModelName) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCost: %w", err) } - if m.tokens != nil { - fields = append(fields, billingusage.FieldTokens) + return oldValue.Cost, nil +} + +// AddCost adds i to the "cost" field. +func (m *BillingRecordMutation) AddCost(i int64) { + if m.addcost != nil { + *m.addcost += i + } else { + m.addcost = &i } - if m.operation != nil { - fields = append(fields, billingusage.FieldOperation) +} + +// AddedCost returns the value that was added to the "cost" field in this mutation. +func (m *BillingRecordMutation) AddedCost() (r int64, exists bool) { + v := m.addcost + if v == nil { + return } - if m.created_at != nil { - fields = append(fields, billingusage.FieldCreatedAt) + return *v, true +} + +// ResetCost resets all changes to the "cost" field. +func (m *BillingRecordMutation) ResetCost() { + m.cost = nil + m.addcost = nil +} + +// SetRequestTime sets the "request_time" field. +func (m *BillingRecordMutation) SetRequestTime(t time.Time) { + m.request_time = &t +} + +// RequestTime returns the value of the "request_time" field in the mutation. +func (m *BillingRecordMutation) RequestTime() (r time.Time, exists bool) { + v := m.request_time + if v == nil { + return } - if m.updated_at != nil { - fields = append(fields, billingusage.FieldUpdatedAt) + return *v, true +} + +// OldRequestTime returns the old "request_time" field's value of the BillingRecord entity. +// If the BillingRecord 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 *BillingRecordMutation) OldRequestTime(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRequestTime is only allowed on UpdateOne operations") } - return fields + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRequestTime requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRequestTime: %w", err) + } + return oldValue.RequestTime, nil } -// 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 *BillingUsageMutation) Field(name string) (ent.Value, bool) { - switch name { - case billingusage.FieldDeletedAt: - return m.DeletedAt() - case billingusage.FieldUserID: - return m.UserID() - case billingusage.FieldModelName: - return m.ModelName() - case billingusage.FieldTokens: - return m.Tokens() - case billingusage.FieldOperation: - return m.Operation() - case billingusage.FieldCreatedAt: - return m.CreatedAt() - case billingusage.FieldUpdatedAt: - return m.UpdatedAt() +// ResetRequestTime resets all changes to the "request_time" field. +func (m *BillingRecordMutation) ResetRequestTime() { + m.request_time = nil +} + +// SetMetadata sets the "metadata" field. +func (m *BillingRecordMutation) SetMetadata(value map[string]interface{}) { + m.metadata = &value +} + +// Metadata returns the value of the "metadata" field in the mutation. +func (m *BillingRecordMutation) Metadata() (r map[string]interface{}, exists bool) { + v := m.metadata + if v == nil { + return } - return nil, false + return *v, true } -// 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 *BillingUsageMutation) OldField(ctx context.Context, name string) (ent.Value, error) { - switch name { - case billingusage.FieldDeletedAt: - return m.OldDeletedAt(ctx) - case billingusage.FieldUserID: - return m.OldUserID(ctx) - case billingusage.FieldModelName: - return m.OldModelName(ctx) - case billingusage.FieldTokens: - return m.OldTokens(ctx) - case billingusage.FieldOperation: - return m.OldOperation(ctx) - case billingusage.FieldCreatedAt: - return m.OldCreatedAt(ctx) - case billingusage.FieldUpdatedAt: - return m.OldUpdatedAt(ctx) +// OldMetadata returns the old "metadata" field's value of the BillingRecord entity. +// If the BillingRecord 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 *BillingRecordMutation) OldMetadata(ctx context.Context) (v map[string]interface{}, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMetadata is only allowed on UpdateOne operations") } - return nil, fmt.Errorf("unknown BillingUsage field %s", name) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMetadata requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMetadata: %w", err) + } + return oldValue.Metadata, nil } -// SetField sets the value of a field with the given name. It returns an error if +// ResetMetadata resets all changes to the "metadata" field. +func (m *BillingRecordMutation) ResetMetadata() { + m.metadata = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *BillingRecordMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *BillingRecordMutation) 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 BillingRecord entity. +// If the BillingRecord 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 *BillingRecordMutation) 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 *BillingRecordMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *BillingRecordMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *BillingRecordMutation) 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 BillingRecord entity. +// If the BillingRecord 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 *BillingRecordMutation) 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 *BillingRecordMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// Where appends a list predicates to the BillingRecordMutation builder. +func (m *BillingRecordMutation) Where(ps ...predicate.BillingRecord) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the BillingRecordMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *BillingRecordMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.BillingRecord, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *BillingRecordMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *BillingRecordMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (BillingRecord). +func (m *BillingRecordMutation) 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 *BillingRecordMutation) Fields() []string { + fields := make([]string, 0, 11) + if m.tenant_id != nil { + fields = append(fields, billingrecord.FieldTenantID) + } + if m.user_id != nil { + fields = append(fields, billingrecord.FieldUserID) + } + if m.model != nil { + fields = append(fields, billingrecord.FieldModel) + } + if m.operation != nil { + fields = append(fields, billingrecord.FieldOperation) + } + if m.input_tokens != nil { + fields = append(fields, billingrecord.FieldInputTokens) + } + if m.output_tokens != nil { + fields = append(fields, billingrecord.FieldOutputTokens) + } + if m.cost != nil { + fields = append(fields, billingrecord.FieldCost) + } + if m.request_time != nil { + fields = append(fields, billingrecord.FieldRequestTime) + } + if m.metadata != nil { + fields = append(fields, billingrecord.FieldMetadata) + } + if m.created_at != nil { + fields = append(fields, billingrecord.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, billingrecord.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 *BillingRecordMutation) Field(name string) (ent.Value, bool) { + switch name { + case billingrecord.FieldTenantID: + return m.TenantID() + case billingrecord.FieldUserID: + return m.UserID() + case billingrecord.FieldModel: + return m.Model() + case billingrecord.FieldOperation: + return m.Operation() + case billingrecord.FieldInputTokens: + return m.InputTokens() + case billingrecord.FieldOutputTokens: + return m.OutputTokens() + case billingrecord.FieldCost: + return m.Cost() + case billingrecord.FieldRequestTime: + return m.RequestTime() + case billingrecord.FieldMetadata: + return m.Metadata() + case billingrecord.FieldCreatedAt: + return m.CreatedAt() + case billingrecord.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 *BillingRecordMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case billingrecord.FieldTenantID: + return m.OldTenantID(ctx) + case billingrecord.FieldUserID: + return m.OldUserID(ctx) + case billingrecord.FieldModel: + return m.OldModel(ctx) + case billingrecord.FieldOperation: + return m.OldOperation(ctx) + case billingrecord.FieldInputTokens: + return m.OldInputTokens(ctx) + case billingrecord.FieldOutputTokens: + return m.OldOutputTokens(ctx) + case billingrecord.FieldCost: + return m.OldCost(ctx) + case billingrecord.FieldRequestTime: + return m.OldRequestTime(ctx) + case billingrecord.FieldMetadata: + return m.OldMetadata(ctx) + case billingrecord.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case billingrecord.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + } + return nil, fmt.Errorf("unknown BillingRecord 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 *BillingUsageMutation) SetField(name string, value ent.Value) error { +func (m *BillingRecordMutation) SetField(name string, value ent.Value) error { switch name { - case billingusage.FieldDeletedAt: - v, ok := value.(time.Time) + case billingrecord.FieldTenantID: + v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetDeletedAt(v) + m.SetTenantID(v) return nil - case billingusage.FieldUserID: + case billingrecord.FieldUserID: v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } m.SetUserID(v) return nil - case billingusage.FieldModelName: + case billingrecord.FieldModel: v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetModelName(v) + m.SetModel(v) return nil - case billingusage.FieldTokens: + case billingrecord.FieldOperation: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetOperation(v) + return nil + case billingrecord.FieldInputTokens: v, ok := value.(int64) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetTokens(v) + m.SetInputTokens(v) return nil - case billingusage.FieldOperation: - v, ok := value.(string) + case billingrecord.FieldOutputTokens: + v, ok := value.(int64) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetOperation(v) + m.SetOutputTokens(v) return nil - case billingusage.FieldCreatedAt: - v, ok := value.(time.Time) + case billingrecord.FieldCost: + v, ok := value.(int64) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetCreatedAt(v) + m.SetCost(v) return nil - case billingusage.FieldUpdatedAt: + case billingrecord.FieldRequestTime: v, ok := value.(time.Time) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetUpdatedAt(v) + m.SetRequestTime(v) return nil - } - return fmt.Errorf("unknown BillingUsage field %s", name) -} - + case billingrecord.FieldMetadata: + v, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMetadata(v) + return nil + case billingrecord.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 billingrecord.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 BillingRecord field %s", name) +} + // AddedFields returns all numeric fields that were incremented/decremented during // this mutation. -func (m *BillingUsageMutation) AddedFields() []string { +func (m *BillingRecordMutation) AddedFields() []string { var fields []string - if m.addtokens != nil { - fields = append(fields, billingusage.FieldTokens) + if m.addinput_tokens != nil { + fields = append(fields, billingrecord.FieldInputTokens) + } + if m.addoutput_tokens != nil { + fields = append(fields, billingrecord.FieldOutputTokens) + } + if m.addcost != nil { + fields = append(fields, billingrecord.FieldCost) } return fields } @@ -5374,10 +5553,14 @@ func (m *BillingUsageMutation) AddedFields() []string { // 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 *BillingUsageMutation) AddedField(name string) (ent.Value, bool) { +func (m *BillingRecordMutation) AddedField(name string) (ent.Value, bool) { switch name { - case billingusage.FieldTokens: - return m.AddedTokens() + case billingrecord.FieldInputTokens: + return m.AddedInputTokens() + case billingrecord.FieldOutputTokens: + return m.AddedOutputTokens() + case billingrecord.FieldCost: + return m.AddedCost() } return nil, false } @@ -5385,175 +5568,172 @@ func (m *BillingUsageMutation) AddedField(name string) (ent.Value, bool) { // 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 *BillingUsageMutation) AddField(name string, value ent.Value) error { +func (m *BillingRecordMutation) AddField(name string, value ent.Value) error { switch name { - case billingusage.FieldTokens: + case billingrecord.FieldInputTokens: v, ok := value.(int64) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.AddTokens(v) + m.AddInputTokens(v) + return nil + case billingrecord.FieldOutputTokens: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddOutputTokens(v) + return nil + case billingrecord.FieldCost: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddCost(v) return nil } - return fmt.Errorf("unknown BillingUsage numeric field %s", name) + return fmt.Errorf("unknown BillingRecord numeric field %s", name) } // ClearedFields returns all nullable fields that were cleared during this // mutation. -func (m *BillingUsageMutation) ClearedFields() []string { - var fields []string - if m.FieldCleared(billingusage.FieldDeletedAt) { - fields = append(fields, billingusage.FieldDeletedAt) - } - return fields +func (m *BillingRecordMutation) ClearedFields() []string { + return nil } // FieldCleared returns a boolean indicating if a field with the given name was // cleared in this mutation. -func (m *BillingUsageMutation) FieldCleared(name string) bool { +func (m *BillingRecordMutation) 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 *BillingUsageMutation) ClearField(name string) error { - switch name { - case billingusage.FieldDeletedAt: - m.ClearDeletedAt() - return nil - } - return fmt.Errorf("unknown BillingUsage nullable field %s", name) +func (m *BillingRecordMutation) ClearField(name string) error { + return fmt.Errorf("unknown BillingRecord 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 *BillingUsageMutation) ResetField(name string) error { +func (m *BillingRecordMutation) ResetField(name string) error { switch name { - case billingusage.FieldDeletedAt: - m.ResetDeletedAt() + case billingrecord.FieldTenantID: + m.ResetTenantID() return nil - case billingusage.FieldUserID: + case billingrecord.FieldUserID: m.ResetUserID() return nil - case billingusage.FieldModelName: - m.ResetModelName() - return nil - case billingusage.FieldTokens: - m.ResetTokens() + case billingrecord.FieldModel: + m.ResetModel() return nil - case billingusage.FieldOperation: + case billingrecord.FieldOperation: m.ResetOperation() return nil - case billingusage.FieldCreatedAt: + case billingrecord.FieldInputTokens: + m.ResetInputTokens() + return nil + case billingrecord.FieldOutputTokens: + m.ResetOutputTokens() + return nil + case billingrecord.FieldCost: + m.ResetCost() + return nil + case billingrecord.FieldRequestTime: + m.ResetRequestTime() + return nil + case billingrecord.FieldMetadata: + m.ResetMetadata() + return nil + case billingrecord.FieldCreatedAt: m.ResetCreatedAt() return nil - case billingusage.FieldUpdatedAt: + case billingrecord.FieldUpdatedAt: m.ResetUpdatedAt() return nil } - return fmt.Errorf("unknown BillingUsage field %s", name) + return fmt.Errorf("unknown BillingRecord field %s", name) } // AddedEdges returns all edge names that were set/added in this mutation. -func (m *BillingUsageMutation) AddedEdges() []string { +func (m *BillingRecordMutation) 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 *BillingUsageMutation) AddedIDs(name string) []ent.Value { +func (m *BillingRecordMutation) AddedIDs(name string) []ent.Value { return nil } // RemovedEdges returns all edge names that were removed in this mutation. -func (m *BillingUsageMutation) RemovedEdges() []string { +func (m *BillingRecordMutation) 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 *BillingUsageMutation) RemovedIDs(name string) []ent.Value { +func (m *BillingRecordMutation) RemovedIDs(name string) []ent.Value { return nil } // ClearedEdges returns all edge names that were cleared in this mutation. -func (m *BillingUsageMutation) ClearedEdges() []string { +func (m *BillingRecordMutation) 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 *BillingUsageMutation) EdgeCleared(name string) bool { +func (m *BillingRecordMutation) 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 *BillingUsageMutation) ClearEdge(name string) error { - return fmt.Errorf("unknown BillingUsage unique edge %s", name) +func (m *BillingRecordMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown BillingRecord 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 *BillingUsageMutation) ResetEdge(name string) error { - return fmt.Errorf("unknown BillingUsage edge %s", name) +func (m *BillingRecordMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown BillingRecord edge %s", name) } -// CodeSnippetMutation represents an operation that mutates the CodeSnippet nodes in the graph. -type CodeSnippetMutation struct { +// BillingUsageMutation represents an operation that mutates the BillingUsage nodes in the graph. +type BillingUsageMutation struct { config - op Op - typ string - id *uuid.UUID - name *string - snippet_type *string - language *string - content *string - hash *string - start_line *int - addstart_line *int - end_line *int - addend_line *int - start_column *int - addstart_column *int - end_column *int - addend_column *int - namespace *string - container_name *string - scope *[]string - appendscope []string - dependencies *[]string - appenddependencies []string - parameters *[]map[string]interface{} - appendparameters []map[string]interface{} - signature *string - definition_text *string - structured_info *map[string]interface{} - embedding *pgvector.Vector - workspacePath *string - clearedFields map[string]struct{} - source_file *uuid.UUID - clearedsource_file bool - done bool - oldValue func(context.Context) (*CodeSnippet, error) - predicates []predicate.CodeSnippet + op Op + typ string + id *string + deleted_at *time.Time + user_id *string + model_name *string + tokens *int64 + addtokens *int64 + operation *string + created_at *time.Time + updated_at *time.Time + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*BillingUsage, error) + predicates []predicate.BillingUsage } -var _ ent.Mutation = (*CodeSnippetMutation)(nil) +var _ ent.Mutation = (*BillingUsageMutation)(nil) -// codesnippetOption allows management of the mutation configuration using functional options. -type codesnippetOption func(*CodeSnippetMutation) +// billingusageOption allows management of the mutation configuration using functional options. +type billingusageOption func(*BillingUsageMutation) -// newCodeSnippetMutation creates new mutation for the CodeSnippet entity. -func newCodeSnippetMutation(c config, op Op, opts ...codesnippetOption) *CodeSnippetMutation { - m := &CodeSnippetMutation{ +// newBillingUsageMutation creates new mutation for the BillingUsage entity. +func newBillingUsageMutation(c config, op Op, opts ...billingusageOption) *BillingUsageMutation { + m := &BillingUsageMutation{ config: c, op: op, - typ: TypeCodeSnippet, + typ: TypeBillingUsage, clearedFields: make(map[string]struct{}), } for _, opt := range opts { @@ -5562,20 +5742,20 @@ func newCodeSnippetMutation(c config, op Op, opts ...codesnippetOption) *CodeSni return m } -// withCodeSnippetID sets the ID field of the mutation. -func withCodeSnippetID(id uuid.UUID) codesnippetOption { - return func(m *CodeSnippetMutation) { +// withBillingUsageID sets the ID field of the mutation. +func withBillingUsageID(id string) billingusageOption { + return func(m *BillingUsageMutation) { var ( err error once sync.Once - value *CodeSnippet + value *BillingUsage ) - m.oldValue = func(ctx context.Context) (*CodeSnippet, error) { + m.oldValue = func(ctx context.Context) (*BillingUsage, error) { once.Do(func() { if m.done { err = errors.New("querying old values post mutation is not allowed") } else { - value, err = m.Client().CodeSnippet.Get(ctx, id) + value, err = m.Client().BillingUsage.Get(ctx, id) } }) return value, err @@ -5584,10 +5764,10 @@ func withCodeSnippetID(id uuid.UUID) codesnippetOption { } } -// withCodeSnippet sets the old CodeSnippet of the mutation. -func withCodeSnippet(node *CodeSnippet) codesnippetOption { - return func(m *CodeSnippetMutation) { - m.oldValue = func(context.Context) (*CodeSnippet, error) { +// withBillingUsage sets the old BillingUsage of the mutation. +func withBillingUsage(node *BillingUsage) billingusageOption { + return func(m *BillingUsageMutation) { + m.oldValue = func(context.Context) (*BillingUsage, error) { return node, nil } m.id = &node.ID @@ -5596,7 +5776,7 @@ func withCodeSnippet(node *CodeSnippet) codesnippetOption { // Client returns a new `ent.Client` from the mutation. If the mutation was // executed in a transaction (ent.Tx), a transactional client is returned. -func (m CodeSnippetMutation) Client() *Client { +func (m BillingUsageMutation) Client() *Client { client := &Client{config: m.config} client.init() return client @@ -5604,7 +5784,7 @@ func (m CodeSnippetMutation) Client() *Client { // Tx returns an `ent.Tx` for mutations that were executed in transactions; // it returns an error otherwise. -func (m CodeSnippetMutation) Tx() (*Tx, error) { +func (m BillingUsageMutation) Tx() (*Tx, error) { if _, ok := m.driver.(*txDriver); !ok { return nil, errors.New("db: mutation is not running in a transaction") } @@ -5614,14 +5794,14 @@ func (m CodeSnippetMutation) Tx() (*Tx, error) { } // SetID sets the value of the id field. Note that this -// operation is only accepted on creation of CodeSnippet entities. -func (m *CodeSnippetMutation) SetID(id uuid.UUID) { +// operation is only accepted on creation of BillingUsage entities. +func (m *BillingUsageMutation) SetID(id string) { m.id = &id } // ID returns the ID value in the mutation. Note that the ID is only available // if it was provided to the builder or after it was returned from the database. -func (m *CodeSnippetMutation) ID() (id uuid.UUID, exists bool) { +func (m *BillingUsageMutation) ID() (id string, exists bool) { if m.id == nil { return } @@ -5632,1917 +5812,1782 @@ func (m *CodeSnippetMutation) ID() (id uuid.UUID, exists bool) { // That means, if the mutation is applied within a transaction with an isolation level such // as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated // or updated by the mutation. -func (m *CodeSnippetMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { +func (m *BillingUsageMutation) IDs(ctx context.Context) ([]string, error) { switch { case m.op.Is(OpUpdateOne | OpDeleteOne): id, exists := m.ID() if exists { - return []uuid.UUID{id}, nil + return []string{id}, nil } fallthrough case m.op.Is(OpUpdate | OpDelete): - return m.Client().CodeSnippet.Query().Where(m.predicates...).IDs(ctx) + return m.Client().BillingUsage.Query().Where(m.predicates...).IDs(ctx) default: return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) } } -// SetWorkspaceFileID sets the "workspace_file_id" field. -func (m *CodeSnippetMutation) SetWorkspaceFileID(u uuid.UUID) { - m.source_file = &u +// SetDeletedAt sets the "deleted_at" field. +func (m *BillingUsageMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t } -// WorkspaceFileID returns the value of the "workspace_file_id" field in the mutation. -func (m *CodeSnippetMutation) WorkspaceFileID() (r uuid.UUID, exists bool) { - v := m.source_file +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *BillingUsageMutation) DeletedAt() (r time.Time, exists bool) { + v := m.deleted_at if v == nil { return } return *v, true } -// OldWorkspaceFileID returns the old "workspace_file_id" field's value of the CodeSnippet entity. -// If the CodeSnippet object wasn't provided to the builder, the object is fetched from the database. +// OldDeletedAt returns the old "deleted_at" field's value of the BillingUsage entity. +// If the BillingUsage object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *CodeSnippetMutation) OldWorkspaceFileID(ctx context.Context) (v uuid.UUID, err error) { +func (m *BillingUsageMutation) OldDeletedAt(ctx context.Context) (v time.Time, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldWorkspaceFileID is only allowed on UpdateOne operations") + return v, errors.New("OldDeletedAt is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldWorkspaceFileID requires an ID field in the mutation") + return v, errors.New("OldDeletedAt requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldWorkspaceFileID: %w", err) + return v, fmt.Errorf("querying old value for OldDeletedAt: %w", err) } - return oldValue.WorkspaceFileID, nil + return oldValue.DeletedAt, nil } -// ResetWorkspaceFileID resets all changes to the "workspace_file_id" field. -func (m *CodeSnippetMutation) ResetWorkspaceFileID() { - m.source_file = nil +// ClearDeletedAt clears the value of the "deleted_at" field. +func (m *BillingUsageMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[billingusage.FieldDeletedAt] = struct{}{} } -// SetName sets the "name" field. -func (m *CodeSnippetMutation) SetName(s string) { - m.name = &s +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *BillingUsageMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[billingusage.FieldDeletedAt] + return ok } -// Name returns the value of the "name" field in the mutation. -func (m *CodeSnippetMutation) Name() (r string, exists bool) { - v := m.name +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *BillingUsageMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, billingusage.FieldDeletedAt) +} + +// SetUserID sets the "user_id" field. +func (m *BillingUsageMutation) SetUserID(s string) { + m.user_id = &s +} + +// UserID returns the value of the "user_id" field in the mutation. +func (m *BillingUsageMutation) UserID() (r string, exists bool) { + v := m.user_id if v == nil { return } return *v, true } -// OldName returns the old "name" field's value of the CodeSnippet entity. -// If the CodeSnippet object wasn't provided to the builder, the object is fetched from the database. +// OldUserID returns the old "user_id" field's value of the BillingUsage entity. +// If the BillingUsage object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *CodeSnippetMutation) OldName(ctx context.Context) (v string, err error) { +func (m *BillingUsageMutation) OldUserID(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldName is only allowed on UpdateOne operations") + return v, errors.New("OldUserID 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") + return v, errors.New("OldUserID requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldName: %w", err) + return v, fmt.Errorf("querying old value for OldUserID: %w", err) } - return oldValue.Name, nil + return oldValue.UserID, nil } -// ResetName resets all changes to the "name" field. -func (m *CodeSnippetMutation) ResetName() { - m.name = nil +// ResetUserID resets all changes to the "user_id" field. +func (m *BillingUsageMutation) ResetUserID() { + m.user_id = nil } -// SetSnippetType sets the "snippet_type" field. -func (m *CodeSnippetMutation) SetSnippetType(s string) { - m.snippet_type = &s +// SetModelName sets the "model_name" field. +func (m *BillingUsageMutation) SetModelName(s string) { + m.model_name = &s } -// SnippetType returns the value of the "snippet_type" field in the mutation. -func (m *CodeSnippetMutation) SnippetType() (r string, exists bool) { - v := m.snippet_type +// ModelName returns the value of the "model_name" field in the mutation. +func (m *BillingUsageMutation) ModelName() (r string, exists bool) { + v := m.model_name if v == nil { return } return *v, true } -// OldSnippetType returns the old "snippet_type" field's value of the CodeSnippet entity. -// If the CodeSnippet object wasn't provided to the builder, the object is fetched from the database. +// OldModelName returns the old "model_name" field's value of the BillingUsage entity. +// If the BillingUsage object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *CodeSnippetMutation) OldSnippetType(ctx context.Context) (v string, err error) { +func (m *BillingUsageMutation) OldModelName(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldSnippetType is only allowed on UpdateOne operations") + return v, errors.New("OldModelName is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldSnippetType requires an ID field in the mutation") + return v, errors.New("OldModelName requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldSnippetType: %w", err) + return v, fmt.Errorf("querying old value for OldModelName: %w", err) } - return oldValue.SnippetType, nil + return oldValue.ModelName, nil } -// ResetSnippetType resets all changes to the "snippet_type" field. -func (m *CodeSnippetMutation) ResetSnippetType() { - m.snippet_type = nil +// ResetModelName resets all changes to the "model_name" field. +func (m *BillingUsageMutation) ResetModelName() { + m.model_name = nil } -// SetLanguage sets the "language" field. -func (m *CodeSnippetMutation) SetLanguage(s string) { - m.language = &s +// SetTokens sets the "tokens" field. +func (m *BillingUsageMutation) SetTokens(i int64) { + m.tokens = &i + m.addtokens = nil } -// Language returns the value of the "language" field in the mutation. -func (m *CodeSnippetMutation) Language() (r string, exists bool) { - v := m.language +// Tokens returns the value of the "tokens" field in the mutation. +func (m *BillingUsageMutation) Tokens() (r int64, exists bool) { + v := m.tokens if v == nil { return } return *v, true } -// OldLanguage returns the old "language" field's value of the CodeSnippet entity. -// If the CodeSnippet object wasn't provided to the builder, the object is fetched from the database. +// OldTokens returns the old "tokens" field's value of the BillingUsage entity. +// If the BillingUsage object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *CodeSnippetMutation) OldLanguage(ctx context.Context) (v string, err error) { +func (m *BillingUsageMutation) OldTokens(ctx context.Context) (v int64, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldLanguage is only allowed on UpdateOne operations") + return v, errors.New("OldTokens is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldLanguage requires an ID field in the mutation") + return v, errors.New("OldTokens requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldLanguage: %w", err) + return v, fmt.Errorf("querying old value for OldTokens: %w", err) } - return oldValue.Language, nil + return oldValue.Tokens, nil } -// ResetLanguage resets all changes to the "language" field. -func (m *CodeSnippetMutation) ResetLanguage() { - m.language = nil +// AddTokens adds i to the "tokens" field. +func (m *BillingUsageMutation) AddTokens(i int64) { + if m.addtokens != nil { + *m.addtokens += i + } else { + m.addtokens = &i + } } -// SetContent sets the "content" field. -func (m *CodeSnippetMutation) SetContent(s string) { - m.content = &s +// AddedTokens returns the value that was added to the "tokens" field in this mutation. +func (m *BillingUsageMutation) AddedTokens() (r int64, exists bool) { + v := m.addtokens + if v == nil { + return + } + return *v, true } -// Content returns the value of the "content" field in the mutation. -func (m *CodeSnippetMutation) Content() (r string, exists bool) { - v := m.content +// ResetTokens resets all changes to the "tokens" field. +func (m *BillingUsageMutation) ResetTokens() { + m.tokens = nil + m.addtokens = nil +} + +// SetOperation sets the "operation" field. +func (m *BillingUsageMutation) SetOperation(s string) { + m.operation = &s +} + +// Operation returns the value of the "operation" field in the mutation. +func (m *BillingUsageMutation) Operation() (r string, exists bool) { + v := m.operation if v == nil { return } return *v, true } -// OldContent returns the old "content" field's value of the CodeSnippet entity. -// If the CodeSnippet object wasn't provided to the builder, the object is fetched from the database. +// OldOperation returns the old "operation" field's value of the BillingUsage entity. +// If the BillingUsage object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *CodeSnippetMutation) OldContent(ctx context.Context) (v string, err error) { +func (m *BillingUsageMutation) OldOperation(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldContent is only allowed on UpdateOne operations") + return v, errors.New("OldOperation 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") + return v, errors.New("OldOperation 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 v, fmt.Errorf("querying old value for OldOperation: %w", err) } - return oldValue.Content, nil + return oldValue.Operation, nil } -// ResetContent resets all changes to the "content" field. -func (m *CodeSnippetMutation) ResetContent() { - m.content = nil +// ResetOperation resets all changes to the "operation" field. +func (m *BillingUsageMutation) ResetOperation() { + m.operation = nil } -// SetHash sets the "hash" field. -func (m *CodeSnippetMutation) SetHash(s string) { - m.hash = &s +// SetCreatedAt sets the "created_at" field. +func (m *BillingUsageMutation) SetCreatedAt(t time.Time) { + m.created_at = &t } -// Hash returns the value of the "hash" field in the mutation. -func (m *CodeSnippetMutation) Hash() (r string, exists bool) { - v := m.hash +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *BillingUsageMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at if v == nil { return } return *v, true } -// OldHash returns the old "hash" field's value of the CodeSnippet entity. -// If the CodeSnippet object wasn't provided to the builder, the object is fetched from the database. +// OldCreatedAt returns the old "created_at" field's value of the BillingUsage entity. +// If the BillingUsage object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *CodeSnippetMutation) OldHash(ctx context.Context) (v string, err error) { +func (m *BillingUsageMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldHash is only allowed on UpdateOne operations") + return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldHash requires an ID field in the mutation") + 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 OldHash: %w", err) + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) } - return oldValue.Hash, nil + return oldValue.CreatedAt, nil } -// ResetHash resets all changes to the "hash" field. -func (m *CodeSnippetMutation) ResetHash() { - m.hash = nil +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *BillingUsageMutation) ResetCreatedAt() { + m.created_at = nil } -// SetStartLine sets the "start_line" field. -func (m *CodeSnippetMutation) SetStartLine(i int) { - m.start_line = &i - m.addstart_line = nil +// SetUpdatedAt sets the "updated_at" field. +func (m *BillingUsageMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t } -// StartLine returns the value of the "start_line" field in the mutation. -func (m *CodeSnippetMutation) StartLine() (r int, exists bool) { - v := m.start_line +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *BillingUsageMutation) UpdatedAt() (r time.Time, exists bool) { + v := m.updated_at if v == nil { return } return *v, true } -// OldStartLine returns the old "start_line" field's value of the CodeSnippet entity. -// If the CodeSnippet object wasn't provided to the builder, the object is fetched from the database. +// OldUpdatedAt returns the old "updated_at" field's value of the BillingUsage entity. +// If the BillingUsage object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *CodeSnippetMutation) OldStartLine(ctx context.Context) (v int, err error) { +func (m *BillingUsageMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldStartLine is only allowed on UpdateOne operations") + return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldStartLine requires an ID field in the mutation") + 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 OldStartLine: %w", err) + return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) } - return oldValue.StartLine, nil + return oldValue.UpdatedAt, nil } -// AddStartLine adds i to the "start_line" field. -func (m *CodeSnippetMutation) AddStartLine(i int) { - if m.addstart_line != nil { - *m.addstart_line += i - } else { - m.addstart_line = &i - } +// ResetUpdatedAt resets all changes to the "updated_at" field. +func (m *BillingUsageMutation) ResetUpdatedAt() { + m.updated_at = nil } -// AddedStartLine returns the value that was added to the "start_line" field in this mutation. -func (m *CodeSnippetMutation) AddedStartLine() (r int, exists bool) { - v := m.addstart_line - if v == nil { - return +// Where appends a list predicates to the BillingUsageMutation builder. +func (m *BillingUsageMutation) Where(ps ...predicate.BillingUsage) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the BillingUsageMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *BillingUsageMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.BillingUsage, len(ps)) + for i := range ps { + p[i] = ps[i] } - return *v, true + m.Where(p...) } -// ResetStartLine resets all changes to the "start_line" field. -func (m *CodeSnippetMutation) ResetStartLine() { - m.start_line = nil - m.addstart_line = nil +// Op returns the operation name. +func (m *BillingUsageMutation) Op() Op { + return m.op } -// SetEndLine sets the "end_line" field. -func (m *CodeSnippetMutation) SetEndLine(i int) { - m.end_line = &i - m.addend_line = nil +// SetOp allows setting the mutation operation. +func (m *BillingUsageMutation) SetOp(op Op) { + m.op = op } -// EndLine returns the value of the "end_line" field in the mutation. -func (m *CodeSnippetMutation) EndLine() (r int, exists bool) { - v := m.end_line - if v == nil { - return - } - return *v, true +// Type returns the node type of this mutation (BillingUsage). +func (m *BillingUsageMutation) Type() string { + return m.typ } -// OldEndLine returns the old "end_line" field's value of the CodeSnippet entity. -// If the CodeSnippet object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *CodeSnippetMutation) OldEndLine(ctx context.Context) (v int, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldEndLine is only allowed on UpdateOne operations") +// 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 *BillingUsageMutation) Fields() []string { + fields := make([]string, 0, 7) + if m.deleted_at != nil { + fields = append(fields, billingusage.FieldDeletedAt) } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldEndLine requires an ID field in the mutation") + if m.user_id != nil { + fields = append(fields, billingusage.FieldUserID) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldEndLine: %w", err) + if m.model_name != nil { + fields = append(fields, billingusage.FieldModelName) } - return oldValue.EndLine, nil + if m.tokens != nil { + fields = append(fields, billingusage.FieldTokens) + } + if m.operation != nil { + fields = append(fields, billingusage.FieldOperation) + } + if m.created_at != nil { + fields = append(fields, billingusage.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, billingusage.FieldUpdatedAt) + } + return fields } -// AddEndLine adds i to the "end_line" field. -func (m *CodeSnippetMutation) AddEndLine(i int) { - if m.addend_line != nil { - *m.addend_line += i - } else { - m.addend_line = &i +// 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 *BillingUsageMutation) Field(name string) (ent.Value, bool) { + switch name { + case billingusage.FieldDeletedAt: + return m.DeletedAt() + case billingusage.FieldUserID: + return m.UserID() + case billingusage.FieldModelName: + return m.ModelName() + case billingusage.FieldTokens: + return m.Tokens() + case billingusage.FieldOperation: + return m.Operation() + case billingusage.FieldCreatedAt: + return m.CreatedAt() + case billingusage.FieldUpdatedAt: + return m.UpdatedAt() } + return nil, false } -// AddedEndLine returns the value that was added to the "end_line" field in this mutation. -func (m *CodeSnippetMutation) AddedEndLine() (r int, exists bool) { - v := m.addend_line - if v == nil { - return +// 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 *BillingUsageMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case billingusage.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case billingusage.FieldUserID: + return m.OldUserID(ctx) + case billingusage.FieldModelName: + return m.OldModelName(ctx) + case billingusage.FieldTokens: + return m.OldTokens(ctx) + case billingusage.FieldOperation: + return m.OldOperation(ctx) + case billingusage.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case billingusage.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) } - return *v, true + return nil, fmt.Errorf("unknown BillingUsage field %s", name) } -// ResetEndLine resets all changes to the "end_line" field. -func (m *CodeSnippetMutation) ResetEndLine() { - m.end_line = nil - m.addend_line = nil +// 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 *BillingUsageMutation) SetField(name string, value ent.Value) error { + switch name { + case billingusage.FieldDeletedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDeletedAt(v) + return nil + case billingusage.FieldUserID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUserID(v) + return nil + case billingusage.FieldModelName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetModelName(v) + return nil + case billingusage.FieldTokens: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTokens(v) + return nil + case billingusage.FieldOperation: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetOperation(v) + return nil + case billingusage.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 billingusage.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 BillingUsage field %s", name) } -// SetStartColumn sets the "start_column" field. -func (m *CodeSnippetMutation) SetStartColumn(i int) { - m.start_column = &i - m.addstart_column = nil +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *BillingUsageMutation) AddedFields() []string { + var fields []string + if m.addtokens != nil { + fields = append(fields, billingusage.FieldTokens) + } + return fields } -// StartColumn returns the value of the "start_column" field in the mutation. -func (m *CodeSnippetMutation) StartColumn() (r int, exists bool) { - v := m.start_column - if v == nil { - return +// 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 *BillingUsageMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case billingusage.FieldTokens: + return m.AddedTokens() } - return *v, true + return nil, false } -// OldStartColumn returns the old "start_column" field's value of the CodeSnippet entity. -// If the CodeSnippet object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *CodeSnippetMutation) OldStartColumn(ctx context.Context) (v int, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldStartColumn is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldStartColumn requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldStartColumn: %w", err) +// 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 *BillingUsageMutation) AddField(name string, value ent.Value) error { + switch name { + case billingusage.FieldTokens: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddTokens(v) + return nil } - return oldValue.StartColumn, nil + return fmt.Errorf("unknown BillingUsage numeric field %s", name) } -// AddStartColumn adds i to the "start_column" field. -func (m *CodeSnippetMutation) AddStartColumn(i int) { - if m.addstart_column != nil { - *m.addstart_column += i - } else { - m.addstart_column = &i +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *BillingUsageMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(billingusage.FieldDeletedAt) { + fields = append(fields, billingusage.FieldDeletedAt) } + return fields } -// AddedStartColumn returns the value that was added to the "start_column" field in this mutation. -func (m *CodeSnippetMutation) AddedStartColumn() (r int, exists bool) { - v := m.addstart_column - if v == nil { - return - } - return *v, true -} - -// ResetStartColumn resets all changes to the "start_column" field. -func (m *CodeSnippetMutation) ResetStartColumn() { - m.start_column = nil - m.addstart_column = nil -} - -// SetEndColumn sets the "end_column" field. -func (m *CodeSnippetMutation) SetEndColumn(i int) { - m.end_column = &i - m.addend_column = nil +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *BillingUsageMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok } -// EndColumn returns the value of the "end_column" field in the mutation. -func (m *CodeSnippetMutation) EndColumn() (r int, exists bool) { - v := m.end_column - if v == nil { - return +// 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 *BillingUsageMutation) ClearField(name string) error { + switch name { + case billingusage.FieldDeletedAt: + m.ClearDeletedAt() + return nil } - return *v, true + return fmt.Errorf("unknown BillingUsage nullable field %s", name) } -// OldEndColumn returns the old "end_column" field's value of the CodeSnippet entity. -// If the CodeSnippet object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *CodeSnippetMutation) OldEndColumn(ctx context.Context) (v int, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldEndColumn is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldEndColumn requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldEndColumn: %w", err) +// 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 *BillingUsageMutation) ResetField(name string) error { + switch name { + case billingusage.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case billingusage.FieldUserID: + m.ResetUserID() + return nil + case billingusage.FieldModelName: + m.ResetModelName() + return nil + case billingusage.FieldTokens: + m.ResetTokens() + return nil + case billingusage.FieldOperation: + m.ResetOperation() + return nil + case billingusage.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case billingusage.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil } - return oldValue.EndColumn, nil + return fmt.Errorf("unknown BillingUsage field %s", name) } -// AddEndColumn adds i to the "end_column" field. -func (m *CodeSnippetMutation) AddEndColumn(i int) { - if m.addend_column != nil { - *m.addend_column += i - } else { - m.addend_column = &i - } +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *BillingUsageMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges } -// AddedEndColumn returns the value that was added to the "end_column" field in this mutation. -func (m *CodeSnippetMutation) AddedEndColumn() (r int, exists bool) { - v := m.addend_column - if v == nil { - return - } - return *v, true +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *BillingUsageMutation) AddedIDs(name string) []ent.Value { + return nil } -// ResetEndColumn resets all changes to the "end_column" field. -func (m *CodeSnippetMutation) ResetEndColumn() { - m.end_column = nil - m.addend_column = nil +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *BillingUsageMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges } -// SetNamespace sets the "namespace" field. -func (m *CodeSnippetMutation) SetNamespace(s string) { - m.namespace = &s +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *BillingUsageMutation) RemovedIDs(name string) []ent.Value { + return nil } -// Namespace returns the value of the "namespace" field in the mutation. -func (m *CodeSnippetMutation) Namespace() (r string, exists bool) { - v := m.namespace - if v == nil { - return - } - return *v, true +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *BillingUsageMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges } -// OldNamespace returns the old "namespace" field's value of the CodeSnippet entity. -// If the CodeSnippet object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *CodeSnippetMutation) OldNamespace(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldNamespace is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldNamespace requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldNamespace: %w", err) - } - return oldValue.Namespace, nil +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *BillingUsageMutation) EdgeCleared(name string) bool { + return false } -// ClearNamespace clears the value of the "namespace" field. -func (m *CodeSnippetMutation) ClearNamespace() { - m.namespace = nil - m.clearedFields[codesnippet.FieldNamespace] = struct{}{} +// 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 *BillingUsageMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown BillingUsage unique edge %s", name) } -// NamespaceCleared returns if the "namespace" field was cleared in this mutation. -func (m *CodeSnippetMutation) NamespaceCleared() bool { - _, ok := m.clearedFields[codesnippet.FieldNamespace] - return ok +// 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 *BillingUsageMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown BillingUsage edge %s", name) } -// ResetNamespace resets all changes to the "namespace" field. -func (m *CodeSnippetMutation) ResetNamespace() { - m.namespace = nil - delete(m.clearedFields, codesnippet.FieldNamespace) +// CodeSnippetMutation represents an operation that mutates the CodeSnippet nodes in the graph. +type CodeSnippetMutation struct { + config + op Op + typ string + id *uuid.UUID + name *string + snippet_type *string + language *string + content *string + hash *string + start_line *int + addstart_line *int + end_line *int + addend_line *int + start_column *int + addstart_column *int + end_column *int + addend_column *int + namespace *string + container_name *string + scope *[]string + appendscope []string + dependencies *[]string + appenddependencies []string + parameters *[]map[string]interface{} + appendparameters []map[string]interface{} + signature *string + definition_text *string + structured_info *map[string]interface{} + embedding *pgvector.Vector + workspacePath *string + clearedFields map[string]struct{} + source_file *uuid.UUID + clearedsource_file bool + done bool + oldValue func(context.Context) (*CodeSnippet, error) + predicates []predicate.CodeSnippet } -// SetContainerName sets the "container_name" field. -func (m *CodeSnippetMutation) SetContainerName(s string) { - m.container_name = &s -} +var _ ent.Mutation = (*CodeSnippetMutation)(nil) -// ContainerName returns the value of the "container_name" field in the mutation. -func (m *CodeSnippetMutation) ContainerName() (r string, exists bool) { - v := m.container_name - if v == nil { - return - } - return *v, true -} +// codesnippetOption allows management of the mutation configuration using functional options. +type codesnippetOption func(*CodeSnippetMutation) -// OldContainerName returns the old "container_name" field's value of the CodeSnippet entity. -// If the CodeSnippet object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *CodeSnippetMutation) OldContainerName(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldContainerName is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldContainerName requires an ID field in the mutation") +// newCodeSnippetMutation creates new mutation for the CodeSnippet entity. +func newCodeSnippetMutation(c config, op Op, opts ...codesnippetOption) *CodeSnippetMutation { + m := &CodeSnippetMutation{ + config: c, + op: op, + typ: TypeCodeSnippet, + clearedFields: make(map[string]struct{}), } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldContainerName: %w", err) + for _, opt := range opts { + opt(m) } - return oldValue.ContainerName, nil -} - -// ClearContainerName clears the value of the "container_name" field. -func (m *CodeSnippetMutation) ClearContainerName() { - m.container_name = nil - m.clearedFields[codesnippet.FieldContainerName] = struct{}{} -} - -// ContainerNameCleared returns if the "container_name" field was cleared in this mutation. -func (m *CodeSnippetMutation) ContainerNameCleared() bool { - _, ok := m.clearedFields[codesnippet.FieldContainerName] - return ok + return m } -// ResetContainerName resets all changes to the "container_name" field. -func (m *CodeSnippetMutation) ResetContainerName() { - m.container_name = nil - delete(m.clearedFields, codesnippet.FieldContainerName) +// withCodeSnippetID sets the ID field of the mutation. +func withCodeSnippetID(id uuid.UUID) codesnippetOption { + return func(m *CodeSnippetMutation) { + var ( + err error + once sync.Once + value *CodeSnippet + ) + m.oldValue = func(ctx context.Context) (*CodeSnippet, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().CodeSnippet.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } } -// SetScope sets the "scope" field. -func (m *CodeSnippetMutation) SetScope(s []string) { - m.scope = &s - m.appendscope = nil +// withCodeSnippet sets the old CodeSnippet of the mutation. +func withCodeSnippet(node *CodeSnippet) codesnippetOption { + return func(m *CodeSnippetMutation) { + m.oldValue = func(context.Context) (*CodeSnippet, error) { + return node, nil + } + m.id = &node.ID + } } -// Scope returns the value of the "scope" field in the mutation. -func (m *CodeSnippetMutation) Scope() (r []string, exists bool) { - v := m.scope +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m CodeSnippetMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m CodeSnippetMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("db: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of CodeSnippet entities. +func (m *CodeSnippetMutation) SetID(id uuid.UUID) { + m.id = &id +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *CodeSnippetMutation) ID() (id uuid.UUID, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *CodeSnippetMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []uuid.UUID{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().CodeSnippet.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetWorkspaceFileID sets the "workspace_file_id" field. +func (m *CodeSnippetMutation) SetWorkspaceFileID(u uuid.UUID) { + m.source_file = &u +} + +// WorkspaceFileID returns the value of the "workspace_file_id" field in the mutation. +func (m *CodeSnippetMutation) WorkspaceFileID() (r uuid.UUID, exists bool) { + v := m.source_file if v == nil { return } return *v, true } -// OldScope returns the old "scope" field's value of the CodeSnippet entity. +// OldWorkspaceFileID returns the old "workspace_file_id" field's value of the CodeSnippet entity. // If the CodeSnippet object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *CodeSnippetMutation) OldScope(ctx context.Context) (v []string, err error) { +func (m *CodeSnippetMutation) OldWorkspaceFileID(ctx context.Context) (v uuid.UUID, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldScope is only allowed on UpdateOne operations") + return v, errors.New("OldWorkspaceFileID is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldScope requires an ID field in the mutation") + return v, errors.New("OldWorkspaceFileID requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldScope: %w", err) - } - return oldValue.Scope, nil -} - -// AppendScope adds s to the "scope" field. -func (m *CodeSnippetMutation) AppendScope(s []string) { - m.appendscope = append(m.appendscope, s...) -} - -// AppendedScope returns the list of values that were appended to the "scope" field in this mutation. -func (m *CodeSnippetMutation) AppendedScope() ([]string, bool) { - if len(m.appendscope) == 0 { - return nil, false + return v, fmt.Errorf("querying old value for OldWorkspaceFileID: %w", err) } - return m.appendscope, true -} - -// ClearScope clears the value of the "scope" field. -func (m *CodeSnippetMutation) ClearScope() { - m.scope = nil - m.appendscope = nil - m.clearedFields[codesnippet.FieldScope] = struct{}{} -} - -// ScopeCleared returns if the "scope" field was cleared in this mutation. -func (m *CodeSnippetMutation) ScopeCleared() bool { - _, ok := m.clearedFields[codesnippet.FieldScope] - return ok + return oldValue.WorkspaceFileID, nil } -// ResetScope resets all changes to the "scope" field. -func (m *CodeSnippetMutation) ResetScope() { - m.scope = nil - m.appendscope = nil - delete(m.clearedFields, codesnippet.FieldScope) +// ResetWorkspaceFileID resets all changes to the "workspace_file_id" field. +func (m *CodeSnippetMutation) ResetWorkspaceFileID() { + m.source_file = nil } -// SetDependencies sets the "dependencies" field. -func (m *CodeSnippetMutation) SetDependencies(s []string) { - m.dependencies = &s - m.appenddependencies = nil +// SetName sets the "name" field. +func (m *CodeSnippetMutation) SetName(s string) { + m.name = &s } -// Dependencies returns the value of the "dependencies" field in the mutation. -func (m *CodeSnippetMutation) Dependencies() (r []string, exists bool) { - v := m.dependencies +// Name returns the value of the "name" field in the mutation. +func (m *CodeSnippetMutation) Name() (r string, exists bool) { + v := m.name if v == nil { return } return *v, true } -// OldDependencies returns the old "dependencies" field's value of the CodeSnippet entity. +// OldName returns the old "name" field's value of the CodeSnippet entity. // If the CodeSnippet object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *CodeSnippetMutation) OldDependencies(ctx context.Context) (v []string, err error) { +func (m *CodeSnippetMutation) OldName(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldDependencies is only allowed on UpdateOne operations") + return v, errors.New("OldName is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldDependencies requires an ID field in the mutation") + 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 OldDependencies: %w", err) + return v, fmt.Errorf("querying old value for OldName: %w", err) } - return oldValue.Dependencies, nil + return oldValue.Name, nil } -// AppendDependencies adds s to the "dependencies" field. -func (m *CodeSnippetMutation) AppendDependencies(s []string) { - m.appenddependencies = append(m.appenddependencies, s...) +// ResetName resets all changes to the "name" field. +func (m *CodeSnippetMutation) ResetName() { + m.name = nil } -// AppendedDependencies returns the list of values that were appended to the "dependencies" field in this mutation. -func (m *CodeSnippetMutation) AppendedDependencies() ([]string, bool) { - if len(m.appenddependencies) == 0 { - return nil, false - } - return m.appenddependencies, true +// SetSnippetType sets the "snippet_type" field. +func (m *CodeSnippetMutation) SetSnippetType(s string) { + m.snippet_type = &s } -// ClearDependencies clears the value of the "dependencies" field. -func (m *CodeSnippetMutation) ClearDependencies() { - m.dependencies = nil - m.appenddependencies = nil - m.clearedFields[codesnippet.FieldDependencies] = struct{}{} +// SnippetType returns the value of the "snippet_type" field in the mutation. +func (m *CodeSnippetMutation) SnippetType() (r string, exists bool) { + v := m.snippet_type + if v == nil { + return + } + return *v, true } -// DependenciesCleared returns if the "dependencies" field was cleared in this mutation. -func (m *CodeSnippetMutation) DependenciesCleared() bool { - _, ok := m.clearedFields[codesnippet.FieldDependencies] - return ok +// OldSnippetType returns the old "snippet_type" field's value of the CodeSnippet entity. +// If the CodeSnippet object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *CodeSnippetMutation) OldSnippetType(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSnippetType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSnippetType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSnippetType: %w", err) + } + return oldValue.SnippetType, nil } -// ResetDependencies resets all changes to the "dependencies" field. -func (m *CodeSnippetMutation) ResetDependencies() { - m.dependencies = nil - m.appenddependencies = nil - delete(m.clearedFields, codesnippet.FieldDependencies) +// ResetSnippetType resets all changes to the "snippet_type" field. +func (m *CodeSnippetMutation) ResetSnippetType() { + m.snippet_type = nil } -// SetParameters sets the "parameters" field. -func (m *CodeSnippetMutation) SetParameters(value []map[string]interface{}) { - m.parameters = &value - m.appendparameters = nil +// SetLanguage sets the "language" field. +func (m *CodeSnippetMutation) SetLanguage(s string) { + m.language = &s } -// Parameters returns the value of the "parameters" field in the mutation. -func (m *CodeSnippetMutation) Parameters() (r []map[string]interface{}, exists bool) { - v := m.parameters +// Language returns the value of the "language" field in the mutation. +func (m *CodeSnippetMutation) Language() (r string, exists bool) { + v := m.language if v == nil { return } return *v, true } -// OldParameters returns the old "parameters" field's value of the CodeSnippet entity. +// OldLanguage returns the old "language" field's value of the CodeSnippet entity. // If the CodeSnippet object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *CodeSnippetMutation) OldParameters(ctx context.Context) (v []map[string]interface{}, err error) { +func (m *CodeSnippetMutation) OldLanguage(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldParameters is only allowed on UpdateOne operations") + return v, errors.New("OldLanguage is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldParameters requires an ID field in the mutation") + return v, errors.New("OldLanguage requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldParameters: %w", err) + return v, fmt.Errorf("querying old value for OldLanguage: %w", err) } - return oldValue.Parameters, nil + return oldValue.Language, nil } -// AppendParameters adds value to the "parameters" field. -func (m *CodeSnippetMutation) AppendParameters(value []map[string]interface{}) { - m.appendparameters = append(m.appendparameters, value...) +// ResetLanguage resets all changes to the "language" field. +func (m *CodeSnippetMutation) ResetLanguage() { + m.language = nil } -// AppendedParameters returns the list of values that were appended to the "parameters" field in this mutation. -func (m *CodeSnippetMutation) AppendedParameters() ([]map[string]interface{}, bool) { - if len(m.appendparameters) == 0 { - return nil, false - } - return m.appendparameters, true -} - -// ClearParameters clears the value of the "parameters" field. -func (m *CodeSnippetMutation) ClearParameters() { - m.parameters = nil - m.appendparameters = nil - m.clearedFields[codesnippet.FieldParameters] = struct{}{} -} - -// ParametersCleared returns if the "parameters" field was cleared in this mutation. -func (m *CodeSnippetMutation) ParametersCleared() bool { - _, ok := m.clearedFields[codesnippet.FieldParameters] - return ok -} - -// ResetParameters resets all changes to the "parameters" field. -func (m *CodeSnippetMutation) ResetParameters() { - m.parameters = nil - m.appendparameters = nil - delete(m.clearedFields, codesnippet.FieldParameters) -} - -// SetSignature sets the "signature" field. -func (m *CodeSnippetMutation) SetSignature(s string) { - m.signature = &s +// SetContent sets the "content" field. +func (m *CodeSnippetMutation) SetContent(s string) { + m.content = &s } -// Signature returns the value of the "signature" field in the mutation. -func (m *CodeSnippetMutation) Signature() (r string, exists bool) { - v := m.signature +// Content returns the value of the "content" field in the mutation. +func (m *CodeSnippetMutation) Content() (r string, exists bool) { + v := m.content if v == nil { return } return *v, true } -// OldSignature returns the old "signature" field's value of the CodeSnippet entity. +// OldContent returns the old "content" field's value of the CodeSnippet entity. // If the CodeSnippet object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *CodeSnippetMutation) OldSignature(ctx context.Context) (v string, err error) { +func (m *CodeSnippetMutation) OldContent(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldSignature is only allowed on UpdateOne operations") + return v, errors.New("OldContent is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldSignature requires an ID field in the mutation") + 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 OldSignature: %w", err) + return v, fmt.Errorf("querying old value for OldContent: %w", err) } - return oldValue.Signature, nil -} - -// ClearSignature clears the value of the "signature" field. -func (m *CodeSnippetMutation) ClearSignature() { - m.signature = nil - m.clearedFields[codesnippet.FieldSignature] = struct{}{} -} - -// SignatureCleared returns if the "signature" field was cleared in this mutation. -func (m *CodeSnippetMutation) SignatureCleared() bool { - _, ok := m.clearedFields[codesnippet.FieldSignature] - return ok + return oldValue.Content, nil } -// ResetSignature resets all changes to the "signature" field. -func (m *CodeSnippetMutation) ResetSignature() { - m.signature = nil - delete(m.clearedFields, codesnippet.FieldSignature) +// ResetContent resets all changes to the "content" field. +func (m *CodeSnippetMutation) ResetContent() { + m.content = nil } -// SetDefinitionText sets the "definition_text" field. -func (m *CodeSnippetMutation) SetDefinitionText(s string) { - m.definition_text = &s +// SetHash sets the "hash" field. +func (m *CodeSnippetMutation) SetHash(s string) { + m.hash = &s } -// DefinitionText returns the value of the "definition_text" field in the mutation. -func (m *CodeSnippetMutation) DefinitionText() (r string, exists bool) { - v := m.definition_text +// Hash returns the value of the "hash" field in the mutation. +func (m *CodeSnippetMutation) Hash() (r string, exists bool) { + v := m.hash if v == nil { return } return *v, true } -// OldDefinitionText returns the old "definition_text" field's value of the CodeSnippet entity. +// OldHash returns the old "hash" field's value of the CodeSnippet entity. // If the CodeSnippet object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *CodeSnippetMutation) OldDefinitionText(ctx context.Context) (v string, err error) { +func (m *CodeSnippetMutation) OldHash(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldDefinitionText is only allowed on UpdateOne operations") + return v, errors.New("OldHash is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldDefinitionText requires an ID field in the mutation") + return v, errors.New("OldHash requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldDefinitionText: %w", err) + return v, fmt.Errorf("querying old value for OldHash: %w", err) } - return oldValue.DefinitionText, nil -} - -// ClearDefinitionText clears the value of the "definition_text" field. -func (m *CodeSnippetMutation) ClearDefinitionText() { - m.definition_text = nil - m.clearedFields[codesnippet.FieldDefinitionText] = struct{}{} -} - -// DefinitionTextCleared returns if the "definition_text" field was cleared in this mutation. -func (m *CodeSnippetMutation) DefinitionTextCleared() bool { - _, ok := m.clearedFields[codesnippet.FieldDefinitionText] - return ok + return oldValue.Hash, nil } -// ResetDefinitionText resets all changes to the "definition_text" field. -func (m *CodeSnippetMutation) ResetDefinitionText() { - m.definition_text = nil - delete(m.clearedFields, codesnippet.FieldDefinitionText) +// ResetHash resets all changes to the "hash" field. +func (m *CodeSnippetMutation) ResetHash() { + m.hash = nil } -// SetStructuredInfo sets the "structured_info" field. -func (m *CodeSnippetMutation) SetStructuredInfo(value map[string]interface{}) { - m.structured_info = &value +// SetStartLine sets the "start_line" field. +func (m *CodeSnippetMutation) SetStartLine(i int) { + m.start_line = &i + m.addstart_line = nil } -// StructuredInfo returns the value of the "structured_info" field in the mutation. -func (m *CodeSnippetMutation) StructuredInfo() (r map[string]interface{}, exists bool) { - v := m.structured_info +// StartLine returns the value of the "start_line" field in the mutation. +func (m *CodeSnippetMutation) StartLine() (r int, exists bool) { + v := m.start_line if v == nil { return } return *v, true } -// OldStructuredInfo returns the old "structured_info" field's value of the CodeSnippet entity. +// OldStartLine returns the old "start_line" field's value of the CodeSnippet entity. // If the CodeSnippet object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *CodeSnippetMutation) OldStructuredInfo(ctx context.Context) (v map[string]interface{}, err error) { +func (m *CodeSnippetMutation) OldStartLine(ctx context.Context) (v int, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldStructuredInfo is only allowed on UpdateOne operations") + return v, errors.New("OldStartLine is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldStructuredInfo requires an ID field in the mutation") + return v, errors.New("OldStartLine requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldStructuredInfo: %w", err) + return v, fmt.Errorf("querying old value for OldStartLine: %w", err) } - return oldValue.StructuredInfo, nil + return oldValue.StartLine, nil } -// ClearStructuredInfo clears the value of the "structured_info" field. -func (m *CodeSnippetMutation) ClearStructuredInfo() { - m.structured_info = nil - m.clearedFields[codesnippet.FieldStructuredInfo] = struct{}{} +// AddStartLine adds i to the "start_line" field. +func (m *CodeSnippetMutation) AddStartLine(i int) { + if m.addstart_line != nil { + *m.addstart_line += i + } else { + m.addstart_line = &i + } } -// StructuredInfoCleared returns if the "structured_info" field was cleared in this mutation. -func (m *CodeSnippetMutation) StructuredInfoCleared() bool { - _, ok := m.clearedFields[codesnippet.FieldStructuredInfo] - return ok +// AddedStartLine returns the value that was added to the "start_line" field in this mutation. +func (m *CodeSnippetMutation) AddedStartLine() (r int, exists bool) { + v := m.addstart_line + if v == nil { + return + } + return *v, true } -// ResetStructuredInfo resets all changes to the "structured_info" field. -func (m *CodeSnippetMutation) ResetStructuredInfo() { - m.structured_info = nil - delete(m.clearedFields, codesnippet.FieldStructuredInfo) +// ResetStartLine resets all changes to the "start_line" field. +func (m *CodeSnippetMutation) ResetStartLine() { + m.start_line = nil + m.addstart_line = nil } -// SetEmbedding sets the "embedding" field. -func (m *CodeSnippetMutation) SetEmbedding(pg pgvector.Vector) { - m.embedding = &pg +// SetEndLine sets the "end_line" field. +func (m *CodeSnippetMutation) SetEndLine(i int) { + m.end_line = &i + m.addend_line = nil } -// Embedding returns the value of the "embedding" field in the mutation. -func (m *CodeSnippetMutation) Embedding() (r pgvector.Vector, exists bool) { - v := m.embedding +// EndLine returns the value of the "end_line" field in the mutation. +func (m *CodeSnippetMutation) EndLine() (r int, exists bool) { + v := m.end_line if v == nil { return } return *v, true } -// OldEmbedding returns the old "embedding" field's value of the CodeSnippet entity. +// OldEndLine returns the old "end_line" field's value of the CodeSnippet entity. // If the CodeSnippet object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *CodeSnippetMutation) OldEmbedding(ctx context.Context) (v pgvector.Vector, err error) { +func (m *CodeSnippetMutation) OldEndLine(ctx context.Context) (v int, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldEmbedding is only allowed on UpdateOne operations") + return v, errors.New("OldEndLine is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldEmbedding requires an ID field in the mutation") + return v, errors.New("OldEndLine requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldEmbedding: %w", err) + return v, fmt.Errorf("querying old value for OldEndLine: %w", err) } - return oldValue.Embedding, nil + return oldValue.EndLine, nil } -// ClearEmbedding clears the value of the "embedding" field. -func (m *CodeSnippetMutation) ClearEmbedding() { - m.embedding = nil - m.clearedFields[codesnippet.FieldEmbedding] = struct{}{} +// AddEndLine adds i to the "end_line" field. +func (m *CodeSnippetMutation) AddEndLine(i int) { + if m.addend_line != nil { + *m.addend_line += i + } else { + m.addend_line = &i + } } -// EmbeddingCleared returns if the "embedding" field was cleared in this mutation. -func (m *CodeSnippetMutation) EmbeddingCleared() bool { - _, ok := m.clearedFields[codesnippet.FieldEmbedding] - return ok +// AddedEndLine returns the value that was added to the "end_line" field in this mutation. +func (m *CodeSnippetMutation) AddedEndLine() (r int, exists bool) { + v := m.addend_line + if v == nil { + return + } + return *v, true } -// ResetEmbedding resets all changes to the "embedding" field. -func (m *CodeSnippetMutation) ResetEmbedding() { - m.embedding = nil - delete(m.clearedFields, codesnippet.FieldEmbedding) +// ResetEndLine resets all changes to the "end_line" field. +func (m *CodeSnippetMutation) ResetEndLine() { + m.end_line = nil + m.addend_line = nil } -// SetWorkspacePath sets the "workspacePath" field. -func (m *CodeSnippetMutation) SetWorkspacePath(s string) { - m.workspacePath = &s +// SetStartColumn sets the "start_column" field. +func (m *CodeSnippetMutation) SetStartColumn(i int) { + m.start_column = &i + m.addstart_column = nil } -// WorkspacePath returns the value of the "workspacePath" field in the mutation. -func (m *CodeSnippetMutation) WorkspacePath() (r string, exists bool) { - v := m.workspacePath +// StartColumn returns the value of the "start_column" field in the mutation. +func (m *CodeSnippetMutation) StartColumn() (r int, exists bool) { + v := m.start_column if v == nil { return } return *v, true } -// OldWorkspacePath returns the old "workspacePath" field's value of the CodeSnippet entity. +// OldStartColumn returns the old "start_column" field's value of the CodeSnippet entity. // If the CodeSnippet object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *CodeSnippetMutation) OldWorkspacePath(ctx context.Context) (v string, err error) { +func (m *CodeSnippetMutation) OldStartColumn(ctx context.Context) (v int, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldWorkspacePath is only allowed on UpdateOne operations") + return v, errors.New("OldStartColumn is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldWorkspacePath requires an ID field in the mutation") + return v, errors.New("OldStartColumn requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldWorkspacePath: %w", err) + return v, fmt.Errorf("querying old value for OldStartColumn: %w", err) } - return oldValue.WorkspacePath, nil -} - -// ClearWorkspacePath clears the value of the "workspacePath" field. -func (m *CodeSnippetMutation) ClearWorkspacePath() { - m.workspacePath = nil - m.clearedFields[codesnippet.FieldWorkspacePath] = struct{}{} + return oldValue.StartColumn, nil } -// WorkspacePathCleared returns if the "workspacePath" field was cleared in this mutation. -func (m *CodeSnippetMutation) WorkspacePathCleared() bool { - _, ok := m.clearedFields[codesnippet.FieldWorkspacePath] - return ok +// AddStartColumn adds i to the "start_column" field. +func (m *CodeSnippetMutation) AddStartColumn(i int) { + if m.addstart_column != nil { + *m.addstart_column += i + } else { + m.addstart_column = &i + } } -// ResetWorkspacePath resets all changes to the "workspacePath" field. -func (m *CodeSnippetMutation) ResetWorkspacePath() { - m.workspacePath = nil - delete(m.clearedFields, codesnippet.FieldWorkspacePath) +// AddedStartColumn returns the value that was added to the "start_column" field in this mutation. +func (m *CodeSnippetMutation) AddedStartColumn() (r int, exists bool) { + v := m.addstart_column + if v == nil { + return + } + return *v, true } -// SetSourceFileID sets the "source_file" edge to the WorkspaceFile entity by id. -func (m *CodeSnippetMutation) SetSourceFileID(id uuid.UUID) { - m.source_file = &id +// ResetStartColumn resets all changes to the "start_column" field. +func (m *CodeSnippetMutation) ResetStartColumn() { + m.start_column = nil + m.addstart_column = nil } -// ClearSourceFile clears the "source_file" edge to the WorkspaceFile entity. -func (m *CodeSnippetMutation) ClearSourceFile() { - m.clearedsource_file = true - m.clearedFields[codesnippet.FieldWorkspaceFileID] = struct{}{} +// SetEndColumn sets the "end_column" field. +func (m *CodeSnippetMutation) SetEndColumn(i int) { + m.end_column = &i + m.addend_column = nil } -// SourceFileCleared reports if the "source_file" edge to the WorkspaceFile entity was cleared. -func (m *CodeSnippetMutation) SourceFileCleared() bool { - return m.clearedsource_file +// EndColumn returns the value of the "end_column" field in the mutation. +func (m *CodeSnippetMutation) EndColumn() (r int, exists bool) { + v := m.end_column + if v == nil { + return + } + return *v, true } -// SourceFileID returns the "source_file" edge ID in the mutation. -func (m *CodeSnippetMutation) SourceFileID() (id uuid.UUID, exists bool) { - if m.source_file != nil { - return *m.source_file, true +// OldEndColumn returns the old "end_column" field's value of the CodeSnippet entity. +// If the CodeSnippet object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *CodeSnippetMutation) OldEndColumn(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEndColumn is only allowed on UpdateOne operations") } - return + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEndColumn requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEndColumn: %w", err) + } + return oldValue.EndColumn, nil } -// SourceFileIDs returns the "source_file" edge IDs in the mutation. -// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// SourceFileID instead. It exists only for internal usage by the builders. -func (m *CodeSnippetMutation) SourceFileIDs() (ids []uuid.UUID) { - if id := m.source_file; id != nil { - ids = append(ids, *id) +// AddEndColumn adds i to the "end_column" field. +func (m *CodeSnippetMutation) AddEndColumn(i int) { + if m.addend_column != nil { + *m.addend_column += i + } else { + m.addend_column = &i } - return } -// ResetSourceFile resets all changes to the "source_file" edge. -func (m *CodeSnippetMutation) ResetSourceFile() { - m.source_file = nil - m.clearedsource_file = false +// AddedEndColumn returns the value that was added to the "end_column" field in this mutation. +func (m *CodeSnippetMutation) AddedEndColumn() (r int, exists bool) { + v := m.addend_column + if v == nil { + return + } + return *v, true } -// Where appends a list predicates to the CodeSnippetMutation builder. -func (m *CodeSnippetMutation) Where(ps ...predicate.CodeSnippet) { - m.predicates = append(m.predicates, ps...) +// ResetEndColumn resets all changes to the "end_column" field. +func (m *CodeSnippetMutation) ResetEndColumn() { + m.end_column = nil + m.addend_column = nil } -// WhereP appends storage-level predicates to the CodeSnippetMutation builder. Using this method, -// users can use type-assertion to append predicates that do not depend on any generated package. -func (m *CodeSnippetMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.CodeSnippet, len(ps)) - for i := range ps { - p[i] = ps[i] +// SetNamespace sets the "namespace" field. +func (m *CodeSnippetMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *CodeSnippetMutation) Namespace() (r string, exists bool) { + v := m.namespace + if v == nil { + return } - m.Where(p...) + return *v, true } -// Op returns the operation name. -func (m *CodeSnippetMutation) Op() Op { - return m.op +// OldNamespace returns the old "namespace" field's value of the CodeSnippet entity. +// If the CodeSnippet object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *CodeSnippetMutation) OldNamespace(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldNamespace is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldNamespace requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldNamespace: %w", err) + } + return oldValue.Namespace, nil } -// SetOp allows setting the mutation operation. -func (m *CodeSnippetMutation) SetOp(op Op) { - m.op = op +// ClearNamespace clears the value of the "namespace" field. +func (m *CodeSnippetMutation) ClearNamespace() { + m.namespace = nil + m.clearedFields[codesnippet.FieldNamespace] = struct{}{} } -// Type returns the node type of this mutation (CodeSnippet). -func (m *CodeSnippetMutation) Type() string { - return m.typ +// NamespaceCleared returns if the "namespace" field was cleared in this mutation. +func (m *CodeSnippetMutation) NamespaceCleared() bool { + _, ok := m.clearedFields[codesnippet.FieldNamespace] + return ok } -// Fields returns all fields that were changed during this mutation. Note that in -// order to get all numeric fields that were incremented/decremented, call -// AddedFields(). -func (m *CodeSnippetMutation) Fields() []string { - fields := make([]string, 0, 20) - if m.source_file != nil { - fields = append(fields, codesnippet.FieldWorkspaceFileID) +// ResetNamespace resets all changes to the "namespace" field. +func (m *CodeSnippetMutation) ResetNamespace() { + m.namespace = nil + delete(m.clearedFields, codesnippet.FieldNamespace) +} + +// SetContainerName sets the "container_name" field. +func (m *CodeSnippetMutation) SetContainerName(s string) { + m.container_name = &s +} + +// ContainerName returns the value of the "container_name" field in the mutation. +func (m *CodeSnippetMutation) ContainerName() (r string, exists bool) { + v := m.container_name + if v == nil { + return } - if m.name != nil { - fields = append(fields, codesnippet.FieldName) + return *v, true +} + +// OldContainerName returns the old "container_name" field's value of the CodeSnippet entity. +// If the CodeSnippet object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *CodeSnippetMutation) OldContainerName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldContainerName is only allowed on UpdateOne operations") } - if m.snippet_type != nil { - fields = append(fields, codesnippet.FieldSnippetType) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldContainerName requires an ID field in the mutation") } - if m.language != nil { - fields = append(fields, codesnippet.FieldLanguage) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldContainerName: %w", err) } - if m.content != nil { - fields = append(fields, codesnippet.FieldContent) + return oldValue.ContainerName, nil +} + +// ClearContainerName clears the value of the "container_name" field. +func (m *CodeSnippetMutation) ClearContainerName() { + m.container_name = nil + m.clearedFields[codesnippet.FieldContainerName] = struct{}{} +} + +// ContainerNameCleared returns if the "container_name" field was cleared in this mutation. +func (m *CodeSnippetMutation) ContainerNameCleared() bool { + _, ok := m.clearedFields[codesnippet.FieldContainerName] + return ok +} + +// ResetContainerName resets all changes to the "container_name" field. +func (m *CodeSnippetMutation) ResetContainerName() { + m.container_name = nil + delete(m.clearedFields, codesnippet.FieldContainerName) +} + +// SetScope sets the "scope" field. +func (m *CodeSnippetMutation) SetScope(s []string) { + m.scope = &s + m.appendscope = nil +} + +// Scope returns the value of the "scope" field in the mutation. +func (m *CodeSnippetMutation) Scope() (r []string, exists bool) { + v := m.scope + if v == nil { + return } - if m.hash != nil { - fields = append(fields, codesnippet.FieldHash) + return *v, true +} + +// OldScope returns the old "scope" field's value of the CodeSnippet entity. +// If the CodeSnippet object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *CodeSnippetMutation) OldScope(ctx context.Context) (v []string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldScope is only allowed on UpdateOne operations") } - if m.start_line != nil { - fields = append(fields, codesnippet.FieldStartLine) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldScope requires an ID field in the mutation") } - if m.end_line != nil { - fields = append(fields, codesnippet.FieldEndLine) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldScope: %w", err) } - if m.start_column != nil { - fields = append(fields, codesnippet.FieldStartColumn) + return oldValue.Scope, nil +} + +// AppendScope adds s to the "scope" field. +func (m *CodeSnippetMutation) AppendScope(s []string) { + m.appendscope = append(m.appendscope, s...) +} + +// AppendedScope returns the list of values that were appended to the "scope" field in this mutation. +func (m *CodeSnippetMutation) AppendedScope() ([]string, bool) { + if len(m.appendscope) == 0 { + return nil, false } - if m.end_column != nil { - fields = append(fields, codesnippet.FieldEndColumn) - } - if m.namespace != nil { - fields = append(fields, codesnippet.FieldNamespace) - } - if m.container_name != nil { - fields = append(fields, codesnippet.FieldContainerName) + return m.appendscope, true +} + +// ClearScope clears the value of the "scope" field. +func (m *CodeSnippetMutation) ClearScope() { + m.scope = nil + m.appendscope = nil + m.clearedFields[codesnippet.FieldScope] = struct{}{} +} + +// ScopeCleared returns if the "scope" field was cleared in this mutation. +func (m *CodeSnippetMutation) ScopeCleared() bool { + _, ok := m.clearedFields[codesnippet.FieldScope] + return ok +} + +// ResetScope resets all changes to the "scope" field. +func (m *CodeSnippetMutation) ResetScope() { + m.scope = nil + m.appendscope = nil + delete(m.clearedFields, codesnippet.FieldScope) +} + +// SetDependencies sets the "dependencies" field. +func (m *CodeSnippetMutation) SetDependencies(s []string) { + m.dependencies = &s + m.appenddependencies = nil +} + +// Dependencies returns the value of the "dependencies" field in the mutation. +func (m *CodeSnippetMutation) Dependencies() (r []string, exists bool) { + v := m.dependencies + if v == nil { + return } - if m.scope != nil { - fields = append(fields, codesnippet.FieldScope) + return *v, true +} + +// OldDependencies returns the old "dependencies" field's value of the CodeSnippet entity. +// If the CodeSnippet object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *CodeSnippetMutation) OldDependencies(ctx context.Context) (v []string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDependencies is only allowed on UpdateOne operations") } - if m.dependencies != nil { - fields = append(fields, codesnippet.FieldDependencies) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDependencies requires an ID field in the mutation") } - if m.parameters != nil { - fields = append(fields, codesnippet.FieldParameters) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDependencies: %w", err) } - if m.signature != nil { - fields = append(fields, codesnippet.FieldSignature) + return oldValue.Dependencies, nil +} + +// AppendDependencies adds s to the "dependencies" field. +func (m *CodeSnippetMutation) AppendDependencies(s []string) { + m.appenddependencies = append(m.appenddependencies, s...) +} + +// AppendedDependencies returns the list of values that were appended to the "dependencies" field in this mutation. +func (m *CodeSnippetMutation) AppendedDependencies() ([]string, bool) { + if len(m.appenddependencies) == 0 { + return nil, false } - if m.definition_text != nil { - fields = append(fields, codesnippet.FieldDefinitionText) + return m.appenddependencies, true +} + +// ClearDependencies clears the value of the "dependencies" field. +func (m *CodeSnippetMutation) ClearDependencies() { + m.dependencies = nil + m.appenddependencies = nil + m.clearedFields[codesnippet.FieldDependencies] = struct{}{} +} + +// DependenciesCleared returns if the "dependencies" field was cleared in this mutation. +func (m *CodeSnippetMutation) DependenciesCleared() bool { + _, ok := m.clearedFields[codesnippet.FieldDependencies] + return ok +} + +// ResetDependencies resets all changes to the "dependencies" field. +func (m *CodeSnippetMutation) ResetDependencies() { + m.dependencies = nil + m.appenddependencies = nil + delete(m.clearedFields, codesnippet.FieldDependencies) +} + +// SetParameters sets the "parameters" field. +func (m *CodeSnippetMutation) SetParameters(value []map[string]interface{}) { + m.parameters = &value + m.appendparameters = nil +} + +// Parameters returns the value of the "parameters" field in the mutation. +func (m *CodeSnippetMutation) Parameters() (r []map[string]interface{}, exists bool) { + v := m.parameters + if v == nil { + return } - if m.structured_info != nil { - fields = append(fields, codesnippet.FieldStructuredInfo) + return *v, true +} + +// OldParameters returns the old "parameters" field's value of the CodeSnippet entity. +// If the CodeSnippet object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *CodeSnippetMutation) OldParameters(ctx context.Context) (v []map[string]interface{}, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldParameters is only allowed on UpdateOne operations") } - if m.embedding != nil { - fields = append(fields, codesnippet.FieldEmbedding) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldParameters requires an ID field in the mutation") } - if m.workspacePath != nil { - fields = append(fields, codesnippet.FieldWorkspacePath) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldParameters: %w", err) } - return fields + return oldValue.Parameters, nil } -// Field returns the value of a field with the given name. The second boolean -// return value indicates that this field was not set, or was not defined in the -// schema. -func (m *CodeSnippetMutation) Field(name string) (ent.Value, bool) { - switch name { - case codesnippet.FieldWorkspaceFileID: - return m.WorkspaceFileID() - case codesnippet.FieldName: - return m.Name() - case codesnippet.FieldSnippetType: - return m.SnippetType() - case codesnippet.FieldLanguage: - return m.Language() - case codesnippet.FieldContent: - return m.Content() - case codesnippet.FieldHash: - return m.Hash() - case codesnippet.FieldStartLine: - return m.StartLine() - case codesnippet.FieldEndLine: - return m.EndLine() - case codesnippet.FieldStartColumn: - return m.StartColumn() - case codesnippet.FieldEndColumn: - return m.EndColumn() - case codesnippet.FieldNamespace: - return m.Namespace() - case codesnippet.FieldContainerName: - return m.ContainerName() - case codesnippet.FieldScope: - return m.Scope() - case codesnippet.FieldDependencies: - return m.Dependencies() - case codesnippet.FieldParameters: - return m.Parameters() - case codesnippet.FieldSignature: - return m.Signature() - case codesnippet.FieldDefinitionText: - return m.DefinitionText() - case codesnippet.FieldStructuredInfo: - return m.StructuredInfo() - case codesnippet.FieldEmbedding: - return m.Embedding() - case codesnippet.FieldWorkspacePath: - return m.WorkspacePath() - } - return nil, false +// AppendParameters adds value to the "parameters" field. +func (m *CodeSnippetMutation) AppendParameters(value []map[string]interface{}) { + m.appendparameters = append(m.appendparameters, value...) } -// OldField returns the old value of the field from the database. An error is -// returned if the mutation operation is not UpdateOne, or the query to the -// database failed. -func (m *CodeSnippetMutation) OldField(ctx context.Context, name string) (ent.Value, error) { - switch name { - case codesnippet.FieldWorkspaceFileID: - return m.OldWorkspaceFileID(ctx) - case codesnippet.FieldName: - return m.OldName(ctx) - case codesnippet.FieldSnippetType: - return m.OldSnippetType(ctx) - case codesnippet.FieldLanguage: - return m.OldLanguage(ctx) - case codesnippet.FieldContent: - return m.OldContent(ctx) - case codesnippet.FieldHash: - return m.OldHash(ctx) - case codesnippet.FieldStartLine: - return m.OldStartLine(ctx) - case codesnippet.FieldEndLine: - return m.OldEndLine(ctx) - case codesnippet.FieldStartColumn: - return m.OldStartColumn(ctx) - case codesnippet.FieldEndColumn: - return m.OldEndColumn(ctx) - case codesnippet.FieldNamespace: - return m.OldNamespace(ctx) - case codesnippet.FieldContainerName: - return m.OldContainerName(ctx) - case codesnippet.FieldScope: - return m.OldScope(ctx) - case codesnippet.FieldDependencies: - return m.OldDependencies(ctx) - case codesnippet.FieldParameters: - return m.OldParameters(ctx) - case codesnippet.FieldSignature: - return m.OldSignature(ctx) - case codesnippet.FieldDefinitionText: - return m.OldDefinitionText(ctx) - case codesnippet.FieldStructuredInfo: - return m.OldStructuredInfo(ctx) - case codesnippet.FieldEmbedding: - return m.OldEmbedding(ctx) - case codesnippet.FieldWorkspacePath: - return m.OldWorkspacePath(ctx) +// AppendedParameters returns the list of values that were appended to the "parameters" field in this mutation. +func (m *CodeSnippetMutation) AppendedParameters() ([]map[string]interface{}, bool) { + if len(m.appendparameters) == 0 { + return nil, false } - return nil, fmt.Errorf("unknown CodeSnippet field %s", name) + return m.appendparameters, true } -// SetField sets the value of a field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *CodeSnippetMutation) SetField(name string, value ent.Value) error { - switch name { - case codesnippet.FieldWorkspaceFileID: - v, ok := value.(uuid.UUID) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetWorkspaceFileID(v) - return nil - case codesnippet.FieldName: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetName(v) - return nil - case codesnippet.FieldSnippetType: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetSnippetType(v) - return nil - case codesnippet.FieldLanguage: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetLanguage(v) - return nil - case codesnippet.FieldContent: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetContent(v) - return nil - case codesnippet.FieldHash: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetHash(v) - return nil - case codesnippet.FieldStartLine: - v, ok := value.(int) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetStartLine(v) - return nil - case codesnippet.FieldEndLine: - v, ok := value.(int) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetEndLine(v) - return nil - case codesnippet.FieldStartColumn: - v, ok := value.(int) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetStartColumn(v) - return nil - case codesnippet.FieldEndColumn: - v, ok := value.(int) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetEndColumn(v) - return nil - case codesnippet.FieldNamespace: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetNamespace(v) - return nil - case codesnippet.FieldContainerName: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetContainerName(v) - return nil - case codesnippet.FieldScope: - v, ok := value.([]string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetScope(v) - return nil - case codesnippet.FieldDependencies: - v, ok := value.([]string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetDependencies(v) - return nil - case codesnippet.FieldParameters: - v, ok := value.([]map[string]interface{}) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetParameters(v) - return nil - case codesnippet.FieldSignature: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetSignature(v) - return nil - case codesnippet.FieldDefinitionText: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetDefinitionText(v) - return nil - case codesnippet.FieldStructuredInfo: - v, ok := value.(map[string]interface{}) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetStructuredInfo(v) - return nil - case codesnippet.FieldEmbedding: - v, ok := value.(pgvector.Vector) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetEmbedding(v) - return nil - case codesnippet.FieldWorkspacePath: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetWorkspacePath(v) - return nil - } - return fmt.Errorf("unknown CodeSnippet field %s", name) +// ClearParameters clears the value of the "parameters" field. +func (m *CodeSnippetMutation) ClearParameters() { + m.parameters = nil + m.appendparameters = nil + m.clearedFields[codesnippet.FieldParameters] = struct{}{} } -// AddedFields returns all numeric fields that were incremented/decremented during -// this mutation. -func (m *CodeSnippetMutation) AddedFields() []string { - var fields []string - if m.addstart_line != nil { - fields = append(fields, codesnippet.FieldStartLine) +// ParametersCleared returns if the "parameters" field was cleared in this mutation. +func (m *CodeSnippetMutation) ParametersCleared() bool { + _, ok := m.clearedFields[codesnippet.FieldParameters] + return ok +} + +// ResetParameters resets all changes to the "parameters" field. +func (m *CodeSnippetMutation) ResetParameters() { + m.parameters = nil + m.appendparameters = nil + delete(m.clearedFields, codesnippet.FieldParameters) +} + +// SetSignature sets the "signature" field. +func (m *CodeSnippetMutation) SetSignature(s string) { + m.signature = &s +} + +// Signature returns the value of the "signature" field in the mutation. +func (m *CodeSnippetMutation) Signature() (r string, exists bool) { + v := m.signature + if v == nil { + return } - if m.addend_line != nil { - fields = append(fields, codesnippet.FieldEndLine) + return *v, true +} + +// OldSignature returns the old "signature" field's value of the CodeSnippet entity. +// If the CodeSnippet object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *CodeSnippetMutation) OldSignature(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSignature is only allowed on UpdateOne operations") } - if m.addstart_column != nil { - fields = append(fields, codesnippet.FieldStartColumn) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSignature requires an ID field in the mutation") } - if m.addend_column != nil { - fields = append(fields, codesnippet.FieldEndColumn) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSignature: %w", err) } - return fields + return oldValue.Signature, 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 *CodeSnippetMutation) AddedField(name string) (ent.Value, bool) { - switch name { - case codesnippet.FieldStartLine: - return m.AddedStartLine() - case codesnippet.FieldEndLine: - return m.AddedEndLine() - case codesnippet.FieldStartColumn: - return m.AddedStartColumn() - case codesnippet.FieldEndColumn: - return m.AddedEndColumn() - } - return nil, false +// ClearSignature clears the value of the "signature" field. +func (m *CodeSnippetMutation) ClearSignature() { + m.signature = nil + m.clearedFields[codesnippet.FieldSignature] = struct{}{} } -// AddField adds the value to the field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *CodeSnippetMutation) AddField(name string, value ent.Value) error { - switch name { - case codesnippet.FieldStartLine: - v, ok := value.(int) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddStartLine(v) - return nil - case codesnippet.FieldEndLine: - v, ok := value.(int) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddEndLine(v) - return nil - case codesnippet.FieldStartColumn: - v, ok := value.(int) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddStartColumn(v) - return nil - case codesnippet.FieldEndColumn: - v, ok := value.(int) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddEndColumn(v) - return nil +// SignatureCleared returns if the "signature" field was cleared in this mutation. +func (m *CodeSnippetMutation) SignatureCleared() bool { + _, ok := m.clearedFields[codesnippet.FieldSignature] + return ok +} + +// ResetSignature resets all changes to the "signature" field. +func (m *CodeSnippetMutation) ResetSignature() { + m.signature = nil + delete(m.clearedFields, codesnippet.FieldSignature) +} + +// SetDefinitionText sets the "definition_text" field. +func (m *CodeSnippetMutation) SetDefinitionText(s string) { + m.definition_text = &s +} + +// DefinitionText returns the value of the "definition_text" field in the mutation. +func (m *CodeSnippetMutation) DefinitionText() (r string, exists bool) { + v := m.definition_text + if v == nil { + return } - return fmt.Errorf("unknown CodeSnippet numeric field %s", name) + return *v, true } -// ClearedFields returns all nullable fields that were cleared during this -// mutation. -func (m *CodeSnippetMutation) ClearedFields() []string { - var fields []string - if m.FieldCleared(codesnippet.FieldNamespace) { - fields = append(fields, codesnippet.FieldNamespace) - } - if m.FieldCleared(codesnippet.FieldContainerName) { - fields = append(fields, codesnippet.FieldContainerName) - } - if m.FieldCleared(codesnippet.FieldScope) { - fields = append(fields, codesnippet.FieldScope) - } - if m.FieldCleared(codesnippet.FieldDependencies) { - fields = append(fields, codesnippet.FieldDependencies) - } - if m.FieldCleared(codesnippet.FieldParameters) { - fields = append(fields, codesnippet.FieldParameters) - } - if m.FieldCleared(codesnippet.FieldSignature) { - fields = append(fields, codesnippet.FieldSignature) - } - if m.FieldCleared(codesnippet.FieldDefinitionText) { - fields = append(fields, codesnippet.FieldDefinitionText) - } - if m.FieldCleared(codesnippet.FieldStructuredInfo) { - fields = append(fields, codesnippet.FieldStructuredInfo) +// OldDefinitionText returns the old "definition_text" field's value of the CodeSnippet entity. +// If the CodeSnippet object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *CodeSnippetMutation) OldDefinitionText(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDefinitionText is only allowed on UpdateOne operations") } - if m.FieldCleared(codesnippet.FieldEmbedding) { - fields = append(fields, codesnippet.FieldEmbedding) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDefinitionText requires an ID field in the mutation") } - if m.FieldCleared(codesnippet.FieldWorkspacePath) { - fields = append(fields, codesnippet.FieldWorkspacePath) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDefinitionText: %w", err) } - return fields + return oldValue.DefinitionText, nil } -// FieldCleared returns a boolean indicating if a field with the given name was -// cleared in this mutation. -func (m *CodeSnippetMutation) FieldCleared(name string) bool { - _, ok := m.clearedFields[name] +// ClearDefinitionText clears the value of the "definition_text" field. +func (m *CodeSnippetMutation) ClearDefinitionText() { + m.definition_text = nil + m.clearedFields[codesnippet.FieldDefinitionText] = struct{}{} +} + +// DefinitionTextCleared returns if the "definition_text" field was cleared in this mutation. +func (m *CodeSnippetMutation) DefinitionTextCleared() bool { + _, ok := m.clearedFields[codesnippet.FieldDefinitionText] return ok } -// ClearField clears the value of the field with the given name. It returns an -// error if the field is not defined in the schema. -func (m *CodeSnippetMutation) ClearField(name string) error { - switch name { - case codesnippet.FieldNamespace: - m.ClearNamespace() - return nil - case codesnippet.FieldContainerName: - m.ClearContainerName() - return nil - case codesnippet.FieldScope: - m.ClearScope() - return nil - case codesnippet.FieldDependencies: - m.ClearDependencies() - return nil - case codesnippet.FieldParameters: - m.ClearParameters() - return nil - case codesnippet.FieldSignature: - m.ClearSignature() - return nil - case codesnippet.FieldDefinitionText: - m.ClearDefinitionText() - return nil - case codesnippet.FieldStructuredInfo: - m.ClearStructuredInfo() - return nil - case codesnippet.FieldEmbedding: - m.ClearEmbedding() - return nil - case codesnippet.FieldWorkspacePath: - m.ClearWorkspacePath() - return nil - } - return fmt.Errorf("unknown CodeSnippet nullable field %s", name) +// ResetDefinitionText resets all changes to the "definition_text" field. +func (m *CodeSnippetMutation) ResetDefinitionText() { + m.definition_text = nil + delete(m.clearedFields, codesnippet.FieldDefinitionText) } -// ResetField resets all changes in the mutation for the field with the given name. -// It returns an error if the field is not defined in the schema. -func (m *CodeSnippetMutation) ResetField(name string) error { - switch name { - case codesnippet.FieldWorkspaceFileID: - m.ResetWorkspaceFileID() - return nil - case codesnippet.FieldName: - m.ResetName() - return nil - case codesnippet.FieldSnippetType: - m.ResetSnippetType() - return nil - case codesnippet.FieldLanguage: - m.ResetLanguage() - return nil - case codesnippet.FieldContent: - m.ResetContent() - return nil - case codesnippet.FieldHash: - m.ResetHash() - return nil - case codesnippet.FieldStartLine: - m.ResetStartLine() - return nil - case codesnippet.FieldEndLine: - m.ResetEndLine() - return nil - case codesnippet.FieldStartColumn: - m.ResetStartColumn() - return nil - case codesnippet.FieldEndColumn: - m.ResetEndColumn() - return nil - case codesnippet.FieldNamespace: - m.ResetNamespace() - return nil - case codesnippet.FieldContainerName: - m.ResetContainerName() - return nil - case codesnippet.FieldScope: - m.ResetScope() - return nil - case codesnippet.FieldDependencies: - m.ResetDependencies() - return nil - case codesnippet.FieldParameters: - m.ResetParameters() - return nil - case codesnippet.FieldSignature: - m.ResetSignature() - return nil - case codesnippet.FieldDefinitionText: - m.ResetDefinitionText() - return nil - case codesnippet.FieldStructuredInfo: - m.ResetStructuredInfo() - return nil - case codesnippet.FieldEmbedding: - m.ResetEmbedding() - return nil - case codesnippet.FieldWorkspacePath: - m.ResetWorkspacePath() - return nil - } - return fmt.Errorf("unknown CodeSnippet field %s", name) +// SetStructuredInfo sets the "structured_info" field. +func (m *CodeSnippetMutation) SetStructuredInfo(value map[string]interface{}) { + m.structured_info = &value } -// AddedEdges returns all edge names that were set/added in this mutation. -func (m *CodeSnippetMutation) AddedEdges() []string { - edges := make([]string, 0, 1) - if m.source_file != nil { - edges = append(edges, codesnippet.EdgeSourceFile) +// StructuredInfo returns the value of the "structured_info" field in the mutation. +func (m *CodeSnippetMutation) StructuredInfo() (r map[string]interface{}, exists bool) { + v := m.structured_info + if v == nil { + return } - return edges + return *v, true } -// AddedIDs returns all IDs (to other nodes) that were added for the given edge -// name in this mutation. -func (m *CodeSnippetMutation) AddedIDs(name string) []ent.Value { - switch name { - case codesnippet.EdgeSourceFile: - if id := m.source_file; id != nil { - return []ent.Value{*id} - } +// OldStructuredInfo returns the old "structured_info" field's value of the CodeSnippet entity. +// If the CodeSnippet object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *CodeSnippetMutation) OldStructuredInfo(ctx context.Context) (v map[string]interface{}, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldStructuredInfo is only allowed on UpdateOne operations") } - return nil + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldStructuredInfo requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldStructuredInfo: %w", err) + } + return oldValue.StructuredInfo, nil } -// RemovedEdges returns all edge names that were removed in this mutation. -func (m *CodeSnippetMutation) RemovedEdges() []string { - edges := make([]string, 0, 1) - return edges +// ClearStructuredInfo clears the value of the "structured_info" field. +func (m *CodeSnippetMutation) ClearStructuredInfo() { + m.structured_info = nil + m.clearedFields[codesnippet.FieldStructuredInfo] = struct{}{} } -// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with -// the given name in this mutation. -func (m *CodeSnippetMutation) RemovedIDs(name string) []ent.Value { - return nil +// StructuredInfoCleared returns if the "structured_info" field was cleared in this mutation. +func (m *CodeSnippetMutation) StructuredInfoCleared() bool { + _, ok := m.clearedFields[codesnippet.FieldStructuredInfo] + return ok } -// ClearedEdges returns all edge names that were cleared in this mutation. -func (m *CodeSnippetMutation) ClearedEdges() []string { - edges := make([]string, 0, 1) - if m.clearedsource_file { - edges = append(edges, codesnippet.EdgeSourceFile) - } - return edges +// ResetStructuredInfo resets all changes to the "structured_info" field. +func (m *CodeSnippetMutation) ResetStructuredInfo() { + m.structured_info = nil + delete(m.clearedFields, codesnippet.FieldStructuredInfo) } -// EdgeCleared returns a boolean which indicates if the edge with the given name -// was cleared in this mutation. -func (m *CodeSnippetMutation) EdgeCleared(name string) bool { - switch name { - case codesnippet.EdgeSourceFile: - return m.clearedsource_file - } - return false +// SetEmbedding sets the "embedding" field. +func (m *CodeSnippetMutation) SetEmbedding(pg pgvector.Vector) { + m.embedding = &pg } -// ClearEdge clears the value of the edge with the given name. It returns an error -// if that edge is not defined in the schema. -func (m *CodeSnippetMutation) ClearEdge(name string) error { - switch name { - case codesnippet.EdgeSourceFile: - m.ClearSourceFile() - return nil +// Embedding returns the value of the "embedding" field in the mutation. +func (m *CodeSnippetMutation) Embedding() (r pgvector.Vector, exists bool) { + v := m.embedding + if v == nil { + return } - return fmt.Errorf("unknown CodeSnippet unique edge %s", name) + return *v, true } -// ResetEdge resets all changes to the edge with the given name in this mutation. -// It returns an error if the edge is not defined in the schema. -func (m *CodeSnippetMutation) ResetEdge(name string) error { - switch name { - case codesnippet.EdgeSourceFile: - m.ResetSourceFile() - return nil - } - return fmt.Errorf("unknown CodeSnippet edge %s", name) -} - -// ExtensionMutation represents an operation that mutates the Extension nodes in the graph. -type ExtensionMutation struct { - config - op Op - typ string - id *uuid.UUID - version *string - _path *string - created_at *time.Time - clearedFields map[string]struct{} - done bool - oldValue func(context.Context) (*Extension, error) - predicates []predicate.Extension -} - -var _ ent.Mutation = (*ExtensionMutation)(nil) - -// extensionOption allows management of the mutation configuration using functional options. -type extensionOption func(*ExtensionMutation) - -// newExtensionMutation creates new mutation for the Extension entity. -func newExtensionMutation(c config, op Op, opts ...extensionOption) *ExtensionMutation { - m := &ExtensionMutation{ - config: c, - op: op, - typ: TypeExtension, - clearedFields: make(map[string]struct{}), - } - for _, opt := range opts { - opt(m) - } - return m -} - -// withExtensionID sets the ID field of the mutation. -func withExtensionID(id uuid.UUID) extensionOption { - return func(m *ExtensionMutation) { - var ( - err error - once sync.Once - value *Extension - ) - m.oldValue = func(ctx context.Context) (*Extension, error) { - once.Do(func() { - if m.done { - err = errors.New("querying old values post mutation is not allowed") - } else { - value, err = m.Client().Extension.Get(ctx, id) - } - }) - return value, err - } - m.id = &id +// OldEmbedding returns the old "embedding" field's value of the CodeSnippet entity. +// If the CodeSnippet object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *CodeSnippetMutation) OldEmbedding(ctx context.Context) (v pgvector.Vector, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEmbedding is only allowed on UpdateOne operations") } -} - -// withExtension sets the old Extension of the mutation. -func withExtension(node *Extension) extensionOption { - return func(m *ExtensionMutation) { - m.oldValue = func(context.Context) (*Extension, error) { - return node, nil - } - m.id = &node.ID + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEmbedding requires an ID field in the mutation") } -} - -// Client returns a new `ent.Client` from the mutation. If the mutation was -// executed in a transaction (ent.Tx), a transactional client is returned. -func (m ExtensionMutation) Client() *Client { - client := &Client{config: m.config} - client.init() - return client -} - -// Tx returns an `ent.Tx` for mutations that were executed in transactions; -// it returns an error otherwise. -func (m ExtensionMutation) Tx() (*Tx, error) { - if _, ok := m.driver.(*txDriver); !ok { - return nil, errors.New("db: mutation is not running in a transaction") + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEmbedding: %w", err) } - tx := &Tx{config: m.config} - tx.init() - return tx, nil + return oldValue.Embedding, nil } -// SetID sets the value of the id field. Note that this -// operation is only accepted on creation of Extension entities. -func (m *ExtensionMutation) SetID(id uuid.UUID) { - m.id = &id +// ClearEmbedding clears the value of the "embedding" field. +func (m *CodeSnippetMutation) ClearEmbedding() { + m.embedding = nil + m.clearedFields[codesnippet.FieldEmbedding] = struct{}{} } -// ID returns the ID value in the mutation. Note that the ID is only available -// if it was provided to the builder or after it was returned from the database. -func (m *ExtensionMutation) ID() (id uuid.UUID, exists bool) { - if m.id == nil { - return - } - return *m.id, true +// EmbeddingCleared returns if the "embedding" field was cleared in this mutation. +func (m *CodeSnippetMutation) EmbeddingCleared() bool { + _, ok := m.clearedFields[codesnippet.FieldEmbedding] + return ok } -// IDs queries the database and returns the entity ids that match the mutation's predicate. -// That means, if the mutation is applied within a transaction with an isolation level such -// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated -// or updated by the mutation. -func (m *ExtensionMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { - switch { - case m.op.Is(OpUpdateOne | OpDeleteOne): - id, exists := m.ID() - if exists { - return []uuid.UUID{id}, nil - } - fallthrough - case m.op.Is(OpUpdate | OpDelete): - return m.Client().Extension.Query().Where(m.predicates...).IDs(ctx) - default: - return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) - } +// ResetEmbedding resets all changes to the "embedding" field. +func (m *CodeSnippetMutation) ResetEmbedding() { + m.embedding = nil + delete(m.clearedFields, codesnippet.FieldEmbedding) } -// SetVersion sets the "version" field. -func (m *ExtensionMutation) SetVersion(s string) { - m.version = &s +// SetWorkspacePath sets the "workspacePath" field. +func (m *CodeSnippetMutation) SetWorkspacePath(s string) { + m.workspacePath = &s } -// Version returns the value of the "version" field in the mutation. -func (m *ExtensionMutation) Version() (r string, exists bool) { - v := m.version +// WorkspacePath returns the value of the "workspacePath" field in the mutation. +func (m *CodeSnippetMutation) WorkspacePath() (r string, exists bool) { + v := m.workspacePath if v == nil { return } return *v, true } -// OldVersion returns the old "version" field's value of the Extension entity. -// If the Extension object wasn't provided to the builder, the object is fetched from the database. +// OldWorkspacePath returns the old "workspacePath" field's value of the CodeSnippet entity. +// If the CodeSnippet object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *ExtensionMutation) OldVersion(ctx context.Context) (v string, err error) { +func (m *CodeSnippetMutation) OldWorkspacePath(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldVersion is only allowed on UpdateOne operations") + return v, errors.New("OldWorkspacePath 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") + return v, errors.New("OldWorkspacePath 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 v, fmt.Errorf("querying old value for OldWorkspacePath: %w", err) } - return oldValue.Version, nil + return oldValue.WorkspacePath, nil } -// ResetVersion resets all changes to the "version" field. -func (m *ExtensionMutation) ResetVersion() { - m.version = nil +// ClearWorkspacePath clears the value of the "workspacePath" field. +func (m *CodeSnippetMutation) ClearWorkspacePath() { + m.workspacePath = nil + m.clearedFields[codesnippet.FieldWorkspacePath] = struct{}{} } -// SetPath sets the "path" field. -func (m *ExtensionMutation) SetPath(s string) { - m._path = &s +// WorkspacePathCleared returns if the "workspacePath" field was cleared in this mutation. +func (m *CodeSnippetMutation) WorkspacePathCleared() bool { + _, ok := m.clearedFields[codesnippet.FieldWorkspacePath] + return ok } -// Path returns the value of the "path" field in the mutation. -func (m *ExtensionMutation) Path() (r string, exists bool) { - v := m._path - if v == nil { - return - } - return *v, true +// ResetWorkspacePath resets all changes to the "workspacePath" field. +func (m *CodeSnippetMutation) ResetWorkspacePath() { + m.workspacePath = nil + delete(m.clearedFields, codesnippet.FieldWorkspacePath) } -// OldPath returns the old "path" field's value of the Extension entity. -// If the Extension object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *ExtensionMutation) OldPath(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldPath is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldPath requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldPath: %w", err) - } - return oldValue.Path, nil +// SetSourceFileID sets the "source_file" edge to the WorkspaceFile entity by id. +func (m *CodeSnippetMutation) SetSourceFileID(id uuid.UUID) { + m.source_file = &id } -// ResetPath resets all changes to the "path" field. -func (m *ExtensionMutation) ResetPath() { - m._path = nil +// ClearSourceFile clears the "source_file" edge to the WorkspaceFile entity. +func (m *CodeSnippetMutation) ClearSourceFile() { + m.clearedsource_file = true + m.clearedFields[codesnippet.FieldWorkspaceFileID] = struct{}{} } -// SetCreatedAt sets the "created_at" field. -func (m *ExtensionMutation) SetCreatedAt(t time.Time) { - m.created_at = &t +// SourceFileCleared reports if the "source_file" edge to the WorkspaceFile entity was cleared. +func (m *CodeSnippetMutation) SourceFileCleared() bool { + return m.clearedsource_file } -// CreatedAt returns the value of the "created_at" field in the mutation. -func (m *ExtensionMutation) CreatedAt() (r time.Time, exists bool) { - v := m.created_at - if v == nil { - return +// SourceFileID returns the "source_file" edge ID in the mutation. +func (m *CodeSnippetMutation) SourceFileID() (id uuid.UUID, exists bool) { + if m.source_file != nil { + return *m.source_file, true } - return *v, true + return } -// OldCreatedAt returns the old "created_at" field's value of the Extension entity. -// If the Extension object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *ExtensionMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCreatedAt requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) +// SourceFileIDs returns the "source_file" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// SourceFileID instead. It exists only for internal usage by the builders. +func (m *CodeSnippetMutation) SourceFileIDs() (ids []uuid.UUID) { + if id := m.source_file; id != nil { + ids = append(ids, *id) } - return oldValue.CreatedAt, nil + return } -// ResetCreatedAt resets all changes to the "created_at" field. -func (m *ExtensionMutation) ResetCreatedAt() { - m.created_at = nil +// ResetSourceFile resets all changes to the "source_file" edge. +func (m *CodeSnippetMutation) ResetSourceFile() { + m.source_file = nil + m.clearedsource_file = false } -// Where appends a list predicates to the ExtensionMutation builder. -func (m *ExtensionMutation) Where(ps ...predicate.Extension) { +// Where appends a list predicates to the CodeSnippetMutation builder. +func (m *CodeSnippetMutation) Where(ps ...predicate.CodeSnippet) { m.predicates = append(m.predicates, ps...) } -// WhereP appends storage-level predicates to the ExtensionMutation builder. Using this method, +// WhereP appends storage-level predicates to the CodeSnippetMutation builder. Using this method, // users can use type-assertion to append predicates that do not depend on any generated package. -func (m *ExtensionMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.Extension, len(ps)) +func (m *CodeSnippetMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.CodeSnippet, len(ps)) for i := range ps { p[i] = ps[i] } @@ -7550,33 +7595,84 @@ func (m *ExtensionMutation) WhereP(ps ...func(*sql.Selector)) { } // Op returns the operation name. -func (m *ExtensionMutation) Op() Op { +func (m *CodeSnippetMutation) Op() Op { return m.op } // SetOp allows setting the mutation operation. -func (m *ExtensionMutation) SetOp(op Op) { +func (m *CodeSnippetMutation) SetOp(op Op) { m.op = op } -// Type returns the node type of this mutation (Extension). -func (m *ExtensionMutation) Type() string { +// Type returns the node type of this mutation (CodeSnippet). +func (m *CodeSnippetMutation) Type() string { return m.typ } // Fields returns all fields that were changed during this mutation. Note that in // order to get all numeric fields that were incremented/decremented, call // AddedFields(). -func (m *ExtensionMutation) Fields() []string { - fields := make([]string, 0, 3) - if m.version != nil { - fields = append(fields, extension.FieldVersion) +func (m *CodeSnippetMutation) Fields() []string { + fields := make([]string, 0, 20) + if m.source_file != nil { + fields = append(fields, codesnippet.FieldWorkspaceFileID) } - if m._path != nil { - fields = append(fields, extension.FieldPath) + if m.name != nil { + fields = append(fields, codesnippet.FieldName) } - if m.created_at != nil { - fields = append(fields, extension.FieldCreatedAt) + if m.snippet_type != nil { + fields = append(fields, codesnippet.FieldSnippetType) + } + if m.language != nil { + fields = append(fields, codesnippet.FieldLanguage) + } + if m.content != nil { + fields = append(fields, codesnippet.FieldContent) + } + if m.hash != nil { + fields = append(fields, codesnippet.FieldHash) + } + if m.start_line != nil { + fields = append(fields, codesnippet.FieldStartLine) + } + if m.end_line != nil { + fields = append(fields, codesnippet.FieldEndLine) + } + if m.start_column != nil { + fields = append(fields, codesnippet.FieldStartColumn) + } + if m.end_column != nil { + fields = append(fields, codesnippet.FieldEndColumn) + } + if m.namespace != nil { + fields = append(fields, codesnippet.FieldNamespace) + } + if m.container_name != nil { + fields = append(fields, codesnippet.FieldContainerName) + } + if m.scope != nil { + fields = append(fields, codesnippet.FieldScope) + } + if m.dependencies != nil { + fields = append(fields, codesnippet.FieldDependencies) + } + if m.parameters != nil { + fields = append(fields, codesnippet.FieldParameters) + } + if m.signature != nil { + fields = append(fields, codesnippet.FieldSignature) + } + if m.definition_text != nil { + fields = append(fields, codesnippet.FieldDefinitionText) + } + if m.structured_info != nil { + fields = append(fields, codesnippet.FieldStructuredInfo) + } + if m.embedding != nil { + fields = append(fields, codesnippet.FieldEmbedding) + } + if m.workspacePath != nil { + fields = append(fields, codesnippet.FieldWorkspacePath) } return fields } @@ -7584,14 +7680,48 @@ func (m *ExtensionMutation) Fields() []string { // Field returns the value of a field with the given name. The second boolean // return value indicates that this field was not set, or was not defined in the // schema. -func (m *ExtensionMutation) Field(name string) (ent.Value, bool) { +func (m *CodeSnippetMutation) Field(name string) (ent.Value, bool) { switch name { - case extension.FieldVersion: - return m.Version() - case extension.FieldPath: - return m.Path() - case extension.FieldCreatedAt: - return m.CreatedAt() + case codesnippet.FieldWorkspaceFileID: + return m.WorkspaceFileID() + case codesnippet.FieldName: + return m.Name() + case codesnippet.FieldSnippetType: + return m.SnippetType() + case codesnippet.FieldLanguage: + return m.Language() + case codesnippet.FieldContent: + return m.Content() + case codesnippet.FieldHash: + return m.Hash() + case codesnippet.FieldStartLine: + return m.StartLine() + case codesnippet.FieldEndLine: + return m.EndLine() + case codesnippet.FieldStartColumn: + return m.StartColumn() + case codesnippet.FieldEndColumn: + return m.EndColumn() + case codesnippet.FieldNamespace: + return m.Namespace() + case codesnippet.FieldContainerName: + return m.ContainerName() + case codesnippet.FieldScope: + return m.Scope() + case codesnippet.FieldDependencies: + return m.Dependencies() + case codesnippet.FieldParameters: + return m.Parameters() + case codesnippet.FieldSignature: + return m.Signature() + case codesnippet.FieldDefinitionText: + return m.DefinitionText() + case codesnippet.FieldStructuredInfo: + return m.StructuredInfo() + case codesnippet.FieldEmbedding: + return m.Embedding() + case codesnippet.FieldWorkspacePath: + return m.WorkspacePath() } return nil, false } @@ -7599,183 +7729,524 @@ func (m *ExtensionMutation) Field(name string) (ent.Value, bool) { // OldField returns the old value of the field from the database. An error is // returned if the mutation operation is not UpdateOne, or the query to the // database failed. -func (m *ExtensionMutation) OldField(ctx context.Context, name string) (ent.Value, error) { +func (m *CodeSnippetMutation) OldField(ctx context.Context, name string) (ent.Value, error) { switch name { - case extension.FieldVersion: - return m.OldVersion(ctx) - case extension.FieldPath: - return m.OldPath(ctx) - case extension.FieldCreatedAt: - return m.OldCreatedAt(ctx) + case codesnippet.FieldWorkspaceFileID: + return m.OldWorkspaceFileID(ctx) + case codesnippet.FieldName: + return m.OldName(ctx) + case codesnippet.FieldSnippetType: + return m.OldSnippetType(ctx) + case codesnippet.FieldLanguage: + return m.OldLanguage(ctx) + case codesnippet.FieldContent: + return m.OldContent(ctx) + case codesnippet.FieldHash: + return m.OldHash(ctx) + case codesnippet.FieldStartLine: + return m.OldStartLine(ctx) + case codesnippet.FieldEndLine: + return m.OldEndLine(ctx) + case codesnippet.FieldStartColumn: + return m.OldStartColumn(ctx) + case codesnippet.FieldEndColumn: + return m.OldEndColumn(ctx) + case codesnippet.FieldNamespace: + return m.OldNamespace(ctx) + case codesnippet.FieldContainerName: + return m.OldContainerName(ctx) + case codesnippet.FieldScope: + return m.OldScope(ctx) + case codesnippet.FieldDependencies: + return m.OldDependencies(ctx) + case codesnippet.FieldParameters: + return m.OldParameters(ctx) + case codesnippet.FieldSignature: + return m.OldSignature(ctx) + case codesnippet.FieldDefinitionText: + return m.OldDefinitionText(ctx) + case codesnippet.FieldStructuredInfo: + return m.OldStructuredInfo(ctx) + case codesnippet.FieldEmbedding: + return m.OldEmbedding(ctx) + case codesnippet.FieldWorkspacePath: + return m.OldWorkspacePath(ctx) } - return nil, fmt.Errorf("unknown Extension field %s", name) + return nil, fmt.Errorf("unknown CodeSnippet field %s", name) } // SetField sets the value of a field with the given name. It returns an error if // the field is not defined in the schema, or if the type mismatched the field // type. -func (m *ExtensionMutation) SetField(name string, value ent.Value) error { +func (m *CodeSnippetMutation) SetField(name string, value ent.Value) error { switch name { - case extension.FieldVersion: + case codesnippet.FieldWorkspaceFileID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetWorkspaceFileID(v) + return nil + case codesnippet.FieldName: v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetVersion(v) + m.SetName(v) return nil - case extension.FieldPath: + case codesnippet.FieldSnippetType: v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetPath(v) + m.SetSnippetType(v) return nil - case extension.FieldCreatedAt: - v, ok := value.(time.Time) + case codesnippet.FieldLanguage: + v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetCreatedAt(v) + m.SetLanguage(v) return nil - } - return fmt.Errorf("unknown Extension field %s", name) -} - -// AddedFields returns all numeric fields that were incremented/decremented during -// this mutation. -func (m *ExtensionMutation) AddedFields() []string { - return nil -} - -// AddedField returns the numeric value that was incremented/decremented on a field -// with the given name. The second boolean return value indicates that this field -// was not set, or was not defined in the schema. -func (m *ExtensionMutation) AddedField(name string) (ent.Value, bool) { - return nil, false -} - -// AddField adds the value to the field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *ExtensionMutation) AddField(name string, value ent.Value) error { - switch name { - } - return fmt.Errorf("unknown Extension numeric field %s", name) -} - -// ClearedFields returns all nullable fields that were cleared during this -// mutation. -func (m *ExtensionMutation) ClearedFields() []string { - return nil -} - -// FieldCleared returns a boolean indicating if a field with the given name was -// cleared in this mutation. -func (m *ExtensionMutation) FieldCleared(name string) bool { - _, ok := m.clearedFields[name] - return ok -} - -// ClearField clears the value of the field with the given name. It returns an -// error if the field is not defined in the schema. -func (m *ExtensionMutation) ClearField(name string) error { - return fmt.Errorf("unknown Extension nullable field %s", name) -} - -// ResetField resets all changes in the mutation for the field with the given name. -// It returns an error if the field is not defined in the schema. -func (m *ExtensionMutation) ResetField(name string) error { - switch name { - case extension.FieldVersion: - m.ResetVersion() + case codesnippet.FieldContent: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetContent(v) return nil - case extension.FieldPath: - m.ResetPath() + case codesnippet.FieldHash: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetHash(v) return nil - case extension.FieldCreatedAt: - m.ResetCreatedAt() + case codesnippet.FieldStartLine: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStartLine(v) + return nil + case codesnippet.FieldEndLine: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEndLine(v) + return nil + case codesnippet.FieldStartColumn: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStartColumn(v) + return nil + case codesnippet.FieldEndColumn: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEndColumn(v) + return nil + case codesnippet.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case codesnippet.FieldContainerName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetContainerName(v) + return nil + case codesnippet.FieldScope: + v, ok := value.([]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetScope(v) + return nil + case codesnippet.FieldDependencies: + v, ok := value.([]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDependencies(v) + return nil + case codesnippet.FieldParameters: + v, ok := value.([]map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetParameters(v) + return nil + case codesnippet.FieldSignature: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSignature(v) + return nil + case codesnippet.FieldDefinitionText: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDefinitionText(v) + return nil + case codesnippet.FieldStructuredInfo: + v, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStructuredInfo(v) + return nil + case codesnippet.FieldEmbedding: + v, ok := value.(pgvector.Vector) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEmbedding(v) + return nil + case codesnippet.FieldWorkspacePath: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetWorkspacePath(v) return nil } - return fmt.Errorf("unknown Extension field %s", name) -} - -// AddedEdges returns all edge names that were set/added in this mutation. -func (m *ExtensionMutation) AddedEdges() []string { - edges := make([]string, 0, 0) - return edges + return fmt.Errorf("unknown CodeSnippet field %s", name) } -// AddedIDs returns all IDs (to other nodes) that were added for the given edge -// name in this mutation. -func (m *ExtensionMutation) AddedIDs(name string) []ent.Value { - return nil +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *CodeSnippetMutation) AddedFields() []string { + var fields []string + if m.addstart_line != nil { + fields = append(fields, codesnippet.FieldStartLine) + } + if m.addend_line != nil { + fields = append(fields, codesnippet.FieldEndLine) + } + if m.addstart_column != nil { + fields = append(fields, codesnippet.FieldStartColumn) + } + if m.addend_column != nil { + fields = append(fields, codesnippet.FieldEndColumn) + } + return fields } -// RemovedEdges returns all edge names that were removed in this mutation. -func (m *ExtensionMutation) RemovedEdges() []string { - edges := make([]string, 0, 0) - return edges +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *CodeSnippetMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case codesnippet.FieldStartLine: + return m.AddedStartLine() + case codesnippet.FieldEndLine: + return m.AddedEndLine() + case codesnippet.FieldStartColumn: + return m.AddedStartColumn() + case codesnippet.FieldEndColumn: + return m.AddedEndColumn() + } + return nil, false } -// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with -// the given name in this mutation. -func (m *ExtensionMutation) RemovedIDs(name string) []ent.Value { - return nil +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *CodeSnippetMutation) AddField(name string, value ent.Value) error { + switch name { + case codesnippet.FieldStartLine: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddStartLine(v) + return nil + case codesnippet.FieldEndLine: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddEndLine(v) + return nil + case codesnippet.FieldStartColumn: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddStartColumn(v) + return nil + case codesnippet.FieldEndColumn: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddEndColumn(v) + return nil + } + return fmt.Errorf("unknown CodeSnippet numeric field %s", name) } -// ClearedEdges returns all edge names that were cleared in this mutation. -func (m *ExtensionMutation) ClearedEdges() []string { - edges := make([]string, 0, 0) - return edges +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *CodeSnippetMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(codesnippet.FieldNamespace) { + fields = append(fields, codesnippet.FieldNamespace) + } + if m.FieldCleared(codesnippet.FieldContainerName) { + fields = append(fields, codesnippet.FieldContainerName) + } + if m.FieldCleared(codesnippet.FieldScope) { + fields = append(fields, codesnippet.FieldScope) + } + if m.FieldCleared(codesnippet.FieldDependencies) { + fields = append(fields, codesnippet.FieldDependencies) + } + if m.FieldCleared(codesnippet.FieldParameters) { + fields = append(fields, codesnippet.FieldParameters) + } + if m.FieldCleared(codesnippet.FieldSignature) { + fields = append(fields, codesnippet.FieldSignature) + } + if m.FieldCleared(codesnippet.FieldDefinitionText) { + fields = append(fields, codesnippet.FieldDefinitionText) + } + if m.FieldCleared(codesnippet.FieldStructuredInfo) { + fields = append(fields, codesnippet.FieldStructuredInfo) + } + if m.FieldCleared(codesnippet.FieldEmbedding) { + fields = append(fields, codesnippet.FieldEmbedding) + } + if m.FieldCleared(codesnippet.FieldWorkspacePath) { + fields = append(fields, codesnippet.FieldWorkspacePath) + } + return fields } -// EdgeCleared returns a boolean which indicates if the edge with the given name -// was cleared in this mutation. -func (m *ExtensionMutation) EdgeCleared(name string) bool { - return false +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *CodeSnippetMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok } -// ClearEdge clears the value of the edge with the given name. It returns an error -// if that edge is not defined in the schema. -func (m *ExtensionMutation) ClearEdge(name string) error { - return fmt.Errorf("unknown Extension unique edge %s", name) +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *CodeSnippetMutation) ClearField(name string) error { + switch name { + case codesnippet.FieldNamespace: + m.ClearNamespace() + return nil + case codesnippet.FieldContainerName: + m.ClearContainerName() + return nil + case codesnippet.FieldScope: + m.ClearScope() + return nil + case codesnippet.FieldDependencies: + m.ClearDependencies() + return nil + case codesnippet.FieldParameters: + m.ClearParameters() + return nil + case codesnippet.FieldSignature: + m.ClearSignature() + return nil + case codesnippet.FieldDefinitionText: + m.ClearDefinitionText() + return nil + case codesnippet.FieldStructuredInfo: + m.ClearStructuredInfo() + return nil + case codesnippet.FieldEmbedding: + m.ClearEmbedding() + return nil + case codesnippet.FieldWorkspacePath: + m.ClearWorkspacePath() + return nil + } + return fmt.Errorf("unknown CodeSnippet nullable field %s", name) +} + +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *CodeSnippetMutation) ResetField(name string) error { + switch name { + case codesnippet.FieldWorkspaceFileID: + m.ResetWorkspaceFileID() + return nil + case codesnippet.FieldName: + m.ResetName() + return nil + case codesnippet.FieldSnippetType: + m.ResetSnippetType() + return nil + case codesnippet.FieldLanguage: + m.ResetLanguage() + return nil + case codesnippet.FieldContent: + m.ResetContent() + return nil + case codesnippet.FieldHash: + m.ResetHash() + return nil + case codesnippet.FieldStartLine: + m.ResetStartLine() + return nil + case codesnippet.FieldEndLine: + m.ResetEndLine() + return nil + case codesnippet.FieldStartColumn: + m.ResetStartColumn() + return nil + case codesnippet.FieldEndColumn: + m.ResetEndColumn() + return nil + case codesnippet.FieldNamespace: + m.ResetNamespace() + return nil + case codesnippet.FieldContainerName: + m.ResetContainerName() + return nil + case codesnippet.FieldScope: + m.ResetScope() + return nil + case codesnippet.FieldDependencies: + m.ResetDependencies() + return nil + case codesnippet.FieldParameters: + m.ResetParameters() + return nil + case codesnippet.FieldSignature: + m.ResetSignature() + return nil + case codesnippet.FieldDefinitionText: + m.ResetDefinitionText() + return nil + case codesnippet.FieldStructuredInfo: + m.ResetStructuredInfo() + return nil + case codesnippet.FieldEmbedding: + m.ResetEmbedding() + return nil + case codesnippet.FieldWorkspacePath: + m.ResetWorkspacePath() + return nil + } + return fmt.Errorf("unknown CodeSnippet field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *CodeSnippetMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.source_file != nil { + edges = append(edges, codesnippet.EdgeSourceFile) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *CodeSnippetMutation) AddedIDs(name string) []ent.Value { + switch name { + case codesnippet.EdgeSourceFile: + if id := m.source_file; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *CodeSnippetMutation) RemovedEdges() []string { + edges := make([]string, 0, 1) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *CodeSnippetMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *CodeSnippetMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedsource_file { + edges = append(edges, codesnippet.EdgeSourceFile) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *CodeSnippetMutation) EdgeCleared(name string) bool { + switch name { + case codesnippet.EdgeSourceFile: + return m.clearedsource_file + } + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *CodeSnippetMutation) ClearEdge(name string) error { + switch name { + case codesnippet.EdgeSourceFile: + m.ClearSourceFile() + return nil + } + return fmt.Errorf("unknown CodeSnippet unique edge %s", name) } // ResetEdge resets all changes to the edge with the given name in this mutation. // It returns an error if the edge is not defined in the schema. -func (m *ExtensionMutation) ResetEdge(name string) error { - return fmt.Errorf("unknown Extension edge %s", name) +func (m *CodeSnippetMutation) ResetEdge(name string) error { + switch name { + case codesnippet.EdgeSourceFile: + m.ResetSourceFile() + return nil + } + return fmt.Errorf("unknown CodeSnippet edge %s", name) } -// InviteCodeMutation represents an operation that mutates the InviteCode nodes in the graph. -type InviteCodeMutation struct { +// ExtensionMutation represents an operation that mutates the Extension nodes in the graph. +type ExtensionMutation struct { config op Op typ string id *uuid.UUID - admin_id *uuid.UUID - code *string - status *consts.InviteCodeStatus + version *string + _path *string created_at *time.Time - updated_at *time.Time - expired_at *time.Time clearedFields map[string]struct{} done bool - oldValue func(context.Context) (*InviteCode, error) - predicates []predicate.InviteCode + oldValue func(context.Context) (*Extension, error) + predicates []predicate.Extension } -var _ ent.Mutation = (*InviteCodeMutation)(nil) +var _ ent.Mutation = (*ExtensionMutation)(nil) -// invitecodeOption allows management of the mutation configuration using functional options. -type invitecodeOption func(*InviteCodeMutation) +// extensionOption allows management of the mutation configuration using functional options. +type extensionOption func(*ExtensionMutation) -// newInviteCodeMutation creates new mutation for the InviteCode entity. -func newInviteCodeMutation(c config, op Op, opts ...invitecodeOption) *InviteCodeMutation { - m := &InviteCodeMutation{ +// newExtensionMutation creates new mutation for the Extension entity. +func newExtensionMutation(c config, op Op, opts ...extensionOption) *ExtensionMutation { + m := &ExtensionMutation{ config: c, op: op, - typ: TypeInviteCode, + typ: TypeExtension, clearedFields: make(map[string]struct{}), } for _, opt := range opts { @@ -7784,20 +8255,20 @@ func newInviteCodeMutation(c config, op Op, opts ...invitecodeOption) *InviteCod return m } -// withInviteCodeID sets the ID field of the mutation. -func withInviteCodeID(id uuid.UUID) invitecodeOption { - return func(m *InviteCodeMutation) { +// withExtensionID sets the ID field of the mutation. +func withExtensionID(id uuid.UUID) extensionOption { + return func(m *ExtensionMutation) { var ( err error once sync.Once - value *InviteCode + value *Extension ) - m.oldValue = func(ctx context.Context) (*InviteCode, error) { + m.oldValue = func(ctx context.Context) (*Extension, error) { once.Do(func() { if m.done { err = errors.New("querying old values post mutation is not allowed") } else { - value, err = m.Client().InviteCode.Get(ctx, id) + value, err = m.Client().Extension.Get(ctx, id) } }) return value, err @@ -7806,10 +8277,10 @@ func withInviteCodeID(id uuid.UUID) invitecodeOption { } } -// withInviteCode sets the old InviteCode of the mutation. -func withInviteCode(node *InviteCode) invitecodeOption { - return func(m *InviteCodeMutation) { - m.oldValue = func(context.Context) (*InviteCode, error) { +// withExtension sets the old Extension of the mutation. +func withExtension(node *Extension) extensionOption { + return func(m *ExtensionMutation) { + m.oldValue = func(context.Context) (*Extension, error) { return node, nil } m.id = &node.ID @@ -7818,7 +8289,7 @@ func withInviteCode(node *InviteCode) invitecodeOption { // 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 InviteCodeMutation) Client() *Client { +func (m ExtensionMutation) Client() *Client { client := &Client{config: m.config} client.init() return client @@ -7826,7 +8297,7 @@ func (m InviteCodeMutation) Client() *Client { // Tx returns an `ent.Tx` for mutations that were executed in transactions; // it returns an error otherwise. -func (m InviteCodeMutation) Tx() (*Tx, error) { +func (m ExtensionMutation) Tx() (*Tx, error) { if _, ok := m.driver.(*txDriver); !ok { return nil, errors.New("db: mutation is not running in a transaction") } @@ -7836,14 +8307,14 @@ func (m InviteCodeMutation) Tx() (*Tx, error) { } // SetID sets the value of the id field. Note that this -// operation is only accepted on creation of InviteCode entities. -func (m *InviteCodeMutation) SetID(id uuid.UUID) { +// operation is only accepted on creation of Extension entities. +func (m *ExtensionMutation) SetID(id uuid.UUID) { m.id = &id } // ID returns the ID value in the mutation. Note that the ID is only available // if it was provided to the builder or after it was returned from the database. -func (m *InviteCodeMutation) ID() (id uuid.UUID, exists bool) { +func (m *ExtensionMutation) ID() (id uuid.UUID, exists bool) { if m.id == nil { return } @@ -7854,7 +8325,7 @@ func (m *InviteCodeMutation) ID() (id uuid.UUID, exists bool) { // 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 *InviteCodeMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { +func (m *ExtensionMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { switch { case m.op.Is(OpUpdateOne | OpDeleteOne): id, exists := m.ID() @@ -7863,127 +8334,91 @@ func (m *InviteCodeMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { } fallthrough case m.op.Is(OpUpdate | OpDelete): - return m.Client().InviteCode.Query().Where(m.predicates...).IDs(ctx) + return m.Client().Extension.Query().Where(m.predicates...).IDs(ctx) default: return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) } } -// SetAdminID sets the "admin_id" field. -func (m *InviteCodeMutation) SetAdminID(u uuid.UUID) { - m.admin_id = &u +// SetVersion sets the "version" field. +func (m *ExtensionMutation) SetVersion(s string) { + m.version = &s } -// AdminID returns the value of the "admin_id" field in the mutation. -func (m *InviteCodeMutation) AdminID() (r uuid.UUID, exists bool) { - v := m.admin_id +// Version returns the value of the "version" field in the mutation. +func (m *ExtensionMutation) Version() (r string, exists bool) { + v := m.version if v == nil { return } return *v, true } -// OldAdminID returns the old "admin_id" field's value of the InviteCode entity. -// If the InviteCode 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 *InviteCodeMutation) OldAdminID(ctx context.Context) (v uuid.UUID, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldAdminID is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldAdminID requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldAdminID: %w", err) - } - return oldValue.AdminID, nil -} - -// ResetAdminID resets all changes to the "admin_id" field. -func (m *InviteCodeMutation) ResetAdminID() { - m.admin_id = nil -} - -// SetCode sets the "code" field. -func (m *InviteCodeMutation) SetCode(s string) { - m.code = &s -} - -// Code returns the value of the "code" field in the mutation. -func (m *InviteCodeMutation) Code() (r string, exists bool) { - v := m.code - if v == nil { - return - } - return *v, true -} - -// OldCode returns the old "code" field's value of the InviteCode entity. -// If the InviteCode object wasn't provided to the builder, the object is fetched from the database. +// OldVersion returns the old "version" field's value of the Extension entity. +// If the Extension object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *InviteCodeMutation) OldCode(ctx context.Context) (v string, err error) { +func (m *ExtensionMutation) OldVersion(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCode is only allowed on UpdateOne operations") + return v, errors.New("OldVersion is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCode requires an ID field in the mutation") + 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 OldCode: %w", err) + return v, fmt.Errorf("querying old value for OldVersion: %w", err) } - return oldValue.Code, nil + return oldValue.Version, nil } -// ResetCode resets all changes to the "code" field. -func (m *InviteCodeMutation) ResetCode() { - m.code = nil +// ResetVersion resets all changes to the "version" field. +func (m *ExtensionMutation) ResetVersion() { + m.version = nil } -// SetStatus sets the "status" field. -func (m *InviteCodeMutation) SetStatus(ccs consts.InviteCodeStatus) { - m.status = &ccs +// SetPath sets the "path" field. +func (m *ExtensionMutation) SetPath(s string) { + m._path = &s } -// Status returns the value of the "status" field in the mutation. -func (m *InviteCodeMutation) Status() (r consts.InviteCodeStatus, exists bool) { - v := m.status +// Path returns the value of the "path" field in the mutation. +func (m *ExtensionMutation) Path() (r string, exists bool) { + v := m._path if v == nil { return } return *v, true } -// OldStatus returns the old "status" field's value of the InviteCode entity. -// If the InviteCode object wasn't provided to the builder, the object is fetched from the database. +// OldPath returns the old "path" field's value of the Extension entity. +// If the Extension object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *InviteCodeMutation) OldStatus(ctx context.Context) (v consts.InviteCodeStatus, err error) { +func (m *ExtensionMutation) OldPath(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldStatus is only allowed on UpdateOne operations") + return v, errors.New("OldPath 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") + return v, errors.New("OldPath requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldStatus: %w", err) + return v, fmt.Errorf("querying old value for OldPath: %w", err) } - return oldValue.Status, nil + return oldValue.Path, nil } -// ResetStatus resets all changes to the "status" field. -func (m *InviteCodeMutation) ResetStatus() { - m.status = nil +// ResetPath resets all changes to the "path" field. +func (m *ExtensionMutation) ResetPath() { + m._path = nil } // SetCreatedAt sets the "created_at" field. -func (m *InviteCodeMutation) SetCreatedAt(t time.Time) { +func (m *ExtensionMutation) SetCreatedAt(t time.Time) { m.created_at = &t } // CreatedAt returns the value of the "created_at" field in the mutation. -func (m *InviteCodeMutation) CreatedAt() (r time.Time, exists bool) { +func (m *ExtensionMutation) CreatedAt() (r time.Time, exists bool) { v := m.created_at if v == nil { return @@ -7991,10 +8426,10 @@ func (m *InviteCodeMutation) CreatedAt() (r time.Time, exists bool) { return *v, true } -// OldCreatedAt returns the old "created_at" field's value of the InviteCode entity. -// If the InviteCode object wasn't provided to the builder, the object is fetched from the database. +// OldCreatedAt returns the old "created_at" field's value of the Extension entity. +// If the Extension object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *InviteCodeMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { +func (m *ExtensionMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { if !m.op.Is(OpUpdateOne) { return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") } @@ -8009,91 +8444,19 @@ func (m *InviteCodeMutation) OldCreatedAt(ctx context.Context) (v time.Time, err } // ResetCreatedAt resets all changes to the "created_at" field. -func (m *InviteCodeMutation) ResetCreatedAt() { +func (m *ExtensionMutation) ResetCreatedAt() { m.created_at = nil } -// SetUpdatedAt sets the "updated_at" field. -func (m *InviteCodeMutation) SetUpdatedAt(t time.Time) { - m.updated_at = &t -} - -// UpdatedAt returns the value of the "updated_at" field in the mutation. -func (m *InviteCodeMutation) 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 InviteCode entity. -// If the InviteCode 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 *InviteCodeMutation) 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 *InviteCodeMutation) ResetUpdatedAt() { - m.updated_at = nil -} - -// SetExpiredAt sets the "expired_at" field. -func (m *InviteCodeMutation) SetExpiredAt(t time.Time) { - m.expired_at = &t -} - -// ExpiredAt returns the value of the "expired_at" field in the mutation. -func (m *InviteCodeMutation) ExpiredAt() (r time.Time, exists bool) { - v := m.expired_at - if v == nil { - return - } - return *v, true -} - -// OldExpiredAt returns the old "expired_at" field's value of the InviteCode entity. -// If the InviteCode 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 *InviteCodeMutation) OldExpiredAt(ctx context.Context) (v time.Time, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldExpiredAt is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldExpiredAt requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldExpiredAt: %w", err) - } - return oldValue.ExpiredAt, nil -} - -// ResetExpiredAt resets all changes to the "expired_at" field. -func (m *InviteCodeMutation) ResetExpiredAt() { - m.expired_at = nil -} - -// Where appends a list predicates to the InviteCodeMutation builder. -func (m *InviteCodeMutation) Where(ps ...predicate.InviteCode) { +// Where appends a list predicates to the ExtensionMutation builder. +func (m *ExtensionMutation) Where(ps ...predicate.Extension) { m.predicates = append(m.predicates, ps...) } -// WhereP appends storage-level predicates to the InviteCodeMutation builder. Using this method, +// WhereP appends storage-level predicates to the ExtensionMutation builder. Using this method, // users can use type-assertion to append predicates that do not depend on any generated package. -func (m *InviteCodeMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.InviteCode, len(ps)) +func (m *ExtensionMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Extension, len(ps)) for i := range ps { p[i] = ps[i] } @@ -8101,42 +8464,33 @@ func (m *InviteCodeMutation) WhereP(ps ...func(*sql.Selector)) { } // Op returns the operation name. -func (m *InviteCodeMutation) Op() Op { +func (m *ExtensionMutation) Op() Op { return m.op } // SetOp allows setting the mutation operation. -func (m *InviteCodeMutation) SetOp(op Op) { +func (m *ExtensionMutation) SetOp(op Op) { m.op = op } -// Type returns the node type of this mutation (InviteCode). -func (m *InviteCodeMutation) Type() string { +// Type returns the node type of this mutation (Extension). +func (m *ExtensionMutation) Type() string { return m.typ } // Fields returns all fields that were changed during this mutation. Note that in // order to get all numeric fields that were incremented/decremented, call // AddedFields(). -func (m *InviteCodeMutation) Fields() []string { - fields := make([]string, 0, 6) - if m.admin_id != nil { - fields = append(fields, invitecode.FieldAdminID) - } - if m.code != nil { - fields = append(fields, invitecode.FieldCode) +func (m *ExtensionMutation) Fields() []string { + fields := make([]string, 0, 3) + if m.version != nil { + fields = append(fields, extension.FieldVersion) } - if m.status != nil { - fields = append(fields, invitecode.FieldStatus) + if m._path != nil { + fields = append(fields, extension.FieldPath) } if m.created_at != nil { - fields = append(fields, invitecode.FieldCreatedAt) - } - if m.updated_at != nil { - fields = append(fields, invitecode.FieldUpdatedAt) - } - if m.expired_at != nil { - fields = append(fields, invitecode.FieldExpiredAt) + fields = append(fields, extension.FieldCreatedAt) } return fields } @@ -8144,20 +8498,14 @@ func (m *InviteCodeMutation) Fields() []string { // 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 *InviteCodeMutation) Field(name string) (ent.Value, bool) { +func (m *ExtensionMutation) Field(name string) (ent.Value, bool) { switch name { - case invitecode.FieldAdminID: - return m.AdminID() - case invitecode.FieldCode: - return m.Code() - case invitecode.FieldStatus: - return m.Status() - case invitecode.FieldCreatedAt: + case extension.FieldVersion: + return m.Version() + case extension.FieldPath: + return m.Path() + case extension.FieldCreatedAt: return m.CreatedAt() - case invitecode.FieldUpdatedAt: - return m.UpdatedAt() - case invitecode.FieldExpiredAt: - return m.ExpiredAt() } return nil, false } @@ -8165,217 +8513,183 @@ func (m *InviteCodeMutation) Field(name string) (ent.Value, bool) { // 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 *InviteCodeMutation) OldField(ctx context.Context, name string) (ent.Value, error) { +func (m *ExtensionMutation) OldField(ctx context.Context, name string) (ent.Value, error) { switch name { - case invitecode.FieldAdminID: - return m.OldAdminID(ctx) - case invitecode.FieldCode: - return m.OldCode(ctx) - case invitecode.FieldStatus: - return m.OldStatus(ctx) - case invitecode.FieldCreatedAt: + case extension.FieldVersion: + return m.OldVersion(ctx) + case extension.FieldPath: + return m.OldPath(ctx) + case extension.FieldCreatedAt: return m.OldCreatedAt(ctx) - case invitecode.FieldUpdatedAt: - return m.OldUpdatedAt(ctx) - case invitecode.FieldExpiredAt: - return m.OldExpiredAt(ctx) } - return nil, fmt.Errorf("unknown InviteCode field %s", name) + return nil, fmt.Errorf("unknown Extension field %s", name) } // SetField sets the value of a field with the given name. It returns an error if // the field is not defined in the schema, or if the type mismatched the field // type. -func (m *InviteCodeMutation) SetField(name string, value ent.Value) error { +func (m *ExtensionMutation) SetField(name string, value ent.Value) error { switch name { - case invitecode.FieldAdminID: - v, ok := value.(uuid.UUID) + case extension.FieldVersion: + v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetAdminID(v) + m.SetVersion(v) return nil - case invitecode.FieldCode: + case extension.FieldPath: v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetCode(v) - return nil - case invitecode.FieldStatus: - v, ok := value.(consts.InviteCodeStatus) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetStatus(v) + m.SetPath(v) return nil - case invitecode.FieldCreatedAt: + case extension.FieldCreatedAt: v, ok := value.(time.Time) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } m.SetCreatedAt(v) return nil - case invitecode.FieldUpdatedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetUpdatedAt(v) - return nil - case invitecode.FieldExpiredAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetExpiredAt(v) - return nil } - return fmt.Errorf("unknown InviteCode field %s", name) + return fmt.Errorf("unknown Extension field %s", name) } // AddedFields returns all numeric fields that were incremented/decremented during // this mutation. -func (m *InviteCodeMutation) AddedFields() []string { +func (m *ExtensionMutation) AddedFields() []string { return nil } // AddedField returns the numeric value that was incremented/decremented on a field // with the given name. The second boolean return value indicates that this field // was not set, or was not defined in the schema. -func (m *InviteCodeMutation) AddedField(name string) (ent.Value, bool) { +func (m *ExtensionMutation) AddedField(name string) (ent.Value, bool) { return nil, false } // AddField adds the value to the field with the given name. It returns an error if // the field is not defined in the schema, or if the type mismatched the field // type. -func (m *InviteCodeMutation) AddField(name string, value ent.Value) error { +func (m *ExtensionMutation) AddField(name string, value ent.Value) error { switch name { } - return fmt.Errorf("unknown InviteCode numeric field %s", name) + return fmt.Errorf("unknown Extension numeric field %s", name) } // ClearedFields returns all nullable fields that were cleared during this // mutation. -func (m *InviteCodeMutation) ClearedFields() []string { +func (m *ExtensionMutation) ClearedFields() []string { return nil } // FieldCleared returns a boolean indicating if a field with the given name was // cleared in this mutation. -func (m *InviteCodeMutation) FieldCleared(name string) bool { +func (m *ExtensionMutation) FieldCleared(name string) bool { _, ok := m.clearedFields[name] return ok } // ClearField clears the value of the field with the given name. It returns an // error if the field is not defined in the schema. -func (m *InviteCodeMutation) ClearField(name string) error { - return fmt.Errorf("unknown InviteCode nullable field %s", name) +func (m *ExtensionMutation) ClearField(name string) error { + return fmt.Errorf("unknown Extension nullable field %s", name) } // ResetField resets all changes in the mutation for the field with the given name. // It returns an error if the field is not defined in the schema. -func (m *InviteCodeMutation) ResetField(name string) error { +func (m *ExtensionMutation) ResetField(name string) error { switch name { - case invitecode.FieldAdminID: - m.ResetAdminID() - return nil - case invitecode.FieldCode: - m.ResetCode() + case extension.FieldVersion: + m.ResetVersion() return nil - case invitecode.FieldStatus: - m.ResetStatus() + case extension.FieldPath: + m.ResetPath() return nil - case invitecode.FieldCreatedAt: + case extension.FieldCreatedAt: m.ResetCreatedAt() return nil - case invitecode.FieldUpdatedAt: - m.ResetUpdatedAt() - return nil - case invitecode.FieldExpiredAt: - m.ResetExpiredAt() - return nil } - return fmt.Errorf("unknown InviteCode field %s", name) + return fmt.Errorf("unknown Extension field %s", name) } // AddedEdges returns all edge names that were set/added in this mutation. -func (m *InviteCodeMutation) AddedEdges() []string { +func (m *ExtensionMutation) AddedEdges() []string { edges := make([]string, 0, 0) return edges } // AddedIDs returns all IDs (to other nodes) that were added for the given edge // name in this mutation. -func (m *InviteCodeMutation) AddedIDs(name string) []ent.Value { +func (m *ExtensionMutation) AddedIDs(name string) []ent.Value { return nil } // RemovedEdges returns all edge names that were removed in this mutation. -func (m *InviteCodeMutation) RemovedEdges() []string { +func (m *ExtensionMutation) RemovedEdges() []string { edges := make([]string, 0, 0) return edges } // RemovedIDs returns all IDs (to other nodes) that were removed for the edge with // the given name in this mutation. -func (m *InviteCodeMutation) RemovedIDs(name string) []ent.Value { +func (m *ExtensionMutation) RemovedIDs(name string) []ent.Value { return nil } // ClearedEdges returns all edge names that were cleared in this mutation. -func (m *InviteCodeMutation) ClearedEdges() []string { +func (m *ExtensionMutation) ClearedEdges() []string { edges := make([]string, 0, 0) return edges } // EdgeCleared returns a boolean which indicates if the edge with the given name // was cleared in this mutation. -func (m *InviteCodeMutation) EdgeCleared(name string) bool { +func (m *ExtensionMutation) EdgeCleared(name string) bool { return false } // ClearEdge clears the value of the edge with the given name. It returns an error // if that edge is not defined in the schema. -func (m *InviteCodeMutation) ClearEdge(name string) error { - return fmt.Errorf("unknown InviteCode unique edge %s", name) +func (m *ExtensionMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown Extension unique edge %s", name) } // ResetEdge resets all changes to the edge with the given name in this mutation. // It returns an error if the edge is not defined in the schema. -func (m *InviteCodeMutation) ResetEdge(name string) error { - return fmt.Errorf("unknown InviteCode edge %s", name) +func (m *ExtensionMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown Extension edge %s", name) } -// LicenseMutation represents an operation that mutates the License nodes in the graph. -type LicenseMutation struct { +// InviteCodeMutation represents an operation that mutates the InviteCode nodes in the graph. +type InviteCodeMutation struct { config op Op typ string - id *int - _type *consts.LicenseType - data *[]byte + id *uuid.UUID + admin_id *uuid.UUID code *string + status *consts.InviteCodeStatus created_at *time.Time + updated_at *time.Time + expired_at *time.Time clearedFields map[string]struct{} done bool - oldValue func(context.Context) (*License, error) - predicates []predicate.License + oldValue func(context.Context) (*InviteCode, error) + predicates []predicate.InviteCode } -var _ ent.Mutation = (*LicenseMutation)(nil) +var _ ent.Mutation = (*InviteCodeMutation)(nil) -// licenseOption allows management of the mutation configuration using functional options. -type licenseOption func(*LicenseMutation) +// invitecodeOption allows management of the mutation configuration using functional options. +type invitecodeOption func(*InviteCodeMutation) -// newLicenseMutation creates new mutation for the License entity. -func newLicenseMutation(c config, op Op, opts ...licenseOption) *LicenseMutation { - m := &LicenseMutation{ +// newInviteCodeMutation creates new mutation for the InviteCode entity. +func newInviteCodeMutation(c config, op Op, opts ...invitecodeOption) *InviteCodeMutation { + m := &InviteCodeMutation{ config: c, op: op, - typ: TypeLicense, + typ: TypeInviteCode, clearedFields: make(map[string]struct{}), } for _, opt := range opts { @@ -8384,20 +8698,20 @@ func newLicenseMutation(c config, op Op, opts ...licenseOption) *LicenseMutation return m } -// withLicenseID sets the ID field of the mutation. -func withLicenseID(id int) licenseOption { - return func(m *LicenseMutation) { +// withInviteCodeID sets the ID field of the mutation. +func withInviteCodeID(id uuid.UUID) invitecodeOption { + return func(m *InviteCodeMutation) { var ( err error once sync.Once - value *License + value *InviteCode ) - m.oldValue = func(ctx context.Context) (*License, error) { + m.oldValue = func(ctx context.Context) (*InviteCode, error) { once.Do(func() { if m.done { err = errors.New("querying old values post mutation is not allowed") } else { - value, err = m.Client().License.Get(ctx, id) + value, err = m.Client().InviteCode.Get(ctx, id) } }) return value, err @@ -8406,10 +8720,10 @@ func withLicenseID(id int) licenseOption { } } -// withLicense sets the old License of the mutation. -func withLicense(node *License) licenseOption { - return func(m *LicenseMutation) { - m.oldValue = func(context.Context) (*License, error) { +// withInviteCode sets the old InviteCode of the mutation. +func withInviteCode(node *InviteCode) invitecodeOption { + return func(m *InviteCodeMutation) { + m.oldValue = func(context.Context) (*InviteCode, error) { return node, nil } m.id = &node.ID @@ -8418,7 +8732,7 @@ func withLicense(node *License) licenseOption { // 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 LicenseMutation) Client() *Client { +func (m InviteCodeMutation) Client() *Client { client := &Client{config: m.config} client.init() return client @@ -8426,7 +8740,7 @@ func (m LicenseMutation) Client() *Client { // Tx returns an `ent.Tx` for mutations that were executed in transactions; // it returns an error otherwise. -func (m LicenseMutation) Tx() (*Tx, error) { +func (m InviteCodeMutation) Tx() (*Tx, error) { if _, ok := m.driver.(*txDriver); !ok { return nil, errors.New("db: mutation is not running in a transaction") } @@ -8436,14 +8750,14 @@ func (m LicenseMutation) Tx() (*Tx, error) { } // SetID sets the value of the id field. Note that this -// operation is only accepted on creation of License entities. -func (m *LicenseMutation) SetID(id int) { +// operation is only accepted on creation of InviteCode entities. +func (m *InviteCodeMutation) 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 *LicenseMutation) ID() (id int, exists bool) { +func (m *InviteCodeMutation) ID() (id uuid.UUID, exists bool) { if m.id == nil { return } @@ -8454,162 +8768,136 @@ func (m *LicenseMutation) ID() (id int, exists bool) { // 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 *LicenseMutation) IDs(ctx context.Context) ([]int, error) { +func (m *InviteCodeMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { switch { case m.op.Is(OpUpdateOne | OpDeleteOne): id, exists := m.ID() if exists { - return []int{id}, nil + return []uuid.UUID{id}, nil } fallthrough case m.op.Is(OpUpdate | OpDelete): - return m.Client().License.Query().Where(m.predicates...).IDs(ctx) + return m.Client().InviteCode.Query().Where(m.predicates...).IDs(ctx) default: return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) } } -// SetType sets the "type" field. -func (m *LicenseMutation) SetType(ct consts.LicenseType) { - m._type = &ct +// SetAdminID sets the "admin_id" field. +func (m *InviteCodeMutation) SetAdminID(u uuid.UUID) { + m.admin_id = &u } -// GetType returns the value of the "type" field in the mutation. -func (m *LicenseMutation) GetType() (r consts.LicenseType, exists bool) { - v := m._type +// AdminID returns the value of the "admin_id" field in the mutation. +func (m *InviteCodeMutation) AdminID() (r uuid.UUID, exists bool) { + v := m.admin_id if v == nil { return } return *v, true } -// OldType returns the old "type" field's value of the License entity. -// If the License object wasn't provided to the builder, the object is fetched from the database. +// OldAdminID returns the old "admin_id" field's value of the InviteCode entity. +// If the InviteCode 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 *LicenseMutation) OldType(ctx context.Context) (v consts.LicenseType, err error) { +func (m *InviteCodeMutation) OldAdminID(ctx context.Context) (v uuid.UUID, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldType is only allowed on UpdateOne operations") + return v, errors.New("OldAdminID is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldType requires an ID field in the mutation") + return v, errors.New("OldAdminID requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldType: %w", err) + return v, fmt.Errorf("querying old value for OldAdminID: %w", err) } - return oldValue.Type, nil + return oldValue.AdminID, nil } -// ResetType resets all changes to the "type" field. -func (m *LicenseMutation) ResetType() { - m._type = nil +// ResetAdminID resets all changes to the "admin_id" field. +func (m *InviteCodeMutation) ResetAdminID() { + m.admin_id = nil } -// SetData sets the "data" field. -func (m *LicenseMutation) SetData(b []byte) { - m.data = &b +// SetCode sets the "code" field. +func (m *InviteCodeMutation) SetCode(s string) { + m.code = &s } -// Data returns the value of the "data" field in the mutation. -func (m *LicenseMutation) Data() (r []byte, exists bool) { - v := m.data +// Code returns the value of the "code" field in the mutation. +func (m *InviteCodeMutation) Code() (r string, exists bool) { + v := m.code if v == nil { return } return *v, true } -// OldData returns the old "data" field's value of the License entity. -// If the License object wasn't provided to the builder, the object is fetched from the database. +// OldCode returns the old "code" field's value of the InviteCode entity. +// If the InviteCode 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 *LicenseMutation) OldData(ctx context.Context) (v []byte, err error) { +func (m *InviteCodeMutation) OldCode(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldData is only allowed on UpdateOne operations") + return v, errors.New("OldCode is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldData requires an ID field in the mutation") + return v, errors.New("OldCode requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldData: %w", err) + return v, fmt.Errorf("querying old value for OldCode: %w", err) } - return oldValue.Data, nil -} - -// ClearData clears the value of the "data" field. -func (m *LicenseMutation) ClearData() { - m.data = nil - m.clearedFields[license.FieldData] = struct{}{} -} - -// DataCleared returns if the "data" field was cleared in this mutation. -func (m *LicenseMutation) DataCleared() bool { - _, ok := m.clearedFields[license.FieldData] - return ok + return oldValue.Code, nil } -// ResetData resets all changes to the "data" field. -func (m *LicenseMutation) ResetData() { - m.data = nil - delete(m.clearedFields, license.FieldData) +// ResetCode resets all changes to the "code" field. +func (m *InviteCodeMutation) ResetCode() { + m.code = nil } -// SetCode sets the "code" field. -func (m *LicenseMutation) SetCode(s string) { - m.code = &s +// SetStatus sets the "status" field. +func (m *InviteCodeMutation) SetStatus(ccs consts.InviteCodeStatus) { + m.status = &ccs } -// Code returns the value of the "code" field in the mutation. -func (m *LicenseMutation) Code() (r string, exists bool) { - v := m.code +// Status returns the value of the "status" field in the mutation. +func (m *InviteCodeMutation) Status() (r consts.InviteCodeStatus, exists bool) { + v := m.status if v == nil { return } return *v, true } -// OldCode returns the old "code" field's value of the License entity. -// If the License object wasn't provided to the builder, the object is fetched from the database. +// OldStatus returns the old "status" field's value of the InviteCode entity. +// If the InviteCode 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 *LicenseMutation) OldCode(ctx context.Context) (v string, err error) { +func (m *InviteCodeMutation) OldStatus(ctx context.Context) (v consts.InviteCodeStatus, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCode is only allowed on UpdateOne operations") + return v, errors.New("OldStatus is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCode requires an ID field in the mutation") + 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 OldCode: %w", err) + return v, fmt.Errorf("querying old value for OldStatus: %w", err) } - return oldValue.Code, nil -} - -// ClearCode clears the value of the "code" field. -func (m *LicenseMutation) ClearCode() { - m.code = nil - m.clearedFields[license.FieldCode] = struct{}{} -} - -// CodeCleared returns if the "code" field was cleared in this mutation. -func (m *LicenseMutation) CodeCleared() bool { - _, ok := m.clearedFields[license.FieldCode] - return ok + return oldValue.Status, nil } -// ResetCode resets all changes to the "code" field. -func (m *LicenseMutation) ResetCode() { - m.code = nil - delete(m.clearedFields, license.FieldCode) +// ResetStatus resets all changes to the "status" field. +func (m *InviteCodeMutation) ResetStatus() { + m.status = nil } // SetCreatedAt sets the "created_at" field. -func (m *LicenseMutation) SetCreatedAt(t time.Time) { +func (m *InviteCodeMutation) SetCreatedAt(t time.Time) { m.created_at = &t } // CreatedAt returns the value of the "created_at" field in the mutation. -func (m *LicenseMutation) CreatedAt() (r time.Time, exists bool) { +func (m *InviteCodeMutation) CreatedAt() (r time.Time, exists bool) { v := m.created_at if v == nil { return @@ -8617,10 +8905,10 @@ func (m *LicenseMutation) CreatedAt() (r time.Time, exists bool) { return *v, true } -// OldCreatedAt returns the old "created_at" field's value of the License entity. -// If the License object wasn't provided to the builder, the object is fetched from the database. +// OldCreatedAt returns the old "created_at" field's value of the InviteCode entity. +// If the InviteCode 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 *LicenseMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { +func (m *InviteCodeMutation) 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") } @@ -8635,19 +8923,91 @@ func (m *LicenseMutation) OldCreatedAt(ctx context.Context) (v time.Time, err er } // ResetCreatedAt resets all changes to the "created_at" field. -func (m *LicenseMutation) ResetCreatedAt() { +func (m *InviteCodeMutation) ResetCreatedAt() { m.created_at = nil } -// Where appends a list predicates to the LicenseMutation builder. -func (m *LicenseMutation) Where(ps ...predicate.License) { +// SetUpdatedAt sets the "updated_at" field. +func (m *InviteCodeMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *InviteCodeMutation) 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 InviteCode entity. +// If the InviteCode 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 *InviteCodeMutation) 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 *InviteCodeMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetExpiredAt sets the "expired_at" field. +func (m *InviteCodeMutation) SetExpiredAt(t time.Time) { + m.expired_at = &t +} + +// ExpiredAt returns the value of the "expired_at" field in the mutation. +func (m *InviteCodeMutation) ExpiredAt() (r time.Time, exists bool) { + v := m.expired_at + if v == nil { + return + } + return *v, true +} + +// OldExpiredAt returns the old "expired_at" field's value of the InviteCode entity. +// If the InviteCode 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 *InviteCodeMutation) OldExpiredAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldExpiredAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldExpiredAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldExpiredAt: %w", err) + } + return oldValue.ExpiredAt, nil +} + +// ResetExpiredAt resets all changes to the "expired_at" field. +func (m *InviteCodeMutation) ResetExpiredAt() { + m.expired_at = nil +} + +// Where appends a list predicates to the InviteCodeMutation builder. +func (m *InviteCodeMutation) Where(ps ...predicate.InviteCode) { m.predicates = append(m.predicates, ps...) } -// WhereP appends storage-level predicates to the LicenseMutation builder. Using this method, +// WhereP appends storage-level predicates to the InviteCodeMutation builder. Using this method, // users can use type-assertion to append predicates that do not depend on any generated package. -func (m *LicenseMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.License, len(ps)) +func (m *InviteCodeMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.InviteCode, len(ps)) for i := range ps { p[i] = ps[i] } @@ -8655,36 +9015,42 @@ func (m *LicenseMutation) WhereP(ps ...func(*sql.Selector)) { } // Op returns the operation name. -func (m *LicenseMutation) Op() Op { +func (m *InviteCodeMutation) Op() Op { return m.op } // SetOp allows setting the mutation operation. -func (m *LicenseMutation) SetOp(op Op) { +func (m *InviteCodeMutation) SetOp(op Op) { m.op = op } -// Type returns the node type of this mutation (License). -func (m *LicenseMutation) Type() string { +// Type returns the node type of this mutation (InviteCode). +func (m *InviteCodeMutation) 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 *LicenseMutation) Fields() []string { - fields := make([]string, 0, 4) - if m._type != nil { - fields = append(fields, license.FieldType) - } - if m.data != nil { - fields = append(fields, license.FieldData) +func (m *InviteCodeMutation) Fields() []string { + fields := make([]string, 0, 6) + if m.admin_id != nil { + fields = append(fields, invitecode.FieldAdminID) } if m.code != nil { - fields = append(fields, license.FieldCode) + fields = append(fields, invitecode.FieldCode) + } + if m.status != nil { + fields = append(fields, invitecode.FieldStatus) } if m.created_at != nil { - fields = append(fields, license.FieldCreatedAt) + fields = append(fields, invitecode.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, invitecode.FieldUpdatedAt) + } + if m.expired_at != nil { + fields = append(fields, invitecode.FieldExpiredAt) } return fields } @@ -8692,16 +9058,20 @@ func (m *LicenseMutation) Fields() []string { // 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 *LicenseMutation) Field(name string) (ent.Value, bool) { +func (m *InviteCodeMutation) Field(name string) (ent.Value, bool) { switch name { - case license.FieldType: - return m.GetType() - case license.FieldData: - return m.Data() - case license.FieldCode: + case invitecode.FieldAdminID: + return m.AdminID() + case invitecode.FieldCode: return m.Code() - case license.FieldCreatedAt: + case invitecode.FieldStatus: + return m.Status() + case invitecode.FieldCreatedAt: return m.CreatedAt() + case invitecode.FieldUpdatedAt: + return m.UpdatedAt() + case invitecode.FieldExpiredAt: + return m.ExpiredAt() } return nil, false } @@ -8709,225 +9079,217 @@ func (m *LicenseMutation) Field(name string) (ent.Value, bool) { // 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 *LicenseMutation) OldField(ctx context.Context, name string) (ent.Value, error) { +func (m *InviteCodeMutation) OldField(ctx context.Context, name string) (ent.Value, error) { switch name { - case license.FieldType: - return m.OldType(ctx) - case license.FieldData: - return m.OldData(ctx) - case license.FieldCode: + case invitecode.FieldAdminID: + return m.OldAdminID(ctx) + case invitecode.FieldCode: return m.OldCode(ctx) - case license.FieldCreatedAt: + case invitecode.FieldStatus: + return m.OldStatus(ctx) + case invitecode.FieldCreatedAt: return m.OldCreatedAt(ctx) + case invitecode.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case invitecode.FieldExpiredAt: + return m.OldExpiredAt(ctx) } - return nil, fmt.Errorf("unknown License field %s", name) + return nil, fmt.Errorf("unknown InviteCode 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 *LicenseMutation) SetField(name string, value ent.Value) error { +func (m *InviteCodeMutation) SetField(name string, value ent.Value) error { switch name { - case license.FieldType: - v, ok := value.(consts.LicenseType) + case invitecode.FieldAdminID: + v, ok := value.(uuid.UUID) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetType(v) + m.SetAdminID(v) return nil - case license.FieldData: - v, ok := value.([]byte) + case invitecode.FieldCode: + v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetData(v) + m.SetCode(v) return nil - case license.FieldCode: - v, ok := value.(string) + case invitecode.FieldStatus: + v, ok := value.(consts.InviteCodeStatus) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetCode(v) + m.SetStatus(v) return nil - case license.FieldCreatedAt: + case invitecode.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 invitecode.FieldUpdatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdatedAt(v) + return nil + case invitecode.FieldExpiredAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetExpiredAt(v) + return nil } - return fmt.Errorf("unknown License field %s", name) + return fmt.Errorf("unknown InviteCode field %s", name) } // AddedFields returns all numeric fields that were incremented/decremented during // this mutation. -func (m *LicenseMutation) AddedFields() []string { +func (m *InviteCodeMutation) 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 *LicenseMutation) AddedField(name string) (ent.Value, bool) { +func (m *InviteCodeMutation) 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 *LicenseMutation) AddField(name string, value ent.Value) error { +func (m *InviteCodeMutation) AddField(name string, value ent.Value) error { switch name { } - return fmt.Errorf("unknown License numeric field %s", name) + return fmt.Errorf("unknown InviteCode numeric field %s", name) } // ClearedFields returns all nullable fields that were cleared during this // mutation. -func (m *LicenseMutation) ClearedFields() []string { - var fields []string - if m.FieldCleared(license.FieldData) { - fields = append(fields, license.FieldData) - } - if m.FieldCleared(license.FieldCode) { - fields = append(fields, license.FieldCode) - } - return fields +func (m *InviteCodeMutation) ClearedFields() []string { + return nil } // FieldCleared returns a boolean indicating if a field with the given name was // cleared in this mutation. -func (m *LicenseMutation) FieldCleared(name string) bool { +func (m *InviteCodeMutation) 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 *LicenseMutation) ClearField(name string) error { - switch name { - case license.FieldData: - m.ClearData() - return nil - case license.FieldCode: - m.ClearCode() - return nil - } - return fmt.Errorf("unknown License nullable field %s", name) +func (m *InviteCodeMutation) ClearField(name string) error { + return fmt.Errorf("unknown InviteCode 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 *LicenseMutation) ResetField(name string) error { +func (m *InviteCodeMutation) ResetField(name string) error { switch name { - case license.FieldType: - m.ResetType() - return nil - case license.FieldData: - m.ResetData() + case invitecode.FieldAdminID: + m.ResetAdminID() return nil - case license.FieldCode: + case invitecode.FieldCode: m.ResetCode() return nil - case license.FieldCreatedAt: + case invitecode.FieldStatus: + m.ResetStatus() + return nil + case invitecode.FieldCreatedAt: m.ResetCreatedAt() return nil + case invitecode.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case invitecode.FieldExpiredAt: + m.ResetExpiredAt() + return nil } - return fmt.Errorf("unknown License field %s", name) + return fmt.Errorf("unknown InviteCode field %s", name) } // AddedEdges returns all edge names that were set/added in this mutation. -func (m *LicenseMutation) AddedEdges() []string { +func (m *InviteCodeMutation) 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 *LicenseMutation) AddedIDs(name string) []ent.Value { +func (m *InviteCodeMutation) AddedIDs(name string) []ent.Value { return nil } // RemovedEdges returns all edge names that were removed in this mutation. -func (m *LicenseMutation) RemovedEdges() []string { +func (m *InviteCodeMutation) 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 *LicenseMutation) RemovedIDs(name string) []ent.Value { +func (m *InviteCodeMutation) RemovedIDs(name string) []ent.Value { return nil } // ClearedEdges returns all edge names that were cleared in this mutation. -func (m *LicenseMutation) ClearedEdges() []string { +func (m *InviteCodeMutation) 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 *LicenseMutation) EdgeCleared(name string) bool { +func (m *InviteCodeMutation) 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 *LicenseMutation) ClearEdge(name string) error { - return fmt.Errorf("unknown License unique edge %s", name) +func (m *InviteCodeMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown InviteCode 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 *LicenseMutation) ResetEdge(name string) error { - return fmt.Errorf("unknown License edge %s", name) +func (m *InviteCodeMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown InviteCode edge %s", name) } -// ModelMutation represents an operation that mutates the Model nodes in the graph. -type ModelMutation struct { +// LicenseMutation represents an operation that mutates the License nodes in the graph. +type LicenseMutation struct { config - op Op - typ string - id *uuid.UUID - model_name *string - model_type *consts.ModelType - show_name *string - api_base *string - api_key *string - api_version *string - api_header *string - description *string - is_internal *bool - provider *consts.ModelProvider - status *consts.ModelStatus - parameters **types.ModelParam - context_length *int - addcontext_length *int - created_at *time.Time - updated_at *time.Time - clearedFields map[string]struct{} - tasks map[uuid.UUID]struct{} - removedtasks map[uuid.UUID]struct{} - clearedtasks bool - user *uuid.UUID - cleareduser bool - done bool - oldValue func(context.Context) (*Model, error) - predicates []predicate.Model + op Op + typ string + id *int + _type *consts.LicenseType + data *[]byte + code *string + created_at *time.Time + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*License, error) + predicates []predicate.License } -var _ ent.Mutation = (*ModelMutation)(nil) +var _ ent.Mutation = (*LicenseMutation)(nil) -// modelOption allows management of the mutation configuration using functional options. -type modelOption func(*ModelMutation) +// licenseOption allows management of the mutation configuration using functional options. +type licenseOption func(*LicenseMutation) -// newModelMutation creates new mutation for the Model entity. -func newModelMutation(c config, op Op, opts ...modelOption) *ModelMutation { - m := &ModelMutation{ +// newLicenseMutation creates new mutation for the License entity. +func newLicenseMutation(c config, op Op, opts ...licenseOption) *LicenseMutation { + m := &LicenseMutation{ config: c, op: op, - typ: TypeModel, + typ: TypeLicense, clearedFields: make(map[string]struct{}), } for _, opt := range opts { @@ -8936,20 +9298,20 @@ func newModelMutation(c config, op Op, opts ...modelOption) *ModelMutation { return m } -// withModelID sets the ID field of the mutation. -func withModelID(id uuid.UUID) modelOption { - return func(m *ModelMutation) { +// withLicenseID sets the ID field of the mutation. +func withLicenseID(id int) licenseOption { + return func(m *LicenseMutation) { var ( err error once sync.Once - value *Model + value *License ) - m.oldValue = func(ctx context.Context) (*Model, error) { + m.oldValue = func(ctx context.Context) (*License, error) { once.Do(func() { if m.done { err = errors.New("querying old values post mutation is not allowed") } else { - value, err = m.Client().Model.Get(ctx, id) + value, err = m.Client().License.Get(ctx, id) } }) return value, err @@ -8958,10 +9320,10 @@ func withModelID(id uuid.UUID) modelOption { } } -// withModel sets the old Model of the mutation. -func withModel(node *Model) modelOption { - return func(m *ModelMutation) { - m.oldValue = func(context.Context) (*Model, error) { +// withLicense sets the old License of the mutation. +func withLicense(node *License) licenseOption { + return func(m *LicenseMutation) { + m.oldValue = func(context.Context) (*License, error) { return node, nil } m.id = &node.ID @@ -8970,7 +9332,7 @@ func withModel(node *Model) modelOption { // 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 ModelMutation) Client() *Client { +func (m LicenseMutation) Client() *Client { client := &Client{config: m.config} client.init() return client @@ -8978,7 +9340,7 @@ func (m ModelMutation) Client() *Client { // Tx returns an `ent.Tx` for mutations that were executed in transactions; // it returns an error otherwise. -func (m ModelMutation) Tx() (*Tx, error) { +func (m LicenseMutation) Tx() (*Tx, error) { if _, ok := m.driver.(*txDriver); !ok { return nil, errors.New("db: mutation is not running in a transaction") } @@ -8988,14 +9350,14 @@ func (m ModelMutation) Tx() (*Tx, error) { } // SetID sets the value of the id field. Note that this -// operation is only accepted on creation of Model entities. -func (m *ModelMutation) SetID(id uuid.UUID) { +// operation is only accepted on creation of License entities. +func (m *LicenseMutation) SetID(id int) { 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 *ModelMutation) ID() (id uuid.UUID, exists bool) { +func (m *LicenseMutation) ID() (id int, exists bool) { if m.id == nil { return } @@ -9006,1861 +9368,1634 @@ func (m *ModelMutation) ID() (id uuid.UUID, exists bool) { // 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 *ModelMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { +func (m *LicenseMutation) IDs(ctx context.Context) ([]int, error) { switch { case m.op.Is(OpUpdateOne | OpDeleteOne): id, exists := m.ID() if exists { - return []uuid.UUID{id}, nil + return []int{id}, nil } fallthrough case m.op.Is(OpUpdate | OpDelete): - return m.Client().Model.Query().Where(m.predicates...).IDs(ctx) + return m.Client().License.Query().Where(m.predicates...).IDs(ctx) default: return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) } } -// SetUserID sets the "user_id" field. -func (m *ModelMutation) SetUserID(u uuid.UUID) { - m.user = &u +// SetType sets the "type" field. +func (m *LicenseMutation) SetType(ct consts.LicenseType) { + m._type = &ct } -// UserID returns the value of the "user_id" field in the mutation. -func (m *ModelMutation) UserID() (r uuid.UUID, exists bool) { - v := m.user +// GetType returns the value of the "type" field in the mutation. +func (m *LicenseMutation) GetType() (r consts.LicenseType, exists bool) { + v := m._type if v == nil { return } return *v, true } -// OldUserID returns the old "user_id" field's value of the Model entity. -// If the Model object wasn't provided to the builder, the object is fetched from the database. +// OldType returns the old "type" field's value of the License entity. +// If the License 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 *ModelMutation) OldUserID(ctx context.Context) (v uuid.UUID, err error) { +func (m *LicenseMutation) OldType(ctx context.Context) (v consts.LicenseType, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldUserID is only allowed on UpdateOne operations") + return v, errors.New("OldType is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldUserID requires an ID field in the mutation") + return v, errors.New("OldType requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldUserID: %w", err) + return v, fmt.Errorf("querying old value for OldType: %w", err) } - return oldValue.UserID, nil -} - -// ClearUserID clears the value of the "user_id" field. -func (m *ModelMutation) ClearUserID() { - m.user = nil - m.clearedFields[model.FieldUserID] = struct{}{} -} - -// UserIDCleared returns if the "user_id" field was cleared in this mutation. -func (m *ModelMutation) UserIDCleared() bool { - _, ok := m.clearedFields[model.FieldUserID] - return ok + return oldValue.Type, nil } -// ResetUserID resets all changes to the "user_id" field. -func (m *ModelMutation) ResetUserID() { - m.user = nil - delete(m.clearedFields, model.FieldUserID) +// ResetType resets all changes to the "type" field. +func (m *LicenseMutation) ResetType() { + m._type = nil } -// SetModelName sets the "model_name" field. -func (m *ModelMutation) SetModelName(s string) { - m.model_name = &s +// SetData sets the "data" field. +func (m *LicenseMutation) SetData(b []byte) { + m.data = &b } -// ModelName returns the value of the "model_name" field in the mutation. -func (m *ModelMutation) ModelName() (r string, exists bool) { - v := m.model_name +// Data returns the value of the "data" field in the mutation. +func (m *LicenseMutation) Data() (r []byte, exists bool) { + v := m.data if v == nil { return } return *v, true } -// OldModelName returns the old "model_name" field's value of the Model entity. -// If the Model object wasn't provided to the builder, the object is fetched from the database. +// OldData returns the old "data" field's value of the License entity. +// If the License 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 *ModelMutation) OldModelName(ctx context.Context) (v string, err error) { +func (m *LicenseMutation) OldData(ctx context.Context) (v []byte, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldModelName is only allowed on UpdateOne operations") + return v, errors.New("OldData is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldModelName requires an ID field in the mutation") + return v, errors.New("OldData requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldModelName: %w", err) + return v, fmt.Errorf("querying old value for OldData: %w", err) } - return oldValue.ModelName, nil + return oldValue.Data, nil } -// ResetModelName resets all changes to the "model_name" field. -func (m *ModelMutation) ResetModelName() { - m.model_name = nil +// ClearData clears the value of the "data" field. +func (m *LicenseMutation) ClearData() { + m.data = nil + m.clearedFields[license.FieldData] = struct{}{} } -// SetModelType sets the "model_type" field. -func (m *ModelMutation) SetModelType(ct consts.ModelType) { - m.model_type = &ct +// DataCleared returns if the "data" field was cleared in this mutation. +func (m *LicenseMutation) DataCleared() bool { + _, ok := m.clearedFields[license.FieldData] + return ok } -// ModelType returns the value of the "model_type" field in the mutation. -func (m *ModelMutation) ModelType() (r consts.ModelType, exists bool) { - v := m.model_type +// ResetData resets all changes to the "data" field. +func (m *LicenseMutation) ResetData() { + m.data = nil + delete(m.clearedFields, license.FieldData) +} + +// SetCode sets the "code" field. +func (m *LicenseMutation) SetCode(s string) { + m.code = &s +} + +// Code returns the value of the "code" field in the mutation. +func (m *LicenseMutation) Code() (r string, exists bool) { + v := m.code if v == nil { return } return *v, true } -// OldModelType returns the old "model_type" field's value of the Model entity. -// If the Model object wasn't provided to the builder, the object is fetched from the database. +// OldCode returns the old "code" field's value of the License entity. +// If the License 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 *ModelMutation) OldModelType(ctx context.Context) (v consts.ModelType, err error) { +func (m *LicenseMutation) OldCode(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldModelType is only allowed on UpdateOne operations") + return v, errors.New("OldCode is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldModelType requires an ID field in the mutation") + return v, errors.New("OldCode requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldModelType: %w", err) + return v, fmt.Errorf("querying old value for OldCode: %w", err) } - return oldValue.ModelType, nil + return oldValue.Code, nil } -// ResetModelType resets all changes to the "model_type" field. -func (m *ModelMutation) ResetModelType() { - m.model_type = nil -} +// ClearCode clears the value of the "code" field. +func (m *LicenseMutation) ClearCode() { + m.code = nil + m.clearedFields[license.FieldCode] = struct{}{} +} -// SetShowName sets the "show_name" field. -func (m *ModelMutation) SetShowName(s string) { - m.show_name = &s +// CodeCleared returns if the "code" field was cleared in this mutation. +func (m *LicenseMutation) CodeCleared() bool { + _, ok := m.clearedFields[license.FieldCode] + return ok } -// ShowName returns the value of the "show_name" field in the mutation. -func (m *ModelMutation) ShowName() (r string, exists bool) { - v := m.show_name +// ResetCode resets all changes to the "code" field. +func (m *LicenseMutation) ResetCode() { + m.code = nil + delete(m.clearedFields, license.FieldCode) +} + +// SetCreatedAt sets the "created_at" field. +func (m *LicenseMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *LicenseMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at if v == nil { return } return *v, true } -// OldShowName returns the old "show_name" field's value of the Model entity. -// If the Model object wasn't provided to the builder, the object is fetched from the database. +// OldCreatedAt returns the old "created_at" field's value of the License entity. +// If the License 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 *ModelMutation) OldShowName(ctx context.Context) (v string, err error) { +func (m *LicenseMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldShowName is only allowed on UpdateOne operations") + return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldShowName requires an ID field in the mutation") + 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 OldShowName: %w", err) + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) } - return oldValue.ShowName, nil + return oldValue.CreatedAt, nil } -// ClearShowName clears the value of the "show_name" field. -func (m *ModelMutation) ClearShowName() { - m.show_name = nil - m.clearedFields[model.FieldShowName] = struct{}{} +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *LicenseMutation) ResetCreatedAt() { + m.created_at = nil } -// ShowNameCleared returns if the "show_name" field was cleared in this mutation. -func (m *ModelMutation) ShowNameCleared() bool { - _, ok := m.clearedFields[model.FieldShowName] - return ok +// Where appends a list predicates to the LicenseMutation builder. +func (m *LicenseMutation) Where(ps ...predicate.License) { + m.predicates = append(m.predicates, ps...) } -// ResetShowName resets all changes to the "show_name" field. -func (m *ModelMutation) ResetShowName() { - m.show_name = nil - delete(m.clearedFields, model.FieldShowName) +// WhereP appends storage-level predicates to the LicenseMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *LicenseMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.License, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) } -// SetAPIBase sets the "api_base" field. -func (m *ModelMutation) SetAPIBase(s string) { - m.api_base = &s +// Op returns the operation name. +func (m *LicenseMutation) Op() Op { + return m.op } -// APIBase returns the value of the "api_base" field in the mutation. -func (m *ModelMutation) APIBase() (r string, exists bool) { - v := m.api_base - if v == nil { - return - } - return *v, true +// SetOp allows setting the mutation operation. +func (m *LicenseMutation) SetOp(op Op) { + m.op = op } -// OldAPIBase returns the old "api_base" field's value of the Model entity. -// If the Model 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 *ModelMutation) OldAPIBase(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldAPIBase is only allowed on UpdateOne operations") +// Type returns the node type of this mutation (License). +func (m *LicenseMutation) 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 *LicenseMutation) Fields() []string { + fields := make([]string, 0, 4) + if m._type != nil { + fields = append(fields, license.FieldType) } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldAPIBase requires an ID field in the mutation") + if m.data != nil { + fields = append(fields, license.FieldData) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldAPIBase: %w", err) + if m.code != nil { + fields = append(fields, license.FieldCode) } - return oldValue.APIBase, nil + if m.created_at != nil { + fields = append(fields, license.FieldCreatedAt) + } + return fields } -// ResetAPIBase resets all changes to the "api_base" field. -func (m *ModelMutation) ResetAPIBase() { - m.api_base = nil +// 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 *LicenseMutation) Field(name string) (ent.Value, bool) { + switch name { + case license.FieldType: + return m.GetType() + case license.FieldData: + return m.Data() + case license.FieldCode: + return m.Code() + case license.FieldCreatedAt: + return m.CreatedAt() + } + return nil, false } -// SetAPIKey sets the "api_key" field. -func (m *ModelMutation) SetAPIKey(s string) { - m.api_key = &s +// 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 *LicenseMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case license.FieldType: + return m.OldType(ctx) + case license.FieldData: + return m.OldData(ctx) + case license.FieldCode: + return m.OldCode(ctx) + case license.FieldCreatedAt: + return m.OldCreatedAt(ctx) + } + return nil, fmt.Errorf("unknown License field %s", name) } -// APIKey returns the value of the "api_key" field in the mutation. -func (m *ModelMutation) APIKey() (r string, exists bool) { - v := m.api_key - if v == nil { - return +// 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 *LicenseMutation) SetField(name string, value ent.Value) error { + switch name { + case license.FieldType: + v, ok := value.(consts.LicenseType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetType(v) + return nil + case license.FieldData: + v, ok := value.([]byte) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetData(v) + return nil + case license.FieldCode: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCode(v) + return nil + case license.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 *v, true + return fmt.Errorf("unknown License field %s", name) } -// OldAPIKey returns the old "api_key" field's value of the Model entity. -// If the Model 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 *ModelMutation) OldAPIKey(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldAPIKey is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldAPIKey requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldAPIKey: %w", err) - } - return oldValue.APIKey, nil +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *LicenseMutation) AddedFields() []string { + return nil } -// ClearAPIKey clears the value of the "api_key" field. -func (m *ModelMutation) ClearAPIKey() { - m.api_key = nil - m.clearedFields[model.FieldAPIKey] = struct{}{} +// 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 *LicenseMutation) AddedField(name string) (ent.Value, bool) { + return nil, false } -// APIKeyCleared returns if the "api_key" field was cleared in this mutation. -func (m *ModelMutation) APIKeyCleared() bool { - _, ok := m.clearedFields[model.FieldAPIKey] - return ok +// 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 *LicenseMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown License numeric field %s", name) } -// ResetAPIKey resets all changes to the "api_key" field. -func (m *ModelMutation) ResetAPIKey() { - m.api_key = nil - delete(m.clearedFields, model.FieldAPIKey) +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *LicenseMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(license.FieldData) { + fields = append(fields, license.FieldData) + } + if m.FieldCleared(license.FieldCode) { + fields = append(fields, license.FieldCode) + } + return fields } -// SetAPIVersion sets the "api_version" field. -func (m *ModelMutation) SetAPIVersion(s string) { - m.api_version = &s +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *LicenseMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok } -// APIVersion returns the value of the "api_version" field in the mutation. -func (m *ModelMutation) APIVersion() (r string, exists bool) { - v := m.api_version - if v == nil { - return +// 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 *LicenseMutation) ClearField(name string) error { + switch name { + case license.FieldData: + m.ClearData() + return nil + case license.FieldCode: + m.ClearCode() + return nil } - return *v, true + return fmt.Errorf("unknown License nullable field %s", name) } -// OldAPIVersion returns the old "api_version" field's value of the Model entity. -// If the Model 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 *ModelMutation) OldAPIVersion(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldAPIVersion is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldAPIVersion requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldAPIVersion: %w", err) +// 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 *LicenseMutation) ResetField(name string) error { + switch name { + case license.FieldType: + m.ResetType() + return nil + case license.FieldData: + m.ResetData() + return nil + case license.FieldCode: + m.ResetCode() + return nil + case license.FieldCreatedAt: + m.ResetCreatedAt() + return nil } - return oldValue.APIVersion, nil + return fmt.Errorf("unknown License field %s", name) } -// ClearAPIVersion clears the value of the "api_version" field. -func (m *ModelMutation) ClearAPIVersion() { - m.api_version = nil - m.clearedFields[model.FieldAPIVersion] = struct{}{} +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *LicenseMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges } -// APIVersionCleared returns if the "api_version" field was cleared in this mutation. -func (m *ModelMutation) APIVersionCleared() bool { - _, ok := m.clearedFields[model.FieldAPIVersion] - return ok +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *LicenseMutation) AddedIDs(name string) []ent.Value { + return nil } -// ResetAPIVersion resets all changes to the "api_version" field. -func (m *ModelMutation) ResetAPIVersion() { - m.api_version = nil - delete(m.clearedFields, model.FieldAPIVersion) +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *LicenseMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges } -// SetAPIHeader sets the "api_header" field. -func (m *ModelMutation) SetAPIHeader(s string) { - m.api_header = &s +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *LicenseMutation) RemovedIDs(name string) []ent.Value { + return nil } -// APIHeader returns the value of the "api_header" field in the mutation. -func (m *ModelMutation) APIHeader() (r string, exists bool) { - v := m.api_header - if v == nil { - return - } - return *v, true +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *LicenseMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges } -// OldAPIHeader returns the old "api_header" field's value of the Model entity. -// If the Model 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 *ModelMutation) OldAPIHeader(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldAPIHeader is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldAPIHeader requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldAPIHeader: %w", err) - } - return oldValue.APIHeader, nil +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *LicenseMutation) EdgeCleared(name string) bool { + return false } -// ClearAPIHeader clears the value of the "api_header" field. -func (m *ModelMutation) ClearAPIHeader() { - m.api_header = nil - m.clearedFields[model.FieldAPIHeader] = struct{}{} +// 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 *LicenseMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown License unique edge %s", name) } -// APIHeaderCleared returns if the "api_header" field was cleared in this mutation. -func (m *ModelMutation) APIHeaderCleared() bool { - _, ok := m.clearedFields[model.FieldAPIHeader] - return ok +// 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 *LicenseMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown License edge %s", name) } -// ResetAPIHeader resets all changes to the "api_header" field. -func (m *ModelMutation) ResetAPIHeader() { - m.api_header = nil - delete(m.clearedFields, model.FieldAPIHeader) +// ModelMutation represents an operation that mutates the Model nodes in the graph. +type ModelMutation struct { + config + op Op + typ string + id *uuid.UUID + model_name *string + model_type *consts.ModelType + show_name *string + api_base *string + api_key *string + api_version *string + api_header *string + description *string + is_internal *bool + provider *consts.ModelProvider + status *consts.ModelStatus + parameters **types.ModelParam + context_length *int + addcontext_length *int + created_at *time.Time + updated_at *time.Time + clearedFields map[string]struct{} + tasks map[uuid.UUID]struct{} + removedtasks map[uuid.UUID]struct{} + clearedtasks bool + user *uuid.UUID + cleareduser bool + done bool + oldValue func(context.Context) (*Model, error) + predicates []predicate.Model } -// SetDescription sets the "description" field. -func (m *ModelMutation) SetDescription(s string) { - m.description = &s -} +var _ ent.Mutation = (*ModelMutation)(nil) -// Description returns the value of the "description" field in the mutation. -func (m *ModelMutation) Description() (r string, exists bool) { - v := m.description - if v == nil { - return - } - return *v, true -} +// modelOption allows management of the mutation configuration using functional options. +type modelOption func(*ModelMutation) -// OldDescription returns the old "description" field's value of the Model entity. -// If the Model 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 *ModelMutation) 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") +// newModelMutation creates new mutation for the Model entity. +func newModelMutation(c config, op Op, opts ...modelOption) *ModelMutation { + m := &ModelMutation{ + config: c, + op: op, + typ: TypeModel, + clearedFields: make(map[string]struct{}), } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldDescription: %w", err) + for _, opt := range opts { + opt(m) } - return oldValue.Description, nil + return m } -// ClearDescription clears the value of the "description" field. -func (m *ModelMutation) ClearDescription() { - m.description = nil - m.clearedFields[model.FieldDescription] = struct{}{} +// withModelID sets the ID field of the mutation. +func withModelID(id uuid.UUID) modelOption { + return func(m *ModelMutation) { + var ( + err error + once sync.Once + value *Model + ) + m.oldValue = func(ctx context.Context) (*Model, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Model.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } } -// DescriptionCleared returns if the "description" field was cleared in this mutation. -func (m *ModelMutation) DescriptionCleared() bool { - _, ok := m.clearedFields[model.FieldDescription] - return ok +// withModel sets the old Model of the mutation. +func withModel(node *Model) modelOption { + return func(m *ModelMutation) { + m.oldValue = func(context.Context) (*Model, error) { + return node, nil + } + m.id = &node.ID + } } -// ResetDescription resets all changes to the "description" field. -func (m *ModelMutation) ResetDescription() { - m.description = nil - delete(m.clearedFields, model.FieldDescription) +// 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 ModelMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client } -// SetIsInternal sets the "is_internal" field. -func (m *ModelMutation) SetIsInternal(b bool) { - m.is_internal = &b +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m ModelMutation) 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 } -// IsInternal returns the value of the "is_internal" field in the mutation. -func (m *ModelMutation) IsInternal() (r bool, exists bool) { - v := m.is_internal +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of Model entities. +func (m *ModelMutation) 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 *ModelMutation) 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 *ModelMutation) 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().Model.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetUserID sets the "user_id" field. +func (m *ModelMutation) SetUserID(u uuid.UUID) { + m.user = &u +} + +// UserID returns the value of the "user_id" field in the mutation. +func (m *ModelMutation) UserID() (r uuid.UUID, exists bool) { + v := m.user if v == nil { return } return *v, true } -// OldIsInternal returns the old "is_internal" field's value of the Model entity. +// OldUserID returns the old "user_id" field's value of the Model entity. // If the Model 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 *ModelMutation) OldIsInternal(ctx context.Context) (v bool, err error) { +func (m *ModelMutation) OldUserID(ctx context.Context) (v uuid.UUID, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldIsInternal is only allowed on UpdateOne operations") + return v, errors.New("OldUserID is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldIsInternal requires an ID field in the mutation") + return v, errors.New("OldUserID requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldIsInternal: %w", err) + return v, fmt.Errorf("querying old value for OldUserID: %w", err) } - return oldValue.IsInternal, nil + return oldValue.UserID, nil } -// ResetIsInternal resets all changes to the "is_internal" field. -func (m *ModelMutation) ResetIsInternal() { - m.is_internal = nil +// ClearUserID clears the value of the "user_id" field. +func (m *ModelMutation) ClearUserID() { + m.user = nil + m.clearedFields[model.FieldUserID] = struct{}{} } -// SetProvider sets the "provider" field. -func (m *ModelMutation) SetProvider(cp consts.ModelProvider) { - m.provider = &cp +// UserIDCleared returns if the "user_id" field was cleared in this mutation. +func (m *ModelMutation) UserIDCleared() bool { + _, ok := m.clearedFields[model.FieldUserID] + return ok } -// Provider returns the value of the "provider" field in the mutation. -func (m *ModelMutation) Provider() (r consts.ModelProvider, exists bool) { - v := m.provider +// ResetUserID resets all changes to the "user_id" field. +func (m *ModelMutation) ResetUserID() { + m.user = nil + delete(m.clearedFields, model.FieldUserID) +} + +// SetModelName sets the "model_name" field. +func (m *ModelMutation) SetModelName(s string) { + m.model_name = &s +} + +// ModelName returns the value of the "model_name" field in the mutation. +func (m *ModelMutation) ModelName() (r string, exists bool) { + v := m.model_name if v == nil { return } return *v, true } -// OldProvider returns the old "provider" field's value of the Model entity. +// OldModelName returns the old "model_name" field's value of the Model entity. // If the Model 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 *ModelMutation) OldProvider(ctx context.Context) (v consts.ModelProvider, err error) { +func (m *ModelMutation) OldModelName(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldProvider is only allowed on UpdateOne operations") + return v, errors.New("OldModelName is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldProvider requires an ID field in the mutation") + return v, errors.New("OldModelName requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldProvider: %w", err) + return v, fmt.Errorf("querying old value for OldModelName: %w", err) } - return oldValue.Provider, nil + return oldValue.ModelName, nil } -// ResetProvider resets all changes to the "provider" field. -func (m *ModelMutation) ResetProvider() { - m.provider = nil +// ResetModelName resets all changes to the "model_name" field. +func (m *ModelMutation) ResetModelName() { + m.model_name = nil } -// SetStatus sets the "status" field. -func (m *ModelMutation) SetStatus(cs consts.ModelStatus) { - m.status = &cs +// SetModelType sets the "model_type" field. +func (m *ModelMutation) SetModelType(ct consts.ModelType) { + m.model_type = &ct } -// Status returns the value of the "status" field in the mutation. -func (m *ModelMutation) Status() (r consts.ModelStatus, exists bool) { - v := m.status +// ModelType returns the value of the "model_type" field in the mutation. +func (m *ModelMutation) ModelType() (r consts.ModelType, exists bool) { + v := m.model_type if v == nil { return } return *v, true } -// OldStatus returns the old "status" field's value of the Model entity. +// OldModelType returns the old "model_type" field's value of the Model entity. // If the Model 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 *ModelMutation) OldStatus(ctx context.Context) (v consts.ModelStatus, err error) { +func (m *ModelMutation) OldModelType(ctx context.Context) (v consts.ModelType, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldStatus is only allowed on UpdateOne operations") + return v, errors.New("OldModelType 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") + return v, errors.New("OldModelType requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldStatus: %w", err) + return v, fmt.Errorf("querying old value for OldModelType: %w", err) } - return oldValue.Status, nil + return oldValue.ModelType, nil } -// ResetStatus resets all changes to the "status" field. -func (m *ModelMutation) ResetStatus() { - m.status = nil +// ResetModelType resets all changes to the "model_type" field. +func (m *ModelMutation) ResetModelType() { + m.model_type = nil } -// SetParameters sets the "parameters" field. -func (m *ModelMutation) SetParameters(tp *types.ModelParam) { - m.parameters = &tp +// SetShowName sets the "show_name" field. +func (m *ModelMutation) SetShowName(s string) { + m.show_name = &s } -// Parameters returns the value of the "parameters" field in the mutation. -func (m *ModelMutation) Parameters() (r *types.ModelParam, exists bool) { - v := m.parameters +// ShowName returns the value of the "show_name" field in the mutation. +func (m *ModelMutation) ShowName() (r string, exists bool) { + v := m.show_name if v == nil { return } return *v, true } -// OldParameters returns the old "parameters" field's value of the Model entity. +// OldShowName returns the old "show_name" field's value of the Model entity. // If the Model 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 *ModelMutation) OldParameters(ctx context.Context) (v *types.ModelParam, err error) { +func (m *ModelMutation) OldShowName(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldParameters is only allowed on UpdateOne operations") + return v, errors.New("OldShowName is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldParameters requires an ID field in the mutation") + return v, errors.New("OldShowName requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldParameters: %w", err) + return v, fmt.Errorf("querying old value for OldShowName: %w", err) } - return oldValue.Parameters, nil + return oldValue.ShowName, nil } -// ClearParameters clears the value of the "parameters" field. -func (m *ModelMutation) ClearParameters() { - m.parameters = nil - m.clearedFields[model.FieldParameters] = struct{}{} +// ClearShowName clears the value of the "show_name" field. +func (m *ModelMutation) ClearShowName() { + m.show_name = nil + m.clearedFields[model.FieldShowName] = struct{}{} } -// ParametersCleared returns if the "parameters" field was cleared in this mutation. -func (m *ModelMutation) ParametersCleared() bool { - _, ok := m.clearedFields[model.FieldParameters] +// ShowNameCleared returns if the "show_name" field was cleared in this mutation. +func (m *ModelMutation) ShowNameCleared() bool { + _, ok := m.clearedFields[model.FieldShowName] return ok } -// ResetParameters resets all changes to the "parameters" field. -func (m *ModelMutation) ResetParameters() { - m.parameters = nil - delete(m.clearedFields, model.FieldParameters) +// ResetShowName resets all changes to the "show_name" field. +func (m *ModelMutation) ResetShowName() { + m.show_name = nil + delete(m.clearedFields, model.FieldShowName) } -// SetContextLength sets the "context_length" field. -func (m *ModelMutation) SetContextLength(i int) { - m.context_length = &i - m.addcontext_length = nil +// SetAPIBase sets the "api_base" field. +func (m *ModelMutation) SetAPIBase(s string) { + m.api_base = &s } -// ContextLength returns the value of the "context_length" field in the mutation. -func (m *ModelMutation) ContextLength() (r int, exists bool) { - v := m.context_length +// APIBase returns the value of the "api_base" field in the mutation. +func (m *ModelMutation) APIBase() (r string, exists bool) { + v := m.api_base if v == nil { return } return *v, true } -// OldContextLength returns the old "context_length" field's value of the Model entity. +// OldAPIBase returns the old "api_base" field's value of the Model entity. // If the Model 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 *ModelMutation) OldContextLength(ctx context.Context) (v int, err error) { +func (m *ModelMutation) OldAPIBase(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldContextLength is only allowed on UpdateOne operations") + return v, errors.New("OldAPIBase is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldContextLength requires an ID field in the mutation") + return v, errors.New("OldAPIBase requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldContextLength: %w", err) + return v, fmt.Errorf("querying old value for OldAPIBase: %w", err) } - return oldValue.ContextLength, nil + return oldValue.APIBase, nil } -// AddContextLength adds i to the "context_length" field. -func (m *ModelMutation) AddContextLength(i int) { - if m.addcontext_length != nil { - *m.addcontext_length += i - } else { - m.addcontext_length = &i - } +// ResetAPIBase resets all changes to the "api_base" field. +func (m *ModelMutation) ResetAPIBase() { + m.api_base = nil } -// AddedContextLength returns the value that was added to the "context_length" field in this mutation. -func (m *ModelMutation) AddedContextLength() (r int, exists bool) { - v := m.addcontext_length +// SetAPIKey sets the "api_key" field. +func (m *ModelMutation) SetAPIKey(s string) { + m.api_key = &s +} + +// APIKey returns the value of the "api_key" field in the mutation. +func (m *ModelMutation) APIKey() (r string, exists bool) { + v := m.api_key if v == nil { return } return *v, true } -// ClearContextLength clears the value of the "context_length" field. -func (m *ModelMutation) ClearContextLength() { - m.context_length = nil - m.addcontext_length = nil - m.clearedFields[model.FieldContextLength] = struct{}{} +// OldAPIKey returns the old "api_key" field's value of the Model entity. +// If the Model 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 *ModelMutation) OldAPIKey(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAPIKey is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAPIKey requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAPIKey: %w", err) + } + return oldValue.APIKey, nil } -// ContextLengthCleared returns if the "context_length" field was cleared in this mutation. -func (m *ModelMutation) ContextLengthCleared() bool { - _, ok := m.clearedFields[model.FieldContextLength] - return ok +// ClearAPIKey clears the value of the "api_key" field. +func (m *ModelMutation) ClearAPIKey() { + m.api_key = nil + m.clearedFields[model.FieldAPIKey] = struct{}{} } -// ResetContextLength resets all changes to the "context_length" field. -func (m *ModelMutation) ResetContextLength() { - m.context_length = nil - m.addcontext_length = nil - delete(m.clearedFields, model.FieldContextLength) +// APIKeyCleared returns if the "api_key" field was cleared in this mutation. +func (m *ModelMutation) APIKeyCleared() bool { + _, ok := m.clearedFields[model.FieldAPIKey] + return ok } -// SetCreatedAt sets the "created_at" field. -func (m *ModelMutation) SetCreatedAt(t time.Time) { - m.created_at = &t +// ResetAPIKey resets all changes to the "api_key" field. +func (m *ModelMutation) ResetAPIKey() { + m.api_key = nil + delete(m.clearedFields, model.FieldAPIKey) } -// CreatedAt returns the value of the "created_at" field in the mutation. -func (m *ModelMutation) CreatedAt() (r time.Time, exists bool) { - v := m.created_at +// SetAPIVersion sets the "api_version" field. +func (m *ModelMutation) SetAPIVersion(s string) { + m.api_version = &s +} + +// APIVersion returns the value of the "api_version" field in the mutation. +func (m *ModelMutation) APIVersion() (r string, exists bool) { + v := m.api_version if v == nil { return } return *v, true } -// OldCreatedAt returns the old "created_at" field's value of the Model entity. +// OldAPIVersion returns the old "api_version" field's value of the Model entity. // If the Model 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 *ModelMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { +func (m *ModelMutation) OldAPIVersion(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") + return v, errors.New("OldAPIVersion 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") + return v, errors.New("OldAPIVersion 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 v, fmt.Errorf("querying old value for OldAPIVersion: %w", err) } - return oldValue.CreatedAt, nil + return oldValue.APIVersion, nil } -// ResetCreatedAt resets all changes to the "created_at" field. -func (m *ModelMutation) ResetCreatedAt() { - m.created_at = nil +// ClearAPIVersion clears the value of the "api_version" field. +func (m *ModelMutation) ClearAPIVersion() { + m.api_version = nil + m.clearedFields[model.FieldAPIVersion] = struct{}{} } -// SetUpdatedAt sets the "updated_at" field. -func (m *ModelMutation) SetUpdatedAt(t time.Time) { - m.updated_at = &t +// APIVersionCleared returns if the "api_version" field was cleared in this mutation. +func (m *ModelMutation) APIVersionCleared() bool { + _, ok := m.clearedFields[model.FieldAPIVersion] + return ok } -// UpdatedAt returns the value of the "updated_at" field in the mutation. -func (m *ModelMutation) UpdatedAt() (r time.Time, exists bool) { - v := m.updated_at +// ResetAPIVersion resets all changes to the "api_version" field. +func (m *ModelMutation) ResetAPIVersion() { + m.api_version = nil + delete(m.clearedFields, model.FieldAPIVersion) +} + +// SetAPIHeader sets the "api_header" field. +func (m *ModelMutation) SetAPIHeader(s string) { + m.api_header = &s +} + +// APIHeader returns the value of the "api_header" field in the mutation. +func (m *ModelMutation) APIHeader() (r string, exists bool) { + v := m.api_header if v == nil { return } return *v, true } -// OldUpdatedAt returns the old "updated_at" field's value of the Model entity. +// OldAPIHeader returns the old "api_header" field's value of the Model entity. // If the Model 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 *ModelMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { +func (m *ModelMutation) OldAPIHeader(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") + return v, errors.New("OldAPIHeader 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") + return v, errors.New("OldAPIHeader 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 v, fmt.Errorf("querying old value for OldAPIHeader: %w", err) } - return oldValue.UpdatedAt, nil + return oldValue.APIHeader, nil } -// ResetUpdatedAt resets all changes to the "updated_at" field. -func (m *ModelMutation) ResetUpdatedAt() { - m.updated_at = nil +// ClearAPIHeader clears the value of the "api_header" field. +func (m *ModelMutation) ClearAPIHeader() { + m.api_header = nil + m.clearedFields[model.FieldAPIHeader] = struct{}{} } -// AddTaskIDs adds the "tasks" edge to the Task entity by ids. -func (m *ModelMutation) AddTaskIDs(ids ...uuid.UUID) { - if m.tasks == nil { - m.tasks = make(map[uuid.UUID]struct{}) - } - for i := range ids { - m.tasks[ids[i]] = struct{}{} - } +// APIHeaderCleared returns if the "api_header" field was cleared in this mutation. +func (m *ModelMutation) APIHeaderCleared() bool { + _, ok := m.clearedFields[model.FieldAPIHeader] + return ok } -// ClearTasks clears the "tasks" edge to the Task entity. -func (m *ModelMutation) ClearTasks() { - m.clearedtasks = true +// ResetAPIHeader resets all changes to the "api_header" field. +func (m *ModelMutation) ResetAPIHeader() { + m.api_header = nil + delete(m.clearedFields, model.FieldAPIHeader) } -// TasksCleared reports if the "tasks" edge to the Task entity was cleared. -func (m *ModelMutation) TasksCleared() bool { - return m.clearedtasks +// SetDescription sets the "description" field. +func (m *ModelMutation) SetDescription(s string) { + m.description = &s } -// RemoveTaskIDs removes the "tasks" edge to the Task entity by IDs. -func (m *ModelMutation) RemoveTaskIDs(ids ...uuid.UUID) { - if m.removedtasks == nil { - m.removedtasks = make(map[uuid.UUID]struct{}) - } - for i := range ids { - delete(m.tasks, ids[i]) - m.removedtasks[ids[i]] = struct{}{} +// Description returns the value of the "description" field in the mutation. +func (m *ModelMutation) Description() (r string, exists bool) { + v := m.description + if v == nil { + return } + return *v, true } -// RemovedTasks returns the removed IDs of the "tasks" edge to the Task entity. -func (m *ModelMutation) RemovedTasksIDs() (ids []uuid.UUID) { - for id := range m.removedtasks { - ids = append(ids, id) +// OldDescription returns the old "description" field's value of the Model entity. +// If the Model 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 *ModelMutation) OldDescription(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDescription is only allowed on UpdateOne operations") } - return + 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 } -// TasksIDs returns the "tasks" edge IDs in the mutation. -func (m *ModelMutation) TasksIDs() (ids []uuid.UUID) { - for id := range m.tasks { - ids = append(ids, id) - } - return +// ClearDescription clears the value of the "description" field. +func (m *ModelMutation) ClearDescription() { + m.description = nil + m.clearedFields[model.FieldDescription] = struct{}{} } -// ResetTasks resets all changes to the "tasks" edge. -func (m *ModelMutation) ResetTasks() { - m.tasks = nil - m.clearedtasks = false - m.removedtasks = nil +// DescriptionCleared returns if the "description" field was cleared in this mutation. +func (m *ModelMutation) DescriptionCleared() bool { + _, ok := m.clearedFields[model.FieldDescription] + return ok } -// ClearUser clears the "user" edge to the User entity. -func (m *ModelMutation) ClearUser() { - m.cleareduser = true - m.clearedFields[model.FieldUserID] = struct{}{} +// ResetDescription resets all changes to the "description" field. +func (m *ModelMutation) ResetDescription() { + m.description = nil + delete(m.clearedFields, model.FieldDescription) } -// UserCleared reports if the "user" edge to the User entity was cleared. -func (m *ModelMutation) UserCleared() bool { - return m.UserIDCleared() || m.cleareduser +// SetIsInternal sets the "is_internal" field. +func (m *ModelMutation) SetIsInternal(b bool) { + m.is_internal = &b } -// UserIDs returns the "user" edge IDs in the mutation. -// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// UserID instead. It exists only for internal usage by the builders. -func (m *ModelMutation) UserIDs() (ids []uuid.UUID) { - if id := m.user; id != nil { - ids = append(ids, *id) +// IsInternal returns the value of the "is_internal" field in the mutation. +func (m *ModelMutation) IsInternal() (r bool, exists bool) { + v := m.is_internal + if v == nil { + return } - return + return *v, true } -// ResetUser resets all changes to the "user" edge. -func (m *ModelMutation) ResetUser() { - m.user = nil - m.cleareduser = false +// OldIsInternal returns the old "is_internal" field's value of the Model entity. +// If the Model 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 *ModelMutation) OldIsInternal(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldIsInternal is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldIsInternal requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldIsInternal: %w", err) + } + return oldValue.IsInternal, nil } -// Where appends a list predicates to the ModelMutation builder. -func (m *ModelMutation) Where(ps ...predicate.Model) { - m.predicates = append(m.predicates, ps...) +// ResetIsInternal resets all changes to the "is_internal" field. +func (m *ModelMutation) ResetIsInternal() { + m.is_internal = nil } -// WhereP appends storage-level predicates to the ModelMutation builder. Using this method, -// users can use type-assertion to append predicates that do not depend on any generated package. -func (m *ModelMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.Model, len(ps)) - for i := range ps { - p[i] = ps[i] - } - m.Where(p...) +// SetProvider sets the "provider" field. +func (m *ModelMutation) SetProvider(cp consts.ModelProvider) { + m.provider = &cp } -// Op returns the operation name. -func (m *ModelMutation) Op() Op { - return m.op +// Provider returns the value of the "provider" field in the mutation. +func (m *ModelMutation) Provider() (r consts.ModelProvider, exists bool) { + v := m.provider + if v == nil { + return + } + return *v, true } -// SetOp allows setting the mutation operation. -func (m *ModelMutation) SetOp(op Op) { - m.op = op +// OldProvider returns the old "provider" field's value of the Model entity. +// If the Model 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 *ModelMutation) OldProvider(ctx context.Context) (v consts.ModelProvider, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldProvider is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldProvider requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldProvider: %w", err) + } + return oldValue.Provider, nil } -// Type returns the node type of this mutation (Model). -func (m *ModelMutation) Type() string { - return m.typ +// ResetProvider resets all changes to the "provider" field. +func (m *ModelMutation) ResetProvider() { + m.provider = nil } -// 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 *ModelMutation) Fields() []string { - fields := make([]string, 0, 16) - if m.user != nil { - fields = append(fields, model.FieldUserID) - } - if m.model_name != nil { - fields = append(fields, model.FieldModelName) - } - if m.model_type != nil { - fields = append(fields, model.FieldModelType) - } - if m.show_name != nil { - fields = append(fields, model.FieldShowName) - } - if m.api_base != nil { - fields = append(fields, model.FieldAPIBase) +// SetStatus sets the "status" field. +func (m *ModelMutation) SetStatus(cs consts.ModelStatus) { + m.status = &cs +} + +// Status returns the value of the "status" field in the mutation. +func (m *ModelMutation) Status() (r consts.ModelStatus, exists bool) { + v := m.status + if v == nil { + return } - if m.api_key != nil { - fields = append(fields, model.FieldAPIKey) + return *v, true +} + +// OldStatus returns the old "status" field's value of the Model entity. +// If the Model 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 *ModelMutation) OldStatus(ctx context.Context) (v consts.ModelStatus, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldStatus is only allowed on UpdateOne operations") } - if m.api_version != nil { - fields = append(fields, model.FieldAPIVersion) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldStatus requires an ID field in the mutation") } - if m.api_header != nil { - fields = append(fields, model.FieldAPIHeader) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldStatus: %w", err) } - if m.description != nil { - fields = append(fields, model.FieldDescription) + return oldValue.Status, nil +} + +// ResetStatus resets all changes to the "status" field. +func (m *ModelMutation) ResetStatus() { + m.status = nil +} + +// SetParameters sets the "parameters" field. +func (m *ModelMutation) SetParameters(tp *types.ModelParam) { + m.parameters = &tp +} + +// Parameters returns the value of the "parameters" field in the mutation. +func (m *ModelMutation) Parameters() (r *types.ModelParam, exists bool) { + v := m.parameters + if v == nil { + return } - if m.is_internal != nil { - fields = append(fields, model.FieldIsInternal) + return *v, true +} + +// OldParameters returns the old "parameters" field's value of the Model entity. +// If the Model 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 *ModelMutation) OldParameters(ctx context.Context) (v *types.ModelParam, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldParameters is only allowed on UpdateOne operations") } - if m.provider != nil { - fields = append(fields, model.FieldProvider) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldParameters requires an ID field in the mutation") } - if m.status != nil { - fields = append(fields, model.FieldStatus) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldParameters: %w", err) } - if m.parameters != nil { - fields = append(fields, model.FieldParameters) + return oldValue.Parameters, nil +} + +// ClearParameters clears the value of the "parameters" field. +func (m *ModelMutation) ClearParameters() { + m.parameters = nil + m.clearedFields[model.FieldParameters] = struct{}{} +} + +// ParametersCleared returns if the "parameters" field was cleared in this mutation. +func (m *ModelMutation) ParametersCleared() bool { + _, ok := m.clearedFields[model.FieldParameters] + return ok +} + +// ResetParameters resets all changes to the "parameters" field. +func (m *ModelMutation) ResetParameters() { + m.parameters = nil + delete(m.clearedFields, model.FieldParameters) +} + +// SetContextLength sets the "context_length" field. +func (m *ModelMutation) SetContextLength(i int) { + m.context_length = &i + m.addcontext_length = nil +} + +// ContextLength returns the value of the "context_length" field in the mutation. +func (m *ModelMutation) ContextLength() (r int, exists bool) { + v := m.context_length + if v == nil { + return } - if m.context_length != nil { - fields = append(fields, model.FieldContextLength) + return *v, true +} + +// OldContextLength returns the old "context_length" field's value of the Model entity. +// If the Model 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 *ModelMutation) OldContextLength(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldContextLength is only allowed on UpdateOne operations") } - if m.created_at != nil { - fields = append(fields, model.FieldCreatedAt) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldContextLength requires an ID field in the mutation") } - if m.updated_at != nil { - fields = append(fields, model.FieldUpdatedAt) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldContextLength: %w", err) } - return fields + return oldValue.ContextLength, nil } -// 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 *ModelMutation) Field(name string) (ent.Value, bool) { - switch name { - case model.FieldUserID: - return m.UserID() - case model.FieldModelName: - return m.ModelName() - case model.FieldModelType: - return m.ModelType() - case model.FieldShowName: - return m.ShowName() - case model.FieldAPIBase: - return m.APIBase() - case model.FieldAPIKey: - return m.APIKey() - case model.FieldAPIVersion: - return m.APIVersion() - case model.FieldAPIHeader: - return m.APIHeader() - case model.FieldDescription: - return m.Description() - case model.FieldIsInternal: - return m.IsInternal() - case model.FieldProvider: - return m.Provider() - case model.FieldStatus: - return m.Status() - case model.FieldParameters: - return m.Parameters() - case model.FieldContextLength: - return m.ContextLength() - case model.FieldCreatedAt: - return m.CreatedAt() - case model.FieldUpdatedAt: - return m.UpdatedAt() +// AddContextLength adds i to the "context_length" field. +func (m *ModelMutation) AddContextLength(i int) { + if m.addcontext_length != nil { + *m.addcontext_length += i + } else { + m.addcontext_length = &i } - 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 *ModelMutation) OldField(ctx context.Context, name string) (ent.Value, error) { - switch name { - case model.FieldUserID: - return m.OldUserID(ctx) - case model.FieldModelName: - return m.OldModelName(ctx) - case model.FieldModelType: - return m.OldModelType(ctx) - case model.FieldShowName: - return m.OldShowName(ctx) - case model.FieldAPIBase: - return m.OldAPIBase(ctx) - case model.FieldAPIKey: - return m.OldAPIKey(ctx) - case model.FieldAPIVersion: - return m.OldAPIVersion(ctx) - case model.FieldAPIHeader: - return m.OldAPIHeader(ctx) - case model.FieldDescription: - return m.OldDescription(ctx) - case model.FieldIsInternal: - return m.OldIsInternal(ctx) - case model.FieldProvider: - return m.OldProvider(ctx) - case model.FieldStatus: - return m.OldStatus(ctx) - case model.FieldParameters: - return m.OldParameters(ctx) - case model.FieldContextLength: - return m.OldContextLength(ctx) - case model.FieldCreatedAt: - return m.OldCreatedAt(ctx) - case model.FieldUpdatedAt: - return m.OldUpdatedAt(ctx) +// AddedContextLength returns the value that was added to the "context_length" field in this mutation. +func (m *ModelMutation) AddedContextLength() (r int, exists bool) { + v := m.addcontext_length + if v == nil { + return } - return nil, fmt.Errorf("unknown Model field %s", name) + return *v, true } -// 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 *ModelMutation) SetField(name string, value ent.Value) error { - switch name { - case model.FieldUserID: - v, ok := value.(uuid.UUID) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetUserID(v) - return nil - case model.FieldModelName: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetModelName(v) - return nil - case model.FieldModelType: - v, ok := value.(consts.ModelType) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetModelType(v) - return nil - case model.FieldShowName: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetShowName(v) - return nil - case model.FieldAPIBase: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetAPIBase(v) - return nil - case model.FieldAPIKey: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetAPIKey(v) - return nil - case model.FieldAPIVersion: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetAPIVersion(v) - return nil - case model.FieldAPIHeader: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetAPIHeader(v) - return nil - case model.FieldDescription: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetDescription(v) - return nil - case model.FieldIsInternal: - v, ok := value.(bool) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetIsInternal(v) - return nil - case model.FieldProvider: - v, ok := value.(consts.ModelProvider) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetProvider(v) - return nil - case model.FieldStatus: - v, ok := value.(consts.ModelStatus) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetStatus(v) - return nil - case model.FieldParameters: - v, ok := value.(*types.ModelParam) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetParameters(v) - return nil - case model.FieldContextLength: - v, ok := value.(int) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetContextLength(v) - return nil - case model.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 model.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 Model field %s", name) +// ClearContextLength clears the value of the "context_length" field. +func (m *ModelMutation) ClearContextLength() { + m.context_length = nil + m.addcontext_length = nil + m.clearedFields[model.FieldContextLength] = struct{}{} } -// AddedFields returns all numeric fields that were incremented/decremented during -// this mutation. -func (m *ModelMutation) AddedFields() []string { - var fields []string - if m.addcontext_length != nil { - fields = append(fields, model.FieldContextLength) - } - return fields +// ContextLengthCleared returns if the "context_length" field was cleared in this mutation. +func (m *ModelMutation) ContextLengthCleared() bool { + _, ok := m.clearedFields[model.FieldContextLength] + return ok } -// 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 *ModelMutation) AddedField(name string) (ent.Value, bool) { - switch name { - case model.FieldContextLength: - return m.AddedContextLength() - } - return nil, false +// ResetContextLength resets all changes to the "context_length" field. +func (m *ModelMutation) ResetContextLength() { + m.context_length = nil + m.addcontext_length = nil + delete(m.clearedFields, model.FieldContextLength) } -// 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 *ModelMutation) AddField(name string, value ent.Value) error { - switch name { - case model.FieldContextLength: - v, ok := value.(int) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddContextLength(v) - return nil +// SetCreatedAt sets the "created_at" field. +func (m *ModelMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *ModelMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at + if v == nil { + return } - return fmt.Errorf("unknown Model numeric field %s", name) + return *v, true } -// ClearedFields returns all nullable fields that were cleared during this -// mutation. -func (m *ModelMutation) ClearedFields() []string { - var fields []string - if m.FieldCleared(model.FieldUserID) { - fields = append(fields, model.FieldUserID) +// OldCreatedAt returns the old "created_at" field's value of the Model entity. +// If the Model 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 *ModelMutation) 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.FieldCleared(model.FieldShowName) { - fields = append(fields, model.FieldShowName) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreatedAt requires an ID field in the mutation") } - if m.FieldCleared(model.FieldAPIKey) { - fields = append(fields, model.FieldAPIKey) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) } - if m.FieldCleared(model.FieldAPIVersion) { - fields = append(fields, model.FieldAPIVersion) + return oldValue.CreatedAt, nil +} + +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *ModelMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *ModelMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *ModelMutation) UpdatedAt() (r time.Time, exists bool) { + v := m.updated_at + if v == nil { + return } - if m.FieldCleared(model.FieldAPIHeader) { - fields = append(fields, model.FieldAPIHeader) + return *v, true +} + +// OldUpdatedAt returns the old "updated_at" field's value of the Model entity. +// If the Model 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 *ModelMutation) 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.FieldCleared(model.FieldDescription) { - fields = append(fields, model.FieldDescription) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUpdatedAt requires an ID field in the mutation") } - if m.FieldCleared(model.FieldParameters) { - fields = append(fields, model.FieldParameters) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) } - if m.FieldCleared(model.FieldContextLength) { - fields = append(fields, model.FieldContextLength) + return oldValue.UpdatedAt, nil +} + +// ResetUpdatedAt resets all changes to the "updated_at" field. +func (m *ModelMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// AddTaskIDs adds the "tasks" edge to the Task entity by ids. +func (m *ModelMutation) AddTaskIDs(ids ...uuid.UUID) { + if m.tasks == nil { + m.tasks = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.tasks[ids[i]] = struct{}{} } - return fields } -// FieldCleared returns a boolean indicating if a field with the given name was -// cleared in this mutation. -func (m *ModelMutation) FieldCleared(name string) bool { - _, ok := m.clearedFields[name] - return ok +// ClearTasks clears the "tasks" edge to the Task entity. +func (m *ModelMutation) ClearTasks() { + m.clearedtasks = true } -// 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 *ModelMutation) ClearField(name string) error { - switch name { - case model.FieldUserID: - m.ClearUserID() - return nil - case model.FieldShowName: - m.ClearShowName() - return nil - case model.FieldAPIKey: - m.ClearAPIKey() - return nil - case model.FieldAPIVersion: - m.ClearAPIVersion() - return nil - case model.FieldAPIHeader: - m.ClearAPIHeader() - return nil - case model.FieldDescription: - m.ClearDescription() - return nil - case model.FieldParameters: - m.ClearParameters() - return nil - case model.FieldContextLength: - m.ClearContextLength() - return nil - } - return fmt.Errorf("unknown Model nullable field %s", name) +// TasksCleared reports if the "tasks" edge to the Task entity was cleared. +func (m *ModelMutation) TasksCleared() bool { + return m.clearedtasks } -// 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 *ModelMutation) ResetField(name string) error { - switch name { - case model.FieldUserID: - m.ResetUserID() - return nil - case model.FieldModelName: - m.ResetModelName() - return nil - case model.FieldModelType: - m.ResetModelType() - return nil - case model.FieldShowName: - m.ResetShowName() - return nil - case model.FieldAPIBase: - m.ResetAPIBase() - return nil - case model.FieldAPIKey: - m.ResetAPIKey() - return nil - case model.FieldAPIVersion: - m.ResetAPIVersion() - return nil - case model.FieldAPIHeader: - m.ResetAPIHeader() - return nil - case model.FieldDescription: - m.ResetDescription() - return nil - case model.FieldIsInternal: - m.ResetIsInternal() - return nil - case model.FieldProvider: - m.ResetProvider() - return nil - case model.FieldStatus: - m.ResetStatus() - return nil - case model.FieldParameters: - m.ResetParameters() - return nil - case model.FieldContextLength: - m.ResetContextLength() - return nil - case model.FieldCreatedAt: - m.ResetCreatedAt() - return nil - case model.FieldUpdatedAt: - m.ResetUpdatedAt() - return nil +// RemoveTaskIDs removes the "tasks" edge to the Task entity by IDs. +func (m *ModelMutation) RemoveTaskIDs(ids ...uuid.UUID) { + if m.removedtasks == nil { + m.removedtasks = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.tasks, ids[i]) + m.removedtasks[ids[i]] = struct{}{} } - return fmt.Errorf("unknown Model field %s", name) } -// AddedEdges returns all edge names that were set/added in this mutation. -func (m *ModelMutation) AddedEdges() []string { - edges := make([]string, 0, 2) - if m.tasks != nil { - edges = append(edges, model.EdgeTasks) - } - if m.user != nil { - edges = append(edges, model.EdgeUser) +// RemovedTasks returns the removed IDs of the "tasks" edge to the Task entity. +func (m *ModelMutation) RemovedTasksIDs() (ids []uuid.UUID) { + for id := range m.removedtasks { + ids = append(ids, id) } - return edges + return } -// AddedIDs returns all IDs (to other nodes) that were added for the given edge -// name in this mutation. -func (m *ModelMutation) AddedIDs(name string) []ent.Value { - switch name { - case model.EdgeTasks: - ids := make([]ent.Value, 0, len(m.tasks)) - for id := range m.tasks { - ids = append(ids, id) - } - return ids - case model.EdgeUser: - if id := m.user; id != nil { - return []ent.Value{*id} - } +// TasksIDs returns the "tasks" edge IDs in the mutation. +func (m *ModelMutation) TasksIDs() (ids []uuid.UUID) { + for id := range m.tasks { + ids = append(ids, id) } - return nil + return } -// RemovedEdges returns all edge names that were removed in this mutation. -func (m *ModelMutation) RemovedEdges() []string { - edges := make([]string, 0, 2) - if m.removedtasks != nil { - edges = append(edges, model.EdgeTasks) - } - return edges +// ResetTasks resets all changes to the "tasks" edge. +func (m *ModelMutation) ResetTasks() { + m.tasks = nil + m.clearedtasks = false + m.removedtasks = nil } -// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with -// the given name in this mutation. -func (m *ModelMutation) RemovedIDs(name string) []ent.Value { - switch name { - case model.EdgeTasks: - ids := make([]ent.Value, 0, len(m.removedtasks)) - for id := range m.removedtasks { - ids = append(ids, id) - } - return ids - } - return nil +// ClearUser clears the "user" edge to the User entity. +func (m *ModelMutation) ClearUser() { + m.cleareduser = true + m.clearedFields[model.FieldUserID] = struct{}{} } -// ClearedEdges returns all edge names that were cleared in this mutation. -func (m *ModelMutation) ClearedEdges() []string { - edges := make([]string, 0, 2) - if m.clearedtasks { - edges = append(edges, model.EdgeTasks) - } - if m.cleareduser { - edges = append(edges, model.EdgeUser) - } - return edges +// UserCleared reports if the "user" edge to the User entity was cleared. +func (m *ModelMutation) UserCleared() bool { + return m.UserIDCleared() || m.cleareduser } -// EdgeCleared returns a boolean which indicates if the edge with the given name -// was cleared in this mutation. -func (m *ModelMutation) EdgeCleared(name string) bool { - switch name { - case model.EdgeTasks: - return m.clearedtasks - case model.EdgeUser: - return m.cleareduser +// UserIDs returns the "user" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// UserID instead. It exists only for internal usage by the builders. +func (m *ModelMutation) UserIDs() (ids []uuid.UUID) { + if id := m.user; id != nil { + ids = append(ids, *id) } - return false + return } -// 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 *ModelMutation) ClearEdge(name string) error { - switch name { - case model.EdgeUser: - m.ClearUser() - return nil - } - return fmt.Errorf("unknown Model unique edge %s", name) +// ResetUser resets all changes to the "user" edge. +func (m *ModelMutation) ResetUser() { + m.user = nil + m.cleareduser = false } -// 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 *ModelMutation) ResetEdge(name string) error { - switch name { - case model.EdgeTasks: - m.ResetTasks() - return nil - case model.EdgeUser: - m.ResetUser() - return nil - } - return fmt.Errorf("unknown Model edge %s", name) +// Where appends a list predicates to the ModelMutation builder. +func (m *ModelMutation) Where(ps ...predicate.Model) { + m.predicates = append(m.predicates, ps...) } -// ModelProviderMutation represents an operation that mutates the ModelProvider nodes in the graph. -type ModelProviderMutation struct { - config - op Op - typ string - id *string - name *string - api_base *string - priority *int - addpriority *int - created_at *time.Time - updated_at *time.Time - clearedFields map[string]struct{} - models map[uuid.UUID]struct{} - removedmodels map[uuid.UUID]struct{} - clearedmodels bool - done bool - oldValue func(context.Context) (*ModelProvider, error) - predicates []predicate.ModelProvider +// WhereP appends storage-level predicates to the ModelMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *ModelMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Model, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) } -var _ ent.Mutation = (*ModelProviderMutation)(nil) +// Op returns the operation name. +func (m *ModelMutation) Op() Op { + return m.op +} -// modelproviderOption allows management of the mutation configuration using functional options. -type modelproviderOption func(*ModelProviderMutation) +// SetOp allows setting the mutation operation. +func (m *ModelMutation) SetOp(op Op) { + m.op = op +} -// newModelProviderMutation creates new mutation for the ModelProvider entity. -func newModelProviderMutation(c config, op Op, opts ...modelproviderOption) *ModelProviderMutation { - m := &ModelProviderMutation{ - config: c, - op: op, - typ: TypeModelProvider, - clearedFields: make(map[string]struct{}), - } - for _, opt := range opts { - opt(m) - } - return m +// Type returns the node type of this mutation (Model). +func (m *ModelMutation) Type() string { + return m.typ } -// withModelProviderID sets the ID field of the mutation. -func withModelProviderID(id string) modelproviderOption { - return func(m *ModelProviderMutation) { - var ( - err error - once sync.Once - value *ModelProvider - ) - m.oldValue = func(ctx context.Context) (*ModelProvider, error) { - once.Do(func() { - if m.done { - err = errors.New("querying old values post mutation is not allowed") - } else { - value, err = m.Client().ModelProvider.Get(ctx, id) - } - }) - return value, err - } - m.id = &id - } -} - -// withModelProvider sets the old ModelProvider of the mutation. -func withModelProvider(node *ModelProvider) modelproviderOption { - return func(m *ModelProviderMutation) { - m.oldValue = func(context.Context) (*ModelProvider, error) { - return node, nil - } - m.id = &node.ID +// 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 *ModelMutation) Fields() []string { + fields := make([]string, 0, 16) + if m.user != nil { + fields = append(fields, model.FieldUserID) } -} - -// 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 ModelProviderMutation) 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 ModelProviderMutation) Tx() (*Tx, error) { - if _, ok := m.driver.(*txDriver); !ok { - return nil, errors.New("db: mutation is not running in a transaction") + if m.model_name != nil { + fields = append(fields, model.FieldModelName) } - 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 ModelProvider entities. -func (m *ModelProviderMutation) SetID(id string) { - 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 *ModelProviderMutation) ID() (id string, exists bool) { - if m.id == nil { - return + if m.model_type != nil { + fields = append(fields, model.FieldModelType) } - 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 *ModelProviderMutation) IDs(ctx context.Context) ([]string, error) { - switch { - case m.op.Is(OpUpdateOne | OpDeleteOne): - id, exists := m.ID() - if exists { - return []string{id}, nil - } - fallthrough - case m.op.Is(OpUpdate | OpDelete): - return m.Client().ModelProvider.Query().Where(m.predicates...).IDs(ctx) - default: - return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + if m.show_name != nil { + fields = append(fields, model.FieldShowName) } -} - -// SetName sets the "name" field. -func (m *ModelProviderMutation) SetName(s string) { - m.name = &s -} - -// Name returns the value of the "name" field in the mutation. -func (m *ModelProviderMutation) Name() (r string, exists bool) { - v := m.name - if v == nil { - return + if m.api_base != nil { + fields = append(fields, model.FieldAPIBase) } - return *v, true -} - -// OldName returns the old "name" field's value of the ModelProvider entity. -// If the ModelProvider 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 *ModelProviderMutation) 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.api_key != nil { + fields = append(fields, model.FieldAPIKey) } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldName requires an ID field in the mutation") + if m.api_version != nil { + fields = append(fields, model.FieldAPIVersion) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldName: %w", err) + if m.api_header != nil { + fields = append(fields, model.FieldAPIHeader) } - return oldValue.Name, nil -} - -// ResetName resets all changes to the "name" field. -func (m *ModelProviderMutation) ResetName() { - m.name = nil -} - -// SetAPIBase sets the "api_base" field. -func (m *ModelProviderMutation) SetAPIBase(s string) { - m.api_base = &s -} - -// APIBase returns the value of the "api_base" field in the mutation. -func (m *ModelProviderMutation) APIBase() (r string, exists bool) { - v := m.api_base - if v == nil { - return + if m.description != nil { + fields = append(fields, model.FieldDescription) } - return *v, true -} - -// OldAPIBase returns the old "api_base" field's value of the ModelProvider entity. -// If the ModelProvider 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 *ModelProviderMutation) OldAPIBase(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldAPIBase is only allowed on UpdateOne operations") + if m.is_internal != nil { + fields = append(fields, model.FieldIsInternal) } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldAPIBase requires an ID field in the mutation") + if m.provider != nil { + fields = append(fields, model.FieldProvider) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldAPIBase: %w", err) + if m.status != nil { + fields = append(fields, model.FieldStatus) } - return oldValue.APIBase, nil -} - -// ResetAPIBase resets all changes to the "api_base" field. -func (m *ModelProviderMutation) ResetAPIBase() { - m.api_base = nil -} - -// SetPriority sets the "priority" field. -func (m *ModelProviderMutation) SetPriority(i int) { - m.priority = &i - m.addpriority = nil -} - -// Priority returns the value of the "priority" field in the mutation. -func (m *ModelProviderMutation) Priority() (r int, exists bool) { - v := m.priority - if v == nil { - return + if m.parameters != nil { + fields = append(fields, model.FieldParameters) } - return *v, true -} - -// OldPriority returns the old "priority" field's value of the ModelProvider entity. -// If the ModelProvider 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 *ModelProviderMutation) OldPriority(ctx context.Context) (v int, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldPriority is only allowed on UpdateOne operations") + if m.context_length != nil { + fields = append(fields, model.FieldContextLength) } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldPriority requires an ID field in the mutation") + if m.created_at != nil { + fields = append(fields, model.FieldCreatedAt) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldPriority: %w", err) + if m.updated_at != nil { + fields = append(fields, model.FieldUpdatedAt) } - return oldValue.Priority, nil + return fields } -// AddPriority adds i to the "priority" field. -func (m *ModelProviderMutation) AddPriority(i int) { - if m.addpriority != nil { - *m.addpriority += i - } else { - m.addpriority = &i +// 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 *ModelMutation) Field(name string) (ent.Value, bool) { + switch name { + case model.FieldUserID: + return m.UserID() + case model.FieldModelName: + return m.ModelName() + case model.FieldModelType: + return m.ModelType() + case model.FieldShowName: + return m.ShowName() + case model.FieldAPIBase: + return m.APIBase() + case model.FieldAPIKey: + return m.APIKey() + case model.FieldAPIVersion: + return m.APIVersion() + case model.FieldAPIHeader: + return m.APIHeader() + case model.FieldDescription: + return m.Description() + case model.FieldIsInternal: + return m.IsInternal() + case model.FieldProvider: + return m.Provider() + case model.FieldStatus: + return m.Status() + case model.FieldParameters: + return m.Parameters() + case model.FieldContextLength: + return m.ContextLength() + case model.FieldCreatedAt: + return m.CreatedAt() + case model.FieldUpdatedAt: + return m.UpdatedAt() } -} - -// AddedPriority returns the value that was added to the "priority" field in this mutation. -func (m *ModelProviderMutation) AddedPriority() (r int, exists bool) { - v := m.addpriority - if v == nil { - return - } - return *v, true -} - -// ResetPriority resets all changes to the "priority" field. -func (m *ModelProviderMutation) ResetPriority() { - m.priority = nil - m.addpriority = nil -} - -// SetCreatedAt sets the "created_at" field. -func (m *ModelProviderMutation) SetCreatedAt(t time.Time) { - m.created_at = &t -} - -// CreatedAt returns the value of the "created_at" field in the mutation. -func (m *ModelProviderMutation) 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 ModelProvider entity. -// If the ModelProvider 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 *ModelProviderMutation) 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 *ModelProviderMutation) ResetCreatedAt() { - m.created_at = nil -} - -// SetUpdatedAt sets the "updated_at" field. -func (m *ModelProviderMutation) SetUpdatedAt(t time.Time) { - m.updated_at = &t -} - -// UpdatedAt returns the value of the "updated_at" field in the mutation. -func (m *ModelProviderMutation) 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 ModelProvider entity. -// If the ModelProvider 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 *ModelProviderMutation) 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 *ModelProviderMutation) ResetUpdatedAt() { - m.updated_at = nil -} - -// AddModelIDs adds the "models" edge to the ModelProviderModel entity by ids. -func (m *ModelProviderMutation) AddModelIDs(ids ...uuid.UUID) { - if m.models == nil { - m.models = make(map[uuid.UUID]struct{}) - } - for i := range ids { - m.models[ids[i]] = struct{}{} - } -} - -// ClearModels clears the "models" edge to the ModelProviderModel entity. -func (m *ModelProviderMutation) ClearModels() { - m.clearedmodels = true -} - -// ModelsCleared reports if the "models" edge to the ModelProviderModel entity was cleared. -func (m *ModelProviderMutation) ModelsCleared() bool { - return m.clearedmodels -} - -// RemoveModelIDs removes the "models" edge to the ModelProviderModel entity by IDs. -func (m *ModelProviderMutation) RemoveModelIDs(ids ...uuid.UUID) { - if m.removedmodels == nil { - m.removedmodels = make(map[uuid.UUID]struct{}) - } - for i := range ids { - delete(m.models, ids[i]) - m.removedmodels[ids[i]] = struct{}{} - } -} - -// RemovedModels returns the removed IDs of the "models" edge to the ModelProviderModel entity. -func (m *ModelProviderMutation) RemovedModelsIDs() (ids []uuid.UUID) { - for id := range m.removedmodels { - ids = append(ids, id) - } - return -} - -// ModelsIDs returns the "models" edge IDs in the mutation. -func (m *ModelProviderMutation) ModelsIDs() (ids []uuid.UUID) { - for id := range m.models { - ids = append(ids, id) - } - return -} - -// ResetModels resets all changes to the "models" edge. -func (m *ModelProviderMutation) ResetModels() { - m.models = nil - m.clearedmodels = false - m.removedmodels = nil -} - -// Where appends a list predicates to the ModelProviderMutation builder. -func (m *ModelProviderMutation) Where(ps ...predicate.ModelProvider) { - m.predicates = append(m.predicates, ps...) -} - -// WhereP appends storage-level predicates to the ModelProviderMutation builder. Using this method, -// users can use type-assertion to append predicates that do not depend on any generated package. -func (m *ModelProviderMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.ModelProvider, len(ps)) - for i := range ps { - p[i] = ps[i] - } - m.Where(p...) -} - -// Op returns the operation name. -func (m *ModelProviderMutation) Op() Op { - return m.op -} - -// SetOp allows setting the mutation operation. -func (m *ModelProviderMutation) SetOp(op Op) { - m.op = op -} - -// Type returns the node type of this mutation (ModelProvider). -func (m *ModelProviderMutation) 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 *ModelProviderMutation) Fields() []string { - fields := make([]string, 0, 5) - if m.name != nil { - fields = append(fields, modelprovider.FieldName) - } - if m.api_base != nil { - fields = append(fields, modelprovider.FieldAPIBase) - } - if m.priority != nil { - fields = append(fields, modelprovider.FieldPriority) - } - if m.created_at != nil { - fields = append(fields, modelprovider.FieldCreatedAt) - } - if m.updated_at != nil { - fields = append(fields, modelprovider.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 *ModelProviderMutation) Field(name string) (ent.Value, bool) { - switch name { - case modelprovider.FieldName: - return m.Name() - case modelprovider.FieldAPIBase: - return m.APIBase() - case modelprovider.FieldPriority: - return m.Priority() - case modelprovider.FieldCreatedAt: - return m.CreatedAt() - case modelprovider.FieldUpdatedAt: - return m.UpdatedAt() - } - return nil, false + 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 *ModelProviderMutation) OldField(ctx context.Context, name string) (ent.Value, error) { +func (m *ModelMutation) OldField(ctx context.Context, name string) (ent.Value, error) { switch name { - case modelprovider.FieldName: - return m.OldName(ctx) - case modelprovider.FieldAPIBase: + case model.FieldUserID: + return m.OldUserID(ctx) + case model.FieldModelName: + return m.OldModelName(ctx) + case model.FieldModelType: + return m.OldModelType(ctx) + case model.FieldShowName: + return m.OldShowName(ctx) + case model.FieldAPIBase: return m.OldAPIBase(ctx) - case modelprovider.FieldPriority: - return m.OldPriority(ctx) - case modelprovider.FieldCreatedAt: + case model.FieldAPIKey: + return m.OldAPIKey(ctx) + case model.FieldAPIVersion: + return m.OldAPIVersion(ctx) + case model.FieldAPIHeader: + return m.OldAPIHeader(ctx) + case model.FieldDescription: + return m.OldDescription(ctx) + case model.FieldIsInternal: + return m.OldIsInternal(ctx) + case model.FieldProvider: + return m.OldProvider(ctx) + case model.FieldStatus: + return m.OldStatus(ctx) + case model.FieldParameters: + return m.OldParameters(ctx) + case model.FieldContextLength: + return m.OldContextLength(ctx) + case model.FieldCreatedAt: return m.OldCreatedAt(ctx) - case modelprovider.FieldUpdatedAt: + case model.FieldUpdatedAt: return m.OldUpdatedAt(ctx) } - return nil, fmt.Errorf("unknown ModelProvider field %s", name) + return nil, fmt.Errorf("unknown Model 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 *ModelProviderMutation) SetField(name string, value ent.Value) error { +func (m *ModelMutation) SetField(name string, value ent.Value) error { switch name { - case modelprovider.FieldName: - v, ok := value.(string) + case model.FieldUserID: + v, ok := value.(uuid.UUID) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetName(v) + m.SetUserID(v) return nil - case modelprovider.FieldAPIBase: + case model.FieldModelName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetModelName(v) + return nil + case model.FieldModelType: + v, ok := value.(consts.ModelType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetModelType(v) + return nil + case model.FieldShowName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetShowName(v) + return nil + case model.FieldAPIBase: v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } m.SetAPIBase(v) return nil - case modelprovider.FieldPriority: + case model.FieldAPIKey: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAPIKey(v) + return nil + case model.FieldAPIVersion: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAPIVersion(v) + return nil + case model.FieldAPIHeader: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAPIHeader(v) + return nil + case model.FieldDescription: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDescription(v) + return nil + case model.FieldIsInternal: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIsInternal(v) + return nil + case model.FieldProvider: + v, ok := value.(consts.ModelProvider) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetProvider(v) + return nil + case model.FieldStatus: + v, ok := value.(consts.ModelStatus) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStatus(v) + return nil + case model.FieldParameters: + v, ok := value.(*types.ModelParam) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetParameters(v) + return nil + case model.FieldContextLength: v, ok := value.(int) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetPriority(v) + m.SetContextLength(v) return nil - case modelprovider.FieldCreatedAt: + case model.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 modelprovider.FieldUpdatedAt: + case model.FieldUpdatedAt: v, ok := value.(time.Time) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) @@ -10868,15 +11003,15 @@ func (m *ModelProviderMutation) SetField(name string, value ent.Value) error { m.SetUpdatedAt(v) return nil } - return fmt.Errorf("unknown ModelProvider field %s", name) + return fmt.Errorf("unknown Model field %s", name) } // AddedFields returns all numeric fields that were incremented/decremented during // this mutation. -func (m *ModelProviderMutation) AddedFields() []string { +func (m *ModelMutation) AddedFields() []string { var fields []string - if m.addpriority != nil { - fields = append(fields, modelprovider.FieldPriority) + if m.addcontext_length != nil { + fields = append(fields, model.FieldContextLength) } return fields } @@ -10884,10 +11019,10 @@ func (m *ModelProviderMutation) AddedFields() []string { // 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 *ModelProviderMutation) AddedField(name string) (ent.Value, bool) { +func (m *ModelMutation) AddedField(name string) (ent.Value, bool) { switch name { - case modelprovider.FieldPriority: - return m.AddedPriority() + case model.FieldContextLength: + return m.AddedContextLength() } return nil, false } @@ -10895,100 +11030,191 @@ func (m *ModelProviderMutation) AddedField(name string) (ent.Value, bool) { // 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 *ModelProviderMutation) AddField(name string, value ent.Value) error { +func (m *ModelMutation) AddField(name string, value ent.Value) error { switch name { - case modelprovider.FieldPriority: + case model.FieldContextLength: v, ok := value.(int) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.AddPriority(v) + m.AddContextLength(v) return nil } - return fmt.Errorf("unknown ModelProvider numeric field %s", name) + return fmt.Errorf("unknown Model numeric field %s", name) } // ClearedFields returns all nullable fields that were cleared during this // mutation. -func (m *ModelProviderMutation) ClearedFields() []string { - return nil +func (m *ModelMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(model.FieldUserID) { + fields = append(fields, model.FieldUserID) + } + if m.FieldCleared(model.FieldShowName) { + fields = append(fields, model.FieldShowName) + } + if m.FieldCleared(model.FieldAPIKey) { + fields = append(fields, model.FieldAPIKey) + } + if m.FieldCleared(model.FieldAPIVersion) { + fields = append(fields, model.FieldAPIVersion) + } + if m.FieldCleared(model.FieldAPIHeader) { + fields = append(fields, model.FieldAPIHeader) + } + if m.FieldCleared(model.FieldDescription) { + fields = append(fields, model.FieldDescription) + } + if m.FieldCleared(model.FieldParameters) { + fields = append(fields, model.FieldParameters) + } + if m.FieldCleared(model.FieldContextLength) { + fields = append(fields, model.FieldContextLength) + } + return fields } // FieldCleared returns a boolean indicating if a field with the given name was // cleared in this mutation. -func (m *ModelProviderMutation) FieldCleared(name string) bool { +func (m *ModelMutation) 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 *ModelProviderMutation) ClearField(name string) error { - return fmt.Errorf("unknown ModelProvider nullable field %s", name) +func (m *ModelMutation) ClearField(name string) error { + switch name { + case model.FieldUserID: + m.ClearUserID() + return nil + case model.FieldShowName: + m.ClearShowName() + return nil + case model.FieldAPIKey: + m.ClearAPIKey() + return nil + case model.FieldAPIVersion: + m.ClearAPIVersion() + return nil + case model.FieldAPIHeader: + m.ClearAPIHeader() + return nil + case model.FieldDescription: + m.ClearDescription() + return nil + case model.FieldParameters: + m.ClearParameters() + return nil + case model.FieldContextLength: + m.ClearContextLength() + return nil + } + return fmt.Errorf("unknown Model 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 *ModelProviderMutation) ResetField(name string) error { +func (m *ModelMutation) ResetField(name string) error { switch name { - case modelprovider.FieldName: - m.ResetName() + case model.FieldUserID: + m.ResetUserID() return nil - case modelprovider.FieldAPIBase: + case model.FieldModelName: + m.ResetModelName() + return nil + case model.FieldModelType: + m.ResetModelType() + return nil + case model.FieldShowName: + m.ResetShowName() + return nil + case model.FieldAPIBase: m.ResetAPIBase() return nil - case modelprovider.FieldPriority: - m.ResetPriority() + case model.FieldAPIKey: + m.ResetAPIKey() return nil - case modelprovider.FieldCreatedAt: + case model.FieldAPIVersion: + m.ResetAPIVersion() + return nil + case model.FieldAPIHeader: + m.ResetAPIHeader() + return nil + case model.FieldDescription: + m.ResetDescription() + return nil + case model.FieldIsInternal: + m.ResetIsInternal() + return nil + case model.FieldProvider: + m.ResetProvider() + return nil + case model.FieldStatus: + m.ResetStatus() + return nil + case model.FieldParameters: + m.ResetParameters() + return nil + case model.FieldContextLength: + m.ResetContextLength() + return nil + case model.FieldCreatedAt: m.ResetCreatedAt() return nil - case modelprovider.FieldUpdatedAt: + case model.FieldUpdatedAt: m.ResetUpdatedAt() return nil } - return fmt.Errorf("unknown ModelProvider field %s", name) + return fmt.Errorf("unknown Model field %s", name) } // AddedEdges returns all edge names that were set/added in this mutation. -func (m *ModelProviderMutation) AddedEdges() []string { - edges := make([]string, 0, 1) - if m.models != nil { - edges = append(edges, modelprovider.EdgeModels) +func (m *ModelMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.tasks != nil { + edges = append(edges, model.EdgeTasks) + } + if m.user != nil { + edges = append(edges, model.EdgeUser) } return edges } // AddedIDs returns all IDs (to other nodes) that were added for the given edge // name in this mutation. -func (m *ModelProviderMutation) AddedIDs(name string) []ent.Value { +func (m *ModelMutation) AddedIDs(name string) []ent.Value { switch name { - case modelprovider.EdgeModels: - ids := make([]ent.Value, 0, len(m.models)) - for id := range m.models { + case model.EdgeTasks: + ids := make([]ent.Value, 0, len(m.tasks)) + for id := range m.tasks { ids = append(ids, id) } return ids + case model.EdgeUser: + if id := m.user; id != nil { + return []ent.Value{*id} + } } return nil } // RemovedEdges returns all edge names that were removed in this mutation. -func (m *ModelProviderMutation) RemovedEdges() []string { - edges := make([]string, 0, 1) - if m.removedmodels != nil { - edges = append(edges, modelprovider.EdgeModels) +func (m *ModelMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + if m.removedtasks != nil { + edges = append(edges, model.EdgeTasks) } return edges } // RemovedIDs returns all IDs (to other nodes) that were removed for the edge with // the given name in this mutation. -func (m *ModelProviderMutation) RemovedIDs(name string) []ent.Value { +func (m *ModelMutation) RemovedIDs(name string) []ent.Value { switch name { - case modelprovider.EdgeModels: - ids := make([]ent.Value, 0, len(m.removedmodels)) - for id := range m.removedmodels { + case model.EdgeTasks: + ids := make([]ent.Value, 0, len(m.removedtasks)) + for id := range m.removedtasks { ids = append(ids, id) } return ids @@ -10997,71 +11223,86 @@ func (m *ModelProviderMutation) RemovedIDs(name string) []ent.Value { } // ClearedEdges returns all edge names that were cleared in this mutation. -func (m *ModelProviderMutation) ClearedEdges() []string { - edges := make([]string, 0, 1) - if m.clearedmodels { - edges = append(edges, modelprovider.EdgeModels) +func (m *ModelMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedtasks { + edges = append(edges, model.EdgeTasks) + } + if m.cleareduser { + edges = append(edges, model.EdgeUser) } return edges } // EdgeCleared returns a boolean which indicates if the edge with the given name // was cleared in this mutation. -func (m *ModelProviderMutation) EdgeCleared(name string) bool { +func (m *ModelMutation) EdgeCleared(name string) bool { switch name { - case modelprovider.EdgeModels: - return m.clearedmodels + case model.EdgeTasks: + return m.clearedtasks + case model.EdgeUser: + return m.cleareduser } 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 *ModelProviderMutation) ClearEdge(name string) error { +func (m *ModelMutation) ClearEdge(name string) error { switch name { + case model.EdgeUser: + m.ClearUser() + return nil } - return fmt.Errorf("unknown ModelProvider unique edge %s", name) + return fmt.Errorf("unknown Model 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 *ModelProviderMutation) ResetEdge(name string) error { +func (m *ModelMutation) ResetEdge(name string) error { switch name { - case modelprovider.EdgeModels: - m.ResetModels() + case model.EdgeTasks: + m.ResetTasks() + return nil + case model.EdgeUser: + m.ResetUser() return nil } - return fmt.Errorf("unknown ModelProvider edge %s", name) + return fmt.Errorf("unknown Model edge %s", name) } -// ModelProviderModelMutation represents an operation that mutates the ModelProviderModel nodes in the graph. -type ModelProviderModelMutation struct { +// ModelProviderMutation represents an operation that mutates the ModelProvider nodes in the graph. +type ModelProviderMutation struct { config - op Op - typ string - id *uuid.UUID - name *string - created_at *time.Time - updated_at *time.Time - clearedFields map[string]struct{} - provider *string - clearedprovider bool - done bool - oldValue func(context.Context) (*ModelProviderModel, error) - predicates []predicate.ModelProviderModel + op Op + typ string + id *string + name *string + api_base *string + priority *int + addpriority *int + created_at *time.Time + updated_at *time.Time + clearedFields map[string]struct{} + models map[uuid.UUID]struct{} + removedmodels map[uuid.UUID]struct{} + clearedmodels bool + done bool + oldValue func(context.Context) (*ModelProvider, error) + predicates []predicate.ModelProvider } -var _ ent.Mutation = (*ModelProviderModelMutation)(nil) +var _ ent.Mutation = (*ModelProviderMutation)(nil) -// modelprovidermodelOption allows management of the mutation configuration using functional options. -type modelprovidermodelOption func(*ModelProviderModelMutation) +// modelproviderOption allows management of the mutation configuration using functional options. +type modelproviderOption func(*ModelProviderMutation) -// newModelProviderModelMutation creates new mutation for the ModelProviderModel entity. -func newModelProviderModelMutation(c config, op Op, opts ...modelprovidermodelOption) *ModelProviderModelMutation { - m := &ModelProviderModelMutation{ +// newModelProviderMutation creates new mutation for the ModelProvider entity. +func newModelProviderMutation(c config, op Op, opts ...modelproviderOption) *ModelProviderMutation { + m := &ModelProviderMutation{ config: c, op: op, - typ: TypeModelProviderModel, + typ: TypeModelProvider, clearedFields: make(map[string]struct{}), } for _, opt := range opts { @@ -11070,20 +11311,20 @@ func newModelProviderModelMutation(c config, op Op, opts ...modelprovidermodelOp return m } -// withModelProviderModelID sets the ID field of the mutation. -func withModelProviderModelID(id uuid.UUID) modelprovidermodelOption { - return func(m *ModelProviderModelMutation) { +// withModelProviderID sets the ID field of the mutation. +func withModelProviderID(id string) modelproviderOption { + return func(m *ModelProviderMutation) { var ( err error once sync.Once - value *ModelProviderModel + value *ModelProvider ) - m.oldValue = func(ctx context.Context) (*ModelProviderModel, error) { + m.oldValue = func(ctx context.Context) (*ModelProvider, error) { once.Do(func() { if m.done { err = errors.New("querying old values post mutation is not allowed") } else { - value, err = m.Client().ModelProviderModel.Get(ctx, id) + value, err = m.Client().ModelProvider.Get(ctx, id) } }) return value, err @@ -11092,10 +11333,10 @@ func withModelProviderModelID(id uuid.UUID) modelprovidermodelOption { } } -// withModelProviderModel sets the old ModelProviderModel of the mutation. -func withModelProviderModel(node *ModelProviderModel) modelprovidermodelOption { - return func(m *ModelProviderModelMutation) { - m.oldValue = func(context.Context) (*ModelProviderModel, error) { +// withModelProvider sets the old ModelProvider of the mutation. +func withModelProvider(node *ModelProvider) modelproviderOption { + return func(m *ModelProviderMutation) { + m.oldValue = func(context.Context) (*ModelProvider, error) { return node, nil } m.id = &node.ID @@ -11104,7 +11345,7 @@ func withModelProviderModel(node *ModelProviderModel) modelprovidermodelOption { // 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 ModelProviderModelMutation) Client() *Client { +func (m ModelProviderMutation) Client() *Client { client := &Client{config: m.config} client.init() return client @@ -11112,7 +11353,7 @@ func (m ModelProviderModelMutation) Client() *Client { // Tx returns an `ent.Tx` for mutations that were executed in transactions; // it returns an error otherwise. -func (m ModelProviderModelMutation) Tx() (*Tx, error) { +func (m ModelProviderMutation) Tx() (*Tx, error) { if _, ok := m.driver.(*txDriver); !ok { return nil, errors.New("db: mutation is not running in a transaction") } @@ -11122,14 +11363,14 @@ func (m ModelProviderModelMutation) Tx() (*Tx, error) { } // SetID sets the value of the id field. Note that this -// operation is only accepted on creation of ModelProviderModel entities. -func (m *ModelProviderModelMutation) SetID(id uuid.UUID) { +// operation is only accepted on creation of ModelProvider entities. +func (m *ModelProviderMutation) SetID(id string) { 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 *ModelProviderModelMutation) ID() (id uuid.UUID, exists bool) { +func (m *ModelProviderMutation) ID() (id string, exists bool) { if m.id == nil { return } @@ -11140,28 +11381,28 @@ func (m *ModelProviderModelMutation) ID() (id uuid.UUID, exists bool) { // 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 *ModelProviderModelMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { +func (m *ModelProviderMutation) IDs(ctx context.Context) ([]string, error) { switch { case m.op.Is(OpUpdateOne | OpDeleteOne): id, exists := m.ID() if exists { - return []uuid.UUID{id}, nil + return []string{id}, nil } fallthrough case m.op.Is(OpUpdate | OpDelete): - return m.Client().ModelProviderModel.Query().Where(m.predicates...).IDs(ctx) + return m.Client().ModelProvider.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 *ModelProviderModelMutation) SetName(s string) { +func (m *ModelProviderMutation) SetName(s string) { m.name = &s } // Name returns the value of the "name" field in the mutation. -func (m *ModelProviderModelMutation) Name() (r string, exists bool) { +func (m *ModelProviderMutation) Name() (r string, exists bool) { v := m.name if v == nil { return @@ -11169,10 +11410,10 @@ func (m *ModelProviderModelMutation) Name() (r string, exists bool) { return *v, true } -// OldName returns the old "name" field's value of the ModelProviderModel entity. -// If the ModelProviderModel object wasn't provided to the builder, the object is fetched from the database. +// OldName returns the old "name" field's value of the ModelProvider entity. +// If the ModelProvider 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 *ModelProviderModelMutation) OldName(ctx context.Context) (v string, err error) { +func (m *ModelProviderMutation) OldName(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { return v, errors.New("OldName is only allowed on UpdateOne operations") } @@ -11187,66 +11428,109 @@ func (m *ModelProviderModelMutation) OldName(ctx context.Context) (v string, err } // ResetName resets all changes to the "name" field. -func (m *ModelProviderModelMutation) ResetName() { +func (m *ModelProviderMutation) ResetName() { m.name = nil } -// SetProviderID sets the "provider_id" field. -func (m *ModelProviderModelMutation) SetProviderID(s string) { - m.provider = &s +// SetAPIBase sets the "api_base" field. +func (m *ModelProviderMutation) SetAPIBase(s string) { + m.api_base = &s } -// ProviderID returns the value of the "provider_id" field in the mutation. -func (m *ModelProviderModelMutation) ProviderID() (r string, exists bool) { - v := m.provider +// APIBase returns the value of the "api_base" field in the mutation. +func (m *ModelProviderMutation) APIBase() (r string, exists bool) { + v := m.api_base if v == nil { return } return *v, true } -// OldProviderID returns the old "provider_id" field's value of the ModelProviderModel entity. -// If the ModelProviderModel object wasn't provided to the builder, the object is fetched from the database. +// OldAPIBase returns the old "api_base" field's value of the ModelProvider entity. +// If the ModelProvider 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 *ModelProviderModelMutation) OldProviderID(ctx context.Context) (v string, err error) { +func (m *ModelProviderMutation) OldAPIBase(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldProviderID is only allowed on UpdateOne operations") + return v, errors.New("OldAPIBase is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldProviderID requires an ID field in the mutation") + return v, errors.New("OldAPIBase requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldProviderID: %w", err) + return v, fmt.Errorf("querying old value for OldAPIBase: %w", err) } - return oldValue.ProviderID, nil + return oldValue.APIBase, nil } -// ClearProviderID clears the value of the "provider_id" field. -func (m *ModelProviderModelMutation) ClearProviderID() { - m.provider = nil - m.clearedFields[modelprovidermodel.FieldProviderID] = struct{}{} +// ResetAPIBase resets all changes to the "api_base" field. +func (m *ModelProviderMutation) ResetAPIBase() { + m.api_base = nil } -// ProviderIDCleared returns if the "provider_id" field was cleared in this mutation. -func (m *ModelProviderModelMutation) ProviderIDCleared() bool { - _, ok := m.clearedFields[modelprovidermodel.FieldProviderID] - return ok +// SetPriority sets the "priority" field. +func (m *ModelProviderMutation) SetPriority(i int) { + m.priority = &i + m.addpriority = nil } -// ResetProviderID resets all changes to the "provider_id" field. -func (m *ModelProviderModelMutation) ResetProviderID() { - m.provider = nil - delete(m.clearedFields, modelprovidermodel.FieldProviderID) +// Priority returns the value of the "priority" field in the mutation. +func (m *ModelProviderMutation) Priority() (r int, exists bool) { + v := m.priority + if v == nil { + return + } + return *v, true +} + +// OldPriority returns the old "priority" field's value of the ModelProvider entity. +// If the ModelProvider 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 *ModelProviderMutation) OldPriority(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPriority is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPriority requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPriority: %w", err) + } + return oldValue.Priority, nil +} + +// AddPriority adds i to the "priority" field. +func (m *ModelProviderMutation) AddPriority(i int) { + if m.addpriority != nil { + *m.addpriority += i + } else { + m.addpriority = &i + } +} + +// AddedPriority returns the value that was added to the "priority" field in this mutation. +func (m *ModelProviderMutation) AddedPriority() (r int, exists bool) { + v := m.addpriority + if v == nil { + return + } + return *v, true +} + +// ResetPriority resets all changes to the "priority" field. +func (m *ModelProviderMutation) ResetPriority() { + m.priority = nil + m.addpriority = nil } // SetCreatedAt sets the "created_at" field. -func (m *ModelProviderModelMutation) SetCreatedAt(t time.Time) { +func (m *ModelProviderMutation) SetCreatedAt(t time.Time) { m.created_at = &t } // CreatedAt returns the value of the "created_at" field in the mutation. -func (m *ModelProviderModelMutation) CreatedAt() (r time.Time, exists bool) { +func (m *ModelProviderMutation) CreatedAt() (r time.Time, exists bool) { v := m.created_at if v == nil { return @@ -11254,10 +11538,10 @@ func (m *ModelProviderModelMutation) CreatedAt() (r time.Time, exists bool) { return *v, true } -// OldCreatedAt returns the old "created_at" field's value of the ModelProviderModel entity. -// If the ModelProviderModel object wasn't provided to the builder, the object is fetched from the database. +// OldCreatedAt returns the old "created_at" field's value of the ModelProvider entity. +// If the ModelProvider 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 *ModelProviderModelMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { +func (m *ModelProviderMutation) 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") } @@ -11272,17 +11556,17 @@ func (m *ModelProviderModelMutation) OldCreatedAt(ctx context.Context) (v time.T } // ResetCreatedAt resets all changes to the "created_at" field. -func (m *ModelProviderModelMutation) ResetCreatedAt() { +func (m *ModelProviderMutation) ResetCreatedAt() { m.created_at = nil } // SetUpdatedAt sets the "updated_at" field. -func (m *ModelProviderModelMutation) SetUpdatedAt(t time.Time) { +func (m *ModelProviderMutation) SetUpdatedAt(t time.Time) { m.updated_at = &t } // UpdatedAt returns the value of the "updated_at" field in the mutation. -func (m *ModelProviderModelMutation) UpdatedAt() (r time.Time, exists bool) { +func (m *ModelProviderMutation) UpdatedAt() (r time.Time, exists bool) { v := m.updated_at if v == nil { return @@ -11290,10 +11574,10 @@ func (m *ModelProviderModelMutation) UpdatedAt() (r time.Time, exists bool) { return *v, true } -// OldUpdatedAt returns the old "updated_at" field's value of the ModelProviderModel entity. -// If the ModelProviderModel object wasn't provided to the builder, the object is fetched from the database. +// OldUpdatedAt returns the old "updated_at" field's value of the ModelProvider entity. +// If the ModelProvider 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 *ModelProviderModelMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { +func (m *ModelProviderMutation) 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") } @@ -11308,46 +11592,73 @@ func (m *ModelProviderModelMutation) OldUpdatedAt(ctx context.Context) (v time.T } // ResetUpdatedAt resets all changes to the "updated_at" field. -func (m *ModelProviderModelMutation) ResetUpdatedAt() { +func (m *ModelProviderMutation) ResetUpdatedAt() { m.updated_at = nil } -// ClearProvider clears the "provider" edge to the ModelProvider entity. -func (m *ModelProviderModelMutation) ClearProvider() { - m.clearedprovider = true - m.clearedFields[modelprovidermodel.FieldProviderID] = struct{}{} +// AddModelIDs adds the "models" edge to the ModelProviderModel entity by ids. +func (m *ModelProviderMutation) AddModelIDs(ids ...uuid.UUID) { + if m.models == nil { + m.models = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.models[ids[i]] = struct{}{} + } } -// ProviderCleared reports if the "provider" edge to the ModelProvider entity was cleared. -func (m *ModelProviderModelMutation) ProviderCleared() bool { - return m.ProviderIDCleared() || m.clearedprovider +// ClearModels clears the "models" edge to the ModelProviderModel entity. +func (m *ModelProviderMutation) ClearModels() { + m.clearedmodels = true } -// ProviderIDs returns the "provider" edge IDs in the mutation. -// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// ProviderID instead. It exists only for internal usage by the builders. -func (m *ModelProviderModelMutation) ProviderIDs() (ids []string) { - if id := m.provider; id != nil { - ids = append(ids, *id) +// ModelsCleared reports if the "models" edge to the ModelProviderModel entity was cleared. +func (m *ModelProviderMutation) ModelsCleared() bool { + return m.clearedmodels +} + +// RemoveModelIDs removes the "models" edge to the ModelProviderModel entity by IDs. +func (m *ModelProviderMutation) RemoveModelIDs(ids ...uuid.UUID) { + if m.removedmodels == nil { + m.removedmodels = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.models, ids[i]) + m.removedmodels[ids[i]] = struct{}{} + } +} + +// RemovedModels returns the removed IDs of the "models" edge to the ModelProviderModel entity. +func (m *ModelProviderMutation) RemovedModelsIDs() (ids []uuid.UUID) { + for id := range m.removedmodels { + ids = append(ids, id) } return } -// ResetProvider resets all changes to the "provider" edge. -func (m *ModelProviderModelMutation) ResetProvider() { - m.provider = nil - m.clearedprovider = false +// ModelsIDs returns the "models" edge IDs in the mutation. +func (m *ModelProviderMutation) ModelsIDs() (ids []uuid.UUID) { + for id := range m.models { + ids = append(ids, id) + } + return } -// Where appends a list predicates to the ModelProviderModelMutation builder. -func (m *ModelProviderModelMutation) Where(ps ...predicate.ModelProviderModel) { +// ResetModels resets all changes to the "models" edge. +func (m *ModelProviderMutation) ResetModels() { + m.models = nil + m.clearedmodels = false + m.removedmodels = nil +} + +// Where appends a list predicates to the ModelProviderMutation builder. +func (m *ModelProviderMutation) Where(ps ...predicate.ModelProvider) { m.predicates = append(m.predicates, ps...) } -// WhereP appends storage-level predicates to the ModelProviderModelMutation builder. Using this method, +// WhereP appends storage-level predicates to the ModelProviderMutation builder. Using this method, // users can use type-assertion to append predicates that do not depend on any generated package. -func (m *ModelProviderModelMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.ModelProviderModel, len(ps)) +func (m *ModelProviderMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.ModelProvider, len(ps)) for i := range ps { p[i] = ps[i] } @@ -11355,36 +11666,39 @@ func (m *ModelProviderModelMutation) WhereP(ps ...func(*sql.Selector)) { } // Op returns the operation name. -func (m *ModelProviderModelMutation) Op() Op { +func (m *ModelProviderMutation) Op() Op { return m.op } // SetOp allows setting the mutation operation. -func (m *ModelProviderModelMutation) SetOp(op Op) { +func (m *ModelProviderMutation) SetOp(op Op) { m.op = op } -// Type returns the node type of this mutation (ModelProviderModel). -func (m *ModelProviderModelMutation) Type() string { +// Type returns the node type of this mutation (ModelProvider). +func (m *ModelProviderMutation) 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 *ModelProviderModelMutation) Fields() []string { - fields := make([]string, 0, 4) +func (m *ModelProviderMutation) Fields() []string { + fields := make([]string, 0, 5) if m.name != nil { - fields = append(fields, modelprovidermodel.FieldName) + fields = append(fields, modelprovider.FieldName) } - if m.provider != nil { - fields = append(fields, modelprovidermodel.FieldProviderID) + if m.api_base != nil { + fields = append(fields, modelprovider.FieldAPIBase) + } + if m.priority != nil { + fields = append(fields, modelprovider.FieldPriority) } if m.created_at != nil { - fields = append(fields, modelprovidermodel.FieldCreatedAt) + fields = append(fields, modelprovider.FieldCreatedAt) } if m.updated_at != nil { - fields = append(fields, modelprovidermodel.FieldUpdatedAt) + fields = append(fields, modelprovider.FieldUpdatedAt) } return fields } @@ -11392,15 +11706,17 @@ func (m *ModelProviderModelMutation) Fields() []string { // 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 *ModelProviderModelMutation) Field(name string) (ent.Value, bool) { +func (m *ModelProviderMutation) Field(name string) (ent.Value, bool) { switch name { - case modelprovidermodel.FieldName: + case modelprovider.FieldName: return m.Name() - case modelprovidermodel.FieldProviderID: - return m.ProviderID() - case modelprovidermodel.FieldCreatedAt: + case modelprovider.FieldAPIBase: + return m.APIBase() + case modelprovider.FieldPriority: + return m.Priority() + case modelprovider.FieldCreatedAt: return m.CreatedAt() - case modelprovidermodel.FieldUpdatedAt: + case modelprovider.FieldUpdatedAt: return m.UpdatedAt() } return nil, false @@ -11409,47 +11725,56 @@ func (m *ModelProviderModelMutation) Field(name string) (ent.Value, bool) { // 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 *ModelProviderModelMutation) OldField(ctx context.Context, name string) (ent.Value, error) { +func (m *ModelProviderMutation) OldField(ctx context.Context, name string) (ent.Value, error) { switch name { - case modelprovidermodel.FieldName: + case modelprovider.FieldName: return m.OldName(ctx) - case modelprovidermodel.FieldProviderID: - return m.OldProviderID(ctx) - case modelprovidermodel.FieldCreatedAt: + case modelprovider.FieldAPIBase: + return m.OldAPIBase(ctx) + case modelprovider.FieldPriority: + return m.OldPriority(ctx) + case modelprovider.FieldCreatedAt: return m.OldCreatedAt(ctx) - case modelprovidermodel.FieldUpdatedAt: + case modelprovider.FieldUpdatedAt: return m.OldUpdatedAt(ctx) } - return nil, fmt.Errorf("unknown ModelProviderModel field %s", name) + return nil, fmt.Errorf("unknown ModelProvider 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 *ModelProviderModelMutation) SetField(name string, value ent.Value) error { +func (m *ModelProviderMutation) SetField(name string, value ent.Value) error { switch name { - case modelprovidermodel.FieldName: + case modelprovider.FieldName: v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } m.SetName(v) return nil - case modelprovidermodel.FieldProviderID: + case modelprovider.FieldAPIBase: v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetProviderID(v) + m.SetAPIBase(v) return nil - case modelprovidermodel.FieldCreatedAt: + case modelprovider.FieldPriority: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPriority(v) + return nil + case modelprovider.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 modelprovidermodel.FieldUpdatedAt: + case modelprovider.FieldUpdatedAt: v, ok := value.(time.Time) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) @@ -11457,190 +11782,200 @@ func (m *ModelProviderModelMutation) SetField(name string, value ent.Value) erro m.SetUpdatedAt(v) return nil } - return fmt.Errorf("unknown ModelProviderModel field %s", name) + return fmt.Errorf("unknown ModelProvider field %s", name) } // AddedFields returns all numeric fields that were incremented/decremented during // this mutation. -func (m *ModelProviderModelMutation) AddedFields() []string { - return nil +func (m *ModelProviderMutation) AddedFields() []string { + var fields []string + if m.addpriority != nil { + fields = append(fields, modelprovider.FieldPriority) + } + return fields } // AddedField returns the numeric value that was incremented/decremented on a field // with the given name. The second boolean return value indicates that this field // was not set, or was not defined in the schema. -func (m *ModelProviderModelMutation) AddedField(name string) (ent.Value, bool) { +func (m *ModelProviderMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case modelprovider.FieldPriority: + return m.AddedPriority() + } 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 *ModelProviderModelMutation) AddField(name string, value ent.Value) error { +func (m *ModelProviderMutation) AddField(name string, value ent.Value) error { switch name { + case modelprovider.FieldPriority: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddPriority(v) + return nil } - return fmt.Errorf("unknown ModelProviderModel numeric field %s", name) + return fmt.Errorf("unknown ModelProvider numeric field %s", name) } // ClearedFields returns all nullable fields that were cleared during this // mutation. -func (m *ModelProviderModelMutation) ClearedFields() []string { - var fields []string - if m.FieldCleared(modelprovidermodel.FieldProviderID) { - fields = append(fields, modelprovidermodel.FieldProviderID) - } - return fields +func (m *ModelProviderMutation) ClearedFields() []string { + return nil } // FieldCleared returns a boolean indicating if a field with the given name was // cleared in this mutation. -func (m *ModelProviderModelMutation) FieldCleared(name string) bool { +func (m *ModelProviderMutation) 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 *ModelProviderModelMutation) ClearField(name string) error { - switch name { - case modelprovidermodel.FieldProviderID: - m.ClearProviderID() - return nil - } - return fmt.Errorf("unknown ModelProviderModel nullable field %s", name) +func (m *ModelProviderMutation) ClearField(name string) error { + return fmt.Errorf("unknown ModelProvider 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 *ModelProviderModelMutation) ResetField(name string) error { +func (m *ModelProviderMutation) ResetField(name string) error { switch name { - case modelprovidermodel.FieldName: + case modelprovider.FieldName: m.ResetName() return nil - case modelprovidermodel.FieldProviderID: - m.ResetProviderID() + case modelprovider.FieldAPIBase: + m.ResetAPIBase() return nil - case modelprovidermodel.FieldCreatedAt: + case modelprovider.FieldPriority: + m.ResetPriority() + return nil + case modelprovider.FieldCreatedAt: m.ResetCreatedAt() return nil - case modelprovidermodel.FieldUpdatedAt: + case modelprovider.FieldUpdatedAt: m.ResetUpdatedAt() return nil } - return fmt.Errorf("unknown ModelProviderModel field %s", name) + return fmt.Errorf("unknown ModelProvider field %s", name) } // AddedEdges returns all edge names that were set/added in this mutation. -func (m *ModelProviderModelMutation) AddedEdges() []string { +func (m *ModelProviderMutation) AddedEdges() []string { edges := make([]string, 0, 1) - if m.provider != nil { - edges = append(edges, modelprovidermodel.EdgeProvider) + if m.models != nil { + edges = append(edges, modelprovider.EdgeModels) } return edges } // AddedIDs returns all IDs (to other nodes) that were added for the given edge // name in this mutation. -func (m *ModelProviderModelMutation) AddedIDs(name string) []ent.Value { +func (m *ModelProviderMutation) AddedIDs(name string) []ent.Value { switch name { - case modelprovidermodel.EdgeProvider: - if id := m.provider; id != nil { - return []ent.Value{*id} + case modelprovider.EdgeModels: + ids := make([]ent.Value, 0, len(m.models)) + for id := range m.models { + ids = append(ids, id) } + return ids } return nil } // RemovedEdges returns all edge names that were removed in this mutation. -func (m *ModelProviderModelMutation) RemovedEdges() []string { +func (m *ModelProviderMutation) RemovedEdges() []string { edges := make([]string, 0, 1) + if m.removedmodels != nil { + edges = append(edges, modelprovider.EdgeModels) + } return edges } // RemovedIDs returns all IDs (to other nodes) that were removed for the edge with // the given name in this mutation. -func (m *ModelProviderModelMutation) RemovedIDs(name string) []ent.Value { +func (m *ModelProviderMutation) RemovedIDs(name string) []ent.Value { + switch name { + case modelprovider.EdgeModels: + ids := make([]ent.Value, 0, len(m.removedmodels)) + for id := range m.removedmodels { + ids = append(ids, id) + } + return ids + } return nil } // ClearedEdges returns all edge names that were cleared in this mutation. -func (m *ModelProviderModelMutation) ClearedEdges() []string { +func (m *ModelProviderMutation) ClearedEdges() []string { edges := make([]string, 0, 1) - if m.clearedprovider { - edges = append(edges, modelprovidermodel.EdgeProvider) + if m.clearedmodels { + edges = append(edges, modelprovider.EdgeModels) } return edges } // EdgeCleared returns a boolean which indicates if the edge with the given name // was cleared in this mutation. -func (m *ModelProviderModelMutation) EdgeCleared(name string) bool { +func (m *ModelProviderMutation) EdgeCleared(name string) bool { switch name { - case modelprovidermodel.EdgeProvider: - return m.clearedprovider + case modelprovider.EdgeModels: + return m.clearedmodels } 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 *ModelProviderModelMutation) ClearEdge(name string) error { +func (m *ModelProviderMutation) ClearEdge(name string) error { switch name { - case modelprovidermodel.EdgeProvider: - m.ClearProvider() - return nil } - return fmt.Errorf("unknown ModelProviderModel unique edge %s", name) + return fmt.Errorf("unknown ModelProvider 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 *ModelProviderModelMutation) ResetEdge(name string) error { +func (m *ModelProviderMutation) ResetEdge(name string) error { switch name { - case modelprovidermodel.EdgeProvider: - m.ResetProvider() + case modelprovider.EdgeModels: + m.ResetModels() return nil } - return fmt.Errorf("unknown ModelProviderModel edge %s", name) + return fmt.Errorf("unknown ModelProvider edge %s", name) } -// SecurityScanningMutation represents an operation that mutates the SecurityScanning nodes in the graph. -type SecurityScanningMutation struct { +// ModelProviderModelMutation represents an operation that mutates the ModelProviderModel nodes in the graph. +type ModelProviderModelMutation struct { config - op Op - typ string - id *uuid.UUID - status *consts.SecurityScanningStatus - workspace *string - language *consts.SecurityScanningLanguage - rule *string - error_message *string - created_at *time.Time - updated_at *time.Time - clearedFields map[string]struct{} - user *uuid.UUID - cleareduser bool - results map[uuid.UUID]struct{} - removedresults map[uuid.UUID]struct{} - clearedresults bool - workspace_edge *uuid.UUID - clearedworkspace_edge bool - done bool - oldValue func(context.Context) (*SecurityScanning, error) - predicates []predicate.SecurityScanning + op Op + typ string + id *uuid.UUID + name *string + created_at *time.Time + updated_at *time.Time + clearedFields map[string]struct{} + provider *string + clearedprovider bool + done bool + oldValue func(context.Context) (*ModelProviderModel, error) + predicates []predicate.ModelProviderModel } -var _ ent.Mutation = (*SecurityScanningMutation)(nil) +var _ ent.Mutation = (*ModelProviderModelMutation)(nil) -// securityscanningOption allows management of the mutation configuration using functional options. -type securityscanningOption func(*SecurityScanningMutation) +// modelprovidermodelOption allows management of the mutation configuration using functional options. +type modelprovidermodelOption func(*ModelProviderModelMutation) -// newSecurityScanningMutation creates new mutation for the SecurityScanning entity. -func newSecurityScanningMutation(c config, op Op, opts ...securityscanningOption) *SecurityScanningMutation { - m := &SecurityScanningMutation{ +// newModelProviderModelMutation creates new mutation for the ModelProviderModel entity. +func newModelProviderModelMutation(c config, op Op, opts ...modelprovidermodelOption) *ModelProviderModelMutation { + m := &ModelProviderModelMutation{ config: c, op: op, - typ: TypeSecurityScanning, + typ: TypeModelProviderModel, clearedFields: make(map[string]struct{}), } for _, opt := range opts { @@ -11649,20 +11984,20 @@ func newSecurityScanningMutation(c config, op Op, opts ...securityscanningOption return m } -// withSecurityScanningID sets the ID field of the mutation. -func withSecurityScanningID(id uuid.UUID) securityscanningOption { - return func(m *SecurityScanningMutation) { +// withModelProviderModelID sets the ID field of the mutation. +func withModelProviderModelID(id uuid.UUID) modelprovidermodelOption { + return func(m *ModelProviderModelMutation) { var ( err error once sync.Once - value *SecurityScanning + value *ModelProviderModel ) - m.oldValue = func(ctx context.Context) (*SecurityScanning, error) { + m.oldValue = func(ctx context.Context) (*ModelProviderModel, error) { once.Do(func() { if m.done { err = errors.New("querying old values post mutation is not allowed") } else { - value, err = m.Client().SecurityScanning.Get(ctx, id) + value, err = m.Client().ModelProviderModel.Get(ctx, id) } }) return value, err @@ -11671,10 +12006,10 @@ func withSecurityScanningID(id uuid.UUID) securityscanningOption { } } -// withSecurityScanning sets the old SecurityScanning of the mutation. -func withSecurityScanning(node *SecurityScanning) securityscanningOption { - return func(m *SecurityScanningMutation) { - m.oldValue = func(context.Context) (*SecurityScanning, error) { +// withModelProviderModel sets the old ModelProviderModel of the mutation. +func withModelProviderModel(node *ModelProviderModel) modelprovidermodelOption { + return func(m *ModelProviderModelMutation) { + m.oldValue = func(context.Context) (*ModelProviderModel, error) { return node, nil } m.id = &node.ID @@ -11683,7 +12018,7 @@ func withSecurityScanning(node *SecurityScanning) securityscanningOption { // Client returns a new `ent.Client` from the mutation. If the mutation was // executed in a transaction (ent.Tx), a transactional client is returned. -func (m SecurityScanningMutation) Client() *Client { +func (m ModelProviderModelMutation) Client() *Client { client := &Client{config: m.config} client.init() return client @@ -11691,7 +12026,7 @@ func (m SecurityScanningMutation) Client() *Client { // Tx returns an `ent.Tx` for mutations that were executed in transactions; // it returns an error otherwise. -func (m SecurityScanningMutation) Tx() (*Tx, error) { +func (m ModelProviderModelMutation) Tx() (*Tx, error) { if _, ok := m.driver.(*txDriver); !ok { return nil, errors.New("db: mutation is not running in a transaction") } @@ -11701,14 +12036,14 @@ func (m SecurityScanningMutation) Tx() (*Tx, error) { } // SetID sets the value of the id field. Note that this -// operation is only accepted on creation of SecurityScanning entities. -func (m *SecurityScanningMutation) SetID(id uuid.UUID) { +// operation is only accepted on creation of ModelProviderModel entities. +func (m *ModelProviderModelMutation) SetID(id uuid.UUID) { m.id = &id } // ID returns the ID value in the mutation. Note that the ID is only available // if it was provided to the builder or after it was returned from the database. -func (m *SecurityScanningMutation) ID() (id uuid.UUID, exists bool) { +func (m *ModelProviderModelMutation) ID() (id uuid.UUID, exists bool) { if m.id == nil { return } @@ -11719,7 +12054,7 @@ func (m *SecurityScanningMutation) ID() (id uuid.UUID, exists bool) { // That means, if the mutation is applied within a transaction with an isolation level such // as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated // or updated by the mutation. -func (m *SecurityScanningMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { +func (m *ModelProviderModelMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { switch { case m.op.Is(OpUpdateOne | OpDeleteOne): id, exists := m.ID() @@ -11728,492 +12063,811 @@ func (m *SecurityScanningMutation) IDs(ctx context.Context) ([]uuid.UUID, error) } fallthrough case m.op.Is(OpUpdate | OpDelete): - return m.Client().SecurityScanning.Query().Where(m.predicates...).IDs(ctx) + return m.Client().ModelProviderModel.Query().Where(m.predicates...).IDs(ctx) default: return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) } } -// SetUserID sets the "user_id" field. -func (m *SecurityScanningMutation) SetUserID(u uuid.UUID) { - m.user = &u +// SetName sets the "name" field. +func (m *ModelProviderModelMutation) SetName(s string) { + m.name = &s } -// UserID returns the value of the "user_id" field in the mutation. -func (m *SecurityScanningMutation) UserID() (r uuid.UUID, exists bool) { - v := m.user +// Name returns the value of the "name" field in the mutation. +func (m *ModelProviderModelMutation) Name() (r string, exists bool) { + v := m.name if v == nil { return } return *v, true } -// OldUserID returns the old "user_id" field's value of the SecurityScanning entity. -// If the SecurityScanning object wasn't provided to the builder, the object is fetched from the database. +// OldName returns the old "name" field's value of the ModelProviderModel entity. +// If the ModelProviderModel object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SecurityScanningMutation) OldUserID(ctx context.Context) (v uuid.UUID, err error) { +func (m *ModelProviderModelMutation) OldName(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldUserID is only allowed on UpdateOne operations") + return v, errors.New("OldName is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldUserID requires an ID field in the mutation") + 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 OldUserID: %w", err) + return v, fmt.Errorf("querying old value for OldName: %w", err) } - return oldValue.UserID, nil + return oldValue.Name, nil } -// ResetUserID resets all changes to the "user_id" field. -func (m *SecurityScanningMutation) ResetUserID() { - m.user = nil +// ResetName resets all changes to the "name" field. +func (m *ModelProviderModelMutation) ResetName() { + m.name = nil } -// SetWorkspaceID sets the "workspace_id" field. -func (m *SecurityScanningMutation) SetWorkspaceID(u uuid.UUID) { - m.workspace_edge = &u +// SetProviderID sets the "provider_id" field. +func (m *ModelProviderModelMutation) SetProviderID(s string) { + m.provider = &s } -// WorkspaceID returns the value of the "workspace_id" field in the mutation. -func (m *SecurityScanningMutation) WorkspaceID() (r uuid.UUID, exists bool) { - v := m.workspace_edge +// ProviderID returns the value of the "provider_id" field in the mutation. +func (m *ModelProviderModelMutation) ProviderID() (r string, exists bool) { + v := m.provider if v == nil { return } return *v, true } -// OldWorkspaceID returns the old "workspace_id" field's value of the SecurityScanning entity. -// If the SecurityScanning object wasn't provided to the builder, the object is fetched from the database. +// OldProviderID returns the old "provider_id" field's value of the ModelProviderModel entity. +// If the ModelProviderModel object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SecurityScanningMutation) OldWorkspaceID(ctx context.Context) (v uuid.UUID, err error) { +func (m *ModelProviderModelMutation) OldProviderID(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldWorkspaceID is only allowed on UpdateOne operations") + return v, errors.New("OldProviderID is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldWorkspaceID requires an ID field in the mutation") + return v, errors.New("OldProviderID requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldWorkspaceID: %w", err) + return v, fmt.Errorf("querying old value for OldProviderID: %w", err) } - return oldValue.WorkspaceID, nil + return oldValue.ProviderID, nil } -// ResetWorkspaceID resets all changes to the "workspace_id" field. -func (m *SecurityScanningMutation) ResetWorkspaceID() { - m.workspace_edge = nil +// ClearProviderID clears the value of the "provider_id" field. +func (m *ModelProviderModelMutation) ClearProviderID() { + m.provider = nil + m.clearedFields[modelprovidermodel.FieldProviderID] = struct{}{} } -// SetStatus sets the "status" field. -func (m *SecurityScanningMutation) SetStatus(css consts.SecurityScanningStatus) { - m.status = &css +// ProviderIDCleared returns if the "provider_id" field was cleared in this mutation. +func (m *ModelProviderModelMutation) ProviderIDCleared() bool { + _, ok := m.clearedFields[modelprovidermodel.FieldProviderID] + return ok } -// Status returns the value of the "status" field in the mutation. -func (m *SecurityScanningMutation) Status() (r consts.SecurityScanningStatus, exists bool) { - v := m.status +// ResetProviderID resets all changes to the "provider_id" field. +func (m *ModelProviderModelMutation) ResetProviderID() { + m.provider = nil + delete(m.clearedFields, modelprovidermodel.FieldProviderID) +} + +// SetCreatedAt sets the "created_at" field. +func (m *ModelProviderModelMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *ModelProviderModelMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at if v == nil { return } return *v, true } -// OldStatus returns the old "status" field's value of the SecurityScanning entity. -// If the SecurityScanning object wasn't provided to the builder, the object is fetched from the database. +// OldCreatedAt returns the old "created_at" field's value of the ModelProviderModel entity. +// If the ModelProviderModel object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SecurityScanningMutation) OldStatus(ctx context.Context) (v consts.SecurityScanningStatus, err error) { +func (m *ModelProviderModelMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldStatus is only allowed on UpdateOne operations") + return v, errors.New("OldCreatedAt 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") + 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 OldStatus: %w", err) + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) } - return oldValue.Status, nil + return oldValue.CreatedAt, nil } -// ResetStatus resets all changes to the "status" field. -func (m *SecurityScanningMutation) ResetStatus() { - m.status = nil +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *ModelProviderModelMutation) ResetCreatedAt() { + m.created_at = nil } -// SetWorkspace sets the "workspace" field. -func (m *SecurityScanningMutation) SetWorkspace(s string) { - m.workspace = &s +// SetUpdatedAt sets the "updated_at" field. +func (m *ModelProviderModelMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t } -// Workspace returns the value of the "workspace" field in the mutation. -func (m *SecurityScanningMutation) Workspace() (r string, exists bool) { - v := m.workspace +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *ModelProviderModelMutation) UpdatedAt() (r time.Time, exists bool) { + v := m.updated_at if v == nil { return } return *v, true } -// OldWorkspace returns the old "workspace" field's value of the SecurityScanning entity. -// If the SecurityScanning object wasn't provided to the builder, the object is fetched from the database. +// OldUpdatedAt returns the old "updated_at" field's value of the ModelProviderModel entity. +// If the ModelProviderModel object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SecurityScanningMutation) OldWorkspace(ctx context.Context) (v string, err error) { +func (m *ModelProviderModelMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldWorkspace is only allowed on UpdateOne operations") + return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldWorkspace requires an ID field in the mutation") + 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 OldWorkspace: %w", err) + return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) } - return oldValue.Workspace, nil + return oldValue.UpdatedAt, nil } -// ResetWorkspace resets all changes to the "workspace" field. -func (m *SecurityScanningMutation) ResetWorkspace() { - m.workspace = nil +// ResetUpdatedAt resets all changes to the "updated_at" field. +func (m *ModelProviderModelMutation) ResetUpdatedAt() { + m.updated_at = nil } -// SetLanguage sets the "language" field. -func (m *SecurityScanningMutation) SetLanguage(csl consts.SecurityScanningLanguage) { - m.language = &csl +// ClearProvider clears the "provider" edge to the ModelProvider entity. +func (m *ModelProviderModelMutation) ClearProvider() { + m.clearedprovider = true + m.clearedFields[modelprovidermodel.FieldProviderID] = struct{}{} } -// Language returns the value of the "language" field in the mutation. -func (m *SecurityScanningMutation) Language() (r consts.SecurityScanningLanguage, exists bool) { - v := m.language - if v == nil { - return - } - return *v, true +// ProviderCleared reports if the "provider" edge to the ModelProvider entity was cleared. +func (m *ModelProviderModelMutation) ProviderCleared() bool { + return m.ProviderIDCleared() || m.clearedprovider } -// OldLanguage returns the old "language" field's value of the SecurityScanning entity. -// If the SecurityScanning object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SecurityScanningMutation) OldLanguage(ctx context.Context) (v consts.SecurityScanningLanguage, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldLanguage is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldLanguage requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldLanguage: %w", err) +// ProviderIDs returns the "provider" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// ProviderID instead. It exists only for internal usage by the builders. +func (m *ModelProviderModelMutation) ProviderIDs() (ids []string) { + if id := m.provider; id != nil { + ids = append(ids, *id) } - return oldValue.Language, nil -} - -// ResetLanguage resets all changes to the "language" field. -func (m *SecurityScanningMutation) ResetLanguage() { - m.language = nil + return } -// SetRule sets the "rule" field. -func (m *SecurityScanningMutation) SetRule(s string) { - m.rule = &s +// ResetProvider resets all changes to the "provider" edge. +func (m *ModelProviderModelMutation) ResetProvider() { + m.provider = nil + m.clearedprovider = false } -// Rule returns the value of the "rule" field in the mutation. -func (m *SecurityScanningMutation) Rule() (r string, exists bool) { - v := m.rule - if v == nil { - return - } - return *v, true +// Where appends a list predicates to the ModelProviderModelMutation builder. +func (m *ModelProviderModelMutation) Where(ps ...predicate.ModelProviderModel) { + m.predicates = append(m.predicates, ps...) } -// OldRule returns the old "rule" field's value of the SecurityScanning entity. -// If the SecurityScanning object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SecurityScanningMutation) OldRule(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldRule is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldRule requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldRule: %w", err) +// WhereP appends storage-level predicates to the ModelProviderModelMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *ModelProviderModelMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.ModelProviderModel, len(ps)) + for i := range ps { + p[i] = ps[i] } - return oldValue.Rule, nil -} - -// ClearRule clears the value of the "rule" field. -func (m *SecurityScanningMutation) ClearRule() { - m.rule = nil - m.clearedFields[securityscanning.FieldRule] = struct{}{} + m.Where(p...) } -// RuleCleared returns if the "rule" field was cleared in this mutation. -func (m *SecurityScanningMutation) RuleCleared() bool { - _, ok := m.clearedFields[securityscanning.FieldRule] - return ok +// Op returns the operation name. +func (m *ModelProviderModelMutation) Op() Op { + return m.op } -// ResetRule resets all changes to the "rule" field. -func (m *SecurityScanningMutation) ResetRule() { - m.rule = nil - delete(m.clearedFields, securityscanning.FieldRule) +// SetOp allows setting the mutation operation. +func (m *ModelProviderModelMutation) SetOp(op Op) { + m.op = op } -// SetErrorMessage sets the "error_message" field. -func (m *SecurityScanningMutation) SetErrorMessage(s string) { - m.error_message = &s +// Type returns the node type of this mutation (ModelProviderModel). +func (m *ModelProviderModelMutation) Type() string { + return m.typ } -// ErrorMessage returns the value of the "error_message" field in the mutation. -func (m *SecurityScanningMutation) ErrorMessage() (r string, exists bool) { - v := m.error_message - if v == nil { - return +// 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 *ModelProviderModelMutation) Fields() []string { + fields := make([]string, 0, 4) + if m.name != nil { + fields = append(fields, modelprovidermodel.FieldName) } - return *v, true -} - -// OldErrorMessage returns the old "error_message" field's value of the SecurityScanning entity. -// If the SecurityScanning object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SecurityScanningMutation) OldErrorMessage(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldErrorMessage is only allowed on UpdateOne operations") + if m.provider != nil { + fields = append(fields, modelprovidermodel.FieldProviderID) } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldErrorMessage requires an ID field in the mutation") + if m.created_at != nil { + fields = append(fields, modelprovidermodel.FieldCreatedAt) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldErrorMessage: %w", err) + if m.updated_at != nil { + fields = append(fields, modelprovidermodel.FieldUpdatedAt) } - return oldValue.ErrorMessage, nil + return fields } -// ClearErrorMessage clears the value of the "error_message" field. -func (m *SecurityScanningMutation) ClearErrorMessage() { - m.error_message = nil - m.clearedFields[securityscanning.FieldErrorMessage] = struct{}{} +// 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 *ModelProviderModelMutation) Field(name string) (ent.Value, bool) { + switch name { + case modelprovidermodel.FieldName: + return m.Name() + case modelprovidermodel.FieldProviderID: + return m.ProviderID() + case modelprovidermodel.FieldCreatedAt: + return m.CreatedAt() + case modelprovidermodel.FieldUpdatedAt: + return m.UpdatedAt() + } + return nil, false } -// ErrorMessageCleared returns if the "error_message" field was cleared in this mutation. -func (m *SecurityScanningMutation) ErrorMessageCleared() bool { - _, ok := m.clearedFields[securityscanning.FieldErrorMessage] - return ok +// 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 *ModelProviderModelMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case modelprovidermodel.FieldName: + return m.OldName(ctx) + case modelprovidermodel.FieldProviderID: + return m.OldProviderID(ctx) + case modelprovidermodel.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case modelprovidermodel.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + } + return nil, fmt.Errorf("unknown ModelProviderModel field %s", name) } -// ResetErrorMessage resets all changes to the "error_message" field. -func (m *SecurityScanningMutation) ResetErrorMessage() { - m.error_message = nil - delete(m.clearedFields, securityscanning.FieldErrorMessage) +// 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 *ModelProviderModelMutation) SetField(name string, value ent.Value) error { + switch name { + case modelprovidermodel.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case modelprovidermodel.FieldProviderID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetProviderID(v) + return nil + case modelprovidermodel.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 modelprovidermodel.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 ModelProviderModel field %s", name) } -// SetCreatedAt sets the "created_at" field. -func (m *SecurityScanningMutation) SetCreatedAt(t time.Time) { - m.created_at = &t +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *ModelProviderModelMutation) AddedFields() []string { + return nil } -// CreatedAt returns the value of the "created_at" field in the mutation. -func (m *SecurityScanningMutation) CreatedAt() (r time.Time, exists bool) { - v := m.created_at - if v == nil { - return - } - return *v, true +// 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 *ModelProviderModelMutation) AddedField(name string) (ent.Value, bool) { + return nil, false } -// OldCreatedAt returns the old "created_at" field's value of the SecurityScanning entity. -// If the SecurityScanning object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SecurityScanningMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCreatedAt requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) +// 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 *ModelProviderModelMutation) AddField(name string, value ent.Value) error { + switch name { } - return oldValue.CreatedAt, nil + return fmt.Errorf("unknown ModelProviderModel numeric field %s", name) } -// ResetCreatedAt resets all changes to the "created_at" field. -func (m *SecurityScanningMutation) ResetCreatedAt() { - m.created_at = nil +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *ModelProviderModelMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(modelprovidermodel.FieldProviderID) { + fields = append(fields, modelprovidermodel.FieldProviderID) + } + return fields } -// SetUpdatedAt sets the "updated_at" field. -func (m *SecurityScanningMutation) SetUpdatedAt(t time.Time) { - m.updated_at = &t +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *ModelProviderModelMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok } -// UpdatedAt returns the value of the "updated_at" field in the mutation. -func (m *SecurityScanningMutation) UpdatedAt() (r time.Time, exists bool) { - v := m.updated_at - if v == nil { - return +// 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 *ModelProviderModelMutation) ClearField(name string) error { + switch name { + case modelprovidermodel.FieldProviderID: + m.ClearProviderID() + return nil } - return *v, true + return fmt.Errorf("unknown ModelProviderModel nullable field %s", name) } -// OldUpdatedAt returns the old "updated_at" field's value of the SecurityScanning entity. -// If the SecurityScanning object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SecurityScanningMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldUpdatedAt requires an ID field in the mutation") +// 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 *ModelProviderModelMutation) ResetField(name string) error { + switch name { + case modelprovidermodel.FieldName: + m.ResetName() + return nil + case modelprovidermodel.FieldProviderID: + m.ResetProviderID() + return nil + case modelprovidermodel.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case modelprovidermodel.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) + return fmt.Errorf("unknown ModelProviderModel field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *ModelProviderModelMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.provider != nil { + edges = append(edges, modelprovidermodel.EdgeProvider) } - return oldValue.UpdatedAt, nil + return edges } -// ResetUpdatedAt resets all changes to the "updated_at" field. -func (m *SecurityScanningMutation) ResetUpdatedAt() { - m.updated_at = nil +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *ModelProviderModelMutation) AddedIDs(name string) []ent.Value { + switch name { + case modelprovidermodel.EdgeProvider: + if id := m.provider; id != nil { + return []ent.Value{*id} + } + } + return nil } -// ClearUser clears the "user" edge to the User entity. -func (m *SecurityScanningMutation) ClearUser() { - m.cleareduser = true - m.clearedFields[securityscanning.FieldUserID] = struct{}{} +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *ModelProviderModelMutation) RemovedEdges() []string { + edges := make([]string, 0, 1) + return edges } -// UserCleared reports if the "user" edge to the User entity was cleared. -func (m *SecurityScanningMutation) UserCleared() bool { - return m.cleareduser +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *ModelProviderModelMutation) RemovedIDs(name string) []ent.Value { + return nil } -// UserIDs returns the "user" edge IDs in the mutation. -// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// UserID instead. It exists only for internal usage by the builders. -func (m *SecurityScanningMutation) UserIDs() (ids []uuid.UUID) { - if id := m.user; id != nil { - ids = append(ids, *id) +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *ModelProviderModelMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedprovider { + edges = append(edges, modelprovidermodel.EdgeProvider) } - return + return edges } -// ResetUser resets all changes to the "user" edge. -func (m *SecurityScanningMutation) ResetUser() { - m.user = nil - m.cleareduser = false +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *ModelProviderModelMutation) EdgeCleared(name string) bool { + switch name { + case modelprovidermodel.EdgeProvider: + return m.clearedprovider + } + return false } -// AddResultIDs adds the "results" edge to the SecurityScanningResult entity by ids. -func (m *SecurityScanningMutation) AddResultIDs(ids ...uuid.UUID) { - if m.results == nil { - m.results = make(map[uuid.UUID]struct{}) - } - for i := range ids { - m.results[ids[i]] = struct{}{} +// 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 *ModelProviderModelMutation) ClearEdge(name string) error { + switch name { + case modelprovidermodel.EdgeProvider: + m.ClearProvider() + return nil } + return fmt.Errorf("unknown ModelProviderModel unique edge %s", name) } -// ClearResults clears the "results" edge to the SecurityScanningResult entity. -func (m *SecurityScanningMutation) ClearResults() { - m.clearedresults = true +// 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 *ModelProviderModelMutation) ResetEdge(name string) error { + switch name { + case modelprovidermodel.EdgeProvider: + m.ResetProvider() + return nil + } + return fmt.Errorf("unknown ModelProviderModel edge %s", name) } -// ResultsCleared reports if the "results" edge to the SecurityScanningResult entity was cleared. -func (m *SecurityScanningMutation) ResultsCleared() bool { - return m.clearedresults +// RoleMutation represents an operation that mutates the Role nodes in the graph. +type RoleMutation struct { + config + op Op + typ string + id *int64 + name *string + description *string + created_at *time.Time + clearedFields map[string]struct{} + admins map[uuid.UUID]struct{} + removedadmins map[uuid.UUID]struct{} + clearedadmins bool + admin_roles map[uuid.UUID]struct{} + removedadmin_roles map[uuid.UUID]struct{} + clearedadmin_roles bool + done bool + oldValue func(context.Context) (*Role, error) + predicates []predicate.Role } -// RemoveResultIDs removes the "results" edge to the SecurityScanningResult entity by IDs. -func (m *SecurityScanningMutation) RemoveResultIDs(ids ...uuid.UUID) { - if m.removedresults == nil { - m.removedresults = make(map[uuid.UUID]struct{}) +var _ ent.Mutation = (*RoleMutation)(nil) + +// roleOption allows management of the mutation configuration using functional options. +type roleOption func(*RoleMutation) + +// newRoleMutation creates new mutation for the Role entity. +func newRoleMutation(c config, op Op, opts ...roleOption) *RoleMutation { + m := &RoleMutation{ + config: c, + op: op, + typ: TypeRole, + clearedFields: make(map[string]struct{}), } - for i := range ids { - delete(m.results, ids[i]) - m.removedresults[ids[i]] = struct{}{} + for _, opt := range opts { + opt(m) } + return m } -// RemovedResults returns the removed IDs of the "results" edge to the SecurityScanningResult entity. -func (m *SecurityScanningMutation) RemovedResultsIDs() (ids []uuid.UUID) { - for id := range m.removedresults { - ids = append(ids, id) +// withRoleID sets the ID field of the mutation. +func withRoleID(id int64) roleOption { + return func(m *RoleMutation) { + var ( + err error + once sync.Once + value *Role + ) + m.oldValue = func(ctx context.Context) (*Role, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Role.Get(ctx, id) + } + }) + return value, err + } + m.id = &id } - return } -// ResultsIDs returns the "results" edge IDs in the mutation. -func (m *SecurityScanningMutation) ResultsIDs() (ids []uuid.UUID) { - for id := range m.results { - ids = append(ids, id) +// withRole sets the old Role of the mutation. +func withRole(node *Role) roleOption { + return func(m *RoleMutation) { + m.oldValue = func(context.Context) (*Role, error) { + return node, nil + } + m.id = &node.ID } - return -} - -// ResetResults resets all changes to the "results" edge. -func (m *SecurityScanningMutation) ResetResults() { - m.results = nil - m.clearedresults = false - m.removedresults = nil } -// SetWorkspaceEdgeID sets the "workspace_edge" edge to the Workspace entity by id. -func (m *SecurityScanningMutation) SetWorkspaceEdgeID(id uuid.UUID) { - m.workspace_edge = &id +// 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 RoleMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client } -// ClearWorkspaceEdge clears the "workspace_edge" edge to the Workspace entity. -func (m *SecurityScanningMutation) ClearWorkspaceEdge() { - m.clearedworkspace_edge = true - m.clearedFields[securityscanning.FieldWorkspaceID] = struct{}{} +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m RoleMutation) 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 } -// WorkspaceEdgeCleared reports if the "workspace_edge" edge to the Workspace entity was cleared. -func (m *SecurityScanningMutation) WorkspaceEdgeCleared() bool { - return m.clearedworkspace_edge +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of Role entities. +func (m *RoleMutation) SetID(id int64) { + m.id = &id } -// WorkspaceEdgeID returns the "workspace_edge" edge ID in the mutation. -func (m *SecurityScanningMutation) WorkspaceEdgeID() (id uuid.UUID, exists bool) { - if m.workspace_edge != nil { - return *m.workspace_edge, true +// 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 *RoleMutation) ID() (id int64, exists bool) { + if m.id == nil { + return } - return + return *m.id, true } -// WorkspaceEdgeIDs returns the "workspace_edge" edge IDs in the mutation. -// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// WorkspaceEdgeID instead. It exists only for internal usage by the builders. -func (m *SecurityScanningMutation) WorkspaceEdgeIDs() (ids []uuid.UUID) { - if id := m.workspace_edge; id != nil { - ids = append(ids, *id) +// 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 *RoleMutation) IDs(ctx context.Context) ([]int64, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int64{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().Role.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) } - return } -// ResetWorkspaceEdge resets all changes to the "workspace_edge" edge. -func (m *SecurityScanningMutation) ResetWorkspaceEdge() { - m.workspace_edge = nil - m.clearedworkspace_edge = false +// SetName sets the "name" field. +func (m *RoleMutation) SetName(s string) { + m.name = &s } -// Where appends a list predicates to the SecurityScanningMutation builder. -func (m *SecurityScanningMutation) Where(ps ...predicate.SecurityScanning) { - m.predicates = append(m.predicates, ps...) +// Name returns the value of the "name" field in the mutation. +func (m *RoleMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true } -// WhereP appends storage-level predicates to the SecurityScanningMutation builder. Using this method, +// OldName returns the old "name" field's value of the Role entity. +// If the Role 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 *RoleMutation) 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 *RoleMutation) ResetName() { + m.name = nil +} + +// SetDescription sets the "description" field. +func (m *RoleMutation) SetDescription(s string) { + m.description = &s +} + +// Description returns the value of the "description" field in the mutation. +func (m *RoleMutation) 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 Role entity. +// If the Role 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 *RoleMutation) 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 +} + +// ResetDescription resets all changes to the "description" field. +func (m *RoleMutation) ResetDescription() { + m.description = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *RoleMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *RoleMutation) 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 Role entity. +// If the Role 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 *RoleMutation) 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 *RoleMutation) ResetCreatedAt() { + m.created_at = nil +} + +// AddAdminIDs adds the "admins" edge to the Admin entity by ids. +func (m *RoleMutation) AddAdminIDs(ids ...uuid.UUID) { + if m.admins == nil { + m.admins = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.admins[ids[i]] = struct{}{} + } +} + +// ClearAdmins clears the "admins" edge to the Admin entity. +func (m *RoleMutation) ClearAdmins() { + m.clearedadmins = true +} + +// AdminsCleared reports if the "admins" edge to the Admin entity was cleared. +func (m *RoleMutation) AdminsCleared() bool { + return m.clearedadmins +} + +// RemoveAdminIDs removes the "admins" edge to the Admin entity by IDs. +func (m *RoleMutation) RemoveAdminIDs(ids ...uuid.UUID) { + if m.removedadmins == nil { + m.removedadmins = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.admins, ids[i]) + m.removedadmins[ids[i]] = struct{}{} + } +} + +// RemovedAdmins returns the removed IDs of the "admins" edge to the Admin entity. +func (m *RoleMutation) RemovedAdminsIDs() (ids []uuid.UUID) { + for id := range m.removedadmins { + ids = append(ids, id) + } + return +} + +// AdminsIDs returns the "admins" edge IDs in the mutation. +func (m *RoleMutation) AdminsIDs() (ids []uuid.UUID) { + for id := range m.admins { + ids = append(ids, id) + } + return +} + +// ResetAdmins resets all changes to the "admins" edge. +func (m *RoleMutation) ResetAdmins() { + m.admins = nil + m.clearedadmins = false + m.removedadmins = nil +} + +// AddAdminRoleIDs adds the "admin_roles" edge to the AdminRole entity by ids. +func (m *RoleMutation) AddAdminRoleIDs(ids ...uuid.UUID) { + if m.admin_roles == nil { + m.admin_roles = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.admin_roles[ids[i]] = struct{}{} + } +} + +// ClearAdminRoles clears the "admin_roles" edge to the AdminRole entity. +func (m *RoleMutation) ClearAdminRoles() { + m.clearedadmin_roles = true +} + +// AdminRolesCleared reports if the "admin_roles" edge to the AdminRole entity was cleared. +func (m *RoleMutation) AdminRolesCleared() bool { + return m.clearedadmin_roles +} + +// RemoveAdminRoleIDs removes the "admin_roles" edge to the AdminRole entity by IDs. +func (m *RoleMutation) RemoveAdminRoleIDs(ids ...uuid.UUID) { + if m.removedadmin_roles == nil { + m.removedadmin_roles = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.admin_roles, ids[i]) + m.removedadmin_roles[ids[i]] = struct{}{} + } +} + +// RemovedAdminRoles returns the removed IDs of the "admin_roles" edge to the AdminRole entity. +func (m *RoleMutation) RemovedAdminRolesIDs() (ids []uuid.UUID) { + for id := range m.removedadmin_roles { + ids = append(ids, id) + } + return +} + +// AdminRolesIDs returns the "admin_roles" edge IDs in the mutation. +func (m *RoleMutation) AdminRolesIDs() (ids []uuid.UUID) { + for id := range m.admin_roles { + ids = append(ids, id) + } + return +} + +// ResetAdminRoles resets all changes to the "admin_roles" edge. +func (m *RoleMutation) ResetAdminRoles() { + m.admin_roles = nil + m.clearedadmin_roles = false + m.removedadmin_roles = nil +} + +// Where appends a list predicates to the RoleMutation builder. +func (m *RoleMutation) Where(ps ...predicate.Role) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the RoleMutation builder. Using this method, // users can use type-assertion to append predicates that do not depend on any generated package. -func (m *SecurityScanningMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.SecurityScanning, len(ps)) +func (m *RoleMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Role, len(ps)) for i := range ps { p[i] = ps[i] } @@ -12221,51 +12875,33 @@ func (m *SecurityScanningMutation) WhereP(ps ...func(*sql.Selector)) { } // Op returns the operation name. -func (m *SecurityScanningMutation) Op() Op { +func (m *RoleMutation) Op() Op { return m.op } // SetOp allows setting the mutation operation. -func (m *SecurityScanningMutation) SetOp(op Op) { +func (m *RoleMutation) SetOp(op Op) { m.op = op } -// Type returns the node type of this mutation (SecurityScanning). -func (m *SecurityScanningMutation) Type() string { +// Type returns the node type of this mutation (Role). +func (m *RoleMutation) Type() string { return m.typ } // Fields returns all fields that were changed during this mutation. Note that in // order to get all numeric fields that were incremented/decremented, call // AddedFields(). -func (m *SecurityScanningMutation) Fields() []string { - fields := make([]string, 0, 9) - if m.user != nil { - fields = append(fields, securityscanning.FieldUserID) - } - if m.workspace_edge != nil { - fields = append(fields, securityscanning.FieldWorkspaceID) - } - if m.status != nil { - fields = append(fields, securityscanning.FieldStatus) - } - if m.workspace != nil { - fields = append(fields, securityscanning.FieldWorkspace) - } - if m.language != nil { - fields = append(fields, securityscanning.FieldLanguage) - } - if m.rule != nil { - fields = append(fields, securityscanning.FieldRule) +func (m *RoleMutation) Fields() []string { + fields := make([]string, 0, 3) + if m.name != nil { + fields = append(fields, role.FieldName) } - if m.error_message != nil { - fields = append(fields, securityscanning.FieldErrorMessage) + if m.description != nil { + fields = append(fields, role.FieldDescription) } if m.created_at != nil { - fields = append(fields, securityscanning.FieldCreatedAt) - } - if m.updated_at != nil { - fields = append(fields, securityscanning.FieldUpdatedAt) + fields = append(fields, role.FieldCreatedAt) } return fields } @@ -12273,26 +12909,14 @@ func (m *SecurityScanningMutation) Fields() []string { // Field returns the value of a field with the given name. The second boolean // return value indicates that this field was not set, or was not defined in the // schema. -func (m *SecurityScanningMutation) Field(name string) (ent.Value, bool) { +func (m *RoleMutation) Field(name string) (ent.Value, bool) { switch name { - case securityscanning.FieldUserID: - return m.UserID() - case securityscanning.FieldWorkspaceID: - return m.WorkspaceID() - case securityscanning.FieldStatus: - return m.Status() - case securityscanning.FieldWorkspace: - return m.Workspace() - case securityscanning.FieldLanguage: - return m.Language() - case securityscanning.FieldRule: - return m.Rule() - case securityscanning.FieldErrorMessage: - return m.ErrorMessage() - case securityscanning.FieldCreatedAt: + case role.FieldName: + return m.Name() + case role.FieldDescription: + return m.Description() + case role.FieldCreatedAt: return m.CreatedAt() - case securityscanning.FieldUpdatedAt: - return m.UpdatedAt() } return nil, false } @@ -12300,246 +12924,163 @@ func (m *SecurityScanningMutation) Field(name string) (ent.Value, bool) { // OldField returns the old value of the field from the database. An error is // returned if the mutation operation is not UpdateOne, or the query to the // database failed. -func (m *SecurityScanningMutation) OldField(ctx context.Context, name string) (ent.Value, error) { +func (m *RoleMutation) OldField(ctx context.Context, name string) (ent.Value, error) { switch name { - case securityscanning.FieldUserID: - return m.OldUserID(ctx) - case securityscanning.FieldWorkspaceID: - return m.OldWorkspaceID(ctx) - case securityscanning.FieldStatus: - return m.OldStatus(ctx) - case securityscanning.FieldWorkspace: - return m.OldWorkspace(ctx) - case securityscanning.FieldLanguage: - return m.OldLanguage(ctx) - case securityscanning.FieldRule: - return m.OldRule(ctx) - case securityscanning.FieldErrorMessage: - return m.OldErrorMessage(ctx) - case securityscanning.FieldCreatedAt: + case role.FieldName: + return m.OldName(ctx) + case role.FieldDescription: + return m.OldDescription(ctx) + case role.FieldCreatedAt: return m.OldCreatedAt(ctx) - case securityscanning.FieldUpdatedAt: - return m.OldUpdatedAt(ctx) } - return nil, fmt.Errorf("unknown SecurityScanning field %s", name) + return nil, fmt.Errorf("unknown Role field %s", name) } // SetField sets the value of a field with the given name. It returns an error if // the field is not defined in the schema, or if the type mismatched the field // type. -func (m *SecurityScanningMutation) SetField(name string, value ent.Value) error { +func (m *RoleMutation) SetField(name string, value ent.Value) error { switch name { - case securityscanning.FieldUserID: - v, ok := value.(uuid.UUID) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetUserID(v) - return nil - case securityscanning.FieldWorkspaceID: - v, ok := value.(uuid.UUID) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetWorkspaceID(v) - return nil - case securityscanning.FieldStatus: - v, ok := value.(consts.SecurityScanningStatus) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetStatus(v) - return nil - case securityscanning.FieldWorkspace: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetWorkspace(v) - return nil - case securityscanning.FieldLanguage: - v, ok := value.(consts.SecurityScanningLanguage) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetLanguage(v) - return nil - case securityscanning.FieldRule: + case role.FieldName: v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetRule(v) + m.SetName(v) return nil - case securityscanning.FieldErrorMessage: + case role.FieldDescription: v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetErrorMessage(v) + m.SetDescription(v) return nil - case securityscanning.FieldCreatedAt: + case role.FieldCreatedAt: v, ok := value.(time.Time) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } m.SetCreatedAt(v) return nil - case securityscanning.FieldUpdatedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetUpdatedAt(v) - return nil } - return fmt.Errorf("unknown SecurityScanning field %s", name) + return fmt.Errorf("unknown Role field %s", name) } // AddedFields returns all numeric fields that were incremented/decremented during // this mutation. -func (m *SecurityScanningMutation) AddedFields() []string { +func (m *RoleMutation) AddedFields() []string { return nil } // AddedField returns the numeric value that was incremented/decremented on a field // with the given name. The second boolean return value indicates that this field // was not set, or was not defined in the schema. -func (m *SecurityScanningMutation) AddedField(name string) (ent.Value, bool) { +func (m *RoleMutation) AddedField(name string) (ent.Value, bool) { return nil, false } // AddField adds the value to the field with the given name. It returns an error if // the field is not defined in the schema, or if the type mismatched the field // type. -func (m *SecurityScanningMutation) AddField(name string, value ent.Value) error { +func (m *RoleMutation) AddField(name string, value ent.Value) error { switch name { } - return fmt.Errorf("unknown SecurityScanning numeric field %s", name) + return fmt.Errorf("unknown Role numeric field %s", name) } // ClearedFields returns all nullable fields that were cleared during this // mutation. -func (m *SecurityScanningMutation) ClearedFields() []string { - var fields []string - if m.FieldCleared(securityscanning.FieldRule) { - fields = append(fields, securityscanning.FieldRule) - } - if m.FieldCleared(securityscanning.FieldErrorMessage) { - fields = append(fields, securityscanning.FieldErrorMessage) - } - return fields +func (m *RoleMutation) ClearedFields() []string { + return nil } // FieldCleared returns a boolean indicating if a field with the given name was // cleared in this mutation. -func (m *SecurityScanningMutation) FieldCleared(name string) bool { +func (m *RoleMutation) FieldCleared(name string) bool { _, ok := m.clearedFields[name] return ok } // ClearField clears the value of the field with the given name. It returns an // error if the field is not defined in the schema. -func (m *SecurityScanningMutation) ClearField(name string) error { - switch name { - case securityscanning.FieldRule: - m.ClearRule() - return nil - case securityscanning.FieldErrorMessage: - m.ClearErrorMessage() - return nil - } - return fmt.Errorf("unknown SecurityScanning nullable field %s", name) +func (m *RoleMutation) ClearField(name string) error { + return fmt.Errorf("unknown Role nullable field %s", name) } // ResetField resets all changes in the mutation for the field with the given name. // It returns an error if the field is not defined in the schema. -func (m *SecurityScanningMutation) ResetField(name string) error { +func (m *RoleMutation) ResetField(name string) error { switch name { - case securityscanning.FieldUserID: - m.ResetUserID() - return nil - case securityscanning.FieldWorkspaceID: - m.ResetWorkspaceID() - return nil - case securityscanning.FieldStatus: - m.ResetStatus() - return nil - case securityscanning.FieldWorkspace: - m.ResetWorkspace() - return nil - case securityscanning.FieldLanguage: - m.ResetLanguage() - return nil - case securityscanning.FieldRule: - m.ResetRule() + case role.FieldName: + m.ResetName() return nil - case securityscanning.FieldErrorMessage: - m.ResetErrorMessage() + case role.FieldDescription: + m.ResetDescription() return nil - case securityscanning.FieldCreatedAt: + case role.FieldCreatedAt: m.ResetCreatedAt() return nil - case securityscanning.FieldUpdatedAt: - m.ResetUpdatedAt() - return nil } - return fmt.Errorf("unknown SecurityScanning field %s", name) + return fmt.Errorf("unknown Role field %s", name) } // AddedEdges returns all edge names that were set/added in this mutation. -func (m *SecurityScanningMutation) AddedEdges() []string { - edges := make([]string, 0, 3) - if m.user != nil { - edges = append(edges, securityscanning.EdgeUser) - } - if m.results != nil { - edges = append(edges, securityscanning.EdgeResults) +func (m *RoleMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.admins != nil { + edges = append(edges, role.EdgeAdmins) } - if m.workspace_edge != nil { - edges = append(edges, securityscanning.EdgeWorkspaceEdge) + if m.admin_roles != nil { + edges = append(edges, role.EdgeAdminRoles) } return edges } // AddedIDs returns all IDs (to other nodes) that were added for the given edge // name in this mutation. -func (m *SecurityScanningMutation) AddedIDs(name string) []ent.Value { +func (m *RoleMutation) AddedIDs(name string) []ent.Value { switch name { - case securityscanning.EdgeUser: - if id := m.user; id != nil { - return []ent.Value{*id} - } - case securityscanning.EdgeResults: - ids := make([]ent.Value, 0, len(m.results)) - for id := range m.results { + case role.EdgeAdmins: + ids := make([]ent.Value, 0, len(m.admins)) + for id := range m.admins { ids = append(ids, id) } return ids - case securityscanning.EdgeWorkspaceEdge: - if id := m.workspace_edge; id != nil { - return []ent.Value{*id} + case role.EdgeAdminRoles: + ids := make([]ent.Value, 0, len(m.admin_roles)) + for id := range m.admin_roles { + ids = append(ids, id) } + return ids } return nil } // RemovedEdges returns all edge names that were removed in this mutation. -func (m *SecurityScanningMutation) RemovedEdges() []string { - edges := make([]string, 0, 3) - if m.removedresults != nil { - edges = append(edges, securityscanning.EdgeResults) +func (m *RoleMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + if m.removedadmins != nil { + edges = append(edges, role.EdgeAdmins) + } + if m.removedadmin_roles != nil { + edges = append(edges, role.EdgeAdminRoles) } return edges } // RemovedIDs returns all IDs (to other nodes) that were removed for the edge with // the given name in this mutation. -func (m *SecurityScanningMutation) RemovedIDs(name string) []ent.Value { +func (m *RoleMutation) RemovedIDs(name string) []ent.Value { switch name { - case securityscanning.EdgeResults: - ids := make([]ent.Value, 0, len(m.removedresults)) - for id := range m.removedresults { + case role.EdgeAdmins: + ids := make([]ent.Value, 0, len(m.removedadmins)) + for id := range m.removedadmins { + ids = append(ids, id) + } + return ids + case role.EdgeAdminRoles: + ids := make([]ent.Value, 0, len(m.removedadmin_roles)) + for id := range m.removedadmin_roles { ids = append(ids, id) } return ids @@ -12548,111 +13089,88 @@ func (m *SecurityScanningMutation) RemovedIDs(name string) []ent.Value { } // ClearedEdges returns all edge names that were cleared in this mutation. -func (m *SecurityScanningMutation) ClearedEdges() []string { - edges := make([]string, 0, 3) - if m.cleareduser { - edges = append(edges, securityscanning.EdgeUser) - } - if m.clearedresults { - edges = append(edges, securityscanning.EdgeResults) +func (m *RoleMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedadmins { + edges = append(edges, role.EdgeAdmins) } - if m.clearedworkspace_edge { - edges = append(edges, securityscanning.EdgeWorkspaceEdge) + if m.clearedadmin_roles { + edges = append(edges, role.EdgeAdminRoles) } return edges } // EdgeCleared returns a boolean which indicates if the edge with the given name // was cleared in this mutation. -func (m *SecurityScanningMutation) EdgeCleared(name string) bool { +func (m *RoleMutation) EdgeCleared(name string) bool { switch name { - case securityscanning.EdgeUser: - return m.cleareduser - case securityscanning.EdgeResults: - return m.clearedresults - case securityscanning.EdgeWorkspaceEdge: - return m.clearedworkspace_edge + case role.EdgeAdmins: + return m.clearedadmins + case role.EdgeAdminRoles: + return m.clearedadmin_roles } return false } // ClearEdge clears the value of the edge with the given name. It returns an error // if that edge is not defined in the schema. -func (m *SecurityScanningMutation) ClearEdge(name string) error { +func (m *RoleMutation) ClearEdge(name string) error { switch name { - case securityscanning.EdgeUser: - m.ClearUser() - return nil - case securityscanning.EdgeWorkspaceEdge: - m.ClearWorkspaceEdge() - return nil } - return fmt.Errorf("unknown SecurityScanning unique edge %s", name) + return fmt.Errorf("unknown Role unique edge %s", name) } // ResetEdge resets all changes to the edge with the given name in this mutation. // It returns an error if the edge is not defined in the schema. -func (m *SecurityScanningMutation) ResetEdge(name string) error { +func (m *RoleMutation) ResetEdge(name string) error { switch name { - case securityscanning.EdgeUser: - m.ResetUser() - return nil - case securityscanning.EdgeResults: - m.ResetResults() + case role.EdgeAdmins: + m.ResetAdmins() return nil - case securityscanning.EdgeWorkspaceEdge: - m.ResetWorkspaceEdge() + case role.EdgeAdminRoles: + m.ResetAdminRoles() return nil } - return fmt.Errorf("unknown SecurityScanning edge %s", name) + return fmt.Errorf("unknown Role edge %s", name) } -// SecurityScanningResultMutation represents an operation that mutates the SecurityScanningResult nodes in the graph. -type SecurityScanningResultMutation struct { +// SecurityScanningMutation represents an operation that mutates the SecurityScanning nodes in the graph. +type SecurityScanningMutation struct { config - op Op - typ string - id *uuid.UUID - check_id *string - engine_kind *string - lines *string - _path *string - message *string - message_zh *string - severity *string - abstract_en *string - abstract_zh *string - category_en *string - category_zh *string - confidence *string - cwe *[]interface{} - appendcwe []interface{} - impact *string - owasp *[]interface{} - appendowasp []interface{} - file_content *string - start_position **types.Position - end_position **types.Position - created_at *time.Time - clearedFields map[string]struct{} - security_scanning *uuid.UUID - clearedsecurity_scanning bool - done bool - oldValue func(context.Context) (*SecurityScanningResult, error) - predicates []predicate.SecurityScanningResult + op Op + typ string + id *uuid.UUID + status *consts.SecurityScanningStatus + workspace *string + language *consts.SecurityScanningLanguage + rule *string + error_message *string + created_at *time.Time + updated_at *time.Time + clearedFields map[string]struct{} + user *uuid.UUID + cleareduser bool + results map[uuid.UUID]struct{} + removedresults map[uuid.UUID]struct{} + clearedresults bool + workspace_edge *uuid.UUID + clearedworkspace_edge bool + done bool + oldValue func(context.Context) (*SecurityScanning, error) + predicates []predicate.SecurityScanning } -var _ ent.Mutation = (*SecurityScanningResultMutation)(nil) +var _ ent.Mutation = (*SecurityScanningMutation)(nil) -// securityscanningresultOption allows management of the mutation configuration using functional options. -type securityscanningresultOption func(*SecurityScanningResultMutation) +// securityscanningOption allows management of the mutation configuration using functional options. +type securityscanningOption func(*SecurityScanningMutation) -// newSecurityScanningResultMutation creates new mutation for the SecurityScanningResult entity. -func newSecurityScanningResultMutation(c config, op Op, opts ...securityscanningresultOption) *SecurityScanningResultMutation { - m := &SecurityScanningResultMutation{ +// newSecurityScanningMutation creates new mutation for the SecurityScanning entity. +func newSecurityScanningMutation(c config, op Op, opts ...securityscanningOption) *SecurityScanningMutation { + m := &SecurityScanningMutation{ config: c, op: op, - typ: TypeSecurityScanningResult, + typ: TypeSecurityScanning, clearedFields: make(map[string]struct{}), } for _, opt := range opts { @@ -12661,20 +13179,20 @@ func newSecurityScanningResultMutation(c config, op Op, opts ...securityscanning return m } -// withSecurityScanningResultID sets the ID field of the mutation. -func withSecurityScanningResultID(id uuid.UUID) securityscanningresultOption { - return func(m *SecurityScanningResultMutation) { +// withSecurityScanningID sets the ID field of the mutation. +func withSecurityScanningID(id uuid.UUID) securityscanningOption { + return func(m *SecurityScanningMutation) { var ( err error once sync.Once - value *SecurityScanningResult + value *SecurityScanning ) - m.oldValue = func(ctx context.Context) (*SecurityScanningResult, error) { + m.oldValue = func(ctx context.Context) (*SecurityScanning, error) { once.Do(func() { if m.done { err = errors.New("querying old values post mutation is not allowed") } else { - value, err = m.Client().SecurityScanningResult.Get(ctx, id) + value, err = m.Client().SecurityScanning.Get(ctx, id) } }) return value, err @@ -12683,10 +13201,10 @@ func withSecurityScanningResultID(id uuid.UUID) securityscanningresultOption { } } -// withSecurityScanningResult sets the old SecurityScanningResult of the mutation. -func withSecurityScanningResult(node *SecurityScanningResult) securityscanningresultOption { - return func(m *SecurityScanningResultMutation) { - m.oldValue = func(context.Context) (*SecurityScanningResult, error) { +// withSecurityScanning sets the old SecurityScanning of the mutation. +func withSecurityScanning(node *SecurityScanning) securityscanningOption { + return func(m *SecurityScanningMutation) { + m.oldValue = func(context.Context) (*SecurityScanning, error) { return node, nil } m.id = &node.ID @@ -12695,7 +13213,7 @@ func withSecurityScanningResult(node *SecurityScanningResult) securityscanningre // Client returns a new `ent.Client` from the mutation. If the mutation was // executed in a transaction (ent.Tx), a transactional client is returned. -func (m SecurityScanningResultMutation) Client() *Client { +func (m SecurityScanningMutation) Client() *Client { client := &Client{config: m.config} client.init() return client @@ -12703,7 +13221,7 @@ func (m SecurityScanningResultMutation) Client() *Client { // Tx returns an `ent.Tx` for mutations that were executed in transactions; // it returns an error otherwise. -func (m SecurityScanningResultMutation) Tx() (*Tx, error) { +func (m SecurityScanningMutation) Tx() (*Tx, error) { if _, ok := m.driver.(*txDriver); !ok { return nil, errors.New("db: mutation is not running in a transaction") } @@ -12713,14 +13231,14 @@ func (m SecurityScanningResultMutation) Tx() (*Tx, error) { } // SetID sets the value of the id field. Note that this -// operation is only accepted on creation of SecurityScanningResult entities. -func (m *SecurityScanningResultMutation) SetID(id uuid.UUID) { +// operation is only accepted on creation of SecurityScanning entities. +func (m *SecurityScanningMutation) SetID(id uuid.UUID) { m.id = &id } // ID returns the ID value in the mutation. Note that the ID is only available // if it was provided to the builder or after it was returned from the database. -func (m *SecurityScanningResultMutation) ID() (id uuid.UUID, exists bool) { +func (m *SecurityScanningMutation) ID() (id uuid.UUID, exists bool) { if m.id == nil { return } @@ -12731,7 +13249,7 @@ func (m *SecurityScanningResultMutation) ID() (id uuid.UUID, exists bool) { // That means, if the mutation is applied within a transaction with an isolation level such // as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated // or updated by the mutation. -func (m *SecurityScanningResultMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { +func (m *SecurityScanningMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { switch { case m.op.Is(OpUpdateOne | OpDeleteOne): id, exists := m.ID() @@ -12740,1814 +13258,4329 @@ func (m *SecurityScanningResultMutation) IDs(ctx context.Context) ([]uuid.UUID, } fallthrough case m.op.Is(OpUpdate | OpDelete): - return m.Client().SecurityScanningResult.Query().Where(m.predicates...).IDs(ctx) + return m.Client().SecurityScanning.Query().Where(m.predicates...).IDs(ctx) default: return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) } } -// SetSecurityScanningID sets the "security_scanning_id" field. -func (m *SecurityScanningResultMutation) SetSecurityScanningID(u uuid.UUID) { - m.security_scanning = &u +// SetUserID sets the "user_id" field. +func (m *SecurityScanningMutation) SetUserID(u uuid.UUID) { + m.user = &u } -// SecurityScanningID returns the value of the "security_scanning_id" field in the mutation. -func (m *SecurityScanningResultMutation) SecurityScanningID() (r uuid.UUID, exists bool) { - v := m.security_scanning +// UserID returns the value of the "user_id" field in the mutation. +func (m *SecurityScanningMutation) UserID() (r uuid.UUID, exists bool) { + v := m.user if v == nil { return } return *v, true } -// OldSecurityScanningID returns the old "security_scanning_id" field's value of the SecurityScanningResult entity. -// If the SecurityScanningResult object wasn't provided to the builder, the object is fetched from the database. +// OldUserID returns the old "user_id" field's value of the SecurityScanning entity. +// If the SecurityScanning object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SecurityScanningResultMutation) OldSecurityScanningID(ctx context.Context) (v uuid.UUID, err error) { +func (m *SecurityScanningMutation) OldUserID(ctx context.Context) (v uuid.UUID, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldSecurityScanningID is only allowed on UpdateOne operations") + return v, errors.New("OldUserID is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldSecurityScanningID requires an ID field in the mutation") + return v, errors.New("OldUserID requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldSecurityScanningID: %w", err) + return v, fmt.Errorf("querying old value for OldUserID: %w", err) } - return oldValue.SecurityScanningID, nil + return oldValue.UserID, nil } -// ResetSecurityScanningID resets all changes to the "security_scanning_id" field. -func (m *SecurityScanningResultMutation) ResetSecurityScanningID() { - m.security_scanning = nil +// ResetUserID resets all changes to the "user_id" field. +func (m *SecurityScanningMutation) ResetUserID() { + m.user = nil } -// SetCheckID sets the "check_id" field. -func (m *SecurityScanningResultMutation) SetCheckID(s string) { - m.check_id = &s +// SetWorkspaceID sets the "workspace_id" field. +func (m *SecurityScanningMutation) SetWorkspaceID(u uuid.UUID) { + m.workspace_edge = &u } -// CheckID returns the value of the "check_id" field in the mutation. -func (m *SecurityScanningResultMutation) CheckID() (r string, exists bool) { - v := m.check_id +// WorkspaceID returns the value of the "workspace_id" field in the mutation. +func (m *SecurityScanningMutation) WorkspaceID() (r uuid.UUID, exists bool) { + v := m.workspace_edge if v == nil { return } return *v, true } -// OldCheckID returns the old "check_id" field's value of the SecurityScanningResult entity. -// If the SecurityScanningResult object wasn't provided to the builder, the object is fetched from the database. +// OldWorkspaceID returns the old "workspace_id" field's value of the SecurityScanning entity. +// If the SecurityScanning object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SecurityScanningResultMutation) OldCheckID(ctx context.Context) (v string, err error) { +func (m *SecurityScanningMutation) OldWorkspaceID(ctx context.Context) (v uuid.UUID, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCheckID is only allowed on UpdateOne operations") + return v, errors.New("OldWorkspaceID is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCheckID requires an ID field in the mutation") + return v, errors.New("OldWorkspaceID requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldCheckID: %w", err) + return v, fmt.Errorf("querying old value for OldWorkspaceID: %w", err) } - return oldValue.CheckID, nil + return oldValue.WorkspaceID, nil } -// ResetCheckID resets all changes to the "check_id" field. -func (m *SecurityScanningResultMutation) ResetCheckID() { - m.check_id = nil +// ResetWorkspaceID resets all changes to the "workspace_id" field. +func (m *SecurityScanningMutation) ResetWorkspaceID() { + m.workspace_edge = nil } -// SetEngineKind sets the "engine_kind" field. -func (m *SecurityScanningResultMutation) SetEngineKind(s string) { - m.engine_kind = &s +// SetStatus sets the "status" field. +func (m *SecurityScanningMutation) SetStatus(css consts.SecurityScanningStatus) { + m.status = &css } -// EngineKind returns the value of the "engine_kind" field in the mutation. -func (m *SecurityScanningResultMutation) EngineKind() (r string, exists bool) { - v := m.engine_kind +// Status returns the value of the "status" field in the mutation. +func (m *SecurityScanningMutation) Status() (r consts.SecurityScanningStatus, exists bool) { + v := m.status if v == nil { return } return *v, true } -// OldEngineKind returns the old "engine_kind" field's value of the SecurityScanningResult entity. -// If the SecurityScanningResult object wasn't provided to the builder, the object is fetched from the database. +// OldStatus returns the old "status" field's value of the SecurityScanning entity. +// If the SecurityScanning object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SecurityScanningResultMutation) OldEngineKind(ctx context.Context) (v string, err error) { +func (m *SecurityScanningMutation) OldStatus(ctx context.Context) (v consts.SecurityScanningStatus, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldEngineKind is only allowed on UpdateOne operations") + return v, errors.New("OldStatus is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldEngineKind requires an ID field in the mutation") + 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 OldEngineKind: %w", err) + return v, fmt.Errorf("querying old value for OldStatus: %w", err) } - return oldValue.EngineKind, nil + return oldValue.Status, nil } -// ResetEngineKind resets all changes to the "engine_kind" field. -func (m *SecurityScanningResultMutation) ResetEngineKind() { - m.engine_kind = nil +// ResetStatus resets all changes to the "status" field. +func (m *SecurityScanningMutation) ResetStatus() { + m.status = nil } -// SetLines sets the "lines" field. -func (m *SecurityScanningResultMutation) SetLines(s string) { - m.lines = &s +// SetWorkspace sets the "workspace" field. +func (m *SecurityScanningMutation) SetWorkspace(s string) { + m.workspace = &s } -// Lines returns the value of the "lines" field in the mutation. -func (m *SecurityScanningResultMutation) Lines() (r string, exists bool) { - v := m.lines +// Workspace returns the value of the "workspace" field in the mutation. +func (m *SecurityScanningMutation) Workspace() (r string, exists bool) { + v := m.workspace if v == nil { return } return *v, true } -// OldLines returns the old "lines" field's value of the SecurityScanningResult entity. -// If the SecurityScanningResult object wasn't provided to the builder, the object is fetched from the database. +// OldWorkspace returns the old "workspace" field's value of the SecurityScanning entity. +// If the SecurityScanning object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SecurityScanningResultMutation) OldLines(ctx context.Context) (v string, err error) { +func (m *SecurityScanningMutation) OldWorkspace(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldLines is only allowed on UpdateOne operations") + return v, errors.New("OldWorkspace is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldLines requires an ID field in the mutation") + return v, errors.New("OldWorkspace requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldLines: %w", err) + return v, fmt.Errorf("querying old value for OldWorkspace: %w", err) } - return oldValue.Lines, nil + return oldValue.Workspace, nil } -// ResetLines resets all changes to the "lines" field. -func (m *SecurityScanningResultMutation) ResetLines() { - m.lines = nil +// ResetWorkspace resets all changes to the "workspace" field. +func (m *SecurityScanningMutation) ResetWorkspace() { + m.workspace = nil } -// SetPath sets the "path" field. -func (m *SecurityScanningResultMutation) SetPath(s string) { - m._path = &s +// SetLanguage sets the "language" field. +func (m *SecurityScanningMutation) SetLanguage(csl consts.SecurityScanningLanguage) { + m.language = &csl } -// Path returns the value of the "path" field in the mutation. -func (m *SecurityScanningResultMutation) Path() (r string, exists bool) { - v := m._path +// Language returns the value of the "language" field in the mutation. +func (m *SecurityScanningMutation) Language() (r consts.SecurityScanningLanguage, exists bool) { + v := m.language if v == nil { return } return *v, true } -// OldPath returns the old "path" field's value of the SecurityScanningResult entity. -// If the SecurityScanningResult object wasn't provided to the builder, the object is fetched from the database. +// OldLanguage returns the old "language" field's value of the SecurityScanning entity. +// If the SecurityScanning object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SecurityScanningResultMutation) OldPath(ctx context.Context) (v string, err error) { +func (m *SecurityScanningMutation) OldLanguage(ctx context.Context) (v consts.SecurityScanningLanguage, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldPath is only allowed on UpdateOne operations") + return v, errors.New("OldLanguage is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldPath requires an ID field in the mutation") + return v, errors.New("OldLanguage requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldPath: %w", err) + return v, fmt.Errorf("querying old value for OldLanguage: %w", err) } - return oldValue.Path, nil + return oldValue.Language, nil } -// ResetPath resets all changes to the "path" field. -func (m *SecurityScanningResultMutation) ResetPath() { - m._path = nil +// ResetLanguage resets all changes to the "language" field. +func (m *SecurityScanningMutation) ResetLanguage() { + m.language = nil } -// SetMessage sets the "message" field. -func (m *SecurityScanningResultMutation) SetMessage(s string) { - m.message = &s +// SetRule sets the "rule" field. +func (m *SecurityScanningMutation) SetRule(s string) { + m.rule = &s } -// Message returns the value of the "message" field in the mutation. -func (m *SecurityScanningResultMutation) Message() (r string, exists bool) { - v := m.message +// Rule returns the value of the "rule" field in the mutation. +func (m *SecurityScanningMutation) Rule() (r string, exists bool) { + v := m.rule if v == nil { return } return *v, true } -// OldMessage returns the old "message" field's value of the SecurityScanningResult entity. -// If the SecurityScanningResult object wasn't provided to the builder, the object is fetched from the database. +// OldRule returns the old "rule" field's value of the SecurityScanning entity. +// If the SecurityScanning object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SecurityScanningResultMutation) OldMessage(ctx context.Context) (v string, err error) { +func (m *SecurityScanningMutation) OldRule(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldMessage is only allowed on UpdateOne operations") + return v, errors.New("OldRule is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldMessage requires an ID field in the mutation") + return v, errors.New("OldRule requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldMessage: %w", err) + return v, fmt.Errorf("querying old value for OldRule: %w", err) } - return oldValue.Message, nil + return oldValue.Rule, nil } -// ResetMessage resets all changes to the "message" field. -func (m *SecurityScanningResultMutation) ResetMessage() { - m.message = nil +// ClearRule clears the value of the "rule" field. +func (m *SecurityScanningMutation) ClearRule() { + m.rule = nil + m.clearedFields[securityscanning.FieldRule] = struct{}{} } -// SetMessageZh sets the "message_zh" field. -func (m *SecurityScanningResultMutation) SetMessageZh(s string) { - m.message_zh = &s +// RuleCleared returns if the "rule" field was cleared in this mutation. +func (m *SecurityScanningMutation) RuleCleared() bool { + _, ok := m.clearedFields[securityscanning.FieldRule] + return ok } -// MessageZh returns the value of the "message_zh" field in the mutation. -func (m *SecurityScanningResultMutation) MessageZh() (r string, exists bool) { - v := m.message_zh +// ResetRule resets all changes to the "rule" field. +func (m *SecurityScanningMutation) ResetRule() { + m.rule = nil + delete(m.clearedFields, securityscanning.FieldRule) +} + +// SetErrorMessage sets the "error_message" field. +func (m *SecurityScanningMutation) SetErrorMessage(s string) { + m.error_message = &s +} + +// ErrorMessage returns the value of the "error_message" field in the mutation. +func (m *SecurityScanningMutation) ErrorMessage() (r string, exists bool) { + v := m.error_message if v == nil { return } return *v, true } -// OldMessageZh returns the old "message_zh" field's value of the SecurityScanningResult entity. -// If the SecurityScanningResult object wasn't provided to the builder, the object is fetched from the database. +// OldErrorMessage returns the old "error_message" field's value of the SecurityScanning entity. +// If the SecurityScanning object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SecurityScanningResultMutation) OldMessageZh(ctx context.Context) (v string, err error) { +func (m *SecurityScanningMutation) OldErrorMessage(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldMessageZh is only allowed on UpdateOne operations") + return v, errors.New("OldErrorMessage is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldMessageZh requires an ID field in the mutation") + return v, errors.New("OldErrorMessage requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldMessageZh: %w", err) + return v, fmt.Errorf("querying old value for OldErrorMessage: %w", err) } - return oldValue.MessageZh, nil + return oldValue.ErrorMessage, nil } -// ResetMessageZh resets all changes to the "message_zh" field. -func (m *SecurityScanningResultMutation) ResetMessageZh() { - m.message_zh = nil +// ClearErrorMessage clears the value of the "error_message" field. +func (m *SecurityScanningMutation) ClearErrorMessage() { + m.error_message = nil + m.clearedFields[securityscanning.FieldErrorMessage] = struct{}{} } -// SetSeverity sets the "severity" field. -func (m *SecurityScanningResultMutation) SetSeverity(s string) { - m.severity = &s +// ErrorMessageCleared returns if the "error_message" field was cleared in this mutation. +func (m *SecurityScanningMutation) ErrorMessageCleared() bool { + _, ok := m.clearedFields[securityscanning.FieldErrorMessage] + return ok } -// Severity returns the value of the "severity" field in the mutation. -func (m *SecurityScanningResultMutation) Severity() (r string, exists bool) { - v := m.severity +// ResetErrorMessage resets all changes to the "error_message" field. +func (m *SecurityScanningMutation) ResetErrorMessage() { + m.error_message = nil + delete(m.clearedFields, securityscanning.FieldErrorMessage) +} + +// SetCreatedAt sets the "created_at" field. +func (m *SecurityScanningMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *SecurityScanningMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at if v == nil { return } return *v, true } -// OldSeverity returns the old "severity" field's value of the SecurityScanningResult entity. -// If the SecurityScanningResult object wasn't provided to the builder, the object is fetched from the database. +// OldCreatedAt returns the old "created_at" field's value of the SecurityScanning entity. +// If the SecurityScanning object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SecurityScanningResultMutation) OldSeverity(ctx context.Context) (v string, err error) { +func (m *SecurityScanningMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldSeverity is only allowed on UpdateOne operations") + return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldSeverity requires an ID field in the mutation") + 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 OldSeverity: %w", err) + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) } - return oldValue.Severity, nil + return oldValue.CreatedAt, nil } -// ResetSeverity resets all changes to the "severity" field. -func (m *SecurityScanningResultMutation) ResetSeverity() { - m.severity = nil +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *SecurityScanningMutation) ResetCreatedAt() { + m.created_at = nil } -// SetAbstractEn sets the "abstract_en" field. -func (m *SecurityScanningResultMutation) SetAbstractEn(s string) { - m.abstract_en = &s +// SetUpdatedAt sets the "updated_at" field. +func (m *SecurityScanningMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t } -// AbstractEn returns the value of the "abstract_en" field in the mutation. -func (m *SecurityScanningResultMutation) AbstractEn() (r string, exists bool) { - v := m.abstract_en +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *SecurityScanningMutation) UpdatedAt() (r time.Time, exists bool) { + v := m.updated_at if v == nil { return } return *v, true } -// OldAbstractEn returns the old "abstract_en" field's value of the SecurityScanningResult entity. -// If the SecurityScanningResult object wasn't provided to the builder, the object is fetched from the database. +// OldUpdatedAt returns the old "updated_at" field's value of the SecurityScanning entity. +// If the SecurityScanning object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SecurityScanningResultMutation) OldAbstractEn(ctx context.Context) (v string, err error) { +func (m *SecurityScanningMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldAbstractEn is only allowed on UpdateOne operations") + return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldAbstractEn requires an ID field in the mutation") + 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 OldAbstractEn: %w", err) + return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) } - return oldValue.AbstractEn, nil + return oldValue.UpdatedAt, nil } -// ResetAbstractEn resets all changes to the "abstract_en" field. -func (m *SecurityScanningResultMutation) ResetAbstractEn() { - m.abstract_en = nil +// ResetUpdatedAt resets all changes to the "updated_at" field. +func (m *SecurityScanningMutation) ResetUpdatedAt() { + m.updated_at = nil } -// SetAbstractZh sets the "abstract_zh" field. -func (m *SecurityScanningResultMutation) SetAbstractZh(s string) { - m.abstract_zh = &s +// ClearUser clears the "user" edge to the User entity. +func (m *SecurityScanningMutation) ClearUser() { + m.cleareduser = true + m.clearedFields[securityscanning.FieldUserID] = struct{}{} } -// AbstractZh returns the value of the "abstract_zh" field in the mutation. -func (m *SecurityScanningResultMutation) AbstractZh() (r string, exists bool) { - v := m.abstract_zh - if v == nil { - return - } - return *v, true +// UserCleared reports if the "user" edge to the User entity was cleared. +func (m *SecurityScanningMutation) UserCleared() bool { + return m.cleareduser } -// OldAbstractZh returns the old "abstract_zh" field's value of the SecurityScanningResult entity. -// If the SecurityScanningResult object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SecurityScanningResultMutation) OldAbstractZh(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldAbstractZh is only allowed on UpdateOne operations") +// UserIDs returns the "user" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// UserID instead. It exists only for internal usage by the builders. +func (m *SecurityScanningMutation) UserIDs() (ids []uuid.UUID) { + if id := m.user; id != nil { + ids = append(ids, *id) } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldAbstractZh requires an ID field in the mutation") + return +} + +// ResetUser resets all changes to the "user" edge. +func (m *SecurityScanningMutation) ResetUser() { + m.user = nil + m.cleareduser = false +} + +// AddResultIDs adds the "results" edge to the SecurityScanningResult entity by ids. +func (m *SecurityScanningMutation) AddResultIDs(ids ...uuid.UUID) { + if m.results == nil { + m.results = make(map[uuid.UUID]struct{}) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldAbstractZh: %w", err) + for i := range ids { + m.results[ids[i]] = struct{}{} } - return oldValue.AbstractZh, nil } -// ResetAbstractZh resets all changes to the "abstract_zh" field. -func (m *SecurityScanningResultMutation) ResetAbstractZh() { - m.abstract_zh = nil +// ClearResults clears the "results" edge to the SecurityScanningResult entity. +func (m *SecurityScanningMutation) ClearResults() { + m.clearedresults = true } -// SetCategoryEn sets the "category_en" field. -func (m *SecurityScanningResultMutation) SetCategoryEn(s string) { - m.category_en = &s +// ResultsCleared reports if the "results" edge to the SecurityScanningResult entity was cleared. +func (m *SecurityScanningMutation) ResultsCleared() bool { + return m.clearedresults } -// CategoryEn returns the value of the "category_en" field in the mutation. -func (m *SecurityScanningResultMutation) CategoryEn() (r string, exists bool) { - v := m.category_en - if v == nil { - return +// RemoveResultIDs removes the "results" edge to the SecurityScanningResult entity by IDs. +func (m *SecurityScanningMutation) RemoveResultIDs(ids ...uuid.UUID) { + if m.removedresults == nil { + m.removedresults = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.results, ids[i]) + m.removedresults[ids[i]] = struct{}{} } - return *v, true } -// OldCategoryEn returns the old "category_en" field's value of the SecurityScanningResult entity. -// If the SecurityScanningResult object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SecurityScanningResultMutation) OldCategoryEn(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCategoryEn is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCategoryEn requires an ID field in the mutation") +// RemovedResults returns the removed IDs of the "results" edge to the SecurityScanningResult entity. +func (m *SecurityScanningMutation) RemovedResultsIDs() (ids []uuid.UUID) { + for id := range m.removedresults { + ids = append(ids, id) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldCategoryEn: %w", err) + return +} + +// ResultsIDs returns the "results" edge IDs in the mutation. +func (m *SecurityScanningMutation) ResultsIDs() (ids []uuid.UUID) { + for id := range m.results { + ids = append(ids, id) } - return oldValue.CategoryEn, nil + return } -// ResetCategoryEn resets all changes to the "category_en" field. -func (m *SecurityScanningResultMutation) ResetCategoryEn() { - m.category_en = nil +// ResetResults resets all changes to the "results" edge. +func (m *SecurityScanningMutation) ResetResults() { + m.results = nil + m.clearedresults = false + m.removedresults = nil } -// SetCategoryZh sets the "category_zh" field. -func (m *SecurityScanningResultMutation) SetCategoryZh(s string) { - m.category_zh = &s +// SetWorkspaceEdgeID sets the "workspace_edge" edge to the Workspace entity by id. +func (m *SecurityScanningMutation) SetWorkspaceEdgeID(id uuid.UUID) { + m.workspace_edge = &id } -// CategoryZh returns the value of the "category_zh" field in the mutation. -func (m *SecurityScanningResultMutation) CategoryZh() (r string, exists bool) { - v := m.category_zh - if v == nil { - return - } - return *v, true +// ClearWorkspaceEdge clears the "workspace_edge" edge to the Workspace entity. +func (m *SecurityScanningMutation) ClearWorkspaceEdge() { + m.clearedworkspace_edge = true + m.clearedFields[securityscanning.FieldWorkspaceID] = struct{}{} } -// OldCategoryZh returns the old "category_zh" field's value of the SecurityScanningResult entity. -// If the SecurityScanningResult object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SecurityScanningResultMutation) OldCategoryZh(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCategoryZh is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCategoryZh requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldCategoryZh: %w", err) +// WorkspaceEdgeCleared reports if the "workspace_edge" edge to the Workspace entity was cleared. +func (m *SecurityScanningMutation) WorkspaceEdgeCleared() bool { + return m.clearedworkspace_edge +} + +// WorkspaceEdgeID returns the "workspace_edge" edge ID in the mutation. +func (m *SecurityScanningMutation) WorkspaceEdgeID() (id uuid.UUID, exists bool) { + if m.workspace_edge != nil { + return *m.workspace_edge, true } - return oldValue.CategoryZh, nil + return } -// ResetCategoryZh resets all changes to the "category_zh" field. -func (m *SecurityScanningResultMutation) ResetCategoryZh() { - m.category_zh = nil +// WorkspaceEdgeIDs returns the "workspace_edge" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// WorkspaceEdgeID instead. It exists only for internal usage by the builders. +func (m *SecurityScanningMutation) WorkspaceEdgeIDs() (ids []uuid.UUID) { + if id := m.workspace_edge; id != nil { + ids = append(ids, *id) + } + return } -// SetConfidence sets the "confidence" field. -func (m *SecurityScanningResultMutation) SetConfidence(s string) { - m.confidence = &s +// ResetWorkspaceEdge resets all changes to the "workspace_edge" edge. +func (m *SecurityScanningMutation) ResetWorkspaceEdge() { + m.workspace_edge = nil + m.clearedworkspace_edge = false } -// Confidence returns the value of the "confidence" field in the mutation. -func (m *SecurityScanningResultMutation) Confidence() (r string, exists bool) { - v := m.confidence - if v == nil { - return - } - return *v, true +// Where appends a list predicates to the SecurityScanningMutation builder. +func (m *SecurityScanningMutation) Where(ps ...predicate.SecurityScanning) { + m.predicates = append(m.predicates, ps...) } -// OldConfidence returns the old "confidence" field's value of the SecurityScanningResult entity. -// If the SecurityScanningResult object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SecurityScanningResultMutation) OldConfidence(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldConfidence is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldConfidence requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldConfidence: %w", err) +// WhereP appends storage-level predicates to the SecurityScanningMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *SecurityScanningMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.SecurityScanning, len(ps)) + for i := range ps { + p[i] = ps[i] } - return oldValue.Confidence, nil + m.Where(p...) } -// ResetConfidence resets all changes to the "confidence" field. -func (m *SecurityScanningResultMutation) ResetConfidence() { - m.confidence = nil +// Op returns the operation name. +func (m *SecurityScanningMutation) Op() Op { + return m.op } -// SetCwe sets the "cwe" field. -func (m *SecurityScanningResultMutation) SetCwe(i []interface{}) { - m.cwe = &i - m.appendcwe = nil +// SetOp allows setting the mutation operation. +func (m *SecurityScanningMutation) SetOp(op Op) { + m.op = op } -// Cwe returns the value of the "cwe" field in the mutation. -func (m *SecurityScanningResultMutation) Cwe() (r []interface{}, exists bool) { - v := m.cwe - if v == nil { - return - } - return *v, true +// Type returns the node type of this mutation (SecurityScanning). +func (m *SecurityScanningMutation) Type() string { + return m.typ } -// OldCwe returns the old "cwe" field's value of the SecurityScanningResult entity. -// If the SecurityScanningResult object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SecurityScanningResultMutation) OldCwe(ctx context.Context) (v []interface{}, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCwe is only allowed on UpdateOne operations") +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *SecurityScanningMutation) Fields() []string { + fields := make([]string, 0, 9) + if m.user != nil { + fields = append(fields, securityscanning.FieldUserID) } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCwe requires an ID field in the mutation") + if m.workspace_edge != nil { + fields = append(fields, securityscanning.FieldWorkspaceID) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldCwe: %w", err) + if m.status != nil { + fields = append(fields, securityscanning.FieldStatus) } - return oldValue.Cwe, nil -} - -// AppendCwe adds i to the "cwe" field. -func (m *SecurityScanningResultMutation) AppendCwe(i []interface{}) { - m.appendcwe = append(m.appendcwe, i...) -} - -// AppendedCwe returns the list of values that were appended to the "cwe" field in this mutation. -func (m *SecurityScanningResultMutation) AppendedCwe() ([]interface{}, bool) { - if len(m.appendcwe) == 0 { - return nil, false + if m.workspace != nil { + fields = append(fields, securityscanning.FieldWorkspace) } - return m.appendcwe, true -} - -// ResetCwe resets all changes to the "cwe" field. -func (m *SecurityScanningResultMutation) ResetCwe() { - m.cwe = nil - m.appendcwe = nil + if m.language != nil { + fields = append(fields, securityscanning.FieldLanguage) + } + if m.rule != nil { + fields = append(fields, securityscanning.FieldRule) + } + if m.error_message != nil { + fields = append(fields, securityscanning.FieldErrorMessage) + } + if m.created_at != nil { + fields = append(fields, securityscanning.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, securityscanning.FieldUpdatedAt) + } + return fields } -// SetImpact sets the "impact" field. -func (m *SecurityScanningResultMutation) SetImpact(s string) { - m.impact = &s +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *SecurityScanningMutation) Field(name string) (ent.Value, bool) { + switch name { + case securityscanning.FieldUserID: + return m.UserID() + case securityscanning.FieldWorkspaceID: + return m.WorkspaceID() + case securityscanning.FieldStatus: + return m.Status() + case securityscanning.FieldWorkspace: + return m.Workspace() + case securityscanning.FieldLanguage: + return m.Language() + case securityscanning.FieldRule: + return m.Rule() + case securityscanning.FieldErrorMessage: + return m.ErrorMessage() + case securityscanning.FieldCreatedAt: + return m.CreatedAt() + case securityscanning.FieldUpdatedAt: + return m.UpdatedAt() + } + return nil, false } -// Impact returns the value of the "impact" field in the mutation. -func (m *SecurityScanningResultMutation) Impact() (r string, exists bool) { - v := m.impact - if v == nil { - return +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *SecurityScanningMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case securityscanning.FieldUserID: + return m.OldUserID(ctx) + case securityscanning.FieldWorkspaceID: + return m.OldWorkspaceID(ctx) + case securityscanning.FieldStatus: + return m.OldStatus(ctx) + case securityscanning.FieldWorkspace: + return m.OldWorkspace(ctx) + case securityscanning.FieldLanguage: + return m.OldLanguage(ctx) + case securityscanning.FieldRule: + return m.OldRule(ctx) + case securityscanning.FieldErrorMessage: + return m.OldErrorMessage(ctx) + case securityscanning.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case securityscanning.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) } - return *v, true + return nil, fmt.Errorf("unknown SecurityScanning field %s", name) } -// OldImpact returns the old "impact" field's value of the SecurityScanningResult entity. -// If the SecurityScanningResult object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SecurityScanningResultMutation) OldImpact(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldImpact is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldImpact requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldImpact: %w", err) +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *SecurityScanningMutation) SetField(name string, value ent.Value) error { + switch name { + case securityscanning.FieldUserID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUserID(v) + return nil + case securityscanning.FieldWorkspaceID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetWorkspaceID(v) + return nil + case securityscanning.FieldStatus: + v, ok := value.(consts.SecurityScanningStatus) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStatus(v) + return nil + case securityscanning.FieldWorkspace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetWorkspace(v) + return nil + case securityscanning.FieldLanguage: + v, ok := value.(consts.SecurityScanningLanguage) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLanguage(v) + return nil + case securityscanning.FieldRule: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRule(v) + return nil + case securityscanning.FieldErrorMessage: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetErrorMessage(v) + return nil + case securityscanning.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + case securityscanning.FieldUpdatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdatedAt(v) + return nil } - return oldValue.Impact, nil + return fmt.Errorf("unknown SecurityScanning field %s", name) } -// ResetImpact resets all changes to the "impact" field. -func (m *SecurityScanningResultMutation) ResetImpact() { - m.impact = nil +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *SecurityScanningMutation) AddedFields() []string { + return nil } -// SetOwasp sets the "owasp" field. -func (m *SecurityScanningResultMutation) SetOwasp(i []interface{}) { - m.owasp = &i - m.appendowasp = nil +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *SecurityScanningMutation) AddedField(name string) (ent.Value, bool) { + return nil, false } -// Owasp returns the value of the "owasp" field in the mutation. -func (m *SecurityScanningResultMutation) Owasp() (r []interface{}, exists bool) { - v := m.owasp - if v == nil { - return +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *SecurityScanningMutation) AddField(name string, value ent.Value) error { + switch name { } - return *v, true + return fmt.Errorf("unknown SecurityScanning numeric field %s", name) } -// OldOwasp returns the old "owasp" field's value of the SecurityScanningResult entity. -// If the SecurityScanningResult object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SecurityScanningResultMutation) OldOwasp(ctx context.Context) (v []interface{}, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldOwasp is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldOwasp requires an ID field in the mutation") +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *SecurityScanningMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(securityscanning.FieldRule) { + fields = append(fields, securityscanning.FieldRule) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldOwasp: %w", err) + if m.FieldCleared(securityscanning.FieldErrorMessage) { + fields = append(fields, securityscanning.FieldErrorMessage) } - return oldValue.Owasp, nil + return fields } -// AppendOwasp adds i to the "owasp" field. -func (m *SecurityScanningResultMutation) AppendOwasp(i []interface{}) { - m.appendowasp = append(m.appendowasp, i...) +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *SecurityScanningMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok } -// AppendedOwasp returns the list of values that were appended to the "owasp" field in this mutation. -func (m *SecurityScanningResultMutation) AppendedOwasp() ([]interface{}, bool) { - if len(m.appendowasp) == 0 { - return nil, false +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *SecurityScanningMutation) ClearField(name string) error { + switch name { + case securityscanning.FieldRule: + m.ClearRule() + return nil + case securityscanning.FieldErrorMessage: + m.ClearErrorMessage() + return nil } - return m.appendowasp, true -} - -// ResetOwasp resets all changes to the "owasp" field. -func (m *SecurityScanningResultMutation) ResetOwasp() { - m.owasp = nil - m.appendowasp = nil -} - -// SetFileContent sets the "file_content" field. -func (m *SecurityScanningResultMutation) SetFileContent(s string) { - m.file_content = &s + return fmt.Errorf("unknown SecurityScanning nullable field %s", name) } -// FileContent returns the value of the "file_content" field in the mutation. -func (m *SecurityScanningResultMutation) FileContent() (r string, exists bool) { - v := m.file_content - if v == nil { - return +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *SecurityScanningMutation) ResetField(name string) error { + switch name { + case securityscanning.FieldUserID: + m.ResetUserID() + return nil + case securityscanning.FieldWorkspaceID: + m.ResetWorkspaceID() + return nil + case securityscanning.FieldStatus: + m.ResetStatus() + return nil + case securityscanning.FieldWorkspace: + m.ResetWorkspace() + return nil + case securityscanning.FieldLanguage: + m.ResetLanguage() + return nil + case securityscanning.FieldRule: + m.ResetRule() + return nil + case securityscanning.FieldErrorMessage: + m.ResetErrorMessage() + return nil + case securityscanning.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case securityscanning.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil } - return *v, true + return fmt.Errorf("unknown SecurityScanning field %s", name) } -// OldFileContent returns the old "file_content" field's value of the SecurityScanningResult entity. -// If the SecurityScanningResult object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SecurityScanningResultMutation) OldFileContent(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldFileContent is only allowed on UpdateOne operations") +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *SecurityScanningMutation) AddedEdges() []string { + edges := make([]string, 0, 3) + if m.user != nil { + edges = append(edges, securityscanning.EdgeUser) } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldFileContent requires an ID field in the mutation") + if m.results != nil { + edges = append(edges, securityscanning.EdgeResults) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldFileContent: %w", err) + if m.workspace_edge != nil { + edges = append(edges, securityscanning.EdgeWorkspaceEdge) } - return oldValue.FileContent, nil -} - -// ResetFileContent resets all changes to the "file_content" field. -func (m *SecurityScanningResultMutation) ResetFileContent() { - m.file_content = nil -} - -// SetStartPosition sets the "start_position" field. -func (m *SecurityScanningResultMutation) SetStartPosition(t *types.Position) { - m.start_position = &t + return edges } -// StartPosition returns the value of the "start_position" field in the mutation. -func (m *SecurityScanningResultMutation) StartPosition() (r *types.Position, exists bool) { - v := m.start_position - if v == nil { - return +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *SecurityScanningMutation) AddedIDs(name string) []ent.Value { + switch name { + case securityscanning.EdgeUser: + if id := m.user; id != nil { + return []ent.Value{*id} + } + case securityscanning.EdgeResults: + ids := make([]ent.Value, 0, len(m.results)) + for id := range m.results { + ids = append(ids, id) + } + return ids + case securityscanning.EdgeWorkspaceEdge: + if id := m.workspace_edge; id != nil { + return []ent.Value{*id} + } } - return *v, true + return nil } -// OldStartPosition returns the old "start_position" field's value of the SecurityScanningResult entity. -// If the SecurityScanningResult object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SecurityScanningResultMutation) OldStartPosition(ctx context.Context) (v *types.Position, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldStartPosition is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldStartPosition requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldStartPosition: %w", err) +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *SecurityScanningMutation) RemovedEdges() []string { + edges := make([]string, 0, 3) + if m.removedresults != nil { + edges = append(edges, securityscanning.EdgeResults) } - return oldValue.StartPosition, nil -} - -// ResetStartPosition resets all changes to the "start_position" field. -func (m *SecurityScanningResultMutation) ResetStartPosition() { - m.start_position = nil -} - -// SetEndPosition sets the "end_position" field. -func (m *SecurityScanningResultMutation) SetEndPosition(t *types.Position) { - m.end_position = &t + return edges } -// EndPosition returns the value of the "end_position" field in the mutation. -func (m *SecurityScanningResultMutation) EndPosition() (r *types.Position, exists bool) { - v := m.end_position - if v == nil { - return +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *SecurityScanningMutation) RemovedIDs(name string) []ent.Value { + switch name { + case securityscanning.EdgeResults: + ids := make([]ent.Value, 0, len(m.removedresults)) + for id := range m.removedresults { + ids = append(ids, id) + } + return ids } - return *v, true + return nil } -// OldEndPosition returns the old "end_position" field's value of the SecurityScanningResult entity. -// If the SecurityScanningResult object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SecurityScanningResultMutation) OldEndPosition(ctx context.Context) (v *types.Position, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldEndPosition is only allowed on UpdateOne operations") +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *SecurityScanningMutation) ClearedEdges() []string { + edges := make([]string, 0, 3) + if m.cleareduser { + edges = append(edges, securityscanning.EdgeUser) } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldEndPosition requires an ID field in the mutation") + if m.clearedresults { + edges = append(edges, securityscanning.EdgeResults) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldEndPosition: %w", err) + if m.clearedworkspace_edge { + edges = append(edges, securityscanning.EdgeWorkspaceEdge) } - return oldValue.EndPosition, nil -} - -// ResetEndPosition resets all changes to the "end_position" field. -func (m *SecurityScanningResultMutation) ResetEndPosition() { - m.end_position = nil + return edges } -// SetCreatedAt sets the "created_at" field. -func (m *SecurityScanningResultMutation) SetCreatedAt(t time.Time) { - m.created_at = &t +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *SecurityScanningMutation) EdgeCleared(name string) bool { + switch name { + case securityscanning.EdgeUser: + return m.cleareduser + case securityscanning.EdgeResults: + return m.clearedresults + case securityscanning.EdgeWorkspaceEdge: + return m.clearedworkspace_edge + } + return false } -// CreatedAt returns the value of the "created_at" field in the mutation. -func (m *SecurityScanningResultMutation) CreatedAt() (r time.Time, exists bool) { - v := m.created_at - if v == nil { - return +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *SecurityScanningMutation) ClearEdge(name string) error { + switch name { + case securityscanning.EdgeUser: + m.ClearUser() + return nil + case securityscanning.EdgeWorkspaceEdge: + m.ClearWorkspaceEdge() + return nil } - return *v, true + return fmt.Errorf("unknown SecurityScanning unique edge %s", name) } -// OldCreatedAt returns the old "created_at" field's value of the SecurityScanningResult entity. -// If the SecurityScanningResult object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SecurityScanningResultMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCreatedAt requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. +func (m *SecurityScanningMutation) ResetEdge(name string) error { + switch name { + case securityscanning.EdgeUser: + m.ResetUser() + return nil + case securityscanning.EdgeResults: + m.ResetResults() + return nil + case securityscanning.EdgeWorkspaceEdge: + m.ResetWorkspaceEdge() + return nil } - return oldValue.CreatedAt, nil + return fmt.Errorf("unknown SecurityScanning edge %s", name) } -// ResetCreatedAt resets all changes to the "created_at" field. -func (m *SecurityScanningResultMutation) ResetCreatedAt() { - m.created_at = nil +// SecurityScanningResultMutation represents an operation that mutates the SecurityScanningResult nodes in the graph. +type SecurityScanningResultMutation struct { + config + op Op + typ string + id *uuid.UUID + check_id *string + engine_kind *string + lines *string + _path *string + message *string + message_zh *string + severity *string + abstract_en *string + abstract_zh *string + category_en *string + category_zh *string + confidence *string + cwe *[]interface{} + appendcwe []interface{} + impact *string + owasp *[]interface{} + appendowasp []interface{} + file_content *string + start_position **types.Position + end_position **types.Position + created_at *time.Time + clearedFields map[string]struct{} + security_scanning *uuid.UUID + clearedsecurity_scanning bool + done bool + oldValue func(context.Context) (*SecurityScanningResult, error) + predicates []predicate.SecurityScanningResult } -// ClearSecurityScanning clears the "security_scanning" edge to the SecurityScanning entity. -func (m *SecurityScanningResultMutation) ClearSecurityScanning() { - m.clearedsecurity_scanning = true - m.clearedFields[securityscanningresult.FieldSecurityScanningID] = struct{}{} -} +var _ ent.Mutation = (*SecurityScanningResultMutation)(nil) -// SecurityScanningCleared reports if the "security_scanning" edge to the SecurityScanning entity was cleared. -func (m *SecurityScanningResultMutation) SecurityScanningCleared() bool { - return m.clearedsecurity_scanning +// securityscanningresultOption allows management of the mutation configuration using functional options. +type securityscanningresultOption func(*SecurityScanningResultMutation) + +// newSecurityScanningResultMutation creates new mutation for the SecurityScanningResult entity. +func newSecurityScanningResultMutation(c config, op Op, opts ...securityscanningresultOption) *SecurityScanningResultMutation { + m := &SecurityScanningResultMutation{ + config: c, + op: op, + typ: TypeSecurityScanningResult, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m } -// SecurityScanningIDs returns the "security_scanning" edge IDs in the mutation. -// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// SecurityScanningID instead. It exists only for internal usage by the builders. -func (m *SecurityScanningResultMutation) SecurityScanningIDs() (ids []uuid.UUID) { - if id := m.security_scanning; id != nil { - ids = append(ids, *id) +// withSecurityScanningResultID sets the ID field of the mutation. +func withSecurityScanningResultID(id uuid.UUID) securityscanningresultOption { + return func(m *SecurityScanningResultMutation) { + var ( + err error + once sync.Once + value *SecurityScanningResult + ) + m.oldValue = func(ctx context.Context) (*SecurityScanningResult, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().SecurityScanningResult.Get(ctx, id) + } + }) + return value, err + } + m.id = &id } - return } -// ResetSecurityScanning resets all changes to the "security_scanning" edge. -func (m *SecurityScanningResultMutation) ResetSecurityScanning() { - m.security_scanning = nil - m.clearedsecurity_scanning = false +// withSecurityScanningResult sets the old SecurityScanningResult of the mutation. +func withSecurityScanningResult(node *SecurityScanningResult) securityscanningresultOption { + return func(m *SecurityScanningResultMutation) { + m.oldValue = func(context.Context) (*SecurityScanningResult, error) { + return node, nil + } + m.id = &node.ID + } } -// Where appends a list predicates to the SecurityScanningResultMutation builder. -func (m *SecurityScanningResultMutation) Where(ps ...predicate.SecurityScanningResult) { - m.predicates = append(m.predicates, ps...) +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m SecurityScanningResultMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client } -// WhereP appends storage-level predicates to the SecurityScanningResultMutation builder. Using this method, -// users can use type-assertion to append predicates that do not depend on any generated package. -func (m *SecurityScanningResultMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.SecurityScanningResult, len(ps)) - for i := range ps { - p[i] = ps[i] +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m SecurityScanningResultMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("db: mutation is not running in a transaction") } - m.Where(p...) + tx := &Tx{config: m.config} + tx.init() + return tx, nil } -// Op returns the operation name. -func (m *SecurityScanningResultMutation) Op() Op { - return m.op +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of SecurityScanningResult entities. +func (m *SecurityScanningResultMutation) SetID(id uuid.UUID) { + m.id = &id } -// SetOp allows setting the mutation operation. -func (m *SecurityScanningResultMutation) SetOp(op Op) { - m.op = op +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *SecurityScanningResultMutation) ID() (id uuid.UUID, exists bool) { + if m.id == nil { + return + } + return *m.id, true } -// Type returns the node type of this mutation (SecurityScanningResult). -func (m *SecurityScanningResultMutation) Type() string { - return m.typ +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *SecurityScanningResultMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []uuid.UUID{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().SecurityScanningResult.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } } -// Fields returns all fields that were changed during this mutation. Note that in -// order to get all numeric fields that were incremented/decremented, call -// AddedFields(). -func (m *SecurityScanningResultMutation) Fields() []string { - fields := make([]string, 0, 20) - if m.security_scanning != nil { - fields = append(fields, securityscanningresult.FieldSecurityScanningID) +// SetSecurityScanningID sets the "security_scanning_id" field. +func (m *SecurityScanningResultMutation) SetSecurityScanningID(u uuid.UUID) { + m.security_scanning = &u +} + +// SecurityScanningID returns the value of the "security_scanning_id" field in the mutation. +func (m *SecurityScanningResultMutation) SecurityScanningID() (r uuid.UUID, exists bool) { + v := m.security_scanning + if v == nil { + return } - if m.check_id != nil { - fields = append(fields, securityscanningresult.FieldCheckID) + return *v, true +} + +// OldSecurityScanningID returns the old "security_scanning_id" field's value of the SecurityScanningResult entity. +// If the SecurityScanningResult object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SecurityScanningResultMutation) OldSecurityScanningID(ctx context.Context) (v uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSecurityScanningID is only allowed on UpdateOne operations") } - if m.engine_kind != nil { - fields = append(fields, securityscanningresult.FieldEngineKind) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSecurityScanningID requires an ID field in the mutation") } - if m.lines != nil { - fields = append(fields, securityscanningresult.FieldLines) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSecurityScanningID: %w", err) } - if m._path != nil { - fields = append(fields, securityscanningresult.FieldPath) + return oldValue.SecurityScanningID, nil +} + +// ResetSecurityScanningID resets all changes to the "security_scanning_id" field. +func (m *SecurityScanningResultMutation) ResetSecurityScanningID() { + m.security_scanning = nil +} + +// SetCheckID sets the "check_id" field. +func (m *SecurityScanningResultMutation) SetCheckID(s string) { + m.check_id = &s +} + +// CheckID returns the value of the "check_id" field in the mutation. +func (m *SecurityScanningResultMutation) CheckID() (r string, exists bool) { + v := m.check_id + if v == nil { + return } - if m.message != nil { - fields = append(fields, securityscanningresult.FieldMessage) + return *v, true +} + +// OldCheckID returns the old "check_id" field's value of the SecurityScanningResult entity. +// If the SecurityScanningResult object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SecurityScanningResultMutation) OldCheckID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCheckID is only allowed on UpdateOne operations") } - if m.message_zh != nil { - fields = append(fields, securityscanningresult.FieldMessageZh) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCheckID requires an ID field in the mutation") } - if m.severity != nil { - fields = append(fields, securityscanningresult.FieldSeverity) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCheckID: %w", err) } - if m.abstract_en != nil { - fields = append(fields, securityscanningresult.FieldAbstractEn) + return oldValue.CheckID, nil +} + +// ResetCheckID resets all changes to the "check_id" field. +func (m *SecurityScanningResultMutation) ResetCheckID() { + m.check_id = nil +} + +// SetEngineKind sets the "engine_kind" field. +func (m *SecurityScanningResultMutation) SetEngineKind(s string) { + m.engine_kind = &s +} + +// EngineKind returns the value of the "engine_kind" field in the mutation. +func (m *SecurityScanningResultMutation) EngineKind() (r string, exists bool) { + v := m.engine_kind + if v == nil { + return } - if m.abstract_zh != nil { - fields = append(fields, securityscanningresult.FieldAbstractZh) + return *v, true +} + +// OldEngineKind returns the old "engine_kind" field's value of the SecurityScanningResult entity. +// If the SecurityScanningResult object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SecurityScanningResultMutation) OldEngineKind(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEngineKind is only allowed on UpdateOne operations") } - if m.category_en != nil { - fields = append(fields, securityscanningresult.FieldCategoryEn) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEngineKind requires an ID field in the mutation") } - if m.category_zh != nil { - fields = append(fields, securityscanningresult.FieldCategoryZh) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEngineKind: %w", err) } - if m.confidence != nil { - fields = append(fields, securityscanningresult.FieldConfidence) + return oldValue.EngineKind, nil +} + +// ResetEngineKind resets all changes to the "engine_kind" field. +func (m *SecurityScanningResultMutation) ResetEngineKind() { + m.engine_kind = nil +} + +// SetLines sets the "lines" field. +func (m *SecurityScanningResultMutation) SetLines(s string) { + m.lines = &s +} + +// Lines returns the value of the "lines" field in the mutation. +func (m *SecurityScanningResultMutation) Lines() (r string, exists bool) { + v := m.lines + if v == nil { + return } - if m.cwe != nil { - fields = append(fields, securityscanningresult.FieldCwe) + return *v, true +} + +// OldLines returns the old "lines" field's value of the SecurityScanningResult entity. +// If the SecurityScanningResult object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SecurityScanningResultMutation) OldLines(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldLines is only allowed on UpdateOne operations") } - if m.impact != nil { - fields = append(fields, securityscanningresult.FieldImpact) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldLines requires an ID field in the mutation") } - if m.owasp != nil { - fields = append(fields, securityscanningresult.FieldOwasp) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldLines: %w", err) } - if m.file_content != nil { - fields = append(fields, securityscanningresult.FieldFileContent) + return oldValue.Lines, nil +} + +// ResetLines resets all changes to the "lines" field. +func (m *SecurityScanningResultMutation) ResetLines() { + m.lines = nil +} + +// SetPath sets the "path" field. +func (m *SecurityScanningResultMutation) SetPath(s string) { + m._path = &s +} + +// Path returns the value of the "path" field in the mutation. +func (m *SecurityScanningResultMutation) Path() (r string, exists bool) { + v := m._path + if v == nil { + return } - if m.start_position != nil { - fields = append(fields, securityscanningresult.FieldStartPosition) + return *v, true +} + +// OldPath returns the old "path" field's value of the SecurityScanningResult entity. +// If the SecurityScanningResult object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SecurityScanningResultMutation) OldPath(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPath is only allowed on UpdateOne operations") } - if m.end_position != nil { - fields = append(fields, securityscanningresult.FieldEndPosition) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPath requires an ID field in the mutation") } - if m.created_at != nil { - fields = append(fields, securityscanningresult.FieldCreatedAt) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPath: %w", err) } - return fields + return oldValue.Path, nil } -// Field returns the value of a field with the given name. The second boolean -// return value indicates that this field was not set, or was not defined in the -// schema. -func (m *SecurityScanningResultMutation) Field(name string) (ent.Value, bool) { - switch name { - case securityscanningresult.FieldSecurityScanningID: - return m.SecurityScanningID() - case securityscanningresult.FieldCheckID: - return m.CheckID() - case securityscanningresult.FieldEngineKind: - return m.EngineKind() - case securityscanningresult.FieldLines: - return m.Lines() - case securityscanningresult.FieldPath: - return m.Path() - case securityscanningresult.FieldMessage: - return m.Message() - case securityscanningresult.FieldMessageZh: - return m.MessageZh() - case securityscanningresult.FieldSeverity: - return m.Severity() - case securityscanningresult.FieldAbstractEn: - return m.AbstractEn() - case securityscanningresult.FieldAbstractZh: - return m.AbstractZh() - case securityscanningresult.FieldCategoryEn: - return m.CategoryEn() - case securityscanningresult.FieldCategoryZh: - return m.CategoryZh() - case securityscanningresult.FieldConfidence: - return m.Confidence() - case securityscanningresult.FieldCwe: - return m.Cwe() - case securityscanningresult.FieldImpact: - return m.Impact() - case securityscanningresult.FieldOwasp: - return m.Owasp() - case securityscanningresult.FieldFileContent: - return m.FileContent() - case securityscanningresult.FieldStartPosition: - return m.StartPosition() - case securityscanningresult.FieldEndPosition: - return m.EndPosition() - case securityscanningresult.FieldCreatedAt: - return m.CreatedAt() +// ResetPath resets all changes to the "path" field. +func (m *SecurityScanningResultMutation) ResetPath() { + m._path = nil +} + +// SetMessage sets the "message" field. +func (m *SecurityScanningResultMutation) SetMessage(s string) { + m.message = &s +} + +// Message returns the value of the "message" field in the mutation. +func (m *SecurityScanningResultMutation) Message() (r string, exists bool) { + v := m.message + if v == nil { + return } - return nil, false + return *v, true } -// OldField returns the old value of the field from the database. An error is -// returned if the mutation operation is not UpdateOne, or the query to the -// database failed. -func (m *SecurityScanningResultMutation) OldField(ctx context.Context, name string) (ent.Value, error) { - switch name { - case securityscanningresult.FieldSecurityScanningID: - return m.OldSecurityScanningID(ctx) - case securityscanningresult.FieldCheckID: - return m.OldCheckID(ctx) - case securityscanningresult.FieldEngineKind: - return m.OldEngineKind(ctx) - case securityscanningresult.FieldLines: - return m.OldLines(ctx) - case securityscanningresult.FieldPath: - return m.OldPath(ctx) - case securityscanningresult.FieldMessage: - return m.OldMessage(ctx) - case securityscanningresult.FieldMessageZh: - return m.OldMessageZh(ctx) - case securityscanningresult.FieldSeverity: - return m.OldSeverity(ctx) - case securityscanningresult.FieldAbstractEn: - return m.OldAbstractEn(ctx) - case securityscanningresult.FieldAbstractZh: - return m.OldAbstractZh(ctx) - case securityscanningresult.FieldCategoryEn: - return m.OldCategoryEn(ctx) - case securityscanningresult.FieldCategoryZh: - return m.OldCategoryZh(ctx) - case securityscanningresult.FieldConfidence: - return m.OldConfidence(ctx) - case securityscanningresult.FieldCwe: - return m.OldCwe(ctx) - case securityscanningresult.FieldImpact: - return m.OldImpact(ctx) - case securityscanningresult.FieldOwasp: - return m.OldOwasp(ctx) - case securityscanningresult.FieldFileContent: - return m.OldFileContent(ctx) - case securityscanningresult.FieldStartPosition: - return m.OldStartPosition(ctx) - case securityscanningresult.FieldEndPosition: - return m.OldEndPosition(ctx) - case securityscanningresult.FieldCreatedAt: - return m.OldCreatedAt(ctx) +// OldMessage returns the old "message" field's value of the SecurityScanningResult entity. +// If the SecurityScanningResult object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SecurityScanningResultMutation) OldMessage(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMessage is only allowed on UpdateOne operations") } - return nil, fmt.Errorf("unknown SecurityScanningResult field %s", name) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMessage requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMessage: %w", err) + } + return oldValue.Message, nil } -// SetField sets the value of a field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *SecurityScanningResultMutation) SetField(name string, value ent.Value) error { - switch name { - case securityscanningresult.FieldSecurityScanningID: - v, ok := value.(uuid.UUID) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetSecurityScanningID(v) - return nil - case securityscanningresult.FieldCheckID: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetCheckID(v) - return nil - case securityscanningresult.FieldEngineKind: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetEngineKind(v) - return nil - case securityscanningresult.FieldLines: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetLines(v) - return nil - case securityscanningresult.FieldPath: +// ResetMessage resets all changes to the "message" field. +func (m *SecurityScanningResultMutation) ResetMessage() { + m.message = nil +} + +// SetMessageZh sets the "message_zh" field. +func (m *SecurityScanningResultMutation) SetMessageZh(s string) { + m.message_zh = &s +} + +// MessageZh returns the value of the "message_zh" field in the mutation. +func (m *SecurityScanningResultMutation) MessageZh() (r string, exists bool) { + v := m.message_zh + if v == nil { + return + } + return *v, true +} + +// OldMessageZh returns the old "message_zh" field's value of the SecurityScanningResult entity. +// If the SecurityScanningResult object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SecurityScanningResultMutation) OldMessageZh(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMessageZh is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMessageZh requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMessageZh: %w", err) + } + return oldValue.MessageZh, nil +} + +// ResetMessageZh resets all changes to the "message_zh" field. +func (m *SecurityScanningResultMutation) ResetMessageZh() { + m.message_zh = nil +} + +// SetSeverity sets the "severity" field. +func (m *SecurityScanningResultMutation) SetSeverity(s string) { + m.severity = &s +} + +// Severity returns the value of the "severity" field in the mutation. +func (m *SecurityScanningResultMutation) Severity() (r string, exists bool) { + v := m.severity + if v == nil { + return + } + return *v, true +} + +// OldSeverity returns the old "severity" field's value of the SecurityScanningResult entity. +// If the SecurityScanningResult object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SecurityScanningResultMutation) OldSeverity(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSeverity is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSeverity requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSeverity: %w", err) + } + return oldValue.Severity, nil +} + +// ResetSeverity resets all changes to the "severity" field. +func (m *SecurityScanningResultMutation) ResetSeverity() { + m.severity = nil +} + +// SetAbstractEn sets the "abstract_en" field. +func (m *SecurityScanningResultMutation) SetAbstractEn(s string) { + m.abstract_en = &s +} + +// AbstractEn returns the value of the "abstract_en" field in the mutation. +func (m *SecurityScanningResultMutation) AbstractEn() (r string, exists bool) { + v := m.abstract_en + if v == nil { + return + } + return *v, true +} + +// OldAbstractEn returns the old "abstract_en" field's value of the SecurityScanningResult entity. +// If the SecurityScanningResult object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SecurityScanningResultMutation) OldAbstractEn(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAbstractEn is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAbstractEn requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAbstractEn: %w", err) + } + return oldValue.AbstractEn, nil +} + +// ResetAbstractEn resets all changes to the "abstract_en" field. +func (m *SecurityScanningResultMutation) ResetAbstractEn() { + m.abstract_en = nil +} + +// SetAbstractZh sets the "abstract_zh" field. +func (m *SecurityScanningResultMutation) SetAbstractZh(s string) { + m.abstract_zh = &s +} + +// AbstractZh returns the value of the "abstract_zh" field in the mutation. +func (m *SecurityScanningResultMutation) AbstractZh() (r string, exists bool) { + v := m.abstract_zh + if v == nil { + return + } + return *v, true +} + +// OldAbstractZh returns the old "abstract_zh" field's value of the SecurityScanningResult entity. +// If the SecurityScanningResult object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SecurityScanningResultMutation) OldAbstractZh(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAbstractZh is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAbstractZh requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAbstractZh: %w", err) + } + return oldValue.AbstractZh, nil +} + +// ResetAbstractZh resets all changes to the "abstract_zh" field. +func (m *SecurityScanningResultMutation) ResetAbstractZh() { + m.abstract_zh = nil +} + +// SetCategoryEn sets the "category_en" field. +func (m *SecurityScanningResultMutation) SetCategoryEn(s string) { + m.category_en = &s +} + +// CategoryEn returns the value of the "category_en" field in the mutation. +func (m *SecurityScanningResultMutation) CategoryEn() (r string, exists bool) { + v := m.category_en + if v == nil { + return + } + return *v, true +} + +// OldCategoryEn returns the old "category_en" field's value of the SecurityScanningResult entity. +// If the SecurityScanningResult object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SecurityScanningResultMutation) OldCategoryEn(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCategoryEn is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCategoryEn requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCategoryEn: %w", err) + } + return oldValue.CategoryEn, nil +} + +// ResetCategoryEn resets all changes to the "category_en" field. +func (m *SecurityScanningResultMutation) ResetCategoryEn() { + m.category_en = nil +} + +// SetCategoryZh sets the "category_zh" field. +func (m *SecurityScanningResultMutation) SetCategoryZh(s string) { + m.category_zh = &s +} + +// CategoryZh returns the value of the "category_zh" field in the mutation. +func (m *SecurityScanningResultMutation) CategoryZh() (r string, exists bool) { + v := m.category_zh + if v == nil { + return + } + return *v, true +} + +// OldCategoryZh returns the old "category_zh" field's value of the SecurityScanningResult entity. +// If the SecurityScanningResult object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SecurityScanningResultMutation) OldCategoryZh(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCategoryZh is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCategoryZh requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCategoryZh: %w", err) + } + return oldValue.CategoryZh, nil +} + +// ResetCategoryZh resets all changes to the "category_zh" field. +func (m *SecurityScanningResultMutation) ResetCategoryZh() { + m.category_zh = nil +} + +// SetConfidence sets the "confidence" field. +func (m *SecurityScanningResultMutation) SetConfidence(s string) { + m.confidence = &s +} + +// Confidence returns the value of the "confidence" field in the mutation. +func (m *SecurityScanningResultMutation) Confidence() (r string, exists bool) { + v := m.confidence + if v == nil { + return + } + return *v, true +} + +// OldConfidence returns the old "confidence" field's value of the SecurityScanningResult entity. +// If the SecurityScanningResult object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SecurityScanningResultMutation) OldConfidence(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldConfidence is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldConfidence requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldConfidence: %w", err) + } + return oldValue.Confidence, nil +} + +// ResetConfidence resets all changes to the "confidence" field. +func (m *SecurityScanningResultMutation) ResetConfidence() { + m.confidence = nil +} + +// SetCwe sets the "cwe" field. +func (m *SecurityScanningResultMutation) SetCwe(i []interface{}) { + m.cwe = &i + m.appendcwe = nil +} + +// Cwe returns the value of the "cwe" field in the mutation. +func (m *SecurityScanningResultMutation) Cwe() (r []interface{}, exists bool) { + v := m.cwe + if v == nil { + return + } + return *v, true +} + +// OldCwe returns the old "cwe" field's value of the SecurityScanningResult entity. +// If the SecurityScanningResult object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SecurityScanningResultMutation) OldCwe(ctx context.Context) (v []interface{}, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCwe is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCwe requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCwe: %w", err) + } + return oldValue.Cwe, nil +} + +// AppendCwe adds i to the "cwe" field. +func (m *SecurityScanningResultMutation) AppendCwe(i []interface{}) { + m.appendcwe = append(m.appendcwe, i...) +} + +// AppendedCwe returns the list of values that were appended to the "cwe" field in this mutation. +func (m *SecurityScanningResultMutation) AppendedCwe() ([]interface{}, bool) { + if len(m.appendcwe) == 0 { + return nil, false + } + return m.appendcwe, true +} + +// ResetCwe resets all changes to the "cwe" field. +func (m *SecurityScanningResultMutation) ResetCwe() { + m.cwe = nil + m.appendcwe = nil +} + +// SetImpact sets the "impact" field. +func (m *SecurityScanningResultMutation) SetImpact(s string) { + m.impact = &s +} + +// Impact returns the value of the "impact" field in the mutation. +func (m *SecurityScanningResultMutation) Impact() (r string, exists bool) { + v := m.impact + if v == nil { + return + } + return *v, true +} + +// OldImpact returns the old "impact" field's value of the SecurityScanningResult entity. +// If the SecurityScanningResult object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SecurityScanningResultMutation) OldImpact(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldImpact is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldImpact requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldImpact: %w", err) + } + return oldValue.Impact, nil +} + +// ResetImpact resets all changes to the "impact" field. +func (m *SecurityScanningResultMutation) ResetImpact() { + m.impact = nil +} + +// SetOwasp sets the "owasp" field. +func (m *SecurityScanningResultMutation) SetOwasp(i []interface{}) { + m.owasp = &i + m.appendowasp = nil +} + +// Owasp returns the value of the "owasp" field in the mutation. +func (m *SecurityScanningResultMutation) Owasp() (r []interface{}, exists bool) { + v := m.owasp + if v == nil { + return + } + return *v, true +} + +// OldOwasp returns the old "owasp" field's value of the SecurityScanningResult entity. +// If the SecurityScanningResult object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SecurityScanningResultMutation) OldOwasp(ctx context.Context) (v []interface{}, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldOwasp is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldOwasp requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldOwasp: %w", err) + } + return oldValue.Owasp, nil +} + +// AppendOwasp adds i to the "owasp" field. +func (m *SecurityScanningResultMutation) AppendOwasp(i []interface{}) { + m.appendowasp = append(m.appendowasp, i...) +} + +// AppendedOwasp returns the list of values that were appended to the "owasp" field in this mutation. +func (m *SecurityScanningResultMutation) AppendedOwasp() ([]interface{}, bool) { + if len(m.appendowasp) == 0 { + return nil, false + } + return m.appendowasp, true +} + +// ResetOwasp resets all changes to the "owasp" field. +func (m *SecurityScanningResultMutation) ResetOwasp() { + m.owasp = nil + m.appendowasp = nil +} + +// SetFileContent sets the "file_content" field. +func (m *SecurityScanningResultMutation) SetFileContent(s string) { + m.file_content = &s +} + +// FileContent returns the value of the "file_content" field in the mutation. +func (m *SecurityScanningResultMutation) FileContent() (r string, exists bool) { + v := m.file_content + if v == nil { + return + } + return *v, true +} + +// OldFileContent returns the old "file_content" field's value of the SecurityScanningResult entity. +// If the SecurityScanningResult object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SecurityScanningResultMutation) OldFileContent(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFileContent is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFileContent requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFileContent: %w", err) + } + return oldValue.FileContent, nil +} + +// ResetFileContent resets all changes to the "file_content" field. +func (m *SecurityScanningResultMutation) ResetFileContent() { + m.file_content = nil +} + +// SetStartPosition sets the "start_position" field. +func (m *SecurityScanningResultMutation) SetStartPosition(t *types.Position) { + m.start_position = &t +} + +// StartPosition returns the value of the "start_position" field in the mutation. +func (m *SecurityScanningResultMutation) StartPosition() (r *types.Position, exists bool) { + v := m.start_position + if v == nil { + return + } + return *v, true +} + +// OldStartPosition returns the old "start_position" field's value of the SecurityScanningResult entity. +// If the SecurityScanningResult object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SecurityScanningResultMutation) OldStartPosition(ctx context.Context) (v *types.Position, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldStartPosition is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldStartPosition requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldStartPosition: %w", err) + } + return oldValue.StartPosition, nil +} + +// ResetStartPosition resets all changes to the "start_position" field. +func (m *SecurityScanningResultMutation) ResetStartPosition() { + m.start_position = nil +} + +// SetEndPosition sets the "end_position" field. +func (m *SecurityScanningResultMutation) SetEndPosition(t *types.Position) { + m.end_position = &t +} + +// EndPosition returns the value of the "end_position" field in the mutation. +func (m *SecurityScanningResultMutation) EndPosition() (r *types.Position, exists bool) { + v := m.end_position + if v == nil { + return + } + return *v, true +} + +// OldEndPosition returns the old "end_position" field's value of the SecurityScanningResult entity. +// If the SecurityScanningResult object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SecurityScanningResultMutation) OldEndPosition(ctx context.Context) (v *types.Position, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEndPosition is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEndPosition requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEndPosition: %w", err) + } + return oldValue.EndPosition, nil +} + +// ResetEndPosition resets all changes to the "end_position" field. +func (m *SecurityScanningResultMutation) ResetEndPosition() { + m.end_position = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *SecurityScanningResultMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *SecurityScanningResultMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at + if v == nil { + return + } + return *v, true +} + +// OldCreatedAt returns the old "created_at" field's value of the SecurityScanningResult entity. +// If the SecurityScanningResult object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SecurityScanningResultMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) + } + return oldValue.CreatedAt, nil +} + +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *SecurityScanningResultMutation) ResetCreatedAt() { + m.created_at = nil +} + +// ClearSecurityScanning clears the "security_scanning" edge to the SecurityScanning entity. +func (m *SecurityScanningResultMutation) ClearSecurityScanning() { + m.clearedsecurity_scanning = true + m.clearedFields[securityscanningresult.FieldSecurityScanningID] = struct{}{} +} + +// SecurityScanningCleared reports if the "security_scanning" edge to the SecurityScanning entity was cleared. +func (m *SecurityScanningResultMutation) SecurityScanningCleared() bool { + return m.clearedsecurity_scanning +} + +// SecurityScanningIDs returns the "security_scanning" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// SecurityScanningID instead. It exists only for internal usage by the builders. +func (m *SecurityScanningResultMutation) SecurityScanningIDs() (ids []uuid.UUID) { + if id := m.security_scanning; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetSecurityScanning resets all changes to the "security_scanning" edge. +func (m *SecurityScanningResultMutation) ResetSecurityScanning() { + m.security_scanning = nil + m.clearedsecurity_scanning = false +} + +// Where appends a list predicates to the SecurityScanningResultMutation builder. +func (m *SecurityScanningResultMutation) Where(ps ...predicate.SecurityScanningResult) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the SecurityScanningResultMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *SecurityScanningResultMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.SecurityScanningResult, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *SecurityScanningResultMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *SecurityScanningResultMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (SecurityScanningResult). +func (m *SecurityScanningResultMutation) Type() string { + return m.typ +} + +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *SecurityScanningResultMutation) Fields() []string { + fields := make([]string, 0, 20) + if m.security_scanning != nil { + fields = append(fields, securityscanningresult.FieldSecurityScanningID) + } + if m.check_id != nil { + fields = append(fields, securityscanningresult.FieldCheckID) + } + if m.engine_kind != nil { + fields = append(fields, securityscanningresult.FieldEngineKind) + } + if m.lines != nil { + fields = append(fields, securityscanningresult.FieldLines) + } + if m._path != nil { + fields = append(fields, securityscanningresult.FieldPath) + } + if m.message != nil { + fields = append(fields, securityscanningresult.FieldMessage) + } + if m.message_zh != nil { + fields = append(fields, securityscanningresult.FieldMessageZh) + } + if m.severity != nil { + fields = append(fields, securityscanningresult.FieldSeverity) + } + if m.abstract_en != nil { + fields = append(fields, securityscanningresult.FieldAbstractEn) + } + if m.abstract_zh != nil { + fields = append(fields, securityscanningresult.FieldAbstractZh) + } + if m.category_en != nil { + fields = append(fields, securityscanningresult.FieldCategoryEn) + } + if m.category_zh != nil { + fields = append(fields, securityscanningresult.FieldCategoryZh) + } + if m.confidence != nil { + fields = append(fields, securityscanningresult.FieldConfidence) + } + if m.cwe != nil { + fields = append(fields, securityscanningresult.FieldCwe) + } + if m.impact != nil { + fields = append(fields, securityscanningresult.FieldImpact) + } + if m.owasp != nil { + fields = append(fields, securityscanningresult.FieldOwasp) + } + if m.file_content != nil { + fields = append(fields, securityscanningresult.FieldFileContent) + } + if m.start_position != nil { + fields = append(fields, securityscanningresult.FieldStartPosition) + } + if m.end_position != nil { + fields = append(fields, securityscanningresult.FieldEndPosition) + } + if m.created_at != nil { + fields = append(fields, securityscanningresult.FieldCreatedAt) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *SecurityScanningResultMutation) Field(name string) (ent.Value, bool) { + switch name { + case securityscanningresult.FieldSecurityScanningID: + return m.SecurityScanningID() + case securityscanningresult.FieldCheckID: + return m.CheckID() + case securityscanningresult.FieldEngineKind: + return m.EngineKind() + case securityscanningresult.FieldLines: + return m.Lines() + case securityscanningresult.FieldPath: + return m.Path() + case securityscanningresult.FieldMessage: + return m.Message() + case securityscanningresult.FieldMessageZh: + return m.MessageZh() + case securityscanningresult.FieldSeverity: + return m.Severity() + case securityscanningresult.FieldAbstractEn: + return m.AbstractEn() + case securityscanningresult.FieldAbstractZh: + return m.AbstractZh() + case securityscanningresult.FieldCategoryEn: + return m.CategoryEn() + case securityscanningresult.FieldCategoryZh: + return m.CategoryZh() + case securityscanningresult.FieldConfidence: + return m.Confidence() + case securityscanningresult.FieldCwe: + return m.Cwe() + case securityscanningresult.FieldImpact: + return m.Impact() + case securityscanningresult.FieldOwasp: + return m.Owasp() + case securityscanningresult.FieldFileContent: + return m.FileContent() + case securityscanningresult.FieldStartPosition: + return m.StartPosition() + case securityscanningresult.FieldEndPosition: + return m.EndPosition() + case securityscanningresult.FieldCreatedAt: + return m.CreatedAt() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *SecurityScanningResultMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case securityscanningresult.FieldSecurityScanningID: + return m.OldSecurityScanningID(ctx) + case securityscanningresult.FieldCheckID: + return m.OldCheckID(ctx) + case securityscanningresult.FieldEngineKind: + return m.OldEngineKind(ctx) + case securityscanningresult.FieldLines: + return m.OldLines(ctx) + case securityscanningresult.FieldPath: + return m.OldPath(ctx) + case securityscanningresult.FieldMessage: + return m.OldMessage(ctx) + case securityscanningresult.FieldMessageZh: + return m.OldMessageZh(ctx) + case securityscanningresult.FieldSeverity: + return m.OldSeverity(ctx) + case securityscanningresult.FieldAbstractEn: + return m.OldAbstractEn(ctx) + case securityscanningresult.FieldAbstractZh: + return m.OldAbstractZh(ctx) + case securityscanningresult.FieldCategoryEn: + return m.OldCategoryEn(ctx) + case securityscanningresult.FieldCategoryZh: + return m.OldCategoryZh(ctx) + case securityscanningresult.FieldConfidence: + return m.OldConfidence(ctx) + case securityscanningresult.FieldCwe: + return m.OldCwe(ctx) + case securityscanningresult.FieldImpact: + return m.OldImpact(ctx) + case securityscanningresult.FieldOwasp: + return m.OldOwasp(ctx) + case securityscanningresult.FieldFileContent: + return m.OldFileContent(ctx) + case securityscanningresult.FieldStartPosition: + return m.OldStartPosition(ctx) + case securityscanningresult.FieldEndPosition: + return m.OldEndPosition(ctx) + case securityscanningresult.FieldCreatedAt: + return m.OldCreatedAt(ctx) + } + return nil, fmt.Errorf("unknown SecurityScanningResult field %s", name) +} + +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *SecurityScanningResultMutation) SetField(name string, value ent.Value) error { + switch name { + case securityscanningresult.FieldSecurityScanningID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSecurityScanningID(v) + return nil + case securityscanningresult.FieldCheckID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCheckID(v) + return nil + case securityscanningresult.FieldEngineKind: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEngineKind(v) + return nil + case securityscanningresult.FieldLines: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLines(v) + return nil + case securityscanningresult.FieldPath: v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetPath(v) + m.SetPath(v) + return nil + case securityscanningresult.FieldMessage: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMessage(v) + return nil + case securityscanningresult.FieldMessageZh: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMessageZh(v) + return nil + case securityscanningresult.FieldSeverity: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSeverity(v) + return nil + case securityscanningresult.FieldAbstractEn: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAbstractEn(v) + return nil + case securityscanningresult.FieldAbstractZh: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAbstractZh(v) + return nil + case securityscanningresult.FieldCategoryEn: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCategoryEn(v) + return nil + case securityscanningresult.FieldCategoryZh: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCategoryZh(v) + return nil + case securityscanningresult.FieldConfidence: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetConfidence(v) + return nil + case securityscanningresult.FieldCwe: + v, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCwe(v) + return nil + case securityscanningresult.FieldImpact: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetImpact(v) + return nil + case securityscanningresult.FieldOwasp: + v, ok := value.([]interface{}) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetOwasp(v) + return nil + case securityscanningresult.FieldFileContent: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFileContent(v) + return nil + case securityscanningresult.FieldStartPosition: + v, ok := value.(*types.Position) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStartPosition(v) + return nil + case securityscanningresult.FieldEndPosition: + v, ok := value.(*types.Position) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEndPosition(v) + return nil + case securityscanningresult.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + } + return fmt.Errorf("unknown SecurityScanningResult field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *SecurityScanningResultMutation) AddedFields() []string { + return nil +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *SecurityScanningResultMutation) AddedField(name string) (ent.Value, bool) { + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *SecurityScanningResultMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown SecurityScanningResult numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *SecurityScanningResultMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *SecurityScanningResultMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *SecurityScanningResultMutation) ClearField(name string) error { + return fmt.Errorf("unknown SecurityScanningResult nullable field %s", name) +} + +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *SecurityScanningResultMutation) ResetField(name string) error { + switch name { + case securityscanningresult.FieldSecurityScanningID: + m.ResetSecurityScanningID() + return nil + case securityscanningresult.FieldCheckID: + m.ResetCheckID() + return nil + case securityscanningresult.FieldEngineKind: + m.ResetEngineKind() + return nil + case securityscanningresult.FieldLines: + m.ResetLines() + return nil + case securityscanningresult.FieldPath: + m.ResetPath() + return nil + case securityscanningresult.FieldMessage: + m.ResetMessage() + return nil + case securityscanningresult.FieldMessageZh: + m.ResetMessageZh() + return nil + case securityscanningresult.FieldSeverity: + m.ResetSeverity() + return nil + case securityscanningresult.FieldAbstractEn: + m.ResetAbstractEn() + return nil + case securityscanningresult.FieldAbstractZh: + m.ResetAbstractZh() + return nil + case securityscanningresult.FieldCategoryEn: + m.ResetCategoryEn() + return nil + case securityscanningresult.FieldCategoryZh: + m.ResetCategoryZh() + return nil + case securityscanningresult.FieldConfidence: + m.ResetConfidence() + return nil + case securityscanningresult.FieldCwe: + m.ResetCwe() + return nil + case securityscanningresult.FieldImpact: + m.ResetImpact() + return nil + case securityscanningresult.FieldOwasp: + m.ResetOwasp() + return nil + case securityscanningresult.FieldFileContent: + m.ResetFileContent() + return nil + case securityscanningresult.FieldStartPosition: + m.ResetStartPosition() + return nil + case securityscanningresult.FieldEndPosition: + m.ResetEndPosition() + return nil + case securityscanningresult.FieldCreatedAt: + m.ResetCreatedAt() + return nil + } + return fmt.Errorf("unknown SecurityScanningResult field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *SecurityScanningResultMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.security_scanning != nil { + edges = append(edges, securityscanningresult.EdgeSecurityScanning) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *SecurityScanningResultMutation) AddedIDs(name string) []ent.Value { + switch name { + case securityscanningresult.EdgeSecurityScanning: + if id := m.security_scanning; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *SecurityScanningResultMutation) RemovedEdges() []string { + edges := make([]string, 0, 1) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *SecurityScanningResultMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *SecurityScanningResultMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedsecurity_scanning { + edges = append(edges, securityscanningresult.EdgeSecurityScanning) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *SecurityScanningResultMutation) EdgeCleared(name string) bool { + switch name { + case securityscanningresult.EdgeSecurityScanning: + return m.clearedsecurity_scanning + } + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *SecurityScanningResultMutation) ClearEdge(name string) error { + switch name { + case securityscanningresult.EdgeSecurityScanning: + m.ClearSecurityScanning() + return nil + } + return fmt.Errorf("unknown SecurityScanningResult unique edge %s", name) +} + +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. +func (m *SecurityScanningResultMutation) ResetEdge(name string) error { + switch name { + case securityscanningresult.EdgeSecurityScanning: + m.ResetSecurityScanning() + return nil + } + return fmt.Errorf("unknown SecurityScanningResult edge %s", name) +} + +// SettingMutation represents an operation that mutates the Setting nodes in the graph. +type SettingMutation struct { + config + op Op + typ string + id *uuid.UUID + enable_sso *bool + force_two_factor_auth *bool + disable_password_login *bool + enable_auto_login *bool + dingtalk_oauth **types.DingtalkOAuth + custom_oauth **types.CustomOAuth + base_url *string + created_at *time.Time + updated_at *time.Time + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*Setting, error) + predicates []predicate.Setting +} + +var _ ent.Mutation = (*SettingMutation)(nil) + +// settingOption allows management of the mutation configuration using functional options. +type settingOption func(*SettingMutation) + +// newSettingMutation creates new mutation for the Setting entity. +func newSettingMutation(c config, op Op, opts ...settingOption) *SettingMutation { + m := &SettingMutation{ + config: c, + op: op, + typ: TypeSetting, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withSettingID sets the ID field of the mutation. +func withSettingID(id uuid.UUID) settingOption { + return func(m *SettingMutation) { + var ( + err error + once sync.Once + value *Setting + ) + m.oldValue = func(ctx context.Context) (*Setting, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Setting.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withSetting sets the old Setting of the mutation. +func withSetting(node *Setting) settingOption { + return func(m *SettingMutation) { + m.oldValue = func(context.Context) (*Setting, 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 SettingMutation) 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 SettingMutation) 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 Setting entities. +func (m *SettingMutation) 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 *SettingMutation) 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 *SettingMutation) 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().Setting.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetEnableSSO sets the "enable_sso" field. +func (m *SettingMutation) SetEnableSSO(b bool) { + m.enable_sso = &b +} + +// EnableSSO returns the value of the "enable_sso" field in the mutation. +func (m *SettingMutation) EnableSSO() (r bool, exists bool) { + v := m.enable_sso + if v == nil { + return + } + return *v, true +} + +// OldEnableSSO returns the old "enable_sso" field's value of the Setting entity. +// If the Setting 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 *SettingMutation) OldEnableSSO(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEnableSSO is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEnableSSO requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEnableSSO: %w", err) + } + return oldValue.EnableSSO, nil +} + +// ResetEnableSSO resets all changes to the "enable_sso" field. +func (m *SettingMutation) ResetEnableSSO() { + m.enable_sso = nil +} + +// SetForceTwoFactorAuth sets the "force_two_factor_auth" field. +func (m *SettingMutation) SetForceTwoFactorAuth(b bool) { + m.force_two_factor_auth = &b +} + +// ForceTwoFactorAuth returns the value of the "force_two_factor_auth" field in the mutation. +func (m *SettingMutation) ForceTwoFactorAuth() (r bool, exists bool) { + v := m.force_two_factor_auth + if v == nil { + return + } + return *v, true +} + +// OldForceTwoFactorAuth returns the old "force_two_factor_auth" field's value of the Setting entity. +// If the Setting 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 *SettingMutation) OldForceTwoFactorAuth(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldForceTwoFactorAuth is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldForceTwoFactorAuth requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldForceTwoFactorAuth: %w", err) + } + return oldValue.ForceTwoFactorAuth, nil +} + +// ResetForceTwoFactorAuth resets all changes to the "force_two_factor_auth" field. +func (m *SettingMutation) ResetForceTwoFactorAuth() { + m.force_two_factor_auth = nil +} + +// SetDisablePasswordLogin sets the "disable_password_login" field. +func (m *SettingMutation) SetDisablePasswordLogin(b bool) { + m.disable_password_login = &b +} + +// DisablePasswordLogin returns the value of the "disable_password_login" field in the mutation. +func (m *SettingMutation) DisablePasswordLogin() (r bool, exists bool) { + v := m.disable_password_login + if v == nil { + return + } + return *v, true +} + +// OldDisablePasswordLogin returns the old "disable_password_login" field's value of the Setting entity. +// If the Setting 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 *SettingMutation) OldDisablePasswordLogin(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDisablePasswordLogin is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDisablePasswordLogin requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDisablePasswordLogin: %w", err) + } + return oldValue.DisablePasswordLogin, nil +} + +// ResetDisablePasswordLogin resets all changes to the "disable_password_login" field. +func (m *SettingMutation) ResetDisablePasswordLogin() { + m.disable_password_login = nil +} + +// SetEnableAutoLogin sets the "enable_auto_login" field. +func (m *SettingMutation) SetEnableAutoLogin(b bool) { + m.enable_auto_login = &b +} + +// EnableAutoLogin returns the value of the "enable_auto_login" field in the mutation. +func (m *SettingMutation) EnableAutoLogin() (r bool, exists bool) { + v := m.enable_auto_login + if v == nil { + return + } + return *v, true +} + +// OldEnableAutoLogin returns the old "enable_auto_login" field's value of the Setting entity. +// If the Setting 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 *SettingMutation) OldEnableAutoLogin(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEnableAutoLogin is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEnableAutoLogin requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEnableAutoLogin: %w", err) + } + return oldValue.EnableAutoLogin, nil +} + +// ResetEnableAutoLogin resets all changes to the "enable_auto_login" field. +func (m *SettingMutation) ResetEnableAutoLogin() { + m.enable_auto_login = nil +} + +// SetDingtalkOauth sets the "dingtalk_oauth" field. +func (m *SettingMutation) SetDingtalkOauth(to *types.DingtalkOAuth) { + m.dingtalk_oauth = &to +} + +// DingtalkOauth returns the value of the "dingtalk_oauth" field in the mutation. +func (m *SettingMutation) DingtalkOauth() (r *types.DingtalkOAuth, exists bool) { + v := m.dingtalk_oauth + if v == nil { + return + } + return *v, true +} + +// OldDingtalkOauth returns the old "dingtalk_oauth" field's value of the Setting entity. +// If the Setting 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 *SettingMutation) OldDingtalkOauth(ctx context.Context) (v *types.DingtalkOAuth, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDingtalkOauth is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDingtalkOauth requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDingtalkOauth: %w", err) + } + return oldValue.DingtalkOauth, nil +} + +// ClearDingtalkOauth clears the value of the "dingtalk_oauth" field. +func (m *SettingMutation) ClearDingtalkOauth() { + m.dingtalk_oauth = nil + m.clearedFields[setting.FieldDingtalkOauth] = struct{}{} +} + +// DingtalkOauthCleared returns if the "dingtalk_oauth" field was cleared in this mutation. +func (m *SettingMutation) DingtalkOauthCleared() bool { + _, ok := m.clearedFields[setting.FieldDingtalkOauth] + return ok +} + +// ResetDingtalkOauth resets all changes to the "dingtalk_oauth" field. +func (m *SettingMutation) ResetDingtalkOauth() { + m.dingtalk_oauth = nil + delete(m.clearedFields, setting.FieldDingtalkOauth) +} + +// SetCustomOauth sets the "custom_oauth" field. +func (m *SettingMutation) SetCustomOauth(to *types.CustomOAuth) { + m.custom_oauth = &to +} + +// CustomOauth returns the value of the "custom_oauth" field in the mutation. +func (m *SettingMutation) CustomOauth() (r *types.CustomOAuth, exists bool) { + v := m.custom_oauth + if v == nil { + return + } + return *v, true +} + +// OldCustomOauth returns the old "custom_oauth" field's value of the Setting entity. +// If the Setting 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 *SettingMutation) OldCustomOauth(ctx context.Context) (v *types.CustomOAuth, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCustomOauth is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCustomOauth requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCustomOauth: %w", err) + } + return oldValue.CustomOauth, nil +} + +// ClearCustomOauth clears the value of the "custom_oauth" field. +func (m *SettingMutation) ClearCustomOauth() { + m.custom_oauth = nil + m.clearedFields[setting.FieldCustomOauth] = struct{}{} +} + +// CustomOauthCleared returns if the "custom_oauth" field was cleared in this mutation. +func (m *SettingMutation) CustomOauthCleared() bool { + _, ok := m.clearedFields[setting.FieldCustomOauth] + return ok +} + +// ResetCustomOauth resets all changes to the "custom_oauth" field. +func (m *SettingMutation) ResetCustomOauth() { + m.custom_oauth = nil + delete(m.clearedFields, setting.FieldCustomOauth) +} + +// SetBaseURL sets the "base_url" field. +func (m *SettingMutation) SetBaseURL(s string) { + m.base_url = &s +} + +// BaseURL returns the value of the "base_url" field in the mutation. +func (m *SettingMutation) BaseURL() (r string, exists bool) { + v := m.base_url + if v == nil { + return + } + return *v, true +} + +// OldBaseURL returns the old "base_url" field's value of the Setting entity. +// If the Setting 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 *SettingMutation) OldBaseURL(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldBaseURL is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldBaseURL requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldBaseURL: %w", err) + } + return oldValue.BaseURL, nil +} + +// ClearBaseURL clears the value of the "base_url" field. +func (m *SettingMutation) ClearBaseURL() { + m.base_url = nil + m.clearedFields[setting.FieldBaseURL] = struct{}{} +} + +// BaseURLCleared returns if the "base_url" field was cleared in this mutation. +func (m *SettingMutation) BaseURLCleared() bool { + _, ok := m.clearedFields[setting.FieldBaseURL] + return ok +} + +// ResetBaseURL resets all changes to the "base_url" field. +func (m *SettingMutation) ResetBaseURL() { + m.base_url = nil + delete(m.clearedFields, setting.FieldBaseURL) +} + +// SetCreatedAt sets the "created_at" field. +func (m *SettingMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *SettingMutation) 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 Setting entity. +// If the Setting 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 *SettingMutation) 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 *SettingMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *SettingMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *SettingMutation) 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 Setting entity. +// If the Setting 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 *SettingMutation) 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 *SettingMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// Where appends a list predicates to the SettingMutation builder. +func (m *SettingMutation) Where(ps ...predicate.Setting) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the SettingMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *SettingMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Setting, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *SettingMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *SettingMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Setting). +func (m *SettingMutation) 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 *SettingMutation) Fields() []string { + fields := make([]string, 0, 9) + if m.enable_sso != nil { + fields = append(fields, setting.FieldEnableSSO) + } + if m.force_two_factor_auth != nil { + fields = append(fields, setting.FieldForceTwoFactorAuth) + } + if m.disable_password_login != nil { + fields = append(fields, setting.FieldDisablePasswordLogin) + } + if m.enable_auto_login != nil { + fields = append(fields, setting.FieldEnableAutoLogin) + } + if m.dingtalk_oauth != nil { + fields = append(fields, setting.FieldDingtalkOauth) + } + if m.custom_oauth != nil { + fields = append(fields, setting.FieldCustomOauth) + } + if m.base_url != nil { + fields = append(fields, setting.FieldBaseURL) + } + if m.created_at != nil { + fields = append(fields, setting.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, setting.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 *SettingMutation) Field(name string) (ent.Value, bool) { + switch name { + case setting.FieldEnableSSO: + return m.EnableSSO() + case setting.FieldForceTwoFactorAuth: + return m.ForceTwoFactorAuth() + case setting.FieldDisablePasswordLogin: + return m.DisablePasswordLogin() + case setting.FieldEnableAutoLogin: + return m.EnableAutoLogin() + case setting.FieldDingtalkOauth: + return m.DingtalkOauth() + case setting.FieldCustomOauth: + return m.CustomOauth() + case setting.FieldBaseURL: + return m.BaseURL() + case setting.FieldCreatedAt: + return m.CreatedAt() + case setting.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 *SettingMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case setting.FieldEnableSSO: + return m.OldEnableSSO(ctx) + case setting.FieldForceTwoFactorAuth: + return m.OldForceTwoFactorAuth(ctx) + case setting.FieldDisablePasswordLogin: + return m.OldDisablePasswordLogin(ctx) + case setting.FieldEnableAutoLogin: + return m.OldEnableAutoLogin(ctx) + case setting.FieldDingtalkOauth: + return m.OldDingtalkOauth(ctx) + case setting.FieldCustomOauth: + return m.OldCustomOauth(ctx) + case setting.FieldBaseURL: + return m.OldBaseURL(ctx) + case setting.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case setting.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + } + return nil, fmt.Errorf("unknown Setting 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 *SettingMutation) SetField(name string, value ent.Value) error { + switch name { + case setting.FieldEnableSSO: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEnableSSO(v) return nil - case securityscanningresult.FieldMessage: - v, ok := value.(string) + case setting.FieldForceTwoFactorAuth: + v, ok := value.(bool) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetMessage(v) + m.SetForceTwoFactorAuth(v) return nil - case securityscanningresult.FieldMessageZh: - v, ok := value.(string) + case setting.FieldDisablePasswordLogin: + v, ok := value.(bool) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetMessageZh(v) + m.SetDisablePasswordLogin(v) return nil - case securityscanningresult.FieldSeverity: - v, ok := value.(string) + case setting.FieldEnableAutoLogin: + v, ok := value.(bool) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetSeverity(v) + m.SetEnableAutoLogin(v) return nil - case securityscanningresult.FieldAbstractEn: - v, ok := value.(string) + case setting.FieldDingtalkOauth: + v, ok := value.(*types.DingtalkOAuth) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetAbstractEn(v) + m.SetDingtalkOauth(v) return nil - case securityscanningresult.FieldAbstractZh: - v, ok := value.(string) + case setting.FieldCustomOauth: + v, ok := value.(*types.CustomOAuth) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetAbstractZh(v) + m.SetCustomOauth(v) return nil - case securityscanningresult.FieldCategoryEn: + case setting.FieldBaseURL: v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetCategoryEn(v) + m.SetBaseURL(v) return nil - case securityscanningresult.FieldCategoryZh: - v, ok := value.(string) + case setting.FieldCreatedAt: + v, ok := value.(time.Time) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetCategoryZh(v) + m.SetCreatedAt(v) return nil - case securityscanningresult.FieldConfidence: - v, ok := value.(string) + case setting.FieldUpdatedAt: + v, ok := value.(time.Time) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetConfidence(v) + m.SetUpdatedAt(v) return nil - case securityscanningresult.FieldCwe: - v, ok := value.([]interface{}) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetCwe(v) + } + return fmt.Errorf("unknown Setting field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *SettingMutation) 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 *SettingMutation) 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 *SettingMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown Setting numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *SettingMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(setting.FieldDingtalkOauth) { + fields = append(fields, setting.FieldDingtalkOauth) + } + if m.FieldCleared(setting.FieldCustomOauth) { + fields = append(fields, setting.FieldCustomOauth) + } + if m.FieldCleared(setting.FieldBaseURL) { + fields = append(fields, setting.FieldBaseURL) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *SettingMutation) 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 *SettingMutation) ClearField(name string) error { + switch name { + case setting.FieldDingtalkOauth: + m.ClearDingtalkOauth() return nil - case securityscanningresult.FieldImpact: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetImpact(v) + case setting.FieldCustomOauth: + m.ClearCustomOauth() return nil - case securityscanningresult.FieldOwasp: - v, ok := value.([]interface{}) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetOwasp(v) + case setting.FieldBaseURL: + m.ClearBaseURL() return nil - case securityscanningresult.FieldFileContent: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetFileContent(v) + } + return fmt.Errorf("unknown Setting 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 *SettingMutation) ResetField(name string) error { + switch name { + case setting.FieldEnableSSO: + m.ResetEnableSSO() return nil - case securityscanningresult.FieldStartPosition: - v, ok := value.(*types.Position) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) + case setting.FieldForceTwoFactorAuth: + m.ResetForceTwoFactorAuth() + return nil + case setting.FieldDisablePasswordLogin: + m.ResetDisablePasswordLogin() + return nil + case setting.FieldEnableAutoLogin: + m.ResetEnableAutoLogin() + return nil + case setting.FieldDingtalkOauth: + m.ResetDingtalkOauth() + return nil + case setting.FieldCustomOauth: + m.ResetCustomOauth() + return nil + case setting.FieldBaseURL: + m.ResetBaseURL() + return nil + case setting.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case setting.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + } + return fmt.Errorf("unknown Setting field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *SettingMutation) 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 *SettingMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *SettingMutation) 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 *SettingMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *SettingMutation) 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 *SettingMutation) 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 *SettingMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown Setting 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 *SettingMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown Setting edge %s", name) +} + +// TaskMutation represents an operation that mutates the Task nodes in the graph. +type TaskMutation struct { + config + op Op + typ string + id *uuid.UUID + task_id *string + request_id *string + model_type *consts.ModelType + is_accept *bool + program_language *string + work_mode *string + prompt *string + completion *string + code_lines *int64 + addcode_lines *int64 + input_tokens *int64 + addinput_tokens *int64 + output_tokens *int64 + addoutput_tokens *int64 + is_suggested *bool + source_code *string + cursor_position *map[string]interface{} + user_input *string + created_at *time.Time + updated_at *time.Time + clearedFields map[string]struct{} + task_records map[uuid.UUID]struct{} + removedtask_records map[uuid.UUID]struct{} + clearedtask_records bool + user *uuid.UUID + cleareduser bool + model *uuid.UUID + clearedmodel bool + done bool + oldValue func(context.Context) (*Task, error) + predicates []predicate.Task +} + +var _ ent.Mutation = (*TaskMutation)(nil) + +// taskOption allows management of the mutation configuration using functional options. +type taskOption func(*TaskMutation) + +// newTaskMutation creates new mutation for the Task entity. +func newTaskMutation(c config, op Op, opts ...taskOption) *TaskMutation { + m := &TaskMutation{ + config: c, + op: op, + typ: TypeTask, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withTaskID sets the ID field of the mutation. +func withTaskID(id uuid.UUID) taskOption { + return func(m *TaskMutation) { + var ( + err error + once sync.Once + value *Task + ) + m.oldValue = func(ctx context.Context) (*Task, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Task.Get(ctx, id) + } + }) + return value, err } - m.SetStartPosition(v) - return nil - case securityscanningresult.FieldEndPosition: - v, ok := value.(*types.Position) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) + m.id = &id + } +} + +// withTask sets the old Task of the mutation. +func withTask(node *Task) taskOption { + return func(m *TaskMutation) { + m.oldValue = func(context.Context) (*Task, error) { + return node, nil } - m.SetEndPosition(v) - return nil - case securityscanningresult.FieldCreatedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) + m.id = &node.ID + } +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m TaskMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m TaskMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("db: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of Task entities. +func (m *TaskMutation) SetID(id uuid.UUID) { + m.id = &id +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *TaskMutation) ID() (id uuid.UUID, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *TaskMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []uuid.UUID{id}, nil } - m.SetCreatedAt(v) - return nil + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().Task.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetTaskID sets the "task_id" field. +func (m *TaskMutation) SetTaskID(s string) { + m.task_id = &s +} + +// TaskID returns the value of the "task_id" field in the mutation. +func (m *TaskMutation) TaskID() (r string, exists bool) { + v := m.task_id + if v == nil { + return + } + return *v, true +} + +// OldTaskID returns the old "task_id" field's value of the Task entity. +// If the Task object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *TaskMutation) OldTaskID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTaskID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTaskID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTaskID: %w", err) + } + return oldValue.TaskID, nil +} + +// ResetTaskID resets all changes to the "task_id" field. +func (m *TaskMutation) ResetTaskID() { + m.task_id = nil +} + +// SetUserID sets the "user_id" field. +func (m *TaskMutation) SetUserID(u uuid.UUID) { + m.user = &u +} + +// UserID returns the value of the "user_id" field in the mutation. +func (m *TaskMutation) UserID() (r uuid.UUID, exists bool) { + v := m.user + if v == nil { + return + } + return *v, true +} + +// OldUserID returns the old "user_id" field's value of the Task entity. +// If the Task object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *TaskMutation) OldUserID(ctx context.Context) (v uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUserID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUserID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUserID: %w", err) + } + return oldValue.UserID, nil +} + +// ClearUserID clears the value of the "user_id" field. +func (m *TaskMutation) ClearUserID() { + m.user = nil + m.clearedFields[task.FieldUserID] = struct{}{} +} + +// UserIDCleared returns if the "user_id" field was cleared in this mutation. +func (m *TaskMutation) UserIDCleared() bool { + _, ok := m.clearedFields[task.FieldUserID] + return ok +} + +// ResetUserID resets all changes to the "user_id" field. +func (m *TaskMutation) ResetUserID() { + m.user = nil + delete(m.clearedFields, task.FieldUserID) +} + +// SetModelID sets the "model_id" field. +func (m *TaskMutation) SetModelID(u uuid.UUID) { + m.model = &u +} + +// ModelID returns the value of the "model_id" field in the mutation. +func (m *TaskMutation) ModelID() (r uuid.UUID, exists bool) { + v := m.model + if v == nil { + return + } + return *v, true +} + +// OldModelID returns the old "model_id" field's value of the Task entity. +// If the Task object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *TaskMutation) OldModelID(ctx context.Context) (v uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldModelID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldModelID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldModelID: %w", err) + } + return oldValue.ModelID, nil +} + +// ClearModelID clears the value of the "model_id" field. +func (m *TaskMutation) ClearModelID() { + m.model = nil + m.clearedFields[task.FieldModelID] = struct{}{} +} + +// ModelIDCleared returns if the "model_id" field was cleared in this mutation. +func (m *TaskMutation) ModelIDCleared() bool { + _, ok := m.clearedFields[task.FieldModelID] + return ok +} + +// ResetModelID resets all changes to the "model_id" field. +func (m *TaskMutation) ResetModelID() { + m.model = nil + delete(m.clearedFields, task.FieldModelID) +} + +// SetRequestID sets the "request_id" field. +func (m *TaskMutation) SetRequestID(s string) { + m.request_id = &s +} + +// RequestID returns the value of the "request_id" field in the mutation. +func (m *TaskMutation) RequestID() (r string, exists bool) { + v := m.request_id + if v == nil { + return } - return fmt.Errorf("unknown SecurityScanningResult field %s", name) + return *v, true } -// AddedFields returns all numeric fields that were incremented/decremented during -// this mutation. -func (m *SecurityScanningResultMutation) AddedFields() []string { - return nil +// OldRequestID returns the old "request_id" field's value of the Task entity. +// If the Task object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *TaskMutation) OldRequestID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRequestID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRequestID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRequestID: %w", err) + } + return oldValue.RequestID, nil +} + +// ClearRequestID clears the value of the "request_id" field. +func (m *TaskMutation) ClearRequestID() { + m.request_id = nil + m.clearedFields[task.FieldRequestID] = struct{}{} +} + +// RequestIDCleared returns if the "request_id" field was cleared in this mutation. +func (m *TaskMutation) RequestIDCleared() bool { + _, ok := m.clearedFields[task.FieldRequestID] + return ok +} + +// ResetRequestID resets all changes to the "request_id" field. +func (m *TaskMutation) ResetRequestID() { + m.request_id = nil + delete(m.clearedFields, task.FieldRequestID) +} + +// SetModelType sets the "model_type" field. +func (m *TaskMutation) SetModelType(ct consts.ModelType) { + m.model_type = &ct +} + +// ModelType returns the value of the "model_type" field in the mutation. +func (m *TaskMutation) ModelType() (r consts.ModelType, exists bool) { + v := m.model_type + if v == nil { + return + } + return *v, true +} + +// OldModelType returns the old "model_type" field's value of the Task entity. +// If the Task object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *TaskMutation) OldModelType(ctx context.Context) (v consts.ModelType, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldModelType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldModelType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldModelType: %w", err) + } + return oldValue.ModelType, nil +} + +// ResetModelType resets all changes to the "model_type" field. +func (m *TaskMutation) ResetModelType() { + m.model_type = nil +} + +// SetIsAccept sets the "is_accept" field. +func (m *TaskMutation) SetIsAccept(b bool) { + m.is_accept = &b +} + +// IsAccept returns the value of the "is_accept" field in the mutation. +func (m *TaskMutation) IsAccept() (r bool, exists bool) { + v := m.is_accept + if v == nil { + return + } + return *v, true +} + +// OldIsAccept returns the old "is_accept" field's value of the Task entity. +// If the Task object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *TaskMutation) OldIsAccept(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldIsAccept is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldIsAccept requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldIsAccept: %w", err) + } + return oldValue.IsAccept, nil +} + +// ResetIsAccept resets all changes to the "is_accept" field. +func (m *TaskMutation) ResetIsAccept() { + m.is_accept = nil +} + +// SetProgramLanguage sets the "program_language" field. +func (m *TaskMutation) SetProgramLanguage(s string) { + m.program_language = &s +} + +// ProgramLanguage returns the value of the "program_language" field in the mutation. +func (m *TaskMutation) ProgramLanguage() (r string, exists bool) { + v := m.program_language + if v == nil { + return + } + return *v, true +} + +// OldProgramLanguage returns the old "program_language" field's value of the Task entity. +// If the Task object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *TaskMutation) OldProgramLanguage(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldProgramLanguage is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldProgramLanguage requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldProgramLanguage: %w", err) + } + return oldValue.ProgramLanguage, nil +} + +// ClearProgramLanguage clears the value of the "program_language" field. +func (m *TaskMutation) ClearProgramLanguage() { + m.program_language = nil + m.clearedFields[task.FieldProgramLanguage] = struct{}{} +} + +// ProgramLanguageCleared returns if the "program_language" field was cleared in this mutation. +func (m *TaskMutation) ProgramLanguageCleared() bool { + _, ok := m.clearedFields[task.FieldProgramLanguage] + return ok +} + +// ResetProgramLanguage resets all changes to the "program_language" field. +func (m *TaskMutation) ResetProgramLanguage() { + m.program_language = nil + delete(m.clearedFields, task.FieldProgramLanguage) +} + +// SetWorkMode sets the "work_mode" field. +func (m *TaskMutation) SetWorkMode(s string) { + m.work_mode = &s +} + +// WorkMode returns the value of the "work_mode" field in the mutation. +func (m *TaskMutation) WorkMode() (r string, exists bool) { + v := m.work_mode + if v == nil { + return + } + return *v, true +} + +// OldWorkMode returns the old "work_mode" field's value of the Task entity. +// If the Task object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *TaskMutation) OldWorkMode(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldWorkMode is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldWorkMode requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldWorkMode: %w", err) + } + return oldValue.WorkMode, nil +} + +// ClearWorkMode clears the value of the "work_mode" field. +func (m *TaskMutation) ClearWorkMode() { + m.work_mode = nil + m.clearedFields[task.FieldWorkMode] = struct{}{} +} + +// WorkModeCleared returns if the "work_mode" field was cleared in this mutation. +func (m *TaskMutation) WorkModeCleared() bool { + _, ok := m.clearedFields[task.FieldWorkMode] + return ok +} + +// ResetWorkMode resets all changes to the "work_mode" field. +func (m *TaskMutation) ResetWorkMode() { + m.work_mode = nil + delete(m.clearedFields, task.FieldWorkMode) +} + +// SetPrompt sets the "prompt" field. +func (m *TaskMutation) SetPrompt(s string) { + m.prompt = &s +} + +// Prompt returns the value of the "prompt" field in the mutation. +func (m *TaskMutation) Prompt() (r string, exists bool) { + v := m.prompt + if v == nil { + return + } + return *v, true +} + +// OldPrompt returns the old "prompt" field's value of the Task entity. +// If the Task object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *TaskMutation) OldPrompt(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPrompt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPrompt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPrompt: %w", err) + } + return oldValue.Prompt, nil } -// AddedField returns the numeric value that was incremented/decremented on a field -// with the given name. The second boolean return value indicates that this field -// was not set, or was not defined in the schema. -func (m *SecurityScanningResultMutation) AddedField(name string) (ent.Value, bool) { - return nil, false +// ClearPrompt clears the value of the "prompt" field. +func (m *TaskMutation) ClearPrompt() { + m.prompt = nil + m.clearedFields[task.FieldPrompt] = struct{}{} } -// AddField adds the value to the field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *SecurityScanningResultMutation) AddField(name string, value ent.Value) error { - switch name { - } - return fmt.Errorf("unknown SecurityScanningResult numeric field %s", name) +// PromptCleared returns if the "prompt" field was cleared in this mutation. +func (m *TaskMutation) PromptCleared() bool { + _, ok := m.clearedFields[task.FieldPrompt] + return ok } -// ClearedFields returns all nullable fields that were cleared during this -// mutation. -func (m *SecurityScanningResultMutation) ClearedFields() []string { - return nil +// ResetPrompt resets all changes to the "prompt" field. +func (m *TaskMutation) ResetPrompt() { + m.prompt = nil + delete(m.clearedFields, task.FieldPrompt) } -// FieldCleared returns a boolean indicating if a field with the given name was -// cleared in this mutation. -func (m *SecurityScanningResultMutation) FieldCleared(name string) bool { - _, ok := m.clearedFields[name] - return ok +// SetCompletion sets the "completion" field. +func (m *TaskMutation) SetCompletion(s string) { + m.completion = &s } -// ClearField clears the value of the field with the given name. It returns an -// error if the field is not defined in the schema. -func (m *SecurityScanningResultMutation) ClearField(name string) error { - return fmt.Errorf("unknown SecurityScanningResult nullable field %s", name) +// Completion returns the value of the "completion" field in the mutation. +func (m *TaskMutation) Completion() (r string, exists bool) { + v := m.completion + if v == nil { + return + } + return *v, true } -// ResetField resets all changes in the mutation for the field with the given name. -// It returns an error if the field is not defined in the schema. -func (m *SecurityScanningResultMutation) ResetField(name string) error { - switch name { - case securityscanningresult.FieldSecurityScanningID: - m.ResetSecurityScanningID() - return nil - case securityscanningresult.FieldCheckID: - m.ResetCheckID() - return nil - case securityscanningresult.FieldEngineKind: - m.ResetEngineKind() - return nil - case securityscanningresult.FieldLines: - m.ResetLines() - return nil - case securityscanningresult.FieldPath: - m.ResetPath() - return nil - case securityscanningresult.FieldMessage: - m.ResetMessage() - return nil - case securityscanningresult.FieldMessageZh: - m.ResetMessageZh() - return nil - case securityscanningresult.FieldSeverity: - m.ResetSeverity() - return nil - case securityscanningresult.FieldAbstractEn: - m.ResetAbstractEn() - return nil - case securityscanningresult.FieldAbstractZh: - m.ResetAbstractZh() - return nil - case securityscanningresult.FieldCategoryEn: - m.ResetCategoryEn() - return nil - case securityscanningresult.FieldCategoryZh: - m.ResetCategoryZh() - return nil - case securityscanningresult.FieldConfidence: - m.ResetConfidence() - return nil - case securityscanningresult.FieldCwe: - m.ResetCwe() - return nil - case securityscanningresult.FieldImpact: - m.ResetImpact() - return nil - case securityscanningresult.FieldOwasp: - m.ResetOwasp() - return nil - case securityscanningresult.FieldFileContent: - m.ResetFileContent() - return nil - case securityscanningresult.FieldStartPosition: - m.ResetStartPosition() - return nil - case securityscanningresult.FieldEndPosition: - m.ResetEndPosition() - return nil - case securityscanningresult.FieldCreatedAt: - m.ResetCreatedAt() - return nil +// OldCompletion returns the old "completion" field's value of the Task entity. +// If the Task object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *TaskMutation) OldCompletion(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCompletion is only allowed on UpdateOne operations") } - return fmt.Errorf("unknown SecurityScanningResult field %s", name) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCompletion requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCompletion: %w", err) + } + return oldValue.Completion, nil } -// AddedEdges returns all edge names that were set/added in this mutation. -func (m *SecurityScanningResultMutation) AddedEdges() []string { - edges := make([]string, 0, 1) - if m.security_scanning != nil { - edges = append(edges, securityscanningresult.EdgeSecurityScanning) - } - return edges +// ClearCompletion clears the value of the "completion" field. +func (m *TaskMutation) ClearCompletion() { + m.completion = nil + m.clearedFields[task.FieldCompletion] = struct{}{} } -// AddedIDs returns all IDs (to other nodes) that were added for the given edge -// name in this mutation. -func (m *SecurityScanningResultMutation) AddedIDs(name string) []ent.Value { - switch name { - case securityscanningresult.EdgeSecurityScanning: - if id := m.security_scanning; id != nil { - return []ent.Value{*id} - } - } - return nil +// CompletionCleared returns if the "completion" field was cleared in this mutation. +func (m *TaskMutation) CompletionCleared() bool { + _, ok := m.clearedFields[task.FieldCompletion] + return ok } -// RemovedEdges returns all edge names that were removed in this mutation. -func (m *SecurityScanningResultMutation) RemovedEdges() []string { - edges := make([]string, 0, 1) - return edges +// ResetCompletion resets all changes to the "completion" field. +func (m *TaskMutation) ResetCompletion() { + m.completion = nil + delete(m.clearedFields, task.FieldCompletion) } -// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with -// the given name in this mutation. -func (m *SecurityScanningResultMutation) RemovedIDs(name string) []ent.Value { - return nil +// SetCodeLines sets the "code_lines" field. +func (m *TaskMutation) SetCodeLines(i int64) { + m.code_lines = &i + m.addcode_lines = nil } -// ClearedEdges returns all edge names that were cleared in this mutation. -func (m *SecurityScanningResultMutation) ClearedEdges() []string { - edges := make([]string, 0, 1) - if m.clearedsecurity_scanning { - edges = append(edges, securityscanningresult.EdgeSecurityScanning) +// CodeLines returns the value of the "code_lines" field in the mutation. +func (m *TaskMutation) CodeLines() (r int64, exists bool) { + v := m.code_lines + if v == nil { + return } - return edges + return *v, true } -// EdgeCleared returns a boolean which indicates if the edge with the given name -// was cleared in this mutation. -func (m *SecurityScanningResultMutation) EdgeCleared(name string) bool { - switch name { - case securityscanningresult.EdgeSecurityScanning: - return m.clearedsecurity_scanning +// OldCodeLines returns the old "code_lines" field's value of the Task entity. +// If the Task object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *TaskMutation) OldCodeLines(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCodeLines is only allowed on UpdateOne operations") } - return false + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCodeLines requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCodeLines: %w", err) + } + return oldValue.CodeLines, nil } -// ClearEdge clears the value of the edge with the given name. It returns an error -// if that edge is not defined in the schema. -func (m *SecurityScanningResultMutation) ClearEdge(name string) error { - switch name { - case securityscanningresult.EdgeSecurityScanning: - m.ClearSecurityScanning() - return nil +// AddCodeLines adds i to the "code_lines" field. +func (m *TaskMutation) AddCodeLines(i int64) { + if m.addcode_lines != nil { + *m.addcode_lines += i + } else { + m.addcode_lines = &i } - return fmt.Errorf("unknown SecurityScanningResult unique edge %s", name) } -// ResetEdge resets all changes to the edge with the given name in this mutation. -// It returns an error if the edge is not defined in the schema. -func (m *SecurityScanningResultMutation) ResetEdge(name string) error { - switch name { - case securityscanningresult.EdgeSecurityScanning: - m.ResetSecurityScanning() - return nil +// AddedCodeLines returns the value that was added to the "code_lines" field in this mutation. +func (m *TaskMutation) AddedCodeLines() (r int64, exists bool) { + v := m.addcode_lines + if v == nil { + return } - return fmt.Errorf("unknown SecurityScanningResult edge %s", name) + return *v, true } -// SettingMutation represents an operation that mutates the Setting nodes in the graph. -type SettingMutation struct { - config - op Op - typ string - id *uuid.UUID - enable_sso *bool - force_two_factor_auth *bool - disable_password_login *bool - enable_auto_login *bool - dingtalk_oauth **types.DingtalkOAuth - custom_oauth **types.CustomOAuth - base_url *string - created_at *time.Time - updated_at *time.Time - clearedFields map[string]struct{} - done bool - oldValue func(context.Context) (*Setting, error) - predicates []predicate.Setting +// ClearCodeLines clears the value of the "code_lines" field. +func (m *TaskMutation) ClearCodeLines() { + m.code_lines = nil + m.addcode_lines = nil + m.clearedFields[task.FieldCodeLines] = struct{}{} } -var _ ent.Mutation = (*SettingMutation)(nil) +// CodeLinesCleared returns if the "code_lines" field was cleared in this mutation. +func (m *TaskMutation) CodeLinesCleared() bool { + _, ok := m.clearedFields[task.FieldCodeLines] + return ok +} -// settingOption allows management of the mutation configuration using functional options. -type settingOption func(*SettingMutation) +// ResetCodeLines resets all changes to the "code_lines" field. +func (m *TaskMutation) ResetCodeLines() { + m.code_lines = nil + m.addcode_lines = nil + delete(m.clearedFields, task.FieldCodeLines) +} -// newSettingMutation creates new mutation for the Setting entity. -func newSettingMutation(c config, op Op, opts ...settingOption) *SettingMutation { - m := &SettingMutation{ - config: c, - op: op, - typ: TypeSetting, - clearedFields: make(map[string]struct{}), - } - for _, opt := range opts { - opt(m) - } - return m +// SetInputTokens sets the "input_tokens" field. +func (m *TaskMutation) SetInputTokens(i int64) { + m.input_tokens = &i + m.addinput_tokens = nil } -// withSettingID sets the ID field of the mutation. -func withSettingID(id uuid.UUID) settingOption { - return func(m *SettingMutation) { - var ( - err error - once sync.Once - value *Setting - ) - m.oldValue = func(ctx context.Context) (*Setting, error) { - once.Do(func() { - if m.done { - err = errors.New("querying old values post mutation is not allowed") - } else { - value, err = m.Client().Setting.Get(ctx, id) - } - }) - return value, err - } - m.id = &id +// InputTokens returns the value of the "input_tokens" field in the mutation. +func (m *TaskMutation) InputTokens() (r int64, exists bool) { + v := m.input_tokens + if v == nil { + return } + return *v, true } -// withSetting sets the old Setting of the mutation. -func withSetting(node *Setting) settingOption { - return func(m *SettingMutation) { - m.oldValue = func(context.Context) (*Setting, error) { - return node, nil - } - m.id = &node.ID +// OldInputTokens returns the old "input_tokens" field's value of the Task entity. +// If the Task object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *TaskMutation) OldInputTokens(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInputTokens is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInputTokens requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInputTokens: %w", err) } + return oldValue.InputTokens, nil } -// 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 SettingMutation) Client() *Client { - client := &Client{config: m.config} - client.init() - return client +// AddInputTokens adds i to the "input_tokens" field. +func (m *TaskMutation) AddInputTokens(i int64) { + if m.addinput_tokens != nil { + *m.addinput_tokens += i + } else { + m.addinput_tokens = &i + } } -// Tx returns an `ent.Tx` for mutations that were executed in transactions; -// it returns an error otherwise. -func (m SettingMutation) Tx() (*Tx, error) { - if _, ok := m.driver.(*txDriver); !ok { - return nil, errors.New("db: mutation is not running in a transaction") +// AddedInputTokens returns the value that was added to the "input_tokens" field in this mutation. +func (m *TaskMutation) AddedInputTokens() (r int64, exists bool) { + v := m.addinput_tokens + if v == nil { + return } - tx := &Tx{config: m.config} - tx.init() - return tx, nil + return *v, true } -// SetID sets the value of the id field. Note that this -// operation is only accepted on creation of Setting entities. -func (m *SettingMutation) SetID(id uuid.UUID) { - m.id = &id +// ClearInputTokens clears the value of the "input_tokens" field. +func (m *TaskMutation) ClearInputTokens() { + m.input_tokens = nil + m.addinput_tokens = nil + m.clearedFields[task.FieldInputTokens] = struct{}{} } -// 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 *SettingMutation) ID() (id uuid.UUID, exists bool) { - if m.id == nil { - return - } - return *m.id, true +// InputTokensCleared returns if the "input_tokens" field was cleared in this mutation. +func (m *TaskMutation) InputTokensCleared() bool { + _, ok := m.clearedFields[task.FieldInputTokens] + return ok } -// 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 *SettingMutation) 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().Setting.Query().Where(m.predicates...).IDs(ctx) - default: - return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) - } +// ResetInputTokens resets all changes to the "input_tokens" field. +func (m *TaskMutation) ResetInputTokens() { + m.input_tokens = nil + m.addinput_tokens = nil + delete(m.clearedFields, task.FieldInputTokens) } -// SetEnableSSO sets the "enable_sso" field. -func (m *SettingMutation) SetEnableSSO(b bool) { - m.enable_sso = &b +// SetOutputTokens sets the "output_tokens" field. +func (m *TaskMutation) SetOutputTokens(i int64) { + m.output_tokens = &i + m.addoutput_tokens = nil } -// EnableSSO returns the value of the "enable_sso" field in the mutation. -func (m *SettingMutation) EnableSSO() (r bool, exists bool) { - v := m.enable_sso +// OutputTokens returns the value of the "output_tokens" field in the mutation. +func (m *TaskMutation) OutputTokens() (r int64, exists bool) { + v := m.output_tokens if v == nil { return } return *v, true } -// OldEnableSSO returns the old "enable_sso" field's value of the Setting entity. -// If the Setting object wasn't provided to the builder, the object is fetched from the database. +// OldOutputTokens returns the old "output_tokens" field's value of the Task entity. +// If the Task object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SettingMutation) OldEnableSSO(ctx context.Context) (v bool, err error) { +func (m *TaskMutation) OldOutputTokens(ctx context.Context) (v int64, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldEnableSSO is only allowed on UpdateOne operations") + return v, errors.New("OldOutputTokens is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldEnableSSO requires an ID field in the mutation") + return v, errors.New("OldOutputTokens requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldEnableSSO: %w", err) + return v, fmt.Errorf("querying old value for OldOutputTokens: %w", err) } - return oldValue.EnableSSO, nil + return oldValue.OutputTokens, nil } -// ResetEnableSSO resets all changes to the "enable_sso" field. -func (m *SettingMutation) ResetEnableSSO() { - m.enable_sso = nil +// AddOutputTokens adds i to the "output_tokens" field. +func (m *TaskMutation) AddOutputTokens(i int64) { + if m.addoutput_tokens != nil { + *m.addoutput_tokens += i + } else { + m.addoutput_tokens = &i + } } -// SetForceTwoFactorAuth sets the "force_two_factor_auth" field. -func (m *SettingMutation) SetForceTwoFactorAuth(b bool) { - m.force_two_factor_auth = &b +// AddedOutputTokens returns the value that was added to the "output_tokens" field in this mutation. +func (m *TaskMutation) AddedOutputTokens() (r int64, exists bool) { + v := m.addoutput_tokens + if v == nil { + return + } + return *v, true } -// ForceTwoFactorAuth returns the value of the "force_two_factor_auth" field in the mutation. -func (m *SettingMutation) ForceTwoFactorAuth() (r bool, exists bool) { - v := m.force_two_factor_auth +// ClearOutputTokens clears the value of the "output_tokens" field. +func (m *TaskMutation) ClearOutputTokens() { + m.output_tokens = nil + m.addoutput_tokens = nil + m.clearedFields[task.FieldOutputTokens] = struct{}{} +} + +// OutputTokensCleared returns if the "output_tokens" field was cleared in this mutation. +func (m *TaskMutation) OutputTokensCleared() bool { + _, ok := m.clearedFields[task.FieldOutputTokens] + return ok +} + +// ResetOutputTokens resets all changes to the "output_tokens" field. +func (m *TaskMutation) ResetOutputTokens() { + m.output_tokens = nil + m.addoutput_tokens = nil + delete(m.clearedFields, task.FieldOutputTokens) +} + +// SetIsSuggested sets the "is_suggested" field. +func (m *TaskMutation) SetIsSuggested(b bool) { + m.is_suggested = &b +} + +// IsSuggested returns the value of the "is_suggested" field in the mutation. +func (m *TaskMutation) IsSuggested() (r bool, exists bool) { + v := m.is_suggested if v == nil { return } return *v, true } -// OldForceTwoFactorAuth returns the old "force_two_factor_auth" field's value of the Setting entity. -// If the Setting object wasn't provided to the builder, the object is fetched from the database. +// OldIsSuggested returns the old "is_suggested" field's value of the Task entity. +// If the Task object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SettingMutation) OldForceTwoFactorAuth(ctx context.Context) (v bool, err error) { +func (m *TaskMutation) OldIsSuggested(ctx context.Context) (v bool, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldForceTwoFactorAuth is only allowed on UpdateOne operations") + return v, errors.New("OldIsSuggested is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldForceTwoFactorAuth requires an ID field in the mutation") + return v, errors.New("OldIsSuggested requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldForceTwoFactorAuth: %w", err) + return v, fmt.Errorf("querying old value for OldIsSuggested: %w", err) } - return oldValue.ForceTwoFactorAuth, nil + return oldValue.IsSuggested, nil } -// ResetForceTwoFactorAuth resets all changes to the "force_two_factor_auth" field. -func (m *SettingMutation) ResetForceTwoFactorAuth() { - m.force_two_factor_auth = nil +// ResetIsSuggested resets all changes to the "is_suggested" field. +func (m *TaskMutation) ResetIsSuggested() { + m.is_suggested = nil } -// SetDisablePasswordLogin sets the "disable_password_login" field. -func (m *SettingMutation) SetDisablePasswordLogin(b bool) { - m.disable_password_login = &b +// SetSourceCode sets the "source_code" field. +func (m *TaskMutation) SetSourceCode(s string) { + m.source_code = &s } -// DisablePasswordLogin returns the value of the "disable_password_login" field in the mutation. -func (m *SettingMutation) DisablePasswordLogin() (r bool, exists bool) { - v := m.disable_password_login +// SourceCode returns the value of the "source_code" field in the mutation. +func (m *TaskMutation) SourceCode() (r string, exists bool) { + v := m.source_code if v == nil { return } return *v, true } -// OldDisablePasswordLogin returns the old "disable_password_login" field's value of the Setting entity. -// If the Setting object wasn't provided to the builder, the object is fetched from the database. +// OldSourceCode returns the old "source_code" field's value of the Task entity. +// If the Task object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SettingMutation) OldDisablePasswordLogin(ctx context.Context) (v bool, err error) { +func (m *TaskMutation) OldSourceCode(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldDisablePasswordLogin is only allowed on UpdateOne operations") + return v, errors.New("OldSourceCode is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldDisablePasswordLogin requires an ID field in the mutation") + return v, errors.New("OldSourceCode requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldDisablePasswordLogin: %w", err) + return v, fmt.Errorf("querying old value for OldSourceCode: %w", err) } - return oldValue.DisablePasswordLogin, nil + return oldValue.SourceCode, nil } -// ResetDisablePasswordLogin resets all changes to the "disable_password_login" field. -func (m *SettingMutation) ResetDisablePasswordLogin() { - m.disable_password_login = nil +// ClearSourceCode clears the value of the "source_code" field. +func (m *TaskMutation) ClearSourceCode() { + m.source_code = nil + m.clearedFields[task.FieldSourceCode] = struct{}{} } -// SetEnableAutoLogin sets the "enable_auto_login" field. -func (m *SettingMutation) SetEnableAutoLogin(b bool) { - m.enable_auto_login = &b +// SourceCodeCleared returns if the "source_code" field was cleared in this mutation. +func (m *TaskMutation) SourceCodeCleared() bool { + _, ok := m.clearedFields[task.FieldSourceCode] + return ok } -// EnableAutoLogin returns the value of the "enable_auto_login" field in the mutation. -func (m *SettingMutation) EnableAutoLogin() (r bool, exists bool) { - v := m.enable_auto_login +// ResetSourceCode resets all changes to the "source_code" field. +func (m *TaskMutation) ResetSourceCode() { + m.source_code = nil + delete(m.clearedFields, task.FieldSourceCode) +} + +// SetCursorPosition sets the "cursor_position" field. +func (m *TaskMutation) SetCursorPosition(value map[string]interface{}) { + m.cursor_position = &value +} + +// CursorPosition returns the value of the "cursor_position" field in the mutation. +func (m *TaskMutation) CursorPosition() (r map[string]interface{}, exists bool) { + v := m.cursor_position if v == nil { return } return *v, true } -// OldEnableAutoLogin returns the old "enable_auto_login" field's value of the Setting entity. -// If the Setting object wasn't provided to the builder, the object is fetched from the database. +// OldCursorPosition returns the old "cursor_position" field's value of the Task entity. +// If the Task object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SettingMutation) OldEnableAutoLogin(ctx context.Context) (v bool, err error) { +func (m *TaskMutation) OldCursorPosition(ctx context.Context) (v map[string]interface{}, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldEnableAutoLogin is only allowed on UpdateOne operations") + return v, errors.New("OldCursorPosition is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldEnableAutoLogin requires an ID field in the mutation") + return v, errors.New("OldCursorPosition requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldEnableAutoLogin: %w", err) + return v, fmt.Errorf("querying old value for OldCursorPosition: %w", err) } - return oldValue.EnableAutoLogin, nil + return oldValue.CursorPosition, nil } -// ResetEnableAutoLogin resets all changes to the "enable_auto_login" field. -func (m *SettingMutation) ResetEnableAutoLogin() { - m.enable_auto_login = nil +// ClearCursorPosition clears the value of the "cursor_position" field. +func (m *TaskMutation) ClearCursorPosition() { + m.cursor_position = nil + m.clearedFields[task.FieldCursorPosition] = struct{}{} } -// SetDingtalkOauth sets the "dingtalk_oauth" field. -func (m *SettingMutation) SetDingtalkOauth(to *types.DingtalkOAuth) { - m.dingtalk_oauth = &to +// CursorPositionCleared returns if the "cursor_position" field was cleared in this mutation. +func (m *TaskMutation) CursorPositionCleared() bool { + _, ok := m.clearedFields[task.FieldCursorPosition] + return ok } -// DingtalkOauth returns the value of the "dingtalk_oauth" field in the mutation. -func (m *SettingMutation) DingtalkOauth() (r *types.DingtalkOAuth, exists bool) { - v := m.dingtalk_oauth +// ResetCursorPosition resets all changes to the "cursor_position" field. +func (m *TaskMutation) ResetCursorPosition() { + m.cursor_position = nil + delete(m.clearedFields, task.FieldCursorPosition) +} + +// SetUserInput sets the "user_input" field. +func (m *TaskMutation) SetUserInput(s string) { + m.user_input = &s +} + +// UserInput returns the value of the "user_input" field in the mutation. +func (m *TaskMutation) UserInput() (r string, exists bool) { + v := m.user_input if v == nil { return } return *v, true } -// OldDingtalkOauth returns the old "dingtalk_oauth" field's value of the Setting entity. -// If the Setting object wasn't provided to the builder, the object is fetched from the database. +// OldUserInput returns the old "user_input" field's value of the Task entity. +// If the Task object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SettingMutation) OldDingtalkOauth(ctx context.Context) (v *types.DingtalkOAuth, err error) { +func (m *TaskMutation) OldUserInput(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldDingtalkOauth is only allowed on UpdateOne operations") + return v, errors.New("OldUserInput is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldDingtalkOauth requires an ID field in the mutation") + return v, errors.New("OldUserInput requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldDingtalkOauth: %w", err) + return v, fmt.Errorf("querying old value for OldUserInput: %w", err) } - return oldValue.DingtalkOauth, nil + return oldValue.UserInput, nil } -// ClearDingtalkOauth clears the value of the "dingtalk_oauth" field. -func (m *SettingMutation) ClearDingtalkOauth() { - m.dingtalk_oauth = nil - m.clearedFields[setting.FieldDingtalkOauth] = struct{}{} +// ClearUserInput clears the value of the "user_input" field. +func (m *TaskMutation) ClearUserInput() { + m.user_input = nil + m.clearedFields[task.FieldUserInput] = struct{}{} } -// DingtalkOauthCleared returns if the "dingtalk_oauth" field was cleared in this mutation. -func (m *SettingMutation) DingtalkOauthCleared() bool { - _, ok := m.clearedFields[setting.FieldDingtalkOauth] +// UserInputCleared returns if the "user_input" field was cleared in this mutation. +func (m *TaskMutation) UserInputCleared() bool { + _, ok := m.clearedFields[task.FieldUserInput] return ok } -// ResetDingtalkOauth resets all changes to the "dingtalk_oauth" field. -func (m *SettingMutation) ResetDingtalkOauth() { - m.dingtalk_oauth = nil - delete(m.clearedFields, setting.FieldDingtalkOauth) +// ResetUserInput resets all changes to the "user_input" field. +func (m *TaskMutation) ResetUserInput() { + m.user_input = nil + delete(m.clearedFields, task.FieldUserInput) } -// SetCustomOauth sets the "custom_oauth" field. -func (m *SettingMutation) SetCustomOauth(to *types.CustomOAuth) { - m.custom_oauth = &to +// SetCreatedAt sets the "created_at" field. +func (m *TaskMutation) SetCreatedAt(t time.Time) { + m.created_at = &t } -// CustomOauth returns the value of the "custom_oauth" field in the mutation. -func (m *SettingMutation) CustomOauth() (r *types.CustomOAuth, exists bool) { - v := m.custom_oauth +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *TaskMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at if v == nil { return } return *v, true } -// OldCustomOauth returns the old "custom_oauth" field's value of the Setting entity. -// If the Setting object wasn't provided to the builder, the object is fetched from the database. +// OldCreatedAt returns the old "created_at" field's value of the Task entity. +// If the Task object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SettingMutation) OldCustomOauth(ctx context.Context) (v *types.CustomOAuth, err error) { +func (m *TaskMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCustomOauth is only allowed on UpdateOne operations") + return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCustomOauth requires an ID field in the mutation") + 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 OldCustomOauth: %w", err) + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) } - return oldValue.CustomOauth, nil -} - -// ClearCustomOauth clears the value of the "custom_oauth" field. -func (m *SettingMutation) ClearCustomOauth() { - m.custom_oauth = nil - m.clearedFields[setting.FieldCustomOauth] = struct{}{} -} - -// CustomOauthCleared returns if the "custom_oauth" field was cleared in this mutation. -func (m *SettingMutation) CustomOauthCleared() bool { - _, ok := m.clearedFields[setting.FieldCustomOauth] - return ok + return oldValue.CreatedAt, nil } -// ResetCustomOauth resets all changes to the "custom_oauth" field. -func (m *SettingMutation) ResetCustomOauth() { - m.custom_oauth = nil - delete(m.clearedFields, setting.FieldCustomOauth) +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *TaskMutation) ResetCreatedAt() { + m.created_at = nil } -// SetBaseURL sets the "base_url" field. -func (m *SettingMutation) SetBaseURL(s string) { - m.base_url = &s +// SetUpdatedAt sets the "updated_at" field. +func (m *TaskMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t } -// BaseURL returns the value of the "base_url" field in the mutation. -func (m *SettingMutation) BaseURL() (r string, exists bool) { - v := m.base_url +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *TaskMutation) UpdatedAt() (r time.Time, exists bool) { + v := m.updated_at if v == nil { return } return *v, true } -// OldBaseURL returns the old "base_url" field's value of the Setting entity. -// If the Setting object wasn't provided to the builder, the object is fetched from the database. +// OldUpdatedAt returns the old "updated_at" field's value of the Task entity. +// If the Task object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *SettingMutation) OldBaseURL(ctx context.Context) (v string, err error) { +func (m *TaskMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldBaseURL is only allowed on UpdateOne operations") + return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldBaseURL requires an ID field in the mutation") + 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 OldBaseURL: %w", err) + return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) } - return oldValue.BaseURL, nil + return oldValue.UpdatedAt, nil } -// ClearBaseURL clears the value of the "base_url" field. -func (m *SettingMutation) ClearBaseURL() { - m.base_url = nil - m.clearedFields[setting.FieldBaseURL] = struct{}{} +// ResetUpdatedAt resets all changes to the "updated_at" field. +func (m *TaskMutation) ResetUpdatedAt() { + m.updated_at = nil } -// BaseURLCleared returns if the "base_url" field was cleared in this mutation. -func (m *SettingMutation) BaseURLCleared() bool { - _, ok := m.clearedFields[setting.FieldBaseURL] - return ok +// AddTaskRecordIDs adds the "task_records" edge to the TaskRecord entity by ids. +func (m *TaskMutation) AddTaskRecordIDs(ids ...uuid.UUID) { + if m.task_records == nil { + m.task_records = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.task_records[ids[i]] = struct{}{} + } } -// ResetBaseURL resets all changes to the "base_url" field. -func (m *SettingMutation) ResetBaseURL() { - m.base_url = nil - delete(m.clearedFields, setting.FieldBaseURL) +// ClearTaskRecords clears the "task_records" edge to the TaskRecord entity. +func (m *TaskMutation) ClearTaskRecords() { + m.clearedtask_records = true +} + +// TaskRecordsCleared reports if the "task_records" edge to the TaskRecord entity was cleared. +func (m *TaskMutation) TaskRecordsCleared() bool { + return m.clearedtask_records +} + +// RemoveTaskRecordIDs removes the "task_records" edge to the TaskRecord entity by IDs. +func (m *TaskMutation) RemoveTaskRecordIDs(ids ...uuid.UUID) { + if m.removedtask_records == nil { + m.removedtask_records = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.task_records, ids[i]) + m.removedtask_records[ids[i]] = struct{}{} + } +} + +// RemovedTaskRecords returns the removed IDs of the "task_records" edge to the TaskRecord entity. +func (m *TaskMutation) RemovedTaskRecordsIDs() (ids []uuid.UUID) { + for id := range m.removedtask_records { + ids = append(ids, id) + } + return +} + +// TaskRecordsIDs returns the "task_records" edge IDs in the mutation. +func (m *TaskMutation) TaskRecordsIDs() (ids []uuid.UUID) { + for id := range m.task_records { + ids = append(ids, id) + } + return } -// SetCreatedAt sets the "created_at" field. -func (m *SettingMutation) SetCreatedAt(t time.Time) { - m.created_at = &t +// ResetTaskRecords resets all changes to the "task_records" edge. +func (m *TaskMutation) ResetTaskRecords() { + m.task_records = nil + m.clearedtask_records = false + m.removedtask_records = nil } -// CreatedAt returns the value of the "created_at" field in the mutation. -func (m *SettingMutation) CreatedAt() (r time.Time, exists bool) { - v := m.created_at - if v == nil { - return - } - return *v, true +// ClearUser clears the "user" edge to the User entity. +func (m *TaskMutation) ClearUser() { + m.cleareduser = true + m.clearedFields[task.FieldUserID] = struct{}{} } -// OldCreatedAt returns the old "created_at" field's value of the Setting entity. -// If the Setting 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 *SettingMutation) 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) +// UserCleared reports if the "user" edge to the User entity was cleared. +func (m *TaskMutation) UserCleared() bool { + return m.UserIDCleared() || m.cleareduser +} + +// UserIDs returns the "user" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// UserID instead. It exists only for internal usage by the builders. +func (m *TaskMutation) UserIDs() (ids []uuid.UUID) { + if id := m.user; id != nil { + ids = append(ids, *id) } - return oldValue.CreatedAt, nil + return } -// ResetCreatedAt resets all changes to the "created_at" field. -func (m *SettingMutation) ResetCreatedAt() { - m.created_at = nil +// ResetUser resets all changes to the "user" edge. +func (m *TaskMutation) ResetUser() { + m.user = nil + m.cleareduser = false } -// SetUpdatedAt sets the "updated_at" field. -func (m *SettingMutation) SetUpdatedAt(t time.Time) { - m.updated_at = &t +// ClearModel clears the "model" edge to the Model entity. +func (m *TaskMutation) ClearModel() { + m.clearedmodel = true + m.clearedFields[task.FieldModelID] = struct{}{} } -// UpdatedAt returns the value of the "updated_at" field in the mutation. -func (m *SettingMutation) UpdatedAt() (r time.Time, exists bool) { - v := m.updated_at - if v == nil { - return - } - return *v, true +// ModelCleared reports if the "model" edge to the Model entity was cleared. +func (m *TaskMutation) ModelCleared() bool { + return m.ModelIDCleared() || m.clearedmodel } -// OldUpdatedAt returns the old "updated_at" field's value of the Setting entity. -// If the Setting 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 *SettingMutation) 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) +// ModelIDs returns the "model" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// ModelID instead. It exists only for internal usage by the builders. +func (m *TaskMutation) ModelIDs() (ids []uuid.UUID) { + if id := m.model; id != nil { + ids = append(ids, *id) } - return oldValue.UpdatedAt, nil + return } -// ResetUpdatedAt resets all changes to the "updated_at" field. -func (m *SettingMutation) ResetUpdatedAt() { - m.updated_at = nil +// ResetModel resets all changes to the "model" edge. +func (m *TaskMutation) ResetModel() { + m.model = nil + m.clearedmodel = false } -// Where appends a list predicates to the SettingMutation builder. -func (m *SettingMutation) Where(ps ...predicate.Setting) { +// Where appends a list predicates to the TaskMutation builder. +func (m *TaskMutation) Where(ps ...predicate.Task) { m.predicates = append(m.predicates, ps...) } -// WhereP appends storage-level predicates to the SettingMutation builder. Using this method, +// WhereP appends storage-level predicates to the TaskMutation builder. Using this method, // users can use type-assertion to append predicates that do not depend on any generated package. -func (m *SettingMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.Setting, len(ps)) +func (m *TaskMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Task, len(ps)) for i := range ps { p[i] = ps[i] } @@ -14555,51 +17588,81 @@ func (m *SettingMutation) WhereP(ps ...func(*sql.Selector)) { } // Op returns the operation name. -func (m *SettingMutation) Op() Op { +func (m *TaskMutation) Op() Op { return m.op } // SetOp allows setting the mutation operation. -func (m *SettingMutation) SetOp(op Op) { +func (m *TaskMutation) SetOp(op Op) { m.op = op } -// Type returns the node type of this mutation (Setting). -func (m *SettingMutation) Type() string { +// Type returns the node type of this mutation (Task). +func (m *TaskMutation) Type() string { return m.typ } // Fields returns all fields that were changed during this mutation. Note that in // order to get all numeric fields that were incremented/decremented, call // AddedFields(). -func (m *SettingMutation) Fields() []string { - fields := make([]string, 0, 9) - if m.enable_sso != nil { - fields = append(fields, setting.FieldEnableSSO) +func (m *TaskMutation) Fields() []string { + fields := make([]string, 0, 19) + if m.task_id != nil { + fields = append(fields, task.FieldTaskID) } - if m.force_two_factor_auth != nil { - fields = append(fields, setting.FieldForceTwoFactorAuth) + if m.user != nil { + fields = append(fields, task.FieldUserID) } - if m.disable_password_login != nil { - fields = append(fields, setting.FieldDisablePasswordLogin) + if m.model != nil { + fields = append(fields, task.FieldModelID) } - if m.enable_auto_login != nil { - fields = append(fields, setting.FieldEnableAutoLogin) + if m.request_id != nil { + fields = append(fields, task.FieldRequestID) } - if m.dingtalk_oauth != nil { - fields = append(fields, setting.FieldDingtalkOauth) + if m.model_type != nil { + fields = append(fields, task.FieldModelType) } - if m.custom_oauth != nil { - fields = append(fields, setting.FieldCustomOauth) + if m.is_accept != nil { + fields = append(fields, task.FieldIsAccept) } - if m.base_url != nil { - fields = append(fields, setting.FieldBaseURL) + if m.program_language != nil { + fields = append(fields, task.FieldProgramLanguage) + } + if m.work_mode != nil { + fields = append(fields, task.FieldWorkMode) + } + if m.prompt != nil { + fields = append(fields, task.FieldPrompt) + } + if m.completion != nil { + fields = append(fields, task.FieldCompletion) + } + if m.code_lines != nil { + fields = append(fields, task.FieldCodeLines) + } + if m.input_tokens != nil { + fields = append(fields, task.FieldInputTokens) + } + if m.output_tokens != nil { + fields = append(fields, task.FieldOutputTokens) + } + if m.is_suggested != nil { + fields = append(fields, task.FieldIsSuggested) + } + if m.source_code != nil { + fields = append(fields, task.FieldSourceCode) + } + if m.cursor_position != nil { + fields = append(fields, task.FieldCursorPosition) + } + if m.user_input != nil { + fields = append(fields, task.FieldUserInput) } if m.created_at != nil { - fields = append(fields, setting.FieldCreatedAt) + fields = append(fields, task.FieldCreatedAt) } if m.updated_at != nil { - fields = append(fields, setting.FieldUpdatedAt) + fields = append(fields, task.FieldUpdatedAt) } return fields } @@ -14607,25 +17670,45 @@ func (m *SettingMutation) Fields() []string { // 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 *SettingMutation) Field(name string) (ent.Value, bool) { +func (m *TaskMutation) Field(name string) (ent.Value, bool) { switch name { - case setting.FieldEnableSSO: - return m.EnableSSO() - case setting.FieldForceTwoFactorAuth: - return m.ForceTwoFactorAuth() - case setting.FieldDisablePasswordLogin: - return m.DisablePasswordLogin() - case setting.FieldEnableAutoLogin: - return m.EnableAutoLogin() - case setting.FieldDingtalkOauth: - return m.DingtalkOauth() - case setting.FieldCustomOauth: - return m.CustomOauth() - case setting.FieldBaseURL: - return m.BaseURL() - case setting.FieldCreatedAt: + case task.FieldTaskID: + return m.TaskID() + case task.FieldUserID: + return m.UserID() + case task.FieldModelID: + return m.ModelID() + case task.FieldRequestID: + return m.RequestID() + case task.FieldModelType: + return m.ModelType() + case task.FieldIsAccept: + return m.IsAccept() + case task.FieldProgramLanguage: + return m.ProgramLanguage() + case task.FieldWorkMode: + return m.WorkMode() + case task.FieldPrompt: + return m.Prompt() + case task.FieldCompletion: + return m.Completion() + case task.FieldCodeLines: + return m.CodeLines() + case task.FieldInputTokens: + return m.InputTokens() + case task.FieldOutputTokens: + return m.OutputTokens() + case task.FieldIsSuggested: + return m.IsSuggested() + case task.FieldSourceCode: + return m.SourceCode() + case task.FieldCursorPosition: + return m.CursorPosition() + case task.FieldUserInput: + return m.UserInput() + case task.FieldCreatedAt: return m.CreatedAt() - case setting.FieldUpdatedAt: + case task.FieldUpdatedAt: return m.UpdatedAt() } return nil, false @@ -14634,92 +17717,182 @@ func (m *SettingMutation) Field(name string) (ent.Value, bool) { // 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 *SettingMutation) OldField(ctx context.Context, name string) (ent.Value, error) { +func (m *TaskMutation) OldField(ctx context.Context, name string) (ent.Value, error) { switch name { - case setting.FieldEnableSSO: - return m.OldEnableSSO(ctx) - case setting.FieldForceTwoFactorAuth: - return m.OldForceTwoFactorAuth(ctx) - case setting.FieldDisablePasswordLogin: - return m.OldDisablePasswordLogin(ctx) - case setting.FieldEnableAutoLogin: - return m.OldEnableAutoLogin(ctx) - case setting.FieldDingtalkOauth: - return m.OldDingtalkOauth(ctx) - case setting.FieldCustomOauth: - return m.OldCustomOauth(ctx) - case setting.FieldBaseURL: - return m.OldBaseURL(ctx) - case setting.FieldCreatedAt: + case task.FieldTaskID: + return m.OldTaskID(ctx) + case task.FieldUserID: + return m.OldUserID(ctx) + case task.FieldModelID: + return m.OldModelID(ctx) + case task.FieldRequestID: + return m.OldRequestID(ctx) + case task.FieldModelType: + return m.OldModelType(ctx) + case task.FieldIsAccept: + return m.OldIsAccept(ctx) + case task.FieldProgramLanguage: + return m.OldProgramLanguage(ctx) + case task.FieldWorkMode: + return m.OldWorkMode(ctx) + case task.FieldPrompt: + return m.OldPrompt(ctx) + case task.FieldCompletion: + return m.OldCompletion(ctx) + case task.FieldCodeLines: + return m.OldCodeLines(ctx) + case task.FieldInputTokens: + return m.OldInputTokens(ctx) + case task.FieldOutputTokens: + return m.OldOutputTokens(ctx) + case task.FieldIsSuggested: + return m.OldIsSuggested(ctx) + case task.FieldSourceCode: + return m.OldSourceCode(ctx) + case task.FieldCursorPosition: + return m.OldCursorPosition(ctx) + case task.FieldUserInput: + return m.OldUserInput(ctx) + case task.FieldCreatedAt: return m.OldCreatedAt(ctx) - case setting.FieldUpdatedAt: + case task.FieldUpdatedAt: return m.OldUpdatedAt(ctx) } - return nil, fmt.Errorf("unknown Setting field %s", name) + return nil, fmt.Errorf("unknown Task field %s", name) } // SetField sets the value of a field with the given name. It returns an error if // the field is not defined in the schema, or if the type mismatched the field // type. -func (m *SettingMutation) SetField(name string, value ent.Value) error { +func (m *TaskMutation) SetField(name string, value ent.Value) error { switch name { - case setting.FieldEnableSSO: - v, ok := value.(bool) + case task.FieldTaskID: + v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetEnableSSO(v) + m.SetTaskID(v) return nil - case setting.FieldForceTwoFactorAuth: - v, ok := value.(bool) + case task.FieldUserID: + v, ok := value.(uuid.UUID) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetForceTwoFactorAuth(v) + m.SetUserID(v) return nil - case setting.FieldDisablePasswordLogin: + case task.FieldModelID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetModelID(v) + return nil + case task.FieldRequestID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRequestID(v) + return nil + case task.FieldModelType: + v, ok := value.(consts.ModelType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetModelType(v) + return nil + case task.FieldIsAccept: v, ok := value.(bool) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetDisablePasswordLogin(v) + m.SetIsAccept(v) return nil - case setting.FieldEnableAutoLogin: + case task.FieldProgramLanguage: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetProgramLanguage(v) + return nil + case task.FieldWorkMode: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetWorkMode(v) + return nil + case task.FieldPrompt: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPrompt(v) + return nil + case task.FieldCompletion: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCompletion(v) + return nil + case task.FieldCodeLines: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCodeLines(v) + return nil + case task.FieldInputTokens: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInputTokens(v) + return nil + case task.FieldOutputTokens: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetOutputTokens(v) + return nil + case task.FieldIsSuggested: v, ok := value.(bool) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetEnableAutoLogin(v) + m.SetIsSuggested(v) return nil - case setting.FieldDingtalkOauth: - v, ok := value.(*types.DingtalkOAuth) + case task.FieldSourceCode: + v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetDingtalkOauth(v) + m.SetSourceCode(v) return nil - case setting.FieldCustomOauth: - v, ok := value.(*types.CustomOAuth) + case task.FieldCursorPosition: + v, ok := value.(map[string]interface{}) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetCustomOauth(v) + m.SetCursorPosition(v) return nil - case setting.FieldBaseURL: + case task.FieldUserInput: v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetBaseURL(v) + m.SetUserInput(v) return nil - case setting.FieldCreatedAt: + case task.FieldCreatedAt: v, ok := value.(time.Time) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } m.SetCreatedAt(v) return nil - case setting.FieldUpdatedAt: + case task.FieldUpdatedAt: v, ok := value.(time.Time) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) @@ -14727,204 +17900,390 @@ func (m *SettingMutation) SetField(name string, value ent.Value) error { m.SetUpdatedAt(v) return nil } - return fmt.Errorf("unknown Setting field %s", name) + return fmt.Errorf("unknown Task field %s", name) } // AddedFields returns all numeric fields that were incremented/decremented during // this mutation. -func (m *SettingMutation) AddedFields() []string { - return nil +func (m *TaskMutation) AddedFields() []string { + var fields []string + if m.addcode_lines != nil { + fields = append(fields, task.FieldCodeLines) + } + if m.addinput_tokens != nil { + fields = append(fields, task.FieldInputTokens) + } + if m.addoutput_tokens != nil { + fields = append(fields, task.FieldOutputTokens) + } + return fields } // AddedField returns the numeric value that was incremented/decremented on a field // with the given name. The second boolean return value indicates that this field // was not set, or was not defined in the schema. -func (m *SettingMutation) AddedField(name string) (ent.Value, bool) { +func (m *TaskMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case task.FieldCodeLines: + return m.AddedCodeLines() + case task.FieldInputTokens: + return m.AddedInputTokens() + case task.FieldOutputTokens: + return m.AddedOutputTokens() + } return nil, false } // AddField adds the value to the field with the given name. It returns an error if // the field is not defined in the schema, or if the type mismatched the field // type. -func (m *SettingMutation) AddField(name string, value ent.Value) error { +func (m *TaskMutation) AddField(name string, value ent.Value) error { switch name { + case task.FieldCodeLines: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddCodeLines(v) + return nil + case task.FieldInputTokens: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddInputTokens(v) + return nil + case task.FieldOutputTokens: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddOutputTokens(v) + return nil } - return fmt.Errorf("unknown Setting numeric field %s", name) + return fmt.Errorf("unknown Task numeric field %s", name) } // ClearedFields returns all nullable fields that were cleared during this // mutation. -func (m *SettingMutation) ClearedFields() []string { +func (m *TaskMutation) ClearedFields() []string { var fields []string - if m.FieldCleared(setting.FieldDingtalkOauth) { - fields = append(fields, setting.FieldDingtalkOauth) + if m.FieldCleared(task.FieldUserID) { + fields = append(fields, task.FieldUserID) } - if m.FieldCleared(setting.FieldCustomOauth) { - fields = append(fields, setting.FieldCustomOauth) + if m.FieldCleared(task.FieldModelID) { + fields = append(fields, task.FieldModelID) } - if m.FieldCleared(setting.FieldBaseURL) { - fields = append(fields, setting.FieldBaseURL) + if m.FieldCleared(task.FieldRequestID) { + fields = append(fields, task.FieldRequestID) + } + if m.FieldCleared(task.FieldProgramLanguage) { + fields = append(fields, task.FieldProgramLanguage) + } + if m.FieldCleared(task.FieldWorkMode) { + fields = append(fields, task.FieldWorkMode) + } + if m.FieldCleared(task.FieldPrompt) { + fields = append(fields, task.FieldPrompt) + } + if m.FieldCleared(task.FieldCompletion) { + fields = append(fields, task.FieldCompletion) + } + if m.FieldCleared(task.FieldCodeLines) { + fields = append(fields, task.FieldCodeLines) + } + if m.FieldCleared(task.FieldInputTokens) { + fields = append(fields, task.FieldInputTokens) + } + if m.FieldCleared(task.FieldOutputTokens) { + fields = append(fields, task.FieldOutputTokens) + } + if m.FieldCleared(task.FieldSourceCode) { + fields = append(fields, task.FieldSourceCode) + } + if m.FieldCleared(task.FieldCursorPosition) { + fields = append(fields, task.FieldCursorPosition) + } + if m.FieldCleared(task.FieldUserInput) { + fields = append(fields, task.FieldUserInput) } return fields } // FieldCleared returns a boolean indicating if a field with the given name was // cleared in this mutation. -func (m *SettingMutation) FieldCleared(name string) bool { +func (m *TaskMutation) FieldCleared(name string) bool { _, ok := m.clearedFields[name] return ok } // ClearField clears the value of the field with the given name. It returns an // error if the field is not defined in the schema. -func (m *SettingMutation) ClearField(name string) error { +func (m *TaskMutation) ClearField(name string) error { switch name { - case setting.FieldDingtalkOauth: - m.ClearDingtalkOauth() + case task.FieldUserID: + m.ClearUserID() + return nil + case task.FieldModelID: + m.ClearModelID() + return nil + case task.FieldRequestID: + m.ClearRequestID() return nil - case setting.FieldCustomOauth: - m.ClearCustomOauth() + case task.FieldProgramLanguage: + m.ClearProgramLanguage() return nil - case setting.FieldBaseURL: - m.ClearBaseURL() + case task.FieldWorkMode: + m.ClearWorkMode() + return nil + case task.FieldPrompt: + m.ClearPrompt() + return nil + case task.FieldCompletion: + m.ClearCompletion() + return nil + case task.FieldCodeLines: + m.ClearCodeLines() + return nil + case task.FieldInputTokens: + m.ClearInputTokens() + return nil + case task.FieldOutputTokens: + m.ClearOutputTokens() + return nil + case task.FieldSourceCode: + m.ClearSourceCode() + return nil + case task.FieldCursorPosition: + m.ClearCursorPosition() + return nil + case task.FieldUserInput: + m.ClearUserInput() return nil } - return fmt.Errorf("unknown Setting nullable field %s", name) + return fmt.Errorf("unknown Task nullable field %s", name) } // ResetField resets all changes in the mutation for the field with the given name. // It returns an error if the field is not defined in the schema. -func (m *SettingMutation) ResetField(name string) error { +func (m *TaskMutation) ResetField(name string) error { switch name { - case setting.FieldEnableSSO: - m.ResetEnableSSO() + case task.FieldTaskID: + m.ResetTaskID() return nil - case setting.FieldForceTwoFactorAuth: - m.ResetForceTwoFactorAuth() + case task.FieldUserID: + m.ResetUserID() return nil - case setting.FieldDisablePasswordLogin: - m.ResetDisablePasswordLogin() + case task.FieldModelID: + m.ResetModelID() return nil - case setting.FieldEnableAutoLogin: - m.ResetEnableAutoLogin() + case task.FieldRequestID: + m.ResetRequestID() return nil - case setting.FieldDingtalkOauth: - m.ResetDingtalkOauth() + case task.FieldModelType: + m.ResetModelType() return nil - case setting.FieldCustomOauth: - m.ResetCustomOauth() + case task.FieldIsAccept: + m.ResetIsAccept() return nil - case setting.FieldBaseURL: - m.ResetBaseURL() + case task.FieldProgramLanguage: + m.ResetProgramLanguage() return nil - case setting.FieldCreatedAt: + case task.FieldWorkMode: + m.ResetWorkMode() + return nil + case task.FieldPrompt: + m.ResetPrompt() + return nil + case task.FieldCompletion: + m.ResetCompletion() + return nil + case task.FieldCodeLines: + m.ResetCodeLines() + return nil + case task.FieldInputTokens: + m.ResetInputTokens() + return nil + case task.FieldOutputTokens: + m.ResetOutputTokens() + return nil + case task.FieldIsSuggested: + m.ResetIsSuggested() + return nil + case task.FieldSourceCode: + m.ResetSourceCode() + return nil + case task.FieldCursorPosition: + m.ResetCursorPosition() + return nil + case task.FieldUserInput: + m.ResetUserInput() + return nil + case task.FieldCreatedAt: m.ResetCreatedAt() return nil - case setting.FieldUpdatedAt: + case task.FieldUpdatedAt: m.ResetUpdatedAt() return nil } - return fmt.Errorf("unknown Setting field %s", name) + return fmt.Errorf("unknown Task field %s", name) } // AddedEdges returns all edge names that were set/added in this mutation. -func (m *SettingMutation) AddedEdges() []string { - edges := make([]string, 0, 0) +func (m *TaskMutation) AddedEdges() []string { + edges := make([]string, 0, 3) + if m.task_records != nil { + edges = append(edges, task.EdgeTaskRecords) + } + if m.user != nil { + edges = append(edges, task.EdgeUser) + } + if m.model != nil { + edges = append(edges, task.EdgeModel) + } return edges } // AddedIDs returns all IDs (to other nodes) that were added for the given edge // name in this mutation. -func (m *SettingMutation) AddedIDs(name string) []ent.Value { +func (m *TaskMutation) AddedIDs(name string) []ent.Value { + switch name { + case task.EdgeTaskRecords: + ids := make([]ent.Value, 0, len(m.task_records)) + for id := range m.task_records { + ids = append(ids, id) + } + return ids + case task.EdgeUser: + if id := m.user; id != nil { + return []ent.Value{*id} + } + case task.EdgeModel: + if id := m.model; id != nil { + return []ent.Value{*id} + } + } return nil } // RemovedEdges returns all edge names that were removed in this mutation. -func (m *SettingMutation) RemovedEdges() []string { - edges := make([]string, 0, 0) +func (m *TaskMutation) RemovedEdges() []string { + edges := make([]string, 0, 3) + if m.removedtask_records != nil { + edges = append(edges, task.EdgeTaskRecords) + } return edges } // RemovedIDs returns all IDs (to other nodes) that were removed for the edge with // the given name in this mutation. -func (m *SettingMutation) RemovedIDs(name string) []ent.Value { +func (m *TaskMutation) RemovedIDs(name string) []ent.Value { + switch name { + case task.EdgeTaskRecords: + ids := make([]ent.Value, 0, len(m.removedtask_records)) + for id := range m.removedtask_records { + ids = append(ids, id) + } + return ids + } return nil } // ClearedEdges returns all edge names that were cleared in this mutation. -func (m *SettingMutation) ClearedEdges() []string { - edges := make([]string, 0, 0) +func (m *TaskMutation) ClearedEdges() []string { + edges := make([]string, 0, 3) + if m.clearedtask_records { + edges = append(edges, task.EdgeTaskRecords) + } + if m.cleareduser { + edges = append(edges, task.EdgeUser) + } + if m.clearedmodel { + edges = append(edges, task.EdgeModel) + } return edges } // EdgeCleared returns a boolean which indicates if the edge with the given name // was cleared in this mutation. -func (m *SettingMutation) EdgeCleared(name string) bool { +func (m *TaskMutation) EdgeCleared(name string) bool { + switch name { + case task.EdgeTaskRecords: + return m.clearedtask_records + case task.EdgeUser: + return m.cleareduser + case task.EdgeModel: + return m.clearedmodel + } return false } // ClearEdge clears the value of the edge with the given name. It returns an error // if that edge is not defined in the schema. -func (m *SettingMutation) ClearEdge(name string) error { - return fmt.Errorf("unknown Setting unique edge %s", name) +func (m *TaskMutation) ClearEdge(name string) error { + switch name { + case task.EdgeUser: + m.ClearUser() + return nil + case task.EdgeModel: + m.ClearModel() + return nil + } + return fmt.Errorf("unknown Task unique edge %s", name) } // ResetEdge resets all changes to the edge with the given name in this mutation. // It returns an error if the edge is not defined in the schema. -func (m *SettingMutation) ResetEdge(name string) error { - return fmt.Errorf("unknown Setting edge %s", name) +func (m *TaskMutation) ResetEdge(name string) error { + switch name { + case task.EdgeTaskRecords: + m.ResetTaskRecords() + return nil + case task.EdgeUser: + m.ResetUser() + return nil + case task.EdgeModel: + m.ResetModel() + return nil + } + return fmt.Errorf("unknown Task edge %s", name) } -// TaskMutation represents an operation that mutates the Task nodes in the graph. -type TaskMutation struct { +// TaskRecordMutation represents an operation that mutates the TaskRecord nodes in the graph. +type TaskRecordMutation struct { config - op Op - typ string - id *uuid.UUID - task_id *string - request_id *string - model_type *consts.ModelType - is_accept *bool - program_language *string - work_mode *string - prompt *string - completion *string - code_lines *int64 - addcode_lines *int64 - input_tokens *int64 - addinput_tokens *int64 - output_tokens *int64 - addoutput_tokens *int64 - is_suggested *bool - source_code *string - cursor_position *map[string]interface{} - user_input *string - created_at *time.Time - updated_at *time.Time - clearedFields map[string]struct{} - task_records map[uuid.UUID]struct{} - removedtask_records map[uuid.UUID]struct{} - clearedtask_records bool - user *uuid.UUID - cleareduser bool - model *uuid.UUID - clearedmodel bool - done bool - oldValue func(context.Context) (*Task, error) - predicates []predicate.Task + op Op + typ string + id *uuid.UUID + prompt *string + role *consts.ChatRole + completion *string + output_tokens *int64 + addoutput_tokens *int64 + code_lines *int64 + addcode_lines *int64 + code *string + created_at *time.Time + updated_at *time.Time + clearedFields map[string]struct{} + task *uuid.UUID + clearedtask bool + done bool + oldValue func(context.Context) (*TaskRecord, error) + predicates []predicate.TaskRecord } -var _ ent.Mutation = (*TaskMutation)(nil) +var _ ent.Mutation = (*TaskRecordMutation)(nil) -// taskOption allows management of the mutation configuration using functional options. -type taskOption func(*TaskMutation) +// taskrecordOption allows management of the mutation configuration using functional options. +type taskrecordOption func(*TaskRecordMutation) -// newTaskMutation creates new mutation for the Task entity. -func newTaskMutation(c config, op Op, opts ...taskOption) *TaskMutation { - m := &TaskMutation{ +// newTaskRecordMutation creates new mutation for the TaskRecord entity. +func newTaskRecordMutation(c config, op Op, opts ...taskrecordOption) *TaskRecordMutation { + m := &TaskRecordMutation{ config: c, op: op, - typ: TypeTask, + typ: TypeTaskRecord, clearedFields: make(map[string]struct{}), } for _, opt := range opts { @@ -14933,20 +18292,20 @@ func newTaskMutation(c config, op Op, opts ...taskOption) *TaskMutation { return m } -// withTaskID sets the ID field of the mutation. -func withTaskID(id uuid.UUID) taskOption { - return func(m *TaskMutation) { +// withTaskRecordID sets the ID field of the mutation. +func withTaskRecordID(id uuid.UUID) taskrecordOption { + return func(m *TaskRecordMutation) { var ( err error once sync.Once - value *Task + value *TaskRecord ) - m.oldValue = func(ctx context.Context) (*Task, error) { + m.oldValue = func(ctx context.Context) (*TaskRecord, error) { once.Do(func() { if m.done { err = errors.New("querying old values post mutation is not allowed") } else { - value, err = m.Client().Task.Get(ctx, id) + value, err = m.Client().TaskRecord.Get(ctx, id) } }) return value, err @@ -14955,10 +18314,10 @@ func withTaskID(id uuid.UUID) taskOption { } } -// withTask sets the old Task of the mutation. -func withTask(node *Task) taskOption { - return func(m *TaskMutation) { - m.oldValue = func(context.Context) (*Task, error) { +// withTaskRecord sets the old TaskRecord of the mutation. +func withTaskRecord(node *TaskRecord) taskrecordOption { + return func(m *TaskRecordMutation) { + m.oldValue = func(context.Context) (*TaskRecord, error) { return node, nil } m.id = &node.ID @@ -14967,7 +18326,7 @@ func withTask(node *Task) taskOption { // Client returns a new `ent.Client` from the mutation. If the mutation was // executed in a transaction (ent.Tx), a transactional client is returned. -func (m TaskMutation) Client() *Client { +func (m TaskRecordMutation) Client() *Client { client := &Client{config: m.config} client.init() return client @@ -14975,7 +18334,7 @@ func (m TaskMutation) Client() *Client { // Tx returns an `ent.Tx` for mutations that were executed in transactions; // it returns an error otherwise. -func (m TaskMutation) Tx() (*Tx, error) { +func (m TaskRecordMutation) Tx() (*Tx, error) { if _, ok := m.driver.(*txDriver); !ok { return nil, errors.New("db: mutation is not running in a transaction") } @@ -14985,14 +18344,14 @@ func (m TaskMutation) Tx() (*Tx, error) { } // SetID sets the value of the id field. Note that this -// operation is only accepted on creation of Task entities. -func (m *TaskMutation) SetID(id uuid.UUID) { +// operation is only accepted on creation of TaskRecord entities. +func (m *TaskRecordMutation) SetID(id uuid.UUID) { m.id = &id } // ID returns the ID value in the mutation. Note that the ID is only available // if it was provided to the builder or after it was returned from the database. -func (m *TaskMutation) ID() (id uuid.UUID, exists bool) { +func (m *TaskRecordMutation) ID() (id uuid.UUID, exists bool) { if m.id == nil { return } @@ -15003,7 +18362,7 @@ func (m *TaskMutation) ID() (id uuid.UUID, exists bool) { // That means, if the mutation is applied within a transaction with an isolation level such // as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated // or updated by the mutation. -func (m *TaskMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { +func (m *TaskRecordMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { switch { case m.op.Is(OpUpdateOne | OpDeleteOne): id, exists := m.ID() @@ -15012,30 +18371,30 @@ func (m *TaskMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { } fallthrough case m.op.Is(OpUpdate | OpDelete): - return m.Client().Task.Query().Where(m.predicates...).IDs(ctx) + return m.Client().TaskRecord.Query().Where(m.predicates...).IDs(ctx) default: return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) } } // SetTaskID sets the "task_id" field. -func (m *TaskMutation) SetTaskID(s string) { - m.task_id = &s +func (m *TaskRecordMutation) SetTaskID(u uuid.UUID) { + m.task = &u } // TaskID returns the value of the "task_id" field in the mutation. -func (m *TaskMutation) TaskID() (r string, exists bool) { - v := m.task_id +func (m *TaskRecordMutation) TaskID() (r uuid.UUID, exists bool) { + v := m.task if v == nil { return } return *v, true } -// OldTaskID returns the old "task_id" field's value of the Task entity. -// If the Task object wasn't provided to the builder, the object is fetched from the database. +// OldTaskID returns the old "task_id" field's value of the TaskRecord entity. +// If the TaskRecord object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *TaskMutation) OldTaskID(ctx context.Context) (v string, err error) { +func (m *TaskRecordMutation) OldTaskID(ctx context.Context) (v uuid.UUID, err error) { if !m.op.Is(OpUpdateOne) { return v, errors.New("OldTaskID is only allowed on UpdateOne operations") } @@ -15049,3621 +18408,4097 @@ func (m *TaskMutation) OldTaskID(ctx context.Context) (v string, err error) { return oldValue.TaskID, nil } +// ClearTaskID clears the value of the "task_id" field. +func (m *TaskRecordMutation) ClearTaskID() { + m.task = nil + m.clearedFields[taskrecord.FieldTaskID] = struct{}{} +} + +// TaskIDCleared returns if the "task_id" field was cleared in this mutation. +func (m *TaskRecordMutation) TaskIDCleared() bool { + _, ok := m.clearedFields[taskrecord.FieldTaskID] + return ok +} + // ResetTaskID resets all changes to the "task_id" field. -func (m *TaskMutation) ResetTaskID() { - m.task_id = nil +func (m *TaskRecordMutation) ResetTaskID() { + m.task = nil + delete(m.clearedFields, taskrecord.FieldTaskID) } -// SetUserID sets the "user_id" field. -func (m *TaskMutation) SetUserID(u uuid.UUID) { - m.user = &u +// SetPrompt sets the "prompt" field. +func (m *TaskRecordMutation) SetPrompt(s string) { + m.prompt = &s } -// UserID returns the value of the "user_id" field in the mutation. -func (m *TaskMutation) UserID() (r uuid.UUID, exists bool) { - v := m.user +// Prompt returns the value of the "prompt" field in the mutation. +func (m *TaskRecordMutation) Prompt() (r string, exists bool) { + v := m.prompt if v == nil { return } return *v, true } -// OldUserID returns the old "user_id" field's value of the Task entity. -// If the Task object wasn't provided to the builder, the object is fetched from the database. +// OldPrompt returns the old "prompt" field's value of the TaskRecord entity. +// If the TaskRecord object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *TaskMutation) OldUserID(ctx context.Context) (v uuid.UUID, err error) { +func (m *TaskRecordMutation) OldPrompt(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldUserID is only allowed on UpdateOne operations") + return v, errors.New("OldPrompt is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldUserID requires an ID field in the mutation") + return v, errors.New("OldPrompt requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldUserID: %w", err) + return v, fmt.Errorf("querying old value for OldPrompt: %w", err) } - return oldValue.UserID, nil + return oldValue.Prompt, nil } -// ClearUserID clears the value of the "user_id" field. -func (m *TaskMutation) ClearUserID() { - m.user = nil - m.clearedFields[task.FieldUserID] = struct{}{} +// ClearPrompt clears the value of the "prompt" field. +func (m *TaskRecordMutation) ClearPrompt() { + m.prompt = nil + m.clearedFields[taskrecord.FieldPrompt] = struct{}{} } -// UserIDCleared returns if the "user_id" field was cleared in this mutation. -func (m *TaskMutation) UserIDCleared() bool { - _, ok := m.clearedFields[task.FieldUserID] +// PromptCleared returns if the "prompt" field was cleared in this mutation. +func (m *TaskRecordMutation) PromptCleared() bool { + _, ok := m.clearedFields[taskrecord.FieldPrompt] return ok } -// ResetUserID resets all changes to the "user_id" field. -func (m *TaskMutation) ResetUserID() { - m.user = nil - delete(m.clearedFields, task.FieldUserID) +// ResetPrompt resets all changes to the "prompt" field. +func (m *TaskRecordMutation) ResetPrompt() { + m.prompt = nil + delete(m.clearedFields, taskrecord.FieldPrompt) } -// SetModelID sets the "model_id" field. -func (m *TaskMutation) SetModelID(u uuid.UUID) { - m.model = &u +// SetRole sets the "role" field. +func (m *TaskRecordMutation) SetRole(cr consts.ChatRole) { + m.role = &cr } -// ModelID returns the value of the "model_id" field in the mutation. -func (m *TaskMutation) ModelID() (r uuid.UUID, exists bool) { - v := m.model +// Role returns the value of the "role" field in the mutation. +func (m *TaskRecordMutation) Role() (r consts.ChatRole, exists bool) { + v := m.role if v == nil { return } return *v, true } -// OldModelID returns the old "model_id" field's value of the Task entity. -// If the Task object wasn't provided to the builder, the object is fetched from the database. +// OldRole returns the old "role" field's value of the TaskRecord entity. +// If the TaskRecord object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *TaskMutation) OldModelID(ctx context.Context) (v uuid.UUID, err error) { +func (m *TaskRecordMutation) OldRole(ctx context.Context) (v consts.ChatRole, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldModelID is only allowed on UpdateOne operations") + return v, errors.New("OldRole is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldModelID requires an ID field in the mutation") + return v, errors.New("OldRole requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldModelID: %w", err) + return v, fmt.Errorf("querying old value for OldRole: %w", err) } - return oldValue.ModelID, nil + return oldValue.Role, nil } -// ClearModelID clears the value of the "model_id" field. -func (m *TaskMutation) ClearModelID() { - m.model = nil - m.clearedFields[task.FieldModelID] = struct{}{} +// ResetRole resets all changes to the "role" field. +func (m *TaskRecordMutation) ResetRole() { + m.role = nil } -// ModelIDCleared returns if the "model_id" field was cleared in this mutation. -func (m *TaskMutation) ModelIDCleared() bool { - _, ok := m.clearedFields[task.FieldModelID] +// SetCompletion sets the "completion" field. +func (m *TaskRecordMutation) SetCompletion(s string) { + m.completion = &s +} + +// Completion returns the value of the "completion" field in the mutation. +func (m *TaskRecordMutation) Completion() (r string, exists bool) { + v := m.completion + if v == nil { + return + } + return *v, true +} + +// OldCompletion returns the old "completion" field's value of the TaskRecord entity. +// If the TaskRecord object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *TaskRecordMutation) OldCompletion(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCompletion is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCompletion requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCompletion: %w", err) + } + return oldValue.Completion, nil +} + +// ClearCompletion clears the value of the "completion" field. +func (m *TaskRecordMutation) ClearCompletion() { + m.completion = nil + m.clearedFields[taskrecord.FieldCompletion] = struct{}{} +} + +// CompletionCleared returns if the "completion" field was cleared in this mutation. +func (m *TaskRecordMutation) CompletionCleared() bool { + _, ok := m.clearedFields[taskrecord.FieldCompletion] return ok } -// ResetModelID resets all changes to the "model_id" field. -func (m *TaskMutation) ResetModelID() { - m.model = nil - delete(m.clearedFields, task.FieldModelID) +// ResetCompletion resets all changes to the "completion" field. +func (m *TaskRecordMutation) ResetCompletion() { + m.completion = nil + delete(m.clearedFields, taskrecord.FieldCompletion) } -// SetRequestID sets the "request_id" field. -func (m *TaskMutation) SetRequestID(s string) { - m.request_id = &s +// SetOutputTokens sets the "output_tokens" field. +func (m *TaskRecordMutation) SetOutputTokens(i int64) { + m.output_tokens = &i + m.addoutput_tokens = nil } -// RequestID returns the value of the "request_id" field in the mutation. -func (m *TaskMutation) RequestID() (r string, exists bool) { - v := m.request_id +// OutputTokens returns the value of the "output_tokens" field in the mutation. +func (m *TaskRecordMutation) OutputTokens() (r int64, exists bool) { + v := m.output_tokens if v == nil { return } return *v, true } -// OldRequestID returns the old "request_id" field's value of the Task entity. -// If the Task object wasn't provided to the builder, the object is fetched from the database. +// OldOutputTokens returns the old "output_tokens" field's value of the TaskRecord entity. +// If the TaskRecord object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *TaskMutation) OldRequestID(ctx context.Context) (v string, err error) { +func (m *TaskRecordMutation) OldOutputTokens(ctx context.Context) (v int64, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldRequestID is only allowed on UpdateOne operations") + return v, errors.New("OldOutputTokens is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldRequestID requires an ID field in the mutation") + return v, errors.New("OldOutputTokens requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldRequestID: %w", err) + return v, fmt.Errorf("querying old value for OldOutputTokens: %w", err) } - return oldValue.RequestID, nil + return oldValue.OutputTokens, nil } -// ClearRequestID clears the value of the "request_id" field. -func (m *TaskMutation) ClearRequestID() { - m.request_id = nil - m.clearedFields[task.FieldRequestID] = struct{}{} +// AddOutputTokens adds i to the "output_tokens" field. +func (m *TaskRecordMutation) AddOutputTokens(i int64) { + if m.addoutput_tokens != nil { + *m.addoutput_tokens += i + } else { + m.addoutput_tokens = &i + } } -// RequestIDCleared returns if the "request_id" field was cleared in this mutation. -func (m *TaskMutation) RequestIDCleared() bool { - _, ok := m.clearedFields[task.FieldRequestID] - return ok +// AddedOutputTokens returns the value that was added to the "output_tokens" field in this mutation. +func (m *TaskRecordMutation) AddedOutputTokens() (r int64, exists bool) { + v := m.addoutput_tokens + if v == nil { + return + } + return *v, true } -// ResetRequestID resets all changes to the "request_id" field. -func (m *TaskMutation) ResetRequestID() { - m.request_id = nil - delete(m.clearedFields, task.FieldRequestID) +// ResetOutputTokens resets all changes to the "output_tokens" field. +func (m *TaskRecordMutation) ResetOutputTokens() { + m.output_tokens = nil + m.addoutput_tokens = nil } -// SetModelType sets the "model_type" field. -func (m *TaskMutation) SetModelType(ct consts.ModelType) { - m.model_type = &ct +// SetCodeLines sets the "code_lines" field. +func (m *TaskRecordMutation) SetCodeLines(i int64) { + m.code_lines = &i + m.addcode_lines = nil } -// ModelType returns the value of the "model_type" field in the mutation. -func (m *TaskMutation) ModelType() (r consts.ModelType, exists bool) { - v := m.model_type +// CodeLines returns the value of the "code_lines" field in the mutation. +func (m *TaskRecordMutation) CodeLines() (r int64, exists bool) { + v := m.code_lines if v == nil { return } return *v, true } -// OldModelType returns the old "model_type" field's value of the Task entity. -// If the Task object wasn't provided to the builder, the object is fetched from the database. +// OldCodeLines returns the old "code_lines" field's value of the TaskRecord entity. +// If the TaskRecord object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *TaskMutation) OldModelType(ctx context.Context) (v consts.ModelType, err error) { +func (m *TaskRecordMutation) OldCodeLines(ctx context.Context) (v int64, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldModelType is only allowed on UpdateOne operations") + return v, errors.New("OldCodeLines is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldModelType requires an ID field in the mutation") + return v, errors.New("OldCodeLines requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldModelType: %w", err) + return v, fmt.Errorf("querying old value for OldCodeLines: %w", err) } - return oldValue.ModelType, nil -} - -// ResetModelType resets all changes to the "model_type" field. -func (m *TaskMutation) ResetModelType() { - m.model_type = nil + return oldValue.CodeLines, nil } -// SetIsAccept sets the "is_accept" field. -func (m *TaskMutation) SetIsAccept(b bool) { - m.is_accept = &b +// AddCodeLines adds i to the "code_lines" field. +func (m *TaskRecordMutation) AddCodeLines(i int64) { + if m.addcode_lines != nil { + *m.addcode_lines += i + } else { + m.addcode_lines = &i + } } -// IsAccept returns the value of the "is_accept" field in the mutation. -func (m *TaskMutation) IsAccept() (r bool, exists bool) { - v := m.is_accept +// AddedCodeLines returns the value that was added to the "code_lines" field in this mutation. +func (m *TaskRecordMutation) AddedCodeLines() (r int64, exists bool) { + v := m.addcode_lines if v == nil { return } return *v, true } -// OldIsAccept returns the old "is_accept" field's value of the Task entity. -// If the Task object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *TaskMutation) OldIsAccept(ctx context.Context) (v bool, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldIsAccept is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldIsAccept requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldIsAccept: %w", err) - } - return oldValue.IsAccept, nil -} - -// ResetIsAccept resets all changes to the "is_accept" field. -func (m *TaskMutation) ResetIsAccept() { - m.is_accept = nil +// ResetCodeLines resets all changes to the "code_lines" field. +func (m *TaskRecordMutation) ResetCodeLines() { + m.code_lines = nil + m.addcode_lines = nil } -// SetProgramLanguage sets the "program_language" field. -func (m *TaskMutation) SetProgramLanguage(s string) { - m.program_language = &s +// SetCode sets the "code" field. +func (m *TaskRecordMutation) SetCode(s string) { + m.code = &s } -// ProgramLanguage returns the value of the "program_language" field in the mutation. -func (m *TaskMutation) ProgramLanguage() (r string, exists bool) { - v := m.program_language +// Code returns the value of the "code" field in the mutation. +func (m *TaskRecordMutation) Code() (r string, exists bool) { + v := m.code if v == nil { return } return *v, true } -// OldProgramLanguage returns the old "program_language" field's value of the Task entity. -// If the Task object wasn't provided to the builder, the object is fetched from the database. +// OldCode returns the old "code" field's value of the TaskRecord entity. +// If the TaskRecord object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *TaskMutation) OldProgramLanguage(ctx context.Context) (v string, err error) { +func (m *TaskRecordMutation) OldCode(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldProgramLanguage is only allowed on UpdateOne operations") + return v, errors.New("OldCode is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldProgramLanguage requires an ID field in the mutation") + return v, errors.New("OldCode requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldProgramLanguage: %w", err) + return v, fmt.Errorf("querying old value for OldCode: %w", err) } - return oldValue.ProgramLanguage, nil + return oldValue.Code, nil } -// ClearProgramLanguage clears the value of the "program_language" field. -func (m *TaskMutation) ClearProgramLanguage() { - m.program_language = nil - m.clearedFields[task.FieldProgramLanguage] = struct{}{} +// ClearCode clears the value of the "code" field. +func (m *TaskRecordMutation) ClearCode() { + m.code = nil + m.clearedFields[taskrecord.FieldCode] = struct{}{} } -// ProgramLanguageCleared returns if the "program_language" field was cleared in this mutation. -func (m *TaskMutation) ProgramLanguageCleared() bool { - _, ok := m.clearedFields[task.FieldProgramLanguage] +// CodeCleared returns if the "code" field was cleared in this mutation. +func (m *TaskRecordMutation) CodeCleared() bool { + _, ok := m.clearedFields[taskrecord.FieldCode] return ok } -// ResetProgramLanguage resets all changes to the "program_language" field. -func (m *TaskMutation) ResetProgramLanguage() { - m.program_language = nil - delete(m.clearedFields, task.FieldProgramLanguage) +// ResetCode resets all changes to the "code" field. +func (m *TaskRecordMutation) ResetCode() { + m.code = nil + delete(m.clearedFields, taskrecord.FieldCode) } -// SetWorkMode sets the "work_mode" field. -func (m *TaskMutation) SetWorkMode(s string) { - m.work_mode = &s +// SetCreatedAt sets the "created_at" field. +func (m *TaskRecordMutation) SetCreatedAt(t time.Time) { + m.created_at = &t } -// WorkMode returns the value of the "work_mode" field in the mutation. -func (m *TaskMutation) WorkMode() (r string, exists bool) { - v := m.work_mode +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *TaskRecordMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at if v == nil { return } return *v, true } -// OldWorkMode returns the old "work_mode" field's value of the Task entity. -// If the Task object wasn't provided to the builder, the object is fetched from the database. +// OldCreatedAt returns the old "created_at" field's value of the TaskRecord entity. +// If the TaskRecord object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *TaskMutation) OldWorkMode(ctx context.Context) (v string, err error) { +func (m *TaskRecordMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldWorkMode is only allowed on UpdateOne operations") + return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldWorkMode requires an ID field in the mutation") + 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 OldWorkMode: %w", err) + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) } - return oldValue.WorkMode, nil -} - -// ClearWorkMode clears the value of the "work_mode" field. -func (m *TaskMutation) ClearWorkMode() { - m.work_mode = nil - m.clearedFields[task.FieldWorkMode] = struct{}{} -} - -// WorkModeCleared returns if the "work_mode" field was cleared in this mutation. -func (m *TaskMutation) WorkModeCleared() bool { - _, ok := m.clearedFields[task.FieldWorkMode] - return ok + return oldValue.CreatedAt, nil } -// ResetWorkMode resets all changes to the "work_mode" field. -func (m *TaskMutation) ResetWorkMode() { - m.work_mode = nil - delete(m.clearedFields, task.FieldWorkMode) +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *TaskRecordMutation) ResetCreatedAt() { + m.created_at = nil } -// SetPrompt sets the "prompt" field. -func (m *TaskMutation) SetPrompt(s string) { - m.prompt = &s +// SetUpdatedAt sets the "updated_at" field. +func (m *TaskRecordMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t } -// Prompt returns the value of the "prompt" field in the mutation. -func (m *TaskMutation) Prompt() (r string, exists bool) { - v := m.prompt +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *TaskRecordMutation) UpdatedAt() (r time.Time, exists bool) { + v := m.updated_at if v == nil { return } return *v, true } -// OldPrompt returns the old "prompt" field's value of the Task entity. -// If the Task object wasn't provided to the builder, the object is fetched from the database. +// OldUpdatedAt returns the old "updated_at" field's value of the TaskRecord entity. +// If the TaskRecord object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *TaskMutation) OldPrompt(ctx context.Context) (v string, err error) { +func (m *TaskRecordMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldPrompt is only allowed on UpdateOne operations") + return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldPrompt requires an ID field in the mutation") + 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 OldPrompt: %w", err) + return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) } - return oldValue.Prompt, nil + return oldValue.UpdatedAt, nil } -// ClearPrompt clears the value of the "prompt" field. -func (m *TaskMutation) ClearPrompt() { - m.prompt = nil - m.clearedFields[task.FieldPrompt] = struct{}{} +// ResetUpdatedAt resets all changes to the "updated_at" field. +func (m *TaskRecordMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// ClearTask clears the "task" edge to the Task entity. +func (m *TaskRecordMutation) ClearTask() { + m.clearedtask = true + m.clearedFields[taskrecord.FieldTaskID] = struct{}{} +} + +// TaskCleared reports if the "task" edge to the Task entity was cleared. +func (m *TaskRecordMutation) TaskCleared() bool { + return m.TaskIDCleared() || m.clearedtask +} + +// TaskIDs returns the "task" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// TaskID instead. It exists only for internal usage by the builders. +func (m *TaskRecordMutation) TaskIDs() (ids []uuid.UUID) { + if id := m.task; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetTask resets all changes to the "task" edge. +func (m *TaskRecordMutation) ResetTask() { + m.task = nil + m.clearedtask = false +} + +// Where appends a list predicates to the TaskRecordMutation builder. +func (m *TaskRecordMutation) Where(ps ...predicate.TaskRecord) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the TaskRecordMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *TaskRecordMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.TaskRecord, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *TaskRecordMutation) Op() Op { + return m.op } -// PromptCleared returns if the "prompt" field was cleared in this mutation. -func (m *TaskMutation) PromptCleared() bool { - _, ok := m.clearedFields[task.FieldPrompt] - return ok +// SetOp allows setting the mutation operation. +func (m *TaskRecordMutation) SetOp(op Op) { + m.op = op } -// ResetPrompt resets all changes to the "prompt" field. -func (m *TaskMutation) ResetPrompt() { - m.prompt = nil - delete(m.clearedFields, task.FieldPrompt) +// Type returns the node type of this mutation (TaskRecord). +func (m *TaskRecordMutation) Type() string { + return m.typ } -// SetCompletion sets the "completion" field. -func (m *TaskMutation) SetCompletion(s string) { - m.completion = &s +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *TaskRecordMutation) Fields() []string { + fields := make([]string, 0, 9) + if m.task != nil { + fields = append(fields, taskrecord.FieldTaskID) + } + if m.prompt != nil { + fields = append(fields, taskrecord.FieldPrompt) + } + if m.role != nil { + fields = append(fields, taskrecord.FieldRole) + } + if m.completion != nil { + fields = append(fields, taskrecord.FieldCompletion) + } + if m.output_tokens != nil { + fields = append(fields, taskrecord.FieldOutputTokens) + } + if m.code_lines != nil { + fields = append(fields, taskrecord.FieldCodeLines) + } + if m.code != nil { + fields = append(fields, taskrecord.FieldCode) + } + if m.created_at != nil { + fields = append(fields, taskrecord.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, taskrecord.FieldUpdatedAt) + } + return fields } -// Completion returns the value of the "completion" field in the mutation. -func (m *TaskMutation) Completion() (r string, exists bool) { - v := m.completion - if v == nil { - return +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *TaskRecordMutation) Field(name string) (ent.Value, bool) { + switch name { + case taskrecord.FieldTaskID: + return m.TaskID() + case taskrecord.FieldPrompt: + return m.Prompt() + case taskrecord.FieldRole: + return m.Role() + case taskrecord.FieldCompletion: + return m.Completion() + case taskrecord.FieldOutputTokens: + return m.OutputTokens() + case taskrecord.FieldCodeLines: + return m.CodeLines() + case taskrecord.FieldCode: + return m.Code() + case taskrecord.FieldCreatedAt: + return m.CreatedAt() + case taskrecord.FieldUpdatedAt: + return m.UpdatedAt() } - return *v, true + return nil, false } -// OldCompletion returns the old "completion" field's value of the Task entity. -// If the Task object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *TaskMutation) OldCompletion(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCompletion is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCompletion requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldCompletion: %w", err) +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *TaskRecordMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case taskrecord.FieldTaskID: + return m.OldTaskID(ctx) + case taskrecord.FieldPrompt: + return m.OldPrompt(ctx) + case taskrecord.FieldRole: + return m.OldRole(ctx) + case taskrecord.FieldCompletion: + return m.OldCompletion(ctx) + case taskrecord.FieldOutputTokens: + return m.OldOutputTokens(ctx) + case taskrecord.FieldCodeLines: + return m.OldCodeLines(ctx) + case taskrecord.FieldCode: + return m.OldCode(ctx) + case taskrecord.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case taskrecord.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) } - return oldValue.Completion, nil + return nil, fmt.Errorf("unknown TaskRecord field %s", name) } -// ClearCompletion clears the value of the "completion" field. -func (m *TaskMutation) ClearCompletion() { - m.completion = nil - m.clearedFields[task.FieldCompletion] = struct{}{} +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *TaskRecordMutation) SetField(name string, value ent.Value) error { + switch name { + case taskrecord.FieldTaskID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTaskID(v) + return nil + case taskrecord.FieldPrompt: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPrompt(v) + return nil + case taskrecord.FieldRole: + v, ok := value.(consts.ChatRole) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRole(v) + return nil + case taskrecord.FieldCompletion: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCompletion(v) + return nil + case taskrecord.FieldOutputTokens: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetOutputTokens(v) + return nil + case taskrecord.FieldCodeLines: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCodeLines(v) + return nil + case taskrecord.FieldCode: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCode(v) + return nil + case taskrecord.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + case taskrecord.FieldUpdatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdatedAt(v) + return nil + } + return fmt.Errorf("unknown TaskRecord field %s", name) } -// CompletionCleared returns if the "completion" field was cleared in this mutation. -func (m *TaskMutation) CompletionCleared() bool { - _, ok := m.clearedFields[task.FieldCompletion] - return ok +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *TaskRecordMutation) AddedFields() []string { + var fields []string + if m.addoutput_tokens != nil { + fields = append(fields, taskrecord.FieldOutputTokens) + } + if m.addcode_lines != nil { + fields = append(fields, taskrecord.FieldCodeLines) + } + return fields } -// ResetCompletion resets all changes to the "completion" field. -func (m *TaskMutation) ResetCompletion() { - m.completion = nil - delete(m.clearedFields, task.FieldCompletion) +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *TaskRecordMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case taskrecord.FieldOutputTokens: + return m.AddedOutputTokens() + case taskrecord.FieldCodeLines: + return m.AddedCodeLines() + } + return nil, false } -// SetCodeLines sets the "code_lines" field. -func (m *TaskMutation) SetCodeLines(i int64) { - m.code_lines = &i - m.addcode_lines = nil +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *TaskRecordMutation) AddField(name string, value ent.Value) error { + switch name { + case taskrecord.FieldOutputTokens: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddOutputTokens(v) + return nil + case taskrecord.FieldCodeLines: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddCodeLines(v) + return nil + } + return fmt.Errorf("unknown TaskRecord numeric field %s", name) } -// CodeLines returns the value of the "code_lines" field in the mutation. -func (m *TaskMutation) CodeLines() (r int64, exists bool) { - v := m.code_lines - if v == nil { - return +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *TaskRecordMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(taskrecord.FieldTaskID) { + fields = append(fields, taskrecord.FieldTaskID) } - return *v, true -} - -// OldCodeLines returns the old "code_lines" field's value of the Task entity. -// If the Task object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *TaskMutation) OldCodeLines(ctx context.Context) (v int64, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCodeLines is only allowed on UpdateOne operations") + if m.FieldCleared(taskrecord.FieldPrompt) { + fields = append(fields, taskrecord.FieldPrompt) } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCodeLines requires an ID field in the mutation") + if m.FieldCleared(taskrecord.FieldCompletion) { + fields = append(fields, taskrecord.FieldCompletion) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldCodeLines: %w", err) + if m.FieldCleared(taskrecord.FieldCode) { + fields = append(fields, taskrecord.FieldCode) } - return oldValue.CodeLines, nil + return fields } -// AddCodeLines adds i to the "code_lines" field. -func (m *TaskMutation) AddCodeLines(i int64) { - if m.addcode_lines != nil { - *m.addcode_lines += i - } else { - m.addcode_lines = &i - } +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *TaskRecordMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok } -// AddedCodeLines returns the value that was added to the "code_lines" field in this mutation. -func (m *TaskMutation) AddedCodeLines() (r int64, exists bool) { - v := m.addcode_lines - if v == nil { - return +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *TaskRecordMutation) ClearField(name string) error { + switch name { + case taskrecord.FieldTaskID: + m.ClearTaskID() + return nil + case taskrecord.FieldPrompt: + m.ClearPrompt() + return nil + case taskrecord.FieldCompletion: + m.ClearCompletion() + return nil + case taskrecord.FieldCode: + m.ClearCode() + return nil } - return *v, true + return fmt.Errorf("unknown TaskRecord nullable field %s", name) } -// ClearCodeLines clears the value of the "code_lines" field. -func (m *TaskMutation) ClearCodeLines() { - m.code_lines = nil - m.addcode_lines = nil - m.clearedFields[task.FieldCodeLines] = struct{}{} +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *TaskRecordMutation) ResetField(name string) error { + switch name { + case taskrecord.FieldTaskID: + m.ResetTaskID() + return nil + case taskrecord.FieldPrompt: + m.ResetPrompt() + return nil + case taskrecord.FieldRole: + m.ResetRole() + return nil + case taskrecord.FieldCompletion: + m.ResetCompletion() + return nil + case taskrecord.FieldOutputTokens: + m.ResetOutputTokens() + return nil + case taskrecord.FieldCodeLines: + m.ResetCodeLines() + return nil + case taskrecord.FieldCode: + m.ResetCode() + return nil + case taskrecord.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case taskrecord.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + } + return fmt.Errorf("unknown TaskRecord field %s", name) } -// CodeLinesCleared returns if the "code_lines" field was cleared in this mutation. -func (m *TaskMutation) CodeLinesCleared() bool { - _, ok := m.clearedFields[task.FieldCodeLines] - return ok +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *TaskRecordMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.task != nil { + edges = append(edges, taskrecord.EdgeTask) + } + return edges } -// ResetCodeLines resets all changes to the "code_lines" field. -func (m *TaskMutation) ResetCodeLines() { - m.code_lines = nil - m.addcode_lines = nil - delete(m.clearedFields, task.FieldCodeLines) +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *TaskRecordMutation) AddedIDs(name string) []ent.Value { + switch name { + case taskrecord.EdgeTask: + if id := m.task; id != nil { + return []ent.Value{*id} + } + } + return nil } -// SetInputTokens sets the "input_tokens" field. -func (m *TaskMutation) SetInputTokens(i int64) { - m.input_tokens = &i - m.addinput_tokens = nil +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *TaskRecordMutation) RemovedEdges() []string { + edges := make([]string, 0, 1) + return edges } -// InputTokens returns the value of the "input_tokens" field in the mutation. -func (m *TaskMutation) InputTokens() (r int64, exists bool) { - v := m.input_tokens - if v == nil { - return - } - return *v, true +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *TaskRecordMutation) RemovedIDs(name string) []ent.Value { + return nil } -// OldInputTokens returns the old "input_tokens" field's value of the Task entity. -// If the Task object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *TaskMutation) OldInputTokens(ctx context.Context) (v int64, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldInputTokens is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldInputTokens requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldInputTokens: %w", err) +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *TaskRecordMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedtask { + edges = append(edges, taskrecord.EdgeTask) } - return oldValue.InputTokens, nil + return edges } -// AddInputTokens adds i to the "input_tokens" field. -func (m *TaskMutation) AddInputTokens(i int64) { - if m.addinput_tokens != nil { - *m.addinput_tokens += i - } else { - m.addinput_tokens = &i +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *TaskRecordMutation) EdgeCleared(name string) bool { + switch name { + case taskrecord.EdgeTask: + return m.clearedtask } + return false } -// AddedInputTokens returns the value that was added to the "input_tokens" field in this mutation. -func (m *TaskMutation) AddedInputTokens() (r int64, exists bool) { - v := m.addinput_tokens - if v == nil { - return +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *TaskRecordMutation) ClearEdge(name string) error { + switch name { + case taskrecord.EdgeTask: + m.ClearTask() + return nil } - return *v, true -} - -// ClearInputTokens clears the value of the "input_tokens" field. -func (m *TaskMutation) ClearInputTokens() { - m.input_tokens = nil - m.addinput_tokens = nil - m.clearedFields[task.FieldInputTokens] = struct{}{} + return fmt.Errorf("unknown TaskRecord unique edge %s", name) } -// InputTokensCleared returns if the "input_tokens" field was cleared in this mutation. -func (m *TaskMutation) InputTokensCleared() bool { - _, ok := m.clearedFields[task.FieldInputTokens] - return ok +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. +func (m *TaskRecordMutation) ResetEdge(name string) error { + switch name { + case taskrecord.EdgeTask: + m.ResetTask() + return nil + } + return fmt.Errorf("unknown TaskRecord edge %s", name) } -// ResetInputTokens resets all changes to the "input_tokens" field. -func (m *TaskMutation) ResetInputTokens() { - m.input_tokens = nil - m.addinput_tokens = nil - delete(m.clearedFields, task.FieldInputTokens) +// UserMutation represents an operation that mutates the User nodes in the graph. +type UserMutation struct { + config + op Op + typ string + id *uuid.UUID + deleted_at *time.Time + username *string + password *string + email *string + avatar_url *string + platform *consts.UserPlatform + status *consts.UserStatus + created_at *time.Time + updated_at *time.Time + clearedFields map[string]struct{} + login_histories map[uuid.UUID]struct{} + removedlogin_histories map[uuid.UUID]struct{} + clearedlogin_histories bool + models map[uuid.UUID]struct{} + removedmodels map[uuid.UUID]struct{} + clearedmodels bool + tasks map[uuid.UUID]struct{} + removedtasks map[uuid.UUID]struct{} + clearedtasks bool + identities map[uuid.UUID]struct{} + removedidentities map[uuid.UUID]struct{} + clearedidentities bool + workspaces map[uuid.UUID]struct{} + removedworkspaces map[uuid.UUID]struct{} + clearedworkspaces bool + workspace_files map[uuid.UUID]struct{} + removedworkspace_files map[uuid.UUID]struct{} + clearedworkspace_files bool + api_keys map[uuid.UUID]struct{} + removedapi_keys map[uuid.UUID]struct{} + clearedapi_keys bool + security_scannings map[uuid.UUID]struct{} + removedsecurity_scannings map[uuid.UUID]struct{} + clearedsecurity_scannings bool + groups map[uuid.UUID]struct{} + removedgroups map[uuid.UUID]struct{} + clearedgroups bool + user_groups map[uuid.UUID]struct{} + removeduser_groups map[uuid.UUID]struct{} + cleareduser_groups bool + done bool + oldValue func(context.Context) (*User, error) + predicates []predicate.User } -// SetOutputTokens sets the "output_tokens" field. -func (m *TaskMutation) SetOutputTokens(i int64) { - m.output_tokens = &i - m.addoutput_tokens = nil -} +var _ ent.Mutation = (*UserMutation)(nil) -// OutputTokens returns the value of the "output_tokens" field in the mutation. -func (m *TaskMutation) OutputTokens() (r int64, exists bool) { - v := m.output_tokens - if v == nil { - return - } - return *v, true -} +// userOption allows management of the mutation configuration using functional options. +type userOption func(*UserMutation) -// OldOutputTokens returns the old "output_tokens" field's value of the Task entity. -// If the Task object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *TaskMutation) OldOutputTokens(ctx context.Context) (v int64, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldOutputTokens is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldOutputTokens requires an ID field in the mutation") +// newUserMutation creates new mutation for the User entity. +func newUserMutation(c config, op Op, opts ...userOption) *UserMutation { + m := &UserMutation{ + config: c, + op: op, + typ: TypeUser, + clearedFields: make(map[string]struct{}), } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldOutputTokens: %w", err) + for _, opt := range opts { + opt(m) } - return oldValue.OutputTokens, nil + return m } -// AddOutputTokens adds i to the "output_tokens" field. -func (m *TaskMutation) AddOutputTokens(i int64) { - if m.addoutput_tokens != nil { - *m.addoutput_tokens += i - } else { - m.addoutput_tokens = &i +// withUserID sets the ID field of the mutation. +func withUserID(id uuid.UUID) userOption { + return func(m *UserMutation) { + var ( + err error + once sync.Once + value *User + ) + m.oldValue = func(ctx context.Context) (*User, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().User.Get(ctx, id) + } + }) + return value, err + } + m.id = &id } } -// AddedOutputTokens returns the value that was added to the "output_tokens" field in this mutation. -func (m *TaskMutation) AddedOutputTokens() (r int64, exists bool) { - v := m.addoutput_tokens - if v == nil { - return +// withUser sets the old User of the mutation. +func withUser(node *User) userOption { + return func(m *UserMutation) { + m.oldValue = func(context.Context) (*User, error) { + return node, nil + } + m.id = &node.ID } - return *v, true -} - -// ClearOutputTokens clears the value of the "output_tokens" field. -func (m *TaskMutation) ClearOutputTokens() { - m.output_tokens = nil - m.addoutput_tokens = nil - m.clearedFields[task.FieldOutputTokens] = struct{}{} } -// OutputTokensCleared returns if the "output_tokens" field was cleared in this mutation. -func (m *TaskMutation) OutputTokensCleared() bool { - _, ok := m.clearedFields[task.FieldOutputTokens] - return ok +// 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 UserMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client } -// ResetOutputTokens resets all changes to the "output_tokens" field. -func (m *TaskMutation) ResetOutputTokens() { - m.output_tokens = nil - m.addoutput_tokens = nil - delete(m.clearedFields, task.FieldOutputTokens) +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m UserMutation) 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 } -// SetIsSuggested sets the "is_suggested" field. -func (m *TaskMutation) SetIsSuggested(b bool) { - m.is_suggested = &b +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of User entities. +func (m *UserMutation) SetID(id uuid.UUID) { + m.id = &id } -// IsSuggested returns the value of the "is_suggested" field in the mutation. -func (m *TaskMutation) IsSuggested() (r bool, exists bool) { - v := m.is_suggested - if v == nil { +// 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 *UserMutation) ID() (id uuid.UUID, exists bool) { + if m.id == nil { return } - return *v, true + return *m.id, true } -// OldIsSuggested returns the old "is_suggested" field's value of the Task entity. -// If the Task object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *TaskMutation) OldIsSuggested(ctx context.Context) (v bool, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldIsSuggested is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldIsSuggested requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldIsSuggested: %w", err) +// 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 *UserMutation) 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().User.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) } - return oldValue.IsSuggested, nil -} - -// ResetIsSuggested resets all changes to the "is_suggested" field. -func (m *TaskMutation) ResetIsSuggested() { - m.is_suggested = nil } -// SetSourceCode sets the "source_code" field. -func (m *TaskMutation) SetSourceCode(s string) { - m.source_code = &s +// SetDeletedAt sets the "deleted_at" field. +func (m *UserMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t } -// SourceCode returns the value of the "source_code" field in the mutation. -func (m *TaskMutation) SourceCode() (r string, exists bool) { - v := m.source_code +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *UserMutation) DeletedAt() (r time.Time, exists bool) { + v := m.deleted_at if v == nil { return } return *v, true } -// OldSourceCode returns the old "source_code" field's value of the Task entity. -// If the Task object wasn't provided to the builder, the object is fetched from the database. +// OldDeletedAt returns the old "deleted_at" field's value of the User entity. +// If the User object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *TaskMutation) OldSourceCode(ctx context.Context) (v string, err error) { +func (m *UserMutation) OldDeletedAt(ctx context.Context) (v time.Time, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldSourceCode is only allowed on UpdateOne operations") + return v, errors.New("OldDeletedAt is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldSourceCode requires an ID field in the mutation") + return v, errors.New("OldDeletedAt requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldSourceCode: %w", err) + return v, fmt.Errorf("querying old value for OldDeletedAt: %w", err) } - return oldValue.SourceCode, nil + return oldValue.DeletedAt, nil } -// ClearSourceCode clears the value of the "source_code" field. -func (m *TaskMutation) ClearSourceCode() { - m.source_code = nil - m.clearedFields[task.FieldSourceCode] = struct{}{} +// ClearDeletedAt clears the value of the "deleted_at" field. +func (m *UserMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[user.FieldDeletedAt] = struct{}{} } -// SourceCodeCleared returns if the "source_code" field was cleared in this mutation. -func (m *TaskMutation) SourceCodeCleared() bool { - _, ok := m.clearedFields[task.FieldSourceCode] +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *UserMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[user.FieldDeletedAt] return ok } -// ResetSourceCode resets all changes to the "source_code" field. -func (m *TaskMutation) ResetSourceCode() { - m.source_code = nil - delete(m.clearedFields, task.FieldSourceCode) +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *UserMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, user.FieldDeletedAt) } -// SetCursorPosition sets the "cursor_position" field. -func (m *TaskMutation) SetCursorPosition(value map[string]interface{}) { - m.cursor_position = &value +// SetUsername sets the "username" field. +func (m *UserMutation) SetUsername(s string) { + m.username = &s } -// CursorPosition returns the value of the "cursor_position" field in the mutation. -func (m *TaskMutation) CursorPosition() (r map[string]interface{}, exists bool) { - v := m.cursor_position +// Username returns the value of the "username" field in the mutation. +func (m *UserMutation) Username() (r string, exists bool) { + v := m.username if v == nil { return } return *v, true } -// OldCursorPosition returns the old "cursor_position" field's value of the Task entity. -// If the Task object wasn't provided to the builder, the object is fetched from the database. +// OldUsername returns the old "username" field's value of the User entity. +// If the User object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *TaskMutation) OldCursorPosition(ctx context.Context) (v map[string]interface{}, err error) { +func (m *UserMutation) OldUsername(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCursorPosition is only allowed on UpdateOne operations") + return v, errors.New("OldUsername is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCursorPosition requires an ID field in the mutation") + return v, errors.New("OldUsername requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldCursorPosition: %w", err) + return v, fmt.Errorf("querying old value for OldUsername: %w", err) } - return oldValue.CursorPosition, nil -} - -// ClearCursorPosition clears the value of the "cursor_position" field. -func (m *TaskMutation) ClearCursorPosition() { - m.cursor_position = nil - m.clearedFields[task.FieldCursorPosition] = struct{}{} + return oldValue.Username, nil } -// CursorPositionCleared returns if the "cursor_position" field was cleared in this mutation. -func (m *TaskMutation) CursorPositionCleared() bool { - _, ok := m.clearedFields[task.FieldCursorPosition] - return ok +// ClearUsername clears the value of the "username" field. +func (m *UserMutation) ClearUsername() { + m.username = nil + m.clearedFields[user.FieldUsername] = struct{}{} } -// ResetCursorPosition resets all changes to the "cursor_position" field. -func (m *TaskMutation) ResetCursorPosition() { - m.cursor_position = nil - delete(m.clearedFields, task.FieldCursorPosition) +// UsernameCleared returns if the "username" field was cleared in this mutation. +func (m *UserMutation) UsernameCleared() bool { + _, ok := m.clearedFields[user.FieldUsername] + return ok } -// SetUserInput sets the "user_input" field. -func (m *TaskMutation) SetUserInput(s string) { - m.user_input = &s +// ResetUsername resets all changes to the "username" field. +func (m *UserMutation) ResetUsername() { + m.username = nil + delete(m.clearedFields, user.FieldUsername) } -// UserInput returns the value of the "user_input" field in the mutation. -func (m *TaskMutation) UserInput() (r string, exists bool) { - v := m.user_input +// SetPassword sets the "password" field. +func (m *UserMutation) SetPassword(s string) { + m.password = &s +} + +// Password returns the value of the "password" field in the mutation. +func (m *UserMutation) Password() (r string, exists bool) { + v := m.password if v == nil { return } return *v, true } -// OldUserInput returns the old "user_input" field's value of the Task entity. -// If the Task object wasn't provided to the builder, the object is fetched from the database. +// OldPassword returns the old "password" field's value of the User entity. +// If the User object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *TaskMutation) OldUserInput(ctx context.Context) (v string, err error) { +func (m *UserMutation) OldPassword(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldUserInput is only allowed on UpdateOne operations") + return v, errors.New("OldPassword is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldUserInput requires an ID field in the mutation") + return v, errors.New("OldPassword requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldUserInput: %w", err) + return v, fmt.Errorf("querying old value for OldPassword: %w", err) } - return oldValue.UserInput, nil + return oldValue.Password, nil } -// ClearUserInput clears the value of the "user_input" field. -func (m *TaskMutation) ClearUserInput() { - m.user_input = nil - m.clearedFields[task.FieldUserInput] = struct{}{} +// ClearPassword clears the value of the "password" field. +func (m *UserMutation) ClearPassword() { + m.password = nil + m.clearedFields[user.FieldPassword] = struct{}{} } -// UserInputCleared returns if the "user_input" field was cleared in this mutation. -func (m *TaskMutation) UserInputCleared() bool { - _, ok := m.clearedFields[task.FieldUserInput] +// PasswordCleared returns if the "password" field was cleared in this mutation. +func (m *UserMutation) PasswordCleared() bool { + _, ok := m.clearedFields[user.FieldPassword] return ok } -// ResetUserInput resets all changes to the "user_input" field. -func (m *TaskMutation) ResetUserInput() { - m.user_input = nil - delete(m.clearedFields, task.FieldUserInput) +// ResetPassword resets all changes to the "password" field. +func (m *UserMutation) ResetPassword() { + m.password = nil + delete(m.clearedFields, user.FieldPassword) } -// SetCreatedAt sets the "created_at" field. -func (m *TaskMutation) SetCreatedAt(t time.Time) { - m.created_at = &t +// SetEmail sets the "email" field. +func (m *UserMutation) SetEmail(s string) { + m.email = &s } -// CreatedAt returns the value of the "created_at" field in the mutation. -func (m *TaskMutation) CreatedAt() (r time.Time, exists bool) { - v := m.created_at +// Email returns the value of the "email" field in the mutation. +func (m *UserMutation) Email() (r string, exists bool) { + v := m.email if v == nil { return } return *v, true } -// OldCreatedAt returns the old "created_at" field's value of the Task entity. -// If the Task object wasn't provided to the builder, the object is fetched from the database. +// OldEmail returns the old "email" field's value of the User entity. +// If the User object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *TaskMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { +func (m *UserMutation) OldEmail(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") + return v, errors.New("OldEmail 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") + return v, errors.New("OldEmail 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 v, fmt.Errorf("querying old value for OldEmail: %w", err) } - return oldValue.CreatedAt, nil + return oldValue.Email, nil } -// ResetCreatedAt resets all changes to the "created_at" field. -func (m *TaskMutation) ResetCreatedAt() { - m.created_at = nil +// ClearEmail clears the value of the "email" field. +func (m *UserMutation) ClearEmail() { + m.email = nil + m.clearedFields[user.FieldEmail] = struct{}{} } -// SetUpdatedAt sets the "updated_at" field. -func (m *TaskMutation) SetUpdatedAt(t time.Time) { - m.updated_at = &t +// EmailCleared returns if the "email" field was cleared in this mutation. +func (m *UserMutation) EmailCleared() bool { + _, ok := m.clearedFields[user.FieldEmail] + return ok } -// UpdatedAt returns the value of the "updated_at" field in the mutation. -func (m *TaskMutation) UpdatedAt() (r time.Time, exists bool) { - v := m.updated_at +// ResetEmail resets all changes to the "email" field. +func (m *UserMutation) ResetEmail() { + m.email = nil + delete(m.clearedFields, user.FieldEmail) +} + +// SetAvatarURL sets the "avatar_url" field. +func (m *UserMutation) SetAvatarURL(s string) { + m.avatar_url = &s +} + +// AvatarURL returns the value of the "avatar_url" field in the mutation. +func (m *UserMutation) AvatarURL() (r string, exists bool) { + v := m.avatar_url if v == nil { return } return *v, true } -// OldUpdatedAt returns the old "updated_at" field's value of the Task entity. -// If the Task object wasn't provided to the builder, the object is fetched from the database. +// OldAvatarURL returns the old "avatar_url" field's value of the User entity. +// If the User object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *TaskMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { +func (m *UserMutation) OldAvatarURL(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") + return v, errors.New("OldAvatarURL 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") + return v, errors.New("OldAvatarURL 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 v, fmt.Errorf("querying old value for OldAvatarURL: %w", err) } - return oldValue.UpdatedAt, nil + return oldValue.AvatarURL, nil } -// ResetUpdatedAt resets all changes to the "updated_at" field. -func (m *TaskMutation) ResetUpdatedAt() { - m.updated_at = nil +// ClearAvatarURL clears the value of the "avatar_url" field. +func (m *UserMutation) ClearAvatarURL() { + m.avatar_url = nil + m.clearedFields[user.FieldAvatarURL] = struct{}{} } -// AddTaskRecordIDs adds the "task_records" edge to the TaskRecord entity by ids. -func (m *TaskMutation) AddTaskRecordIDs(ids ...uuid.UUID) { - if m.task_records == nil { - m.task_records = make(map[uuid.UUID]struct{}) - } - for i := range ids { - m.task_records[ids[i]] = struct{}{} - } +// AvatarURLCleared returns if the "avatar_url" field was cleared in this mutation. +func (m *UserMutation) AvatarURLCleared() bool { + _, ok := m.clearedFields[user.FieldAvatarURL] + return ok } -// ClearTaskRecords clears the "task_records" edge to the TaskRecord entity. -func (m *TaskMutation) ClearTaskRecords() { - m.clearedtask_records = true +// ResetAvatarURL resets all changes to the "avatar_url" field. +func (m *UserMutation) ResetAvatarURL() { + m.avatar_url = nil + delete(m.clearedFields, user.FieldAvatarURL) } -// TaskRecordsCleared reports if the "task_records" edge to the TaskRecord entity was cleared. -func (m *TaskMutation) TaskRecordsCleared() bool { - return m.clearedtask_records +// SetPlatform sets the "platform" field. +func (m *UserMutation) SetPlatform(cp consts.UserPlatform) { + m.platform = &cp } -// RemoveTaskRecordIDs removes the "task_records" edge to the TaskRecord entity by IDs. -func (m *TaskMutation) RemoveTaskRecordIDs(ids ...uuid.UUID) { - if m.removedtask_records == nil { - m.removedtask_records = make(map[uuid.UUID]struct{}) - } - for i := range ids { - delete(m.task_records, ids[i]) - m.removedtask_records[ids[i]] = struct{}{} +// Platform returns the value of the "platform" field in the mutation. +func (m *UserMutation) Platform() (r consts.UserPlatform, exists bool) { + v := m.platform + if v == nil { + return } + return *v, true } -// RemovedTaskRecords returns the removed IDs of the "task_records" edge to the TaskRecord entity. -func (m *TaskMutation) RemovedTaskRecordsIDs() (ids []uuid.UUID) { - for id := range m.removedtask_records { - ids = append(ids, id) +// OldPlatform returns the old "platform" field's value of the User entity. +// If the User 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 *UserMutation) OldPlatform(ctx context.Context) (v consts.UserPlatform, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPlatform is only allowed on UpdateOne operations") } - return -} - -// TaskRecordsIDs returns the "task_records" edge IDs in the mutation. -func (m *TaskMutation) TaskRecordsIDs() (ids []uuid.UUID) { - for id := range m.task_records { - ids = append(ids, id) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPlatform requires an ID field in the mutation") } - return -} - -// ResetTaskRecords resets all changes to the "task_records" edge. -func (m *TaskMutation) ResetTaskRecords() { - m.task_records = nil - m.clearedtask_records = false - m.removedtask_records = nil -} - -// ClearUser clears the "user" edge to the User entity. -func (m *TaskMutation) ClearUser() { - m.cleareduser = true - m.clearedFields[task.FieldUserID] = struct{}{} -} - -// UserCleared reports if the "user" edge to the User entity was cleared. -func (m *TaskMutation) UserCleared() bool { - return m.UserIDCleared() || m.cleareduser -} - -// UserIDs returns the "user" edge IDs in the mutation. -// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// UserID instead. It exists only for internal usage by the builders. -func (m *TaskMutation) UserIDs() (ids []uuid.UUID) { - if id := m.user; id != nil { - ids = append(ids, *id) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPlatform: %w", err) } - return + return oldValue.Platform, nil } -// ResetUser resets all changes to the "user" edge. -func (m *TaskMutation) ResetUser() { - m.user = nil - m.cleareduser = false +// ResetPlatform resets all changes to the "platform" field. +func (m *UserMutation) ResetPlatform() { + m.platform = nil } -// ClearModel clears the "model" edge to the Model entity. -func (m *TaskMutation) ClearModel() { - m.clearedmodel = true - m.clearedFields[task.FieldModelID] = struct{}{} +// SetStatus sets the "status" field. +func (m *UserMutation) SetStatus(cs consts.UserStatus) { + m.status = &cs } -// ModelCleared reports if the "model" edge to the Model entity was cleared. -func (m *TaskMutation) ModelCleared() bool { - return m.ModelIDCleared() || m.clearedmodel +// Status returns the value of the "status" field in the mutation. +func (m *UserMutation) Status() (r consts.UserStatus, exists bool) { + v := m.status + if v == nil { + return + } + return *v, true } -// ModelIDs returns the "model" edge IDs in the mutation. -// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// ModelID instead. It exists only for internal usage by the builders. -func (m *TaskMutation) ModelIDs() (ids []uuid.UUID) { - if id := m.model; id != nil { - ids = append(ids, *id) +// OldStatus returns the old "status" field's value of the User entity. +// If the User 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 *UserMutation) OldStatus(ctx context.Context) (v consts.UserStatus, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldStatus is only allowed on UpdateOne operations") } - return + 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 } -// ResetModel resets all changes to the "model" edge. -func (m *TaskMutation) ResetModel() { - m.model = nil - m.clearedmodel = false +// ResetStatus resets all changes to the "status" field. +func (m *UserMutation) ResetStatus() { + m.status = nil } -// Where appends a list predicates to the TaskMutation builder. -func (m *TaskMutation) Where(ps ...predicate.Task) { - m.predicates = append(m.predicates, ps...) +// SetCreatedAt sets the "created_at" field. +func (m *UserMutation) SetCreatedAt(t time.Time) { + m.created_at = &t } -// WhereP appends storage-level predicates to the TaskMutation builder. Using this method, -// users can use type-assertion to append predicates that do not depend on any generated package. -func (m *TaskMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.Task, len(ps)) - for i := range ps { - p[i] = ps[i] +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *UserMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at + if v == nil { + return } - m.Where(p...) + return *v, true } -// Op returns the operation name. -func (m *TaskMutation) Op() Op { - return m.op +// OldCreatedAt returns the old "created_at" field's value of the User entity. +// If the User 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 *UserMutation) 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 } -// SetOp allows setting the mutation operation. -func (m *TaskMutation) SetOp(op Op) { - m.op = op +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *UserMutation) ResetCreatedAt() { + m.created_at = nil } -// Type returns the node type of this mutation (Task). -func (m *TaskMutation) Type() string { - return m.typ +// SetUpdatedAt sets the "updated_at" field. +func (m *UserMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t } -// Fields returns all fields that were changed during this mutation. Note that in -// order to get all numeric fields that were incremented/decremented, call -// AddedFields(). -func (m *TaskMutation) Fields() []string { - fields := make([]string, 0, 19) - if m.task_id != nil { - fields = append(fields, task.FieldTaskID) - } - if m.user != nil { - fields = append(fields, task.FieldUserID) - } - if m.model != nil { - fields = append(fields, task.FieldModelID) - } - if m.request_id != nil { - fields = append(fields, task.FieldRequestID) - } - if m.model_type != nil { - fields = append(fields, task.FieldModelType) - } - if m.is_accept != nil { - fields = append(fields, task.FieldIsAccept) - } - if m.program_language != nil { - fields = append(fields, task.FieldProgramLanguage) - } - if m.work_mode != nil { - fields = append(fields, task.FieldWorkMode) - } - if m.prompt != nil { - fields = append(fields, task.FieldPrompt) - } - if m.completion != nil { - fields = append(fields, task.FieldCompletion) - } - if m.code_lines != nil { - fields = append(fields, task.FieldCodeLines) - } - if m.input_tokens != nil { - fields = append(fields, task.FieldInputTokens) - } - if m.output_tokens != nil { - fields = append(fields, task.FieldOutputTokens) - } - if m.is_suggested != nil { - fields = append(fields, task.FieldIsSuggested) +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *UserMutation) UpdatedAt() (r time.Time, exists bool) { + v := m.updated_at + if v == nil { + return } - if m.source_code != nil { - fields = append(fields, task.FieldSourceCode) + return *v, true +} + +// OldUpdatedAt returns the old "updated_at" field's value of the User entity. +// If the User 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 *UserMutation) 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.cursor_position != nil { - fields = append(fields, task.FieldCursorPosition) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUpdatedAt requires an ID field in the mutation") } - if m.user_input != nil { - fields = append(fields, task.FieldUserInput) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) } - if m.created_at != nil { - fields = append(fields, task.FieldCreatedAt) + return oldValue.UpdatedAt, nil +} + +// ResetUpdatedAt resets all changes to the "updated_at" field. +func (m *UserMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// AddLoginHistoryIDs adds the "login_histories" edge to the UserLoginHistory entity by ids. +func (m *UserMutation) AddLoginHistoryIDs(ids ...uuid.UUID) { + if m.login_histories == nil { + m.login_histories = make(map[uuid.UUID]struct{}) } - if m.updated_at != nil { - fields = append(fields, task.FieldUpdatedAt) + for i := range ids { + m.login_histories[ids[i]] = struct{}{} } - return fields } -// Field returns the value of a field with the given name. The second boolean -// return value indicates that this field was not set, or was not defined in the -// schema. -func (m *TaskMutation) Field(name string) (ent.Value, bool) { - switch name { - case task.FieldTaskID: - return m.TaskID() - case task.FieldUserID: - return m.UserID() - case task.FieldModelID: - return m.ModelID() - case task.FieldRequestID: - return m.RequestID() - case task.FieldModelType: - return m.ModelType() - case task.FieldIsAccept: - return m.IsAccept() - case task.FieldProgramLanguage: - return m.ProgramLanguage() - case task.FieldWorkMode: - return m.WorkMode() - case task.FieldPrompt: - return m.Prompt() - case task.FieldCompletion: - return m.Completion() - case task.FieldCodeLines: - return m.CodeLines() - case task.FieldInputTokens: - return m.InputTokens() - case task.FieldOutputTokens: - return m.OutputTokens() - case task.FieldIsSuggested: - return m.IsSuggested() - case task.FieldSourceCode: - return m.SourceCode() - case task.FieldCursorPosition: - return m.CursorPosition() - case task.FieldUserInput: - return m.UserInput() - case task.FieldCreatedAt: - return m.CreatedAt() - case task.FieldUpdatedAt: - return m.UpdatedAt() - } - return nil, false +// ClearLoginHistories clears the "login_histories" edge to the UserLoginHistory entity. +func (m *UserMutation) ClearLoginHistories() { + m.clearedlogin_histories = true } -// OldField returns the old value of the field from the database. An error is -// returned if the mutation operation is not UpdateOne, or the query to the -// database failed. -func (m *TaskMutation) OldField(ctx context.Context, name string) (ent.Value, error) { - switch name { - case task.FieldTaskID: - return m.OldTaskID(ctx) - case task.FieldUserID: - return m.OldUserID(ctx) - case task.FieldModelID: - return m.OldModelID(ctx) - case task.FieldRequestID: - return m.OldRequestID(ctx) - case task.FieldModelType: - return m.OldModelType(ctx) - case task.FieldIsAccept: - return m.OldIsAccept(ctx) - case task.FieldProgramLanguage: - return m.OldProgramLanguage(ctx) - case task.FieldWorkMode: - return m.OldWorkMode(ctx) - case task.FieldPrompt: - return m.OldPrompt(ctx) - case task.FieldCompletion: - return m.OldCompletion(ctx) - case task.FieldCodeLines: - return m.OldCodeLines(ctx) - case task.FieldInputTokens: - return m.OldInputTokens(ctx) - case task.FieldOutputTokens: - return m.OldOutputTokens(ctx) - case task.FieldIsSuggested: - return m.OldIsSuggested(ctx) - case task.FieldSourceCode: - return m.OldSourceCode(ctx) - case task.FieldCursorPosition: - return m.OldCursorPosition(ctx) - case task.FieldUserInput: - return m.OldUserInput(ctx) - case task.FieldCreatedAt: - return m.OldCreatedAt(ctx) - case task.FieldUpdatedAt: - return m.OldUpdatedAt(ctx) +// LoginHistoriesCleared reports if the "login_histories" edge to the UserLoginHistory entity was cleared. +func (m *UserMutation) LoginHistoriesCleared() bool { + return m.clearedlogin_histories +} + +// RemoveLoginHistoryIDs removes the "login_histories" edge to the UserLoginHistory entity by IDs. +func (m *UserMutation) RemoveLoginHistoryIDs(ids ...uuid.UUID) { + if m.removedlogin_histories == nil { + m.removedlogin_histories = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.login_histories, ids[i]) + m.removedlogin_histories[ids[i]] = struct{}{} } - return nil, fmt.Errorf("unknown Task field %s", name) } -// SetField sets the value of a field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *TaskMutation) SetField(name string, value ent.Value) error { - switch name { - case task.FieldTaskID: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetTaskID(v) - return nil - case task.FieldUserID: - v, ok := value.(uuid.UUID) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetUserID(v) - return nil - case task.FieldModelID: - v, ok := value.(uuid.UUID) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetModelID(v) - return nil - case task.FieldRequestID: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetRequestID(v) - return nil - case task.FieldModelType: - v, ok := value.(consts.ModelType) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetModelType(v) - return nil - case task.FieldIsAccept: - v, ok := value.(bool) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetIsAccept(v) - return nil - case task.FieldProgramLanguage: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetProgramLanguage(v) - return nil - case task.FieldWorkMode: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetWorkMode(v) - return nil - case task.FieldPrompt: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetPrompt(v) - return nil - case task.FieldCompletion: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetCompletion(v) - return nil - case task.FieldCodeLines: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetCodeLines(v) - return nil - case task.FieldInputTokens: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetInputTokens(v) - return nil - case task.FieldOutputTokens: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetOutputTokens(v) - return nil - case task.FieldIsSuggested: - v, ok := value.(bool) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetIsSuggested(v) - return nil - case task.FieldSourceCode: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetSourceCode(v) - return nil - case task.FieldCursorPosition: - v, ok := value.(map[string]interface{}) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetCursorPosition(v) - return nil - case task.FieldUserInput: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetUserInput(v) - return nil - case task.FieldCreatedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetCreatedAt(v) - return nil - case task.FieldUpdatedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetUpdatedAt(v) - return nil +// RemovedLoginHistories returns the removed IDs of the "login_histories" edge to the UserLoginHistory entity. +func (m *UserMutation) RemovedLoginHistoriesIDs() (ids []uuid.UUID) { + for id := range m.removedlogin_histories { + ids = append(ids, id) } - return fmt.Errorf("unknown Task field %s", name) + return } -// AddedFields returns all numeric fields that were incremented/decremented during -// this mutation. -func (m *TaskMutation) AddedFields() []string { - var fields []string - if m.addcode_lines != nil { - fields = append(fields, task.FieldCodeLines) +// LoginHistoriesIDs returns the "login_histories" edge IDs in the mutation. +func (m *UserMutation) LoginHistoriesIDs() (ids []uuid.UUID) { + for id := range m.login_histories { + ids = append(ids, id) } - if m.addinput_tokens != nil { - fields = append(fields, task.FieldInputTokens) + return +} + +// ResetLoginHistories resets all changes to the "login_histories" edge. +func (m *UserMutation) ResetLoginHistories() { + m.login_histories = nil + m.clearedlogin_histories = false + m.removedlogin_histories = nil +} + +// AddModelIDs adds the "models" edge to the Model entity by ids. +func (m *UserMutation) AddModelIDs(ids ...uuid.UUID) { + if m.models == nil { + m.models = make(map[uuid.UUID]struct{}) } - if m.addoutput_tokens != nil { - fields = append(fields, task.FieldOutputTokens) + for i := range ids { + m.models[ids[i]] = struct{}{} } - return fields } -// AddedField returns the numeric value that was incremented/decremented on a field -// with the given name. The second boolean return value indicates that this field -// was not set, or was not defined in the schema. -func (m *TaskMutation) AddedField(name string) (ent.Value, bool) { - switch name { - case task.FieldCodeLines: - return m.AddedCodeLines() - case task.FieldInputTokens: - return m.AddedInputTokens() - case task.FieldOutputTokens: - return m.AddedOutputTokens() +// ClearModels clears the "models" edge to the Model entity. +func (m *UserMutation) ClearModels() { + m.clearedmodels = true +} + +// ModelsCleared reports if the "models" edge to the Model entity was cleared. +func (m *UserMutation) ModelsCleared() bool { + return m.clearedmodels +} + +// RemoveModelIDs removes the "models" edge to the Model entity by IDs. +func (m *UserMutation) RemoveModelIDs(ids ...uuid.UUID) { + if m.removedmodels == nil { + m.removedmodels = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.models, ids[i]) + m.removedmodels[ids[i]] = struct{}{} } - return nil, false } -// AddField adds the value to the field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *TaskMutation) AddField(name string, value ent.Value) error { - switch name { - case task.FieldCodeLines: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddCodeLines(v) - return nil - case task.FieldInputTokens: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddInputTokens(v) - return nil - case task.FieldOutputTokens: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddOutputTokens(v) - return nil +// RemovedModels returns the removed IDs of the "models" edge to the Model entity. +func (m *UserMutation) RemovedModelsIDs() (ids []uuid.UUID) { + for id := range m.removedmodels { + ids = append(ids, id) } - return fmt.Errorf("unknown Task numeric field %s", name) + return +} + +// ModelsIDs returns the "models" edge IDs in the mutation. +func (m *UserMutation) ModelsIDs() (ids []uuid.UUID) { + for id := range m.models { + ids = append(ids, id) + } + return +} + +// ResetModels resets all changes to the "models" edge. +func (m *UserMutation) ResetModels() { + m.models = nil + m.clearedmodels = false + m.removedmodels = nil } -// ClearedFields returns all nullable fields that were cleared during this -// mutation. -func (m *TaskMutation) ClearedFields() []string { - var fields []string - if m.FieldCleared(task.FieldUserID) { - fields = append(fields, task.FieldUserID) - } - if m.FieldCleared(task.FieldModelID) { - fields = append(fields, task.FieldModelID) +// AddTaskIDs adds the "tasks" edge to the Task entity by ids. +func (m *UserMutation) AddTaskIDs(ids ...uuid.UUID) { + if m.tasks == nil { + m.tasks = make(map[uuid.UUID]struct{}) } - if m.FieldCleared(task.FieldRequestID) { - fields = append(fields, task.FieldRequestID) + for i := range ids { + m.tasks[ids[i]] = struct{}{} } - if m.FieldCleared(task.FieldProgramLanguage) { - fields = append(fields, task.FieldProgramLanguage) +} + +// ClearTasks clears the "tasks" edge to the Task entity. +func (m *UserMutation) ClearTasks() { + m.clearedtasks = true +} + +// TasksCleared reports if the "tasks" edge to the Task entity was cleared. +func (m *UserMutation) TasksCleared() bool { + return m.clearedtasks +} + +// RemoveTaskIDs removes the "tasks" edge to the Task entity by IDs. +func (m *UserMutation) RemoveTaskIDs(ids ...uuid.UUID) { + if m.removedtasks == nil { + m.removedtasks = make(map[uuid.UUID]struct{}) } - if m.FieldCleared(task.FieldWorkMode) { - fields = append(fields, task.FieldWorkMode) + for i := range ids { + delete(m.tasks, ids[i]) + m.removedtasks[ids[i]] = struct{}{} } - if m.FieldCleared(task.FieldPrompt) { - fields = append(fields, task.FieldPrompt) +} + +// RemovedTasks returns the removed IDs of the "tasks" edge to the Task entity. +func (m *UserMutation) RemovedTasksIDs() (ids []uuid.UUID) { + for id := range m.removedtasks { + ids = append(ids, id) } - if m.FieldCleared(task.FieldCompletion) { - fields = append(fields, task.FieldCompletion) + return +} + +// TasksIDs returns the "tasks" edge IDs in the mutation. +func (m *UserMutation) TasksIDs() (ids []uuid.UUID) { + for id := range m.tasks { + ids = append(ids, id) } - if m.FieldCleared(task.FieldCodeLines) { - fields = append(fields, task.FieldCodeLines) + return +} + +// ResetTasks resets all changes to the "tasks" edge. +func (m *UserMutation) ResetTasks() { + m.tasks = nil + m.clearedtasks = false + m.removedtasks = nil +} + +// AddIdentityIDs adds the "identities" edge to the UserIdentity entity by ids. +func (m *UserMutation) AddIdentityIDs(ids ...uuid.UUID) { + if m.identities == nil { + m.identities = make(map[uuid.UUID]struct{}) } - if m.FieldCleared(task.FieldInputTokens) { - fields = append(fields, task.FieldInputTokens) + for i := range ids { + m.identities[ids[i]] = struct{}{} } - if m.FieldCleared(task.FieldOutputTokens) { - fields = append(fields, task.FieldOutputTokens) +} + +// ClearIdentities clears the "identities" edge to the UserIdentity entity. +func (m *UserMutation) ClearIdentities() { + m.clearedidentities = true +} + +// IdentitiesCleared reports if the "identities" edge to the UserIdentity entity was cleared. +func (m *UserMutation) IdentitiesCleared() bool { + return m.clearedidentities +} + +// RemoveIdentityIDs removes the "identities" edge to the UserIdentity entity by IDs. +func (m *UserMutation) RemoveIdentityIDs(ids ...uuid.UUID) { + if m.removedidentities == nil { + m.removedidentities = make(map[uuid.UUID]struct{}) } - if m.FieldCleared(task.FieldSourceCode) { - fields = append(fields, task.FieldSourceCode) + for i := range ids { + delete(m.identities, ids[i]) + m.removedidentities[ids[i]] = struct{}{} } - if m.FieldCleared(task.FieldCursorPosition) { - fields = append(fields, task.FieldCursorPosition) +} + +// RemovedIdentities returns the removed IDs of the "identities" edge to the UserIdentity entity. +func (m *UserMutation) RemovedIdentitiesIDs() (ids []uuid.UUID) { + for id := range m.removedidentities { + ids = append(ids, id) } - if m.FieldCleared(task.FieldUserInput) { - fields = append(fields, task.FieldUserInput) + return +} + +// IdentitiesIDs returns the "identities" edge IDs in the mutation. +func (m *UserMutation) IdentitiesIDs() (ids []uuid.UUID) { + for id := range m.identities { + ids = append(ids, id) } - return fields + return } -// FieldCleared returns a boolean indicating if a field with the given name was -// cleared in this mutation. -func (m *TaskMutation) FieldCleared(name string) bool { - _, ok := m.clearedFields[name] - return ok +// ResetIdentities resets all changes to the "identities" edge. +func (m *UserMutation) ResetIdentities() { + m.identities = nil + m.clearedidentities = false + m.removedidentities = nil } -// ClearField clears the value of the field with the given name. It returns an -// error if the field is not defined in the schema. -func (m *TaskMutation) ClearField(name string) error { - switch name { - case task.FieldUserID: - m.ClearUserID() - return nil - case task.FieldModelID: - m.ClearModelID() - return nil - case task.FieldRequestID: - m.ClearRequestID() - return nil - case task.FieldProgramLanguage: - m.ClearProgramLanguage() - return nil - case task.FieldWorkMode: - m.ClearWorkMode() - return nil - case task.FieldPrompt: - m.ClearPrompt() - return nil - case task.FieldCompletion: - m.ClearCompletion() - return nil - case task.FieldCodeLines: - m.ClearCodeLines() - return nil - case task.FieldInputTokens: - m.ClearInputTokens() - return nil - case task.FieldOutputTokens: - m.ClearOutputTokens() - return nil - case task.FieldSourceCode: - m.ClearSourceCode() - return nil - case task.FieldCursorPosition: - m.ClearCursorPosition() - return nil - case task.FieldUserInput: - m.ClearUserInput() - return nil +// AddWorkspaceIDs adds the "workspaces" edge to the Workspace entity by ids. +func (m *UserMutation) AddWorkspaceIDs(ids ...uuid.UUID) { + if m.workspaces == nil { + m.workspaces = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.workspaces[ids[i]] = struct{}{} } - return fmt.Errorf("unknown Task nullable field %s", name) } -// ResetField resets all changes in the mutation for the field with the given name. -// It returns an error if the field is not defined in the schema. -func (m *TaskMutation) ResetField(name string) error { - switch name { - case task.FieldTaskID: - m.ResetTaskID() - return nil - case task.FieldUserID: - m.ResetUserID() - return nil - case task.FieldModelID: - m.ResetModelID() - return nil - case task.FieldRequestID: - m.ResetRequestID() - return nil - case task.FieldModelType: - m.ResetModelType() - return nil - case task.FieldIsAccept: - m.ResetIsAccept() - return nil - case task.FieldProgramLanguage: - m.ResetProgramLanguage() - return nil - case task.FieldWorkMode: - m.ResetWorkMode() - return nil - case task.FieldPrompt: - m.ResetPrompt() - return nil - case task.FieldCompletion: - m.ResetCompletion() - return nil - case task.FieldCodeLines: - m.ResetCodeLines() - return nil - case task.FieldInputTokens: - m.ResetInputTokens() - return nil - case task.FieldOutputTokens: - m.ResetOutputTokens() - return nil - case task.FieldIsSuggested: - m.ResetIsSuggested() - return nil - case task.FieldSourceCode: - m.ResetSourceCode() - return nil - case task.FieldCursorPosition: - m.ResetCursorPosition() - return nil - case task.FieldUserInput: - m.ResetUserInput() - return nil - case task.FieldCreatedAt: - m.ResetCreatedAt() - return nil - case task.FieldUpdatedAt: - m.ResetUpdatedAt() - return nil +// ClearWorkspaces clears the "workspaces" edge to the Workspace entity. +func (m *UserMutation) ClearWorkspaces() { + m.clearedworkspaces = true +} + +// WorkspacesCleared reports if the "workspaces" edge to the Workspace entity was cleared. +func (m *UserMutation) WorkspacesCleared() bool { + return m.clearedworkspaces +} + +// RemoveWorkspaceIDs removes the "workspaces" edge to the Workspace entity by IDs. +func (m *UserMutation) RemoveWorkspaceIDs(ids ...uuid.UUID) { + if m.removedworkspaces == nil { + m.removedworkspaces = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.workspaces, ids[i]) + m.removedworkspaces[ids[i]] = struct{}{} } - return fmt.Errorf("unknown Task field %s", name) } -// AddedEdges returns all edge names that were set/added in this mutation. -func (m *TaskMutation) AddedEdges() []string { - edges := make([]string, 0, 3) - if m.task_records != nil { - edges = append(edges, task.EdgeTaskRecords) - } - if m.user != nil { - edges = append(edges, task.EdgeUser) +// RemovedWorkspaces returns the removed IDs of the "workspaces" edge to the Workspace entity. +func (m *UserMutation) RemovedWorkspacesIDs() (ids []uuid.UUID) { + for id := range m.removedworkspaces { + ids = append(ids, id) } - if m.model != nil { - edges = append(edges, task.EdgeModel) + return +} + +// WorkspacesIDs returns the "workspaces" edge IDs in the mutation. +func (m *UserMutation) WorkspacesIDs() (ids []uuid.UUID) { + for id := range m.workspaces { + ids = append(ids, id) } - return edges + return } -// AddedIDs returns all IDs (to other nodes) that were added for the given edge -// name in this mutation. -func (m *TaskMutation) AddedIDs(name string) []ent.Value { - switch name { - case task.EdgeTaskRecords: - ids := make([]ent.Value, 0, len(m.task_records)) - for id := range m.task_records { - ids = append(ids, id) - } - return ids - case task.EdgeUser: - if id := m.user; id != nil { - return []ent.Value{*id} - } - case task.EdgeModel: - if id := m.model; id != nil { - return []ent.Value{*id} - } +// ResetWorkspaces resets all changes to the "workspaces" edge. +func (m *UserMutation) ResetWorkspaces() { + m.workspaces = nil + m.clearedworkspaces = false + m.removedworkspaces = nil +} + +// AddWorkspaceFileIDs adds the "workspace_files" edge to the WorkspaceFile entity by ids. +func (m *UserMutation) AddWorkspaceFileIDs(ids ...uuid.UUID) { + if m.workspace_files == nil { + m.workspace_files = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.workspace_files[ids[i]] = struct{}{} } - return nil } -// RemovedEdges returns all edge names that were removed in this mutation. -func (m *TaskMutation) RemovedEdges() []string { - edges := make([]string, 0, 3) - if m.removedtask_records != nil { - edges = append(edges, task.EdgeTaskRecords) +// ClearWorkspaceFiles clears the "workspace_files" edge to the WorkspaceFile entity. +func (m *UserMutation) ClearWorkspaceFiles() { + m.clearedworkspace_files = true +} + +// WorkspaceFilesCleared reports if the "workspace_files" edge to the WorkspaceFile entity was cleared. +func (m *UserMutation) WorkspaceFilesCleared() bool { + return m.clearedworkspace_files +} + +// RemoveWorkspaceFileIDs removes the "workspace_files" edge to the WorkspaceFile entity by IDs. +func (m *UserMutation) RemoveWorkspaceFileIDs(ids ...uuid.UUID) { + if m.removedworkspace_files == nil { + m.removedworkspace_files = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.workspace_files, ids[i]) + m.removedworkspace_files[ids[i]] = struct{}{} } - return edges } -// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with -// the given name in this mutation. -func (m *TaskMutation) RemovedIDs(name string) []ent.Value { - switch name { - case task.EdgeTaskRecords: - ids := make([]ent.Value, 0, len(m.removedtask_records)) - for id := range m.removedtask_records { - ids = append(ids, id) - } - return ids +// RemovedWorkspaceFiles returns the removed IDs of the "workspace_files" edge to the WorkspaceFile entity. +func (m *UserMutation) RemovedWorkspaceFilesIDs() (ids []uuid.UUID) { + for id := range m.removedworkspace_files { + ids = append(ids, id) } - return nil + return } -// ClearedEdges returns all edge names that were cleared in this mutation. -func (m *TaskMutation) ClearedEdges() []string { - edges := make([]string, 0, 3) - if m.clearedtask_records { - edges = append(edges, task.EdgeTaskRecords) +// WorkspaceFilesIDs returns the "workspace_files" edge IDs in the mutation. +func (m *UserMutation) WorkspaceFilesIDs() (ids []uuid.UUID) { + for id := range m.workspace_files { + ids = append(ids, id) } - if m.cleareduser { - edges = append(edges, task.EdgeUser) + return +} + +// ResetWorkspaceFiles resets all changes to the "workspace_files" edge. +func (m *UserMutation) ResetWorkspaceFiles() { + m.workspace_files = nil + m.clearedworkspace_files = false + m.removedworkspace_files = nil +} + +// AddAPIKeyIDs adds the "api_keys" edge to the ApiKey entity by ids. +func (m *UserMutation) AddAPIKeyIDs(ids ...uuid.UUID) { + if m.api_keys == nil { + m.api_keys = make(map[uuid.UUID]struct{}) } - if m.clearedmodel { - edges = append(edges, task.EdgeModel) + for i := range ids { + m.api_keys[ids[i]] = struct{}{} } - return edges } -// EdgeCleared returns a boolean which indicates if the edge with the given name -// was cleared in this mutation. -func (m *TaskMutation) EdgeCleared(name string) bool { - switch name { - case task.EdgeTaskRecords: - return m.clearedtask_records - case task.EdgeUser: - return m.cleareduser - case task.EdgeModel: - return m.clearedmodel +// ClearAPIKeys clears the "api_keys" edge to the ApiKey entity. +func (m *UserMutation) ClearAPIKeys() { + m.clearedapi_keys = true +} + +// APIKeysCleared reports if the "api_keys" edge to the ApiKey entity was cleared. +func (m *UserMutation) APIKeysCleared() bool { + return m.clearedapi_keys +} + +// RemoveAPIKeyIDs removes the "api_keys" edge to the ApiKey entity by IDs. +func (m *UserMutation) RemoveAPIKeyIDs(ids ...uuid.UUID) { + if m.removedapi_keys == nil { + m.removedapi_keys = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.api_keys, ids[i]) + m.removedapi_keys[ids[i]] = struct{}{} } - return false } -// ClearEdge clears the value of the edge with the given name. It returns an error -// if that edge is not defined in the schema. -func (m *TaskMutation) ClearEdge(name string) error { - switch name { - case task.EdgeUser: - m.ClearUser() - return nil - case task.EdgeModel: - m.ClearModel() - return nil +// RemovedAPIKeys returns the removed IDs of the "api_keys" edge to the ApiKey entity. +func (m *UserMutation) RemovedAPIKeysIDs() (ids []uuid.UUID) { + for id := range m.removedapi_keys { + ids = append(ids, id) } - return fmt.Errorf("unknown Task unique edge %s", name) + return } -// ResetEdge resets all changes to the edge with the given name in this mutation. -// It returns an error if the edge is not defined in the schema. -func (m *TaskMutation) ResetEdge(name string) error { - switch name { - case task.EdgeTaskRecords: - m.ResetTaskRecords() - return nil - case task.EdgeUser: - m.ResetUser() - return nil - case task.EdgeModel: - m.ResetModel() - return nil +// APIKeysIDs returns the "api_keys" edge IDs in the mutation. +func (m *UserMutation) APIKeysIDs() (ids []uuid.UUID) { + for id := range m.api_keys { + ids = append(ids, id) } - return fmt.Errorf("unknown Task edge %s", name) + return } -// TaskRecordMutation represents an operation that mutates the TaskRecord nodes in the graph. -type TaskRecordMutation struct { - config - op Op - typ string - id *uuid.UUID - prompt *string - role *consts.ChatRole - completion *string - output_tokens *int64 - addoutput_tokens *int64 - code_lines *int64 - addcode_lines *int64 - code *string - created_at *time.Time - updated_at *time.Time - clearedFields map[string]struct{} - task *uuid.UUID - clearedtask bool - done bool - oldValue func(context.Context) (*TaskRecord, error) - predicates []predicate.TaskRecord +// ResetAPIKeys resets all changes to the "api_keys" edge. +func (m *UserMutation) ResetAPIKeys() { + m.api_keys = nil + m.clearedapi_keys = false + m.removedapi_keys = nil } -var _ ent.Mutation = (*TaskRecordMutation)(nil) +// AddSecurityScanningIDs adds the "security_scannings" edge to the SecurityScanning entity by ids. +func (m *UserMutation) AddSecurityScanningIDs(ids ...uuid.UUID) { + if m.security_scannings == nil { + m.security_scannings = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.security_scannings[ids[i]] = struct{}{} + } +} -// taskrecordOption allows management of the mutation configuration using functional options. -type taskrecordOption func(*TaskRecordMutation) +// ClearSecurityScannings clears the "security_scannings" edge to the SecurityScanning entity. +func (m *UserMutation) ClearSecurityScannings() { + m.clearedsecurity_scannings = true +} -// newTaskRecordMutation creates new mutation for the TaskRecord entity. -func newTaskRecordMutation(c config, op Op, opts ...taskrecordOption) *TaskRecordMutation { - m := &TaskRecordMutation{ - config: c, - op: op, - typ: TypeTaskRecord, - clearedFields: make(map[string]struct{}), +// SecurityScanningsCleared reports if the "security_scannings" edge to the SecurityScanning entity was cleared. +func (m *UserMutation) SecurityScanningsCleared() bool { + return m.clearedsecurity_scannings +} + +// RemoveSecurityScanningIDs removes the "security_scannings" edge to the SecurityScanning entity by IDs. +func (m *UserMutation) RemoveSecurityScanningIDs(ids ...uuid.UUID) { + if m.removedsecurity_scannings == nil { + m.removedsecurity_scannings = make(map[uuid.UUID]struct{}) } - for _, opt := range opts { - opt(m) + for i := range ids { + delete(m.security_scannings, ids[i]) + m.removedsecurity_scannings[ids[i]] = struct{}{} } - return m } -// withTaskRecordID sets the ID field of the mutation. -func withTaskRecordID(id uuid.UUID) taskrecordOption { - return func(m *TaskRecordMutation) { - var ( - err error - once sync.Once - value *TaskRecord - ) - m.oldValue = func(ctx context.Context) (*TaskRecord, error) { - once.Do(func() { - if m.done { - err = errors.New("querying old values post mutation is not allowed") - } else { - value, err = m.Client().TaskRecord.Get(ctx, id) - } - }) - return value, err - } - m.id = &id +// RemovedSecurityScannings returns the removed IDs of the "security_scannings" edge to the SecurityScanning entity. +func (m *UserMutation) RemovedSecurityScanningsIDs() (ids []uuid.UUID) { + for id := range m.removedsecurity_scannings { + ids = append(ids, id) } + return } -// withTaskRecord sets the old TaskRecord of the mutation. -func withTaskRecord(node *TaskRecord) taskrecordOption { - return func(m *TaskRecordMutation) { - m.oldValue = func(context.Context) (*TaskRecord, error) { - return node, nil - } - m.id = &node.ID +// SecurityScanningsIDs returns the "security_scannings" edge IDs in the mutation. +func (m *UserMutation) SecurityScanningsIDs() (ids []uuid.UUID) { + for id := range m.security_scannings { + ids = append(ids, id) } + return } -// Client returns a new `ent.Client` from the mutation. If the mutation was -// executed in a transaction (ent.Tx), a transactional client is returned. -func (m TaskRecordMutation) Client() *Client { - client := &Client{config: m.config} - client.init() - return client +// ResetSecurityScannings resets all changes to the "security_scannings" edge. +func (m *UserMutation) ResetSecurityScannings() { + m.security_scannings = nil + m.clearedsecurity_scannings = false + m.removedsecurity_scannings = nil } -// Tx returns an `ent.Tx` for mutations that were executed in transactions; -// it returns an error otherwise. -func (m TaskRecordMutation) Tx() (*Tx, error) { - if _, ok := m.driver.(*txDriver); !ok { - return nil, errors.New("db: mutation is not running in a transaction") +// AddGroupIDs adds the "groups" edge to the UserGroup entity by ids. +func (m *UserMutation) AddGroupIDs(ids ...uuid.UUID) { + if m.groups == nil { + m.groups = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.groups[ids[i]] = struct{}{} } - tx := &Tx{config: m.config} - tx.init() - return tx, nil } -// SetID sets the value of the id field. Note that this -// operation is only accepted on creation of TaskRecord entities. -func (m *TaskRecordMutation) SetID(id uuid.UUID) { - m.id = &id +// ClearGroups clears the "groups" edge to the UserGroup entity. +func (m *UserMutation) ClearGroups() { + m.clearedgroups = true } -// ID returns the ID value in the mutation. Note that the ID is only available -// if it was provided to the builder or after it was returned from the database. -func (m *TaskRecordMutation) ID() (id uuid.UUID, exists bool) { - if m.id == nil { - return - } - return *m.id, true +// GroupsCleared reports if the "groups" edge to the UserGroup entity was cleared. +func (m *UserMutation) GroupsCleared() bool { + return m.clearedgroups } -// IDs queries the database and returns the entity ids that match the mutation's predicate. -// That means, if the mutation is applied within a transaction with an isolation level such -// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated -// or updated by the mutation. -func (m *TaskRecordMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { - switch { - case m.op.Is(OpUpdateOne | OpDeleteOne): - id, exists := m.ID() - if exists { - return []uuid.UUID{id}, nil - } - fallthrough - case m.op.Is(OpUpdate | OpDelete): - return m.Client().TaskRecord.Query().Where(m.predicates...).IDs(ctx) - default: - return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) +// RemoveGroupIDs removes the "groups" edge to the UserGroup entity by IDs. +func (m *UserMutation) RemoveGroupIDs(ids ...uuid.UUID) { + if m.removedgroups == nil { + m.removedgroups = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.groups, ids[i]) + m.removedgroups[ids[i]] = struct{}{} } } -// SetTaskID sets the "task_id" field. -func (m *TaskRecordMutation) SetTaskID(u uuid.UUID) { - m.task = &u +// RemovedGroups returns the removed IDs of the "groups" edge to the UserGroup entity. +func (m *UserMutation) RemovedGroupsIDs() (ids []uuid.UUID) { + for id := range m.removedgroups { + ids = append(ids, id) + } + return } -// TaskID returns the value of the "task_id" field in the mutation. -func (m *TaskRecordMutation) TaskID() (r uuid.UUID, exists bool) { - v := m.task - if v == nil { - return +// GroupsIDs returns the "groups" edge IDs in the mutation. +func (m *UserMutation) GroupsIDs() (ids []uuid.UUID) { + for id := range m.groups { + ids = append(ids, id) } - return *v, true + return } -// OldTaskID returns the old "task_id" field's value of the TaskRecord entity. -// If the TaskRecord object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *TaskRecordMutation) OldTaskID(ctx context.Context) (v uuid.UUID, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldTaskID is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldTaskID requires an ID field in the mutation") +// ResetGroups resets all changes to the "groups" edge. +func (m *UserMutation) ResetGroups() { + m.groups = nil + m.clearedgroups = false + m.removedgroups = nil +} + +// AddUserGroupIDs adds the "user_groups" edge to the UserGroupUser entity by ids. +func (m *UserMutation) AddUserGroupIDs(ids ...uuid.UUID) { + if m.user_groups == nil { + m.user_groups = make(map[uuid.UUID]struct{}) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldTaskID: %w", err) + for i := range ids { + m.user_groups[ids[i]] = struct{}{} } - return oldValue.TaskID, nil } -// ClearTaskID clears the value of the "task_id" field. -func (m *TaskRecordMutation) ClearTaskID() { - m.task = nil - m.clearedFields[taskrecord.FieldTaskID] = struct{}{} +// ClearUserGroups clears the "user_groups" edge to the UserGroupUser entity. +func (m *UserMutation) ClearUserGroups() { + m.cleareduser_groups = true } -// TaskIDCleared returns if the "task_id" field was cleared in this mutation. -func (m *TaskRecordMutation) TaskIDCleared() bool { - _, ok := m.clearedFields[taskrecord.FieldTaskID] - return ok +// UserGroupsCleared reports if the "user_groups" edge to the UserGroupUser entity was cleared. +func (m *UserMutation) UserGroupsCleared() bool { + return m.cleareduser_groups } -// ResetTaskID resets all changes to the "task_id" field. -func (m *TaskRecordMutation) ResetTaskID() { - m.task = nil - delete(m.clearedFields, taskrecord.FieldTaskID) +// RemoveUserGroupIDs removes the "user_groups" edge to the UserGroupUser entity by IDs. +func (m *UserMutation) RemoveUserGroupIDs(ids ...uuid.UUID) { + if m.removeduser_groups == nil { + m.removeduser_groups = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.user_groups, ids[i]) + m.removeduser_groups[ids[i]] = struct{}{} + } } -// SetPrompt sets the "prompt" field. -func (m *TaskRecordMutation) SetPrompt(s string) { - m.prompt = &s +// RemovedUserGroups returns the removed IDs of the "user_groups" edge to the UserGroupUser entity. +func (m *UserMutation) RemovedUserGroupsIDs() (ids []uuid.UUID) { + for id := range m.removeduser_groups { + ids = append(ids, id) + } + return } -// Prompt returns the value of the "prompt" field in the mutation. -func (m *TaskRecordMutation) Prompt() (r string, exists bool) { - v := m.prompt - if v == nil { - return +// UserGroupsIDs returns the "user_groups" edge IDs in the mutation. +func (m *UserMutation) UserGroupsIDs() (ids []uuid.UUID) { + for id := range m.user_groups { + ids = append(ids, id) } - return *v, true + return } -// OldPrompt returns the old "prompt" field's value of the TaskRecord entity. -// If the TaskRecord object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *TaskRecordMutation) OldPrompt(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldPrompt is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldPrompt requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldPrompt: %w", err) +// ResetUserGroups resets all changes to the "user_groups" edge. +func (m *UserMutation) ResetUserGroups() { + m.user_groups = nil + m.cleareduser_groups = false + m.removeduser_groups = nil +} + +// Where appends a list predicates to the UserMutation builder. +func (m *UserMutation) Where(ps ...predicate.User) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the UserMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *UserMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.User, len(ps)) + for i := range ps { + p[i] = ps[i] } - return oldValue.Prompt, nil + m.Where(p...) } -// ClearPrompt clears the value of the "prompt" field. -func (m *TaskRecordMutation) ClearPrompt() { - m.prompt = nil - m.clearedFields[taskrecord.FieldPrompt] = struct{}{} +// Op returns the operation name. +func (m *UserMutation) Op() Op { + return m.op } -// PromptCleared returns if the "prompt" field was cleared in this mutation. -func (m *TaskRecordMutation) PromptCleared() bool { - _, ok := m.clearedFields[taskrecord.FieldPrompt] - return ok +// SetOp allows setting the mutation operation. +func (m *UserMutation) SetOp(op Op) { + m.op = op } -// ResetPrompt resets all changes to the "prompt" field. -func (m *TaskRecordMutation) ResetPrompt() { - m.prompt = nil - delete(m.clearedFields, taskrecord.FieldPrompt) +// Type returns the node type of this mutation (User). +func (m *UserMutation) Type() string { + return m.typ } -// SetRole sets the "role" field. -func (m *TaskRecordMutation) SetRole(cr consts.ChatRole) { - m.role = &cr +// 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 *UserMutation) Fields() []string { + fields := make([]string, 0, 9) + if m.deleted_at != nil { + fields = append(fields, user.FieldDeletedAt) + } + if m.username != nil { + fields = append(fields, user.FieldUsername) + } + if m.password != nil { + fields = append(fields, user.FieldPassword) + } + if m.email != nil { + fields = append(fields, user.FieldEmail) + } + if m.avatar_url != nil { + fields = append(fields, user.FieldAvatarURL) + } + if m.platform != nil { + fields = append(fields, user.FieldPlatform) + } + if m.status != nil { + fields = append(fields, user.FieldStatus) + } + if m.created_at != nil { + fields = append(fields, user.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, user.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 *UserMutation) Field(name string) (ent.Value, bool) { + switch name { + case user.FieldDeletedAt: + return m.DeletedAt() + case user.FieldUsername: + return m.Username() + case user.FieldPassword: + return m.Password() + case user.FieldEmail: + return m.Email() + case user.FieldAvatarURL: + return m.AvatarURL() + case user.FieldPlatform: + return m.Platform() + case user.FieldStatus: + return m.Status() + case user.FieldCreatedAt: + return m.CreatedAt() + case user.FieldUpdatedAt: + return m.UpdatedAt() + } + return nil, false } -// Role returns the value of the "role" field in the mutation. -func (m *TaskRecordMutation) Role() (r consts.ChatRole, exists bool) { - v := m.role - if v == nil { - return +// 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 *UserMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case user.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case user.FieldUsername: + return m.OldUsername(ctx) + case user.FieldPassword: + return m.OldPassword(ctx) + case user.FieldEmail: + return m.OldEmail(ctx) + case user.FieldAvatarURL: + return m.OldAvatarURL(ctx) + case user.FieldPlatform: + return m.OldPlatform(ctx) + case user.FieldStatus: + return m.OldStatus(ctx) + case user.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case user.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) } - return *v, true + return nil, fmt.Errorf("unknown User field %s", name) } -// OldRole returns the old "role" field's value of the TaskRecord entity. -// If the TaskRecord object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *TaskRecordMutation) OldRole(ctx context.Context) (v consts.ChatRole, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldRole is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldRole requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldRole: %w", err) +// 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 *UserMutation) SetField(name string, value ent.Value) error { + switch name { + case user.FieldDeletedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDeletedAt(v) + return nil + case user.FieldUsername: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUsername(v) + return nil + case user.FieldPassword: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPassword(v) + return nil + case user.FieldEmail: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEmail(v) + return nil + case user.FieldAvatarURL: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAvatarURL(v) + return nil + case user.FieldPlatform: + v, ok := value.(consts.UserPlatform) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPlatform(v) + return nil + case user.FieldStatus: + v, ok := value.(consts.UserStatus) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStatus(v) + return nil + case user.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 user.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 oldValue.Role, nil + return fmt.Errorf("unknown User field %s", name) } -// ResetRole resets all changes to the "role" field. -func (m *TaskRecordMutation) ResetRole() { - m.role = nil +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *UserMutation) AddedFields() []string { + return nil } -// SetCompletion sets the "completion" field. -func (m *TaskRecordMutation) SetCompletion(s string) { - m.completion = &s +// 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 *UserMutation) AddedField(name string) (ent.Value, bool) { + return nil, false } -// Completion returns the value of the "completion" field in the mutation. -func (m *TaskRecordMutation) Completion() (r string, exists bool) { - v := m.completion - if v == nil { - return +// 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 *UserMutation) AddField(name string, value ent.Value) error { + switch name { } - return *v, true + return fmt.Errorf("unknown User numeric field %s", name) } -// OldCompletion returns the old "completion" field's value of the TaskRecord entity. -// If the TaskRecord object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *TaskRecordMutation) OldCompletion(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCompletion is only allowed on UpdateOne operations") +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *UserMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(user.FieldDeletedAt) { + fields = append(fields, user.FieldDeletedAt) } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCompletion requires an ID field in the mutation") + if m.FieldCleared(user.FieldUsername) { + fields = append(fields, user.FieldUsername) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldCompletion: %w", err) + if m.FieldCleared(user.FieldPassword) { + fields = append(fields, user.FieldPassword) } - return oldValue.Completion, nil -} - -// ClearCompletion clears the value of the "completion" field. -func (m *TaskRecordMutation) ClearCompletion() { - m.completion = nil - m.clearedFields[taskrecord.FieldCompletion] = struct{}{} + if m.FieldCleared(user.FieldEmail) { + fields = append(fields, user.FieldEmail) + } + if m.FieldCleared(user.FieldAvatarURL) { + fields = append(fields, user.FieldAvatarURL) + } + return fields } -// CompletionCleared returns if the "completion" field was cleared in this mutation. -func (m *TaskRecordMutation) CompletionCleared() bool { - _, ok := m.clearedFields[taskrecord.FieldCompletion] +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *UserMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] return ok } -// ResetCompletion resets all changes to the "completion" field. -func (m *TaskRecordMutation) ResetCompletion() { - m.completion = nil - delete(m.clearedFields, taskrecord.FieldCompletion) -} - -// SetOutputTokens sets the "output_tokens" field. -func (m *TaskRecordMutation) SetOutputTokens(i int64) { - m.output_tokens = &i - m.addoutput_tokens = nil +// 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 *UserMutation) ClearField(name string) error { + switch name { + case user.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case user.FieldUsername: + m.ClearUsername() + return nil + case user.FieldPassword: + m.ClearPassword() + return nil + case user.FieldEmail: + m.ClearEmail() + return nil + case user.FieldAvatarURL: + m.ClearAvatarURL() + return nil + } + return fmt.Errorf("unknown User nullable field %s", name) } -// OutputTokens returns the value of the "output_tokens" field in the mutation. -func (m *TaskRecordMutation) OutputTokens() (r int64, exists bool) { - v := m.output_tokens - if v == nil { - return +// 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 *UserMutation) ResetField(name string) error { + switch name { + case user.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case user.FieldUsername: + m.ResetUsername() + return nil + case user.FieldPassword: + m.ResetPassword() + return nil + case user.FieldEmail: + m.ResetEmail() + return nil + case user.FieldAvatarURL: + m.ResetAvatarURL() + return nil + case user.FieldPlatform: + m.ResetPlatform() + return nil + case user.FieldStatus: + m.ResetStatus() + return nil + case user.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case user.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil } - return *v, true + return fmt.Errorf("unknown User field %s", name) } -// OldOutputTokens returns the old "output_tokens" field's value of the TaskRecord entity. -// If the TaskRecord object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *TaskRecordMutation) OldOutputTokens(ctx context.Context) (v int64, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldOutputTokens is only allowed on UpdateOne operations") +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *UserMutation) AddedEdges() []string { + edges := make([]string, 0, 10) + if m.login_histories != nil { + edges = append(edges, user.EdgeLoginHistories) } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldOutputTokens requires an ID field in the mutation") + if m.models != nil { + edges = append(edges, user.EdgeModels) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldOutputTokens: %w", err) + if m.tasks != nil { + edges = append(edges, user.EdgeTasks) } - return oldValue.OutputTokens, nil -} - -// AddOutputTokens adds i to the "output_tokens" field. -func (m *TaskRecordMutation) AddOutputTokens(i int64) { - if m.addoutput_tokens != nil { - *m.addoutput_tokens += i - } else { - m.addoutput_tokens = &i + if m.identities != nil { + edges = append(edges, user.EdgeIdentities) } -} - -// AddedOutputTokens returns the value that was added to the "output_tokens" field in this mutation. -func (m *TaskRecordMutation) AddedOutputTokens() (r int64, exists bool) { - v := m.addoutput_tokens - if v == nil { - return + if m.workspaces != nil { + edges = append(edges, user.EdgeWorkspaces) } - return *v, true -} - -// ResetOutputTokens resets all changes to the "output_tokens" field. -func (m *TaskRecordMutation) ResetOutputTokens() { - m.output_tokens = nil - m.addoutput_tokens = nil -} - -// SetCodeLines sets the "code_lines" field. -func (m *TaskRecordMutation) SetCodeLines(i int64) { - m.code_lines = &i - m.addcode_lines = nil -} - -// CodeLines returns the value of the "code_lines" field in the mutation. -func (m *TaskRecordMutation) CodeLines() (r int64, exists bool) { - v := m.code_lines - if v == nil { - return + if m.workspace_files != nil { + edges = append(edges, user.EdgeWorkspaceFiles) } - return *v, true -} - -// OldCodeLines returns the old "code_lines" field's value of the TaskRecord entity. -// If the TaskRecord object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *TaskRecordMutation) OldCodeLines(ctx context.Context) (v int64, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCodeLines is only allowed on UpdateOne operations") + if m.api_keys != nil { + edges = append(edges, user.EdgeAPIKeys) } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCodeLines requires an ID field in the mutation") + if m.security_scannings != nil { + edges = append(edges, user.EdgeSecurityScannings) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldCodeLines: %w", err) + if m.groups != nil { + edges = append(edges, user.EdgeGroups) } - return oldValue.CodeLines, nil -} - -// AddCodeLines adds i to the "code_lines" field. -func (m *TaskRecordMutation) AddCodeLines(i int64) { - if m.addcode_lines != nil { - *m.addcode_lines += i - } else { - m.addcode_lines = &i + if m.user_groups != nil { + edges = append(edges, user.EdgeUserGroups) } + return edges } -// AddedCodeLines returns the value that was added to the "code_lines" field in this mutation. -func (m *TaskRecordMutation) AddedCodeLines() (r int64, exists bool) { - v := m.addcode_lines - if v == nil { - return +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *UserMutation) AddedIDs(name string) []ent.Value { + switch name { + case user.EdgeLoginHistories: + ids := make([]ent.Value, 0, len(m.login_histories)) + for id := range m.login_histories { + ids = append(ids, id) + } + return ids + case user.EdgeModels: + ids := make([]ent.Value, 0, len(m.models)) + for id := range m.models { + ids = append(ids, id) + } + return ids + case user.EdgeTasks: + ids := make([]ent.Value, 0, len(m.tasks)) + for id := range m.tasks { + ids = append(ids, id) + } + return ids + case user.EdgeIdentities: + ids := make([]ent.Value, 0, len(m.identities)) + for id := range m.identities { + ids = append(ids, id) + } + return ids + case user.EdgeWorkspaces: + ids := make([]ent.Value, 0, len(m.workspaces)) + for id := range m.workspaces { + ids = append(ids, id) + } + return ids + case user.EdgeWorkspaceFiles: + ids := make([]ent.Value, 0, len(m.workspace_files)) + for id := range m.workspace_files { + ids = append(ids, id) + } + return ids + case user.EdgeAPIKeys: + ids := make([]ent.Value, 0, len(m.api_keys)) + for id := range m.api_keys { + ids = append(ids, id) + } + return ids + case user.EdgeSecurityScannings: + ids := make([]ent.Value, 0, len(m.security_scannings)) + for id := range m.security_scannings { + ids = append(ids, id) + } + return ids + case user.EdgeGroups: + ids := make([]ent.Value, 0, len(m.groups)) + for id := range m.groups { + ids = append(ids, id) + } + return ids + case user.EdgeUserGroups: + ids := make([]ent.Value, 0, len(m.user_groups)) + for id := range m.user_groups { + ids = append(ids, id) + } + return ids } - return *v, true -} - -// ResetCodeLines resets all changes to the "code_lines" field. -func (m *TaskRecordMutation) ResetCodeLines() { - m.code_lines = nil - m.addcode_lines = nil + return nil } -// SetCode sets the "code" field. -func (m *TaskRecordMutation) SetCode(s string) { - m.code = &s +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *UserMutation) RemovedEdges() []string { + edges := make([]string, 0, 10) + if m.removedlogin_histories != nil { + edges = append(edges, user.EdgeLoginHistories) + } + if m.removedmodels != nil { + edges = append(edges, user.EdgeModels) + } + if m.removedtasks != nil { + edges = append(edges, user.EdgeTasks) + } + if m.removedidentities != nil { + edges = append(edges, user.EdgeIdentities) + } + if m.removedworkspaces != nil { + edges = append(edges, user.EdgeWorkspaces) + } + if m.removedworkspace_files != nil { + edges = append(edges, user.EdgeWorkspaceFiles) + } + if m.removedapi_keys != nil { + edges = append(edges, user.EdgeAPIKeys) + } + if m.removedsecurity_scannings != nil { + edges = append(edges, user.EdgeSecurityScannings) + } + if m.removedgroups != nil { + edges = append(edges, user.EdgeGroups) + } + if m.removeduser_groups != nil { + edges = append(edges, user.EdgeUserGroups) + } + return edges } -// Code returns the value of the "code" field in the mutation. -func (m *TaskRecordMutation) Code() (r string, exists bool) { - v := m.code - if v == nil { - return +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *UserMutation) RemovedIDs(name string) []ent.Value { + switch name { + case user.EdgeLoginHistories: + ids := make([]ent.Value, 0, len(m.removedlogin_histories)) + for id := range m.removedlogin_histories { + ids = append(ids, id) + } + return ids + case user.EdgeModels: + ids := make([]ent.Value, 0, len(m.removedmodels)) + for id := range m.removedmodels { + ids = append(ids, id) + } + return ids + case user.EdgeTasks: + ids := make([]ent.Value, 0, len(m.removedtasks)) + for id := range m.removedtasks { + ids = append(ids, id) + } + return ids + case user.EdgeIdentities: + ids := make([]ent.Value, 0, len(m.removedidentities)) + for id := range m.removedidentities { + ids = append(ids, id) + } + return ids + case user.EdgeWorkspaces: + ids := make([]ent.Value, 0, len(m.removedworkspaces)) + for id := range m.removedworkspaces { + ids = append(ids, id) + } + return ids + case user.EdgeWorkspaceFiles: + ids := make([]ent.Value, 0, len(m.removedworkspace_files)) + for id := range m.removedworkspace_files { + ids = append(ids, id) + } + return ids + case user.EdgeAPIKeys: + ids := make([]ent.Value, 0, len(m.removedapi_keys)) + for id := range m.removedapi_keys { + ids = append(ids, id) + } + return ids + case user.EdgeSecurityScannings: + ids := make([]ent.Value, 0, len(m.removedsecurity_scannings)) + for id := range m.removedsecurity_scannings { + ids = append(ids, id) + } + return ids + case user.EdgeGroups: + ids := make([]ent.Value, 0, len(m.removedgroups)) + for id := range m.removedgroups { + ids = append(ids, id) + } + return ids + case user.EdgeUserGroups: + ids := make([]ent.Value, 0, len(m.removeduser_groups)) + for id := range m.removeduser_groups { + ids = append(ids, id) + } + return ids } - return *v, true + return nil } -// OldCode returns the old "code" field's value of the TaskRecord entity. -// If the TaskRecord object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *TaskRecordMutation) OldCode(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCode is only allowed on UpdateOne operations") +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *UserMutation) ClearedEdges() []string { + edges := make([]string, 0, 10) + if m.clearedlogin_histories { + edges = append(edges, user.EdgeLoginHistories) } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCode requires an ID field in the mutation") + if m.clearedmodels { + edges = append(edges, user.EdgeModels) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldCode: %w", err) + if m.clearedtasks { + edges = append(edges, user.EdgeTasks) } - return oldValue.Code, nil -} - -// ClearCode clears the value of the "code" field. -func (m *TaskRecordMutation) ClearCode() { - m.code = nil - m.clearedFields[taskrecord.FieldCode] = struct{}{} -} - -// CodeCleared returns if the "code" field was cleared in this mutation. -func (m *TaskRecordMutation) CodeCleared() bool { - _, ok := m.clearedFields[taskrecord.FieldCode] - return ok -} - -// ResetCode resets all changes to the "code" field. -func (m *TaskRecordMutation) ResetCode() { - m.code = nil - delete(m.clearedFields, taskrecord.FieldCode) + if m.clearedidentities { + edges = append(edges, user.EdgeIdentities) + } + if m.clearedworkspaces { + edges = append(edges, user.EdgeWorkspaces) + } + if m.clearedworkspace_files { + edges = append(edges, user.EdgeWorkspaceFiles) + } + if m.clearedapi_keys { + edges = append(edges, user.EdgeAPIKeys) + } + if m.clearedsecurity_scannings { + edges = append(edges, user.EdgeSecurityScannings) + } + if m.clearedgroups { + edges = append(edges, user.EdgeGroups) + } + if m.cleareduser_groups { + edges = append(edges, user.EdgeUserGroups) + } + return edges } -// SetCreatedAt sets the "created_at" field. -func (m *TaskRecordMutation) SetCreatedAt(t time.Time) { - m.created_at = &t +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *UserMutation) EdgeCleared(name string) bool { + switch name { + case user.EdgeLoginHistories: + return m.clearedlogin_histories + case user.EdgeModels: + return m.clearedmodels + case user.EdgeTasks: + return m.clearedtasks + case user.EdgeIdentities: + return m.clearedidentities + case user.EdgeWorkspaces: + return m.clearedworkspaces + case user.EdgeWorkspaceFiles: + return m.clearedworkspace_files + case user.EdgeAPIKeys: + return m.clearedapi_keys + case user.EdgeSecurityScannings: + return m.clearedsecurity_scannings + case user.EdgeGroups: + return m.clearedgroups + case user.EdgeUserGroups: + return m.cleareduser_groups + } + return false } -// CreatedAt returns the value of the "created_at" field in the mutation. -func (m *TaskRecordMutation) CreatedAt() (r time.Time, exists bool) { - v := m.created_at - if v == nil { - return +// 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 *UserMutation) ClearEdge(name string) error { + switch name { } - return *v, true + return fmt.Errorf("unknown User unique edge %s", name) } -// OldCreatedAt returns the old "created_at" field's value of the TaskRecord entity. -// If the TaskRecord object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *TaskRecordMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCreatedAt requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) +// 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 *UserMutation) ResetEdge(name string) error { + switch name { + case user.EdgeLoginHistories: + m.ResetLoginHistories() + return nil + case user.EdgeModels: + m.ResetModels() + return nil + case user.EdgeTasks: + m.ResetTasks() + return nil + case user.EdgeIdentities: + m.ResetIdentities() + return nil + case user.EdgeWorkspaces: + m.ResetWorkspaces() + return nil + case user.EdgeWorkspaceFiles: + m.ResetWorkspaceFiles() + return nil + case user.EdgeAPIKeys: + m.ResetAPIKeys() + return nil + case user.EdgeSecurityScannings: + m.ResetSecurityScannings() + return nil + case user.EdgeGroups: + m.ResetGroups() + return nil + case user.EdgeUserGroups: + m.ResetUserGroups() + return nil } - return oldValue.CreatedAt, nil + return fmt.Errorf("unknown User edge %s", name) } -// ResetCreatedAt resets all changes to the "created_at" field. -func (m *TaskRecordMutation) ResetCreatedAt() { - m.created_at = nil +// UserGroupMutation represents an operation that mutates the UserGroup nodes in the graph. +type UserGroupMutation struct { + config + op Op + typ string + id *uuid.UUID + name *string + created_at *time.Time + clearedFields map[string]struct{} + owner *uuid.UUID + clearedowner bool + users map[uuid.UUID]struct{} + removedusers map[uuid.UUID]struct{} + clearedusers bool + admins map[uuid.UUID]struct{} + removedadmins map[uuid.UUID]struct{} + clearedadmins bool + user_groups map[uuid.UUID]struct{} + removeduser_groups map[uuid.UUID]struct{} + cleareduser_groups bool + user_group_admins map[uuid.UUID]struct{} + removeduser_group_admins map[uuid.UUID]struct{} + cleareduser_group_admins bool + done bool + oldValue func(context.Context) (*UserGroup, error) + predicates []predicate.UserGroup } -// SetUpdatedAt sets the "updated_at" field. -func (m *TaskRecordMutation) SetUpdatedAt(t time.Time) { - m.updated_at = &t -} +var _ ent.Mutation = (*UserGroupMutation)(nil) -// UpdatedAt returns the value of the "updated_at" field in the mutation. -func (m *TaskRecordMutation) UpdatedAt() (r time.Time, exists bool) { - v := m.updated_at - if v == nil { - return - } - return *v, true -} +// usergroupOption allows management of the mutation configuration using functional options. +type usergroupOption func(*UserGroupMutation) -// OldUpdatedAt returns the old "updated_at" field's value of the TaskRecord entity. -// If the TaskRecord object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *TaskRecordMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldUpdatedAt requires an ID field in the mutation") +// newUserGroupMutation creates new mutation for the UserGroup entity. +func newUserGroupMutation(c config, op Op, opts ...usergroupOption) *UserGroupMutation { + m := &UserGroupMutation{ + config: c, + op: op, + typ: TypeUserGroup, + clearedFields: make(map[string]struct{}), } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) + for _, opt := range opts { + opt(m) } - return oldValue.UpdatedAt, nil + return m } -// ResetUpdatedAt resets all changes to the "updated_at" field. -func (m *TaskRecordMutation) ResetUpdatedAt() { - m.updated_at = nil +// withUserGroupID sets the ID field of the mutation. +func withUserGroupID(id uuid.UUID) usergroupOption { + return func(m *UserGroupMutation) { + var ( + err error + once sync.Once + value *UserGroup + ) + m.oldValue = func(ctx context.Context) (*UserGroup, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().UserGroup.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } } -// ClearTask clears the "task" edge to the Task entity. -func (m *TaskRecordMutation) ClearTask() { - m.clearedtask = true - m.clearedFields[taskrecord.FieldTaskID] = struct{}{} +// withUserGroup sets the old UserGroup of the mutation. +func withUserGroup(node *UserGroup) usergroupOption { + return func(m *UserGroupMutation) { + m.oldValue = func(context.Context) (*UserGroup, error) { + return node, nil + } + m.id = &node.ID + } } -// TaskCleared reports if the "task" edge to the Task entity was cleared. -func (m *TaskRecordMutation) TaskCleared() bool { - return m.TaskIDCleared() || m.clearedtask +// 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 UserGroupMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client } -// TaskIDs returns the "task" edge IDs in the mutation. -// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// TaskID instead. It exists only for internal usage by the builders. -func (m *TaskRecordMutation) TaskIDs() (ids []uuid.UUID) { - if id := m.task; id != nil { - ids = append(ids, *id) +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m UserGroupMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("db: mutation is not running in a transaction") } - return -} - -// ResetTask resets all changes to the "task" edge. -func (m *TaskRecordMutation) ResetTask() { - m.task = nil - m.clearedtask = false + tx := &Tx{config: m.config} + tx.init() + return tx, nil } -// Where appends a list predicates to the TaskRecordMutation builder. -func (m *TaskRecordMutation) Where(ps ...predicate.TaskRecord) { - m.predicates = append(m.predicates, ps...) +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of UserGroup entities. +func (m *UserGroupMutation) SetID(id uuid.UUID) { + m.id = &id } -// WhereP appends storage-level predicates to the TaskRecordMutation builder. Using this method, -// users can use type-assertion to append predicates that do not depend on any generated package. -func (m *TaskRecordMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.TaskRecord, len(ps)) - for i := range ps { - p[i] = ps[i] +// 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 *UserGroupMutation) ID() (id uuid.UUID, exists bool) { + if m.id == nil { + return } - m.Where(p...) -} - -// Op returns the operation name. -func (m *TaskRecordMutation) Op() Op { - return m.op + return *m.id, true } -// SetOp allows setting the mutation operation. -func (m *TaskRecordMutation) SetOp(op Op) { - m.op = op +// 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 *UserGroupMutation) 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().UserGroup.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } } -// Type returns the node type of this mutation (TaskRecord). -func (m *TaskRecordMutation) Type() string { - return m.typ +// SetAdminID sets the "admin_id" field. +func (m *UserGroupMutation) SetAdminID(u uuid.UUID) { + m.owner = &u } -// Fields returns all fields that were changed during this mutation. Note that in -// order to get all numeric fields that were incremented/decremented, call -// AddedFields(). -func (m *TaskRecordMutation) Fields() []string { - fields := make([]string, 0, 9) - if m.task != nil { - fields = append(fields, taskrecord.FieldTaskID) - } - if m.prompt != nil { - fields = append(fields, taskrecord.FieldPrompt) - } - if m.role != nil { - fields = append(fields, taskrecord.FieldRole) - } - if m.completion != nil { - fields = append(fields, taskrecord.FieldCompletion) - } - if m.output_tokens != nil { - fields = append(fields, taskrecord.FieldOutputTokens) - } - if m.code_lines != nil { - fields = append(fields, taskrecord.FieldCodeLines) +// AdminID returns the value of the "admin_id" field in the mutation. +func (m *UserGroupMutation) AdminID() (r uuid.UUID, exists bool) { + v := m.owner + if v == nil { + return } - if m.code != nil { - fields = append(fields, taskrecord.FieldCode) + return *v, true +} + +// OldAdminID returns the old "admin_id" field's value of the UserGroup entity. +// If the UserGroup 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 *UserGroupMutation) OldAdminID(ctx context.Context) (v uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAdminID is only allowed on UpdateOne operations") } - if m.created_at != nil { - fields = append(fields, taskrecord.FieldCreatedAt) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAdminID requires an ID field in the mutation") } - if m.updated_at != nil { - fields = append(fields, taskrecord.FieldUpdatedAt) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAdminID: %w", err) } - return fields + return oldValue.AdminID, nil } -// Field returns the value of a field with the given name. The second boolean -// return value indicates that this field was not set, or was not defined in the -// schema. -func (m *TaskRecordMutation) Field(name string) (ent.Value, bool) { - switch name { - case taskrecord.FieldTaskID: - return m.TaskID() - case taskrecord.FieldPrompt: - return m.Prompt() - case taskrecord.FieldRole: - return m.Role() - case taskrecord.FieldCompletion: - return m.Completion() - case taskrecord.FieldOutputTokens: - return m.OutputTokens() - case taskrecord.FieldCodeLines: - return m.CodeLines() - case taskrecord.FieldCode: - return m.Code() - case taskrecord.FieldCreatedAt: - return m.CreatedAt() - case taskrecord.FieldUpdatedAt: - return m.UpdatedAt() - } - return nil, false +// ResetAdminID resets all changes to the "admin_id" field. +func (m *UserGroupMutation) ResetAdminID() { + m.owner = nil } -// OldField returns the old value of the field from the database. An error is -// returned if the mutation operation is not UpdateOne, or the query to the -// database failed. -func (m *TaskRecordMutation) OldField(ctx context.Context, name string) (ent.Value, error) { - switch name { - case taskrecord.FieldTaskID: - return m.OldTaskID(ctx) - case taskrecord.FieldPrompt: - return m.OldPrompt(ctx) - case taskrecord.FieldRole: - return m.OldRole(ctx) - case taskrecord.FieldCompletion: - return m.OldCompletion(ctx) - case taskrecord.FieldOutputTokens: - return m.OldOutputTokens(ctx) - case taskrecord.FieldCodeLines: - return m.OldCodeLines(ctx) - case taskrecord.FieldCode: - return m.OldCode(ctx) - case taskrecord.FieldCreatedAt: - return m.OldCreatedAt(ctx) - case taskrecord.FieldUpdatedAt: - return m.OldUpdatedAt(ctx) - } - return nil, fmt.Errorf("unknown TaskRecord field %s", name) +// SetName sets the "name" field. +func (m *UserGroupMutation) SetName(s string) { + m.name = &s } -// SetField sets the value of a field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *TaskRecordMutation) SetField(name string, value ent.Value) error { - switch name { - case taskrecord.FieldTaskID: - v, ok := value.(uuid.UUID) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetTaskID(v) - return nil - case taskrecord.FieldPrompt: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetPrompt(v) - return nil - case taskrecord.FieldRole: - v, ok := value.(consts.ChatRole) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetRole(v) - return nil - case taskrecord.FieldCompletion: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetCompletion(v) - return nil - case taskrecord.FieldOutputTokens: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetOutputTokens(v) - return nil - case taskrecord.FieldCodeLines: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetCodeLines(v) - return nil - case taskrecord.FieldCode: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetCode(v) - return nil - case taskrecord.FieldCreatedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetCreatedAt(v) - return nil - case taskrecord.FieldUpdatedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetUpdatedAt(v) - return nil +// Name returns the value of the "name" field in the mutation. +func (m *UserGroupMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return } - return fmt.Errorf("unknown TaskRecord field %s", name) + return *v, true } -// AddedFields returns all numeric fields that were incremented/decremented during -// this mutation. -func (m *TaskRecordMutation) AddedFields() []string { - var fields []string - if m.addoutput_tokens != nil { - fields = append(fields, taskrecord.FieldOutputTokens) +// OldName returns the old "name" field's value of the UserGroup entity. +// If the UserGroup 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 *UserGroupMutation) 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.addcode_lines != nil { - fields = append(fields, taskrecord.FieldCodeLines) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") } - return fields + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, 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 *TaskRecordMutation) AddedField(name string) (ent.Value, bool) { - switch name { - case taskrecord.FieldOutputTokens: - return m.AddedOutputTokens() - case taskrecord.FieldCodeLines: - return m.AddedCodeLines() - } - return nil, false +// ResetName resets all changes to the "name" field. +func (m *UserGroupMutation) ResetName() { + m.name = nil } -// AddField adds the value to the field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *TaskRecordMutation) AddField(name string, value ent.Value) error { - switch name { - case taskrecord.FieldOutputTokens: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddOutputTokens(v) - return nil - case taskrecord.FieldCodeLines: - v, ok := value.(int64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddCodeLines(v) - return nil +// SetCreatedAt sets the "created_at" field. +func (m *UserGroupMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *UserGroupMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at + if v == nil { + return } - return fmt.Errorf("unknown TaskRecord numeric field %s", name) + return *v, true } -// ClearedFields returns all nullable fields that were cleared during this -// mutation. -func (m *TaskRecordMutation) ClearedFields() []string { - var fields []string - if m.FieldCleared(taskrecord.FieldTaskID) { - fields = append(fields, taskrecord.FieldTaskID) - } - if m.FieldCleared(taskrecord.FieldPrompt) { - fields = append(fields, taskrecord.FieldPrompt) +// OldCreatedAt returns the old "created_at" field's value of the UserGroup entity. +// If the UserGroup 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 *UserGroupMutation) 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.FieldCleared(taskrecord.FieldCompletion) { - fields = append(fields, taskrecord.FieldCompletion) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreatedAt requires an ID field in the mutation") } - if m.FieldCleared(taskrecord.FieldCode) { - fields = append(fields, taskrecord.FieldCode) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) } - return fields + return oldValue.CreatedAt, nil } -// FieldCleared returns a boolean indicating if a field with the given name was -// cleared in this mutation. -func (m *TaskRecordMutation) FieldCleared(name string) bool { - _, ok := m.clearedFields[name] - return ok +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *UserGroupMutation) ResetCreatedAt() { + m.created_at = nil } -// ClearField clears the value of the field with the given name. It returns an -// error if the field is not defined in the schema. -func (m *TaskRecordMutation) ClearField(name string) error { - switch name { - case taskrecord.FieldTaskID: - m.ClearTaskID() - return nil - case taskrecord.FieldPrompt: - m.ClearPrompt() - return nil - case taskrecord.FieldCompletion: - m.ClearCompletion() - return nil - case taskrecord.FieldCode: - m.ClearCode() - return nil - } - return fmt.Errorf("unknown TaskRecord nullable field %s", name) +// SetOwnerID sets the "owner" edge to the Admin entity by id. +func (m *UserGroupMutation) SetOwnerID(id uuid.UUID) { + m.owner = &id } -// ResetField resets all changes in the mutation for the field with the given name. -// It returns an error if the field is not defined in the schema. -func (m *TaskRecordMutation) ResetField(name string) error { - switch name { - case taskrecord.FieldTaskID: - m.ResetTaskID() - return nil - case taskrecord.FieldPrompt: - m.ResetPrompt() - return nil - case taskrecord.FieldRole: - m.ResetRole() - return nil - case taskrecord.FieldCompletion: - m.ResetCompletion() - return nil - case taskrecord.FieldOutputTokens: - m.ResetOutputTokens() - return nil - case taskrecord.FieldCodeLines: - m.ResetCodeLines() - return nil - case taskrecord.FieldCode: - m.ResetCode() - return nil - case taskrecord.FieldCreatedAt: - m.ResetCreatedAt() - return nil - case taskrecord.FieldUpdatedAt: - m.ResetUpdatedAt() - return nil - } - return fmt.Errorf("unknown TaskRecord field %s", name) +// ClearOwner clears the "owner" edge to the Admin entity. +func (m *UserGroupMutation) ClearOwner() { + m.clearedowner = true + m.clearedFields[usergroup.FieldAdminID] = struct{}{} } -// AddedEdges returns all edge names that were set/added in this mutation. -func (m *TaskRecordMutation) AddedEdges() []string { - edges := make([]string, 0, 1) - if m.task != nil { - edges = append(edges, taskrecord.EdgeTask) - } - return edges +// OwnerCleared reports if the "owner" edge to the Admin entity was cleared. +func (m *UserGroupMutation) OwnerCleared() bool { + return m.clearedowner } -// AddedIDs returns all IDs (to other nodes) that were added for the given edge -// name in this mutation. -func (m *TaskRecordMutation) AddedIDs(name string) []ent.Value { - switch name { - case taskrecord.EdgeTask: - if id := m.task; id != nil { - return []ent.Value{*id} - } +// OwnerID returns the "owner" edge ID in the mutation. +func (m *UserGroupMutation) OwnerID() (id uuid.UUID, exists bool) { + if m.owner != nil { + return *m.owner, true } - return nil + return } -// RemovedEdges returns all edge names that were removed in this mutation. -func (m *TaskRecordMutation) RemovedEdges() []string { - edges := make([]string, 0, 1) - return edges +// OwnerIDs returns the "owner" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// OwnerID instead. It exists only for internal usage by the builders. +func (m *UserGroupMutation) OwnerIDs() (ids []uuid.UUID) { + if id := m.owner; id != nil { + ids = append(ids, *id) + } + return } -// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with -// the given name in this mutation. -func (m *TaskRecordMutation) RemovedIDs(name string) []ent.Value { - return nil +// ResetOwner resets all changes to the "owner" edge. +func (m *UserGroupMutation) ResetOwner() { + m.owner = nil + m.clearedowner = false } -// ClearedEdges returns all edge names that were cleared in this mutation. -func (m *TaskRecordMutation) ClearedEdges() []string { - edges := make([]string, 0, 1) - if m.clearedtask { - edges = append(edges, taskrecord.EdgeTask) +// AddUserIDs adds the "users" edge to the User entity by ids. +func (m *UserGroupMutation) AddUserIDs(ids ...uuid.UUID) { + if m.users == nil { + m.users = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.users[ids[i]] = struct{}{} } - return edges } -// EdgeCleared returns a boolean which indicates if the edge with the given name -// was cleared in this mutation. -func (m *TaskRecordMutation) EdgeCleared(name string) bool { - switch name { - case taskrecord.EdgeTask: - return m.clearedtask - } - return false +// ClearUsers clears the "users" edge to the User entity. +func (m *UserGroupMutation) ClearUsers() { + m.clearedusers = true } -// ClearEdge clears the value of the edge with the given name. It returns an error -// if that edge is not defined in the schema. -func (m *TaskRecordMutation) ClearEdge(name string) error { - switch name { - case taskrecord.EdgeTask: - m.ClearTask() - return nil - } - return fmt.Errorf("unknown TaskRecord unique edge %s", name) +// UsersCleared reports if the "users" edge to the User entity was cleared. +func (m *UserGroupMutation) UsersCleared() bool { + return m.clearedusers } -// ResetEdge resets all changes to the edge with the given name in this mutation. -// It returns an error if the edge is not defined in the schema. -func (m *TaskRecordMutation) ResetEdge(name string) error { - switch name { - case taskrecord.EdgeTask: - m.ResetTask() - return nil +// RemoveUserIDs removes the "users" edge to the User entity by IDs. +func (m *UserGroupMutation) RemoveUserIDs(ids ...uuid.UUID) { + if m.removedusers == nil { + m.removedusers = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.users, ids[i]) + m.removedusers[ids[i]] = struct{}{} } - return fmt.Errorf("unknown TaskRecord edge %s", name) } -// UserMutation represents an operation that mutates the User nodes in the graph. -type UserMutation struct { - config - op Op - typ string - id *uuid.UUID - deleted_at *time.Time - username *string - password *string - email *string - avatar_url *string - platform *consts.UserPlatform - status *consts.UserStatus - created_at *time.Time - updated_at *time.Time - clearedFields map[string]struct{} - login_histories map[uuid.UUID]struct{} - removedlogin_histories map[uuid.UUID]struct{} - clearedlogin_histories bool - models map[uuid.UUID]struct{} - removedmodels map[uuid.UUID]struct{} - clearedmodels bool - tasks map[uuid.UUID]struct{} - removedtasks map[uuid.UUID]struct{} - clearedtasks bool - identities map[uuid.UUID]struct{} - removedidentities map[uuid.UUID]struct{} - clearedidentities bool - workspaces map[uuid.UUID]struct{} - removedworkspaces map[uuid.UUID]struct{} - clearedworkspaces bool - workspace_files map[uuid.UUID]struct{} - removedworkspace_files map[uuid.UUID]struct{} - clearedworkspace_files bool - api_keys map[uuid.UUID]struct{} - removedapi_keys map[uuid.UUID]struct{} - clearedapi_keys bool - security_scannings map[uuid.UUID]struct{} - removedsecurity_scannings map[uuid.UUID]struct{} - clearedsecurity_scannings bool - done bool - oldValue func(context.Context) (*User, error) - predicates []predicate.User +// RemovedUsers returns the removed IDs of the "users" edge to the User entity. +func (m *UserGroupMutation) RemovedUsersIDs() (ids []uuid.UUID) { + for id := range m.removedusers { + ids = append(ids, id) + } + return } -var _ ent.Mutation = (*UserMutation)(nil) +// UsersIDs returns the "users" edge IDs in the mutation. +func (m *UserGroupMutation) UsersIDs() (ids []uuid.UUID) { + for id := range m.users { + ids = append(ids, id) + } + return +} -// userOption allows management of the mutation configuration using functional options. -type userOption func(*UserMutation) +// ResetUsers resets all changes to the "users" edge. +func (m *UserGroupMutation) ResetUsers() { + m.users = nil + m.clearedusers = false + m.removedusers = nil +} -// newUserMutation creates new mutation for the User entity. -func newUserMutation(c config, op Op, opts ...userOption) *UserMutation { - m := &UserMutation{ - config: c, - op: op, - typ: TypeUser, - clearedFields: make(map[string]struct{}), +// AddAdminIDs adds the "admins" edge to the Admin entity by ids. +func (m *UserGroupMutation) AddAdminIDs(ids ...uuid.UUID) { + if m.admins == nil { + m.admins = make(map[uuid.UUID]struct{}) } - for _, opt := range opts { - opt(m) + for i := range ids { + m.admins[ids[i]] = struct{}{} } - return m } -// withUserID sets the ID field of the mutation. -func withUserID(id uuid.UUID) userOption { - return func(m *UserMutation) { - var ( - err error - once sync.Once - value *User - ) - m.oldValue = func(ctx context.Context) (*User, error) { - once.Do(func() { - if m.done { - err = errors.New("querying old values post mutation is not allowed") - } else { - value, err = m.Client().User.Get(ctx, id) - } - }) - return value, err - } - m.id = &id - } +// ClearAdmins clears the "admins" edge to the Admin entity. +func (m *UserGroupMutation) ClearAdmins() { + m.clearedadmins = true } -// withUser sets the old User of the mutation. -func withUser(node *User) userOption { - return func(m *UserMutation) { - m.oldValue = func(context.Context) (*User, error) { - return node, nil - } - m.id = &node.ID +// AdminsCleared reports if the "admins" edge to the Admin entity was cleared. +func (m *UserGroupMutation) AdminsCleared() bool { + return m.clearedadmins +} + +// RemoveAdminIDs removes the "admins" edge to the Admin entity by IDs. +func (m *UserGroupMutation) RemoveAdminIDs(ids ...uuid.UUID) { + if m.removedadmins == nil { + m.removedadmins = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.admins, ids[i]) + m.removedadmins[ids[i]] = struct{}{} } } -// 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 UserMutation) Client() *Client { - client := &Client{config: m.config} - client.init() - return client +// RemovedAdmins returns the removed IDs of the "admins" edge to the Admin entity. +func (m *UserGroupMutation) RemovedAdminsIDs() (ids []uuid.UUID) { + for id := range m.removedadmins { + ids = append(ids, id) + } + return } -// Tx returns an `ent.Tx` for mutations that were executed in transactions; -// it returns an error otherwise. -func (m UserMutation) Tx() (*Tx, error) { - if _, ok := m.driver.(*txDriver); !ok { - return nil, errors.New("db: mutation is not running in a transaction") +// AdminsIDs returns the "admins" edge IDs in the mutation. +func (m *UserGroupMutation) AdminsIDs() (ids []uuid.UUID) { + for id := range m.admins { + ids = append(ids, id) } - tx := &Tx{config: m.config} - tx.init() - return tx, nil + return } -// SetID sets the value of the id field. Note that this -// operation is only accepted on creation of User entities. -func (m *UserMutation) SetID(id uuid.UUID) { - m.id = &id +// ResetAdmins resets all changes to the "admins" edge. +func (m *UserGroupMutation) ResetAdmins() { + m.admins = nil + m.clearedadmins = false + m.removedadmins = nil } -// 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 *UserMutation) ID() (id uuid.UUID, exists bool) { - if m.id == nil { - return +// AddUserGroupIDs adds the "user_groups" edge to the UserGroupUser entity by ids. +func (m *UserGroupMutation) AddUserGroupIDs(ids ...uuid.UUID) { + if m.user_groups == nil { + m.user_groups = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.user_groups[ids[i]] = struct{}{} } - 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 *UserMutation) 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().User.Query().Where(m.predicates...).IDs(ctx) - default: - return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) - } +// ClearUserGroups clears the "user_groups" edge to the UserGroupUser entity. +func (m *UserGroupMutation) ClearUserGroups() { + m.cleareduser_groups = true } -// SetDeletedAt sets the "deleted_at" field. -func (m *UserMutation) SetDeletedAt(t time.Time) { - m.deleted_at = &t +// UserGroupsCleared reports if the "user_groups" edge to the UserGroupUser entity was cleared. +func (m *UserGroupMutation) UserGroupsCleared() bool { + return m.cleareduser_groups } -// DeletedAt returns the value of the "deleted_at" field in the mutation. -func (m *UserMutation) DeletedAt() (r time.Time, exists bool) { - v := m.deleted_at - if v == nil { - return +// RemoveUserGroupIDs removes the "user_groups" edge to the UserGroupUser entity by IDs. +func (m *UserGroupMutation) RemoveUserGroupIDs(ids ...uuid.UUID) { + if m.removeduser_groups == nil { + m.removeduser_groups = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.user_groups, ids[i]) + m.removeduser_groups[ids[i]] = struct{}{} } - return *v, true } -// OldDeletedAt returns the old "deleted_at" field's value of the User entity. -// If the User 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 *UserMutation) OldDeletedAt(ctx context.Context) (v time.Time, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldDeletedAt is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldDeletedAt requires an ID field in the mutation") +// RemovedUserGroups returns the removed IDs of the "user_groups" edge to the UserGroupUser entity. +func (m *UserGroupMutation) RemovedUserGroupsIDs() (ids []uuid.UUID) { + for id := range m.removeduser_groups { + ids = append(ids, id) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldDeletedAt: %w", err) + return +} + +// UserGroupsIDs returns the "user_groups" edge IDs in the mutation. +func (m *UserGroupMutation) UserGroupsIDs() (ids []uuid.UUID) { + for id := range m.user_groups { + ids = append(ids, id) } - return oldValue.DeletedAt, nil + return } -// ClearDeletedAt clears the value of the "deleted_at" field. -func (m *UserMutation) ClearDeletedAt() { - m.deleted_at = nil - m.clearedFields[user.FieldDeletedAt] = struct{}{} +// ResetUserGroups resets all changes to the "user_groups" edge. +func (m *UserGroupMutation) ResetUserGroups() { + m.user_groups = nil + m.cleareduser_groups = false + m.removeduser_groups = nil } -// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. -func (m *UserMutation) DeletedAtCleared() bool { - _, ok := m.clearedFields[user.FieldDeletedAt] - return ok +// AddUserGroupAdminIDs adds the "user_group_admins" edge to the UserGroupAdmin entity by ids. +func (m *UserGroupMutation) AddUserGroupAdminIDs(ids ...uuid.UUID) { + if m.user_group_admins == nil { + m.user_group_admins = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.user_group_admins[ids[i]] = struct{}{} + } } -// ResetDeletedAt resets all changes to the "deleted_at" field. -func (m *UserMutation) ResetDeletedAt() { - m.deleted_at = nil - delete(m.clearedFields, user.FieldDeletedAt) +// ClearUserGroupAdmins clears the "user_group_admins" edge to the UserGroupAdmin entity. +func (m *UserGroupMutation) ClearUserGroupAdmins() { + m.cleareduser_group_admins = true } -// SetUsername sets the "username" field. -func (m *UserMutation) SetUsername(s string) { - m.username = &s +// UserGroupAdminsCleared reports if the "user_group_admins" edge to the UserGroupAdmin entity was cleared. +func (m *UserGroupMutation) UserGroupAdminsCleared() bool { + return m.cleareduser_group_admins } -// Username returns the value of the "username" field in the mutation. -func (m *UserMutation) Username() (r string, exists bool) { - v := m.username - if v == nil { - return +// RemoveUserGroupAdminIDs removes the "user_group_admins" edge to the UserGroupAdmin entity by IDs. +func (m *UserGroupMutation) RemoveUserGroupAdminIDs(ids ...uuid.UUID) { + if m.removeduser_group_admins == nil { + m.removeduser_group_admins = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.user_group_admins, ids[i]) + m.removeduser_group_admins[ids[i]] = struct{}{} } - return *v, true } -// OldUsername returns the old "username" field's value of the User entity. -// If the User 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 *UserMutation) OldUsername(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldUsername is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldUsername requires an ID field in the mutation") +// RemovedUserGroupAdmins returns the removed IDs of the "user_group_admins" edge to the UserGroupAdmin entity. +func (m *UserGroupMutation) RemovedUserGroupAdminsIDs() (ids []uuid.UUID) { + for id := range m.removeduser_group_admins { + ids = append(ids, id) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldUsername: %w", err) + return +} + +// UserGroupAdminsIDs returns the "user_group_admins" edge IDs in the mutation. +func (m *UserGroupMutation) UserGroupAdminsIDs() (ids []uuid.UUID) { + for id := range m.user_group_admins { + ids = append(ids, id) } - return oldValue.Username, nil + return } -// ClearUsername clears the value of the "username" field. -func (m *UserMutation) ClearUsername() { - m.username = nil - m.clearedFields[user.FieldUsername] = struct{}{} +// ResetUserGroupAdmins resets all changes to the "user_group_admins" edge. +func (m *UserGroupMutation) ResetUserGroupAdmins() { + m.user_group_admins = nil + m.cleareduser_group_admins = false + m.removeduser_group_admins = nil } -// UsernameCleared returns if the "username" field was cleared in this mutation. -func (m *UserMutation) UsernameCleared() bool { - _, ok := m.clearedFields[user.FieldUsername] - return ok +// Where appends a list predicates to the UserGroupMutation builder. +func (m *UserGroupMutation) Where(ps ...predicate.UserGroup) { + m.predicates = append(m.predicates, ps...) } -// ResetUsername resets all changes to the "username" field. -func (m *UserMutation) ResetUsername() { - m.username = nil - delete(m.clearedFields, user.FieldUsername) +// WhereP appends storage-level predicates to the UserGroupMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *UserGroupMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.UserGroup, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) } -// SetPassword sets the "password" field. -func (m *UserMutation) SetPassword(s string) { - m.password = &s +// Op returns the operation name. +func (m *UserGroupMutation) Op() Op { + return m.op } -// Password returns the value of the "password" field in the mutation. -func (m *UserMutation) Password() (r string, exists bool) { - v := m.password - if v == nil { - return +// SetOp allows setting the mutation operation. +func (m *UserGroupMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (UserGroup). +func (m *UserGroupMutation) 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 *UserGroupMutation) Fields() []string { + fields := make([]string, 0, 3) + if m.owner != nil { + fields = append(fields, usergroup.FieldAdminID) } - return *v, true + if m.name != nil { + fields = append(fields, usergroup.FieldName) + } + if m.created_at != nil { + fields = append(fields, usergroup.FieldCreatedAt) + } + return fields } -// OldPassword returns the old "password" field's value of the User entity. -// If the User 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 *UserMutation) OldPassword(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldPassword is only allowed on UpdateOne operations") +// 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 *UserGroupMutation) Field(name string) (ent.Value, bool) { + switch name { + case usergroup.FieldAdminID: + return m.AdminID() + case usergroup.FieldName: + return m.Name() + case usergroup.FieldCreatedAt: + return m.CreatedAt() } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldPassword requires an ID field in the mutation") + 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 *UserGroupMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case usergroup.FieldAdminID: + return m.OldAdminID(ctx) + case usergroup.FieldName: + return m.OldName(ctx) + case usergroup.FieldCreatedAt: + return m.OldCreatedAt(ctx) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldPassword: %w", err) + return nil, fmt.Errorf("unknown UserGroup 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 *UserGroupMutation) SetField(name string, value ent.Value) error { + switch name { + case usergroup.FieldAdminID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAdminID(v) + return nil + case usergroup.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case usergroup.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 oldValue.Password, nil + return fmt.Errorf("unknown UserGroup field %s", name) } -// ClearPassword clears the value of the "password" field. -func (m *UserMutation) ClearPassword() { - m.password = nil - m.clearedFields[user.FieldPassword] = struct{}{} +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *UserGroupMutation) AddedFields() []string { + return nil } -// PasswordCleared returns if the "password" field was cleared in this mutation. -func (m *UserMutation) PasswordCleared() bool { - _, ok := m.clearedFields[user.FieldPassword] - return ok +// 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 *UserGroupMutation) AddedField(name string) (ent.Value, bool) { + return nil, false } -// ResetPassword resets all changes to the "password" field. -func (m *UserMutation) ResetPassword() { - m.password = nil - delete(m.clearedFields, user.FieldPassword) +// 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 *UserGroupMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown UserGroup numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *UserGroupMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *UserGroupMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok } -// SetEmail sets the "email" field. -func (m *UserMutation) SetEmail(s string) { - m.email = &s +// 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 *UserGroupMutation) ClearField(name string) error { + return fmt.Errorf("unknown UserGroup nullable field %s", name) } -// Email returns the value of the "email" field in the mutation. -func (m *UserMutation) Email() (r string, exists bool) { - v := m.email - if v == nil { - return +// 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 *UserGroupMutation) ResetField(name string) error { + switch name { + case usergroup.FieldAdminID: + m.ResetAdminID() + return nil + case usergroup.FieldName: + m.ResetName() + return nil + case usergroup.FieldCreatedAt: + m.ResetCreatedAt() + return nil } - return *v, true + return fmt.Errorf("unknown UserGroup field %s", name) } -// OldEmail returns the old "email" field's value of the User entity. -// If the User 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 *UserMutation) OldEmail(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldEmail is only allowed on UpdateOne operations") +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *UserGroupMutation) AddedEdges() []string { + edges := make([]string, 0, 5) + if m.owner != nil { + edges = append(edges, usergroup.EdgeOwner) } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldEmail requires an ID field in the mutation") + if m.users != nil { + edges = append(edges, usergroup.EdgeUsers) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldEmail: %w", err) + if m.admins != nil { + edges = append(edges, usergroup.EdgeAdmins) } - return oldValue.Email, nil -} - -// ClearEmail clears the value of the "email" field. -func (m *UserMutation) ClearEmail() { - m.email = nil - m.clearedFields[user.FieldEmail] = struct{}{} -} - -// EmailCleared returns if the "email" field was cleared in this mutation. -func (m *UserMutation) EmailCleared() bool { - _, ok := m.clearedFields[user.FieldEmail] - return ok + if m.user_groups != nil { + edges = append(edges, usergroup.EdgeUserGroups) + } + if m.user_group_admins != nil { + edges = append(edges, usergroup.EdgeUserGroupAdmins) + } + return edges } -// ResetEmail resets all changes to the "email" field. -func (m *UserMutation) ResetEmail() { - m.email = nil - delete(m.clearedFields, user.FieldEmail) +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *UserGroupMutation) AddedIDs(name string) []ent.Value { + switch name { + case usergroup.EdgeOwner: + if id := m.owner; id != nil { + return []ent.Value{*id} + } + case usergroup.EdgeUsers: + ids := make([]ent.Value, 0, len(m.users)) + for id := range m.users { + ids = append(ids, id) + } + return ids + case usergroup.EdgeAdmins: + ids := make([]ent.Value, 0, len(m.admins)) + for id := range m.admins { + ids = append(ids, id) + } + return ids + case usergroup.EdgeUserGroups: + ids := make([]ent.Value, 0, len(m.user_groups)) + for id := range m.user_groups { + ids = append(ids, id) + } + return ids + case usergroup.EdgeUserGroupAdmins: + ids := make([]ent.Value, 0, len(m.user_group_admins)) + for id := range m.user_group_admins { + ids = append(ids, id) + } + return ids + } + return nil } -// SetAvatarURL sets the "avatar_url" field. -func (m *UserMutation) SetAvatarURL(s string) { - m.avatar_url = &s +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *UserGroupMutation) RemovedEdges() []string { + edges := make([]string, 0, 5) + if m.removedusers != nil { + edges = append(edges, usergroup.EdgeUsers) + } + if m.removedadmins != nil { + edges = append(edges, usergroup.EdgeAdmins) + } + if m.removeduser_groups != nil { + edges = append(edges, usergroup.EdgeUserGroups) + } + if m.removeduser_group_admins != nil { + edges = append(edges, usergroup.EdgeUserGroupAdmins) + } + return edges } -// AvatarURL returns the value of the "avatar_url" field in the mutation. -func (m *UserMutation) AvatarURL() (r string, exists bool) { - v := m.avatar_url - if v == nil { - return +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *UserGroupMutation) RemovedIDs(name string) []ent.Value { + switch name { + case usergroup.EdgeUsers: + ids := make([]ent.Value, 0, len(m.removedusers)) + for id := range m.removedusers { + ids = append(ids, id) + } + return ids + case usergroup.EdgeAdmins: + ids := make([]ent.Value, 0, len(m.removedadmins)) + for id := range m.removedadmins { + ids = append(ids, id) + } + return ids + case usergroup.EdgeUserGroups: + ids := make([]ent.Value, 0, len(m.removeduser_groups)) + for id := range m.removeduser_groups { + ids = append(ids, id) + } + return ids + case usergroup.EdgeUserGroupAdmins: + ids := make([]ent.Value, 0, len(m.removeduser_group_admins)) + for id := range m.removeduser_group_admins { + ids = append(ids, id) + } + return ids } - return *v, true + return nil } -// OldAvatarURL returns the old "avatar_url" field's value of the User entity. -// If the User 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 *UserMutation) OldAvatarURL(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldAvatarURL is only allowed on UpdateOne operations") +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *UserGroupMutation) ClearedEdges() []string { + edges := make([]string, 0, 5) + if m.clearedowner { + edges = append(edges, usergroup.EdgeOwner) } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldAvatarURL requires an ID field in the mutation") + if m.clearedusers { + edges = append(edges, usergroup.EdgeUsers) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldAvatarURL: %w", err) + if m.clearedadmins { + edges = append(edges, usergroup.EdgeAdmins) } - return oldValue.AvatarURL, nil + if m.cleareduser_groups { + edges = append(edges, usergroup.EdgeUserGroups) + } + if m.cleareduser_group_admins { + edges = append(edges, usergroup.EdgeUserGroupAdmins) + } + return edges } -// ClearAvatarURL clears the value of the "avatar_url" field. -func (m *UserMutation) ClearAvatarURL() { - m.avatar_url = nil - m.clearedFields[user.FieldAvatarURL] = struct{}{} +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *UserGroupMutation) EdgeCleared(name string) bool { + switch name { + case usergroup.EdgeOwner: + return m.clearedowner + case usergroup.EdgeUsers: + return m.clearedusers + case usergroup.EdgeAdmins: + return m.clearedadmins + case usergroup.EdgeUserGroups: + return m.cleareduser_groups + case usergroup.EdgeUserGroupAdmins: + return m.cleareduser_group_admins + } + return false } -// AvatarURLCleared returns if the "avatar_url" field was cleared in this mutation. -func (m *UserMutation) AvatarURLCleared() bool { - _, ok := m.clearedFields[user.FieldAvatarURL] - return ok +// 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 *UserGroupMutation) ClearEdge(name string) error { + switch name { + case usergroup.EdgeOwner: + m.ClearOwner() + return nil + } + return fmt.Errorf("unknown UserGroup unique edge %s", name) } -// ResetAvatarURL resets all changes to the "avatar_url" field. -func (m *UserMutation) ResetAvatarURL() { - m.avatar_url = nil - delete(m.clearedFields, user.FieldAvatarURL) +// 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 *UserGroupMutation) ResetEdge(name string) error { + switch name { + case usergroup.EdgeOwner: + m.ResetOwner() + return nil + case usergroup.EdgeUsers: + m.ResetUsers() + return nil + case usergroup.EdgeAdmins: + m.ResetAdmins() + return nil + case usergroup.EdgeUserGroups: + m.ResetUserGroups() + return nil + case usergroup.EdgeUserGroupAdmins: + m.ResetUserGroupAdmins() + return nil + } + return fmt.Errorf("unknown UserGroup edge %s", name) } -// SetPlatform sets the "platform" field. -func (m *UserMutation) SetPlatform(cp consts.UserPlatform) { - m.platform = &cp +// UserGroupAdminMutation represents an operation that mutates the UserGroupAdmin nodes in the graph. +type UserGroupAdminMutation struct { + config + op Op + typ string + id *uuid.UUID + clearedFields map[string]struct{} + user_group *uuid.UUID + cleareduser_group bool + admin *uuid.UUID + clearedadmin bool + done bool + oldValue func(context.Context) (*UserGroupAdmin, error) + predicates []predicate.UserGroupAdmin } -// Platform returns the value of the "platform" field in the mutation. -func (m *UserMutation) Platform() (r consts.UserPlatform, exists bool) { - v := m.platform - if v == nil { - return - } - return *v, true -} +var _ ent.Mutation = (*UserGroupAdminMutation)(nil) -// OldPlatform returns the old "platform" field's value of the User entity. -// If the User 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 *UserMutation) OldPlatform(ctx context.Context) (v consts.UserPlatform, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldPlatform is only allowed on UpdateOne operations") +// usergroupadminOption allows management of the mutation configuration using functional options. +type usergroupadminOption func(*UserGroupAdminMutation) + +// newUserGroupAdminMutation creates new mutation for the UserGroupAdmin entity. +func newUserGroupAdminMutation(c config, op Op, opts ...usergroupadminOption) *UserGroupAdminMutation { + m := &UserGroupAdminMutation{ + config: c, + op: op, + typ: TypeUserGroupAdmin, + clearedFields: make(map[string]struct{}), } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldPlatform requires an ID field in the mutation") + for _, opt := range opts { + opt(m) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldPlatform: %w", err) + return m +} + +// withUserGroupAdminID sets the ID field of the mutation. +func withUserGroupAdminID(id uuid.UUID) usergroupadminOption { + return func(m *UserGroupAdminMutation) { + var ( + err error + once sync.Once + value *UserGroupAdmin + ) + m.oldValue = func(ctx context.Context) (*UserGroupAdmin, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().UserGroupAdmin.Get(ctx, id) + } + }) + return value, err + } + m.id = &id } - return oldValue.Platform, nil } -// ResetPlatform resets all changes to the "platform" field. -func (m *UserMutation) ResetPlatform() { - m.platform = nil +// withUserGroupAdmin sets the old UserGroupAdmin of the mutation. +func withUserGroupAdmin(node *UserGroupAdmin) usergroupadminOption { + return func(m *UserGroupAdminMutation) { + m.oldValue = func(context.Context) (*UserGroupAdmin, error) { + return node, nil + } + m.id = &node.ID + } } -// SetStatus sets the "status" field. -func (m *UserMutation) SetStatus(cs consts.UserStatus) { - m.status = &cs +// 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 UserGroupAdminMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client } -// Status returns the value of the "status" field in the mutation. -func (m *UserMutation) Status() (r consts.UserStatus, exists bool) { - v := m.status - if v == nil { - return +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m UserGroupAdminMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("db: mutation is not running in a transaction") } - return *v, true + tx := &Tx{config: m.config} + tx.init() + return tx, nil } -// OldStatus returns the old "status" field's value of the User entity. -// If the User 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 *UserMutation) OldStatus(ctx context.Context) (v consts.UserStatus, 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) +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of UserGroupAdmin entities. +func (m *UserGroupAdminMutation) 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 *UserGroupAdminMutation) ID() (id uuid.UUID, exists bool) { + if m.id == nil { + return } - return oldValue.Status, nil + return *m.id, true } -// ResetStatus resets all changes to the "status" field. -func (m *UserMutation) ResetStatus() { - m.status = nil +// 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 *UserGroupAdminMutation) 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().UserGroupAdmin.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } } -// SetCreatedAt sets the "created_at" field. -func (m *UserMutation) SetCreatedAt(t time.Time) { - m.created_at = &t +// SetUserGroupID sets the "user_group_id" field. +func (m *UserGroupAdminMutation) SetUserGroupID(u uuid.UUID) { + m.user_group = &u } -// CreatedAt returns the value of the "created_at" field in the mutation. -func (m *UserMutation) CreatedAt() (r time.Time, exists bool) { - v := m.created_at +// UserGroupID returns the value of the "user_group_id" field in the mutation. +func (m *UserGroupAdminMutation) UserGroupID() (r uuid.UUID, exists bool) { + v := m.user_group if v == nil { return } return *v, true } -// OldCreatedAt returns the old "created_at" field's value of the User entity. -// If the User object wasn't provided to the builder, the object is fetched from the database. +// OldUserGroupID returns the old "user_group_id" field's value of the UserGroupAdmin entity. +// If the UserGroupAdmin 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 *UserMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { +func (m *UserGroupAdminMutation) OldUserGroupID(ctx context.Context) (v uuid.UUID, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") + return v, errors.New("OldUserGroupID 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") + return v, errors.New("OldUserGroupID 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 v, fmt.Errorf("querying old value for OldUserGroupID: %w", err) } - return oldValue.CreatedAt, nil + return oldValue.UserGroupID, nil } -// ResetCreatedAt resets all changes to the "created_at" field. -func (m *UserMutation) ResetCreatedAt() { - m.created_at = nil +// ResetUserGroupID resets all changes to the "user_group_id" field. +func (m *UserGroupAdminMutation) ResetUserGroupID() { + m.user_group = nil } -// SetUpdatedAt sets the "updated_at" field. -func (m *UserMutation) SetUpdatedAt(t time.Time) { - m.updated_at = &t +// SetAdminID sets the "admin_id" field. +func (m *UserGroupAdminMutation) SetAdminID(u uuid.UUID) { + m.admin = &u } -// UpdatedAt returns the value of the "updated_at" field in the mutation. -func (m *UserMutation) UpdatedAt() (r time.Time, exists bool) { - v := m.updated_at +// AdminID returns the value of the "admin_id" field in the mutation. +func (m *UserGroupAdminMutation) AdminID() (r uuid.UUID, exists bool) { + v := m.admin if v == nil { return } return *v, true } -// OldUpdatedAt returns the old "updated_at" field's value of the User entity. -// If the User object wasn't provided to the builder, the object is fetched from the database. +// OldAdminID returns the old "admin_id" field's value of the UserGroupAdmin entity. +// If the UserGroupAdmin 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 *UserMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { +func (m *UserGroupAdminMutation) OldAdminID(ctx context.Context) (v uuid.UUID, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") + return v, errors.New("OldAdminID 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") + return v, errors.New("OldAdminID 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 v, fmt.Errorf("querying old value for OldAdminID: %w", err) } - return oldValue.UpdatedAt, nil + return oldValue.AdminID, nil } -// ResetUpdatedAt resets all changes to the "updated_at" field. -func (m *UserMutation) ResetUpdatedAt() { - m.updated_at = nil +// ResetAdminID resets all changes to the "admin_id" field. +func (m *UserGroupAdminMutation) ResetAdminID() { + m.admin = nil } -// AddLoginHistoryIDs adds the "login_histories" edge to the UserLoginHistory entity by ids. -func (m *UserMutation) AddLoginHistoryIDs(ids ...uuid.UUID) { - if m.login_histories == nil { - m.login_histories = make(map[uuid.UUID]struct{}) - } - for i := range ids { - m.login_histories[ids[i]] = struct{}{} +// ClearUserGroup clears the "user_group" edge to the UserGroup entity. +func (m *UserGroupAdminMutation) ClearUserGroup() { + m.cleareduser_group = true + m.clearedFields[usergroupadmin.FieldUserGroupID] = struct{}{} +} + +// UserGroupCleared reports if the "user_group" edge to the UserGroup entity was cleared. +func (m *UserGroupAdminMutation) UserGroupCleared() bool { + return m.cleareduser_group +} + +// UserGroupIDs returns the "user_group" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// UserGroupID instead. It exists only for internal usage by the builders. +func (m *UserGroupAdminMutation) UserGroupIDs() (ids []uuid.UUID) { + if id := m.user_group; id != nil { + ids = append(ids, *id) } + return } -// ClearLoginHistories clears the "login_histories" edge to the UserLoginHistory entity. -func (m *UserMutation) ClearLoginHistories() { - m.clearedlogin_histories = true +// ResetUserGroup resets all changes to the "user_group" edge. +func (m *UserGroupAdminMutation) ResetUserGroup() { + m.user_group = nil + m.cleareduser_group = false } -// LoginHistoriesCleared reports if the "login_histories" edge to the UserLoginHistory entity was cleared. -func (m *UserMutation) LoginHistoriesCleared() bool { - return m.clearedlogin_histories +// ClearAdmin clears the "admin" edge to the Admin entity. +func (m *UserGroupAdminMutation) ClearAdmin() { + m.clearedadmin = true + m.clearedFields[usergroupadmin.FieldAdminID] = struct{}{} } -// RemoveLoginHistoryIDs removes the "login_histories" edge to the UserLoginHistory entity by IDs. -func (m *UserMutation) RemoveLoginHistoryIDs(ids ...uuid.UUID) { - if m.removedlogin_histories == nil { - m.removedlogin_histories = make(map[uuid.UUID]struct{}) - } - for i := range ids { - delete(m.login_histories, ids[i]) - m.removedlogin_histories[ids[i]] = struct{}{} - } +// AdminCleared reports if the "admin" edge to the Admin entity was cleared. +func (m *UserGroupAdminMutation) AdminCleared() bool { + return m.clearedadmin } -// RemovedLoginHistories returns the removed IDs of the "login_histories" edge to the UserLoginHistory entity. -func (m *UserMutation) RemovedLoginHistoriesIDs() (ids []uuid.UUID) { - for id := range m.removedlogin_histories { - ids = append(ids, id) +// AdminIDs returns the "admin" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// AdminID instead. It exists only for internal usage by the builders. +func (m *UserGroupAdminMutation) AdminIDs() (ids []uuid.UUID) { + if id := m.admin; id != nil { + ids = append(ids, *id) } return } -// LoginHistoriesIDs returns the "login_histories" edge IDs in the mutation. -func (m *UserMutation) LoginHistoriesIDs() (ids []uuid.UUID) { - for id := range m.login_histories { - ids = append(ids, id) - } - return +// ResetAdmin resets all changes to the "admin" edge. +func (m *UserGroupAdminMutation) ResetAdmin() { + m.admin = nil + m.clearedadmin = false } -// ResetLoginHistories resets all changes to the "login_histories" edge. -func (m *UserMutation) ResetLoginHistories() { - m.login_histories = nil - m.clearedlogin_histories = false - m.removedlogin_histories = nil +// Where appends a list predicates to the UserGroupAdminMutation builder. +func (m *UserGroupAdminMutation) Where(ps ...predicate.UserGroupAdmin) { + m.predicates = append(m.predicates, ps...) } -// AddModelIDs adds the "models" edge to the Model entity by ids. -func (m *UserMutation) AddModelIDs(ids ...uuid.UUID) { - if m.models == nil { - m.models = make(map[uuid.UUID]struct{}) - } - for i := range ids { - m.models[ids[i]] = struct{}{} +// WhereP appends storage-level predicates to the UserGroupAdminMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *UserGroupAdminMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.UserGroupAdmin, len(ps)) + for i := range ps { + p[i] = ps[i] } + m.Where(p...) } -// ClearModels clears the "models" edge to the Model entity. -func (m *UserMutation) ClearModels() { - m.clearedmodels = true +// Op returns the operation name. +func (m *UserGroupAdminMutation) Op() Op { + return m.op } -// ModelsCleared reports if the "models" edge to the Model entity was cleared. -func (m *UserMutation) ModelsCleared() bool { - return m.clearedmodels +// SetOp allows setting the mutation operation. +func (m *UserGroupAdminMutation) SetOp(op Op) { + m.op = op } -// RemoveModelIDs removes the "models" edge to the Model entity by IDs. -func (m *UserMutation) RemoveModelIDs(ids ...uuid.UUID) { - if m.removedmodels == nil { - m.removedmodels = make(map[uuid.UUID]struct{}) - } - for i := range ids { - delete(m.models, ids[i]) - m.removedmodels[ids[i]] = struct{}{} - } +// Type returns the node type of this mutation (UserGroupAdmin). +func (m *UserGroupAdminMutation) Type() string { + return m.typ } -// RemovedModels returns the removed IDs of the "models" edge to the Model entity. -func (m *UserMutation) RemovedModelsIDs() (ids []uuid.UUID) { - for id := range m.removedmodels { - ids = append(ids, id) +// 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 *UserGroupAdminMutation) Fields() []string { + fields := make([]string, 0, 2) + if m.user_group != nil { + fields = append(fields, usergroupadmin.FieldUserGroupID) } - return + if m.admin != nil { + fields = append(fields, usergroupadmin.FieldAdminID) + } + return fields } -// ModelsIDs returns the "models" edge IDs in the mutation. -func (m *UserMutation) ModelsIDs() (ids []uuid.UUID) { - for id := range m.models { - ids = append(ids, id) +// 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 *UserGroupAdminMutation) Field(name string) (ent.Value, bool) { + switch name { + case usergroupadmin.FieldUserGroupID: + return m.UserGroupID() + case usergroupadmin.FieldAdminID: + return m.AdminID() } - return + return nil, false } -// ResetModels resets all changes to the "models" edge. -func (m *UserMutation) ResetModels() { - m.models = nil - m.clearedmodels = false - m.removedmodels = nil +// 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 *UserGroupAdminMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case usergroupadmin.FieldUserGroupID: + return m.OldUserGroupID(ctx) + case usergroupadmin.FieldAdminID: + return m.OldAdminID(ctx) + } + return nil, fmt.Errorf("unknown UserGroupAdmin field %s", name) } -// AddTaskIDs adds the "tasks" edge to the Task entity by ids. -func (m *UserMutation) AddTaskIDs(ids ...uuid.UUID) { - if m.tasks == nil { - m.tasks = make(map[uuid.UUID]struct{}) - } - for i := range ids { - m.tasks[ids[i]] = struct{}{} +// 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 *UserGroupAdminMutation) SetField(name string, value ent.Value) error { + switch name { + case usergroupadmin.FieldUserGroupID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUserGroupID(v) + return nil + case usergroupadmin.FieldAdminID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAdminID(v) + return nil } + return fmt.Errorf("unknown UserGroupAdmin field %s", name) } -// ClearTasks clears the "tasks" edge to the Task entity. -func (m *UserMutation) ClearTasks() { - m.clearedtasks = true +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *UserGroupAdminMutation) AddedFields() []string { + return nil } -// TasksCleared reports if the "tasks" edge to the Task entity was cleared. -func (m *UserMutation) TasksCleared() bool { - return m.clearedtasks +// 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 *UserGroupAdminMutation) AddedField(name string) (ent.Value, bool) { + return nil, false } -// RemoveTaskIDs removes the "tasks" edge to the Task entity by IDs. -func (m *UserMutation) RemoveTaskIDs(ids ...uuid.UUID) { - if m.removedtasks == nil { - m.removedtasks = make(map[uuid.UUID]struct{}) - } - for i := range ids { - delete(m.tasks, ids[i]) - m.removedtasks[ids[i]] = struct{}{} +// 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 *UserGroupAdminMutation) AddField(name string, value ent.Value) error { + switch name { } + return fmt.Errorf("unknown UserGroupAdmin numeric field %s", name) } -// RemovedTasks returns the removed IDs of the "tasks" edge to the Task entity. -func (m *UserMutation) RemovedTasksIDs() (ids []uuid.UUID) { - for id := range m.removedtasks { - ids = append(ids, id) - } - return +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *UserGroupAdminMutation) ClearedFields() []string { + return nil } -// TasksIDs returns the "tasks" edge IDs in the mutation. -func (m *UserMutation) TasksIDs() (ids []uuid.UUID) { - for id := range m.tasks { - ids = append(ids, id) +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *UserGroupAdminMutation) 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 *UserGroupAdminMutation) ClearField(name string) error { + return fmt.Errorf("unknown UserGroupAdmin 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 *UserGroupAdminMutation) ResetField(name string) error { + switch name { + case usergroupadmin.FieldUserGroupID: + m.ResetUserGroupID() + return nil + case usergroupadmin.FieldAdminID: + m.ResetAdminID() + return nil } - return + return fmt.Errorf("unknown UserGroupAdmin field %s", name) } -// ResetTasks resets all changes to the "tasks" edge. -func (m *UserMutation) ResetTasks() { - m.tasks = nil - m.clearedtasks = false - m.removedtasks = nil +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *UserGroupAdminMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.user_group != nil { + edges = append(edges, usergroupadmin.EdgeUserGroup) + } + if m.admin != nil { + edges = append(edges, usergroupadmin.EdgeAdmin) + } + return edges } -// AddIdentityIDs adds the "identities" edge to the UserIdentity entity by ids. -func (m *UserMutation) AddIdentityIDs(ids ...uuid.UUID) { - if m.identities == nil { - m.identities = make(map[uuid.UUID]struct{}) - } - for i := range ids { - m.identities[ids[i]] = struct{}{} +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *UserGroupAdminMutation) AddedIDs(name string) []ent.Value { + switch name { + case usergroupadmin.EdgeUserGroup: + if id := m.user_group; id != nil { + return []ent.Value{*id} + } + case usergroupadmin.EdgeAdmin: + if id := m.admin; id != nil { + return []ent.Value{*id} + } } + return nil } -// ClearIdentities clears the "identities" edge to the UserIdentity entity. -func (m *UserMutation) ClearIdentities() { - m.clearedidentities = true +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *UserGroupAdminMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + return edges } -// IdentitiesCleared reports if the "identities" edge to the UserIdentity entity was cleared. -func (m *UserMutation) IdentitiesCleared() bool { - return m.clearedidentities +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *UserGroupAdminMutation) RemovedIDs(name string) []ent.Value { + return nil } -// RemoveIdentityIDs removes the "identities" edge to the UserIdentity entity by IDs. -func (m *UserMutation) RemoveIdentityIDs(ids ...uuid.UUID) { - if m.removedidentities == nil { - m.removedidentities = make(map[uuid.UUID]struct{}) +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *UserGroupAdminMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.cleareduser_group { + edges = append(edges, usergroupadmin.EdgeUserGroup) } - for i := range ids { - delete(m.identities, ids[i]) - m.removedidentities[ids[i]] = struct{}{} + if m.clearedadmin { + edges = append(edges, usergroupadmin.EdgeAdmin) } + return edges } -// RemovedIdentities returns the removed IDs of the "identities" edge to the UserIdentity entity. -func (m *UserMutation) RemovedIdentitiesIDs() (ids []uuid.UUID) { - for id := range m.removedidentities { - ids = append(ids, id) +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *UserGroupAdminMutation) EdgeCleared(name string) bool { + switch name { + case usergroupadmin.EdgeUserGroup: + return m.cleareduser_group + case usergroupadmin.EdgeAdmin: + return m.clearedadmin } - return + return false } -// IdentitiesIDs returns the "identities" edge IDs in the mutation. -func (m *UserMutation) IdentitiesIDs() (ids []uuid.UUID) { - for id := range m.identities { - ids = append(ids, id) +// 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 *UserGroupAdminMutation) ClearEdge(name string) error { + switch name { + case usergroupadmin.EdgeUserGroup: + m.ClearUserGroup() + return nil + case usergroupadmin.EdgeAdmin: + m.ClearAdmin() + return nil } - return -} - -// ResetIdentities resets all changes to the "identities" edge. -func (m *UserMutation) ResetIdentities() { - m.identities = nil - m.clearedidentities = false - m.removedidentities = nil + return fmt.Errorf("unknown UserGroupAdmin unique edge %s", name) } -// AddWorkspaceIDs adds the "workspaces" edge to the Workspace entity by ids. -func (m *UserMutation) AddWorkspaceIDs(ids ...uuid.UUID) { - if m.workspaces == nil { - m.workspaces = make(map[uuid.UUID]struct{}) - } - for i := range ids { - m.workspaces[ids[i]] = struct{}{} +// 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 *UserGroupAdminMutation) ResetEdge(name string) error { + switch name { + case usergroupadmin.EdgeUserGroup: + m.ResetUserGroup() + return nil + case usergroupadmin.EdgeAdmin: + m.ResetAdmin() + return nil } + return fmt.Errorf("unknown UserGroupAdmin edge %s", name) } -// ClearWorkspaces clears the "workspaces" edge to the Workspace entity. -func (m *UserMutation) ClearWorkspaces() { - m.clearedworkspaces = true +// UserGroupUserMutation represents an operation that mutates the UserGroupUser nodes in the graph. +type UserGroupUserMutation struct { + config + op Op + typ string + id *uuid.UUID + clearedFields map[string]struct{} + user_group *uuid.UUID + cleareduser_group bool + user *uuid.UUID + cleareduser bool + done bool + oldValue func(context.Context) (*UserGroupUser, error) + predicates []predicate.UserGroupUser } -// WorkspacesCleared reports if the "workspaces" edge to the Workspace entity was cleared. -func (m *UserMutation) WorkspacesCleared() bool { - return m.clearedworkspaces -} +var _ ent.Mutation = (*UserGroupUserMutation)(nil) -// RemoveWorkspaceIDs removes the "workspaces" edge to the Workspace entity by IDs. -func (m *UserMutation) RemoveWorkspaceIDs(ids ...uuid.UUID) { - if m.removedworkspaces == nil { - m.removedworkspaces = make(map[uuid.UUID]struct{}) +// usergroupuserOption allows management of the mutation configuration using functional options. +type usergroupuserOption func(*UserGroupUserMutation) + +// newUserGroupUserMutation creates new mutation for the UserGroupUser entity. +func newUserGroupUserMutation(c config, op Op, opts ...usergroupuserOption) *UserGroupUserMutation { + m := &UserGroupUserMutation{ + config: c, + op: op, + typ: TypeUserGroupUser, + clearedFields: make(map[string]struct{}), } - for i := range ids { - delete(m.workspaces, ids[i]) - m.removedworkspaces[ids[i]] = struct{}{} + for _, opt := range opts { + opt(m) } + return m } -// RemovedWorkspaces returns the removed IDs of the "workspaces" edge to the Workspace entity. -func (m *UserMutation) RemovedWorkspacesIDs() (ids []uuid.UUID) { - for id := range m.removedworkspaces { - ids = append(ids, id) +// withUserGroupUserID sets the ID field of the mutation. +func withUserGroupUserID(id uuid.UUID) usergroupuserOption { + return func(m *UserGroupUserMutation) { + var ( + err error + once sync.Once + value *UserGroupUser + ) + m.oldValue = func(ctx context.Context) (*UserGroupUser, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().UserGroupUser.Get(ctx, id) + } + }) + return value, err + } + m.id = &id } - return } -// WorkspacesIDs returns the "workspaces" edge IDs in the mutation. -func (m *UserMutation) WorkspacesIDs() (ids []uuid.UUID) { - for id := range m.workspaces { - ids = append(ids, id) +// withUserGroupUser sets the old UserGroupUser of the mutation. +func withUserGroupUser(node *UserGroupUser) usergroupuserOption { + return func(m *UserGroupUserMutation) { + m.oldValue = func(context.Context) (*UserGroupUser, error) { + return node, nil + } + m.id = &node.ID } - return } -// ResetWorkspaces resets all changes to the "workspaces" edge. -func (m *UserMutation) ResetWorkspaces() { - m.workspaces = nil - m.clearedworkspaces = false - m.removedworkspaces = nil +// 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 UserGroupUserMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client } -// AddWorkspaceFileIDs adds the "workspace_files" edge to the WorkspaceFile entity by ids. -func (m *UserMutation) AddWorkspaceFileIDs(ids ...uuid.UUID) { - if m.workspace_files == nil { - m.workspace_files = make(map[uuid.UUID]struct{}) - } - for i := range ids { - m.workspace_files[ids[i]] = struct{}{} +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m UserGroupUserMutation) 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 } -// ClearWorkspaceFiles clears the "workspace_files" edge to the WorkspaceFile entity. -func (m *UserMutation) ClearWorkspaceFiles() { - m.clearedworkspace_files = true -} - -// WorkspaceFilesCleared reports if the "workspace_files" edge to the WorkspaceFile entity was cleared. -func (m *UserMutation) WorkspaceFilesCleared() bool { - return m.clearedworkspace_files +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of UserGroupUser entities. +func (m *UserGroupUserMutation) SetID(id uuid.UUID) { + m.id = &id } -// RemoveWorkspaceFileIDs removes the "workspace_files" edge to the WorkspaceFile entity by IDs. -func (m *UserMutation) RemoveWorkspaceFileIDs(ids ...uuid.UUID) { - if m.removedworkspace_files == nil { - m.removedworkspace_files = make(map[uuid.UUID]struct{}) - } - for i := range ids { - delete(m.workspace_files, ids[i]) - m.removedworkspace_files[ids[i]] = struct{}{} +// 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 *UserGroupUserMutation) ID() (id uuid.UUID, exists bool) { + if m.id == nil { + return } + return *m.id, true } -// RemovedWorkspaceFiles returns the removed IDs of the "workspace_files" edge to the WorkspaceFile entity. -func (m *UserMutation) RemovedWorkspaceFilesIDs() (ids []uuid.UUID) { - for id := range m.removedworkspace_files { - ids = append(ids, id) +// 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 *UserGroupUserMutation) 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().UserGroupUser.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) } - return } -// WorkspaceFilesIDs returns the "workspace_files" edge IDs in the mutation. -func (m *UserMutation) WorkspaceFilesIDs() (ids []uuid.UUID) { - for id := range m.workspace_files { - ids = append(ids, id) - } - return +// SetUserGroupID sets the "user_group_id" field. +func (m *UserGroupUserMutation) SetUserGroupID(u uuid.UUID) { + m.user_group = &u } -// ResetWorkspaceFiles resets all changes to the "workspace_files" edge. -func (m *UserMutation) ResetWorkspaceFiles() { - m.workspace_files = nil - m.clearedworkspace_files = false - m.removedworkspace_files = nil +// UserGroupID returns the value of the "user_group_id" field in the mutation. +func (m *UserGroupUserMutation) UserGroupID() (r uuid.UUID, exists bool) { + v := m.user_group + if v == nil { + return + } + return *v, true } -// AddAPIKeyIDs adds the "api_keys" edge to the ApiKey entity by ids. -func (m *UserMutation) AddAPIKeyIDs(ids ...uuid.UUID) { - if m.api_keys == nil { - m.api_keys = make(map[uuid.UUID]struct{}) +// OldUserGroupID returns the old "user_group_id" field's value of the UserGroupUser entity. +// If the UserGroupUser 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 *UserGroupUserMutation) OldUserGroupID(ctx context.Context) (v uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUserGroupID is only allowed on UpdateOne operations") } - for i := range ids { - m.api_keys[ids[i]] = struct{}{} + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUserGroupID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUserGroupID: %w", err) } + return oldValue.UserGroupID, nil } -// ClearAPIKeys clears the "api_keys" edge to the ApiKey entity. -func (m *UserMutation) ClearAPIKeys() { - m.clearedapi_keys = true +// ResetUserGroupID resets all changes to the "user_group_id" field. +func (m *UserGroupUserMutation) ResetUserGroupID() { + m.user_group = nil } -// APIKeysCleared reports if the "api_keys" edge to the ApiKey entity was cleared. -func (m *UserMutation) APIKeysCleared() bool { - return m.clearedapi_keys +// SetUserID sets the "user_id" field. +func (m *UserGroupUserMutation) SetUserID(u uuid.UUID) { + m.user = &u } -// RemoveAPIKeyIDs removes the "api_keys" edge to the ApiKey entity by IDs. -func (m *UserMutation) RemoveAPIKeyIDs(ids ...uuid.UUID) { - if m.removedapi_keys == nil { - m.removedapi_keys = make(map[uuid.UUID]struct{}) - } - for i := range ids { - delete(m.api_keys, ids[i]) - m.removedapi_keys[ids[i]] = struct{}{} +// UserID returns the value of the "user_id" field in the mutation. +func (m *UserGroupUserMutation) UserID() (r uuid.UUID, exists bool) { + v := m.user + if v == nil { + return } + return *v, true } -// RemovedAPIKeys returns the removed IDs of the "api_keys" edge to the ApiKey entity. -func (m *UserMutation) RemovedAPIKeysIDs() (ids []uuid.UUID) { - for id := range m.removedapi_keys { - ids = append(ids, id) +// OldUserID returns the old "user_id" field's value of the UserGroupUser entity. +// If the UserGroupUser 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 *UserGroupUserMutation) OldUserID(ctx context.Context) (v uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUserID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUserID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUserID: %w", err) } - return + return oldValue.UserID, nil } -// APIKeysIDs returns the "api_keys" edge IDs in the mutation. -func (m *UserMutation) APIKeysIDs() (ids []uuid.UUID) { - for id := range m.api_keys { - ids = append(ids, id) - } - return +// ResetUserID resets all changes to the "user_id" field. +func (m *UserGroupUserMutation) ResetUserID() { + m.user = nil } -// ResetAPIKeys resets all changes to the "api_keys" edge. -func (m *UserMutation) ResetAPIKeys() { - m.api_keys = nil - m.clearedapi_keys = false - m.removedapi_keys = nil +// ClearUserGroup clears the "user_group" edge to the UserGroup entity. +func (m *UserGroupUserMutation) ClearUserGroup() { + m.cleareduser_group = true + m.clearedFields[usergroupuser.FieldUserGroupID] = struct{}{} } -// AddSecurityScanningIDs adds the "security_scannings" edge to the SecurityScanning entity by ids. -func (m *UserMutation) AddSecurityScanningIDs(ids ...uuid.UUID) { - if m.security_scannings == nil { - m.security_scannings = make(map[uuid.UUID]struct{}) - } - for i := range ids { - m.security_scannings[ids[i]] = struct{}{} - } +// UserGroupCleared reports if the "user_group" edge to the UserGroup entity was cleared. +func (m *UserGroupUserMutation) UserGroupCleared() bool { + return m.cleareduser_group } -// ClearSecurityScannings clears the "security_scannings" edge to the SecurityScanning entity. -func (m *UserMutation) ClearSecurityScannings() { - m.clearedsecurity_scannings = true +// UserGroupIDs returns the "user_group" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// UserGroupID instead. It exists only for internal usage by the builders. +func (m *UserGroupUserMutation) UserGroupIDs() (ids []uuid.UUID) { + if id := m.user_group; id != nil { + ids = append(ids, *id) + } + return } -// SecurityScanningsCleared reports if the "security_scannings" edge to the SecurityScanning entity was cleared. -func (m *UserMutation) SecurityScanningsCleared() bool { - return m.clearedsecurity_scannings +// ResetUserGroup resets all changes to the "user_group" edge. +func (m *UserGroupUserMutation) ResetUserGroup() { + m.user_group = nil + m.cleareduser_group = false } -// RemoveSecurityScanningIDs removes the "security_scannings" edge to the SecurityScanning entity by IDs. -func (m *UserMutation) RemoveSecurityScanningIDs(ids ...uuid.UUID) { - if m.removedsecurity_scannings == nil { - m.removedsecurity_scannings = make(map[uuid.UUID]struct{}) - } - for i := range ids { - delete(m.security_scannings, ids[i]) - m.removedsecurity_scannings[ids[i]] = struct{}{} - } +// ClearUser clears the "user" edge to the User entity. +func (m *UserGroupUserMutation) ClearUser() { + m.cleareduser = true + m.clearedFields[usergroupuser.FieldUserID] = struct{}{} } -// RemovedSecurityScannings returns the removed IDs of the "security_scannings" edge to the SecurityScanning entity. -func (m *UserMutation) RemovedSecurityScanningsIDs() (ids []uuid.UUID) { - for id := range m.removedsecurity_scannings { - ids = append(ids, id) - } - return +// UserCleared reports if the "user" edge to the User entity was cleared. +func (m *UserGroupUserMutation) UserCleared() bool { + return m.cleareduser } -// SecurityScanningsIDs returns the "security_scannings" edge IDs in the mutation. -func (m *UserMutation) SecurityScanningsIDs() (ids []uuid.UUID) { - for id := range m.security_scannings { - ids = append(ids, id) +// UserIDs returns the "user" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// UserID instead. It exists only for internal usage by the builders. +func (m *UserGroupUserMutation) UserIDs() (ids []uuid.UUID) { + if id := m.user; id != nil { + ids = append(ids, *id) } return } -// ResetSecurityScannings resets all changes to the "security_scannings" edge. -func (m *UserMutation) ResetSecurityScannings() { - m.security_scannings = nil - m.clearedsecurity_scannings = false - m.removedsecurity_scannings = nil +// ResetUser resets all changes to the "user" edge. +func (m *UserGroupUserMutation) ResetUser() { + m.user = nil + m.cleareduser = false } -// Where appends a list predicates to the UserMutation builder. -func (m *UserMutation) Where(ps ...predicate.User) { +// Where appends a list predicates to the UserGroupUserMutation builder. +func (m *UserGroupUserMutation) Where(ps ...predicate.UserGroupUser) { m.predicates = append(m.predicates, ps...) } -// WhereP appends storage-level predicates to the UserMutation builder. Using this method, +// WhereP appends storage-level predicates to the UserGroupUserMutation builder. Using this method, // users can use type-assertion to append predicates that do not depend on any generated package. -func (m *UserMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.User, len(ps)) +func (m *UserGroupUserMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.UserGroupUser, len(ps)) for i := range ps { p[i] = ps[i] } @@ -18671,51 +22506,30 @@ func (m *UserMutation) WhereP(ps ...func(*sql.Selector)) { } // Op returns the operation name. -func (m *UserMutation) Op() Op { +func (m *UserGroupUserMutation) Op() Op { return m.op } // SetOp allows setting the mutation operation. -func (m *UserMutation) SetOp(op Op) { +func (m *UserGroupUserMutation) SetOp(op Op) { m.op = op } -// Type returns the node type of this mutation (User). -func (m *UserMutation) Type() string { +// Type returns the node type of this mutation (UserGroupUser). +func (m *UserGroupUserMutation) 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 *UserMutation) Fields() []string { - fields := make([]string, 0, 9) - if m.deleted_at != nil { - fields = append(fields, user.FieldDeletedAt) - } - if m.username != nil { - fields = append(fields, user.FieldUsername) - } - if m.password != nil { - fields = append(fields, user.FieldPassword) - } - if m.email != nil { - fields = append(fields, user.FieldEmail) - } - if m.avatar_url != nil { - fields = append(fields, user.FieldAvatarURL) - } - if m.platform != nil { - fields = append(fields, user.FieldPlatform) - } - if m.status != nil { - fields = append(fields, user.FieldStatus) - } - if m.created_at != nil { - fields = append(fields, user.FieldCreatedAt) +func (m *UserGroupUserMutation) Fields() []string { + fields := make([]string, 0, 2) + if m.user_group != nil { + fields = append(fields, usergroupuser.FieldUserGroupID) } - if m.updated_at != nil { - fields = append(fields, user.FieldUpdatedAt) + if m.user != nil { + fields = append(fields, usergroupuser.FieldUserID) } return fields } @@ -18723,26 +22537,12 @@ func (m *UserMutation) Fields() []string { // 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 *UserMutation) Field(name string) (ent.Value, bool) { +func (m *UserGroupUserMutation) Field(name string) (ent.Value, bool) { switch name { - case user.FieldDeletedAt: - return m.DeletedAt() - case user.FieldUsername: - return m.Username() - case user.FieldPassword: - return m.Password() - case user.FieldEmail: - return m.Email() - case user.FieldAvatarURL: - return m.AvatarURL() - case user.FieldPlatform: - return m.Platform() - case user.FieldStatus: - return m.Status() - case user.FieldCreatedAt: - return m.CreatedAt() - case user.FieldUpdatedAt: - return m.UpdatedAt() + case usergroupuser.FieldUserGroupID: + return m.UserGroupID() + case usergroupuser.FieldUserID: + return m.UserID() } return nil, false } @@ -18750,475 +22550,184 @@ func (m *UserMutation) Field(name string) (ent.Value, bool) { // 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 *UserMutation) OldField(ctx context.Context, name string) (ent.Value, error) { +func (m *UserGroupUserMutation) OldField(ctx context.Context, name string) (ent.Value, error) { switch name { - case user.FieldDeletedAt: - return m.OldDeletedAt(ctx) - case user.FieldUsername: - return m.OldUsername(ctx) - case user.FieldPassword: - return m.OldPassword(ctx) - case user.FieldEmail: - return m.OldEmail(ctx) - case user.FieldAvatarURL: - return m.OldAvatarURL(ctx) - case user.FieldPlatform: - return m.OldPlatform(ctx) - case user.FieldStatus: - return m.OldStatus(ctx) - case user.FieldCreatedAt: - return m.OldCreatedAt(ctx) - case user.FieldUpdatedAt: - return m.OldUpdatedAt(ctx) + case usergroupuser.FieldUserGroupID: + return m.OldUserGroupID(ctx) + case usergroupuser.FieldUserID: + return m.OldUserID(ctx) } - return nil, fmt.Errorf("unknown User field %s", name) + return nil, fmt.Errorf("unknown UserGroupUser 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 *UserMutation) SetField(name string, value ent.Value) error { +func (m *UserGroupUserMutation) SetField(name string, value ent.Value) error { switch name { - case user.FieldDeletedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetDeletedAt(v) - return nil - case user.FieldUsername: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetUsername(v) - return nil - case user.FieldPassword: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetPassword(v) - return nil - case user.FieldEmail: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetEmail(v) - return nil - case user.FieldAvatarURL: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetAvatarURL(v) - return nil - case user.FieldPlatform: - v, ok := value.(consts.UserPlatform) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetPlatform(v) - return nil - case user.FieldStatus: - v, ok := value.(consts.UserStatus) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetStatus(v) - return nil - case user.FieldCreatedAt: - v, ok := value.(time.Time) + case usergroupuser.FieldUserGroupID: + v, ok := value.(uuid.UUID) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetCreatedAt(v) + m.SetUserGroupID(v) return nil - case user.FieldUpdatedAt: - v, ok := value.(time.Time) + case usergroupuser.FieldUserID: + v, ok := value.(uuid.UUID) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetUpdatedAt(v) + m.SetUserID(v) return nil } - return fmt.Errorf("unknown User field %s", name) + return fmt.Errorf("unknown UserGroupUser field %s", name) } // AddedFields returns all numeric fields that were incremented/decremented during // this mutation. -func (m *UserMutation) AddedFields() []string { +func (m *UserGroupUserMutation) 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 *UserMutation) AddedField(name string) (ent.Value, bool) { +func (m *UserGroupUserMutation) 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 *UserMutation) AddField(name string, value ent.Value) error { +func (m *UserGroupUserMutation) AddField(name string, value ent.Value) error { switch name { } - return fmt.Errorf("unknown User numeric field %s", name) + return fmt.Errorf("unknown UserGroupUser numeric field %s", name) } // ClearedFields returns all nullable fields that were cleared during this // mutation. -func (m *UserMutation) ClearedFields() []string { - var fields []string - if m.FieldCleared(user.FieldDeletedAt) { - fields = append(fields, user.FieldDeletedAt) - } - if m.FieldCleared(user.FieldUsername) { - fields = append(fields, user.FieldUsername) - } - if m.FieldCleared(user.FieldPassword) { - fields = append(fields, user.FieldPassword) - } - if m.FieldCleared(user.FieldEmail) { - fields = append(fields, user.FieldEmail) - } - if m.FieldCleared(user.FieldAvatarURL) { - fields = append(fields, user.FieldAvatarURL) - } - return fields +func (m *UserGroupUserMutation) ClearedFields() []string { + return nil } // FieldCleared returns a boolean indicating if a field with the given name was // cleared in this mutation. -func (m *UserMutation) FieldCleared(name string) bool { +func (m *UserGroupUserMutation) 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 *UserMutation) ClearField(name string) error { - switch name { - case user.FieldDeletedAt: - m.ClearDeletedAt() - return nil - case user.FieldUsername: - m.ClearUsername() - return nil - case user.FieldPassword: - m.ClearPassword() - return nil - case user.FieldEmail: - m.ClearEmail() - return nil - case user.FieldAvatarURL: - m.ClearAvatarURL() - return nil - } - return fmt.Errorf("unknown User nullable field %s", name) + +// 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 *UserGroupUserMutation) ClearField(name string) error { + return fmt.Errorf("unknown UserGroupUser 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 *UserMutation) ResetField(name string) error { +func (m *UserGroupUserMutation) ResetField(name string) error { switch name { - case user.FieldDeletedAt: - m.ResetDeletedAt() - return nil - case user.FieldUsername: - m.ResetUsername() - return nil - case user.FieldPassword: - m.ResetPassword() - return nil - case user.FieldEmail: - m.ResetEmail() - return nil - case user.FieldAvatarURL: - m.ResetAvatarURL() - return nil - case user.FieldPlatform: - m.ResetPlatform() - return nil - case user.FieldStatus: - m.ResetStatus() + case usergroupuser.FieldUserGroupID: + m.ResetUserGroupID() return nil - case user.FieldCreatedAt: - m.ResetCreatedAt() - return nil - case user.FieldUpdatedAt: - m.ResetUpdatedAt() + case usergroupuser.FieldUserID: + m.ResetUserID() return nil } - return fmt.Errorf("unknown User field %s", name) + return fmt.Errorf("unknown UserGroupUser field %s", name) } // AddedEdges returns all edge names that were set/added in this mutation. -func (m *UserMutation) AddedEdges() []string { - edges := make([]string, 0, 8) - if m.login_histories != nil { - edges = append(edges, user.EdgeLoginHistories) - } - if m.models != nil { - edges = append(edges, user.EdgeModels) - } - if m.tasks != nil { - edges = append(edges, user.EdgeTasks) - } - if m.identities != nil { - edges = append(edges, user.EdgeIdentities) - } - if m.workspaces != nil { - edges = append(edges, user.EdgeWorkspaces) - } - if m.workspace_files != nil { - edges = append(edges, user.EdgeWorkspaceFiles) - } - if m.api_keys != nil { - edges = append(edges, user.EdgeAPIKeys) +func (m *UserGroupUserMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.user_group != nil { + edges = append(edges, usergroupuser.EdgeUserGroup) } - if m.security_scannings != nil { - edges = append(edges, user.EdgeSecurityScannings) + if m.user != nil { + edges = append(edges, usergroupuser.EdgeUser) } return edges } // AddedIDs returns all IDs (to other nodes) that were added for the given edge // name in this mutation. -func (m *UserMutation) AddedIDs(name string) []ent.Value { +func (m *UserGroupUserMutation) AddedIDs(name string) []ent.Value { switch name { - case user.EdgeLoginHistories: - ids := make([]ent.Value, 0, len(m.login_histories)) - for id := range m.login_histories { - ids = append(ids, id) - } - return ids - case user.EdgeModels: - ids := make([]ent.Value, 0, len(m.models)) - for id := range m.models { - ids = append(ids, id) - } - return ids - case user.EdgeTasks: - ids := make([]ent.Value, 0, len(m.tasks)) - for id := range m.tasks { - ids = append(ids, id) - } - return ids - case user.EdgeIdentities: - ids := make([]ent.Value, 0, len(m.identities)) - for id := range m.identities { - ids = append(ids, id) - } - return ids - case user.EdgeWorkspaces: - ids := make([]ent.Value, 0, len(m.workspaces)) - for id := range m.workspaces { - ids = append(ids, id) - } - return ids - case user.EdgeWorkspaceFiles: - ids := make([]ent.Value, 0, len(m.workspace_files)) - for id := range m.workspace_files { - ids = append(ids, id) - } - return ids - case user.EdgeAPIKeys: - ids := make([]ent.Value, 0, len(m.api_keys)) - for id := range m.api_keys { - ids = append(ids, id) + case usergroupuser.EdgeUserGroup: + if id := m.user_group; id != nil { + return []ent.Value{*id} } - return ids - case user.EdgeSecurityScannings: - ids := make([]ent.Value, 0, len(m.security_scannings)) - for id := range m.security_scannings { - ids = append(ids, id) + case usergroupuser.EdgeUser: + if id := m.user; id != nil { + return []ent.Value{*id} } - return ids } return nil } // RemovedEdges returns all edge names that were removed in this mutation. -func (m *UserMutation) RemovedEdges() []string { - edges := make([]string, 0, 8) - if m.removedlogin_histories != nil { - edges = append(edges, user.EdgeLoginHistories) - } - if m.removedmodels != nil { - edges = append(edges, user.EdgeModels) - } - if m.removedtasks != nil { - edges = append(edges, user.EdgeTasks) - } - if m.removedidentities != nil { - edges = append(edges, user.EdgeIdentities) - } - if m.removedworkspaces != nil { - edges = append(edges, user.EdgeWorkspaces) - } - if m.removedworkspace_files != nil { - edges = append(edges, user.EdgeWorkspaceFiles) - } - if m.removedapi_keys != nil { - edges = append(edges, user.EdgeAPIKeys) - } - if m.removedsecurity_scannings != nil { - edges = append(edges, user.EdgeSecurityScannings) - } +func (m *UserGroupUserMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) return edges } // RemovedIDs returns all IDs (to other nodes) that were removed for the edge with // the given name in this mutation. -func (m *UserMutation) RemovedIDs(name string) []ent.Value { - switch name { - case user.EdgeLoginHistories: - ids := make([]ent.Value, 0, len(m.removedlogin_histories)) - for id := range m.removedlogin_histories { - ids = append(ids, id) - } - return ids - case user.EdgeModels: - ids := make([]ent.Value, 0, len(m.removedmodels)) - for id := range m.removedmodels { - ids = append(ids, id) - } - return ids - case user.EdgeTasks: - ids := make([]ent.Value, 0, len(m.removedtasks)) - for id := range m.removedtasks { - ids = append(ids, id) - } - return ids - case user.EdgeIdentities: - ids := make([]ent.Value, 0, len(m.removedidentities)) - for id := range m.removedidentities { - ids = append(ids, id) - } - return ids - case user.EdgeWorkspaces: - ids := make([]ent.Value, 0, len(m.removedworkspaces)) - for id := range m.removedworkspaces { - ids = append(ids, id) - } - return ids - case user.EdgeWorkspaceFiles: - ids := make([]ent.Value, 0, len(m.removedworkspace_files)) - for id := range m.removedworkspace_files { - ids = append(ids, id) - } - return ids - case user.EdgeAPIKeys: - ids := make([]ent.Value, 0, len(m.removedapi_keys)) - for id := range m.removedapi_keys { - ids = append(ids, id) - } - return ids - case user.EdgeSecurityScannings: - ids := make([]ent.Value, 0, len(m.removedsecurity_scannings)) - for id := range m.removedsecurity_scannings { - ids = append(ids, id) - } - return ids - } +func (m *UserGroupUserMutation) RemovedIDs(name string) []ent.Value { return nil } // ClearedEdges returns all edge names that were cleared in this mutation. -func (m *UserMutation) ClearedEdges() []string { - edges := make([]string, 0, 8) - if m.clearedlogin_histories { - edges = append(edges, user.EdgeLoginHistories) - } - if m.clearedmodels { - edges = append(edges, user.EdgeModels) - } - if m.clearedtasks { - edges = append(edges, user.EdgeTasks) - } - if m.clearedidentities { - edges = append(edges, user.EdgeIdentities) - } - if m.clearedworkspaces { - edges = append(edges, user.EdgeWorkspaces) - } - if m.clearedworkspace_files { - edges = append(edges, user.EdgeWorkspaceFiles) - } - if m.clearedapi_keys { - edges = append(edges, user.EdgeAPIKeys) +func (m *UserGroupUserMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.cleareduser_group { + edges = append(edges, usergroupuser.EdgeUserGroup) } - if m.clearedsecurity_scannings { - edges = append(edges, user.EdgeSecurityScannings) + if m.cleareduser { + edges = append(edges, usergroupuser.EdgeUser) } return edges } // EdgeCleared returns a boolean which indicates if the edge with the given name // was cleared in this mutation. -func (m *UserMutation) EdgeCleared(name string) bool { +func (m *UserGroupUserMutation) EdgeCleared(name string) bool { switch name { - case user.EdgeLoginHistories: - return m.clearedlogin_histories - case user.EdgeModels: - return m.clearedmodels - case user.EdgeTasks: - return m.clearedtasks - case user.EdgeIdentities: - return m.clearedidentities - case user.EdgeWorkspaces: - return m.clearedworkspaces - case user.EdgeWorkspaceFiles: - return m.clearedworkspace_files - case user.EdgeAPIKeys: - return m.clearedapi_keys - case user.EdgeSecurityScannings: - return m.clearedsecurity_scannings + case usergroupuser.EdgeUserGroup: + return m.cleareduser_group + case usergroupuser.EdgeUser: + return m.cleareduser } 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 *UserMutation) ClearEdge(name string) error { +func (m *UserGroupUserMutation) ClearEdge(name string) error { switch name { + case usergroupuser.EdgeUserGroup: + m.ClearUserGroup() + return nil + case usergroupuser.EdgeUser: + m.ClearUser() + return nil } - return fmt.Errorf("unknown User unique edge %s", name) + return fmt.Errorf("unknown UserGroupUser 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 *UserMutation) ResetEdge(name string) error { +func (m *UserGroupUserMutation) ResetEdge(name string) error { switch name { - case user.EdgeLoginHistories: - m.ResetLoginHistories() - return nil - case user.EdgeModels: - m.ResetModels() - return nil - case user.EdgeTasks: - m.ResetTasks() + case usergroupuser.EdgeUserGroup: + m.ResetUserGroup() return nil - case user.EdgeIdentities: - m.ResetIdentities() - return nil - case user.EdgeWorkspaces: - m.ResetWorkspaces() - return nil - case user.EdgeWorkspaceFiles: - m.ResetWorkspaceFiles() - return nil - case user.EdgeAPIKeys: - m.ResetAPIKeys() - return nil - case user.EdgeSecurityScannings: - m.ResetSecurityScannings() + case usergroupuser.EdgeUser: + m.ResetUser() return nil } - return fmt.Errorf("unknown User edge %s", name) + return fmt.Errorf("unknown UserGroupUser edge %s", name) } // UserIdentityMutation represents an operation that mutates the UserIdentity nodes in the graph. diff --git a/backend/db/page.go b/backend/db/page.go index 0eaeb88d..a181dcd4 100644 --- a/backend/db/page.go +++ b/backend/db/page.go @@ -39,6 +39,20 @@ func (alh *AdminLoginHistoryQuery) Page(ctx context.Context, page, size int) ([] return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil } +func (ar *AdminRoleQuery) Page(ctx context.Context, page, size int) ([]*AdminRole, *PageInfo, error) { + cnt, err := ar.Count(ctx) + if err != nil { + return nil, nil, err + } + offset := size * (page - 1) + rs, err := ar.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 (ak *ApiKeyQuery) Page(ctx context.Context, page, size int) ([]*ApiKey, *PageInfo, error) { cnt, err := ak.Count(ctx) if err != nil { @@ -207,6 +221,20 @@ func (mpm *ModelProviderModelQuery) Page(ctx context.Context, page, size int) ([ return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil } +func (r *RoleQuery) Page(ctx context.Context, page, size int) ([]*Role, *PageInfo, error) { + cnt, err := r.Count(ctx) + if err != nil { + return nil, nil, err + } + offset := size * (page - 1) + rs, err := r.Offset(offset).Limit(size).All(ctx) + if err != nil { + return nil, nil, err + } + has := (page * size) < cnt + return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil +} + func (ss *SecurityScanningQuery) Page(ctx context.Context, page, size int) ([]*SecurityScanning, *PageInfo, error) { cnt, err := ss.Count(ctx) if err != nil { @@ -291,6 +319,48 @@ func (u *UserQuery) Page(ctx context.Context, page, size int) ([]*User, *PageInf return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil } +func (ug *UserGroupQuery) Page(ctx context.Context, page, size int) ([]*UserGroup, *PageInfo, error) { + cnt, err := ug.Count(ctx) + if err != nil { + return nil, nil, err + } + offset := size * (page - 1) + rs, err := ug.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 (uga *UserGroupAdminQuery) Page(ctx context.Context, page, size int) ([]*UserGroupAdmin, *PageInfo, error) { + cnt, err := uga.Count(ctx) + if err != nil { + return nil, nil, err + } + offset := size * (page - 1) + rs, err := uga.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 (ugu *UserGroupUserQuery) Page(ctx context.Context, page, size int) ([]*UserGroupUser, *PageInfo, error) { + cnt, err := ugu.Count(ctx) + if err != nil { + return nil, nil, err + } + offset := size * (page - 1) + rs, err := ugu.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 (ui *UserIdentityQuery) Page(ctx context.Context, page, size int) ([]*UserIdentity, *PageInfo, error) { cnt, err := ui.Count(ctx) if err != nil { diff --git a/backend/db/predicate/predicate.go b/backend/db/predicate/predicate.go index e4d8d1ac..8dbf7122 100644 --- a/backend/db/predicate/predicate.go +++ b/backend/db/predicate/predicate.go @@ -12,6 +12,9 @@ type Admin func(*sql.Selector) // AdminLoginHistory is the predicate function for adminloginhistory builders. type AdminLoginHistory func(*sql.Selector) +// AdminRole is the predicate function for adminrole builders. +type AdminRole func(*sql.Selector) + // ApiKey is the predicate function for apikey builders. type ApiKey func(*sql.Selector) @@ -48,6 +51,9 @@ type ModelProvider func(*sql.Selector) // ModelProviderModel is the predicate function for modelprovidermodel builders. type ModelProviderModel func(*sql.Selector) +// Role is the predicate function for role builders. +type Role func(*sql.Selector) + // SecurityScanning is the predicate function for securityscanning builders. type SecurityScanning func(*sql.Selector) @@ -66,6 +72,15 @@ type TaskRecord func(*sql.Selector) // User is the predicate function for user builders. type User func(*sql.Selector) +// UserGroup is the predicate function for usergroup builders. +type UserGroup func(*sql.Selector) + +// UserGroupAdmin is the predicate function for usergroupadmin builders. +type UserGroupAdmin func(*sql.Selector) + +// UserGroupUser is the predicate function for usergroupuser builders. +type UserGroupUser func(*sql.Selector) + // UserIdentity is the predicate function for useridentity builders. type UserIdentity func(*sql.Selector) diff --git a/backend/db/role.go b/backend/db/role.go new file mode 100644 index 00000000..9d4d9f69 --- /dev/null +++ b/backend/db/role.go @@ -0,0 +1,170 @@ +// 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/role" +) + +// Role is the model entity for the Role schema. +type Role struct { + config `json:"-"` + // ID of the ent. + ID int64 `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"` + // 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 RoleQuery when eager-loading is set. + Edges RoleEdges `json:"edges"` + selectValues sql.SelectValues +} + +// RoleEdges holds the relations/edges for other nodes in the graph. +type RoleEdges struct { + // Admins holds the value of the admins edge. + Admins []*Admin `json:"admins,omitempty"` + // AdminRoles holds the value of the admin_roles edge. + AdminRoles []*AdminRole `json:"admin_roles,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool +} + +// AdminsOrErr returns the Admins value or an error if the edge +// was not loaded in eager-loading. +func (e RoleEdges) AdminsOrErr() ([]*Admin, error) { + if e.loadedTypes[0] { + return e.Admins, nil + } + return nil, &NotLoadedError{edge: "admins"} +} + +// AdminRolesOrErr returns the AdminRoles value or an error if the edge +// was not loaded in eager-loading. +func (e RoleEdges) AdminRolesOrErr() ([]*AdminRole, error) { + if e.loadedTypes[1] { + return e.AdminRoles, nil + } + return nil, &NotLoadedError{edge: "admin_roles"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Role) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case role.FieldID: + values[i] = new(sql.NullInt64) + case role.FieldName, role.FieldDescription: + values[i] = new(sql.NullString) + case role.FieldCreatedAt: + values[i] = new(sql.NullTime) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the Role fields. +func (r *Role) 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 role.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + r.ID = int64(value.Int64) + case role.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + r.Name = value.String + } + case role.FieldDescription: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field description", values[i]) + } else if value.Valid { + r.Description = value.String + } + case role.FieldCreatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field created_at", values[i]) + } else if value.Valid { + r.CreatedAt = value.Time + } + default: + r.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the Role. +// This includes values selected through modifiers, order, etc. +func (r *Role) Value(name string) (ent.Value, error) { + return r.selectValues.Get(name) +} + +// QueryAdmins queries the "admins" edge of the Role entity. +func (r *Role) QueryAdmins() *AdminQuery { + return NewRoleClient(r.config).QueryAdmins(r) +} + +// QueryAdminRoles queries the "admin_roles" edge of the Role entity. +func (r *Role) QueryAdminRoles() *AdminRoleQuery { + return NewRoleClient(r.config).QueryAdminRoles(r) +} + +// Update returns a builder for updating this Role. +// Note that you need to call Role.Unwrap() before calling this method if this Role +// was returned from a transaction, and the transaction was committed or rolled back. +func (r *Role) Update() *RoleUpdateOne { + return NewRoleClient(r.config).UpdateOne(r) +} + +// Unwrap unwraps the Role entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (r *Role) Unwrap() *Role { + _tx, ok := r.config.driver.(*txDriver) + if !ok { + panic("db: Role is not a transactional entity") + } + r.config.driver = _tx.drv + return r +} + +// String implements the fmt.Stringer. +func (r *Role) String() string { + var builder strings.Builder + builder.WriteString("Role(") + builder.WriteString(fmt.Sprintf("id=%v, ", r.ID)) + builder.WriteString("name=") + builder.WriteString(r.Name) + builder.WriteString(", ") + builder.WriteString("description=") + builder.WriteString(r.Description) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(r.CreatedAt.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// Roles is a parsable slice of Role. +type Roles []*Role diff --git a/backend/db/role/role.go b/backend/db/role/role.go new file mode 100644 index 00000000..4c55cf3f --- /dev/null +++ b/backend/db/role/role.go @@ -0,0 +1,135 @@ +// Code generated by ent, DO NOT EDIT. + +package role + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the role type in the database. + Label = "role" + // 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" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // EdgeAdmins holds the string denoting the admins edge name in mutations. + EdgeAdmins = "admins" + // EdgeAdminRoles holds the string denoting the admin_roles edge name in mutations. + EdgeAdminRoles = "admin_roles" + // Table holds the table name of the role in the database. + Table = "roles" + // AdminsTable is the table that holds the admins relation/edge. The primary key declared below. + AdminsTable = "admin_roles" + // AdminsInverseTable is the table name for the Admin entity. + // It exists in this package in order to avoid circular dependency with the "admin" package. + AdminsInverseTable = "admins" + // AdminRolesTable is the table that holds the admin_roles relation/edge. + AdminRolesTable = "admin_roles" + // AdminRolesInverseTable is the table name for the AdminRole entity. + // It exists in this package in order to avoid circular dependency with the "adminrole" package. + AdminRolesInverseTable = "admin_roles" + // AdminRolesColumn is the table column denoting the admin_roles relation/edge. + AdminRolesColumn = "role_id" +) + +// Columns holds all SQL columns for role fields. +var Columns = []string{ + FieldID, + FieldName, + FieldDescription, + FieldCreatedAt, +} + +var ( + // AdminsPrimaryKey and AdminsColumn2 are the table columns denoting the + // primary key for the admins relation (M2M). + AdminsPrimaryKey = []string{"role_id", "admin_id"} +) + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time +) + +// OrderOption defines the ordering options for the Role 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() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// ByAdminsCount orders the results by admins count. +func ByAdminsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newAdminsStep(), opts...) + } +} + +// ByAdmins orders the results by admins terms. +func ByAdmins(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newAdminsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByAdminRolesCount orders the results by admin_roles count. +func ByAdminRolesCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newAdminRolesStep(), opts...) + } +} + +// ByAdminRoles orders the results by admin_roles terms. +func ByAdminRoles(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newAdminRolesStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newAdminsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(AdminsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, AdminsTable, AdminsPrimaryKey...), + ) +} +func newAdminRolesStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(AdminRolesInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, AdminRolesTable, AdminRolesColumn), + ) +} diff --git a/backend/db/role/where.go b/backend/db/role/where.go new file mode 100644 index 00000000..df5b2c52 --- /dev/null +++ b/backend/db/role/where.go @@ -0,0 +1,302 @@ +// Code generated by ent, DO NOT EDIT. + +package role + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/chaitin/MonkeyCode/backend/db/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id int64) predicate.Role { + return predicate.Role(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int64) predicate.Role { + return predicate.Role(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int64) predicate.Role { + return predicate.Role(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int64) predicate.Role { + return predicate.Role(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int64) predicate.Role { + return predicate.Role(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int64) predicate.Role { + return predicate.Role(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int64) predicate.Role { + return predicate.Role(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int64) predicate.Role { + return predicate.Role(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int64) predicate.Role { + return predicate.Role(sql.FieldLTE(FieldID, id)) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.Role { + return predicate.Role(sql.FieldEQ(FieldName, v)) +} + +// Description applies equality check predicate on the "description" field. It's identical to DescriptionEQ. +func Description(v string) predicate.Role { + return predicate.Role(sql.FieldEQ(FieldDescription, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.Role { + return predicate.Role(sql.FieldEQ(FieldCreatedAt, v)) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.Role { + return predicate.Role(sql.FieldEQ(FieldName, v)) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.Role { + return predicate.Role(sql.FieldNEQ(FieldName, v)) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.Role { + return predicate.Role(sql.FieldIn(FieldName, vs...)) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.Role { + return predicate.Role(sql.FieldNotIn(FieldName, vs...)) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.Role { + return predicate.Role(sql.FieldGT(FieldName, v)) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.Role { + return predicate.Role(sql.FieldGTE(FieldName, v)) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.Role { + return predicate.Role(sql.FieldLT(FieldName, v)) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.Role { + return predicate.Role(sql.FieldLTE(FieldName, v)) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.Role { + return predicate.Role(sql.FieldContains(FieldName, v)) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.Role { + return predicate.Role(sql.FieldHasPrefix(FieldName, v)) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.Role { + return predicate.Role(sql.FieldHasSuffix(FieldName, v)) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.Role { + return predicate.Role(sql.FieldEqualFold(FieldName, v)) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.Role { + return predicate.Role(sql.FieldContainsFold(FieldName, v)) +} + +// DescriptionEQ applies the EQ predicate on the "description" field. +func DescriptionEQ(v string) predicate.Role { + return predicate.Role(sql.FieldEQ(FieldDescription, v)) +} + +// DescriptionNEQ applies the NEQ predicate on the "description" field. +func DescriptionNEQ(v string) predicate.Role { + return predicate.Role(sql.FieldNEQ(FieldDescription, v)) +} + +// DescriptionIn applies the In predicate on the "description" field. +func DescriptionIn(vs ...string) predicate.Role { + return predicate.Role(sql.FieldIn(FieldDescription, vs...)) +} + +// DescriptionNotIn applies the NotIn predicate on the "description" field. +func DescriptionNotIn(vs ...string) predicate.Role { + return predicate.Role(sql.FieldNotIn(FieldDescription, vs...)) +} + +// DescriptionGT applies the GT predicate on the "description" field. +func DescriptionGT(v string) predicate.Role { + return predicate.Role(sql.FieldGT(FieldDescription, v)) +} + +// DescriptionGTE applies the GTE predicate on the "description" field. +func DescriptionGTE(v string) predicate.Role { + return predicate.Role(sql.FieldGTE(FieldDescription, v)) +} + +// DescriptionLT applies the LT predicate on the "description" field. +func DescriptionLT(v string) predicate.Role { + return predicate.Role(sql.FieldLT(FieldDescription, v)) +} + +// DescriptionLTE applies the LTE predicate on the "description" field. +func DescriptionLTE(v string) predicate.Role { + return predicate.Role(sql.FieldLTE(FieldDescription, v)) +} + +// DescriptionContains applies the Contains predicate on the "description" field. +func DescriptionContains(v string) predicate.Role { + return predicate.Role(sql.FieldContains(FieldDescription, v)) +} + +// DescriptionHasPrefix applies the HasPrefix predicate on the "description" field. +func DescriptionHasPrefix(v string) predicate.Role { + return predicate.Role(sql.FieldHasPrefix(FieldDescription, v)) +} + +// DescriptionHasSuffix applies the HasSuffix predicate on the "description" field. +func DescriptionHasSuffix(v string) predicate.Role { + return predicate.Role(sql.FieldHasSuffix(FieldDescription, v)) +} + +// DescriptionEqualFold applies the EqualFold predicate on the "description" field. +func DescriptionEqualFold(v string) predicate.Role { + return predicate.Role(sql.FieldEqualFold(FieldDescription, v)) +} + +// DescriptionContainsFold applies the ContainsFold predicate on the "description" field. +func DescriptionContainsFold(v string) predicate.Role { + return predicate.Role(sql.FieldContainsFold(FieldDescription, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.Role { + return predicate.Role(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.Role { + return predicate.Role(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.Role { + return predicate.Role(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.Role { + return predicate.Role(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.Role { + return predicate.Role(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.Role { + return predicate.Role(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.Role { + return predicate.Role(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.Role { + return predicate.Role(sql.FieldLTE(FieldCreatedAt, v)) +} + +// HasAdmins applies the HasEdge predicate on the "admins" edge. +func HasAdmins() predicate.Role { + return predicate.Role(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, AdminsTable, AdminsPrimaryKey...), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasAdminsWith applies the HasEdge predicate on the "admins" edge with a given conditions (other predicates). +func HasAdminsWith(preds ...predicate.Admin) predicate.Role { + return predicate.Role(func(s *sql.Selector) { + step := newAdminsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasAdminRoles applies the HasEdge predicate on the "admin_roles" edge. +func HasAdminRoles() predicate.Role { + return predicate.Role(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, AdminRolesTable, AdminRolesColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasAdminRolesWith applies the HasEdge predicate on the "admin_roles" edge with a given conditions (other predicates). +func HasAdminRolesWith(preds ...predicate.AdminRole) predicate.Role { + return predicate.Role(func(s *sql.Selector) { + step := newAdminRolesStep() + 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.Role) predicate.Role { + return predicate.Role(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Role) predicate.Role { + return predicate.Role(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Role) predicate.Role { + return predicate.Role(sql.NotPredicates(p)) +} diff --git a/backend/db/role_create.go b/backend/db/role_create.go new file mode 100644 index 00000000..fdc75fad --- /dev/null +++ b/backend/db/role_create.go @@ -0,0 +1,674 @@ +// 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/admin" + "github.com/chaitin/MonkeyCode/backend/db/adminrole" + "github.com/chaitin/MonkeyCode/backend/db/role" + "github.com/google/uuid" +) + +// RoleCreate is the builder for creating a Role entity. +type RoleCreate struct { + config + mutation *RoleMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetName sets the "name" field. +func (rc *RoleCreate) SetName(s string) *RoleCreate { + rc.mutation.SetName(s) + return rc +} + +// SetDescription sets the "description" field. +func (rc *RoleCreate) SetDescription(s string) *RoleCreate { + rc.mutation.SetDescription(s) + return rc +} + +// SetCreatedAt sets the "created_at" field. +func (rc *RoleCreate) SetCreatedAt(t time.Time) *RoleCreate { + rc.mutation.SetCreatedAt(t) + return rc +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (rc *RoleCreate) SetNillableCreatedAt(t *time.Time) *RoleCreate { + if t != nil { + rc.SetCreatedAt(*t) + } + return rc +} + +// SetID sets the "id" field. +func (rc *RoleCreate) SetID(i int64) *RoleCreate { + rc.mutation.SetID(i) + return rc +} + +// AddAdminIDs adds the "admins" edge to the Admin entity by IDs. +func (rc *RoleCreate) AddAdminIDs(ids ...uuid.UUID) *RoleCreate { + rc.mutation.AddAdminIDs(ids...) + return rc +} + +// AddAdmins adds the "admins" edges to the Admin entity. +func (rc *RoleCreate) AddAdmins(a ...*Admin) *RoleCreate { + ids := make([]uuid.UUID, len(a)) + for i := range a { + ids[i] = a[i].ID + } + return rc.AddAdminIDs(ids...) +} + +// AddAdminRoleIDs adds the "admin_roles" edge to the AdminRole entity by IDs. +func (rc *RoleCreate) AddAdminRoleIDs(ids ...uuid.UUID) *RoleCreate { + rc.mutation.AddAdminRoleIDs(ids...) + return rc +} + +// AddAdminRoles adds the "admin_roles" edges to the AdminRole entity. +func (rc *RoleCreate) AddAdminRoles(a ...*AdminRole) *RoleCreate { + ids := make([]uuid.UUID, len(a)) + for i := range a { + ids[i] = a[i].ID + } + return rc.AddAdminRoleIDs(ids...) +} + +// Mutation returns the RoleMutation object of the builder. +func (rc *RoleCreate) Mutation() *RoleMutation { + return rc.mutation +} + +// Save creates the Role in the database. +func (rc *RoleCreate) Save(ctx context.Context) (*Role, error) { + rc.defaults() + return withHooks(ctx, rc.sqlSave, rc.mutation, rc.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (rc *RoleCreate) SaveX(ctx context.Context) *Role { + v, err := rc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (rc *RoleCreate) Exec(ctx context.Context) error { + _, err := rc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (rc *RoleCreate) ExecX(ctx context.Context) { + if err := rc.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (rc *RoleCreate) defaults() { + if _, ok := rc.mutation.CreatedAt(); !ok { + v := role.DefaultCreatedAt() + rc.mutation.SetCreatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (rc *RoleCreate) check() error { + if _, ok := rc.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`db: missing required field "Role.name"`)} + } + if _, ok := rc.mutation.Description(); !ok { + return &ValidationError{Name: "description", err: errors.New(`db: missing required field "Role.description"`)} + } + if _, ok := rc.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "Role.created_at"`)} + } + return nil +} + +func (rc *RoleCreate) sqlSave(ctx context.Context) (*Role, error) { + if err := rc.check(); err != nil { + return nil, err + } + _node, _spec := rc.createSpec() + if err := sqlgraph.CreateNode(ctx, rc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + if _spec.ID.Value != _node.ID { + id := _spec.ID.Value.(int64) + _node.ID = int64(id) + } + rc.mutation.id = &_node.ID + rc.mutation.done = true + return _node, nil +} + +func (rc *RoleCreate) createSpec() (*Role, *sqlgraph.CreateSpec) { + var ( + _node = &Role{config: rc.config} + _spec = sqlgraph.NewCreateSpec(role.Table, sqlgraph.NewFieldSpec(role.FieldID, field.TypeInt64)) + ) + _spec.OnConflict = rc.conflict + if id, ok := rc.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = id + } + if value, ok := rc.mutation.Name(); ok { + _spec.SetField(role.FieldName, field.TypeString, value) + _node.Name = value + } + if value, ok := rc.mutation.Description(); ok { + _spec.SetField(role.FieldDescription, field.TypeString, value) + _node.Description = value + } + if value, ok := rc.mutation.CreatedAt(); ok { + _spec.SetField(role.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if nodes := rc.mutation.AdminsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: role.AdminsTable, + Columns: role.AdminsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(admin.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := rc.mutation.AdminRolesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: role.AdminRolesTable, + Columns: []string{role.AdminRolesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(adminrole.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.Role.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.RoleUpsert) { +// SetName(v+v). +// }). +// Exec(ctx) +func (rc *RoleCreate) OnConflict(opts ...sql.ConflictOption) *RoleUpsertOne { + rc.conflict = opts + return &RoleUpsertOne{ + create: rc, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.Role.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (rc *RoleCreate) OnConflictColumns(columns ...string) *RoleUpsertOne { + rc.conflict = append(rc.conflict, sql.ConflictColumns(columns...)) + return &RoleUpsertOne{ + create: rc, + } +} + +type ( + // RoleUpsertOne is the builder for "upsert"-ing + // one Role node. + RoleUpsertOne struct { + create *RoleCreate + } + + // RoleUpsert is the "OnConflict" setter. + RoleUpsert struct { + *sql.UpdateSet + } +) + +// SetName sets the "name" field. +func (u *RoleUpsert) SetName(v string) *RoleUpsert { + u.Set(role.FieldName, v) + return u +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *RoleUpsert) UpdateName() *RoleUpsert { + u.SetExcluded(role.FieldName) + return u +} + +// SetDescription sets the "description" field. +func (u *RoleUpsert) SetDescription(v string) *RoleUpsert { + u.Set(role.FieldDescription, v) + return u +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *RoleUpsert) UpdateDescription() *RoleUpsert { + u.SetExcluded(role.FieldDescription) + return u +} + +// SetCreatedAt sets the "created_at" field. +func (u *RoleUpsert) SetCreatedAt(v time.Time) *RoleUpsert { + u.Set(role.FieldCreatedAt, v) + return u +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *RoleUpsert) UpdateCreatedAt() *RoleUpsert { + u.SetExcluded(role.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.Role.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(role.FieldID) +// }), +// ). +// Exec(ctx) +func (u *RoleUpsertOne) UpdateNewValues() *RoleUpsertOne { + 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(role.FieldID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.Role.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *RoleUpsertOne) Ignore() *RoleUpsertOne { + 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 *RoleUpsertOne) DoNothing() *RoleUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the RoleCreate.OnConflict +// documentation for more info. +func (u *RoleUpsertOne) Update(set func(*RoleUpsert)) *RoleUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&RoleUpsert{UpdateSet: update}) + })) + return u +} + +// SetName sets the "name" field. +func (u *RoleUpsertOne) SetName(v string) *RoleUpsertOne { + return u.Update(func(s *RoleUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *RoleUpsertOne) UpdateName() *RoleUpsertOne { + return u.Update(func(s *RoleUpsert) { + s.UpdateName() + }) +} + +// SetDescription sets the "description" field. +func (u *RoleUpsertOne) SetDescription(v string) *RoleUpsertOne { + return u.Update(func(s *RoleUpsert) { + s.SetDescription(v) + }) +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *RoleUpsertOne) UpdateDescription() *RoleUpsertOne { + return u.Update(func(s *RoleUpsert) { + s.UpdateDescription() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *RoleUpsertOne) SetCreatedAt(v time.Time) *RoleUpsertOne { + return u.Update(func(s *RoleUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *RoleUpsertOne) UpdateCreatedAt() *RoleUpsertOne { + return u.Update(func(s *RoleUpsert) { + s.UpdateCreatedAt() + }) +} + +// Exec executes the query. +func (u *RoleUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for RoleCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *RoleUpsertOne) 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 *RoleUpsertOne) ID(ctx context.Context) (id int64, err error) { + 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 *RoleUpsertOne) IDX(ctx context.Context) int64 { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// RoleCreateBulk is the builder for creating many Role entities in bulk. +type RoleCreateBulk struct { + config + err error + builders []*RoleCreate + conflict []sql.ConflictOption +} + +// Save creates the Role entities in the database. +func (rcb *RoleCreateBulk) Save(ctx context.Context) ([]*Role, error) { + if rcb.err != nil { + return nil, rcb.err + } + specs := make([]*sqlgraph.CreateSpec, len(rcb.builders)) + nodes := make([]*Role, len(rcb.builders)) + mutators := make([]Mutator, len(rcb.builders)) + for i := range rcb.builders { + func(i int, root context.Context) { + builder := rcb.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*RoleMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, rcb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = rcb.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, rcb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + if specs[i].ID.Value != nil && nodes[i].ID == 0 { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int64(id) + } + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, rcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (rcb *RoleCreateBulk) SaveX(ctx context.Context) []*Role { + v, err := rcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (rcb *RoleCreateBulk) Exec(ctx context.Context) error { + _, err := rcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (rcb *RoleCreateBulk) ExecX(ctx context.Context) { + if err := rcb.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.Role.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.RoleUpsert) { +// SetName(v+v). +// }). +// Exec(ctx) +func (rcb *RoleCreateBulk) OnConflict(opts ...sql.ConflictOption) *RoleUpsertBulk { + rcb.conflict = opts + return &RoleUpsertBulk{ + create: rcb, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.Role.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (rcb *RoleCreateBulk) OnConflictColumns(columns ...string) *RoleUpsertBulk { + rcb.conflict = append(rcb.conflict, sql.ConflictColumns(columns...)) + return &RoleUpsertBulk{ + create: rcb, + } +} + +// RoleUpsertBulk is the builder for "upsert"-ing +// a bulk of Role nodes. +type RoleUpsertBulk struct { + create *RoleCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.Role.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(role.FieldID) +// }), +// ). +// Exec(ctx) +func (u *RoleUpsertBulk) UpdateNewValues() *RoleUpsertBulk { + 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(role.FieldID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.Role.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *RoleUpsertBulk) Ignore() *RoleUpsertBulk { + 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 *RoleUpsertBulk) DoNothing() *RoleUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the RoleCreateBulk.OnConflict +// documentation for more info. +func (u *RoleUpsertBulk) Update(set func(*RoleUpsert)) *RoleUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&RoleUpsert{UpdateSet: update}) + })) + return u +} + +// SetName sets the "name" field. +func (u *RoleUpsertBulk) SetName(v string) *RoleUpsertBulk { + return u.Update(func(s *RoleUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *RoleUpsertBulk) UpdateName() *RoleUpsertBulk { + return u.Update(func(s *RoleUpsert) { + s.UpdateName() + }) +} + +// SetDescription sets the "description" field. +func (u *RoleUpsertBulk) SetDescription(v string) *RoleUpsertBulk { + return u.Update(func(s *RoleUpsert) { + s.SetDescription(v) + }) +} + +// UpdateDescription sets the "description" field to the value that was provided on create. +func (u *RoleUpsertBulk) UpdateDescription() *RoleUpsertBulk { + return u.Update(func(s *RoleUpsert) { + s.UpdateDescription() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *RoleUpsertBulk) SetCreatedAt(v time.Time) *RoleUpsertBulk { + return u.Update(func(s *RoleUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *RoleUpsertBulk) UpdateCreatedAt() *RoleUpsertBulk { + return u.Update(func(s *RoleUpsert) { + s.UpdateCreatedAt() + }) +} + +// Exec executes the query. +func (u *RoleUpsertBulk) 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 RoleCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for RoleCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *RoleUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/role_delete.go b/backend/db/role_delete.go new file mode 100644 index 00000000..2b354009 --- /dev/null +++ b/backend/db/role_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/role" +) + +// RoleDelete is the builder for deleting a Role entity. +type RoleDelete struct { + config + hooks []Hook + mutation *RoleMutation +} + +// Where appends a list predicates to the RoleDelete builder. +func (rd *RoleDelete) Where(ps ...predicate.Role) *RoleDelete { + rd.mutation.Where(ps...) + return rd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (rd *RoleDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, rd.sqlExec, rd.mutation, rd.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (rd *RoleDelete) ExecX(ctx context.Context) int { + n, err := rd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (rd *RoleDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(role.Table, sqlgraph.NewFieldSpec(role.FieldID, field.TypeInt64)) + if ps := rd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, rd.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + rd.mutation.done = true + return affected, err +} + +// RoleDeleteOne is the builder for deleting a single Role entity. +type RoleDeleteOne struct { + rd *RoleDelete +} + +// Where appends a list predicates to the RoleDelete builder. +func (rdo *RoleDeleteOne) Where(ps ...predicate.Role) *RoleDeleteOne { + rdo.rd.mutation.Where(ps...) + return rdo +} + +// Exec executes the deletion query. +func (rdo *RoleDeleteOne) Exec(ctx context.Context) error { + n, err := rdo.rd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{role.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (rdo *RoleDeleteOne) ExecX(ctx context.Context) { + if err := rdo.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/role_query.go b/backend/db/role_query.go new file mode 100644 index 00000000..105ea8dc --- /dev/null +++ b/backend/db/role_query.go @@ -0,0 +1,762 @@ +// 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/admin" + "github.com/chaitin/MonkeyCode/backend/db/adminrole" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/role" + "github.com/google/uuid" +) + +// RoleQuery is the builder for querying Role entities. +type RoleQuery struct { + config + ctx *QueryContext + order []role.OrderOption + inters []Interceptor + predicates []predicate.Role + withAdmins *AdminQuery + withAdminRoles *AdminRoleQuery + 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 RoleQuery builder. +func (rq *RoleQuery) Where(ps ...predicate.Role) *RoleQuery { + rq.predicates = append(rq.predicates, ps...) + return rq +} + +// Limit the number of records to be returned by this query. +func (rq *RoleQuery) Limit(limit int) *RoleQuery { + rq.ctx.Limit = &limit + return rq +} + +// Offset to start from. +func (rq *RoleQuery) Offset(offset int) *RoleQuery { + rq.ctx.Offset = &offset + return rq +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (rq *RoleQuery) Unique(unique bool) *RoleQuery { + rq.ctx.Unique = &unique + return rq +} + +// Order specifies how the records should be ordered. +func (rq *RoleQuery) Order(o ...role.OrderOption) *RoleQuery { + rq.order = append(rq.order, o...) + return rq +} + +// QueryAdmins chains the current query on the "admins" edge. +func (rq *RoleQuery) QueryAdmins() *AdminQuery { + query := (&AdminClient{config: rq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := rq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := rq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(role.Table, role.FieldID, selector), + sqlgraph.To(admin.Table, admin.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, role.AdminsTable, role.AdminsPrimaryKey...), + ) + fromU = sqlgraph.SetNeighbors(rq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryAdminRoles chains the current query on the "admin_roles" edge. +func (rq *RoleQuery) QueryAdminRoles() *AdminRoleQuery { + query := (&AdminRoleClient{config: rq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := rq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := rq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(role.Table, role.FieldID, selector), + sqlgraph.To(adminrole.Table, adminrole.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, role.AdminRolesTable, role.AdminRolesColumn), + ) + fromU = sqlgraph.SetNeighbors(rq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first Role entity from the query. +// Returns a *NotFoundError when no Role was found. +func (rq *RoleQuery) First(ctx context.Context) (*Role, error) { + nodes, err := rq.Limit(1).All(setContextOp(ctx, rq.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{role.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (rq *RoleQuery) FirstX(ctx context.Context) *Role { + node, err := rq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Role ID from the query. +// Returns a *NotFoundError when no Role ID was found. +func (rq *RoleQuery) FirstID(ctx context.Context) (id int64, err error) { + var ids []int64 + if ids, err = rq.Limit(1).IDs(setContextOp(ctx, rq.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{role.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (rq *RoleQuery) FirstIDX(ctx context.Context) int64 { + id, err := rq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Role entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Role entity is found. +// Returns a *NotFoundError when no Role entities are found. +func (rq *RoleQuery) Only(ctx context.Context) (*Role, error) { + nodes, err := rq.Limit(2).All(setContextOp(ctx, rq.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{role.Label} + default: + return nil, &NotSingularError{role.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (rq *RoleQuery) OnlyX(ctx context.Context) *Role { + node, err := rq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Role ID in the query. +// Returns a *NotSingularError when more than one Role ID is found. +// Returns a *NotFoundError when no entities are found. +func (rq *RoleQuery) OnlyID(ctx context.Context) (id int64, err error) { + var ids []int64 + if ids, err = rq.Limit(2).IDs(setContextOp(ctx, rq.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{role.Label} + default: + err = &NotSingularError{role.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (rq *RoleQuery) OnlyIDX(ctx context.Context) int64 { + id, err := rq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Roles. +func (rq *RoleQuery) All(ctx context.Context) ([]*Role, error) { + ctx = setContextOp(ctx, rq.ctx, ent.OpQueryAll) + if err := rq.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Role, *RoleQuery]() + return withInterceptors[[]*Role](ctx, rq, qr, rq.inters) +} + +// AllX is like All, but panics if an error occurs. +func (rq *RoleQuery) AllX(ctx context.Context) []*Role { + nodes, err := rq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Role IDs. +func (rq *RoleQuery) IDs(ctx context.Context) (ids []int64, err error) { + if rq.ctx.Unique == nil && rq.path != nil { + rq.Unique(true) + } + ctx = setContextOp(ctx, rq.ctx, ent.OpQueryIDs) + if err = rq.Select(role.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (rq *RoleQuery) IDsX(ctx context.Context) []int64 { + ids, err := rq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (rq *RoleQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, rq.ctx, ent.OpQueryCount) + if err := rq.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, rq, querierCount[*RoleQuery](), rq.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (rq *RoleQuery) CountX(ctx context.Context) int { + count, err := rq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (rq *RoleQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, rq.ctx, ent.OpQueryExist) + switch _, err := rq.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("db: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (rq *RoleQuery) ExistX(ctx context.Context) bool { + exist, err := rq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the RoleQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (rq *RoleQuery) Clone() *RoleQuery { + if rq == nil { + return nil + } + return &RoleQuery{ + config: rq.config, + ctx: rq.ctx.Clone(), + order: append([]role.OrderOption{}, rq.order...), + inters: append([]Interceptor{}, rq.inters...), + predicates: append([]predicate.Role{}, rq.predicates...), + withAdmins: rq.withAdmins.Clone(), + withAdminRoles: rq.withAdminRoles.Clone(), + // clone intermediate query. + sql: rq.sql.Clone(), + path: rq.path, + modifiers: append([]func(*sql.Selector){}, rq.modifiers...), + } +} + +// WithAdmins tells the query-builder to eager-load the nodes that are connected to +// the "admins" edge. The optional arguments are used to configure the query builder of the edge. +func (rq *RoleQuery) WithAdmins(opts ...func(*AdminQuery)) *RoleQuery { + query := (&AdminClient{config: rq.config}).Query() + for _, opt := range opts { + opt(query) + } + rq.withAdmins = query + return rq +} + +// WithAdminRoles tells the query-builder to eager-load the nodes that are connected to +// the "admin_roles" edge. The optional arguments are used to configure the query builder of the edge. +func (rq *RoleQuery) WithAdminRoles(opts ...func(*AdminRoleQuery)) *RoleQuery { + query := (&AdminRoleClient{config: rq.config}).Query() + for _, opt := range opts { + opt(query) + } + rq.withAdminRoles = query + return rq +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// Name string `json:"name,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Role.Query(). +// GroupBy(role.FieldName). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (rq *RoleQuery) GroupBy(field string, fields ...string) *RoleGroupBy { + rq.ctx.Fields = append([]string{field}, fields...) + grbuild := &RoleGroupBy{build: rq} + grbuild.flds = &rq.ctx.Fields + grbuild.label = role.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.Role.Query(). +// Select(role.FieldName). +// Scan(ctx, &v) +func (rq *RoleQuery) Select(fields ...string) *RoleSelect { + rq.ctx.Fields = append(rq.ctx.Fields, fields...) + sbuild := &RoleSelect{RoleQuery: rq} + sbuild.label = role.Label + sbuild.flds, sbuild.scan = &rq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a RoleSelect configured with the given aggregations. +func (rq *RoleQuery) Aggregate(fns ...AggregateFunc) *RoleSelect { + return rq.Select().Aggregate(fns...) +} + +func (rq *RoleQuery) prepareQuery(ctx context.Context) error { + for _, inter := range rq.inters { + if inter == nil { + return fmt.Errorf("db: uninitialized interceptor (forgotten import db/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, rq); err != nil { + return err + } + } + } + for _, f := range rq.ctx.Fields { + if !role.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + } + if rq.path != nil { + prev, err := rq.path(ctx) + if err != nil { + return err + } + rq.sql = prev + } + return nil +} + +func (rq *RoleQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Role, error) { + var ( + nodes = []*Role{} + _spec = rq.querySpec() + loadedTypes = [2]bool{ + rq.withAdmins != nil, + rq.withAdminRoles != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Role).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Role{config: rq.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(rq.modifiers) > 0 { + _spec.Modifiers = rq.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, rq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := rq.withAdmins; query != nil { + if err := rq.loadAdmins(ctx, query, nodes, + func(n *Role) { n.Edges.Admins = []*Admin{} }, + func(n *Role, e *Admin) { n.Edges.Admins = append(n.Edges.Admins, e) }); err != nil { + return nil, err + } + } + if query := rq.withAdminRoles; query != nil { + if err := rq.loadAdminRoles(ctx, query, nodes, + func(n *Role) { n.Edges.AdminRoles = []*AdminRole{} }, + func(n *Role, e *AdminRole) { n.Edges.AdminRoles = append(n.Edges.AdminRoles, e) }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (rq *RoleQuery) loadAdmins(ctx context.Context, query *AdminQuery, nodes []*Role, init func(*Role), assign func(*Role, *Admin)) error { + edgeIDs := make([]driver.Value, len(nodes)) + byID := make(map[int64]*Role) + nids := make(map[uuid.UUID]map[*Role]struct{}) + for i, node := range nodes { + edgeIDs[i] = node.ID + byID[node.ID] = node + if init != nil { + init(node) + } + } + query.Where(func(s *sql.Selector) { + joinT := sql.Table(role.AdminsTable) + s.Join(joinT).On(s.C(admin.FieldID), joinT.C(role.AdminsPrimaryKey[1])) + s.Where(sql.InValues(joinT.C(role.AdminsPrimaryKey[0]), edgeIDs...)) + columns := s.SelectedColumns() + s.Select(joinT.C(role.AdminsPrimaryKey[0])) + s.AppendSelect(columns...) + s.SetDistinct(false) + }) + if err := query.prepareQuery(ctx); err != nil { + return err + } + qr := QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + return query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) { + assign := spec.Assign + values := spec.ScanValues + spec.ScanValues = func(columns []string) ([]any, error) { + values, err := values(columns[1:]) + if err != nil { + return nil, err + } + return append([]any{new(sql.NullInt64)}, values...), nil + } + spec.Assign = func(columns []string, values []any) error { + outValue := values[0].(*sql.NullInt64).Int64 + inValue := *values[1].(*uuid.UUID) + if nids[inValue] == nil { + nids[inValue] = map[*Role]struct{}{byID[outValue]: {}} + return assign(columns[1:], values[1:]) + } + nids[inValue][byID[outValue]] = struct{}{} + return nil + } + }) + }) + neighbors, err := withInterceptors[[]*Admin](ctx, query, qr, query.inters) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nids[n.ID] + if !ok { + return fmt.Errorf(`unexpected "admins" node returned %v`, n.ID) + } + for kn := range nodes { + assign(kn, n) + } + } + return nil +} +func (rq *RoleQuery) loadAdminRoles(ctx context.Context, query *AdminRoleQuery, nodes []*Role, init func(*Role), assign func(*Role, *AdminRole)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int64]*Role) + 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(adminrole.FieldRoleID) + } + query.Where(predicate.AdminRole(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(role.AdminRolesColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.RoleID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "role_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} + +func (rq *RoleQuery) sqlCount(ctx context.Context) (int, error) { + _spec := rq.querySpec() + if len(rq.modifiers) > 0 { + _spec.Modifiers = rq.modifiers + } + _spec.Node.Columns = rq.ctx.Fields + if len(rq.ctx.Fields) > 0 { + _spec.Unique = rq.ctx.Unique != nil && *rq.ctx.Unique + } + return sqlgraph.CountNodes(ctx, rq.driver, _spec) +} + +func (rq *RoleQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(role.Table, role.Columns, sqlgraph.NewFieldSpec(role.FieldID, field.TypeInt64)) + _spec.From = rq.sql + if unique := rq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if rq.path != nil { + _spec.Unique = true + } + if fields := rq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, role.FieldID) + for i := range fields { + if fields[i] != role.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := rq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := rq.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := rq.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := rq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (rq *RoleQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(rq.driver.Dialect()) + t1 := builder.Table(role.Table) + columns := rq.ctx.Fields + if len(columns) == 0 { + columns = role.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if rq.sql != nil { + selector = rq.sql + selector.Select(selector.Columns(columns...)...) + } + if rq.ctx.Unique != nil && *rq.ctx.Unique { + selector.Distinct() + } + for _, m := range rq.modifiers { + m(selector) + } + for _, p := range rq.predicates { + p(selector) + } + for _, p := range rq.order { + p(selector) + } + if offset := rq.ctx.Offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := rq.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// ForUpdate locks the selected rows against concurrent updates, and prevent them from being +// updated, deleted or "selected ... for update" by other sessions, until the transaction is +// either committed or rolled-back. +func (rq *RoleQuery) ForUpdate(opts ...sql.LockOption) *RoleQuery { + if rq.driver.Dialect() == dialect.Postgres { + rq.Unique(false) + } + rq.modifiers = append(rq.modifiers, func(s *sql.Selector) { + s.ForUpdate(opts...) + }) + return rq +} + +// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock +// on any rows that are read. Other sessions can read the rows, but cannot modify them +// until your transaction commits. +func (rq *RoleQuery) ForShare(opts ...sql.LockOption) *RoleQuery { + if rq.driver.Dialect() == dialect.Postgres { + rq.Unique(false) + } + rq.modifiers = append(rq.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return rq +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (rq *RoleQuery) Modify(modifiers ...func(s *sql.Selector)) *RoleSelect { + rq.modifiers = append(rq.modifiers, modifiers...) + return rq.Select() +} + +// RoleGroupBy is the group-by builder for Role entities. +type RoleGroupBy struct { + selector + build *RoleQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (rgb *RoleGroupBy) Aggregate(fns ...AggregateFunc) *RoleGroupBy { + rgb.fns = append(rgb.fns, fns...) + return rgb +} + +// Scan applies the selector query and scans the result into the given value. +func (rgb *RoleGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, rgb.build.ctx, ent.OpQueryGroupBy) + if err := rgb.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*RoleQuery, *RoleGroupBy](ctx, rgb.build, rgb, rgb.build.inters, v) +} + +func (rgb *RoleGroupBy) sqlScan(ctx context.Context, root *RoleQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(rgb.fns)) + for _, fn := range rgb.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*rgb.flds)+len(rgb.fns)) + for _, f := range *rgb.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*rgb.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := rgb.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// RoleSelect is the builder for selecting fields of Role entities. +type RoleSelect struct { + *RoleQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (rs *RoleSelect) Aggregate(fns ...AggregateFunc) *RoleSelect { + rs.fns = append(rs.fns, fns...) + return rs +} + +// Scan applies the selector query and scans the result into the given value. +func (rs *RoleSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, rs.ctx, ent.OpQuerySelect) + if err := rs.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*RoleQuery, *RoleSelect](ctx, rs.RoleQuery, rs, rs.inters, v) +} + +func (rs *RoleSelect) sqlScan(ctx context.Context, root *RoleQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(rs.fns)) + for _, fn := range rs.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*rs.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := rs.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (rs *RoleSelect) Modify(modifiers ...func(s *sql.Selector)) *RoleSelect { + rs.modifiers = append(rs.modifiers, modifiers...) + return rs +} diff --git a/backend/db/role_update.go b/backend/db/role_update.go new file mode 100644 index 00000000..d7d1cb43 --- /dev/null +++ b/backend/db/role_update.go @@ -0,0 +1,621 @@ +// 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/admin" + "github.com/chaitin/MonkeyCode/backend/db/adminrole" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/role" + "github.com/google/uuid" +) + +// RoleUpdate is the builder for updating Role entities. +type RoleUpdate struct { + config + hooks []Hook + mutation *RoleMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the RoleUpdate builder. +func (ru *RoleUpdate) Where(ps ...predicate.Role) *RoleUpdate { + ru.mutation.Where(ps...) + return ru +} + +// SetName sets the "name" field. +func (ru *RoleUpdate) SetName(s string) *RoleUpdate { + ru.mutation.SetName(s) + return ru +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (ru *RoleUpdate) SetNillableName(s *string) *RoleUpdate { + if s != nil { + ru.SetName(*s) + } + return ru +} + +// SetDescription sets the "description" field. +func (ru *RoleUpdate) SetDescription(s string) *RoleUpdate { + ru.mutation.SetDescription(s) + return ru +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (ru *RoleUpdate) SetNillableDescription(s *string) *RoleUpdate { + if s != nil { + ru.SetDescription(*s) + } + return ru +} + +// SetCreatedAt sets the "created_at" field. +func (ru *RoleUpdate) SetCreatedAt(t time.Time) *RoleUpdate { + ru.mutation.SetCreatedAt(t) + return ru +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (ru *RoleUpdate) SetNillableCreatedAt(t *time.Time) *RoleUpdate { + if t != nil { + ru.SetCreatedAt(*t) + } + return ru +} + +// AddAdminIDs adds the "admins" edge to the Admin entity by IDs. +func (ru *RoleUpdate) AddAdminIDs(ids ...uuid.UUID) *RoleUpdate { + ru.mutation.AddAdminIDs(ids...) + return ru +} + +// AddAdmins adds the "admins" edges to the Admin entity. +func (ru *RoleUpdate) AddAdmins(a ...*Admin) *RoleUpdate { + ids := make([]uuid.UUID, len(a)) + for i := range a { + ids[i] = a[i].ID + } + return ru.AddAdminIDs(ids...) +} + +// AddAdminRoleIDs adds the "admin_roles" edge to the AdminRole entity by IDs. +func (ru *RoleUpdate) AddAdminRoleIDs(ids ...uuid.UUID) *RoleUpdate { + ru.mutation.AddAdminRoleIDs(ids...) + return ru +} + +// AddAdminRoles adds the "admin_roles" edges to the AdminRole entity. +func (ru *RoleUpdate) AddAdminRoles(a ...*AdminRole) *RoleUpdate { + ids := make([]uuid.UUID, len(a)) + for i := range a { + ids[i] = a[i].ID + } + return ru.AddAdminRoleIDs(ids...) +} + +// Mutation returns the RoleMutation object of the builder. +func (ru *RoleUpdate) Mutation() *RoleMutation { + return ru.mutation +} + +// ClearAdmins clears all "admins" edges to the Admin entity. +func (ru *RoleUpdate) ClearAdmins() *RoleUpdate { + ru.mutation.ClearAdmins() + return ru +} + +// RemoveAdminIDs removes the "admins" edge to Admin entities by IDs. +func (ru *RoleUpdate) RemoveAdminIDs(ids ...uuid.UUID) *RoleUpdate { + ru.mutation.RemoveAdminIDs(ids...) + return ru +} + +// RemoveAdmins removes "admins" edges to Admin entities. +func (ru *RoleUpdate) RemoveAdmins(a ...*Admin) *RoleUpdate { + ids := make([]uuid.UUID, len(a)) + for i := range a { + ids[i] = a[i].ID + } + return ru.RemoveAdminIDs(ids...) +} + +// ClearAdminRoles clears all "admin_roles" edges to the AdminRole entity. +func (ru *RoleUpdate) ClearAdminRoles() *RoleUpdate { + ru.mutation.ClearAdminRoles() + return ru +} + +// RemoveAdminRoleIDs removes the "admin_roles" edge to AdminRole entities by IDs. +func (ru *RoleUpdate) RemoveAdminRoleIDs(ids ...uuid.UUID) *RoleUpdate { + ru.mutation.RemoveAdminRoleIDs(ids...) + return ru +} + +// RemoveAdminRoles removes "admin_roles" edges to AdminRole entities. +func (ru *RoleUpdate) RemoveAdminRoles(a ...*AdminRole) *RoleUpdate { + ids := make([]uuid.UUID, len(a)) + for i := range a { + ids[i] = a[i].ID + } + return ru.RemoveAdminRoleIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (ru *RoleUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, ru.sqlSave, ru.mutation, ru.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (ru *RoleUpdate) SaveX(ctx context.Context) int { + affected, err := ru.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (ru *RoleUpdate) Exec(ctx context.Context) error { + _, err := ru.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ru *RoleUpdate) ExecX(ctx context.Context) { + if err := ru.Exec(ctx); err != nil { + panic(err) + } +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (ru *RoleUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *RoleUpdate { + ru.modifiers = append(ru.modifiers, modifiers...) + return ru +} + +func (ru *RoleUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := sqlgraph.NewUpdateSpec(role.Table, role.Columns, sqlgraph.NewFieldSpec(role.FieldID, field.TypeInt64)) + if ps := ru.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := ru.mutation.Name(); ok { + _spec.SetField(role.FieldName, field.TypeString, value) + } + if value, ok := ru.mutation.Description(); ok { + _spec.SetField(role.FieldDescription, field.TypeString, value) + } + if value, ok := ru.mutation.CreatedAt(); ok { + _spec.SetField(role.FieldCreatedAt, field.TypeTime, value) + } + if ru.mutation.AdminsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: role.AdminsTable, + Columns: role.AdminsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(admin.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ru.mutation.RemovedAdminsIDs(); len(nodes) > 0 && !ru.mutation.AdminsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: role.AdminsTable, + Columns: role.AdminsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(admin.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 := ru.mutation.AdminsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: role.AdminsTable, + Columns: role.AdminsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(admin.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if ru.mutation.AdminRolesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: role.AdminRolesTable, + Columns: []string{role.AdminRolesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(adminrole.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ru.mutation.RemovedAdminRolesIDs(); len(nodes) > 0 && !ru.mutation.AdminRolesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: role.AdminRolesTable, + Columns: []string{role.AdminRolesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(adminrole.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 := ru.mutation.AdminRolesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: role.AdminRolesTable, + Columns: []string{role.AdminRolesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(adminrole.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(ru.modifiers...) + if n, err = sqlgraph.UpdateNodes(ctx, ru.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{role.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + ru.mutation.done = true + return n, nil +} + +// RoleUpdateOne is the builder for updating a single Role entity. +type RoleUpdateOne struct { + config + fields []string + hooks []Hook + mutation *RoleMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetName sets the "name" field. +func (ruo *RoleUpdateOne) SetName(s string) *RoleUpdateOne { + ruo.mutation.SetName(s) + return ruo +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (ruo *RoleUpdateOne) SetNillableName(s *string) *RoleUpdateOne { + if s != nil { + ruo.SetName(*s) + } + return ruo +} + +// SetDescription sets the "description" field. +func (ruo *RoleUpdateOne) SetDescription(s string) *RoleUpdateOne { + ruo.mutation.SetDescription(s) + return ruo +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (ruo *RoleUpdateOne) SetNillableDescription(s *string) *RoleUpdateOne { + if s != nil { + ruo.SetDescription(*s) + } + return ruo +} + +// SetCreatedAt sets the "created_at" field. +func (ruo *RoleUpdateOne) SetCreatedAt(t time.Time) *RoleUpdateOne { + ruo.mutation.SetCreatedAt(t) + return ruo +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (ruo *RoleUpdateOne) SetNillableCreatedAt(t *time.Time) *RoleUpdateOne { + if t != nil { + ruo.SetCreatedAt(*t) + } + return ruo +} + +// AddAdminIDs adds the "admins" edge to the Admin entity by IDs. +func (ruo *RoleUpdateOne) AddAdminIDs(ids ...uuid.UUID) *RoleUpdateOne { + ruo.mutation.AddAdminIDs(ids...) + return ruo +} + +// AddAdmins adds the "admins" edges to the Admin entity. +func (ruo *RoleUpdateOne) AddAdmins(a ...*Admin) *RoleUpdateOne { + ids := make([]uuid.UUID, len(a)) + for i := range a { + ids[i] = a[i].ID + } + return ruo.AddAdminIDs(ids...) +} + +// AddAdminRoleIDs adds the "admin_roles" edge to the AdminRole entity by IDs. +func (ruo *RoleUpdateOne) AddAdminRoleIDs(ids ...uuid.UUID) *RoleUpdateOne { + ruo.mutation.AddAdminRoleIDs(ids...) + return ruo +} + +// AddAdminRoles adds the "admin_roles" edges to the AdminRole entity. +func (ruo *RoleUpdateOne) AddAdminRoles(a ...*AdminRole) *RoleUpdateOne { + ids := make([]uuid.UUID, len(a)) + for i := range a { + ids[i] = a[i].ID + } + return ruo.AddAdminRoleIDs(ids...) +} + +// Mutation returns the RoleMutation object of the builder. +func (ruo *RoleUpdateOne) Mutation() *RoleMutation { + return ruo.mutation +} + +// ClearAdmins clears all "admins" edges to the Admin entity. +func (ruo *RoleUpdateOne) ClearAdmins() *RoleUpdateOne { + ruo.mutation.ClearAdmins() + return ruo +} + +// RemoveAdminIDs removes the "admins" edge to Admin entities by IDs. +func (ruo *RoleUpdateOne) RemoveAdminIDs(ids ...uuid.UUID) *RoleUpdateOne { + ruo.mutation.RemoveAdminIDs(ids...) + return ruo +} + +// RemoveAdmins removes "admins" edges to Admin entities. +func (ruo *RoleUpdateOne) RemoveAdmins(a ...*Admin) *RoleUpdateOne { + ids := make([]uuid.UUID, len(a)) + for i := range a { + ids[i] = a[i].ID + } + return ruo.RemoveAdminIDs(ids...) +} + +// ClearAdminRoles clears all "admin_roles" edges to the AdminRole entity. +func (ruo *RoleUpdateOne) ClearAdminRoles() *RoleUpdateOne { + ruo.mutation.ClearAdminRoles() + return ruo +} + +// RemoveAdminRoleIDs removes the "admin_roles" edge to AdminRole entities by IDs. +func (ruo *RoleUpdateOne) RemoveAdminRoleIDs(ids ...uuid.UUID) *RoleUpdateOne { + ruo.mutation.RemoveAdminRoleIDs(ids...) + return ruo +} + +// RemoveAdminRoles removes "admin_roles" edges to AdminRole entities. +func (ruo *RoleUpdateOne) RemoveAdminRoles(a ...*AdminRole) *RoleUpdateOne { + ids := make([]uuid.UUID, len(a)) + for i := range a { + ids[i] = a[i].ID + } + return ruo.RemoveAdminRoleIDs(ids...) +} + +// Where appends a list predicates to the RoleUpdate builder. +func (ruo *RoleUpdateOne) Where(ps ...predicate.Role) *RoleUpdateOne { + ruo.mutation.Where(ps...) + return ruo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (ruo *RoleUpdateOne) Select(field string, fields ...string) *RoleUpdateOne { + ruo.fields = append([]string{field}, fields...) + return ruo +} + +// Save executes the query and returns the updated Role entity. +func (ruo *RoleUpdateOne) Save(ctx context.Context) (*Role, error) { + return withHooks(ctx, ruo.sqlSave, ruo.mutation, ruo.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (ruo *RoleUpdateOne) SaveX(ctx context.Context) *Role { + node, err := ruo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (ruo *RoleUpdateOne) Exec(ctx context.Context) error { + _, err := ruo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ruo *RoleUpdateOne) ExecX(ctx context.Context) { + if err := ruo.Exec(ctx); err != nil { + panic(err) + } +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (ruo *RoleUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *RoleUpdateOne { + ruo.modifiers = append(ruo.modifiers, modifiers...) + return ruo +} + +func (ruo *RoleUpdateOne) sqlSave(ctx context.Context) (_node *Role, err error) { + _spec := sqlgraph.NewUpdateSpec(role.Table, role.Columns, sqlgraph.NewFieldSpec(role.FieldID, field.TypeInt64)) + id, ok := ruo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "Role.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := ruo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, role.FieldID) + for _, f := range fields { + if !role.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != role.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := ruo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := ruo.mutation.Name(); ok { + _spec.SetField(role.FieldName, field.TypeString, value) + } + if value, ok := ruo.mutation.Description(); ok { + _spec.SetField(role.FieldDescription, field.TypeString, value) + } + if value, ok := ruo.mutation.CreatedAt(); ok { + _spec.SetField(role.FieldCreatedAt, field.TypeTime, value) + } + if ruo.mutation.AdminsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: role.AdminsTable, + Columns: role.AdminsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(admin.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ruo.mutation.RemovedAdminsIDs(); len(nodes) > 0 && !ruo.mutation.AdminsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: role.AdminsTable, + Columns: role.AdminsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(admin.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 := ruo.mutation.AdminsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: role.AdminsTable, + Columns: role.AdminsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(admin.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if ruo.mutation.AdminRolesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: role.AdminRolesTable, + Columns: []string{role.AdminRolesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(adminrole.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ruo.mutation.RemovedAdminRolesIDs(); len(nodes) > 0 && !ruo.mutation.AdminRolesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: role.AdminRolesTable, + Columns: []string{role.AdminRolesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(adminrole.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 := ruo.mutation.AdminRolesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: role.AdminRolesTable, + Columns: []string{role.AdminRolesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(adminrole.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(ruo.modifiers...) + _node = &Role{config: ruo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, ruo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{role.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + ruo.mutation.done = true + return _node, nil +} diff --git a/backend/db/runtime/runtime.go b/backend/db/runtime/runtime.go index 63e364c5..aed89d0a 100644 --- a/backend/db/runtime/runtime.go +++ b/backend/db/runtime/runtime.go @@ -19,12 +19,14 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/model" "github.com/chaitin/MonkeyCode/backend/db/modelprovider" "github.com/chaitin/MonkeyCode/backend/db/modelprovidermodel" + "github.com/chaitin/MonkeyCode/backend/db/role" "github.com/chaitin/MonkeyCode/backend/db/securityscanning" "github.com/chaitin/MonkeyCode/backend/db/securityscanningresult" "github.com/chaitin/MonkeyCode/backend/db/setting" "github.com/chaitin/MonkeyCode/backend/db/task" "github.com/chaitin/MonkeyCode/backend/db/taskrecord" "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/usergroup" "github.com/chaitin/MonkeyCode/backend/db/useridentity" "github.com/chaitin/MonkeyCode/backend/db/userloginhistory" "github.com/chaitin/MonkeyCode/backend/db/workspace" @@ -237,6 +239,12 @@ func init() { modelprovidermodelDescID := modelprovidermodelFields[0].Descriptor() // modelprovidermodel.DefaultID holds the default value on creation for the id field. modelprovidermodel.DefaultID = modelprovidermodelDescID.Default.(func() uuid.UUID) + roleFields := schema.Role{}.Fields() + _ = roleFields + // roleDescCreatedAt is the schema descriptor for created_at field. + roleDescCreatedAt := roleFields[3].Descriptor() + // role.DefaultCreatedAt holds the default value on creation for the created_at field. + role.DefaultCreatedAt = roleDescCreatedAt.Default.(func() time.Time) securityscanningFields := schema.SecurityScanning{}.Fields() _ = securityscanningFields // securityscanningDescCreatedAt is the schema descriptor for created_at field. @@ -344,6 +352,16 @@ func init() { userDescUpdatedAt := userFields[8].Descriptor() // user.DefaultUpdatedAt holds the default value on creation for the updated_at field. user.DefaultUpdatedAt = userDescUpdatedAt.Default.(func() time.Time) + usergroupFields := schema.UserGroup{}.Fields() + _ = usergroupFields + // usergroupDescName is the schema descriptor for name field. + usergroupDescName := usergroupFields[2].Descriptor() + // usergroup.NameValidator is a validator for the "name" field. It is called by the builders before save. + usergroup.NameValidator = usergroupDescName.Validators[0].(func(string) error) + // usergroupDescCreatedAt is the schema descriptor for created_at field. + usergroupDescCreatedAt := usergroupFields[3].Descriptor() + // usergroup.DefaultCreatedAt holds the default value on creation for the created_at field. + usergroup.DefaultCreatedAt = usergroupDescCreatedAt.Default.(func() time.Time) useridentityMixin := schema.UserIdentity{}.Mixin() useridentityMixinHooks0 := useridentityMixin[0].Hooks() useridentity.Hooks[0] = useridentityMixinHooks0[0] diff --git a/backend/db/tx.go b/backend/db/tx.go index 1e92fa01..86925f77 100644 --- a/backend/db/tx.go +++ b/backend/db/tx.go @@ -18,6 +18,8 @@ type Tx struct { Admin *AdminClient // AdminLoginHistory is the client for interacting with the AdminLoginHistory builders. AdminLoginHistory *AdminLoginHistoryClient + // AdminRole is the client for interacting with the AdminRole builders. + AdminRole *AdminRoleClient // ApiKey is the client for interacting with the ApiKey builders. ApiKey *ApiKeyClient // BillingPlan is the client for interacting with the BillingPlan builders. @@ -42,6 +44,8 @@ type Tx struct { ModelProvider *ModelProviderClient // ModelProviderModel is the client for interacting with the ModelProviderModel builders. ModelProviderModel *ModelProviderModelClient + // Role is the client for interacting with the Role builders. + Role *RoleClient // SecurityScanning is the client for interacting with the SecurityScanning builders. SecurityScanning *SecurityScanningClient // SecurityScanningResult is the client for interacting with the SecurityScanningResult builders. @@ -54,6 +58,12 @@ type Tx struct { TaskRecord *TaskRecordClient // User is the client for interacting with the User builders. User *UserClient + // UserGroup is the client for interacting with the UserGroup builders. + UserGroup *UserGroupClient + // UserGroupAdmin is the client for interacting with the UserGroupAdmin builders. + UserGroupAdmin *UserGroupAdminClient + // UserGroupUser is the client for interacting with the UserGroupUser builders. + UserGroupUser *UserGroupUserClient // UserIdentity is the client for interacting with the UserIdentity builders. UserIdentity *UserIdentityClient // UserLoginHistory is the client for interacting with the UserLoginHistory builders. @@ -195,6 +205,7 @@ func (tx *Tx) Client() *Client { func (tx *Tx) init() { tx.Admin = NewAdminClient(tx.config) tx.AdminLoginHistory = NewAdminLoginHistoryClient(tx.config) + tx.AdminRole = NewAdminRoleClient(tx.config) tx.ApiKey = NewApiKeyClient(tx.config) tx.BillingPlan = NewBillingPlanClient(tx.config) tx.BillingQuota = NewBillingQuotaClient(tx.config) @@ -207,12 +218,16 @@ func (tx *Tx) init() { tx.Model = NewModelClient(tx.config) tx.ModelProvider = NewModelProviderClient(tx.config) tx.ModelProviderModel = NewModelProviderModelClient(tx.config) + tx.Role = NewRoleClient(tx.config) tx.SecurityScanning = NewSecurityScanningClient(tx.config) tx.SecurityScanningResult = NewSecurityScanningResultClient(tx.config) tx.Setting = NewSettingClient(tx.config) tx.Task = NewTaskClient(tx.config) tx.TaskRecord = NewTaskRecordClient(tx.config) tx.User = NewUserClient(tx.config) + tx.UserGroup = NewUserGroupClient(tx.config) + tx.UserGroupAdmin = NewUserGroupAdminClient(tx.config) + tx.UserGroupUser = NewUserGroupUserClient(tx.config) tx.UserIdentity = NewUserIdentityClient(tx.config) tx.UserLoginHistory = NewUserLoginHistoryClient(tx.config) tx.Workspace = NewWorkspaceClient(tx.config) diff --git a/backend/db/user.go b/backend/db/user.go index ec0b3bd0..7a74affe 100644 --- a/backend/db/user.go +++ b/backend/db/user.go @@ -61,9 +61,13 @@ type UserEdges struct { APIKeys []*ApiKey `json:"api_keys,omitempty"` // SecurityScannings holds the value of the security_scannings edge. SecurityScannings []*SecurityScanning `json:"security_scannings,omitempty"` + // Groups holds the value of the groups edge. + Groups []*UserGroup `json:"groups,omitempty"` + // UserGroups holds the value of the user_groups edge. + UserGroups []*UserGroupUser `json:"user_groups,omitempty"` // loadedTypes holds the information for reporting if a // type was loaded (or requested) in eager-loading or not. - loadedTypes [8]bool + loadedTypes [10]bool } // LoginHistoriesOrErr returns the LoginHistories value or an error if the edge @@ -138,6 +142,24 @@ func (e UserEdges) SecurityScanningsOrErr() ([]*SecurityScanning, error) { return nil, &NotLoadedError{edge: "security_scannings"} } +// GroupsOrErr returns the Groups value or an error if the edge +// was not loaded in eager-loading. +func (e UserEdges) GroupsOrErr() ([]*UserGroup, error) { + if e.loadedTypes[8] { + return e.Groups, nil + } + return nil, &NotLoadedError{edge: "groups"} +} + +// UserGroupsOrErr returns the UserGroups value or an error if the edge +// was not loaded in eager-loading. +func (e UserEdges) UserGroupsOrErr() ([]*UserGroupUser, error) { + if e.loadedTypes[9] { + return e.UserGroups, nil + } + return nil, &NotLoadedError{edge: "user_groups"} +} + // scanValues returns the types for scanning values from sql.Rows. func (*User) scanValues(columns []string) ([]any, error) { values := make([]any, len(columns)) @@ -277,6 +299,16 @@ func (u *User) QuerySecurityScannings() *SecurityScanningQuery { return NewUserClient(u.config).QuerySecurityScannings(u) } +// QueryGroups queries the "groups" edge of the User entity. +func (u *User) QueryGroups() *UserGroupQuery { + return NewUserClient(u.config).QueryGroups(u) +} + +// QueryUserGroups queries the "user_groups" edge of the User entity. +func (u *User) QueryUserGroups() *UserGroupUserQuery { + return NewUserClient(u.config).QueryUserGroups(u) +} + // Update returns a builder for updating this User. // Note that you need to call User.Unwrap() before calling this method if this User // was returned from a transaction, and the transaction was committed or rolled back. diff --git a/backend/db/user/user.go b/backend/db/user/user.go index c880ce17..67b75a47 100644 --- a/backend/db/user/user.go +++ b/backend/db/user/user.go @@ -50,6 +50,10 @@ const ( EdgeAPIKeys = "api_keys" // EdgeSecurityScannings holds the string denoting the security_scannings edge name in mutations. EdgeSecurityScannings = "security_scannings" + // EdgeGroups holds the string denoting the groups edge name in mutations. + EdgeGroups = "groups" + // EdgeUserGroups holds the string denoting the user_groups edge name in mutations. + EdgeUserGroups = "user_groups" // Table holds the table name of the user in the database. Table = "users" // LoginHistoriesTable is the table that holds the login_histories relation/edge. @@ -108,6 +112,18 @@ const ( SecurityScanningsInverseTable = "security_scannings" // SecurityScanningsColumn is the table column denoting the security_scannings relation/edge. SecurityScanningsColumn = "user_id" + // GroupsTable is the table that holds the groups relation/edge. The primary key declared below. + GroupsTable = "user_group_users" + // GroupsInverseTable is the table name for the UserGroup entity. + // It exists in this package in order to avoid circular dependency with the "usergroup" package. + GroupsInverseTable = "user_groups" + // UserGroupsTable is the table that holds the user_groups relation/edge. + UserGroupsTable = "user_group_users" + // UserGroupsInverseTable is the table name for the UserGroupUser entity. + // It exists in this package in order to avoid circular dependency with the "usergroupuser" package. + UserGroupsInverseTable = "user_group_users" + // UserGroupsColumn is the table column denoting the user_groups relation/edge. + UserGroupsColumn = "user_id" ) // Columns holds all SQL columns for user fields. @@ -124,6 +140,12 @@ var Columns = []string{ FieldUpdatedAt, } +var ( + // GroupsPrimaryKey and GroupsColumn2 are the table columns denoting the + // primary key for the groups relation (M2M). + GroupsPrimaryKey = []string{"user_group_id", "user_id"} +) + // ValidColumn reports if the column name is valid (part of the table columns). func ValidColumn(column string) bool { for i := range Columns { @@ -316,6 +338,34 @@ func BySecurityScannings(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption sqlgraph.OrderByNeighborTerms(s, newSecurityScanningsStep(), append([]sql.OrderTerm{term}, terms...)...) } } + +// ByGroupsCount orders the results by groups count. +func ByGroupsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newGroupsStep(), opts...) + } +} + +// ByGroups orders the results by groups terms. +func ByGroups(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newGroupsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByUserGroupsCount orders the results by user_groups count. +func ByUserGroupsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newUserGroupsStep(), opts...) + } +} + +// ByUserGroups orders the results by user_groups terms. +func ByUserGroups(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newUserGroupsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} func newLoginHistoriesStep() *sqlgraph.Step { return sqlgraph.NewStep( sqlgraph.From(Table, FieldID), @@ -372,3 +422,17 @@ func newSecurityScanningsStep() *sqlgraph.Step { sqlgraph.Edge(sqlgraph.O2M, false, SecurityScanningsTable, SecurityScanningsColumn), ) } +func newGroupsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(GroupsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, GroupsTable, GroupsPrimaryKey...), + ) +} +func newUserGroupsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(UserGroupsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, UserGroupsTable, UserGroupsColumn), + ) +} diff --git a/backend/db/user/where.go b/backend/db/user/where.go index 9ef025af..fa6985ea 100644 --- a/backend/db/user/where.go +++ b/backend/db/user/where.go @@ -886,6 +886,52 @@ func HasSecurityScanningsWith(preds ...predicate.SecurityScanning) predicate.Use }) } +// HasGroups applies the HasEdge predicate on the "groups" edge. +func HasGroups() predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, GroupsTable, GroupsPrimaryKey...), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasGroupsWith applies the HasEdge predicate on the "groups" edge with a given conditions (other predicates). +func HasGroupsWith(preds ...predicate.UserGroup) predicate.User { + return predicate.User(func(s *sql.Selector) { + step := newGroupsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasUserGroups applies the HasEdge predicate on the "user_groups" edge. +func HasUserGroups() predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, UserGroupsTable, UserGroupsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasUserGroupsWith applies the HasEdge predicate on the "user_groups" edge with a given conditions (other predicates). +func HasUserGroupsWith(preds ...predicate.UserGroupUser) predicate.User { + return predicate.User(func(s *sql.Selector) { + step := newUserGroupsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + // And groups predicates with the AND operator between them. func And(predicates ...predicate.User) predicate.User { return predicate.User(sql.AndPredicates(predicates...)) diff --git a/backend/db/user_create.go b/backend/db/user_create.go index 296f363b..ce6f7d6b 100644 --- a/backend/db/user_create.go +++ b/backend/db/user_create.go @@ -18,6 +18,8 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/securityscanning" "github.com/chaitin/MonkeyCode/backend/db/task" "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/usergroup" + "github.com/chaitin/MonkeyCode/backend/db/usergroupuser" "github.com/chaitin/MonkeyCode/backend/db/useridentity" "github.com/chaitin/MonkeyCode/backend/db/userloginhistory" "github.com/chaitin/MonkeyCode/backend/db/workspace" @@ -285,6 +287,36 @@ func (uc *UserCreate) AddSecurityScannings(s ...*SecurityScanning) *UserCreate { return uc.AddSecurityScanningIDs(ids...) } +// AddGroupIDs adds the "groups" edge to the UserGroup entity by IDs. +func (uc *UserCreate) AddGroupIDs(ids ...uuid.UUID) *UserCreate { + uc.mutation.AddGroupIDs(ids...) + return uc +} + +// AddGroups adds the "groups" edges to the UserGroup entity. +func (uc *UserCreate) AddGroups(u ...*UserGroup) *UserCreate { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uc.AddGroupIDs(ids...) +} + +// AddUserGroupIDs adds the "user_groups" edge to the UserGroupUser entity by IDs. +func (uc *UserCreate) AddUserGroupIDs(ids ...uuid.UUID) *UserCreate { + uc.mutation.AddUserGroupIDs(ids...) + return uc +} + +// AddUserGroups adds the "user_groups" edges to the UserGroupUser entity. +func (uc *UserCreate) AddUserGroups(u ...*UserGroupUser) *UserCreate { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uc.AddUserGroupIDs(ids...) +} + // Mutation returns the UserMutation object of the builder. func (uc *UserCreate) Mutation() *UserMutation { return uc.mutation @@ -561,6 +593,38 @@ func (uc *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) { } _spec.Edges = append(_spec.Edges, edge) } + if nodes := uc.mutation.GroupsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: user.GroupsTable, + Columns: user.GroupsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroup.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := uc.mutation.UserGroupsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.UserGroupsTable, + Columns: []string{user.UserGroupsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroupuser.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } return _node, _spec } diff --git a/backend/db/user_query.go b/backend/db/user_query.go index 49d7fc7f..e5355d0d 100644 --- a/backend/db/user_query.go +++ b/backend/db/user_query.go @@ -19,6 +19,8 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/securityscanning" "github.com/chaitin/MonkeyCode/backend/db/task" "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/usergroup" + "github.com/chaitin/MonkeyCode/backend/db/usergroupuser" "github.com/chaitin/MonkeyCode/backend/db/useridentity" "github.com/chaitin/MonkeyCode/backend/db/userloginhistory" "github.com/chaitin/MonkeyCode/backend/db/workspace" @@ -41,6 +43,8 @@ type UserQuery struct { withWorkspaceFiles *WorkspaceFileQuery withAPIKeys *ApiKeyQuery withSecurityScannings *SecurityScanningQuery + withGroups *UserGroupQuery + withUserGroups *UserGroupUserQuery modifiers []func(*sql.Selector) // intermediate query (i.e. traversal path). sql *sql.Selector @@ -254,6 +258,50 @@ func (uq *UserQuery) QuerySecurityScannings() *SecurityScanningQuery { return query } +// QueryGroups chains the current query on the "groups" edge. +func (uq *UserQuery) QueryGroups() *UserGroupQuery { + query := (&UserGroupClient{config: uq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := uq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := uq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, selector), + sqlgraph.To(usergroup.Table, usergroup.FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, user.GroupsTable, user.GroupsPrimaryKey...), + ) + fromU = sqlgraph.SetNeighbors(uq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryUserGroups chains the current query on the "user_groups" edge. +func (uq *UserQuery) QueryUserGroups() *UserGroupUserQuery { + query := (&UserGroupUserClient{config: uq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := uq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := uq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, selector), + sqlgraph.To(usergroupuser.Table, usergroupuser.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, user.UserGroupsTable, user.UserGroupsColumn), + ) + fromU = sqlgraph.SetNeighbors(uq.driver.Dialect(), step) + return fromU, nil + } + return query +} + // First returns the first User entity from the query. // Returns a *NotFoundError when no User was found. func (uq *UserQuery) First(ctx context.Context) (*User, error) { @@ -454,6 +502,8 @@ func (uq *UserQuery) Clone() *UserQuery { withWorkspaceFiles: uq.withWorkspaceFiles.Clone(), withAPIKeys: uq.withAPIKeys.Clone(), withSecurityScannings: uq.withSecurityScannings.Clone(), + withGroups: uq.withGroups.Clone(), + withUserGroups: uq.withUserGroups.Clone(), // clone intermediate query. sql: uq.sql.Clone(), path: uq.path, @@ -549,6 +599,28 @@ func (uq *UserQuery) WithSecurityScannings(opts ...func(*SecurityScanningQuery)) return uq } +// WithGroups tells the query-builder to eager-load the nodes that are connected to +// the "groups" edge. The optional arguments are used to configure the query builder of the edge. +func (uq *UserQuery) WithGroups(opts ...func(*UserGroupQuery)) *UserQuery { + query := (&UserGroupClient{config: uq.config}).Query() + for _, opt := range opts { + opt(query) + } + uq.withGroups = query + return uq +} + +// WithUserGroups tells the query-builder to eager-load the nodes that are connected to +// the "user_groups" edge. The optional arguments are used to configure the query builder of the edge. +func (uq *UserQuery) WithUserGroups(opts ...func(*UserGroupUserQuery)) *UserQuery { + query := (&UserGroupUserClient{config: uq.config}).Query() + for _, opt := range opts { + opt(query) + } + uq.withUserGroups = query + return uq +} + // GroupBy is used to group vertices by one or more fields/columns. // It is often used with aggregate functions, like: count, max, mean, min, sum. // @@ -627,7 +699,7 @@ func (uq *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, e var ( nodes = []*User{} _spec = uq.querySpec() - loadedTypes = [8]bool{ + loadedTypes = [10]bool{ uq.withLoginHistories != nil, uq.withModels != nil, uq.withTasks != nil, @@ -636,6 +708,8 @@ func (uq *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, e uq.withWorkspaceFiles != nil, uq.withAPIKeys != nil, uq.withSecurityScannings != nil, + uq.withGroups != nil, + uq.withUserGroups != nil, } ) _spec.ScanValues = func(columns []string) ([]any, error) { @@ -715,6 +789,20 @@ func (uq *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, e return nil, err } } + if query := uq.withGroups; query != nil { + if err := uq.loadGroups(ctx, query, nodes, + func(n *User) { n.Edges.Groups = []*UserGroup{} }, + func(n *User, e *UserGroup) { n.Edges.Groups = append(n.Edges.Groups, e) }); err != nil { + return nil, err + } + } + if query := uq.withUserGroups; query != nil { + if err := uq.loadUserGroups(ctx, query, nodes, + func(n *User) { n.Edges.UserGroups = []*UserGroupUser{} }, + func(n *User, e *UserGroupUser) { n.Edges.UserGroups = append(n.Edges.UserGroups, e) }); err != nil { + return nil, err + } + } return nodes, nil } @@ -958,6 +1046,97 @@ func (uq *UserQuery) loadSecurityScannings(ctx context.Context, query *SecurityS } return nil } +func (uq *UserQuery) loadGroups(ctx context.Context, query *UserGroupQuery, nodes []*User, init func(*User), assign func(*User, *UserGroup)) error { + edgeIDs := make([]driver.Value, len(nodes)) + byID := make(map[uuid.UUID]*User) + nids := make(map[uuid.UUID]map[*User]struct{}) + for i, node := range nodes { + edgeIDs[i] = node.ID + byID[node.ID] = node + if init != nil { + init(node) + } + } + query.Where(func(s *sql.Selector) { + joinT := sql.Table(user.GroupsTable) + s.Join(joinT).On(s.C(usergroup.FieldID), joinT.C(user.GroupsPrimaryKey[0])) + s.Where(sql.InValues(joinT.C(user.GroupsPrimaryKey[1]), edgeIDs...)) + columns := s.SelectedColumns() + s.Select(joinT.C(user.GroupsPrimaryKey[1])) + s.AppendSelect(columns...) + s.SetDistinct(false) + }) + if err := query.prepareQuery(ctx); err != nil { + return err + } + qr := QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + return query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) { + assign := spec.Assign + values := spec.ScanValues + spec.ScanValues = func(columns []string) ([]any, error) { + values, err := values(columns[1:]) + if err != nil { + return nil, err + } + return append([]any{new(uuid.UUID)}, values...), nil + } + spec.Assign = func(columns []string, values []any) error { + outValue := *values[0].(*uuid.UUID) + inValue := *values[1].(*uuid.UUID) + if nids[inValue] == nil { + nids[inValue] = map[*User]struct{}{byID[outValue]: {}} + return assign(columns[1:], values[1:]) + } + nids[inValue][byID[outValue]] = struct{}{} + return nil + } + }) + }) + neighbors, err := withInterceptors[[]*UserGroup](ctx, query, qr, query.inters) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nids[n.ID] + if !ok { + return fmt.Errorf(`unexpected "groups" node returned %v`, n.ID) + } + for kn := range nodes { + assign(kn, n) + } + } + return nil +} +func (uq *UserQuery) loadUserGroups(ctx context.Context, query *UserGroupUserQuery, nodes []*User, init func(*User), assign func(*User, *UserGroupUser)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[uuid.UUID]*User) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) + } + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(usergroupuser.FieldUserID) + } + query.Where(predicate.UserGroupUser(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(user.UserGroupsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.UserID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "user_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} func (uq *UserQuery) sqlCount(ctx context.Context) (int, error) { _spec := uq.querySpec() diff --git a/backend/db/user_update.go b/backend/db/user_update.go index 0118336d..b6463442 100644 --- a/backend/db/user_update.go +++ b/backend/db/user_update.go @@ -18,6 +18,8 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/securityscanning" "github.com/chaitin/MonkeyCode/backend/db/task" "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/usergroup" + "github.com/chaitin/MonkeyCode/backend/db/usergroupuser" "github.com/chaitin/MonkeyCode/backend/db/useridentity" "github.com/chaitin/MonkeyCode/backend/db/userloginhistory" "github.com/chaitin/MonkeyCode/backend/db/workspace" @@ -315,6 +317,36 @@ func (uu *UserUpdate) AddSecurityScannings(s ...*SecurityScanning) *UserUpdate { return uu.AddSecurityScanningIDs(ids...) } +// AddGroupIDs adds the "groups" edge to the UserGroup entity by IDs. +func (uu *UserUpdate) AddGroupIDs(ids ...uuid.UUID) *UserUpdate { + uu.mutation.AddGroupIDs(ids...) + return uu +} + +// AddGroups adds the "groups" edges to the UserGroup entity. +func (uu *UserUpdate) AddGroups(u ...*UserGroup) *UserUpdate { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uu.AddGroupIDs(ids...) +} + +// AddUserGroupIDs adds the "user_groups" edge to the UserGroupUser entity by IDs. +func (uu *UserUpdate) AddUserGroupIDs(ids ...uuid.UUID) *UserUpdate { + uu.mutation.AddUserGroupIDs(ids...) + return uu +} + +// AddUserGroups adds the "user_groups" edges to the UserGroupUser entity. +func (uu *UserUpdate) AddUserGroups(u ...*UserGroupUser) *UserUpdate { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uu.AddUserGroupIDs(ids...) +} + // Mutation returns the UserMutation object of the builder. func (uu *UserUpdate) Mutation() *UserMutation { return uu.mutation @@ -488,6 +520,48 @@ func (uu *UserUpdate) RemoveSecurityScannings(s ...*SecurityScanning) *UserUpdat return uu.RemoveSecurityScanningIDs(ids...) } +// ClearGroups clears all "groups" edges to the UserGroup entity. +func (uu *UserUpdate) ClearGroups() *UserUpdate { + uu.mutation.ClearGroups() + return uu +} + +// RemoveGroupIDs removes the "groups" edge to UserGroup entities by IDs. +func (uu *UserUpdate) RemoveGroupIDs(ids ...uuid.UUID) *UserUpdate { + uu.mutation.RemoveGroupIDs(ids...) + return uu +} + +// RemoveGroups removes "groups" edges to UserGroup entities. +func (uu *UserUpdate) RemoveGroups(u ...*UserGroup) *UserUpdate { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uu.RemoveGroupIDs(ids...) +} + +// ClearUserGroups clears all "user_groups" edges to the UserGroupUser entity. +func (uu *UserUpdate) ClearUserGroups() *UserUpdate { + uu.mutation.ClearUserGroups() + return uu +} + +// RemoveUserGroupIDs removes the "user_groups" edge to UserGroupUser entities by IDs. +func (uu *UserUpdate) RemoveUserGroupIDs(ids ...uuid.UUID) *UserUpdate { + uu.mutation.RemoveUserGroupIDs(ids...) + return uu +} + +// RemoveUserGroups removes "user_groups" edges to UserGroupUser entities. +func (uu *UserUpdate) RemoveUserGroups(u ...*UserGroupUser) *UserUpdate { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uu.RemoveUserGroupIDs(ids...) +} + // Save executes the query and returns the number of nodes affected by the update operation. func (uu *UserUpdate) Save(ctx context.Context) (int, error) { return withHooks(ctx, uu.sqlSave, uu.mutation, uu.hooks) @@ -932,6 +1006,96 @@ func (uu *UserUpdate) sqlSave(ctx context.Context) (n int, err error) { } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if uu.mutation.GroupsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: user.GroupsTable, + Columns: user.GroupsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroup.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uu.mutation.RemovedGroupsIDs(); len(nodes) > 0 && !uu.mutation.GroupsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: user.GroupsTable, + Columns: user.GroupsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroup.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uu.mutation.GroupsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: user.GroupsTable, + Columns: user.GroupsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroup.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if uu.mutation.UserGroupsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.UserGroupsTable, + Columns: []string{user.UserGroupsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroupuser.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uu.mutation.RemovedUserGroupsIDs(); len(nodes) > 0 && !uu.mutation.UserGroupsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.UserGroupsTable, + Columns: []string{user.UserGroupsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroupuser.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uu.mutation.UserGroupsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.UserGroupsTable, + Columns: []string{user.UserGroupsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroupuser.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } _spec.AddModifiers(uu.modifiers...) if n, err = sqlgraph.UpdateNodes(ctx, uu.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { @@ -1230,6 +1394,36 @@ func (uuo *UserUpdateOne) AddSecurityScannings(s ...*SecurityScanning) *UserUpda return uuo.AddSecurityScanningIDs(ids...) } +// AddGroupIDs adds the "groups" edge to the UserGroup entity by IDs. +func (uuo *UserUpdateOne) AddGroupIDs(ids ...uuid.UUID) *UserUpdateOne { + uuo.mutation.AddGroupIDs(ids...) + return uuo +} + +// AddGroups adds the "groups" edges to the UserGroup entity. +func (uuo *UserUpdateOne) AddGroups(u ...*UserGroup) *UserUpdateOne { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uuo.AddGroupIDs(ids...) +} + +// AddUserGroupIDs adds the "user_groups" edge to the UserGroupUser entity by IDs. +func (uuo *UserUpdateOne) AddUserGroupIDs(ids ...uuid.UUID) *UserUpdateOne { + uuo.mutation.AddUserGroupIDs(ids...) + return uuo +} + +// AddUserGroups adds the "user_groups" edges to the UserGroupUser entity. +func (uuo *UserUpdateOne) AddUserGroups(u ...*UserGroupUser) *UserUpdateOne { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uuo.AddUserGroupIDs(ids...) +} + // Mutation returns the UserMutation object of the builder. func (uuo *UserUpdateOne) Mutation() *UserMutation { return uuo.mutation @@ -1403,6 +1597,48 @@ func (uuo *UserUpdateOne) RemoveSecurityScannings(s ...*SecurityScanning) *UserU return uuo.RemoveSecurityScanningIDs(ids...) } +// ClearGroups clears all "groups" edges to the UserGroup entity. +func (uuo *UserUpdateOne) ClearGroups() *UserUpdateOne { + uuo.mutation.ClearGroups() + return uuo +} + +// RemoveGroupIDs removes the "groups" edge to UserGroup entities by IDs. +func (uuo *UserUpdateOne) RemoveGroupIDs(ids ...uuid.UUID) *UserUpdateOne { + uuo.mutation.RemoveGroupIDs(ids...) + return uuo +} + +// RemoveGroups removes "groups" edges to UserGroup entities. +func (uuo *UserUpdateOne) RemoveGroups(u ...*UserGroup) *UserUpdateOne { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uuo.RemoveGroupIDs(ids...) +} + +// ClearUserGroups clears all "user_groups" edges to the UserGroupUser entity. +func (uuo *UserUpdateOne) ClearUserGroups() *UserUpdateOne { + uuo.mutation.ClearUserGroups() + return uuo +} + +// RemoveUserGroupIDs removes the "user_groups" edge to UserGroupUser entities by IDs. +func (uuo *UserUpdateOne) RemoveUserGroupIDs(ids ...uuid.UUID) *UserUpdateOne { + uuo.mutation.RemoveUserGroupIDs(ids...) + return uuo +} + +// RemoveUserGroups removes "user_groups" edges to UserGroupUser entities. +func (uuo *UserUpdateOne) RemoveUserGroups(u ...*UserGroupUser) *UserUpdateOne { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uuo.RemoveUserGroupIDs(ids...) +} + // Where appends a list predicates to the UserUpdate builder. func (uuo *UserUpdateOne) Where(ps ...predicate.User) *UserUpdateOne { uuo.mutation.Where(ps...) @@ -1877,6 +2113,96 @@ func (uuo *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if uuo.mutation.GroupsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: user.GroupsTable, + Columns: user.GroupsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroup.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uuo.mutation.RemovedGroupsIDs(); len(nodes) > 0 && !uuo.mutation.GroupsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: user.GroupsTable, + Columns: user.GroupsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroup.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uuo.mutation.GroupsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: user.GroupsTable, + Columns: user.GroupsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroup.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if uuo.mutation.UserGroupsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.UserGroupsTable, + Columns: []string{user.UserGroupsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroupuser.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uuo.mutation.RemovedUserGroupsIDs(); len(nodes) > 0 && !uuo.mutation.UserGroupsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.UserGroupsTable, + Columns: []string{user.UserGroupsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroupuser.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uuo.mutation.UserGroupsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.UserGroupsTable, + Columns: []string{user.UserGroupsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroupuser.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } _spec.AddModifiers(uuo.modifiers...) _node = &User{config: uuo.config} _spec.Assign = _node.assignValues diff --git a/backend/db/usergroup.go b/backend/db/usergroup.go new file mode 100644 index 00000000..1eb2e1ab --- /dev/null +++ b/backend/db/usergroup.go @@ -0,0 +1,222 @@ +// 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/admin" + "github.com/chaitin/MonkeyCode/backend/db/usergroup" + "github.com/google/uuid" +) + +// UserGroup is the model entity for the UserGroup schema. +type UserGroup struct { + config `json:"-"` + // ID of the ent. + ID uuid.UUID `json:"id,omitempty"` + // AdminID holds the value of the "admin_id" field. + AdminID uuid.UUID `json:"admin_id,omitempty"` + // Name holds the value of the "name" field. + Name string `json:"name,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 UserGroupQuery when eager-loading is set. + Edges UserGroupEdges `json:"edges"` + selectValues sql.SelectValues +} + +// UserGroupEdges holds the relations/edges for other nodes in the graph. +type UserGroupEdges struct { + // Owner holds the value of the owner edge. + Owner *Admin `json:"owner,omitempty"` + // Users holds the value of the users edge. + Users []*User `json:"users,omitempty"` + // Admins holds the value of the admins edge. + Admins []*Admin `json:"admins,omitempty"` + // UserGroups holds the value of the user_groups edge. + UserGroups []*UserGroupUser `json:"user_groups,omitempty"` + // UserGroupAdmins holds the value of the user_group_admins edge. + UserGroupAdmins []*UserGroupAdmin `json:"user_group_admins,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [5]bool +} + +// OwnerOrErr returns the Owner value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e UserGroupEdges) OwnerOrErr() (*Admin, error) { + if e.Owner != nil { + return e.Owner, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: admin.Label} + } + return nil, &NotLoadedError{edge: "owner"} +} + +// UsersOrErr returns the Users value or an error if the edge +// was not loaded in eager-loading. +func (e UserGroupEdges) UsersOrErr() ([]*User, error) { + if e.loadedTypes[1] { + return e.Users, nil + } + return nil, &NotLoadedError{edge: "users"} +} + +// AdminsOrErr returns the Admins value or an error if the edge +// was not loaded in eager-loading. +func (e UserGroupEdges) AdminsOrErr() ([]*Admin, error) { + if e.loadedTypes[2] { + return e.Admins, nil + } + return nil, &NotLoadedError{edge: "admins"} +} + +// UserGroupsOrErr returns the UserGroups value or an error if the edge +// was not loaded in eager-loading. +func (e UserGroupEdges) UserGroupsOrErr() ([]*UserGroupUser, error) { + if e.loadedTypes[3] { + return e.UserGroups, nil + } + return nil, &NotLoadedError{edge: "user_groups"} +} + +// UserGroupAdminsOrErr returns the UserGroupAdmins value or an error if the edge +// was not loaded in eager-loading. +func (e UserGroupEdges) UserGroupAdminsOrErr() ([]*UserGroupAdmin, error) { + if e.loadedTypes[4] { + return e.UserGroupAdmins, nil + } + return nil, &NotLoadedError{edge: "user_group_admins"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*UserGroup) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case usergroup.FieldName: + values[i] = new(sql.NullString) + case usergroup.FieldCreatedAt: + values[i] = new(sql.NullTime) + case usergroup.FieldID, usergroup.FieldAdminID: + 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 UserGroup fields. +func (ug *UserGroup) 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 usergroup.FieldID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value != nil { + ug.ID = *value + } + case usergroup.FieldAdminID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field admin_id", values[i]) + } else if value != nil { + ug.AdminID = *value + } + case usergroup.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + ug.Name = value.String + } + case usergroup.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 { + ug.CreatedAt = value.Time + } + default: + ug.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the UserGroup. +// This includes values selected through modifiers, order, etc. +func (ug *UserGroup) Value(name string) (ent.Value, error) { + return ug.selectValues.Get(name) +} + +// QueryOwner queries the "owner" edge of the UserGroup entity. +func (ug *UserGroup) QueryOwner() *AdminQuery { + return NewUserGroupClient(ug.config).QueryOwner(ug) +} + +// QueryUsers queries the "users" edge of the UserGroup entity. +func (ug *UserGroup) QueryUsers() *UserQuery { + return NewUserGroupClient(ug.config).QueryUsers(ug) +} + +// QueryAdmins queries the "admins" edge of the UserGroup entity. +func (ug *UserGroup) QueryAdmins() *AdminQuery { + return NewUserGroupClient(ug.config).QueryAdmins(ug) +} + +// QueryUserGroups queries the "user_groups" edge of the UserGroup entity. +func (ug *UserGroup) QueryUserGroups() *UserGroupUserQuery { + return NewUserGroupClient(ug.config).QueryUserGroups(ug) +} + +// QueryUserGroupAdmins queries the "user_group_admins" edge of the UserGroup entity. +func (ug *UserGroup) QueryUserGroupAdmins() *UserGroupAdminQuery { + return NewUserGroupClient(ug.config).QueryUserGroupAdmins(ug) +} + +// Update returns a builder for updating this UserGroup. +// Note that you need to call UserGroup.Unwrap() before calling this method if this UserGroup +// was returned from a transaction, and the transaction was committed or rolled back. +func (ug *UserGroup) Update() *UserGroupUpdateOne { + return NewUserGroupClient(ug.config).UpdateOne(ug) +} + +// Unwrap unwraps the UserGroup 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 (ug *UserGroup) Unwrap() *UserGroup { + _tx, ok := ug.config.driver.(*txDriver) + if !ok { + panic("db: UserGroup is not a transactional entity") + } + ug.config.driver = _tx.drv + return ug +} + +// String implements the fmt.Stringer. +func (ug *UserGroup) String() string { + var builder strings.Builder + builder.WriteString("UserGroup(") + builder.WriteString(fmt.Sprintf("id=%v, ", ug.ID)) + builder.WriteString("admin_id=") + builder.WriteString(fmt.Sprintf("%v", ug.AdminID)) + builder.WriteString(", ") + builder.WriteString("name=") + builder.WriteString(ug.Name) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(ug.CreatedAt.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// UserGroups is a parsable slice of UserGroup. +type UserGroups []*UserGroup diff --git a/backend/db/usergroup/usergroup.go b/backend/db/usergroup/usergroup.go new file mode 100644 index 00000000..88e25016 --- /dev/null +++ b/backend/db/usergroup/usergroup.go @@ -0,0 +1,221 @@ +// Code generated by ent, DO NOT EDIT. + +package usergroup + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the usergroup type in the database. + Label = "user_group" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldAdminID holds the string denoting the admin_id field in the database. + FieldAdminID = "admin_id" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // EdgeOwner holds the string denoting the owner edge name in mutations. + EdgeOwner = "owner" + // EdgeUsers holds the string denoting the users edge name in mutations. + EdgeUsers = "users" + // EdgeAdmins holds the string denoting the admins edge name in mutations. + EdgeAdmins = "admins" + // EdgeUserGroups holds the string denoting the user_groups edge name in mutations. + EdgeUserGroups = "user_groups" + // EdgeUserGroupAdmins holds the string denoting the user_group_admins edge name in mutations. + EdgeUserGroupAdmins = "user_group_admins" + // Table holds the table name of the usergroup in the database. + Table = "user_groups" + // OwnerTable is the table that holds the owner relation/edge. + OwnerTable = "user_groups" + // OwnerInverseTable is the table name for the Admin entity. + // It exists in this package in order to avoid circular dependency with the "admin" package. + OwnerInverseTable = "admins" + // OwnerColumn is the table column denoting the owner relation/edge. + OwnerColumn = "admin_id" + // UsersTable is the table that holds the users relation/edge. The primary key declared below. + UsersTable = "user_group_users" + // UsersInverseTable is the table name for the User entity. + // It exists in this package in order to avoid circular dependency with the "user" package. + UsersInverseTable = "users" + // AdminsTable is the table that holds the admins relation/edge. The primary key declared below. + AdminsTable = "user_group_admins" + // AdminsInverseTable is the table name for the Admin entity. + // It exists in this package in order to avoid circular dependency with the "admin" package. + AdminsInverseTable = "admins" + // UserGroupsTable is the table that holds the user_groups relation/edge. + UserGroupsTable = "user_group_users" + // UserGroupsInverseTable is the table name for the UserGroupUser entity. + // It exists in this package in order to avoid circular dependency with the "usergroupuser" package. + UserGroupsInverseTable = "user_group_users" + // UserGroupsColumn is the table column denoting the user_groups relation/edge. + UserGroupsColumn = "user_group_id" + // UserGroupAdminsTable is the table that holds the user_group_admins relation/edge. + UserGroupAdminsTable = "user_group_admins" + // UserGroupAdminsInverseTable is the table name for the UserGroupAdmin entity. + // It exists in this package in order to avoid circular dependency with the "usergroupadmin" package. + UserGroupAdminsInverseTable = "user_group_admins" + // UserGroupAdminsColumn is the table column denoting the user_group_admins relation/edge. + UserGroupAdminsColumn = "user_group_id" +) + +// Columns holds all SQL columns for usergroup fields. +var Columns = []string{ + FieldID, + FieldAdminID, + FieldName, + FieldCreatedAt, +} + +var ( + // UsersPrimaryKey and UsersColumn2 are the table columns denoting the + // primary key for the users relation (M2M). + UsersPrimaryKey = []string{"user_group_id", "user_id"} + // AdminsPrimaryKey and AdminsColumn2 are the table columns denoting the + // primary key for the admins relation (M2M). + AdminsPrimaryKey = []string{"user_group_id", "admin_id"} +) + +// 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 + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time +) + +// OrderOption defines the ordering options for the UserGroup 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() +} + +// ByAdminID orders the results by the admin_id field. +func ByAdminID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAdminID, opts...).ToFunc() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// ByOwnerField orders the results by owner field. +func ByOwnerField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newOwnerStep(), sql.OrderByField(field, opts...)) + } +} + +// ByUsersCount orders the results by users count. +func ByUsersCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newUsersStep(), opts...) + } +} + +// ByUsers orders the results by users terms. +func ByUsers(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newUsersStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByAdminsCount orders the results by admins count. +func ByAdminsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newAdminsStep(), opts...) + } +} + +// ByAdmins orders the results by admins terms. +func ByAdmins(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newAdminsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByUserGroupsCount orders the results by user_groups count. +func ByUserGroupsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newUserGroupsStep(), opts...) + } +} + +// ByUserGroups orders the results by user_groups terms. +func ByUserGroups(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newUserGroupsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByUserGroupAdminsCount orders the results by user_group_admins count. +func ByUserGroupAdminsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newUserGroupAdminsStep(), opts...) + } +} + +// ByUserGroupAdmins orders the results by user_group_admins terms. +func ByUserGroupAdmins(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newUserGroupAdminsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newOwnerStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(OwnerInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, OwnerTable, OwnerColumn), + ) +} +func newUsersStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(UsersInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, UsersTable, UsersPrimaryKey...), + ) +} +func newAdminsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(AdminsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, AdminsTable, AdminsPrimaryKey...), + ) +} +func newUserGroupsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(UserGroupsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, UserGroupsTable, UserGroupsColumn), + ) +} +func newUserGroupAdminsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(UserGroupAdminsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, UserGroupAdminsTable, UserGroupAdminsColumn), + ) +} diff --git a/backend/db/usergroup/where.go b/backend/db/usergroup/where.go new file mode 100644 index 00000000..fe7b249a --- /dev/null +++ b/backend/db/usergroup/where.go @@ -0,0 +1,327 @@ +// Code generated by ent, DO NOT EDIT. + +package usergroup + +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.UserGroup { + return predicate.UserGroup(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id uuid.UUID) predicate.UserGroup { + return predicate.UserGroup(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id uuid.UUID) predicate.UserGroup { + return predicate.UserGroup(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...uuid.UUID) predicate.UserGroup { + return predicate.UserGroup(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...uuid.UUID) predicate.UserGroup { + return predicate.UserGroup(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id uuid.UUID) predicate.UserGroup { + return predicate.UserGroup(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id uuid.UUID) predicate.UserGroup { + return predicate.UserGroup(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id uuid.UUID) predicate.UserGroup { + return predicate.UserGroup(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id uuid.UUID) predicate.UserGroup { + return predicate.UserGroup(sql.FieldLTE(FieldID, id)) +} + +// AdminID applies equality check predicate on the "admin_id" field. It's identical to AdminIDEQ. +func AdminID(v uuid.UUID) predicate.UserGroup { + return predicate.UserGroup(sql.FieldEQ(FieldAdminID, v)) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.UserGroup { + return predicate.UserGroup(sql.FieldEQ(FieldName, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.UserGroup { + return predicate.UserGroup(sql.FieldEQ(FieldCreatedAt, v)) +} + +// AdminIDEQ applies the EQ predicate on the "admin_id" field. +func AdminIDEQ(v uuid.UUID) predicate.UserGroup { + return predicate.UserGroup(sql.FieldEQ(FieldAdminID, v)) +} + +// AdminIDNEQ applies the NEQ predicate on the "admin_id" field. +func AdminIDNEQ(v uuid.UUID) predicate.UserGroup { + return predicate.UserGroup(sql.FieldNEQ(FieldAdminID, v)) +} + +// AdminIDIn applies the In predicate on the "admin_id" field. +func AdminIDIn(vs ...uuid.UUID) predicate.UserGroup { + return predicate.UserGroup(sql.FieldIn(FieldAdminID, vs...)) +} + +// AdminIDNotIn applies the NotIn predicate on the "admin_id" field. +func AdminIDNotIn(vs ...uuid.UUID) predicate.UserGroup { + return predicate.UserGroup(sql.FieldNotIn(FieldAdminID, vs...)) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.UserGroup { + return predicate.UserGroup(sql.FieldEQ(FieldName, v)) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.UserGroup { + return predicate.UserGroup(sql.FieldNEQ(FieldName, v)) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.UserGroup { + return predicate.UserGroup(sql.FieldIn(FieldName, vs...)) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.UserGroup { + return predicate.UserGroup(sql.FieldNotIn(FieldName, vs...)) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.UserGroup { + return predicate.UserGroup(sql.FieldGT(FieldName, v)) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.UserGroup { + return predicate.UserGroup(sql.FieldGTE(FieldName, v)) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.UserGroup { + return predicate.UserGroup(sql.FieldLT(FieldName, v)) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.UserGroup { + return predicate.UserGroup(sql.FieldLTE(FieldName, v)) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.UserGroup { + return predicate.UserGroup(sql.FieldContains(FieldName, v)) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.UserGroup { + return predicate.UserGroup(sql.FieldHasPrefix(FieldName, v)) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.UserGroup { + return predicate.UserGroup(sql.FieldHasSuffix(FieldName, v)) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.UserGroup { + return predicate.UserGroup(sql.FieldEqualFold(FieldName, v)) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.UserGroup { + return predicate.UserGroup(sql.FieldContainsFold(FieldName, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.UserGroup { + return predicate.UserGroup(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.UserGroup { + return predicate.UserGroup(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.UserGroup { + return predicate.UserGroup(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.UserGroup { + return predicate.UserGroup(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.UserGroup { + return predicate.UserGroup(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.UserGroup { + return predicate.UserGroup(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.UserGroup { + return predicate.UserGroup(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.UserGroup { + return predicate.UserGroup(sql.FieldLTE(FieldCreatedAt, v)) +} + +// HasOwner applies the HasEdge predicate on the "owner" edge. +func HasOwner() predicate.UserGroup { + return predicate.UserGroup(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, OwnerTable, OwnerColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasOwnerWith applies the HasEdge predicate on the "owner" edge with a given conditions (other predicates). +func HasOwnerWith(preds ...predicate.Admin) predicate.UserGroup { + return predicate.UserGroup(func(s *sql.Selector) { + step := newOwnerStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasUsers applies the HasEdge predicate on the "users" edge. +func HasUsers() predicate.UserGroup { + return predicate.UserGroup(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, UsersTable, UsersPrimaryKey...), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasUsersWith applies the HasEdge predicate on the "users" edge with a given conditions (other predicates). +func HasUsersWith(preds ...predicate.User) predicate.UserGroup { + return predicate.UserGroup(func(s *sql.Selector) { + step := newUsersStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasAdmins applies the HasEdge predicate on the "admins" edge. +func HasAdmins() predicate.UserGroup { + return predicate.UserGroup(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, AdminsTable, AdminsPrimaryKey...), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasAdminsWith applies the HasEdge predicate on the "admins" edge with a given conditions (other predicates). +func HasAdminsWith(preds ...predicate.Admin) predicate.UserGroup { + return predicate.UserGroup(func(s *sql.Selector) { + step := newAdminsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasUserGroups applies the HasEdge predicate on the "user_groups" edge. +func HasUserGroups() predicate.UserGroup { + return predicate.UserGroup(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, UserGroupsTable, UserGroupsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasUserGroupsWith applies the HasEdge predicate on the "user_groups" edge with a given conditions (other predicates). +func HasUserGroupsWith(preds ...predicate.UserGroupUser) predicate.UserGroup { + return predicate.UserGroup(func(s *sql.Selector) { + step := newUserGroupsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasUserGroupAdmins applies the HasEdge predicate on the "user_group_admins" edge. +func HasUserGroupAdmins() predicate.UserGroup { + return predicate.UserGroup(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, UserGroupAdminsTable, UserGroupAdminsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasUserGroupAdminsWith applies the HasEdge predicate on the "user_group_admins" edge with a given conditions (other predicates). +func HasUserGroupAdminsWith(preds ...predicate.UserGroupAdmin) predicate.UserGroup { + return predicate.UserGroup(func(s *sql.Selector) { + step := newUserGroupAdminsStep() + 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.UserGroup) predicate.UserGroup { + return predicate.UserGroup(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.UserGroup) predicate.UserGroup { + return predicate.UserGroup(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.UserGroup) predicate.UserGroup { + return predicate.UserGroup(sql.NotPredicates(p)) +} diff --git a/backend/db/usergroup_create.go b/backend/db/usergroup_create.go new file mode 100644 index 00000000..f4e869b2 --- /dev/null +++ b/backend/db/usergroup_create.go @@ -0,0 +1,775 @@ +// 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/admin" + "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/usergroup" + "github.com/chaitin/MonkeyCode/backend/db/usergroupadmin" + "github.com/chaitin/MonkeyCode/backend/db/usergroupuser" + "github.com/google/uuid" +) + +// UserGroupCreate is the builder for creating a UserGroup entity. +type UserGroupCreate struct { + config + mutation *UserGroupMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetAdminID sets the "admin_id" field. +func (ugc *UserGroupCreate) SetAdminID(u uuid.UUID) *UserGroupCreate { + ugc.mutation.SetAdminID(u) + return ugc +} + +// SetName sets the "name" field. +func (ugc *UserGroupCreate) SetName(s string) *UserGroupCreate { + ugc.mutation.SetName(s) + return ugc +} + +// SetCreatedAt sets the "created_at" field. +func (ugc *UserGroupCreate) SetCreatedAt(t time.Time) *UserGroupCreate { + ugc.mutation.SetCreatedAt(t) + return ugc +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (ugc *UserGroupCreate) SetNillableCreatedAt(t *time.Time) *UserGroupCreate { + if t != nil { + ugc.SetCreatedAt(*t) + } + return ugc +} + +// SetID sets the "id" field. +func (ugc *UserGroupCreate) SetID(u uuid.UUID) *UserGroupCreate { + ugc.mutation.SetID(u) + return ugc +} + +// SetOwnerID sets the "owner" edge to the Admin entity by ID. +func (ugc *UserGroupCreate) SetOwnerID(id uuid.UUID) *UserGroupCreate { + ugc.mutation.SetOwnerID(id) + return ugc +} + +// SetOwner sets the "owner" edge to the Admin entity. +func (ugc *UserGroupCreate) SetOwner(a *Admin) *UserGroupCreate { + return ugc.SetOwnerID(a.ID) +} + +// AddUserIDs adds the "users" edge to the User entity by IDs. +func (ugc *UserGroupCreate) AddUserIDs(ids ...uuid.UUID) *UserGroupCreate { + ugc.mutation.AddUserIDs(ids...) + return ugc +} + +// AddUsers adds the "users" edges to the User entity. +func (ugc *UserGroupCreate) AddUsers(u ...*User) *UserGroupCreate { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return ugc.AddUserIDs(ids...) +} + +// AddAdminIDs adds the "admins" edge to the Admin entity by IDs. +func (ugc *UserGroupCreate) AddAdminIDs(ids ...uuid.UUID) *UserGroupCreate { + ugc.mutation.AddAdminIDs(ids...) + return ugc +} + +// AddAdmins adds the "admins" edges to the Admin entity. +func (ugc *UserGroupCreate) AddAdmins(a ...*Admin) *UserGroupCreate { + ids := make([]uuid.UUID, len(a)) + for i := range a { + ids[i] = a[i].ID + } + return ugc.AddAdminIDs(ids...) +} + +// AddUserGroupIDs adds the "user_groups" edge to the UserGroupUser entity by IDs. +func (ugc *UserGroupCreate) AddUserGroupIDs(ids ...uuid.UUID) *UserGroupCreate { + ugc.mutation.AddUserGroupIDs(ids...) + return ugc +} + +// AddUserGroups adds the "user_groups" edges to the UserGroupUser entity. +func (ugc *UserGroupCreate) AddUserGroups(u ...*UserGroupUser) *UserGroupCreate { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return ugc.AddUserGroupIDs(ids...) +} + +// AddUserGroupAdminIDs adds the "user_group_admins" edge to the UserGroupAdmin entity by IDs. +func (ugc *UserGroupCreate) AddUserGroupAdminIDs(ids ...uuid.UUID) *UserGroupCreate { + ugc.mutation.AddUserGroupAdminIDs(ids...) + return ugc +} + +// AddUserGroupAdmins adds the "user_group_admins" edges to the UserGroupAdmin entity. +func (ugc *UserGroupCreate) AddUserGroupAdmins(u ...*UserGroupAdmin) *UserGroupCreate { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return ugc.AddUserGroupAdminIDs(ids...) +} + +// Mutation returns the UserGroupMutation object of the builder. +func (ugc *UserGroupCreate) Mutation() *UserGroupMutation { + return ugc.mutation +} + +// Save creates the UserGroup in the database. +func (ugc *UserGroupCreate) Save(ctx context.Context) (*UserGroup, error) { + ugc.defaults() + return withHooks(ctx, ugc.sqlSave, ugc.mutation, ugc.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (ugc *UserGroupCreate) SaveX(ctx context.Context) *UserGroup { + v, err := ugc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (ugc *UserGroupCreate) Exec(ctx context.Context) error { + _, err := ugc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ugc *UserGroupCreate) ExecX(ctx context.Context) { + if err := ugc.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (ugc *UserGroupCreate) defaults() { + if _, ok := ugc.mutation.CreatedAt(); !ok { + v := usergroup.DefaultCreatedAt() + ugc.mutation.SetCreatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (ugc *UserGroupCreate) check() error { + if _, ok := ugc.mutation.AdminID(); !ok { + return &ValidationError{Name: "admin_id", err: errors.New(`db: missing required field "UserGroup.admin_id"`)} + } + if _, ok := ugc.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`db: missing required field "UserGroup.name"`)} + } + if v, ok := ugc.mutation.Name(); ok { + if err := usergroup.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "UserGroup.name": %w`, err)} + } + } + if _, ok := ugc.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "UserGroup.created_at"`)} + } + if len(ugc.mutation.OwnerIDs()) == 0 { + return &ValidationError{Name: "owner", err: errors.New(`db: missing required edge "UserGroup.owner"`)} + } + return nil +} + +func (ugc *UserGroupCreate) sqlSave(ctx context.Context) (*UserGroup, error) { + if err := ugc.check(); err != nil { + return nil, err + } + _node, _spec := ugc.createSpec() + if err := sqlgraph.CreateNode(ctx, ugc.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 + } + } + ugc.mutation.id = &_node.ID + ugc.mutation.done = true + return _node, nil +} + +func (ugc *UserGroupCreate) createSpec() (*UserGroup, *sqlgraph.CreateSpec) { + var ( + _node = &UserGroup{config: ugc.config} + _spec = sqlgraph.NewCreateSpec(usergroup.Table, sqlgraph.NewFieldSpec(usergroup.FieldID, field.TypeUUID)) + ) + _spec.OnConflict = ugc.conflict + if id, ok := ugc.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = &id + } + if value, ok := ugc.mutation.Name(); ok { + _spec.SetField(usergroup.FieldName, field.TypeString, value) + _node.Name = value + } + if value, ok := ugc.mutation.CreatedAt(); ok { + _spec.SetField(usergroup.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if nodes := ugc.mutation.OwnerIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: usergroup.OwnerTable, + Columns: []string{usergroup.OwnerColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(admin.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.AdminID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := ugc.mutation.UsersIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: usergroup.UsersTable, + Columns: usergroup.UsersPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := ugc.mutation.AdminsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: usergroup.AdminsTable, + Columns: usergroup.AdminsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(admin.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := ugc.mutation.UserGroupsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: usergroup.UserGroupsTable, + Columns: []string{usergroup.UserGroupsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroupuser.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := ugc.mutation.UserGroupAdminsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: usergroup.UserGroupAdminsTable, + Columns: []string{usergroup.UserGroupAdminsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroupadmin.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.UserGroup.Create(). +// SetAdminID(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.UserGroupUpsert) { +// SetAdminID(v+v). +// }). +// Exec(ctx) +func (ugc *UserGroupCreate) OnConflict(opts ...sql.ConflictOption) *UserGroupUpsertOne { + ugc.conflict = opts + return &UserGroupUpsertOne{ + create: ugc, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.UserGroup.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (ugc *UserGroupCreate) OnConflictColumns(columns ...string) *UserGroupUpsertOne { + ugc.conflict = append(ugc.conflict, sql.ConflictColumns(columns...)) + return &UserGroupUpsertOne{ + create: ugc, + } +} + +type ( + // UserGroupUpsertOne is the builder for "upsert"-ing + // one UserGroup node. + UserGroupUpsertOne struct { + create *UserGroupCreate + } + + // UserGroupUpsert is the "OnConflict" setter. + UserGroupUpsert struct { + *sql.UpdateSet + } +) + +// SetAdminID sets the "admin_id" field. +func (u *UserGroupUpsert) SetAdminID(v uuid.UUID) *UserGroupUpsert { + u.Set(usergroup.FieldAdminID, v) + return u +} + +// UpdateAdminID sets the "admin_id" field to the value that was provided on create. +func (u *UserGroupUpsert) UpdateAdminID() *UserGroupUpsert { + u.SetExcluded(usergroup.FieldAdminID) + return u +} + +// SetName sets the "name" field. +func (u *UserGroupUpsert) SetName(v string) *UserGroupUpsert { + u.Set(usergroup.FieldName, v) + return u +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *UserGroupUpsert) UpdateName() *UserGroupUpsert { + u.SetExcluded(usergroup.FieldName) + return u +} + +// SetCreatedAt sets the "created_at" field. +func (u *UserGroupUpsert) SetCreatedAt(v time.Time) *UserGroupUpsert { + u.Set(usergroup.FieldCreatedAt, v) + return u +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *UserGroupUpsert) UpdateCreatedAt() *UserGroupUpsert { + u.SetExcluded(usergroup.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.UserGroup.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(usergroup.FieldID) +// }), +// ). +// Exec(ctx) +func (u *UserGroupUpsertOne) UpdateNewValues() *UserGroupUpsertOne { + 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(usergroup.FieldID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.UserGroup.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *UserGroupUpsertOne) Ignore() *UserGroupUpsertOne { + 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 *UserGroupUpsertOne) DoNothing() *UserGroupUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the UserGroupCreate.OnConflict +// documentation for more info. +func (u *UserGroupUpsertOne) Update(set func(*UserGroupUpsert)) *UserGroupUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&UserGroupUpsert{UpdateSet: update}) + })) + return u +} + +// SetAdminID sets the "admin_id" field. +func (u *UserGroupUpsertOne) SetAdminID(v uuid.UUID) *UserGroupUpsertOne { + return u.Update(func(s *UserGroupUpsert) { + s.SetAdminID(v) + }) +} + +// UpdateAdminID sets the "admin_id" field to the value that was provided on create. +func (u *UserGroupUpsertOne) UpdateAdminID() *UserGroupUpsertOne { + return u.Update(func(s *UserGroupUpsert) { + s.UpdateAdminID() + }) +} + +// SetName sets the "name" field. +func (u *UserGroupUpsertOne) SetName(v string) *UserGroupUpsertOne { + return u.Update(func(s *UserGroupUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *UserGroupUpsertOne) UpdateName() *UserGroupUpsertOne { + return u.Update(func(s *UserGroupUpsert) { + s.UpdateName() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *UserGroupUpsertOne) SetCreatedAt(v time.Time) *UserGroupUpsertOne { + return u.Update(func(s *UserGroupUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *UserGroupUpsertOne) UpdateCreatedAt() *UserGroupUpsertOne { + return u.Update(func(s *UserGroupUpsert) { + s.UpdateCreatedAt() + }) +} + +// Exec executes the query. +func (u *UserGroupUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for UserGroupCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *UserGroupUpsertOne) 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 *UserGroupUpsertOne) 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: UserGroupUpsertOne.ID is not supported by MySQL driver. Use UserGroupUpsertOne.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 *UserGroupUpsertOne) IDX(ctx context.Context) uuid.UUID { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// UserGroupCreateBulk is the builder for creating many UserGroup entities in bulk. +type UserGroupCreateBulk struct { + config + err error + builders []*UserGroupCreate + conflict []sql.ConflictOption +} + +// Save creates the UserGroup entities in the database. +func (ugcb *UserGroupCreateBulk) Save(ctx context.Context) ([]*UserGroup, error) { + if ugcb.err != nil { + return nil, ugcb.err + } + specs := make([]*sqlgraph.CreateSpec, len(ugcb.builders)) + nodes := make([]*UserGroup, len(ugcb.builders)) + mutators := make([]Mutator, len(ugcb.builders)) + for i := range ugcb.builders { + func(i int, root context.Context) { + builder := ugcb.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*UserGroupMutation) + 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, ugcb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = ugcb.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, ugcb.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, ugcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (ugcb *UserGroupCreateBulk) SaveX(ctx context.Context) []*UserGroup { + v, err := ugcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (ugcb *UserGroupCreateBulk) Exec(ctx context.Context) error { + _, err := ugcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ugcb *UserGroupCreateBulk) ExecX(ctx context.Context) { + if err := ugcb.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.UserGroup.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.UserGroupUpsert) { +// SetAdminID(v+v). +// }). +// Exec(ctx) +func (ugcb *UserGroupCreateBulk) OnConflict(opts ...sql.ConflictOption) *UserGroupUpsertBulk { + ugcb.conflict = opts + return &UserGroupUpsertBulk{ + create: ugcb, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.UserGroup.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (ugcb *UserGroupCreateBulk) OnConflictColumns(columns ...string) *UserGroupUpsertBulk { + ugcb.conflict = append(ugcb.conflict, sql.ConflictColumns(columns...)) + return &UserGroupUpsertBulk{ + create: ugcb, + } +} + +// UserGroupUpsertBulk is the builder for "upsert"-ing +// a bulk of UserGroup nodes. +type UserGroupUpsertBulk struct { + create *UserGroupCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.UserGroup.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(usergroup.FieldID) +// }), +// ). +// Exec(ctx) +func (u *UserGroupUpsertBulk) UpdateNewValues() *UserGroupUpsertBulk { + 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(usergroup.FieldID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.UserGroup.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *UserGroupUpsertBulk) Ignore() *UserGroupUpsertBulk { + 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 *UserGroupUpsertBulk) DoNothing() *UserGroupUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the UserGroupCreateBulk.OnConflict +// documentation for more info. +func (u *UserGroupUpsertBulk) Update(set func(*UserGroupUpsert)) *UserGroupUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&UserGroupUpsert{UpdateSet: update}) + })) + return u +} + +// SetAdminID sets the "admin_id" field. +func (u *UserGroupUpsertBulk) SetAdminID(v uuid.UUID) *UserGroupUpsertBulk { + return u.Update(func(s *UserGroupUpsert) { + s.SetAdminID(v) + }) +} + +// UpdateAdminID sets the "admin_id" field to the value that was provided on create. +func (u *UserGroupUpsertBulk) UpdateAdminID() *UserGroupUpsertBulk { + return u.Update(func(s *UserGroupUpsert) { + s.UpdateAdminID() + }) +} + +// SetName sets the "name" field. +func (u *UserGroupUpsertBulk) SetName(v string) *UserGroupUpsertBulk { + return u.Update(func(s *UserGroupUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *UserGroupUpsertBulk) UpdateName() *UserGroupUpsertBulk { + return u.Update(func(s *UserGroupUpsert) { + s.UpdateName() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *UserGroupUpsertBulk) SetCreatedAt(v time.Time) *UserGroupUpsertBulk { + return u.Update(func(s *UserGroupUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *UserGroupUpsertBulk) UpdateCreatedAt() *UserGroupUpsertBulk { + return u.Update(func(s *UserGroupUpsert) { + s.UpdateCreatedAt() + }) +} + +// Exec executes the query. +func (u *UserGroupUpsertBulk) 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 UserGroupCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for UserGroupCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *UserGroupUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/usergroup_delete.go b/backend/db/usergroup_delete.go new file mode 100644 index 00000000..9be52936 --- /dev/null +++ b/backend/db/usergroup_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/usergroup" +) + +// UserGroupDelete is the builder for deleting a UserGroup entity. +type UserGroupDelete struct { + config + hooks []Hook + mutation *UserGroupMutation +} + +// Where appends a list predicates to the UserGroupDelete builder. +func (ugd *UserGroupDelete) Where(ps ...predicate.UserGroup) *UserGroupDelete { + ugd.mutation.Where(ps...) + return ugd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (ugd *UserGroupDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, ugd.sqlExec, ugd.mutation, ugd.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (ugd *UserGroupDelete) ExecX(ctx context.Context) int { + n, err := ugd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (ugd *UserGroupDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(usergroup.Table, sqlgraph.NewFieldSpec(usergroup.FieldID, field.TypeUUID)) + if ps := ugd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, ugd.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + ugd.mutation.done = true + return affected, err +} + +// UserGroupDeleteOne is the builder for deleting a single UserGroup entity. +type UserGroupDeleteOne struct { + ugd *UserGroupDelete +} + +// Where appends a list predicates to the UserGroupDelete builder. +func (ugdo *UserGroupDeleteOne) Where(ps ...predicate.UserGroup) *UserGroupDeleteOne { + ugdo.ugd.mutation.Where(ps...) + return ugdo +} + +// Exec executes the deletion query. +func (ugdo *UserGroupDeleteOne) Exec(ctx context.Context) error { + n, err := ugdo.ugd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{usergroup.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (ugdo *UserGroupDeleteOne) ExecX(ctx context.Context) { + if err := ugdo.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/usergroup_query.go b/backend/db/usergroup_query.go new file mode 100644 index 00000000..71095c2c --- /dev/null +++ b/backend/db/usergroup_query.go @@ -0,0 +1,1015 @@ +// 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/admin" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/usergroup" + "github.com/chaitin/MonkeyCode/backend/db/usergroupadmin" + "github.com/chaitin/MonkeyCode/backend/db/usergroupuser" + "github.com/google/uuid" +) + +// UserGroupQuery is the builder for querying UserGroup entities. +type UserGroupQuery struct { + config + ctx *QueryContext + order []usergroup.OrderOption + inters []Interceptor + predicates []predicate.UserGroup + withOwner *AdminQuery + withUsers *UserQuery + withAdmins *AdminQuery + withUserGroups *UserGroupUserQuery + withUserGroupAdmins *UserGroupAdminQuery + 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 UserGroupQuery builder. +func (ugq *UserGroupQuery) Where(ps ...predicate.UserGroup) *UserGroupQuery { + ugq.predicates = append(ugq.predicates, ps...) + return ugq +} + +// Limit the number of records to be returned by this query. +func (ugq *UserGroupQuery) Limit(limit int) *UserGroupQuery { + ugq.ctx.Limit = &limit + return ugq +} + +// Offset to start from. +func (ugq *UserGroupQuery) Offset(offset int) *UserGroupQuery { + ugq.ctx.Offset = &offset + return ugq +} + +// 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 (ugq *UserGroupQuery) Unique(unique bool) *UserGroupQuery { + ugq.ctx.Unique = &unique + return ugq +} + +// Order specifies how the records should be ordered. +func (ugq *UserGroupQuery) Order(o ...usergroup.OrderOption) *UserGroupQuery { + ugq.order = append(ugq.order, o...) + return ugq +} + +// QueryOwner chains the current query on the "owner" edge. +func (ugq *UserGroupQuery) QueryOwner() *AdminQuery { + query := (&AdminClient{config: ugq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := ugq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := ugq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(usergroup.Table, usergroup.FieldID, selector), + sqlgraph.To(admin.Table, admin.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, usergroup.OwnerTable, usergroup.OwnerColumn), + ) + fromU = sqlgraph.SetNeighbors(ugq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryUsers chains the current query on the "users" edge. +func (ugq *UserGroupQuery) QueryUsers() *UserQuery { + query := (&UserClient{config: ugq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := ugq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := ugq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(usergroup.Table, usergroup.FieldID, selector), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, usergroup.UsersTable, usergroup.UsersPrimaryKey...), + ) + fromU = sqlgraph.SetNeighbors(ugq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryAdmins chains the current query on the "admins" edge. +func (ugq *UserGroupQuery) QueryAdmins() *AdminQuery { + query := (&AdminClient{config: ugq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := ugq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := ugq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(usergroup.Table, usergroup.FieldID, selector), + sqlgraph.To(admin.Table, admin.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, usergroup.AdminsTable, usergroup.AdminsPrimaryKey...), + ) + fromU = sqlgraph.SetNeighbors(ugq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryUserGroups chains the current query on the "user_groups" edge. +func (ugq *UserGroupQuery) QueryUserGroups() *UserGroupUserQuery { + query := (&UserGroupUserClient{config: ugq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := ugq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := ugq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(usergroup.Table, usergroup.FieldID, selector), + sqlgraph.To(usergroupuser.Table, usergroupuser.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, usergroup.UserGroupsTable, usergroup.UserGroupsColumn), + ) + fromU = sqlgraph.SetNeighbors(ugq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryUserGroupAdmins chains the current query on the "user_group_admins" edge. +func (ugq *UserGroupQuery) QueryUserGroupAdmins() *UserGroupAdminQuery { + query := (&UserGroupAdminClient{config: ugq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := ugq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := ugq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(usergroup.Table, usergroup.FieldID, selector), + sqlgraph.To(usergroupadmin.Table, usergroupadmin.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, usergroup.UserGroupAdminsTable, usergroup.UserGroupAdminsColumn), + ) + fromU = sqlgraph.SetNeighbors(ugq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first UserGroup entity from the query. +// Returns a *NotFoundError when no UserGroup was found. +func (ugq *UserGroupQuery) First(ctx context.Context) (*UserGroup, error) { + nodes, err := ugq.Limit(1).All(setContextOp(ctx, ugq.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{usergroup.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (ugq *UserGroupQuery) FirstX(ctx context.Context) *UserGroup { + node, err := ugq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first UserGroup ID from the query. +// Returns a *NotFoundError when no UserGroup ID was found. +func (ugq *UserGroupQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = ugq.Limit(1).IDs(setContextOp(ctx, ugq.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{usergroup.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (ugq *UserGroupQuery) FirstIDX(ctx context.Context) uuid.UUID { + id, err := ugq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single UserGroup entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one UserGroup entity is found. +// Returns a *NotFoundError when no UserGroup entities are found. +func (ugq *UserGroupQuery) Only(ctx context.Context) (*UserGroup, error) { + nodes, err := ugq.Limit(2).All(setContextOp(ctx, ugq.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{usergroup.Label} + default: + return nil, &NotSingularError{usergroup.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (ugq *UserGroupQuery) OnlyX(ctx context.Context) *UserGroup { + node, err := ugq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only UserGroup ID in the query. +// Returns a *NotSingularError when more than one UserGroup ID is found. +// Returns a *NotFoundError when no entities are found. +func (ugq *UserGroupQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = ugq.Limit(2).IDs(setContextOp(ctx, ugq.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{usergroup.Label} + default: + err = &NotSingularError{usergroup.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (ugq *UserGroupQuery) OnlyIDX(ctx context.Context) uuid.UUID { + id, err := ugq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of UserGroups. +func (ugq *UserGroupQuery) All(ctx context.Context) ([]*UserGroup, error) { + ctx = setContextOp(ctx, ugq.ctx, ent.OpQueryAll) + if err := ugq.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*UserGroup, *UserGroupQuery]() + return withInterceptors[[]*UserGroup](ctx, ugq, qr, ugq.inters) +} + +// AllX is like All, but panics if an error occurs. +func (ugq *UserGroupQuery) AllX(ctx context.Context) []*UserGroup { + nodes, err := ugq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of UserGroup IDs. +func (ugq *UserGroupQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) { + if ugq.ctx.Unique == nil && ugq.path != nil { + ugq.Unique(true) + } + ctx = setContextOp(ctx, ugq.ctx, ent.OpQueryIDs) + if err = ugq.Select(usergroup.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (ugq *UserGroupQuery) IDsX(ctx context.Context) []uuid.UUID { + ids, err := ugq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (ugq *UserGroupQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, ugq.ctx, ent.OpQueryCount) + if err := ugq.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, ugq, querierCount[*UserGroupQuery](), ugq.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (ugq *UserGroupQuery) CountX(ctx context.Context) int { + count, err := ugq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (ugq *UserGroupQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, ugq.ctx, ent.OpQueryExist) + switch _, err := ugq.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 (ugq *UserGroupQuery) ExistX(ctx context.Context) bool { + exist, err := ugq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the UserGroupQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (ugq *UserGroupQuery) Clone() *UserGroupQuery { + if ugq == nil { + return nil + } + return &UserGroupQuery{ + config: ugq.config, + ctx: ugq.ctx.Clone(), + order: append([]usergroup.OrderOption{}, ugq.order...), + inters: append([]Interceptor{}, ugq.inters...), + predicates: append([]predicate.UserGroup{}, ugq.predicates...), + withOwner: ugq.withOwner.Clone(), + withUsers: ugq.withUsers.Clone(), + withAdmins: ugq.withAdmins.Clone(), + withUserGroups: ugq.withUserGroups.Clone(), + withUserGroupAdmins: ugq.withUserGroupAdmins.Clone(), + // clone intermediate query. + sql: ugq.sql.Clone(), + path: ugq.path, + modifiers: append([]func(*sql.Selector){}, ugq.modifiers...), + } +} + +// WithOwner tells the query-builder to eager-load the nodes that are connected to +// the "owner" edge. The optional arguments are used to configure the query builder of the edge. +func (ugq *UserGroupQuery) WithOwner(opts ...func(*AdminQuery)) *UserGroupQuery { + query := (&AdminClient{config: ugq.config}).Query() + for _, opt := range opts { + opt(query) + } + ugq.withOwner = query + return ugq +} + +// WithUsers tells the query-builder to eager-load the nodes that are connected to +// the "users" edge. The optional arguments are used to configure the query builder of the edge. +func (ugq *UserGroupQuery) WithUsers(opts ...func(*UserQuery)) *UserGroupQuery { + query := (&UserClient{config: ugq.config}).Query() + for _, opt := range opts { + opt(query) + } + ugq.withUsers = query + return ugq +} + +// WithAdmins tells the query-builder to eager-load the nodes that are connected to +// the "admins" edge. The optional arguments are used to configure the query builder of the edge. +func (ugq *UserGroupQuery) WithAdmins(opts ...func(*AdminQuery)) *UserGroupQuery { + query := (&AdminClient{config: ugq.config}).Query() + for _, opt := range opts { + opt(query) + } + ugq.withAdmins = query + return ugq +} + +// WithUserGroups tells the query-builder to eager-load the nodes that are connected to +// the "user_groups" edge. The optional arguments are used to configure the query builder of the edge. +func (ugq *UserGroupQuery) WithUserGroups(opts ...func(*UserGroupUserQuery)) *UserGroupQuery { + query := (&UserGroupUserClient{config: ugq.config}).Query() + for _, opt := range opts { + opt(query) + } + ugq.withUserGroups = query + return ugq +} + +// WithUserGroupAdmins tells the query-builder to eager-load the nodes that are connected to +// the "user_group_admins" edge. The optional arguments are used to configure the query builder of the edge. +func (ugq *UserGroupQuery) WithUserGroupAdmins(opts ...func(*UserGroupAdminQuery)) *UserGroupQuery { + query := (&UserGroupAdminClient{config: ugq.config}).Query() + for _, opt := range opts { + opt(query) + } + ugq.withUserGroupAdmins = query + return ugq +} + +// 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 { +// AdminID uuid.UUID `json:"admin_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.UserGroup.Query(). +// GroupBy(usergroup.FieldAdminID). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (ugq *UserGroupQuery) GroupBy(field string, fields ...string) *UserGroupGroupBy { + ugq.ctx.Fields = append([]string{field}, fields...) + grbuild := &UserGroupGroupBy{build: ugq} + grbuild.flds = &ugq.ctx.Fields + grbuild.label = usergroup.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 { +// AdminID uuid.UUID `json:"admin_id,omitempty"` +// } +// +// client.UserGroup.Query(). +// Select(usergroup.FieldAdminID). +// Scan(ctx, &v) +func (ugq *UserGroupQuery) Select(fields ...string) *UserGroupSelect { + ugq.ctx.Fields = append(ugq.ctx.Fields, fields...) + sbuild := &UserGroupSelect{UserGroupQuery: ugq} + sbuild.label = usergroup.Label + sbuild.flds, sbuild.scan = &ugq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a UserGroupSelect configured with the given aggregations. +func (ugq *UserGroupQuery) Aggregate(fns ...AggregateFunc) *UserGroupSelect { + return ugq.Select().Aggregate(fns...) +} + +func (ugq *UserGroupQuery) prepareQuery(ctx context.Context) error { + for _, inter := range ugq.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, ugq); err != nil { + return err + } + } + } + for _, f := range ugq.ctx.Fields { + if !usergroup.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + } + if ugq.path != nil { + prev, err := ugq.path(ctx) + if err != nil { + return err + } + ugq.sql = prev + } + return nil +} + +func (ugq *UserGroupQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*UserGroup, error) { + var ( + nodes = []*UserGroup{} + _spec = ugq.querySpec() + loadedTypes = [5]bool{ + ugq.withOwner != nil, + ugq.withUsers != nil, + ugq.withAdmins != nil, + ugq.withUserGroups != nil, + ugq.withUserGroupAdmins != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*UserGroup).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &UserGroup{config: ugq.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(ugq.modifiers) > 0 { + _spec.Modifiers = ugq.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, ugq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := ugq.withOwner; query != nil { + if err := ugq.loadOwner(ctx, query, nodes, nil, + func(n *UserGroup, e *Admin) { n.Edges.Owner = e }); err != nil { + return nil, err + } + } + if query := ugq.withUsers; query != nil { + if err := ugq.loadUsers(ctx, query, nodes, + func(n *UserGroup) { n.Edges.Users = []*User{} }, + func(n *UserGroup, e *User) { n.Edges.Users = append(n.Edges.Users, e) }); err != nil { + return nil, err + } + } + if query := ugq.withAdmins; query != nil { + if err := ugq.loadAdmins(ctx, query, nodes, + func(n *UserGroup) { n.Edges.Admins = []*Admin{} }, + func(n *UserGroup, e *Admin) { n.Edges.Admins = append(n.Edges.Admins, e) }); err != nil { + return nil, err + } + } + if query := ugq.withUserGroups; query != nil { + if err := ugq.loadUserGroups(ctx, query, nodes, + func(n *UserGroup) { n.Edges.UserGroups = []*UserGroupUser{} }, + func(n *UserGroup, e *UserGroupUser) { n.Edges.UserGroups = append(n.Edges.UserGroups, e) }); err != nil { + return nil, err + } + } + if query := ugq.withUserGroupAdmins; query != nil { + if err := ugq.loadUserGroupAdmins(ctx, query, nodes, + func(n *UserGroup) { n.Edges.UserGroupAdmins = []*UserGroupAdmin{} }, + func(n *UserGroup, e *UserGroupAdmin) { n.Edges.UserGroupAdmins = append(n.Edges.UserGroupAdmins, e) }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (ugq *UserGroupQuery) loadOwner(ctx context.Context, query *AdminQuery, nodes []*UserGroup, init func(*UserGroup), assign func(*UserGroup, *Admin)) error { + ids := make([]uuid.UUID, 0, len(nodes)) + nodeids := make(map[uuid.UUID][]*UserGroup) + for i := range nodes { + fk := nodes[i].AdminID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(admin.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 "admin_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (ugq *UserGroupQuery) loadUsers(ctx context.Context, query *UserQuery, nodes []*UserGroup, init func(*UserGroup), assign func(*UserGroup, *User)) error { + edgeIDs := make([]driver.Value, len(nodes)) + byID := make(map[uuid.UUID]*UserGroup) + nids := make(map[uuid.UUID]map[*UserGroup]struct{}) + for i, node := range nodes { + edgeIDs[i] = node.ID + byID[node.ID] = node + if init != nil { + init(node) + } + } + query.Where(func(s *sql.Selector) { + joinT := sql.Table(usergroup.UsersTable) + s.Join(joinT).On(s.C(user.FieldID), joinT.C(usergroup.UsersPrimaryKey[1])) + s.Where(sql.InValues(joinT.C(usergroup.UsersPrimaryKey[0]), edgeIDs...)) + columns := s.SelectedColumns() + s.Select(joinT.C(usergroup.UsersPrimaryKey[0])) + s.AppendSelect(columns...) + s.SetDistinct(false) + }) + if err := query.prepareQuery(ctx); err != nil { + return err + } + qr := QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + return query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) { + assign := spec.Assign + values := spec.ScanValues + spec.ScanValues = func(columns []string) ([]any, error) { + values, err := values(columns[1:]) + if err != nil { + return nil, err + } + return append([]any{new(uuid.UUID)}, values...), nil + } + spec.Assign = func(columns []string, values []any) error { + outValue := *values[0].(*uuid.UUID) + inValue := *values[1].(*uuid.UUID) + if nids[inValue] == nil { + nids[inValue] = map[*UserGroup]struct{}{byID[outValue]: {}} + return assign(columns[1:], values[1:]) + } + nids[inValue][byID[outValue]] = struct{}{} + return nil + } + }) + }) + neighbors, err := withInterceptors[[]*User](ctx, query, qr, query.inters) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nids[n.ID] + if !ok { + return fmt.Errorf(`unexpected "users" node returned %v`, n.ID) + } + for kn := range nodes { + assign(kn, n) + } + } + return nil +} +func (ugq *UserGroupQuery) loadAdmins(ctx context.Context, query *AdminQuery, nodes []*UserGroup, init func(*UserGroup), assign func(*UserGroup, *Admin)) error { + edgeIDs := make([]driver.Value, len(nodes)) + byID := make(map[uuid.UUID]*UserGroup) + nids := make(map[uuid.UUID]map[*UserGroup]struct{}) + for i, node := range nodes { + edgeIDs[i] = node.ID + byID[node.ID] = node + if init != nil { + init(node) + } + } + query.Where(func(s *sql.Selector) { + joinT := sql.Table(usergroup.AdminsTable) + s.Join(joinT).On(s.C(admin.FieldID), joinT.C(usergroup.AdminsPrimaryKey[1])) + s.Where(sql.InValues(joinT.C(usergroup.AdminsPrimaryKey[0]), edgeIDs...)) + columns := s.SelectedColumns() + s.Select(joinT.C(usergroup.AdminsPrimaryKey[0])) + s.AppendSelect(columns...) + s.SetDistinct(false) + }) + if err := query.prepareQuery(ctx); err != nil { + return err + } + qr := QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + return query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) { + assign := spec.Assign + values := spec.ScanValues + spec.ScanValues = func(columns []string) ([]any, error) { + values, err := values(columns[1:]) + if err != nil { + return nil, err + } + return append([]any{new(uuid.UUID)}, values...), nil + } + spec.Assign = func(columns []string, values []any) error { + outValue := *values[0].(*uuid.UUID) + inValue := *values[1].(*uuid.UUID) + if nids[inValue] == nil { + nids[inValue] = map[*UserGroup]struct{}{byID[outValue]: {}} + return assign(columns[1:], values[1:]) + } + nids[inValue][byID[outValue]] = struct{}{} + return nil + } + }) + }) + neighbors, err := withInterceptors[[]*Admin](ctx, query, qr, query.inters) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nids[n.ID] + if !ok { + return fmt.Errorf(`unexpected "admins" node returned %v`, n.ID) + } + for kn := range nodes { + assign(kn, n) + } + } + return nil +} +func (ugq *UserGroupQuery) loadUserGroups(ctx context.Context, query *UserGroupUserQuery, nodes []*UserGroup, init func(*UserGroup), assign func(*UserGroup, *UserGroupUser)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[uuid.UUID]*UserGroup) + 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(usergroupuser.FieldUserGroupID) + } + query.Where(predicate.UserGroupUser(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(usergroup.UserGroupsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.UserGroupID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "user_group_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} +func (ugq *UserGroupQuery) loadUserGroupAdmins(ctx context.Context, query *UserGroupAdminQuery, nodes []*UserGroup, init func(*UserGroup), assign func(*UserGroup, *UserGroupAdmin)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[uuid.UUID]*UserGroup) + 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(usergroupadmin.FieldUserGroupID) + } + query.Where(predicate.UserGroupAdmin(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(usergroup.UserGroupAdminsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.UserGroupID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "user_group_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} + +func (ugq *UserGroupQuery) sqlCount(ctx context.Context) (int, error) { + _spec := ugq.querySpec() + if len(ugq.modifiers) > 0 { + _spec.Modifiers = ugq.modifiers + } + _spec.Node.Columns = ugq.ctx.Fields + if len(ugq.ctx.Fields) > 0 { + _spec.Unique = ugq.ctx.Unique != nil && *ugq.ctx.Unique + } + return sqlgraph.CountNodes(ctx, ugq.driver, _spec) +} + +func (ugq *UserGroupQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(usergroup.Table, usergroup.Columns, sqlgraph.NewFieldSpec(usergroup.FieldID, field.TypeUUID)) + _spec.From = ugq.sql + if unique := ugq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if ugq.path != nil { + _spec.Unique = true + } + if fields := ugq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, usergroup.FieldID) + for i := range fields { + if fields[i] != usergroup.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if ugq.withOwner != nil { + _spec.Node.AddColumnOnce(usergroup.FieldAdminID) + } + } + if ps := ugq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := ugq.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := ugq.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := ugq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (ugq *UserGroupQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(ugq.driver.Dialect()) + t1 := builder.Table(usergroup.Table) + columns := ugq.ctx.Fields + if len(columns) == 0 { + columns = usergroup.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if ugq.sql != nil { + selector = ugq.sql + selector.Select(selector.Columns(columns...)...) + } + if ugq.ctx.Unique != nil && *ugq.ctx.Unique { + selector.Distinct() + } + for _, m := range ugq.modifiers { + m(selector) + } + for _, p := range ugq.predicates { + p(selector) + } + for _, p := range ugq.order { + p(selector) + } + if offset := ugq.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 := ugq.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 (ugq *UserGroupQuery) ForUpdate(opts ...sql.LockOption) *UserGroupQuery { + if ugq.driver.Dialect() == dialect.Postgres { + ugq.Unique(false) + } + ugq.modifiers = append(ugq.modifiers, func(s *sql.Selector) { + s.ForUpdate(opts...) + }) + return ugq +} + +// 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 (ugq *UserGroupQuery) ForShare(opts ...sql.LockOption) *UserGroupQuery { + if ugq.driver.Dialect() == dialect.Postgres { + ugq.Unique(false) + } + ugq.modifiers = append(ugq.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return ugq +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (ugq *UserGroupQuery) Modify(modifiers ...func(s *sql.Selector)) *UserGroupSelect { + ugq.modifiers = append(ugq.modifiers, modifiers...) + return ugq.Select() +} + +// UserGroupGroupBy is the group-by builder for UserGroup entities. +type UserGroupGroupBy struct { + selector + build *UserGroupQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (uggb *UserGroupGroupBy) Aggregate(fns ...AggregateFunc) *UserGroupGroupBy { + uggb.fns = append(uggb.fns, fns...) + return uggb +} + +// Scan applies the selector query and scans the result into the given value. +func (uggb *UserGroupGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, uggb.build.ctx, ent.OpQueryGroupBy) + if err := uggb.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*UserGroupQuery, *UserGroupGroupBy](ctx, uggb.build, uggb, uggb.build.inters, v) +} + +func (uggb *UserGroupGroupBy) sqlScan(ctx context.Context, root *UserGroupQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(uggb.fns)) + for _, fn := range uggb.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*uggb.flds)+len(uggb.fns)) + for _, f := range *uggb.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*uggb.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := uggb.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// UserGroupSelect is the builder for selecting fields of UserGroup entities. +type UserGroupSelect struct { + *UserGroupQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (ugs *UserGroupSelect) Aggregate(fns ...AggregateFunc) *UserGroupSelect { + ugs.fns = append(ugs.fns, fns...) + return ugs +} + +// Scan applies the selector query and scans the result into the given value. +func (ugs *UserGroupSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, ugs.ctx, ent.OpQuerySelect) + if err := ugs.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*UserGroupQuery, *UserGroupSelect](ctx, ugs.UserGroupQuery, ugs, ugs.inters, v) +} + +func (ugs *UserGroupSelect) sqlScan(ctx context.Context, root *UserGroupQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(ugs.fns)) + for _, fn := range ugs.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*ugs.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 := ugs.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 (ugs *UserGroupSelect) Modify(modifiers ...func(s *sql.Selector)) *UserGroupSelect { + ugs.modifiers = append(ugs.modifiers, modifiers...) + return ugs +} diff --git a/backend/db/usergroup_update.go b/backend/db/usergroup_update.go new file mode 100644 index 00000000..63834273 --- /dev/null +++ b/backend/db/usergroup_update.go @@ -0,0 +1,1065 @@ +// 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/admin" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/usergroup" + "github.com/chaitin/MonkeyCode/backend/db/usergroupadmin" + "github.com/chaitin/MonkeyCode/backend/db/usergroupuser" + "github.com/google/uuid" +) + +// UserGroupUpdate is the builder for updating UserGroup entities. +type UserGroupUpdate struct { + config + hooks []Hook + mutation *UserGroupMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the UserGroupUpdate builder. +func (ugu *UserGroupUpdate) Where(ps ...predicate.UserGroup) *UserGroupUpdate { + ugu.mutation.Where(ps...) + return ugu +} + +// SetAdminID sets the "admin_id" field. +func (ugu *UserGroupUpdate) SetAdminID(u uuid.UUID) *UserGroupUpdate { + ugu.mutation.SetAdminID(u) + return ugu +} + +// SetNillableAdminID sets the "admin_id" field if the given value is not nil. +func (ugu *UserGroupUpdate) SetNillableAdminID(u *uuid.UUID) *UserGroupUpdate { + if u != nil { + ugu.SetAdminID(*u) + } + return ugu +} + +// SetName sets the "name" field. +func (ugu *UserGroupUpdate) SetName(s string) *UserGroupUpdate { + ugu.mutation.SetName(s) + return ugu +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (ugu *UserGroupUpdate) SetNillableName(s *string) *UserGroupUpdate { + if s != nil { + ugu.SetName(*s) + } + return ugu +} + +// SetCreatedAt sets the "created_at" field. +func (ugu *UserGroupUpdate) SetCreatedAt(t time.Time) *UserGroupUpdate { + ugu.mutation.SetCreatedAt(t) + return ugu +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (ugu *UserGroupUpdate) SetNillableCreatedAt(t *time.Time) *UserGroupUpdate { + if t != nil { + ugu.SetCreatedAt(*t) + } + return ugu +} + +// SetOwnerID sets the "owner" edge to the Admin entity by ID. +func (ugu *UserGroupUpdate) SetOwnerID(id uuid.UUID) *UserGroupUpdate { + ugu.mutation.SetOwnerID(id) + return ugu +} + +// SetOwner sets the "owner" edge to the Admin entity. +func (ugu *UserGroupUpdate) SetOwner(a *Admin) *UserGroupUpdate { + return ugu.SetOwnerID(a.ID) +} + +// AddUserIDs adds the "users" edge to the User entity by IDs. +func (ugu *UserGroupUpdate) AddUserIDs(ids ...uuid.UUID) *UserGroupUpdate { + ugu.mutation.AddUserIDs(ids...) + return ugu +} + +// AddUsers adds the "users" edges to the User entity. +func (ugu *UserGroupUpdate) AddUsers(u ...*User) *UserGroupUpdate { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return ugu.AddUserIDs(ids...) +} + +// AddAdminIDs adds the "admins" edge to the Admin entity by IDs. +func (ugu *UserGroupUpdate) AddAdminIDs(ids ...uuid.UUID) *UserGroupUpdate { + ugu.mutation.AddAdminIDs(ids...) + return ugu +} + +// AddAdmins adds the "admins" edges to the Admin entity. +func (ugu *UserGroupUpdate) AddAdmins(a ...*Admin) *UserGroupUpdate { + ids := make([]uuid.UUID, len(a)) + for i := range a { + ids[i] = a[i].ID + } + return ugu.AddAdminIDs(ids...) +} + +// AddUserGroupIDs adds the "user_groups" edge to the UserGroupUser entity by IDs. +func (ugu *UserGroupUpdate) AddUserGroupIDs(ids ...uuid.UUID) *UserGroupUpdate { + ugu.mutation.AddUserGroupIDs(ids...) + return ugu +} + +// AddUserGroups adds the "user_groups" edges to the UserGroupUser entity. +func (ugu *UserGroupUpdate) AddUserGroups(u ...*UserGroupUser) *UserGroupUpdate { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return ugu.AddUserGroupIDs(ids...) +} + +// AddUserGroupAdminIDs adds the "user_group_admins" edge to the UserGroupAdmin entity by IDs. +func (ugu *UserGroupUpdate) AddUserGroupAdminIDs(ids ...uuid.UUID) *UserGroupUpdate { + ugu.mutation.AddUserGroupAdminIDs(ids...) + return ugu +} + +// AddUserGroupAdmins adds the "user_group_admins" edges to the UserGroupAdmin entity. +func (ugu *UserGroupUpdate) AddUserGroupAdmins(u ...*UserGroupAdmin) *UserGroupUpdate { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return ugu.AddUserGroupAdminIDs(ids...) +} + +// Mutation returns the UserGroupMutation object of the builder. +func (ugu *UserGroupUpdate) Mutation() *UserGroupMutation { + return ugu.mutation +} + +// ClearOwner clears the "owner" edge to the Admin entity. +func (ugu *UserGroupUpdate) ClearOwner() *UserGroupUpdate { + ugu.mutation.ClearOwner() + return ugu +} + +// ClearUsers clears all "users" edges to the User entity. +func (ugu *UserGroupUpdate) ClearUsers() *UserGroupUpdate { + ugu.mutation.ClearUsers() + return ugu +} + +// RemoveUserIDs removes the "users" edge to User entities by IDs. +func (ugu *UserGroupUpdate) RemoveUserIDs(ids ...uuid.UUID) *UserGroupUpdate { + ugu.mutation.RemoveUserIDs(ids...) + return ugu +} + +// RemoveUsers removes "users" edges to User entities. +func (ugu *UserGroupUpdate) RemoveUsers(u ...*User) *UserGroupUpdate { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return ugu.RemoveUserIDs(ids...) +} + +// ClearAdmins clears all "admins" edges to the Admin entity. +func (ugu *UserGroupUpdate) ClearAdmins() *UserGroupUpdate { + ugu.mutation.ClearAdmins() + return ugu +} + +// RemoveAdminIDs removes the "admins" edge to Admin entities by IDs. +func (ugu *UserGroupUpdate) RemoveAdminIDs(ids ...uuid.UUID) *UserGroupUpdate { + ugu.mutation.RemoveAdminIDs(ids...) + return ugu +} + +// RemoveAdmins removes "admins" edges to Admin entities. +func (ugu *UserGroupUpdate) RemoveAdmins(a ...*Admin) *UserGroupUpdate { + ids := make([]uuid.UUID, len(a)) + for i := range a { + ids[i] = a[i].ID + } + return ugu.RemoveAdminIDs(ids...) +} + +// ClearUserGroups clears all "user_groups" edges to the UserGroupUser entity. +func (ugu *UserGroupUpdate) ClearUserGroups() *UserGroupUpdate { + ugu.mutation.ClearUserGroups() + return ugu +} + +// RemoveUserGroupIDs removes the "user_groups" edge to UserGroupUser entities by IDs. +func (ugu *UserGroupUpdate) RemoveUserGroupIDs(ids ...uuid.UUID) *UserGroupUpdate { + ugu.mutation.RemoveUserGroupIDs(ids...) + return ugu +} + +// RemoveUserGroups removes "user_groups" edges to UserGroupUser entities. +func (ugu *UserGroupUpdate) RemoveUserGroups(u ...*UserGroupUser) *UserGroupUpdate { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return ugu.RemoveUserGroupIDs(ids...) +} + +// ClearUserGroupAdmins clears all "user_group_admins" edges to the UserGroupAdmin entity. +func (ugu *UserGroupUpdate) ClearUserGroupAdmins() *UserGroupUpdate { + ugu.mutation.ClearUserGroupAdmins() + return ugu +} + +// RemoveUserGroupAdminIDs removes the "user_group_admins" edge to UserGroupAdmin entities by IDs. +func (ugu *UserGroupUpdate) RemoveUserGroupAdminIDs(ids ...uuid.UUID) *UserGroupUpdate { + ugu.mutation.RemoveUserGroupAdminIDs(ids...) + return ugu +} + +// RemoveUserGroupAdmins removes "user_group_admins" edges to UserGroupAdmin entities. +func (ugu *UserGroupUpdate) RemoveUserGroupAdmins(u ...*UserGroupAdmin) *UserGroupUpdate { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return ugu.RemoveUserGroupAdminIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (ugu *UserGroupUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, ugu.sqlSave, ugu.mutation, ugu.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (ugu *UserGroupUpdate) SaveX(ctx context.Context) int { + affected, err := ugu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (ugu *UserGroupUpdate) Exec(ctx context.Context) error { + _, err := ugu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ugu *UserGroupUpdate) ExecX(ctx context.Context) { + if err := ugu.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (ugu *UserGroupUpdate) check() error { + if v, ok := ugu.mutation.Name(); ok { + if err := usergroup.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "UserGroup.name": %w`, err)} + } + } + if ugu.mutation.OwnerCleared() && len(ugu.mutation.OwnerIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "UserGroup.owner"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (ugu *UserGroupUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *UserGroupUpdate { + ugu.modifiers = append(ugu.modifiers, modifiers...) + return ugu +} + +func (ugu *UserGroupUpdate) sqlSave(ctx context.Context) (n int, err error) { + if err := ugu.check(); err != nil { + return n, err + } + _spec := sqlgraph.NewUpdateSpec(usergroup.Table, usergroup.Columns, sqlgraph.NewFieldSpec(usergroup.FieldID, field.TypeUUID)) + if ps := ugu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := ugu.mutation.Name(); ok { + _spec.SetField(usergroup.FieldName, field.TypeString, value) + } + if value, ok := ugu.mutation.CreatedAt(); ok { + _spec.SetField(usergroup.FieldCreatedAt, field.TypeTime, value) + } + if ugu.mutation.OwnerCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: usergroup.OwnerTable, + Columns: []string{usergroup.OwnerColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(admin.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ugu.mutation.OwnerIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: usergroup.OwnerTable, + Columns: []string{usergroup.OwnerColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(admin.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if ugu.mutation.UsersCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: usergroup.UsersTable, + Columns: usergroup.UsersPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ugu.mutation.RemovedUsersIDs(); len(nodes) > 0 && !ugu.mutation.UsersCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: usergroup.UsersTable, + Columns: usergroup.UsersPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ugu.mutation.UsersIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: usergroup.UsersTable, + Columns: usergroup.UsersPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if ugu.mutation.AdminsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: usergroup.AdminsTable, + Columns: usergroup.AdminsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(admin.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ugu.mutation.RemovedAdminsIDs(); len(nodes) > 0 && !ugu.mutation.AdminsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: usergroup.AdminsTable, + Columns: usergroup.AdminsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(admin.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 := ugu.mutation.AdminsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: usergroup.AdminsTable, + Columns: usergroup.AdminsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(admin.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if ugu.mutation.UserGroupsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: usergroup.UserGroupsTable, + Columns: []string{usergroup.UserGroupsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroupuser.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ugu.mutation.RemovedUserGroupsIDs(); len(nodes) > 0 && !ugu.mutation.UserGroupsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: usergroup.UserGroupsTable, + Columns: []string{usergroup.UserGroupsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroupuser.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 := ugu.mutation.UserGroupsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: usergroup.UserGroupsTable, + Columns: []string{usergroup.UserGroupsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroupuser.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if ugu.mutation.UserGroupAdminsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: usergroup.UserGroupAdminsTable, + Columns: []string{usergroup.UserGroupAdminsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroupadmin.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ugu.mutation.RemovedUserGroupAdminsIDs(); len(nodes) > 0 && !ugu.mutation.UserGroupAdminsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: usergroup.UserGroupAdminsTable, + Columns: []string{usergroup.UserGroupAdminsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroupadmin.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 := ugu.mutation.UserGroupAdminsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: usergroup.UserGroupAdminsTable, + Columns: []string{usergroup.UserGroupAdminsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroupadmin.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(ugu.modifiers...) + if n, err = sqlgraph.UpdateNodes(ctx, ugu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{usergroup.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + ugu.mutation.done = true + return n, nil +} + +// UserGroupUpdateOne is the builder for updating a single UserGroup entity. +type UserGroupUpdateOne struct { + config + fields []string + hooks []Hook + mutation *UserGroupMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetAdminID sets the "admin_id" field. +func (uguo *UserGroupUpdateOne) SetAdminID(u uuid.UUID) *UserGroupUpdateOne { + uguo.mutation.SetAdminID(u) + return uguo +} + +// SetNillableAdminID sets the "admin_id" field if the given value is not nil. +func (uguo *UserGroupUpdateOne) SetNillableAdminID(u *uuid.UUID) *UserGroupUpdateOne { + if u != nil { + uguo.SetAdminID(*u) + } + return uguo +} + +// SetName sets the "name" field. +func (uguo *UserGroupUpdateOne) SetName(s string) *UserGroupUpdateOne { + uguo.mutation.SetName(s) + return uguo +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (uguo *UserGroupUpdateOne) SetNillableName(s *string) *UserGroupUpdateOne { + if s != nil { + uguo.SetName(*s) + } + return uguo +} + +// SetCreatedAt sets the "created_at" field. +func (uguo *UserGroupUpdateOne) SetCreatedAt(t time.Time) *UserGroupUpdateOne { + uguo.mutation.SetCreatedAt(t) + return uguo +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (uguo *UserGroupUpdateOne) SetNillableCreatedAt(t *time.Time) *UserGroupUpdateOne { + if t != nil { + uguo.SetCreatedAt(*t) + } + return uguo +} + +// SetOwnerID sets the "owner" edge to the Admin entity by ID. +func (uguo *UserGroupUpdateOne) SetOwnerID(id uuid.UUID) *UserGroupUpdateOne { + uguo.mutation.SetOwnerID(id) + return uguo +} + +// SetOwner sets the "owner" edge to the Admin entity. +func (uguo *UserGroupUpdateOne) SetOwner(a *Admin) *UserGroupUpdateOne { + return uguo.SetOwnerID(a.ID) +} + +// AddUserIDs adds the "users" edge to the User entity by IDs. +func (uguo *UserGroupUpdateOne) AddUserIDs(ids ...uuid.UUID) *UserGroupUpdateOne { + uguo.mutation.AddUserIDs(ids...) + return uguo +} + +// AddUsers adds the "users" edges to the User entity. +func (uguo *UserGroupUpdateOne) AddUsers(u ...*User) *UserGroupUpdateOne { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uguo.AddUserIDs(ids...) +} + +// AddAdminIDs adds the "admins" edge to the Admin entity by IDs. +func (uguo *UserGroupUpdateOne) AddAdminIDs(ids ...uuid.UUID) *UserGroupUpdateOne { + uguo.mutation.AddAdminIDs(ids...) + return uguo +} + +// AddAdmins adds the "admins" edges to the Admin entity. +func (uguo *UserGroupUpdateOne) AddAdmins(a ...*Admin) *UserGroupUpdateOne { + ids := make([]uuid.UUID, len(a)) + for i := range a { + ids[i] = a[i].ID + } + return uguo.AddAdminIDs(ids...) +} + +// AddUserGroupIDs adds the "user_groups" edge to the UserGroupUser entity by IDs. +func (uguo *UserGroupUpdateOne) AddUserGroupIDs(ids ...uuid.UUID) *UserGroupUpdateOne { + uguo.mutation.AddUserGroupIDs(ids...) + return uguo +} + +// AddUserGroups adds the "user_groups" edges to the UserGroupUser entity. +func (uguo *UserGroupUpdateOne) AddUserGroups(u ...*UserGroupUser) *UserGroupUpdateOne { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uguo.AddUserGroupIDs(ids...) +} + +// AddUserGroupAdminIDs adds the "user_group_admins" edge to the UserGroupAdmin entity by IDs. +func (uguo *UserGroupUpdateOne) AddUserGroupAdminIDs(ids ...uuid.UUID) *UserGroupUpdateOne { + uguo.mutation.AddUserGroupAdminIDs(ids...) + return uguo +} + +// AddUserGroupAdmins adds the "user_group_admins" edges to the UserGroupAdmin entity. +func (uguo *UserGroupUpdateOne) AddUserGroupAdmins(u ...*UserGroupAdmin) *UserGroupUpdateOne { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uguo.AddUserGroupAdminIDs(ids...) +} + +// Mutation returns the UserGroupMutation object of the builder. +func (uguo *UserGroupUpdateOne) Mutation() *UserGroupMutation { + return uguo.mutation +} + +// ClearOwner clears the "owner" edge to the Admin entity. +func (uguo *UserGroupUpdateOne) ClearOwner() *UserGroupUpdateOne { + uguo.mutation.ClearOwner() + return uguo +} + +// ClearUsers clears all "users" edges to the User entity. +func (uguo *UserGroupUpdateOne) ClearUsers() *UserGroupUpdateOne { + uguo.mutation.ClearUsers() + return uguo +} + +// RemoveUserIDs removes the "users" edge to User entities by IDs. +func (uguo *UserGroupUpdateOne) RemoveUserIDs(ids ...uuid.UUID) *UserGroupUpdateOne { + uguo.mutation.RemoveUserIDs(ids...) + return uguo +} + +// RemoveUsers removes "users" edges to User entities. +func (uguo *UserGroupUpdateOne) RemoveUsers(u ...*User) *UserGroupUpdateOne { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uguo.RemoveUserIDs(ids...) +} + +// ClearAdmins clears all "admins" edges to the Admin entity. +func (uguo *UserGroupUpdateOne) ClearAdmins() *UserGroupUpdateOne { + uguo.mutation.ClearAdmins() + return uguo +} + +// RemoveAdminIDs removes the "admins" edge to Admin entities by IDs. +func (uguo *UserGroupUpdateOne) RemoveAdminIDs(ids ...uuid.UUID) *UserGroupUpdateOne { + uguo.mutation.RemoveAdminIDs(ids...) + return uguo +} + +// RemoveAdmins removes "admins" edges to Admin entities. +func (uguo *UserGroupUpdateOne) RemoveAdmins(a ...*Admin) *UserGroupUpdateOne { + ids := make([]uuid.UUID, len(a)) + for i := range a { + ids[i] = a[i].ID + } + return uguo.RemoveAdminIDs(ids...) +} + +// ClearUserGroups clears all "user_groups" edges to the UserGroupUser entity. +func (uguo *UserGroupUpdateOne) ClearUserGroups() *UserGroupUpdateOne { + uguo.mutation.ClearUserGroups() + return uguo +} + +// RemoveUserGroupIDs removes the "user_groups" edge to UserGroupUser entities by IDs. +func (uguo *UserGroupUpdateOne) RemoveUserGroupIDs(ids ...uuid.UUID) *UserGroupUpdateOne { + uguo.mutation.RemoveUserGroupIDs(ids...) + return uguo +} + +// RemoveUserGroups removes "user_groups" edges to UserGroupUser entities. +func (uguo *UserGroupUpdateOne) RemoveUserGroups(u ...*UserGroupUser) *UserGroupUpdateOne { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uguo.RemoveUserGroupIDs(ids...) +} + +// ClearUserGroupAdmins clears all "user_group_admins" edges to the UserGroupAdmin entity. +func (uguo *UserGroupUpdateOne) ClearUserGroupAdmins() *UserGroupUpdateOne { + uguo.mutation.ClearUserGroupAdmins() + return uguo +} + +// RemoveUserGroupAdminIDs removes the "user_group_admins" edge to UserGroupAdmin entities by IDs. +func (uguo *UserGroupUpdateOne) RemoveUserGroupAdminIDs(ids ...uuid.UUID) *UserGroupUpdateOne { + uguo.mutation.RemoveUserGroupAdminIDs(ids...) + return uguo +} + +// RemoveUserGroupAdmins removes "user_group_admins" edges to UserGroupAdmin entities. +func (uguo *UserGroupUpdateOne) RemoveUserGroupAdmins(u ...*UserGroupAdmin) *UserGroupUpdateOne { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uguo.RemoveUserGroupAdminIDs(ids...) +} + +// Where appends a list predicates to the UserGroupUpdate builder. +func (uguo *UserGroupUpdateOne) Where(ps ...predicate.UserGroup) *UserGroupUpdateOne { + uguo.mutation.Where(ps...) + return uguo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (uguo *UserGroupUpdateOne) Select(field string, fields ...string) *UserGroupUpdateOne { + uguo.fields = append([]string{field}, fields...) + return uguo +} + +// Save executes the query and returns the updated UserGroup entity. +func (uguo *UserGroupUpdateOne) Save(ctx context.Context) (*UserGroup, error) { + return withHooks(ctx, uguo.sqlSave, uguo.mutation, uguo.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (uguo *UserGroupUpdateOne) SaveX(ctx context.Context) *UserGroup { + node, err := uguo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (uguo *UserGroupUpdateOne) Exec(ctx context.Context) error { + _, err := uguo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (uguo *UserGroupUpdateOne) ExecX(ctx context.Context) { + if err := uguo.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (uguo *UserGroupUpdateOne) check() error { + if v, ok := uguo.mutation.Name(); ok { + if err := usergroup.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "UserGroup.name": %w`, err)} + } + } + if uguo.mutation.OwnerCleared() && len(uguo.mutation.OwnerIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "UserGroup.owner"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (uguo *UserGroupUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *UserGroupUpdateOne { + uguo.modifiers = append(uguo.modifiers, modifiers...) + return uguo +} + +func (uguo *UserGroupUpdateOne) sqlSave(ctx context.Context) (_node *UserGroup, err error) { + if err := uguo.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(usergroup.Table, usergroup.Columns, sqlgraph.NewFieldSpec(usergroup.FieldID, field.TypeUUID)) + id, ok := uguo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "UserGroup.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := uguo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, usergroup.FieldID) + for _, f := range fields { + if !usergroup.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != usergroup.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := uguo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := uguo.mutation.Name(); ok { + _spec.SetField(usergroup.FieldName, field.TypeString, value) + } + if value, ok := uguo.mutation.CreatedAt(); ok { + _spec.SetField(usergroup.FieldCreatedAt, field.TypeTime, value) + } + if uguo.mutation.OwnerCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: usergroup.OwnerTable, + Columns: []string{usergroup.OwnerColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(admin.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uguo.mutation.OwnerIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: usergroup.OwnerTable, + Columns: []string{usergroup.OwnerColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(admin.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if uguo.mutation.UsersCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: usergroup.UsersTable, + Columns: usergroup.UsersPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uguo.mutation.RemovedUsersIDs(); len(nodes) > 0 && !uguo.mutation.UsersCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: usergroup.UsersTable, + Columns: usergroup.UsersPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uguo.mutation.UsersIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: usergroup.UsersTable, + Columns: usergroup.UsersPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if uguo.mutation.AdminsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: usergroup.AdminsTable, + Columns: usergroup.AdminsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(admin.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uguo.mutation.RemovedAdminsIDs(); len(nodes) > 0 && !uguo.mutation.AdminsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: usergroup.AdminsTable, + Columns: usergroup.AdminsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(admin.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 := uguo.mutation.AdminsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: usergroup.AdminsTable, + Columns: usergroup.AdminsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(admin.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if uguo.mutation.UserGroupsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: usergroup.UserGroupsTable, + Columns: []string{usergroup.UserGroupsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroupuser.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uguo.mutation.RemovedUserGroupsIDs(); len(nodes) > 0 && !uguo.mutation.UserGroupsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: usergroup.UserGroupsTable, + Columns: []string{usergroup.UserGroupsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroupuser.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 := uguo.mutation.UserGroupsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: usergroup.UserGroupsTable, + Columns: []string{usergroup.UserGroupsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroupuser.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if uguo.mutation.UserGroupAdminsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: usergroup.UserGroupAdminsTable, + Columns: []string{usergroup.UserGroupAdminsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroupadmin.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uguo.mutation.RemovedUserGroupAdminsIDs(); len(nodes) > 0 && !uguo.mutation.UserGroupAdminsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: usergroup.UserGroupAdminsTable, + Columns: []string{usergroup.UserGroupAdminsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroupadmin.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 := uguo.mutation.UserGroupAdminsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: usergroup.UserGroupAdminsTable, + Columns: []string{usergroup.UserGroupAdminsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroupadmin.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(uguo.modifiers...) + _node = &UserGroup{config: uguo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, uguo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{usergroup.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + uguo.mutation.done = true + return _node, nil +} diff --git a/backend/db/usergroupadmin.go b/backend/db/usergroupadmin.go new file mode 100644 index 00000000..a9672856 --- /dev/null +++ b/backend/db/usergroupadmin.go @@ -0,0 +1,161 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "fmt" + "strings" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/chaitin/MonkeyCode/backend/db/admin" + "github.com/chaitin/MonkeyCode/backend/db/usergroup" + "github.com/chaitin/MonkeyCode/backend/db/usergroupadmin" + "github.com/google/uuid" +) + +// UserGroupAdmin is the model entity for the UserGroupAdmin schema. +type UserGroupAdmin struct { + config `json:"-"` + // ID of the ent. + ID uuid.UUID `json:"id,omitempty"` + // UserGroupID holds the value of the "user_group_id" field. + UserGroupID uuid.UUID `json:"user_group_id,omitempty"` + // AdminID holds the value of the "admin_id" field. + AdminID uuid.UUID `json:"admin_id,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the UserGroupAdminQuery when eager-loading is set. + Edges UserGroupAdminEdges `json:"edges"` + selectValues sql.SelectValues +} + +// UserGroupAdminEdges holds the relations/edges for other nodes in the graph. +type UserGroupAdminEdges struct { + // UserGroup holds the value of the user_group edge. + UserGroup *UserGroup `json:"user_group,omitempty"` + // Admin holds the value of the admin edge. + Admin *Admin `json:"admin,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool +} + +// UserGroupOrErr returns the UserGroup value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e UserGroupAdminEdges) UserGroupOrErr() (*UserGroup, error) { + if e.UserGroup != nil { + return e.UserGroup, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: usergroup.Label} + } + return nil, &NotLoadedError{edge: "user_group"} +} + +// AdminOrErr returns the Admin value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e UserGroupAdminEdges) AdminOrErr() (*Admin, error) { + if e.Admin != nil { + return e.Admin, nil + } else if e.loadedTypes[1] { + return nil, &NotFoundError{label: admin.Label} + } + return nil, &NotLoadedError{edge: "admin"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*UserGroupAdmin) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case usergroupadmin.FieldID, usergroupadmin.FieldUserGroupID, usergroupadmin.FieldAdminID: + 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 UserGroupAdmin fields. +func (uga *UserGroupAdmin) 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 usergroupadmin.FieldID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value != nil { + uga.ID = *value + } + case usergroupadmin.FieldUserGroupID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field user_group_id", values[i]) + } else if value != nil { + uga.UserGroupID = *value + } + case usergroupadmin.FieldAdminID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field admin_id", values[i]) + } else if value != nil { + uga.AdminID = *value + } + default: + uga.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the UserGroupAdmin. +// This includes values selected through modifiers, order, etc. +func (uga *UserGroupAdmin) Value(name string) (ent.Value, error) { + return uga.selectValues.Get(name) +} + +// QueryUserGroup queries the "user_group" edge of the UserGroupAdmin entity. +func (uga *UserGroupAdmin) QueryUserGroup() *UserGroupQuery { + return NewUserGroupAdminClient(uga.config).QueryUserGroup(uga) +} + +// QueryAdmin queries the "admin" edge of the UserGroupAdmin entity. +func (uga *UserGroupAdmin) QueryAdmin() *AdminQuery { + return NewUserGroupAdminClient(uga.config).QueryAdmin(uga) +} + +// Update returns a builder for updating this UserGroupAdmin. +// Note that you need to call UserGroupAdmin.Unwrap() before calling this method if this UserGroupAdmin +// was returned from a transaction, and the transaction was committed or rolled back. +func (uga *UserGroupAdmin) Update() *UserGroupAdminUpdateOne { + return NewUserGroupAdminClient(uga.config).UpdateOne(uga) +} + +// Unwrap unwraps the UserGroupAdmin 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 (uga *UserGroupAdmin) Unwrap() *UserGroupAdmin { + _tx, ok := uga.config.driver.(*txDriver) + if !ok { + panic("db: UserGroupAdmin is not a transactional entity") + } + uga.config.driver = _tx.drv + return uga +} + +// String implements the fmt.Stringer. +func (uga *UserGroupAdmin) String() string { + var builder strings.Builder + builder.WriteString("UserGroupAdmin(") + builder.WriteString(fmt.Sprintf("id=%v, ", uga.ID)) + builder.WriteString("user_group_id=") + builder.WriteString(fmt.Sprintf("%v", uga.UserGroupID)) + builder.WriteString(", ") + builder.WriteString("admin_id=") + builder.WriteString(fmt.Sprintf("%v", uga.AdminID)) + builder.WriteByte(')') + return builder.String() +} + +// UserGroupAdmins is a parsable slice of UserGroupAdmin. +type UserGroupAdmins []*UserGroupAdmin diff --git a/backend/db/usergroupadmin/usergroupadmin.go b/backend/db/usergroupadmin/usergroupadmin.go new file mode 100644 index 00000000..60967d47 --- /dev/null +++ b/backend/db/usergroupadmin/usergroupadmin.go @@ -0,0 +1,102 @@ +// Code generated by ent, DO NOT EDIT. + +package usergroupadmin + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the usergroupadmin type in the database. + Label = "user_group_admin" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldUserGroupID holds the string denoting the user_group_id field in the database. + FieldUserGroupID = "user_group_id" + // FieldAdminID holds the string denoting the admin_id field in the database. + FieldAdminID = "admin_id" + // EdgeUserGroup holds the string denoting the user_group edge name in mutations. + EdgeUserGroup = "user_group" + // EdgeAdmin holds the string denoting the admin edge name in mutations. + EdgeAdmin = "admin" + // Table holds the table name of the usergroupadmin in the database. + Table = "user_group_admins" + // UserGroupTable is the table that holds the user_group relation/edge. + UserGroupTable = "user_group_admins" + // UserGroupInverseTable is the table name for the UserGroup entity. + // It exists in this package in order to avoid circular dependency with the "usergroup" package. + UserGroupInverseTable = "user_groups" + // UserGroupColumn is the table column denoting the user_group relation/edge. + UserGroupColumn = "user_group_id" + // AdminTable is the table that holds the admin relation/edge. + AdminTable = "user_group_admins" + // AdminInverseTable is the table name for the Admin entity. + // It exists in this package in order to avoid circular dependency with the "admin" package. + AdminInverseTable = "admins" + // AdminColumn is the table column denoting the admin relation/edge. + AdminColumn = "admin_id" +) + +// Columns holds all SQL columns for usergroupadmin fields. +var Columns = []string{ + FieldID, + FieldUserGroupID, + FieldAdminID, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +// OrderOption defines the ordering options for the UserGroupAdmin 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() +} + +// ByUserGroupID orders the results by the user_group_id field. +func ByUserGroupID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUserGroupID, opts...).ToFunc() +} + +// ByAdminID orders the results by the admin_id field. +func ByAdminID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAdminID, opts...).ToFunc() +} + +// ByUserGroupField orders the results by user_group field. +func ByUserGroupField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newUserGroupStep(), sql.OrderByField(field, opts...)) + } +} + +// ByAdminField orders the results by admin field. +func ByAdminField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newAdminStep(), sql.OrderByField(field, opts...)) + } +} +func newUserGroupStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(UserGroupInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, UserGroupTable, UserGroupColumn), + ) +} +func newAdminStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(AdminInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, AdminTable, AdminColumn), + ) +} diff --git a/backend/db/usergroupadmin/where.go b/backend/db/usergroupadmin/where.go new file mode 100644 index 00000000..4bfc4d1d --- /dev/null +++ b/backend/db/usergroupadmin/where.go @@ -0,0 +1,166 @@ +// Code generated by ent, DO NOT EDIT. + +package usergroupadmin + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/google/uuid" +) + +// ID filters vertices based on their ID field. +func ID(id uuid.UUID) predicate.UserGroupAdmin { + return predicate.UserGroupAdmin(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id uuid.UUID) predicate.UserGroupAdmin { + return predicate.UserGroupAdmin(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id uuid.UUID) predicate.UserGroupAdmin { + return predicate.UserGroupAdmin(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...uuid.UUID) predicate.UserGroupAdmin { + return predicate.UserGroupAdmin(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...uuid.UUID) predicate.UserGroupAdmin { + return predicate.UserGroupAdmin(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id uuid.UUID) predicate.UserGroupAdmin { + return predicate.UserGroupAdmin(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id uuid.UUID) predicate.UserGroupAdmin { + return predicate.UserGroupAdmin(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id uuid.UUID) predicate.UserGroupAdmin { + return predicate.UserGroupAdmin(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id uuid.UUID) predicate.UserGroupAdmin { + return predicate.UserGroupAdmin(sql.FieldLTE(FieldID, id)) +} + +// UserGroupID applies equality check predicate on the "user_group_id" field. It's identical to UserGroupIDEQ. +func UserGroupID(v uuid.UUID) predicate.UserGroupAdmin { + return predicate.UserGroupAdmin(sql.FieldEQ(FieldUserGroupID, v)) +} + +// AdminID applies equality check predicate on the "admin_id" field. It's identical to AdminIDEQ. +func AdminID(v uuid.UUID) predicate.UserGroupAdmin { + return predicate.UserGroupAdmin(sql.FieldEQ(FieldAdminID, v)) +} + +// UserGroupIDEQ applies the EQ predicate on the "user_group_id" field. +func UserGroupIDEQ(v uuid.UUID) predicate.UserGroupAdmin { + return predicate.UserGroupAdmin(sql.FieldEQ(FieldUserGroupID, v)) +} + +// UserGroupIDNEQ applies the NEQ predicate on the "user_group_id" field. +func UserGroupIDNEQ(v uuid.UUID) predicate.UserGroupAdmin { + return predicate.UserGroupAdmin(sql.FieldNEQ(FieldUserGroupID, v)) +} + +// UserGroupIDIn applies the In predicate on the "user_group_id" field. +func UserGroupIDIn(vs ...uuid.UUID) predicate.UserGroupAdmin { + return predicate.UserGroupAdmin(sql.FieldIn(FieldUserGroupID, vs...)) +} + +// UserGroupIDNotIn applies the NotIn predicate on the "user_group_id" field. +func UserGroupIDNotIn(vs ...uuid.UUID) predicate.UserGroupAdmin { + return predicate.UserGroupAdmin(sql.FieldNotIn(FieldUserGroupID, vs...)) +} + +// AdminIDEQ applies the EQ predicate on the "admin_id" field. +func AdminIDEQ(v uuid.UUID) predicate.UserGroupAdmin { + return predicate.UserGroupAdmin(sql.FieldEQ(FieldAdminID, v)) +} + +// AdminIDNEQ applies the NEQ predicate on the "admin_id" field. +func AdminIDNEQ(v uuid.UUID) predicate.UserGroupAdmin { + return predicate.UserGroupAdmin(sql.FieldNEQ(FieldAdminID, v)) +} + +// AdminIDIn applies the In predicate on the "admin_id" field. +func AdminIDIn(vs ...uuid.UUID) predicate.UserGroupAdmin { + return predicate.UserGroupAdmin(sql.FieldIn(FieldAdminID, vs...)) +} + +// AdminIDNotIn applies the NotIn predicate on the "admin_id" field. +func AdminIDNotIn(vs ...uuid.UUID) predicate.UserGroupAdmin { + return predicate.UserGroupAdmin(sql.FieldNotIn(FieldAdminID, vs...)) +} + +// HasUserGroup applies the HasEdge predicate on the "user_group" edge. +func HasUserGroup() predicate.UserGroupAdmin { + return predicate.UserGroupAdmin(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, UserGroupTable, UserGroupColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasUserGroupWith applies the HasEdge predicate on the "user_group" edge with a given conditions (other predicates). +func HasUserGroupWith(preds ...predicate.UserGroup) predicate.UserGroupAdmin { + return predicate.UserGroupAdmin(func(s *sql.Selector) { + step := newUserGroupStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasAdmin applies the HasEdge predicate on the "admin" edge. +func HasAdmin() predicate.UserGroupAdmin { + return predicate.UserGroupAdmin(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, AdminTable, AdminColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasAdminWith applies the HasEdge predicate on the "admin" edge with a given conditions (other predicates). +func HasAdminWith(preds ...predicate.Admin) predicate.UserGroupAdmin { + return predicate.UserGroupAdmin(func(s *sql.Selector) { + step := newAdminStep() + 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.UserGroupAdmin) predicate.UserGroupAdmin { + return predicate.UserGroupAdmin(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.UserGroupAdmin) predicate.UserGroupAdmin { + return predicate.UserGroupAdmin(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.UserGroupAdmin) predicate.UserGroupAdmin { + return predicate.UserGroupAdmin(sql.NotPredicates(p)) +} diff --git a/backend/db/usergroupadmin_create.go b/backend/db/usergroupadmin_create.go new file mode 100644 index 00000000..16af1f5f --- /dev/null +++ b/backend/db/usergroupadmin_create.go @@ -0,0 +1,587 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/admin" + "github.com/chaitin/MonkeyCode/backend/db/usergroup" + "github.com/chaitin/MonkeyCode/backend/db/usergroupadmin" + "github.com/google/uuid" +) + +// UserGroupAdminCreate is the builder for creating a UserGroupAdmin entity. +type UserGroupAdminCreate struct { + config + mutation *UserGroupAdminMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetUserGroupID sets the "user_group_id" field. +func (ugac *UserGroupAdminCreate) SetUserGroupID(u uuid.UUID) *UserGroupAdminCreate { + ugac.mutation.SetUserGroupID(u) + return ugac +} + +// SetAdminID sets the "admin_id" field. +func (ugac *UserGroupAdminCreate) SetAdminID(u uuid.UUID) *UserGroupAdminCreate { + ugac.mutation.SetAdminID(u) + return ugac +} + +// SetID sets the "id" field. +func (ugac *UserGroupAdminCreate) SetID(u uuid.UUID) *UserGroupAdminCreate { + ugac.mutation.SetID(u) + return ugac +} + +// SetUserGroup sets the "user_group" edge to the UserGroup entity. +func (ugac *UserGroupAdminCreate) SetUserGroup(u *UserGroup) *UserGroupAdminCreate { + return ugac.SetUserGroupID(u.ID) +} + +// SetAdmin sets the "admin" edge to the Admin entity. +func (ugac *UserGroupAdminCreate) SetAdmin(a *Admin) *UserGroupAdminCreate { + return ugac.SetAdminID(a.ID) +} + +// Mutation returns the UserGroupAdminMutation object of the builder. +func (ugac *UserGroupAdminCreate) Mutation() *UserGroupAdminMutation { + return ugac.mutation +} + +// Save creates the UserGroupAdmin in the database. +func (ugac *UserGroupAdminCreate) Save(ctx context.Context) (*UserGroupAdmin, error) { + return withHooks(ctx, ugac.sqlSave, ugac.mutation, ugac.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (ugac *UserGroupAdminCreate) SaveX(ctx context.Context) *UserGroupAdmin { + v, err := ugac.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (ugac *UserGroupAdminCreate) Exec(ctx context.Context) error { + _, err := ugac.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ugac *UserGroupAdminCreate) ExecX(ctx context.Context) { + if err := ugac.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (ugac *UserGroupAdminCreate) check() error { + if _, ok := ugac.mutation.UserGroupID(); !ok { + return &ValidationError{Name: "user_group_id", err: errors.New(`db: missing required field "UserGroupAdmin.user_group_id"`)} + } + if _, ok := ugac.mutation.AdminID(); !ok { + return &ValidationError{Name: "admin_id", err: errors.New(`db: missing required field "UserGroupAdmin.admin_id"`)} + } + if len(ugac.mutation.UserGroupIDs()) == 0 { + return &ValidationError{Name: "user_group", err: errors.New(`db: missing required edge "UserGroupAdmin.user_group"`)} + } + if len(ugac.mutation.AdminIDs()) == 0 { + return &ValidationError{Name: "admin", err: errors.New(`db: missing required edge "UserGroupAdmin.admin"`)} + } + return nil +} + +func (ugac *UserGroupAdminCreate) sqlSave(ctx context.Context) (*UserGroupAdmin, error) { + if err := ugac.check(); err != nil { + return nil, err + } + _node, _spec := ugac.createSpec() + if err := sqlgraph.CreateNode(ctx, ugac.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 + } + } + ugac.mutation.id = &_node.ID + ugac.mutation.done = true + return _node, nil +} + +func (ugac *UserGroupAdminCreate) createSpec() (*UserGroupAdmin, *sqlgraph.CreateSpec) { + var ( + _node = &UserGroupAdmin{config: ugac.config} + _spec = sqlgraph.NewCreateSpec(usergroupadmin.Table, sqlgraph.NewFieldSpec(usergroupadmin.FieldID, field.TypeUUID)) + ) + _spec.OnConflict = ugac.conflict + if id, ok := ugac.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = &id + } + if nodes := ugac.mutation.UserGroupIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: usergroupadmin.UserGroupTable, + Columns: []string{usergroupadmin.UserGroupColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroup.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.UserGroupID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := ugac.mutation.AdminIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: usergroupadmin.AdminTable, + Columns: []string{usergroupadmin.AdminColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(admin.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.AdminID = 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.UserGroupAdmin.Create(). +// SetUserGroupID(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.UserGroupAdminUpsert) { +// SetUserGroupID(v+v). +// }). +// Exec(ctx) +func (ugac *UserGroupAdminCreate) OnConflict(opts ...sql.ConflictOption) *UserGroupAdminUpsertOne { + ugac.conflict = opts + return &UserGroupAdminUpsertOne{ + create: ugac, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.UserGroupAdmin.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (ugac *UserGroupAdminCreate) OnConflictColumns(columns ...string) *UserGroupAdminUpsertOne { + ugac.conflict = append(ugac.conflict, sql.ConflictColumns(columns...)) + return &UserGroupAdminUpsertOne{ + create: ugac, + } +} + +type ( + // UserGroupAdminUpsertOne is the builder for "upsert"-ing + // one UserGroupAdmin node. + UserGroupAdminUpsertOne struct { + create *UserGroupAdminCreate + } + + // UserGroupAdminUpsert is the "OnConflict" setter. + UserGroupAdminUpsert struct { + *sql.UpdateSet + } +) + +// SetUserGroupID sets the "user_group_id" field. +func (u *UserGroupAdminUpsert) SetUserGroupID(v uuid.UUID) *UserGroupAdminUpsert { + u.Set(usergroupadmin.FieldUserGroupID, v) + return u +} + +// UpdateUserGroupID sets the "user_group_id" field to the value that was provided on create. +func (u *UserGroupAdminUpsert) UpdateUserGroupID() *UserGroupAdminUpsert { + u.SetExcluded(usergroupadmin.FieldUserGroupID) + return u +} + +// SetAdminID sets the "admin_id" field. +func (u *UserGroupAdminUpsert) SetAdminID(v uuid.UUID) *UserGroupAdminUpsert { + u.Set(usergroupadmin.FieldAdminID, v) + return u +} + +// UpdateAdminID sets the "admin_id" field to the value that was provided on create. +func (u *UserGroupAdminUpsert) UpdateAdminID() *UserGroupAdminUpsert { + u.SetExcluded(usergroupadmin.FieldAdminID) + 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.UserGroupAdmin.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(usergroupadmin.FieldID) +// }), +// ). +// Exec(ctx) +func (u *UserGroupAdminUpsertOne) UpdateNewValues() *UserGroupAdminUpsertOne { + 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(usergroupadmin.FieldID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.UserGroupAdmin.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *UserGroupAdminUpsertOne) Ignore() *UserGroupAdminUpsertOne { + 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 *UserGroupAdminUpsertOne) DoNothing() *UserGroupAdminUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the UserGroupAdminCreate.OnConflict +// documentation for more info. +func (u *UserGroupAdminUpsertOne) Update(set func(*UserGroupAdminUpsert)) *UserGroupAdminUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&UserGroupAdminUpsert{UpdateSet: update}) + })) + return u +} + +// SetUserGroupID sets the "user_group_id" field. +func (u *UserGroupAdminUpsertOne) SetUserGroupID(v uuid.UUID) *UserGroupAdminUpsertOne { + return u.Update(func(s *UserGroupAdminUpsert) { + s.SetUserGroupID(v) + }) +} + +// UpdateUserGroupID sets the "user_group_id" field to the value that was provided on create. +func (u *UserGroupAdminUpsertOne) UpdateUserGroupID() *UserGroupAdminUpsertOne { + return u.Update(func(s *UserGroupAdminUpsert) { + s.UpdateUserGroupID() + }) +} + +// SetAdminID sets the "admin_id" field. +func (u *UserGroupAdminUpsertOne) SetAdminID(v uuid.UUID) *UserGroupAdminUpsertOne { + return u.Update(func(s *UserGroupAdminUpsert) { + s.SetAdminID(v) + }) +} + +// UpdateAdminID sets the "admin_id" field to the value that was provided on create. +func (u *UserGroupAdminUpsertOne) UpdateAdminID() *UserGroupAdminUpsertOne { + return u.Update(func(s *UserGroupAdminUpsert) { + s.UpdateAdminID() + }) +} + +// Exec executes the query. +func (u *UserGroupAdminUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for UserGroupAdminCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *UserGroupAdminUpsertOne) 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 *UserGroupAdminUpsertOne) 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: UserGroupAdminUpsertOne.ID is not supported by MySQL driver. Use UserGroupAdminUpsertOne.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 *UserGroupAdminUpsertOne) IDX(ctx context.Context) uuid.UUID { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// UserGroupAdminCreateBulk is the builder for creating many UserGroupAdmin entities in bulk. +type UserGroupAdminCreateBulk struct { + config + err error + builders []*UserGroupAdminCreate + conflict []sql.ConflictOption +} + +// Save creates the UserGroupAdmin entities in the database. +func (ugacb *UserGroupAdminCreateBulk) Save(ctx context.Context) ([]*UserGroupAdmin, error) { + if ugacb.err != nil { + return nil, ugacb.err + } + specs := make([]*sqlgraph.CreateSpec, len(ugacb.builders)) + nodes := make([]*UserGroupAdmin, len(ugacb.builders)) + mutators := make([]Mutator, len(ugacb.builders)) + for i := range ugacb.builders { + func(i int, root context.Context) { + builder := ugacb.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*UserGroupAdminMutation) + 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, ugacb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = ugacb.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, ugacb.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, ugacb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (ugacb *UserGroupAdminCreateBulk) SaveX(ctx context.Context) []*UserGroupAdmin { + v, err := ugacb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (ugacb *UserGroupAdminCreateBulk) Exec(ctx context.Context) error { + _, err := ugacb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ugacb *UserGroupAdminCreateBulk) ExecX(ctx context.Context) { + if err := ugacb.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.UserGroupAdmin.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.UserGroupAdminUpsert) { +// SetUserGroupID(v+v). +// }). +// Exec(ctx) +func (ugacb *UserGroupAdminCreateBulk) OnConflict(opts ...sql.ConflictOption) *UserGroupAdminUpsertBulk { + ugacb.conflict = opts + return &UserGroupAdminUpsertBulk{ + create: ugacb, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.UserGroupAdmin.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (ugacb *UserGroupAdminCreateBulk) OnConflictColumns(columns ...string) *UserGroupAdminUpsertBulk { + ugacb.conflict = append(ugacb.conflict, sql.ConflictColumns(columns...)) + return &UserGroupAdminUpsertBulk{ + create: ugacb, + } +} + +// UserGroupAdminUpsertBulk is the builder for "upsert"-ing +// a bulk of UserGroupAdmin nodes. +type UserGroupAdminUpsertBulk struct { + create *UserGroupAdminCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.UserGroupAdmin.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(usergroupadmin.FieldID) +// }), +// ). +// Exec(ctx) +func (u *UserGroupAdminUpsertBulk) UpdateNewValues() *UserGroupAdminUpsertBulk { + 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(usergroupadmin.FieldID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.UserGroupAdmin.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *UserGroupAdminUpsertBulk) Ignore() *UserGroupAdminUpsertBulk { + 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 *UserGroupAdminUpsertBulk) DoNothing() *UserGroupAdminUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the UserGroupAdminCreateBulk.OnConflict +// documentation for more info. +func (u *UserGroupAdminUpsertBulk) Update(set func(*UserGroupAdminUpsert)) *UserGroupAdminUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&UserGroupAdminUpsert{UpdateSet: update}) + })) + return u +} + +// SetUserGroupID sets the "user_group_id" field. +func (u *UserGroupAdminUpsertBulk) SetUserGroupID(v uuid.UUID) *UserGroupAdminUpsertBulk { + return u.Update(func(s *UserGroupAdminUpsert) { + s.SetUserGroupID(v) + }) +} + +// UpdateUserGroupID sets the "user_group_id" field to the value that was provided on create. +func (u *UserGroupAdminUpsertBulk) UpdateUserGroupID() *UserGroupAdminUpsertBulk { + return u.Update(func(s *UserGroupAdminUpsert) { + s.UpdateUserGroupID() + }) +} + +// SetAdminID sets the "admin_id" field. +func (u *UserGroupAdminUpsertBulk) SetAdminID(v uuid.UUID) *UserGroupAdminUpsertBulk { + return u.Update(func(s *UserGroupAdminUpsert) { + s.SetAdminID(v) + }) +} + +// UpdateAdminID sets the "admin_id" field to the value that was provided on create. +func (u *UserGroupAdminUpsertBulk) UpdateAdminID() *UserGroupAdminUpsertBulk { + return u.Update(func(s *UserGroupAdminUpsert) { + s.UpdateAdminID() + }) +} + +// Exec executes the query. +func (u *UserGroupAdminUpsertBulk) 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 UserGroupAdminCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for UserGroupAdminCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *UserGroupAdminUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/usergroupadmin_delete.go b/backend/db/usergroupadmin_delete.go new file mode 100644 index 00000000..03e3dd25 --- /dev/null +++ b/backend/db/usergroupadmin_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/usergroupadmin" +) + +// UserGroupAdminDelete is the builder for deleting a UserGroupAdmin entity. +type UserGroupAdminDelete struct { + config + hooks []Hook + mutation *UserGroupAdminMutation +} + +// Where appends a list predicates to the UserGroupAdminDelete builder. +func (ugad *UserGroupAdminDelete) Where(ps ...predicate.UserGroupAdmin) *UserGroupAdminDelete { + ugad.mutation.Where(ps...) + return ugad +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (ugad *UserGroupAdminDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, ugad.sqlExec, ugad.mutation, ugad.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (ugad *UserGroupAdminDelete) ExecX(ctx context.Context) int { + n, err := ugad.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (ugad *UserGroupAdminDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(usergroupadmin.Table, sqlgraph.NewFieldSpec(usergroupadmin.FieldID, field.TypeUUID)) + if ps := ugad.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, ugad.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + ugad.mutation.done = true + return affected, err +} + +// UserGroupAdminDeleteOne is the builder for deleting a single UserGroupAdmin entity. +type UserGroupAdminDeleteOne struct { + ugad *UserGroupAdminDelete +} + +// Where appends a list predicates to the UserGroupAdminDelete builder. +func (ugado *UserGroupAdminDeleteOne) Where(ps ...predicate.UserGroupAdmin) *UserGroupAdminDeleteOne { + ugado.ugad.mutation.Where(ps...) + return ugado +} + +// Exec executes the deletion query. +func (ugado *UserGroupAdminDeleteOne) Exec(ctx context.Context) error { + n, err := ugado.ugad.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{usergroupadmin.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (ugado *UserGroupAdminDeleteOne) ExecX(ctx context.Context) { + if err := ugado.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/usergroupadmin_query.go b/backend/db/usergroupadmin_query.go new file mode 100644 index 00000000..4fb1ce85 --- /dev/null +++ b/backend/db/usergroupadmin_query.go @@ -0,0 +1,732 @@ +// 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/admin" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/usergroup" + "github.com/chaitin/MonkeyCode/backend/db/usergroupadmin" + "github.com/google/uuid" +) + +// UserGroupAdminQuery is the builder for querying UserGroupAdmin entities. +type UserGroupAdminQuery struct { + config + ctx *QueryContext + order []usergroupadmin.OrderOption + inters []Interceptor + predicates []predicate.UserGroupAdmin + withUserGroup *UserGroupQuery + withAdmin *AdminQuery + 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 UserGroupAdminQuery builder. +func (ugaq *UserGroupAdminQuery) Where(ps ...predicate.UserGroupAdmin) *UserGroupAdminQuery { + ugaq.predicates = append(ugaq.predicates, ps...) + return ugaq +} + +// Limit the number of records to be returned by this query. +func (ugaq *UserGroupAdminQuery) Limit(limit int) *UserGroupAdminQuery { + ugaq.ctx.Limit = &limit + return ugaq +} + +// Offset to start from. +func (ugaq *UserGroupAdminQuery) Offset(offset int) *UserGroupAdminQuery { + ugaq.ctx.Offset = &offset + return ugaq +} + +// 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 (ugaq *UserGroupAdminQuery) Unique(unique bool) *UserGroupAdminQuery { + ugaq.ctx.Unique = &unique + return ugaq +} + +// Order specifies how the records should be ordered. +func (ugaq *UserGroupAdminQuery) Order(o ...usergroupadmin.OrderOption) *UserGroupAdminQuery { + ugaq.order = append(ugaq.order, o...) + return ugaq +} + +// QueryUserGroup chains the current query on the "user_group" edge. +func (ugaq *UserGroupAdminQuery) QueryUserGroup() *UserGroupQuery { + query := (&UserGroupClient{config: ugaq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := ugaq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := ugaq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(usergroupadmin.Table, usergroupadmin.FieldID, selector), + sqlgraph.To(usergroup.Table, usergroup.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, usergroupadmin.UserGroupTable, usergroupadmin.UserGroupColumn), + ) + fromU = sqlgraph.SetNeighbors(ugaq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryAdmin chains the current query on the "admin" edge. +func (ugaq *UserGroupAdminQuery) QueryAdmin() *AdminQuery { + query := (&AdminClient{config: ugaq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := ugaq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := ugaq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(usergroupadmin.Table, usergroupadmin.FieldID, selector), + sqlgraph.To(admin.Table, admin.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, usergroupadmin.AdminTable, usergroupadmin.AdminColumn), + ) + fromU = sqlgraph.SetNeighbors(ugaq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first UserGroupAdmin entity from the query. +// Returns a *NotFoundError when no UserGroupAdmin was found. +func (ugaq *UserGroupAdminQuery) First(ctx context.Context) (*UserGroupAdmin, error) { + nodes, err := ugaq.Limit(1).All(setContextOp(ctx, ugaq.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{usergroupadmin.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (ugaq *UserGroupAdminQuery) FirstX(ctx context.Context) *UserGroupAdmin { + node, err := ugaq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first UserGroupAdmin ID from the query. +// Returns a *NotFoundError when no UserGroupAdmin ID was found. +func (ugaq *UserGroupAdminQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = ugaq.Limit(1).IDs(setContextOp(ctx, ugaq.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{usergroupadmin.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (ugaq *UserGroupAdminQuery) FirstIDX(ctx context.Context) uuid.UUID { + id, err := ugaq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single UserGroupAdmin entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one UserGroupAdmin entity is found. +// Returns a *NotFoundError when no UserGroupAdmin entities are found. +func (ugaq *UserGroupAdminQuery) Only(ctx context.Context) (*UserGroupAdmin, error) { + nodes, err := ugaq.Limit(2).All(setContextOp(ctx, ugaq.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{usergroupadmin.Label} + default: + return nil, &NotSingularError{usergroupadmin.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (ugaq *UserGroupAdminQuery) OnlyX(ctx context.Context) *UserGroupAdmin { + node, err := ugaq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only UserGroupAdmin ID in the query. +// Returns a *NotSingularError when more than one UserGroupAdmin ID is found. +// Returns a *NotFoundError when no entities are found. +func (ugaq *UserGroupAdminQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = ugaq.Limit(2).IDs(setContextOp(ctx, ugaq.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{usergroupadmin.Label} + default: + err = &NotSingularError{usergroupadmin.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (ugaq *UserGroupAdminQuery) OnlyIDX(ctx context.Context) uuid.UUID { + id, err := ugaq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of UserGroupAdmins. +func (ugaq *UserGroupAdminQuery) All(ctx context.Context) ([]*UserGroupAdmin, error) { + ctx = setContextOp(ctx, ugaq.ctx, ent.OpQueryAll) + if err := ugaq.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*UserGroupAdmin, *UserGroupAdminQuery]() + return withInterceptors[[]*UserGroupAdmin](ctx, ugaq, qr, ugaq.inters) +} + +// AllX is like All, but panics if an error occurs. +func (ugaq *UserGroupAdminQuery) AllX(ctx context.Context) []*UserGroupAdmin { + nodes, err := ugaq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of UserGroupAdmin IDs. +func (ugaq *UserGroupAdminQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) { + if ugaq.ctx.Unique == nil && ugaq.path != nil { + ugaq.Unique(true) + } + ctx = setContextOp(ctx, ugaq.ctx, ent.OpQueryIDs) + if err = ugaq.Select(usergroupadmin.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (ugaq *UserGroupAdminQuery) IDsX(ctx context.Context) []uuid.UUID { + ids, err := ugaq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (ugaq *UserGroupAdminQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, ugaq.ctx, ent.OpQueryCount) + if err := ugaq.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, ugaq, querierCount[*UserGroupAdminQuery](), ugaq.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (ugaq *UserGroupAdminQuery) CountX(ctx context.Context) int { + count, err := ugaq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (ugaq *UserGroupAdminQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, ugaq.ctx, ent.OpQueryExist) + switch _, err := ugaq.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 (ugaq *UserGroupAdminQuery) ExistX(ctx context.Context) bool { + exist, err := ugaq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the UserGroupAdminQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (ugaq *UserGroupAdminQuery) Clone() *UserGroupAdminQuery { + if ugaq == nil { + return nil + } + return &UserGroupAdminQuery{ + config: ugaq.config, + ctx: ugaq.ctx.Clone(), + order: append([]usergroupadmin.OrderOption{}, ugaq.order...), + inters: append([]Interceptor{}, ugaq.inters...), + predicates: append([]predicate.UserGroupAdmin{}, ugaq.predicates...), + withUserGroup: ugaq.withUserGroup.Clone(), + withAdmin: ugaq.withAdmin.Clone(), + // clone intermediate query. + sql: ugaq.sql.Clone(), + path: ugaq.path, + modifiers: append([]func(*sql.Selector){}, ugaq.modifiers...), + } +} + +// WithUserGroup tells the query-builder to eager-load the nodes that are connected to +// the "user_group" edge. The optional arguments are used to configure the query builder of the edge. +func (ugaq *UserGroupAdminQuery) WithUserGroup(opts ...func(*UserGroupQuery)) *UserGroupAdminQuery { + query := (&UserGroupClient{config: ugaq.config}).Query() + for _, opt := range opts { + opt(query) + } + ugaq.withUserGroup = query + return ugaq +} + +// WithAdmin tells the query-builder to eager-load the nodes that are connected to +// the "admin" edge. The optional arguments are used to configure the query builder of the edge. +func (ugaq *UserGroupAdminQuery) WithAdmin(opts ...func(*AdminQuery)) *UserGroupAdminQuery { + query := (&AdminClient{config: ugaq.config}).Query() + for _, opt := range opts { + opt(query) + } + ugaq.withAdmin = query + return ugaq +} + +// 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 { +// UserGroupID uuid.UUID `json:"user_group_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.UserGroupAdmin.Query(). +// GroupBy(usergroupadmin.FieldUserGroupID). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (ugaq *UserGroupAdminQuery) GroupBy(field string, fields ...string) *UserGroupAdminGroupBy { + ugaq.ctx.Fields = append([]string{field}, fields...) + grbuild := &UserGroupAdminGroupBy{build: ugaq} + grbuild.flds = &ugaq.ctx.Fields + grbuild.label = usergroupadmin.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 { +// UserGroupID uuid.UUID `json:"user_group_id,omitempty"` +// } +// +// client.UserGroupAdmin.Query(). +// Select(usergroupadmin.FieldUserGroupID). +// Scan(ctx, &v) +func (ugaq *UserGroupAdminQuery) Select(fields ...string) *UserGroupAdminSelect { + ugaq.ctx.Fields = append(ugaq.ctx.Fields, fields...) + sbuild := &UserGroupAdminSelect{UserGroupAdminQuery: ugaq} + sbuild.label = usergroupadmin.Label + sbuild.flds, sbuild.scan = &ugaq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a UserGroupAdminSelect configured with the given aggregations. +func (ugaq *UserGroupAdminQuery) Aggregate(fns ...AggregateFunc) *UserGroupAdminSelect { + return ugaq.Select().Aggregate(fns...) +} + +func (ugaq *UserGroupAdminQuery) prepareQuery(ctx context.Context) error { + for _, inter := range ugaq.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, ugaq); err != nil { + return err + } + } + } + for _, f := range ugaq.ctx.Fields { + if !usergroupadmin.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + } + if ugaq.path != nil { + prev, err := ugaq.path(ctx) + if err != nil { + return err + } + ugaq.sql = prev + } + return nil +} + +func (ugaq *UserGroupAdminQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*UserGroupAdmin, error) { + var ( + nodes = []*UserGroupAdmin{} + _spec = ugaq.querySpec() + loadedTypes = [2]bool{ + ugaq.withUserGroup != nil, + ugaq.withAdmin != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*UserGroupAdmin).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &UserGroupAdmin{config: ugaq.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(ugaq.modifiers) > 0 { + _spec.Modifiers = ugaq.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, ugaq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := ugaq.withUserGroup; query != nil { + if err := ugaq.loadUserGroup(ctx, query, nodes, nil, + func(n *UserGroupAdmin, e *UserGroup) { n.Edges.UserGroup = e }); err != nil { + return nil, err + } + } + if query := ugaq.withAdmin; query != nil { + if err := ugaq.loadAdmin(ctx, query, nodes, nil, + func(n *UserGroupAdmin, e *Admin) { n.Edges.Admin = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (ugaq *UserGroupAdminQuery) loadUserGroup(ctx context.Context, query *UserGroupQuery, nodes []*UserGroupAdmin, init func(*UserGroupAdmin), assign func(*UserGroupAdmin, *UserGroup)) error { + ids := make([]uuid.UUID, 0, len(nodes)) + nodeids := make(map[uuid.UUID][]*UserGroupAdmin) + for i := range nodes { + fk := nodes[i].UserGroupID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(usergroup.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return fmt.Errorf(`unexpected foreign-key "user_group_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (ugaq *UserGroupAdminQuery) loadAdmin(ctx context.Context, query *AdminQuery, nodes []*UserGroupAdmin, init func(*UserGroupAdmin), assign func(*UserGroupAdmin, *Admin)) error { + ids := make([]uuid.UUID, 0, len(nodes)) + nodeids := make(map[uuid.UUID][]*UserGroupAdmin) + for i := range nodes { + fk := nodes[i].AdminID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(admin.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 "admin_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (ugaq *UserGroupAdminQuery) sqlCount(ctx context.Context) (int, error) { + _spec := ugaq.querySpec() + if len(ugaq.modifiers) > 0 { + _spec.Modifiers = ugaq.modifiers + } + _spec.Node.Columns = ugaq.ctx.Fields + if len(ugaq.ctx.Fields) > 0 { + _spec.Unique = ugaq.ctx.Unique != nil && *ugaq.ctx.Unique + } + return sqlgraph.CountNodes(ctx, ugaq.driver, _spec) +} + +func (ugaq *UserGroupAdminQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(usergroupadmin.Table, usergroupadmin.Columns, sqlgraph.NewFieldSpec(usergroupadmin.FieldID, field.TypeUUID)) + _spec.From = ugaq.sql + if unique := ugaq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if ugaq.path != nil { + _spec.Unique = true + } + if fields := ugaq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, usergroupadmin.FieldID) + for i := range fields { + if fields[i] != usergroupadmin.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if ugaq.withUserGroup != nil { + _spec.Node.AddColumnOnce(usergroupadmin.FieldUserGroupID) + } + if ugaq.withAdmin != nil { + _spec.Node.AddColumnOnce(usergroupadmin.FieldAdminID) + } + } + if ps := ugaq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := ugaq.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := ugaq.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := ugaq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (ugaq *UserGroupAdminQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(ugaq.driver.Dialect()) + t1 := builder.Table(usergroupadmin.Table) + columns := ugaq.ctx.Fields + if len(columns) == 0 { + columns = usergroupadmin.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if ugaq.sql != nil { + selector = ugaq.sql + selector.Select(selector.Columns(columns...)...) + } + if ugaq.ctx.Unique != nil && *ugaq.ctx.Unique { + selector.Distinct() + } + for _, m := range ugaq.modifiers { + m(selector) + } + for _, p := range ugaq.predicates { + p(selector) + } + for _, p := range ugaq.order { + p(selector) + } + if offset := ugaq.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 := ugaq.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 (ugaq *UserGroupAdminQuery) ForUpdate(opts ...sql.LockOption) *UserGroupAdminQuery { + if ugaq.driver.Dialect() == dialect.Postgres { + ugaq.Unique(false) + } + ugaq.modifiers = append(ugaq.modifiers, func(s *sql.Selector) { + s.ForUpdate(opts...) + }) + return ugaq +} + +// 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 (ugaq *UserGroupAdminQuery) ForShare(opts ...sql.LockOption) *UserGroupAdminQuery { + if ugaq.driver.Dialect() == dialect.Postgres { + ugaq.Unique(false) + } + ugaq.modifiers = append(ugaq.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return ugaq +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (ugaq *UserGroupAdminQuery) Modify(modifiers ...func(s *sql.Selector)) *UserGroupAdminSelect { + ugaq.modifiers = append(ugaq.modifiers, modifiers...) + return ugaq.Select() +} + +// UserGroupAdminGroupBy is the group-by builder for UserGroupAdmin entities. +type UserGroupAdminGroupBy struct { + selector + build *UserGroupAdminQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (ugagb *UserGroupAdminGroupBy) Aggregate(fns ...AggregateFunc) *UserGroupAdminGroupBy { + ugagb.fns = append(ugagb.fns, fns...) + return ugagb +} + +// Scan applies the selector query and scans the result into the given value. +func (ugagb *UserGroupAdminGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, ugagb.build.ctx, ent.OpQueryGroupBy) + if err := ugagb.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*UserGroupAdminQuery, *UserGroupAdminGroupBy](ctx, ugagb.build, ugagb, ugagb.build.inters, v) +} + +func (ugagb *UserGroupAdminGroupBy) sqlScan(ctx context.Context, root *UserGroupAdminQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(ugagb.fns)) + for _, fn := range ugagb.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*ugagb.flds)+len(ugagb.fns)) + for _, f := range *ugagb.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*ugagb.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := ugagb.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// UserGroupAdminSelect is the builder for selecting fields of UserGroupAdmin entities. +type UserGroupAdminSelect struct { + *UserGroupAdminQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (ugas *UserGroupAdminSelect) Aggregate(fns ...AggregateFunc) *UserGroupAdminSelect { + ugas.fns = append(ugas.fns, fns...) + return ugas +} + +// Scan applies the selector query and scans the result into the given value. +func (ugas *UserGroupAdminSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, ugas.ctx, ent.OpQuerySelect) + if err := ugas.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*UserGroupAdminQuery, *UserGroupAdminSelect](ctx, ugas.UserGroupAdminQuery, ugas, ugas.inters, v) +} + +func (ugas *UserGroupAdminSelect) sqlScan(ctx context.Context, root *UserGroupAdminQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(ugas.fns)) + for _, fn := range ugas.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*ugas.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 := ugas.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 (ugas *UserGroupAdminSelect) Modify(modifiers ...func(s *sql.Selector)) *UserGroupAdminSelect { + ugas.modifiers = append(ugas.modifiers, modifiers...) + return ugas +} diff --git a/backend/db/usergroupadmin_update.go b/backend/db/usergroupadmin_update.go new file mode 100644 index 00000000..0147c24b --- /dev/null +++ b/backend/db/usergroupadmin_update.go @@ -0,0 +1,438 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/admin" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/usergroup" + "github.com/chaitin/MonkeyCode/backend/db/usergroupadmin" + "github.com/google/uuid" +) + +// UserGroupAdminUpdate is the builder for updating UserGroupAdmin entities. +type UserGroupAdminUpdate struct { + config + hooks []Hook + mutation *UserGroupAdminMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the UserGroupAdminUpdate builder. +func (ugau *UserGroupAdminUpdate) Where(ps ...predicate.UserGroupAdmin) *UserGroupAdminUpdate { + ugau.mutation.Where(ps...) + return ugau +} + +// SetUserGroupID sets the "user_group_id" field. +func (ugau *UserGroupAdminUpdate) SetUserGroupID(u uuid.UUID) *UserGroupAdminUpdate { + ugau.mutation.SetUserGroupID(u) + return ugau +} + +// SetNillableUserGroupID sets the "user_group_id" field if the given value is not nil. +func (ugau *UserGroupAdminUpdate) SetNillableUserGroupID(u *uuid.UUID) *UserGroupAdminUpdate { + if u != nil { + ugau.SetUserGroupID(*u) + } + return ugau +} + +// SetAdminID sets the "admin_id" field. +func (ugau *UserGroupAdminUpdate) SetAdminID(u uuid.UUID) *UserGroupAdminUpdate { + ugau.mutation.SetAdminID(u) + return ugau +} + +// SetNillableAdminID sets the "admin_id" field if the given value is not nil. +func (ugau *UserGroupAdminUpdate) SetNillableAdminID(u *uuid.UUID) *UserGroupAdminUpdate { + if u != nil { + ugau.SetAdminID(*u) + } + return ugau +} + +// SetUserGroup sets the "user_group" edge to the UserGroup entity. +func (ugau *UserGroupAdminUpdate) SetUserGroup(u *UserGroup) *UserGroupAdminUpdate { + return ugau.SetUserGroupID(u.ID) +} + +// SetAdmin sets the "admin" edge to the Admin entity. +func (ugau *UserGroupAdminUpdate) SetAdmin(a *Admin) *UserGroupAdminUpdate { + return ugau.SetAdminID(a.ID) +} + +// Mutation returns the UserGroupAdminMutation object of the builder. +func (ugau *UserGroupAdminUpdate) Mutation() *UserGroupAdminMutation { + return ugau.mutation +} + +// ClearUserGroup clears the "user_group" edge to the UserGroup entity. +func (ugau *UserGroupAdminUpdate) ClearUserGroup() *UserGroupAdminUpdate { + ugau.mutation.ClearUserGroup() + return ugau +} + +// ClearAdmin clears the "admin" edge to the Admin entity. +func (ugau *UserGroupAdminUpdate) ClearAdmin() *UserGroupAdminUpdate { + ugau.mutation.ClearAdmin() + return ugau +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (ugau *UserGroupAdminUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, ugau.sqlSave, ugau.mutation, ugau.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (ugau *UserGroupAdminUpdate) SaveX(ctx context.Context) int { + affected, err := ugau.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (ugau *UserGroupAdminUpdate) Exec(ctx context.Context) error { + _, err := ugau.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ugau *UserGroupAdminUpdate) ExecX(ctx context.Context) { + if err := ugau.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (ugau *UserGroupAdminUpdate) check() error { + if ugau.mutation.UserGroupCleared() && len(ugau.mutation.UserGroupIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "UserGroupAdmin.user_group"`) + } + if ugau.mutation.AdminCleared() && len(ugau.mutation.AdminIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "UserGroupAdmin.admin"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (ugau *UserGroupAdminUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *UserGroupAdminUpdate { + ugau.modifiers = append(ugau.modifiers, modifiers...) + return ugau +} + +func (ugau *UserGroupAdminUpdate) sqlSave(ctx context.Context) (n int, err error) { + if err := ugau.check(); err != nil { + return n, err + } + _spec := sqlgraph.NewUpdateSpec(usergroupadmin.Table, usergroupadmin.Columns, sqlgraph.NewFieldSpec(usergroupadmin.FieldID, field.TypeUUID)) + if ps := ugau.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if ugau.mutation.UserGroupCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: usergroupadmin.UserGroupTable, + Columns: []string{usergroupadmin.UserGroupColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroup.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ugau.mutation.UserGroupIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: usergroupadmin.UserGroupTable, + Columns: []string{usergroupadmin.UserGroupColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroup.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if ugau.mutation.AdminCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: usergroupadmin.AdminTable, + Columns: []string{usergroupadmin.AdminColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(admin.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ugau.mutation.AdminIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: usergroupadmin.AdminTable, + Columns: []string{usergroupadmin.AdminColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(admin.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(ugau.modifiers...) + if n, err = sqlgraph.UpdateNodes(ctx, ugau.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{usergroupadmin.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + ugau.mutation.done = true + return n, nil +} + +// UserGroupAdminUpdateOne is the builder for updating a single UserGroupAdmin entity. +type UserGroupAdminUpdateOne struct { + config + fields []string + hooks []Hook + mutation *UserGroupAdminMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetUserGroupID sets the "user_group_id" field. +func (ugauo *UserGroupAdminUpdateOne) SetUserGroupID(u uuid.UUID) *UserGroupAdminUpdateOne { + ugauo.mutation.SetUserGroupID(u) + return ugauo +} + +// SetNillableUserGroupID sets the "user_group_id" field if the given value is not nil. +func (ugauo *UserGroupAdminUpdateOne) SetNillableUserGroupID(u *uuid.UUID) *UserGroupAdminUpdateOne { + if u != nil { + ugauo.SetUserGroupID(*u) + } + return ugauo +} + +// SetAdminID sets the "admin_id" field. +func (ugauo *UserGroupAdminUpdateOne) SetAdminID(u uuid.UUID) *UserGroupAdminUpdateOne { + ugauo.mutation.SetAdminID(u) + return ugauo +} + +// SetNillableAdminID sets the "admin_id" field if the given value is not nil. +func (ugauo *UserGroupAdminUpdateOne) SetNillableAdminID(u *uuid.UUID) *UserGroupAdminUpdateOne { + if u != nil { + ugauo.SetAdminID(*u) + } + return ugauo +} + +// SetUserGroup sets the "user_group" edge to the UserGroup entity. +func (ugauo *UserGroupAdminUpdateOne) SetUserGroup(u *UserGroup) *UserGroupAdminUpdateOne { + return ugauo.SetUserGroupID(u.ID) +} + +// SetAdmin sets the "admin" edge to the Admin entity. +func (ugauo *UserGroupAdminUpdateOne) SetAdmin(a *Admin) *UserGroupAdminUpdateOne { + return ugauo.SetAdminID(a.ID) +} + +// Mutation returns the UserGroupAdminMutation object of the builder. +func (ugauo *UserGroupAdminUpdateOne) Mutation() *UserGroupAdminMutation { + return ugauo.mutation +} + +// ClearUserGroup clears the "user_group" edge to the UserGroup entity. +func (ugauo *UserGroupAdminUpdateOne) ClearUserGroup() *UserGroupAdminUpdateOne { + ugauo.mutation.ClearUserGroup() + return ugauo +} + +// ClearAdmin clears the "admin" edge to the Admin entity. +func (ugauo *UserGroupAdminUpdateOne) ClearAdmin() *UserGroupAdminUpdateOne { + ugauo.mutation.ClearAdmin() + return ugauo +} + +// Where appends a list predicates to the UserGroupAdminUpdate builder. +func (ugauo *UserGroupAdminUpdateOne) Where(ps ...predicate.UserGroupAdmin) *UserGroupAdminUpdateOne { + ugauo.mutation.Where(ps...) + return ugauo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (ugauo *UserGroupAdminUpdateOne) Select(field string, fields ...string) *UserGroupAdminUpdateOne { + ugauo.fields = append([]string{field}, fields...) + return ugauo +} + +// Save executes the query and returns the updated UserGroupAdmin entity. +func (ugauo *UserGroupAdminUpdateOne) Save(ctx context.Context) (*UserGroupAdmin, error) { + return withHooks(ctx, ugauo.sqlSave, ugauo.mutation, ugauo.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (ugauo *UserGroupAdminUpdateOne) SaveX(ctx context.Context) *UserGroupAdmin { + node, err := ugauo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (ugauo *UserGroupAdminUpdateOne) Exec(ctx context.Context) error { + _, err := ugauo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ugauo *UserGroupAdminUpdateOne) ExecX(ctx context.Context) { + if err := ugauo.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (ugauo *UserGroupAdminUpdateOne) check() error { + if ugauo.mutation.UserGroupCleared() && len(ugauo.mutation.UserGroupIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "UserGroupAdmin.user_group"`) + } + if ugauo.mutation.AdminCleared() && len(ugauo.mutation.AdminIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "UserGroupAdmin.admin"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (ugauo *UserGroupAdminUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *UserGroupAdminUpdateOne { + ugauo.modifiers = append(ugauo.modifiers, modifiers...) + return ugauo +} + +func (ugauo *UserGroupAdminUpdateOne) sqlSave(ctx context.Context) (_node *UserGroupAdmin, err error) { + if err := ugauo.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(usergroupadmin.Table, usergroupadmin.Columns, sqlgraph.NewFieldSpec(usergroupadmin.FieldID, field.TypeUUID)) + id, ok := ugauo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "UserGroupAdmin.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := ugauo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, usergroupadmin.FieldID) + for _, f := range fields { + if !usergroupadmin.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != usergroupadmin.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := ugauo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if ugauo.mutation.UserGroupCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: usergroupadmin.UserGroupTable, + Columns: []string{usergroupadmin.UserGroupColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroup.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ugauo.mutation.UserGroupIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: usergroupadmin.UserGroupTable, + Columns: []string{usergroupadmin.UserGroupColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroup.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if ugauo.mutation.AdminCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: usergroupadmin.AdminTable, + Columns: []string{usergroupadmin.AdminColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(admin.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ugauo.mutation.AdminIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: usergroupadmin.AdminTable, + Columns: []string{usergroupadmin.AdminColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(admin.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(ugauo.modifiers...) + _node = &UserGroupAdmin{config: ugauo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, ugauo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{usergroupadmin.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + ugauo.mutation.done = true + return _node, nil +} diff --git a/backend/db/usergroupuser.go b/backend/db/usergroupuser.go new file mode 100644 index 00000000..b71d6541 --- /dev/null +++ b/backend/db/usergroupuser.go @@ -0,0 +1,161 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "fmt" + "strings" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/usergroup" + "github.com/chaitin/MonkeyCode/backend/db/usergroupuser" + "github.com/google/uuid" +) + +// UserGroupUser is the model entity for the UserGroupUser schema. +type UserGroupUser struct { + config `json:"-"` + // ID of the ent. + ID uuid.UUID `json:"id,omitempty"` + // UserGroupID holds the value of the "user_group_id" field. + UserGroupID uuid.UUID `json:"user_group_id,omitempty"` + // UserID holds the value of the "user_id" field. + UserID uuid.UUID `json:"user_id,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the UserGroupUserQuery when eager-loading is set. + Edges UserGroupUserEdges `json:"edges"` + selectValues sql.SelectValues +} + +// UserGroupUserEdges holds the relations/edges for other nodes in the graph. +type UserGroupUserEdges struct { + // UserGroup holds the value of the user_group edge. + UserGroup *UserGroup `json:"user_group,omitempty"` + // User holds the value of the user edge. + User *User `json:"user,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool +} + +// UserGroupOrErr returns the UserGroup value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e UserGroupUserEdges) UserGroupOrErr() (*UserGroup, error) { + if e.UserGroup != nil { + return e.UserGroup, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: usergroup.Label} + } + return nil, &NotLoadedError{edge: "user_group"} +} + +// UserOrErr returns the User value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e UserGroupUserEdges) UserOrErr() (*User, error) { + if e.User != nil { + return e.User, nil + } else if e.loadedTypes[1] { + return nil, &NotFoundError{label: user.Label} + } + return nil, &NotLoadedError{edge: "user"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*UserGroupUser) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case usergroupuser.FieldID, usergroupuser.FieldUserGroupID, usergroupuser.FieldUserID: + 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 UserGroupUser fields. +func (ugu *UserGroupUser) 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 usergroupuser.FieldID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value != nil { + ugu.ID = *value + } + case usergroupuser.FieldUserGroupID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field user_group_id", values[i]) + } else if value != nil { + ugu.UserGroupID = *value + } + case usergroupuser.FieldUserID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field user_id", values[i]) + } else if value != nil { + ugu.UserID = *value + } + default: + ugu.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the UserGroupUser. +// This includes values selected through modifiers, order, etc. +func (ugu *UserGroupUser) Value(name string) (ent.Value, error) { + return ugu.selectValues.Get(name) +} + +// QueryUserGroup queries the "user_group" edge of the UserGroupUser entity. +func (ugu *UserGroupUser) QueryUserGroup() *UserGroupQuery { + return NewUserGroupUserClient(ugu.config).QueryUserGroup(ugu) +} + +// QueryUser queries the "user" edge of the UserGroupUser entity. +func (ugu *UserGroupUser) QueryUser() *UserQuery { + return NewUserGroupUserClient(ugu.config).QueryUser(ugu) +} + +// Update returns a builder for updating this UserGroupUser. +// Note that you need to call UserGroupUser.Unwrap() before calling this method if this UserGroupUser +// was returned from a transaction, and the transaction was committed or rolled back. +func (ugu *UserGroupUser) Update() *UserGroupUserUpdateOne { + return NewUserGroupUserClient(ugu.config).UpdateOne(ugu) +} + +// Unwrap unwraps the UserGroupUser 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 (ugu *UserGroupUser) Unwrap() *UserGroupUser { + _tx, ok := ugu.config.driver.(*txDriver) + if !ok { + panic("db: UserGroupUser is not a transactional entity") + } + ugu.config.driver = _tx.drv + return ugu +} + +// String implements the fmt.Stringer. +func (ugu *UserGroupUser) String() string { + var builder strings.Builder + builder.WriteString("UserGroupUser(") + builder.WriteString(fmt.Sprintf("id=%v, ", ugu.ID)) + builder.WriteString("user_group_id=") + builder.WriteString(fmt.Sprintf("%v", ugu.UserGroupID)) + builder.WriteString(", ") + builder.WriteString("user_id=") + builder.WriteString(fmt.Sprintf("%v", ugu.UserID)) + builder.WriteByte(')') + return builder.String() +} + +// UserGroupUsers is a parsable slice of UserGroupUser. +type UserGroupUsers []*UserGroupUser diff --git a/backend/db/usergroupuser/usergroupuser.go b/backend/db/usergroupuser/usergroupuser.go new file mode 100644 index 00000000..fd422873 --- /dev/null +++ b/backend/db/usergroupuser/usergroupuser.go @@ -0,0 +1,102 @@ +// Code generated by ent, DO NOT EDIT. + +package usergroupuser + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the usergroupuser type in the database. + Label = "user_group_user" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldUserGroupID holds the string denoting the user_group_id field in the database. + FieldUserGroupID = "user_group_id" + // FieldUserID holds the string denoting the user_id field in the database. + FieldUserID = "user_id" + // EdgeUserGroup holds the string denoting the user_group edge name in mutations. + EdgeUserGroup = "user_group" + // EdgeUser holds the string denoting the user edge name in mutations. + EdgeUser = "user" + // Table holds the table name of the usergroupuser in the database. + Table = "user_group_users" + // UserGroupTable is the table that holds the user_group relation/edge. + UserGroupTable = "user_group_users" + // UserGroupInverseTable is the table name for the UserGroup entity. + // It exists in this package in order to avoid circular dependency with the "usergroup" package. + UserGroupInverseTable = "user_groups" + // UserGroupColumn is the table column denoting the user_group relation/edge. + UserGroupColumn = "user_group_id" + // UserTable is the table that holds the user relation/edge. + UserTable = "user_group_users" + // UserInverseTable is the table name for the User entity. + // It exists in this package in order to avoid circular dependency with the "user" package. + UserInverseTable = "users" + // UserColumn is the table column denoting the user relation/edge. + UserColumn = "user_id" +) + +// Columns holds all SQL columns for usergroupuser fields. +var Columns = []string{ + FieldID, + FieldUserGroupID, + FieldUserID, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +// OrderOption defines the ordering options for the UserGroupUser 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() +} + +// ByUserGroupID orders the results by the user_group_id field. +func ByUserGroupID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUserGroupID, opts...).ToFunc() +} + +// ByUserID orders the results by the user_id field. +func ByUserID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUserID, opts...).ToFunc() +} + +// ByUserGroupField orders the results by user_group field. +func ByUserGroupField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newUserGroupStep(), sql.OrderByField(field, opts...)) + } +} + +// ByUserField orders the results by user field. +func ByUserField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newUserStep(), sql.OrderByField(field, opts...)) + } +} +func newUserGroupStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(UserGroupInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, UserGroupTable, UserGroupColumn), + ) +} +func newUserStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(UserInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, UserTable, UserColumn), + ) +} diff --git a/backend/db/usergroupuser/where.go b/backend/db/usergroupuser/where.go new file mode 100644 index 00000000..324a3911 --- /dev/null +++ b/backend/db/usergroupuser/where.go @@ -0,0 +1,166 @@ +// Code generated by ent, DO NOT EDIT. + +package usergroupuser + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/google/uuid" +) + +// ID filters vertices based on their ID field. +func ID(id uuid.UUID) predicate.UserGroupUser { + return predicate.UserGroupUser(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id uuid.UUID) predicate.UserGroupUser { + return predicate.UserGroupUser(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id uuid.UUID) predicate.UserGroupUser { + return predicate.UserGroupUser(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...uuid.UUID) predicate.UserGroupUser { + return predicate.UserGroupUser(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...uuid.UUID) predicate.UserGroupUser { + return predicate.UserGroupUser(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id uuid.UUID) predicate.UserGroupUser { + return predicate.UserGroupUser(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id uuid.UUID) predicate.UserGroupUser { + return predicate.UserGroupUser(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id uuid.UUID) predicate.UserGroupUser { + return predicate.UserGroupUser(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id uuid.UUID) predicate.UserGroupUser { + return predicate.UserGroupUser(sql.FieldLTE(FieldID, id)) +} + +// UserGroupID applies equality check predicate on the "user_group_id" field. It's identical to UserGroupIDEQ. +func UserGroupID(v uuid.UUID) predicate.UserGroupUser { + return predicate.UserGroupUser(sql.FieldEQ(FieldUserGroupID, v)) +} + +// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ. +func UserID(v uuid.UUID) predicate.UserGroupUser { + return predicate.UserGroupUser(sql.FieldEQ(FieldUserID, v)) +} + +// UserGroupIDEQ applies the EQ predicate on the "user_group_id" field. +func UserGroupIDEQ(v uuid.UUID) predicate.UserGroupUser { + return predicate.UserGroupUser(sql.FieldEQ(FieldUserGroupID, v)) +} + +// UserGroupIDNEQ applies the NEQ predicate on the "user_group_id" field. +func UserGroupIDNEQ(v uuid.UUID) predicate.UserGroupUser { + return predicate.UserGroupUser(sql.FieldNEQ(FieldUserGroupID, v)) +} + +// UserGroupIDIn applies the In predicate on the "user_group_id" field. +func UserGroupIDIn(vs ...uuid.UUID) predicate.UserGroupUser { + return predicate.UserGroupUser(sql.FieldIn(FieldUserGroupID, vs...)) +} + +// UserGroupIDNotIn applies the NotIn predicate on the "user_group_id" field. +func UserGroupIDNotIn(vs ...uuid.UUID) predicate.UserGroupUser { + return predicate.UserGroupUser(sql.FieldNotIn(FieldUserGroupID, vs...)) +} + +// UserIDEQ applies the EQ predicate on the "user_id" field. +func UserIDEQ(v uuid.UUID) predicate.UserGroupUser { + return predicate.UserGroupUser(sql.FieldEQ(FieldUserID, v)) +} + +// UserIDNEQ applies the NEQ predicate on the "user_id" field. +func UserIDNEQ(v uuid.UUID) predicate.UserGroupUser { + return predicate.UserGroupUser(sql.FieldNEQ(FieldUserID, v)) +} + +// UserIDIn applies the In predicate on the "user_id" field. +func UserIDIn(vs ...uuid.UUID) predicate.UserGroupUser { + return predicate.UserGroupUser(sql.FieldIn(FieldUserID, vs...)) +} + +// UserIDNotIn applies the NotIn predicate on the "user_id" field. +func UserIDNotIn(vs ...uuid.UUID) predicate.UserGroupUser { + return predicate.UserGroupUser(sql.FieldNotIn(FieldUserID, vs...)) +} + +// HasUserGroup applies the HasEdge predicate on the "user_group" edge. +func HasUserGroup() predicate.UserGroupUser { + return predicate.UserGroupUser(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, UserGroupTable, UserGroupColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasUserGroupWith applies the HasEdge predicate on the "user_group" edge with a given conditions (other predicates). +func HasUserGroupWith(preds ...predicate.UserGroup) predicate.UserGroupUser { + return predicate.UserGroupUser(func(s *sql.Selector) { + step := newUserGroupStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasUser applies the HasEdge predicate on the "user" edge. +func HasUser() predicate.UserGroupUser { + return predicate.UserGroupUser(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, UserTable, UserColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasUserWith applies the HasEdge predicate on the "user" edge with a given conditions (other predicates). +func HasUserWith(preds ...predicate.User) predicate.UserGroupUser { + return predicate.UserGroupUser(func(s *sql.Selector) { + step := newUserStep() + 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.UserGroupUser) predicate.UserGroupUser { + return predicate.UserGroupUser(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.UserGroupUser) predicate.UserGroupUser { + return predicate.UserGroupUser(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.UserGroupUser) predicate.UserGroupUser { + return predicate.UserGroupUser(sql.NotPredicates(p)) +} diff --git a/backend/db/usergroupuser_create.go b/backend/db/usergroupuser_create.go new file mode 100644 index 00000000..34428693 --- /dev/null +++ b/backend/db/usergroupuser_create.go @@ -0,0 +1,587 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/usergroup" + "github.com/chaitin/MonkeyCode/backend/db/usergroupuser" + "github.com/google/uuid" +) + +// UserGroupUserCreate is the builder for creating a UserGroupUser entity. +type UserGroupUserCreate struct { + config + mutation *UserGroupUserMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetUserGroupID sets the "user_group_id" field. +func (uguc *UserGroupUserCreate) SetUserGroupID(u uuid.UUID) *UserGroupUserCreate { + uguc.mutation.SetUserGroupID(u) + return uguc +} + +// SetUserID sets the "user_id" field. +func (uguc *UserGroupUserCreate) SetUserID(u uuid.UUID) *UserGroupUserCreate { + uguc.mutation.SetUserID(u) + return uguc +} + +// SetID sets the "id" field. +func (uguc *UserGroupUserCreate) SetID(u uuid.UUID) *UserGroupUserCreate { + uguc.mutation.SetID(u) + return uguc +} + +// SetUserGroup sets the "user_group" edge to the UserGroup entity. +func (uguc *UserGroupUserCreate) SetUserGroup(u *UserGroup) *UserGroupUserCreate { + return uguc.SetUserGroupID(u.ID) +} + +// SetUser sets the "user" edge to the User entity. +func (uguc *UserGroupUserCreate) SetUser(u *User) *UserGroupUserCreate { + return uguc.SetUserID(u.ID) +} + +// Mutation returns the UserGroupUserMutation object of the builder. +func (uguc *UserGroupUserCreate) Mutation() *UserGroupUserMutation { + return uguc.mutation +} + +// Save creates the UserGroupUser in the database. +func (uguc *UserGroupUserCreate) Save(ctx context.Context) (*UserGroupUser, error) { + return withHooks(ctx, uguc.sqlSave, uguc.mutation, uguc.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (uguc *UserGroupUserCreate) SaveX(ctx context.Context) *UserGroupUser { + v, err := uguc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (uguc *UserGroupUserCreate) Exec(ctx context.Context) error { + _, err := uguc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (uguc *UserGroupUserCreate) ExecX(ctx context.Context) { + if err := uguc.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (uguc *UserGroupUserCreate) check() error { + if _, ok := uguc.mutation.UserGroupID(); !ok { + return &ValidationError{Name: "user_group_id", err: errors.New(`db: missing required field "UserGroupUser.user_group_id"`)} + } + if _, ok := uguc.mutation.UserID(); !ok { + return &ValidationError{Name: "user_id", err: errors.New(`db: missing required field "UserGroupUser.user_id"`)} + } + if len(uguc.mutation.UserGroupIDs()) == 0 { + return &ValidationError{Name: "user_group", err: errors.New(`db: missing required edge "UserGroupUser.user_group"`)} + } + if len(uguc.mutation.UserIDs()) == 0 { + return &ValidationError{Name: "user", err: errors.New(`db: missing required edge "UserGroupUser.user"`)} + } + return nil +} + +func (uguc *UserGroupUserCreate) sqlSave(ctx context.Context) (*UserGroupUser, error) { + if err := uguc.check(); err != nil { + return nil, err + } + _node, _spec := uguc.createSpec() + if err := sqlgraph.CreateNode(ctx, uguc.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 + } + } + uguc.mutation.id = &_node.ID + uguc.mutation.done = true + return _node, nil +} + +func (uguc *UserGroupUserCreate) createSpec() (*UserGroupUser, *sqlgraph.CreateSpec) { + var ( + _node = &UserGroupUser{config: uguc.config} + _spec = sqlgraph.NewCreateSpec(usergroupuser.Table, sqlgraph.NewFieldSpec(usergroupuser.FieldID, field.TypeUUID)) + ) + _spec.OnConflict = uguc.conflict + if id, ok := uguc.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = &id + } + if nodes := uguc.mutation.UserGroupIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: usergroupuser.UserGroupTable, + Columns: []string{usergroupuser.UserGroupColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroup.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.UserGroupID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := uguc.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: usergroupuser.UserTable, + Columns: []string{usergroupuser.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.UserID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.UserGroupUser.Create(). +// SetUserGroupID(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.UserGroupUserUpsert) { +// SetUserGroupID(v+v). +// }). +// Exec(ctx) +func (uguc *UserGroupUserCreate) OnConflict(opts ...sql.ConflictOption) *UserGroupUserUpsertOne { + uguc.conflict = opts + return &UserGroupUserUpsertOne{ + create: uguc, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.UserGroupUser.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (uguc *UserGroupUserCreate) OnConflictColumns(columns ...string) *UserGroupUserUpsertOne { + uguc.conflict = append(uguc.conflict, sql.ConflictColumns(columns...)) + return &UserGroupUserUpsertOne{ + create: uguc, + } +} + +type ( + // UserGroupUserUpsertOne is the builder for "upsert"-ing + // one UserGroupUser node. + UserGroupUserUpsertOne struct { + create *UserGroupUserCreate + } + + // UserGroupUserUpsert is the "OnConflict" setter. + UserGroupUserUpsert struct { + *sql.UpdateSet + } +) + +// SetUserGroupID sets the "user_group_id" field. +func (u *UserGroupUserUpsert) SetUserGroupID(v uuid.UUID) *UserGroupUserUpsert { + u.Set(usergroupuser.FieldUserGroupID, v) + return u +} + +// UpdateUserGroupID sets the "user_group_id" field to the value that was provided on create. +func (u *UserGroupUserUpsert) UpdateUserGroupID() *UserGroupUserUpsert { + u.SetExcluded(usergroupuser.FieldUserGroupID) + return u +} + +// SetUserID sets the "user_id" field. +func (u *UserGroupUserUpsert) SetUserID(v uuid.UUID) *UserGroupUserUpsert { + u.Set(usergroupuser.FieldUserID, v) + return u +} + +// UpdateUserID sets the "user_id" field to the value that was provided on create. +func (u *UserGroupUserUpsert) UpdateUserID() *UserGroupUserUpsert { + u.SetExcluded(usergroupuser.FieldUserID) + 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.UserGroupUser.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(usergroupuser.FieldID) +// }), +// ). +// Exec(ctx) +func (u *UserGroupUserUpsertOne) UpdateNewValues() *UserGroupUserUpsertOne { + 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(usergroupuser.FieldID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.UserGroupUser.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *UserGroupUserUpsertOne) Ignore() *UserGroupUserUpsertOne { + 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 *UserGroupUserUpsertOne) DoNothing() *UserGroupUserUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the UserGroupUserCreate.OnConflict +// documentation for more info. +func (u *UserGroupUserUpsertOne) Update(set func(*UserGroupUserUpsert)) *UserGroupUserUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&UserGroupUserUpsert{UpdateSet: update}) + })) + return u +} + +// SetUserGroupID sets the "user_group_id" field. +func (u *UserGroupUserUpsertOne) SetUserGroupID(v uuid.UUID) *UserGroupUserUpsertOne { + return u.Update(func(s *UserGroupUserUpsert) { + s.SetUserGroupID(v) + }) +} + +// UpdateUserGroupID sets the "user_group_id" field to the value that was provided on create. +func (u *UserGroupUserUpsertOne) UpdateUserGroupID() *UserGroupUserUpsertOne { + return u.Update(func(s *UserGroupUserUpsert) { + s.UpdateUserGroupID() + }) +} + +// SetUserID sets the "user_id" field. +func (u *UserGroupUserUpsertOne) SetUserID(v uuid.UUID) *UserGroupUserUpsertOne { + return u.Update(func(s *UserGroupUserUpsert) { + s.SetUserID(v) + }) +} + +// UpdateUserID sets the "user_id" field to the value that was provided on create. +func (u *UserGroupUserUpsertOne) UpdateUserID() *UserGroupUserUpsertOne { + return u.Update(func(s *UserGroupUserUpsert) { + s.UpdateUserID() + }) +} + +// Exec executes the query. +func (u *UserGroupUserUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for UserGroupUserCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *UserGroupUserUpsertOne) 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 *UserGroupUserUpsertOne) 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: UserGroupUserUpsertOne.ID is not supported by MySQL driver. Use UserGroupUserUpsertOne.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 *UserGroupUserUpsertOne) IDX(ctx context.Context) uuid.UUID { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// UserGroupUserCreateBulk is the builder for creating many UserGroupUser entities in bulk. +type UserGroupUserCreateBulk struct { + config + err error + builders []*UserGroupUserCreate + conflict []sql.ConflictOption +} + +// Save creates the UserGroupUser entities in the database. +func (ugucb *UserGroupUserCreateBulk) Save(ctx context.Context) ([]*UserGroupUser, error) { + if ugucb.err != nil { + return nil, ugucb.err + } + specs := make([]*sqlgraph.CreateSpec, len(ugucb.builders)) + nodes := make([]*UserGroupUser, len(ugucb.builders)) + mutators := make([]Mutator, len(ugucb.builders)) + for i := range ugucb.builders { + func(i int, root context.Context) { + builder := ugucb.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*UserGroupUserMutation) + 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, ugucb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = ugucb.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, ugucb.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, ugucb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (ugucb *UserGroupUserCreateBulk) SaveX(ctx context.Context) []*UserGroupUser { + v, err := ugucb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (ugucb *UserGroupUserCreateBulk) Exec(ctx context.Context) error { + _, err := ugucb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ugucb *UserGroupUserCreateBulk) ExecX(ctx context.Context) { + if err := ugucb.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.UserGroupUser.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.UserGroupUserUpsert) { +// SetUserGroupID(v+v). +// }). +// Exec(ctx) +func (ugucb *UserGroupUserCreateBulk) OnConflict(opts ...sql.ConflictOption) *UserGroupUserUpsertBulk { + ugucb.conflict = opts + return &UserGroupUserUpsertBulk{ + create: ugucb, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.UserGroupUser.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (ugucb *UserGroupUserCreateBulk) OnConflictColumns(columns ...string) *UserGroupUserUpsertBulk { + ugucb.conflict = append(ugucb.conflict, sql.ConflictColumns(columns...)) + return &UserGroupUserUpsertBulk{ + create: ugucb, + } +} + +// UserGroupUserUpsertBulk is the builder for "upsert"-ing +// a bulk of UserGroupUser nodes. +type UserGroupUserUpsertBulk struct { + create *UserGroupUserCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.UserGroupUser.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(usergroupuser.FieldID) +// }), +// ). +// Exec(ctx) +func (u *UserGroupUserUpsertBulk) UpdateNewValues() *UserGroupUserUpsertBulk { + 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(usergroupuser.FieldID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.UserGroupUser.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *UserGroupUserUpsertBulk) Ignore() *UserGroupUserUpsertBulk { + 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 *UserGroupUserUpsertBulk) DoNothing() *UserGroupUserUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the UserGroupUserCreateBulk.OnConflict +// documentation for more info. +func (u *UserGroupUserUpsertBulk) Update(set func(*UserGroupUserUpsert)) *UserGroupUserUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&UserGroupUserUpsert{UpdateSet: update}) + })) + return u +} + +// SetUserGroupID sets the "user_group_id" field. +func (u *UserGroupUserUpsertBulk) SetUserGroupID(v uuid.UUID) *UserGroupUserUpsertBulk { + return u.Update(func(s *UserGroupUserUpsert) { + s.SetUserGroupID(v) + }) +} + +// UpdateUserGroupID sets the "user_group_id" field to the value that was provided on create. +func (u *UserGroupUserUpsertBulk) UpdateUserGroupID() *UserGroupUserUpsertBulk { + return u.Update(func(s *UserGroupUserUpsert) { + s.UpdateUserGroupID() + }) +} + +// SetUserID sets the "user_id" field. +func (u *UserGroupUserUpsertBulk) SetUserID(v uuid.UUID) *UserGroupUserUpsertBulk { + return u.Update(func(s *UserGroupUserUpsert) { + s.SetUserID(v) + }) +} + +// UpdateUserID sets the "user_id" field to the value that was provided on create. +func (u *UserGroupUserUpsertBulk) UpdateUserID() *UserGroupUserUpsertBulk { + return u.Update(func(s *UserGroupUserUpsert) { + s.UpdateUserID() + }) +} + +// Exec executes the query. +func (u *UserGroupUserUpsertBulk) 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 UserGroupUserCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for UserGroupUserCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *UserGroupUserUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/usergroupuser_delete.go b/backend/db/usergroupuser_delete.go new file mode 100644 index 00000000..ba01a2e9 --- /dev/null +++ b/backend/db/usergroupuser_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/usergroupuser" +) + +// UserGroupUserDelete is the builder for deleting a UserGroupUser entity. +type UserGroupUserDelete struct { + config + hooks []Hook + mutation *UserGroupUserMutation +} + +// Where appends a list predicates to the UserGroupUserDelete builder. +func (ugud *UserGroupUserDelete) Where(ps ...predicate.UserGroupUser) *UserGroupUserDelete { + ugud.mutation.Where(ps...) + return ugud +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (ugud *UserGroupUserDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, ugud.sqlExec, ugud.mutation, ugud.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (ugud *UserGroupUserDelete) ExecX(ctx context.Context) int { + n, err := ugud.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (ugud *UserGroupUserDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(usergroupuser.Table, sqlgraph.NewFieldSpec(usergroupuser.FieldID, field.TypeUUID)) + if ps := ugud.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, ugud.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + ugud.mutation.done = true + return affected, err +} + +// UserGroupUserDeleteOne is the builder for deleting a single UserGroupUser entity. +type UserGroupUserDeleteOne struct { + ugud *UserGroupUserDelete +} + +// Where appends a list predicates to the UserGroupUserDelete builder. +func (ugudo *UserGroupUserDeleteOne) Where(ps ...predicate.UserGroupUser) *UserGroupUserDeleteOne { + ugudo.ugud.mutation.Where(ps...) + return ugudo +} + +// Exec executes the deletion query. +func (ugudo *UserGroupUserDeleteOne) Exec(ctx context.Context) error { + n, err := ugudo.ugud.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{usergroupuser.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (ugudo *UserGroupUserDeleteOne) ExecX(ctx context.Context) { + if err := ugudo.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/usergroupuser_query.go b/backend/db/usergroupuser_query.go new file mode 100644 index 00000000..b4786c87 --- /dev/null +++ b/backend/db/usergroupuser_query.go @@ -0,0 +1,732 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/usergroup" + "github.com/chaitin/MonkeyCode/backend/db/usergroupuser" + "github.com/google/uuid" +) + +// UserGroupUserQuery is the builder for querying UserGroupUser entities. +type UserGroupUserQuery struct { + config + ctx *QueryContext + order []usergroupuser.OrderOption + inters []Interceptor + predicates []predicate.UserGroupUser + withUserGroup *UserGroupQuery + withUser *UserQuery + 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 UserGroupUserQuery builder. +func (uguq *UserGroupUserQuery) Where(ps ...predicate.UserGroupUser) *UserGroupUserQuery { + uguq.predicates = append(uguq.predicates, ps...) + return uguq +} + +// Limit the number of records to be returned by this query. +func (uguq *UserGroupUserQuery) Limit(limit int) *UserGroupUserQuery { + uguq.ctx.Limit = &limit + return uguq +} + +// Offset to start from. +func (uguq *UserGroupUserQuery) Offset(offset int) *UserGroupUserQuery { + uguq.ctx.Offset = &offset + return uguq +} + +// 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 (uguq *UserGroupUserQuery) Unique(unique bool) *UserGroupUserQuery { + uguq.ctx.Unique = &unique + return uguq +} + +// Order specifies how the records should be ordered. +func (uguq *UserGroupUserQuery) Order(o ...usergroupuser.OrderOption) *UserGroupUserQuery { + uguq.order = append(uguq.order, o...) + return uguq +} + +// QueryUserGroup chains the current query on the "user_group" edge. +func (uguq *UserGroupUserQuery) QueryUserGroup() *UserGroupQuery { + query := (&UserGroupClient{config: uguq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := uguq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := uguq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(usergroupuser.Table, usergroupuser.FieldID, selector), + sqlgraph.To(usergroup.Table, usergroup.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, usergroupuser.UserGroupTable, usergroupuser.UserGroupColumn), + ) + fromU = sqlgraph.SetNeighbors(uguq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryUser chains the current query on the "user" edge. +func (uguq *UserGroupUserQuery) QueryUser() *UserQuery { + query := (&UserClient{config: uguq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := uguq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := uguq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(usergroupuser.Table, usergroupuser.FieldID, selector), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, usergroupuser.UserTable, usergroupuser.UserColumn), + ) + fromU = sqlgraph.SetNeighbors(uguq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first UserGroupUser entity from the query. +// Returns a *NotFoundError when no UserGroupUser was found. +func (uguq *UserGroupUserQuery) First(ctx context.Context) (*UserGroupUser, error) { + nodes, err := uguq.Limit(1).All(setContextOp(ctx, uguq.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{usergroupuser.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (uguq *UserGroupUserQuery) FirstX(ctx context.Context) *UserGroupUser { + node, err := uguq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first UserGroupUser ID from the query. +// Returns a *NotFoundError when no UserGroupUser ID was found. +func (uguq *UserGroupUserQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = uguq.Limit(1).IDs(setContextOp(ctx, uguq.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{usergroupuser.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (uguq *UserGroupUserQuery) FirstIDX(ctx context.Context) uuid.UUID { + id, err := uguq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single UserGroupUser entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one UserGroupUser entity is found. +// Returns a *NotFoundError when no UserGroupUser entities are found. +func (uguq *UserGroupUserQuery) Only(ctx context.Context) (*UserGroupUser, error) { + nodes, err := uguq.Limit(2).All(setContextOp(ctx, uguq.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{usergroupuser.Label} + default: + return nil, &NotSingularError{usergroupuser.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (uguq *UserGroupUserQuery) OnlyX(ctx context.Context) *UserGroupUser { + node, err := uguq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only UserGroupUser ID in the query. +// Returns a *NotSingularError when more than one UserGroupUser ID is found. +// Returns a *NotFoundError when no entities are found. +func (uguq *UserGroupUserQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = uguq.Limit(2).IDs(setContextOp(ctx, uguq.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{usergroupuser.Label} + default: + err = &NotSingularError{usergroupuser.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (uguq *UserGroupUserQuery) OnlyIDX(ctx context.Context) uuid.UUID { + id, err := uguq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of UserGroupUsers. +func (uguq *UserGroupUserQuery) All(ctx context.Context) ([]*UserGroupUser, error) { + ctx = setContextOp(ctx, uguq.ctx, ent.OpQueryAll) + if err := uguq.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*UserGroupUser, *UserGroupUserQuery]() + return withInterceptors[[]*UserGroupUser](ctx, uguq, qr, uguq.inters) +} + +// AllX is like All, but panics if an error occurs. +func (uguq *UserGroupUserQuery) AllX(ctx context.Context) []*UserGroupUser { + nodes, err := uguq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of UserGroupUser IDs. +func (uguq *UserGroupUserQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) { + if uguq.ctx.Unique == nil && uguq.path != nil { + uguq.Unique(true) + } + ctx = setContextOp(ctx, uguq.ctx, ent.OpQueryIDs) + if err = uguq.Select(usergroupuser.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (uguq *UserGroupUserQuery) IDsX(ctx context.Context) []uuid.UUID { + ids, err := uguq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (uguq *UserGroupUserQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, uguq.ctx, ent.OpQueryCount) + if err := uguq.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, uguq, querierCount[*UserGroupUserQuery](), uguq.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (uguq *UserGroupUserQuery) CountX(ctx context.Context) int { + count, err := uguq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (uguq *UserGroupUserQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, uguq.ctx, ent.OpQueryExist) + switch _, err := uguq.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 (uguq *UserGroupUserQuery) ExistX(ctx context.Context) bool { + exist, err := uguq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the UserGroupUserQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (uguq *UserGroupUserQuery) Clone() *UserGroupUserQuery { + if uguq == nil { + return nil + } + return &UserGroupUserQuery{ + config: uguq.config, + ctx: uguq.ctx.Clone(), + order: append([]usergroupuser.OrderOption{}, uguq.order...), + inters: append([]Interceptor{}, uguq.inters...), + predicates: append([]predicate.UserGroupUser{}, uguq.predicates...), + withUserGroup: uguq.withUserGroup.Clone(), + withUser: uguq.withUser.Clone(), + // clone intermediate query. + sql: uguq.sql.Clone(), + path: uguq.path, + modifiers: append([]func(*sql.Selector){}, uguq.modifiers...), + } +} + +// WithUserGroup tells the query-builder to eager-load the nodes that are connected to +// the "user_group" edge. The optional arguments are used to configure the query builder of the edge. +func (uguq *UserGroupUserQuery) WithUserGroup(opts ...func(*UserGroupQuery)) *UserGroupUserQuery { + query := (&UserGroupClient{config: uguq.config}).Query() + for _, opt := range opts { + opt(query) + } + uguq.withUserGroup = query + return uguq +} + +// WithUser tells the query-builder to eager-load the nodes that are connected to +// the "user" edge. The optional arguments are used to configure the query builder of the edge. +func (uguq *UserGroupUserQuery) WithUser(opts ...func(*UserQuery)) *UserGroupUserQuery { + query := (&UserClient{config: uguq.config}).Query() + for _, opt := range opts { + opt(query) + } + uguq.withUser = query + return uguq +} + +// 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 { +// UserGroupID uuid.UUID `json:"user_group_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.UserGroupUser.Query(). +// GroupBy(usergroupuser.FieldUserGroupID). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (uguq *UserGroupUserQuery) GroupBy(field string, fields ...string) *UserGroupUserGroupBy { + uguq.ctx.Fields = append([]string{field}, fields...) + grbuild := &UserGroupUserGroupBy{build: uguq} + grbuild.flds = &uguq.ctx.Fields + grbuild.label = usergroupuser.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 { +// UserGroupID uuid.UUID `json:"user_group_id,omitempty"` +// } +// +// client.UserGroupUser.Query(). +// Select(usergroupuser.FieldUserGroupID). +// Scan(ctx, &v) +func (uguq *UserGroupUserQuery) Select(fields ...string) *UserGroupUserSelect { + uguq.ctx.Fields = append(uguq.ctx.Fields, fields...) + sbuild := &UserGroupUserSelect{UserGroupUserQuery: uguq} + sbuild.label = usergroupuser.Label + sbuild.flds, sbuild.scan = &uguq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a UserGroupUserSelect configured with the given aggregations. +func (uguq *UserGroupUserQuery) Aggregate(fns ...AggregateFunc) *UserGroupUserSelect { + return uguq.Select().Aggregate(fns...) +} + +func (uguq *UserGroupUserQuery) prepareQuery(ctx context.Context) error { + for _, inter := range uguq.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, uguq); err != nil { + return err + } + } + } + for _, f := range uguq.ctx.Fields { + if !usergroupuser.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + } + if uguq.path != nil { + prev, err := uguq.path(ctx) + if err != nil { + return err + } + uguq.sql = prev + } + return nil +} + +func (uguq *UserGroupUserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*UserGroupUser, error) { + var ( + nodes = []*UserGroupUser{} + _spec = uguq.querySpec() + loadedTypes = [2]bool{ + uguq.withUserGroup != nil, + uguq.withUser != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*UserGroupUser).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &UserGroupUser{config: uguq.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(uguq.modifiers) > 0 { + _spec.Modifiers = uguq.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, uguq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := uguq.withUserGroup; query != nil { + if err := uguq.loadUserGroup(ctx, query, nodes, nil, + func(n *UserGroupUser, e *UserGroup) { n.Edges.UserGroup = e }); err != nil { + return nil, err + } + } + if query := uguq.withUser; query != nil { + if err := uguq.loadUser(ctx, query, nodes, nil, + func(n *UserGroupUser, e *User) { n.Edges.User = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (uguq *UserGroupUserQuery) loadUserGroup(ctx context.Context, query *UserGroupQuery, nodes []*UserGroupUser, init func(*UserGroupUser), assign func(*UserGroupUser, *UserGroup)) error { + ids := make([]uuid.UUID, 0, len(nodes)) + nodeids := make(map[uuid.UUID][]*UserGroupUser) + for i := range nodes { + fk := nodes[i].UserGroupID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(usergroup.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return fmt.Errorf(`unexpected foreign-key "user_group_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (uguq *UserGroupUserQuery) loadUser(ctx context.Context, query *UserQuery, nodes []*UserGroupUser, init func(*UserGroupUser), assign func(*UserGroupUser, *User)) error { + ids := make([]uuid.UUID, 0, len(nodes)) + nodeids := make(map[uuid.UUID][]*UserGroupUser) + for i := range nodes { + fk := nodes[i].UserID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(user.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return fmt.Errorf(`unexpected foreign-key "user_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (uguq *UserGroupUserQuery) sqlCount(ctx context.Context) (int, error) { + _spec := uguq.querySpec() + if len(uguq.modifiers) > 0 { + _spec.Modifiers = uguq.modifiers + } + _spec.Node.Columns = uguq.ctx.Fields + if len(uguq.ctx.Fields) > 0 { + _spec.Unique = uguq.ctx.Unique != nil && *uguq.ctx.Unique + } + return sqlgraph.CountNodes(ctx, uguq.driver, _spec) +} + +func (uguq *UserGroupUserQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(usergroupuser.Table, usergroupuser.Columns, sqlgraph.NewFieldSpec(usergroupuser.FieldID, field.TypeUUID)) + _spec.From = uguq.sql + if unique := uguq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if uguq.path != nil { + _spec.Unique = true + } + if fields := uguq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, usergroupuser.FieldID) + for i := range fields { + if fields[i] != usergroupuser.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if uguq.withUserGroup != nil { + _spec.Node.AddColumnOnce(usergroupuser.FieldUserGroupID) + } + if uguq.withUser != nil { + _spec.Node.AddColumnOnce(usergroupuser.FieldUserID) + } + } + if ps := uguq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := uguq.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := uguq.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := uguq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (uguq *UserGroupUserQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(uguq.driver.Dialect()) + t1 := builder.Table(usergroupuser.Table) + columns := uguq.ctx.Fields + if len(columns) == 0 { + columns = usergroupuser.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if uguq.sql != nil { + selector = uguq.sql + selector.Select(selector.Columns(columns...)...) + } + if uguq.ctx.Unique != nil && *uguq.ctx.Unique { + selector.Distinct() + } + for _, m := range uguq.modifiers { + m(selector) + } + for _, p := range uguq.predicates { + p(selector) + } + for _, p := range uguq.order { + p(selector) + } + if offset := uguq.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 := uguq.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 (uguq *UserGroupUserQuery) ForUpdate(opts ...sql.LockOption) *UserGroupUserQuery { + if uguq.driver.Dialect() == dialect.Postgres { + uguq.Unique(false) + } + uguq.modifiers = append(uguq.modifiers, func(s *sql.Selector) { + s.ForUpdate(opts...) + }) + return uguq +} + +// 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 (uguq *UserGroupUserQuery) ForShare(opts ...sql.LockOption) *UserGroupUserQuery { + if uguq.driver.Dialect() == dialect.Postgres { + uguq.Unique(false) + } + uguq.modifiers = append(uguq.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return uguq +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (uguq *UserGroupUserQuery) Modify(modifiers ...func(s *sql.Selector)) *UserGroupUserSelect { + uguq.modifiers = append(uguq.modifiers, modifiers...) + return uguq.Select() +} + +// UserGroupUserGroupBy is the group-by builder for UserGroupUser entities. +type UserGroupUserGroupBy struct { + selector + build *UserGroupUserQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (ugugb *UserGroupUserGroupBy) Aggregate(fns ...AggregateFunc) *UserGroupUserGroupBy { + ugugb.fns = append(ugugb.fns, fns...) + return ugugb +} + +// Scan applies the selector query and scans the result into the given value. +func (ugugb *UserGroupUserGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, ugugb.build.ctx, ent.OpQueryGroupBy) + if err := ugugb.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*UserGroupUserQuery, *UserGroupUserGroupBy](ctx, ugugb.build, ugugb, ugugb.build.inters, v) +} + +func (ugugb *UserGroupUserGroupBy) sqlScan(ctx context.Context, root *UserGroupUserQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(ugugb.fns)) + for _, fn := range ugugb.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*ugugb.flds)+len(ugugb.fns)) + for _, f := range *ugugb.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*ugugb.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := ugugb.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// UserGroupUserSelect is the builder for selecting fields of UserGroupUser entities. +type UserGroupUserSelect struct { + *UserGroupUserQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (ugus *UserGroupUserSelect) Aggregate(fns ...AggregateFunc) *UserGroupUserSelect { + ugus.fns = append(ugus.fns, fns...) + return ugus +} + +// Scan applies the selector query and scans the result into the given value. +func (ugus *UserGroupUserSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, ugus.ctx, ent.OpQuerySelect) + if err := ugus.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*UserGroupUserQuery, *UserGroupUserSelect](ctx, ugus.UserGroupUserQuery, ugus, ugus.inters, v) +} + +func (ugus *UserGroupUserSelect) sqlScan(ctx context.Context, root *UserGroupUserQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(ugus.fns)) + for _, fn := range ugus.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*ugus.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 := ugus.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 (ugus *UserGroupUserSelect) Modify(modifiers ...func(s *sql.Selector)) *UserGroupUserSelect { + ugus.modifiers = append(ugus.modifiers, modifiers...) + return ugus +} diff --git a/backend/db/usergroupuser_update.go b/backend/db/usergroupuser_update.go new file mode 100644 index 00000000..318148c0 --- /dev/null +++ b/backend/db/usergroupuser_update.go @@ -0,0 +1,438 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/usergroup" + "github.com/chaitin/MonkeyCode/backend/db/usergroupuser" + "github.com/google/uuid" +) + +// UserGroupUserUpdate is the builder for updating UserGroupUser entities. +type UserGroupUserUpdate struct { + config + hooks []Hook + mutation *UserGroupUserMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the UserGroupUserUpdate builder. +func (uguu *UserGroupUserUpdate) Where(ps ...predicate.UserGroupUser) *UserGroupUserUpdate { + uguu.mutation.Where(ps...) + return uguu +} + +// SetUserGroupID sets the "user_group_id" field. +func (uguu *UserGroupUserUpdate) SetUserGroupID(u uuid.UUID) *UserGroupUserUpdate { + uguu.mutation.SetUserGroupID(u) + return uguu +} + +// SetNillableUserGroupID sets the "user_group_id" field if the given value is not nil. +func (uguu *UserGroupUserUpdate) SetNillableUserGroupID(u *uuid.UUID) *UserGroupUserUpdate { + if u != nil { + uguu.SetUserGroupID(*u) + } + return uguu +} + +// SetUserID sets the "user_id" field. +func (uguu *UserGroupUserUpdate) SetUserID(u uuid.UUID) *UserGroupUserUpdate { + uguu.mutation.SetUserID(u) + return uguu +} + +// SetNillableUserID sets the "user_id" field if the given value is not nil. +func (uguu *UserGroupUserUpdate) SetNillableUserID(u *uuid.UUID) *UserGroupUserUpdate { + if u != nil { + uguu.SetUserID(*u) + } + return uguu +} + +// SetUserGroup sets the "user_group" edge to the UserGroup entity. +func (uguu *UserGroupUserUpdate) SetUserGroup(u *UserGroup) *UserGroupUserUpdate { + return uguu.SetUserGroupID(u.ID) +} + +// SetUser sets the "user" edge to the User entity. +func (uguu *UserGroupUserUpdate) SetUser(u *User) *UserGroupUserUpdate { + return uguu.SetUserID(u.ID) +} + +// Mutation returns the UserGroupUserMutation object of the builder. +func (uguu *UserGroupUserUpdate) Mutation() *UserGroupUserMutation { + return uguu.mutation +} + +// ClearUserGroup clears the "user_group" edge to the UserGroup entity. +func (uguu *UserGroupUserUpdate) ClearUserGroup() *UserGroupUserUpdate { + uguu.mutation.ClearUserGroup() + return uguu +} + +// ClearUser clears the "user" edge to the User entity. +func (uguu *UserGroupUserUpdate) ClearUser() *UserGroupUserUpdate { + uguu.mutation.ClearUser() + return uguu +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (uguu *UserGroupUserUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, uguu.sqlSave, uguu.mutation, uguu.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (uguu *UserGroupUserUpdate) SaveX(ctx context.Context) int { + affected, err := uguu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (uguu *UserGroupUserUpdate) Exec(ctx context.Context) error { + _, err := uguu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (uguu *UserGroupUserUpdate) ExecX(ctx context.Context) { + if err := uguu.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (uguu *UserGroupUserUpdate) check() error { + if uguu.mutation.UserGroupCleared() && len(uguu.mutation.UserGroupIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "UserGroupUser.user_group"`) + } + if uguu.mutation.UserCleared() && len(uguu.mutation.UserIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "UserGroupUser.user"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (uguu *UserGroupUserUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *UserGroupUserUpdate { + uguu.modifiers = append(uguu.modifiers, modifiers...) + return uguu +} + +func (uguu *UserGroupUserUpdate) sqlSave(ctx context.Context) (n int, err error) { + if err := uguu.check(); err != nil { + return n, err + } + _spec := sqlgraph.NewUpdateSpec(usergroupuser.Table, usergroupuser.Columns, sqlgraph.NewFieldSpec(usergroupuser.FieldID, field.TypeUUID)) + if ps := uguu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if uguu.mutation.UserGroupCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: usergroupuser.UserGroupTable, + Columns: []string{usergroupuser.UserGroupColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroup.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uguu.mutation.UserGroupIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: usergroupuser.UserGroupTable, + Columns: []string{usergroupuser.UserGroupColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroup.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if uguu.mutation.UserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: usergroupuser.UserTable, + Columns: []string{usergroupuser.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uguu.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: usergroupuser.UserTable, + Columns: []string{usergroupuser.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(uguu.modifiers...) + if n, err = sqlgraph.UpdateNodes(ctx, uguu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{usergroupuser.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + uguu.mutation.done = true + return n, nil +} + +// UserGroupUserUpdateOne is the builder for updating a single UserGroupUser entity. +type UserGroupUserUpdateOne struct { + config + fields []string + hooks []Hook + mutation *UserGroupUserMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetUserGroupID sets the "user_group_id" field. +func (uguuo *UserGroupUserUpdateOne) SetUserGroupID(u uuid.UUID) *UserGroupUserUpdateOne { + uguuo.mutation.SetUserGroupID(u) + return uguuo +} + +// SetNillableUserGroupID sets the "user_group_id" field if the given value is not nil. +func (uguuo *UserGroupUserUpdateOne) SetNillableUserGroupID(u *uuid.UUID) *UserGroupUserUpdateOne { + if u != nil { + uguuo.SetUserGroupID(*u) + } + return uguuo +} + +// SetUserID sets the "user_id" field. +func (uguuo *UserGroupUserUpdateOne) SetUserID(u uuid.UUID) *UserGroupUserUpdateOne { + uguuo.mutation.SetUserID(u) + return uguuo +} + +// SetNillableUserID sets the "user_id" field if the given value is not nil. +func (uguuo *UserGroupUserUpdateOne) SetNillableUserID(u *uuid.UUID) *UserGroupUserUpdateOne { + if u != nil { + uguuo.SetUserID(*u) + } + return uguuo +} + +// SetUserGroup sets the "user_group" edge to the UserGroup entity. +func (uguuo *UserGroupUserUpdateOne) SetUserGroup(u *UserGroup) *UserGroupUserUpdateOne { + return uguuo.SetUserGroupID(u.ID) +} + +// SetUser sets the "user" edge to the User entity. +func (uguuo *UserGroupUserUpdateOne) SetUser(u *User) *UserGroupUserUpdateOne { + return uguuo.SetUserID(u.ID) +} + +// Mutation returns the UserGroupUserMutation object of the builder. +func (uguuo *UserGroupUserUpdateOne) Mutation() *UserGroupUserMutation { + return uguuo.mutation +} + +// ClearUserGroup clears the "user_group" edge to the UserGroup entity. +func (uguuo *UserGroupUserUpdateOne) ClearUserGroup() *UserGroupUserUpdateOne { + uguuo.mutation.ClearUserGroup() + return uguuo +} + +// ClearUser clears the "user" edge to the User entity. +func (uguuo *UserGroupUserUpdateOne) ClearUser() *UserGroupUserUpdateOne { + uguuo.mutation.ClearUser() + return uguuo +} + +// Where appends a list predicates to the UserGroupUserUpdate builder. +func (uguuo *UserGroupUserUpdateOne) Where(ps ...predicate.UserGroupUser) *UserGroupUserUpdateOne { + uguuo.mutation.Where(ps...) + return uguuo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (uguuo *UserGroupUserUpdateOne) Select(field string, fields ...string) *UserGroupUserUpdateOne { + uguuo.fields = append([]string{field}, fields...) + return uguuo +} + +// Save executes the query and returns the updated UserGroupUser entity. +func (uguuo *UserGroupUserUpdateOne) Save(ctx context.Context) (*UserGroupUser, error) { + return withHooks(ctx, uguuo.sqlSave, uguuo.mutation, uguuo.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (uguuo *UserGroupUserUpdateOne) SaveX(ctx context.Context) *UserGroupUser { + node, err := uguuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (uguuo *UserGroupUserUpdateOne) Exec(ctx context.Context) error { + _, err := uguuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (uguuo *UserGroupUserUpdateOne) ExecX(ctx context.Context) { + if err := uguuo.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (uguuo *UserGroupUserUpdateOne) check() error { + if uguuo.mutation.UserGroupCleared() && len(uguuo.mutation.UserGroupIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "UserGroupUser.user_group"`) + } + if uguuo.mutation.UserCleared() && len(uguuo.mutation.UserIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "UserGroupUser.user"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (uguuo *UserGroupUserUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *UserGroupUserUpdateOne { + uguuo.modifiers = append(uguuo.modifiers, modifiers...) + return uguuo +} + +func (uguuo *UserGroupUserUpdateOne) sqlSave(ctx context.Context) (_node *UserGroupUser, err error) { + if err := uguuo.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(usergroupuser.Table, usergroupuser.Columns, sqlgraph.NewFieldSpec(usergroupuser.FieldID, field.TypeUUID)) + id, ok := uguuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "UserGroupUser.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := uguuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, usergroupuser.FieldID) + for _, f := range fields { + if !usergroupuser.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != usergroupuser.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := uguuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if uguuo.mutation.UserGroupCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: usergroupuser.UserGroupTable, + Columns: []string{usergroupuser.UserGroupColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroup.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uguuo.mutation.UserGroupIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: usergroupuser.UserGroupTable, + Columns: []string{usergroupuser.UserGroupColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usergroup.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if uguuo.mutation.UserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: usergroupuser.UserTable, + Columns: []string{usergroupuser.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uguuo.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: usergroupuser.UserTable, + Columns: []string{usergroupuser.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(uguuo.modifiers...) + _node = &UserGroupUser{config: uguuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, uguuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{usergroupuser.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + uguuo.mutation.done = true + return _node, nil +} diff --git a/backend/docs/swagger.json b/backend/docs/swagger.json new file mode 100644 index 00000000..6300ba46 --- /dev/null +++ b/backend/docs/swagger.json @@ -0,0 +1,7392 @@ +{ + "swagger": "2.0", + "info": { + "description": "MonkeyCode API", + "title": "MonkeyCode API", + "contact": {}, + "version": "1.0" + }, + "paths": { + "/api/v1/admin/create": { + "post": { + "description": "创建管理员", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Admin" + ], + "summary": "创建管理员", + "operationId": "create-admin", + "parameters": [ + { + "description": "创建管理员参数", + "name": "param", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.CreateAdminReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.AdminUser" + } + } + } + ] + } + } + } + } + }, + "/api/v1/admin/delete": { + "delete": { + "description": "删除管理员", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Admin" + ], + "summary": "删除管理员", + "operationId": "delete-admin", + "parameters": [ + { + "type": "string", + "description": "管理员ID", + "name": "id", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "type": "object" + } + } + } + ] + } + } + } + } + }, + "/api/v1/admin/export-completion-data": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "管理员导出所有补全相关数据", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "admin" + ], + "summary": "导出补全数据", + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.ExportCompletionDataResp" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/web.Resp" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/web.Resp" + } + } + } + } + }, + "/api/v1/admin/list": { + "get": { + "description": "获取管理员用户列表", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Admin" + ], + "summary": "获取管理员用户列表", + "operationId": "list-admin-user", + "parameters": [ + { + "type": "string", + "description": "下一页标识", + "name": "next_token", + "in": "query" + }, + { + "type": "integer", + "description": "分页", + "name": "page", + "in": "query" + }, + { + "type": "integer", + "description": "每页多少条记录", + "name": "size", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.ListAdminUserResp" + } + } + } + ] + } + } + } + } + }, + "/api/v1/admin/login": { + "post": { + "description": "管理员登录", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Admin" + ], + "summary": "管理员登录", + "operationId": "admin-login", + "parameters": [ + { + "description": "登录参数", + "name": "param", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.LoginReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.AdminUser" + } + } + } + ] + } + } + } + } + }, + "/api/v1/admin/login-history": { + "get": { + "description": "获取管理员登录历史", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Admin" + ], + "summary": "获取管理员登录历史", + "operationId": "admin-login-history", + "parameters": [ + { + "type": "string", + "description": "下一页标识", + "name": "next_token", + "in": "query" + }, + { + "type": "integer", + "description": "分页", + "name": "page", + "in": "query" + }, + { + "type": "integer", + "description": "每页多少条记录", + "name": "size", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.ListAdminLoginHistoryResp" + } + } + } + ] + } + } + } + } + }, + "/api/v1/admin/logout": { + "post": { + "description": "管理员登出", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Admin" + ], + "summary": "管理员登出", + "operationId": "admin-logout", + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/web.Resp" + } + } + } + } + }, + "/api/v1/admin/profile": { + "get": { + "description": "管理员信息", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Admin" + ], + "summary": "管理员信息", + "operationId": "admin-profile", + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.AdminUser" + } + } + } + ] + } + } + } + } + }, + "/api/v1/admin/role": { + "get": { + "description": "获取角色列表", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Admin" + ], + "summary": "获取角色列表", + "operationId": "list-role", + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.Role" + } + } + } + } + ] + } + } + } + }, + "post": { + "description": "授权角色", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Admin" + ], + "summary": "授权角色", + "operationId": "grant-role", + "parameters": [ + { + "description": "授权角色参数", + "name": "param", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.GrantRoleReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/web.Resp" + } + } + } + } + }, + "/api/v1/admin/setting": { + "get": { + "description": "获取系统设置", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Admin" + ], + "summary": "获取系统设置", + "operationId": "get-setting", + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.Setting" + } + } + } + ] + } + } + } + }, + "put": { + "description": "更新为增量更新,只传需要更新的字段", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Admin" + ], + "summary": "更新系统设置", + "operationId": "update-setting", + "parameters": [ + { + "description": "更新系统设置参数", + "name": "param", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.UpdateSettingReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.Setting" + } + } + } + ] + } + } + } + } + }, + "/api/v1/admin/user-group": { + "get": { + "description": "列出用户分组", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "UserGroup" + ], + "summary": "列出用户分组", + "operationId": "list-user-group", + "parameters": [ + { + "type": "string", + "description": "下一页标识", + "name": "next_token", + "in": "query" + }, + { + "type": "integer", + "description": "分页", + "name": "page", + "in": "query" + }, + { + "type": "integer", + "description": "每页多少条记录", + "name": "size", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.ListUserGroupResp" + } + } + } + ] + } + } + } + }, + "put": { + "description": "更新用户分组", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "UserGroup" + ], + "summary": "更新用户分组", + "operationId": "update-user-group", + "parameters": [ + { + "description": "参数", + "name": "param", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.UpdateUserGroupReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.UserGroup" + } + } + } + ] + } + } + } + }, + "post": { + "description": "创建用户分组", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "UserGroup" + ], + "summary": "创建用户分组", + "operationId": "create-group", + "parameters": [ + { + "description": "参数", + "name": "param", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.CreateUserGroupReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.UserGroup" + } + } + } + ] + } + } + } + }, + "delete": { + "description": "删除用户分组", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "UserGroup" + ], + "summary": "删除用户分组", + "operationId": "delete-group", + "parameters": [ + { + "type": "string", + "description": "分组id", + "name": "id", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/web.Resp" + } + } + } + } + }, + "/api/v1/admin/user-group/admin": { + "delete": { + "description": "从分组中移除管理员", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "UserGroup" + ], + "summary": "从分组中移除管理员", + "operationId": "remove-admin-from-group", + "parameters": [ + { + "description": "参数", + "name": "param", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.GroupRemoveAdminReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/web.Resp" + } + } + } + } + }, + "/api/v1/admin/user-group/grant": { + "post": { + "description": "授权分组给管理员", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "UserGroup" + ], + "summary": "授权分组给管理员", + "operationId": "grant-group", + "parameters": [ + { + "description": "参数", + "name": "param", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.GrantGroupReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/web.Resp" + } + } + } + } + }, + "/api/v1/admin/user-group/user": { + "post": { + "description": "添加用户到分组", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "UserGroup" + ], + "summary": "添加用户到分组", + "operationId": "add-user-to-group", + "parameters": [ + { + "description": "参数", + "name": "param", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.GroupAddUserReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/web.Resp" + } + } + } + }, + "delete": { + "description": "从分组中移除用户", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "UserGroup" + ], + "summary": "从分组中移除用户", + "operationId": "remove-user-from-group", + "parameters": [ + { + "description": "参数", + "name": "param", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.GroupRemoveUserReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/web.Resp" + } + } + } + } + }, + "/api/v1/billing/chat/info": { + "get": { + "description": "获取对话内容", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Billing" + ], + "summary": "获取对话内容", + "operationId": "chat-info", + "parameters": [ + { + "type": "string", + "description": "对话记录ID", + "name": "id", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.ChatInfo" + } + } + } + ] + } + } + } + } + }, + "/api/v1/billing/chat/record": { + "get": { + "description": "获取对话记录", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Billing" + ], + "summary": "获取对话记录", + "operationId": "list-chat-record", + "parameters": [ + { + "type": "string", + "description": "作者", + "name": "author", + "in": "query" + }, + { + "type": "boolean", + "description": "是否接受筛选", + "name": "is_accept", + "in": "query" + }, + { + "type": "string", + "description": "语言", + "name": "language", + "in": "query" + }, + { + "type": "string", + "description": "下一页标识", + "name": "next_token", + "in": "query" + }, + { + "type": "integer", + "description": "分页", + "name": "page", + "in": "query" + }, + { + "type": "integer", + "description": "每页多少条记录", + "name": "size", + "in": "query" + }, + { + "type": "string", + "description": "工作模式", + "name": "work_mode", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.ListChatRecordResp" + } + } + } + ] + } + } + } + } + }, + "/api/v1/billing/completion/info": { + "get": { + "description": "获取补全内容", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Billing" + ], + "summary": "获取补全内容", + "operationId": "completion-info", + "parameters": [ + { + "type": "string", + "description": "补全记录ID", + "name": "id", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.CompletionInfo" + } + } + } + ] + } + } + } + } + }, + "/api/v1/billing/completion/record": { + "get": { + "description": "获取补全记录", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Billing" + ], + "summary": "获取补全记录", + "operationId": "list-completion-record", + "parameters": [ + { + "type": "string", + "description": "作者", + "name": "author", + "in": "query" + }, + { + "type": "boolean", + "description": "是否接受筛选", + "name": "is_accept", + "in": "query" + }, + { + "type": "string", + "description": "语言", + "name": "language", + "in": "query" + }, + { + "type": "string", + "description": "下一页标识", + "name": "next_token", + "in": "query" + }, + { + "type": "integer", + "description": "分页", + "name": "page", + "in": "query" + }, + { + "type": "integer", + "description": "每页多少条记录", + "name": "size", + "in": "query" + }, + { + "type": "string", + "description": "工作模式", + "name": "work_mode", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.ListCompletionRecordResp" + } + } + } + ] + } + } + } + } + }, + "/api/v1/cli/{command}": { + "post": { + "description": "运行monkeycode-cli命令", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "CLI" + ], + "summary": "运行monkeycode-cli命令", + "parameters": [ + { + "type": "string", + "description": "命令", + "name": "command", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "标志", + "name": "flag", + "in": "query" + }, + { + "description": "代码文件信息", + "name": "fileMetas", + "in": "body", + "required": true, + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.FileMeta" + } + } + } + ], + "responses": { + "200": { + "description": "输出结果", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.IndexResult" + } + } + }, + "500": { + "description": "内部错误", + "schema": { + "$ref": "#/definitions/web.Resp" + } + } + } + } + }, + "/api/v1/dashboard/category-stat": { + "get": { + "description": "获取分类统计信息", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Dashboard" + ], + "summary": "获取分类统计信息", + "operationId": "category-stat-dashboard", + "parameters": [ + { + "maximum": 90, + "minimum": 24, + "type": "integer", + "default": 90, + "description": "持续时间 (小时或天数)`", + "name": "duration", + "in": "query" + }, + { + "enum": [ + "hour", + "day" + ], + "type": "string", + "default": "day", + "description": "精度: \"hour\", \"day\"", + "name": "precision", + "in": "query", + "required": true + }, + { + "type": "string", + "description": "用户ID,可选参数", + "name": "user_id", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.CategoryStat" + } + } + } + ] + } + } + } + } + }, + "/api/v1/dashboard/statistics": { + "get": { + "description": "获取统计信息", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Dashboard" + ], + "summary": "获取统计信息", + "operationId": "statistics-dashboard", + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.Statistics" + } + } + } + ] + } + } + } + } + }, + "/api/v1/dashboard/time-stat": { + "get": { + "description": "获取时间统计信息", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Dashboard" + ], + "summary": "获取时间统计信息", + "operationId": "time-stat-dashboard", + "parameters": [ + { + "maximum": 90, + "minimum": 24, + "type": "integer", + "default": 90, + "description": "持续时间 (小时或天数)`", + "name": "duration", + "in": "query" + }, + { + "enum": [ + "hour", + "day" + ], + "type": "string", + "default": "day", + "description": "精度: \"hour\", \"day\"", + "name": "precision", + "in": "query", + "required": true + }, + { + "type": "string", + "description": "用户ID,可选参数", + "name": "user_id", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.TimeStat" + } + } + } + ] + } + } + } + } + }, + "/api/v1/dashboard/user-code-rank": { + "get": { + "description": "用户贡献榜", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Dashboard" + ], + "summary": "用户贡献榜", + "operationId": "user-code-rank-dashboard", + "parameters": [ + { + "maximum": 90, + "minimum": 24, + "type": "integer", + "default": 90, + "description": "持续时间 (小时或天数)`", + "name": "duration", + "in": "query" + }, + { + "enum": [ + "hour", + "day" + ], + "type": "string", + "default": "day", + "description": "精度: \"hour\", \"day\"", + "name": "precision", + "in": "query", + "required": true + }, + { + "type": "string", + "description": "用户ID,可选参数", + "name": "user_id", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.UserCodeRank" + } + } + } + } + ] + } + } + } + } + }, + "/api/v1/dashboard/user-events": { + "get": { + "description": "获取用户事件", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Dashboard" + ], + "summary": "获取用户事件", + "operationId": "user-events-dashboard", + "parameters": [ + { + "maximum": 90, + "minimum": 24, + "type": "integer", + "default": 90, + "description": "持续时间 (小时或天数)`", + "name": "duration", + "in": "query" + }, + { + "enum": [ + "hour", + "day" + ], + "type": "string", + "default": "day", + "description": "精度: \"hour\", \"day\"", + "name": "precision", + "in": "query", + "required": true + }, + { + "type": "string", + "description": "用户ID,可选参数", + "name": "user_id", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.UserEvent" + } + } + } + } + ] + } + } + } + } + }, + "/api/v1/dashboard/user-heatmap": { + "get": { + "description": "用户热力图", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Dashboard" + ], + "summary": "用户热力图", + "operationId": "user-heatmap-dashboard", + "parameters": [ + { + "type": "string", + "description": "用户ID", + "name": "user_id", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.UserHeatmapResp" + } + } + } + ] + } + } + } + } + }, + "/api/v1/dashboard/user-stat": { + "get": { + "description": "获取用户统计信息", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Dashboard" + ], + "summary": "获取用户统计信息", + "operationId": "user-stat-dashboard", + "parameters": [ + { + "maximum": 90, + "minimum": 24, + "type": "integer", + "default": 90, + "description": "持续时间 (小时或天数)`", + "name": "duration", + "in": "query" + }, + { + "enum": [ + "hour", + "day" + ], + "type": "string", + "default": "day", + "description": "精度: \"hour\", \"day\"", + "name": "precision", + "in": "query", + "required": true + }, + { + "type": "string", + "description": "用户ID,可选参数", + "name": "user_id", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.UserStat" + } + } + } + ] + } + } + } + } + }, + "/api/v1/ide/codesnippet/context": { + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "为IDE端提供代码片段上下文检索功能,使用API Key认证。支持单个查询和批量查询。", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "CodeSnippet" + ], + "summary": "IDE端上下文检索", + "operationId": "get-context", + "parameters": [ + { + "description": "检索请求参数", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/v1.GetContextReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.CodeSnippet" + } + } + } + } + ] + } + } + } + } + }, + "/api/v1/ide/codesnippet/semantic": { + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "为IDE端提供代码片段语义搜索功能,使用API Key认证。通过向量相似性搜索找到相关的代码片段。", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "CodeSnippet" + ], + "summary": "IDE端语义搜索", + "operationId": "get-semantic-context", + "parameters": [ + { + "description": "语义搜索请求参数", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/v1.GetSemanticContextReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.CodeSnippet" + } + } + } + } + ] + } + } + } + } + }, + "/api/v1/license": { + "get": { + "description": "Get license", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "license" + ], + "summary": "Get license", + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.LicenseResp" + } + } + } + ] + } + } + } + }, + "post": { + "description": "Upload license", + "consumes": [ + "multipart/form-data" + ], + "produces": [ + "application/json" + ], + "tags": [ + "license" + ], + "summary": "Upload license", + "parameters": [ + { + "enum": [ + "file", + "code" + ], + "type": "string", + "description": "license type", + "name": "license_type", + "in": "formData", + "required": true + }, + { + "type": "file", + "description": "license file", + "name": "license_file", + "in": "formData", + "required": true + }, + { + "type": "string", + "description": "license code", + "name": "license_code", + "in": "formData", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.LicenseResp" + } + } + } + ] + } + } + } + } + }, + "/api/v1/model": { + "get": { + "description": "获取模型列表", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Model" + ], + "summary": "获取模型列表", + "operationId": "list-model", + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.AllModelResp" + } + } + } + ] + } + } + } + }, + "put": { + "description": "更新模型", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Model" + ], + "summary": "更新模型", + "operationId": "update-model", + "parameters": [ + { + "description": "模型", + "name": "model", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.UpdateModelReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.Model" + } + } + } + ] + } + } + } + }, + "post": { + "description": "创建模型", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Model" + ], + "summary": "创建模型", + "operationId": "create-model", + "parameters": [ + { + "description": "模型", + "name": "model", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.CreateModelReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.Model" + } + } + } + ] + } + } + } + }, + "delete": { + "description": "删除模型", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Model" + ], + "summary": "删除模型", + "operationId": "delete-model", + "parameters": [ + { + "type": "string", + "description": "模型ID", + "name": "id", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/web.Resp" + } + } + } + } + }, + "/api/v1/model/check": { + "post": { + "description": "检查模型", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Model" + ], + "summary": "检查模型", + "operationId": "check-model", + "parameters": [ + { + "description": "模型", + "name": "model", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.CheckModelReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.Model" + } + } + } + ] + } + } + } + } + }, + "/api/v1/model/my": { + "get": { + "description": "获取我的模型列表", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Model" + ], + "summary": "获取我的模型列表", + "operationId": "my-model-list", + "parameters": [ + { + "enum": [ + "llm", + "coder", + "embedding", + "audio", + "reranker" + ], + "type": "string", + "x-enum-varnames": [ + "ModelTypeLLM", + "ModelTypeCoder", + "ModelTypeEmbedding", + "ModelTypeAudio", + "ModelTypeReranker" + ], + "description": "模型类型 llm:对话模型 coder:代码模型", + "name": "model_type", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.Model" + } + } + } + } + ] + } + } + } + } + }, + "/api/v1/model/provider/supported": { + "get": { + "description": "获取供应商支持的模型列表", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Model" + ], + "summary": "获取供应商支持的模型列表", + "operationId": "get-provider-model-list", + "parameters": [ + { + "type": "string", + "name": "api_header", + "in": "query" + }, + { + "type": "string", + "name": "api_key", + "in": "query" + }, + { + "type": "string", + "name": "base_url", + "in": "query", + "required": true + }, + { + "enum": [ + "SiliconFlow", + "OpenAI", + "Ollama", + "DeepSeek", + "Moonshot", + "AzureOpenAI", + "BaiZhiCloud", + "Hunyuan", + "BaiLian", + "Volcengine" + ], + "type": "string", + "x-enum-varnames": [ + "ModelProviderSiliconFlow", + "ModelProviderOpenAI", + "ModelProviderOllama", + "ModelProviderDeepSeek", + "ModelProviderMoonshot", + "ModelProviderAzureOpenAI", + "ModelProviderBaiZhiCloud", + "ModelProviderHunyuan", + "ModelProviderBaiLian", + "ModelProviderVolcengine" + ], + "name": "provider", + "in": "query", + "required": true + }, + { + "enum": [ + "llm", + "coder", + "embedding", + "audio", + "reranker" + ], + "type": "string", + "x-enum-varnames": [ + "ModelTypeLLM", + "ModelTypeCoder", + "ModelTypeEmbedding", + "ModelTypeAudio", + "ModelTypeReranker" + ], + "name": "type", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.GetProviderModelListResp" + } + } + } + ] + } + } + } + } + }, + "/api/v1/model/token-usage": { + "get": { + "description": "获取模型token使用情况", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Model" + ], + "summary": "获取模型token使用情况", + "operationId": "get-token-usage", + "parameters": [ + { + "enum": [ + "llm", + "coder", + "embedding", + "audio", + "reranker" + ], + "type": "string", + "x-enum-varnames": [ + "ModelTypeLLM", + "ModelTypeCoder", + "ModelTypeEmbedding", + "ModelTypeAudio", + "ModelTypeReranker" + ], + "description": "模型类型 llm:对话模型 coder:代码模型", + "name": "model_type", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.ModelTokenUsageResp" + } + } + } + ] + } + } + } + } + }, + "/api/v1/security/scanning": { + "get": { + "description": "获取扫描结果", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Security Scanning" + ], + "summary": "获取扫描结果", + "operationId": "security-scanning-list", + "parameters": [ + { + "type": "string", + "description": "作者", + "name": "author", + "in": "query" + }, + { + "type": "string", + "description": "下一页标识", + "name": "next_token", + "in": "query" + }, + { + "type": "integer", + "description": "分页", + "name": "page", + "in": "query" + }, + { + "type": "string", + "description": "项目名称", + "name": "project_name", + "in": "query" + }, + { + "type": "integer", + "description": "每页多少条记录", + "name": "size", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.ListSecurityScanningResp" + } + } + } + ] + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "type": "string" + } + } + } + } + }, + "/api/v1/security/scanning/detail": { + "get": { + "description": "获取扫描风险详情", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Security Scanning" + ], + "summary": "获取扫描风险详情", + "operationId": "security-scanning-detail", + "parameters": [ + { + "type": "string", + "description": "扫描任务id", + "name": "id", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.SecurityScanningRiskDetail" + } + } + } + } + ] + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "type": "string" + } + } + } + } + }, + "/api/v1/static/vsix": { + "get": { + "description": "下载VSCode插件", + "consumes": [ + "application/json" + ], + "produces": [ + "application/octet-stream" + ], + "tags": [ + "User" + ], + "summary": "下载VSCode插件", + "operationId": "vsix-download", + "responses": {} + } + }, + "/api/v1/user/chat/info": { + "get": { + "description": "获取对话内容", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User Record" + ], + "summary": "获取对话内容", + "operationId": "user-chat-info", + "parameters": [ + { + "type": "string", + "description": "对话记录ID", + "name": "id", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.ChatInfo" + } + } + } + ] + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "type": "string" + } + } + } + } + }, + "/api/v1/user/chat/record": { + "get": { + "description": "获取用户对话记录", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User Record" + ], + "summary": "获取用户对话记录", + "operationId": "user-list-chat-record", + "parameters": [ + { + "type": "string", + "description": "作者", + "name": "author", + "in": "query" + }, + { + "type": "boolean", + "description": "是否接受筛选", + "name": "is_accept", + "in": "query" + }, + { + "type": "string", + "description": "语言", + "name": "language", + "in": "query" + }, + { + "type": "string", + "description": "下一页标识", + "name": "next_token", + "in": "query" + }, + { + "type": "integer", + "description": "分页", + "name": "page", + "in": "query" + }, + { + "type": "integer", + "description": "每页多少条记录", + "name": "size", + "in": "query" + }, + { + "type": "string", + "description": "工作模式", + "name": "work_mode", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.ListChatRecordResp" + } + } + } + ] + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "type": "string" + } + } + } + } + }, + "/api/v1/user/completion/info": { + "get": { + "description": "获取补全内容", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User Record" + ], + "summary": "获取补全内容", + "operationId": "user-completion-info", + "parameters": [ + { + "type": "string", + "description": "补全记录ID", + "name": "id", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.CompletionInfo" + } + } + } + ] + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "type": "string" + } + } + } + } + }, + "/api/v1/user/completion/record": { + "get": { + "description": "获取补全记录", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User Record" + ], + "summary": "获取补全记录", + "operationId": "user-list-completion-record", + "parameters": [ + { + "type": "string", + "description": "作者", + "name": "author", + "in": "query" + }, + { + "type": "boolean", + "description": "是否接受筛选", + "name": "is_accept", + "in": "query" + }, + { + "type": "string", + "description": "语言", + "name": "language", + "in": "query" + }, + { + "type": "string", + "description": "下一页标识", + "name": "next_token", + "in": "query" + }, + { + "type": "integer", + "description": "分页", + "name": "page", + "in": "query" + }, + { + "type": "integer", + "description": "每页多少条记录", + "name": "size", + "in": "query" + }, + { + "type": "string", + "description": "工作模式", + "name": "work_mode", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.ListCompletionRecordResp" + } + } + } + ] + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "type": "string" + } + } + } + } + }, + "/api/v1/user/dashboard/events": { + "get": { + "description": "获取用户事件", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User Dashboard" + ], + "summary": "获取用户事件", + "operationId": "user-dashboard-events", + "parameters": [ + { + "maximum": 90, + "minimum": 24, + "type": "integer", + "default": 90, + "description": "持续时间 (小时或天数)`", + "name": "duration", + "in": "query" + }, + { + "enum": [ + "hour", + "day" + ], + "type": "string", + "default": "day", + "description": "精度: \"hour\", \"day\"", + "name": "precision", + "in": "query", + "required": true + }, + { + "type": "string", + "description": "用户ID,可选参数", + "name": "user_id", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.UserEvent" + } + } + } + } + ] + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "type": "string" + } + } + } + } + }, + "/api/v1/user/dashboard/heatmap": { + "get": { + "description": "用户热力图", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User Dashboard" + ], + "summary": "用户热力图", + "operationId": "user-dashboard-heatmap", + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.UserHeatmapResp" + } + } + } + ] + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "type": "string" + } + } + } + } + }, + "/api/v1/user/dashboard/stat": { + "get": { + "description": "获取用户统计信息", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User Dashboard" + ], + "summary": "获取用户统计信息", + "operationId": "user-dashboard-stat", + "parameters": [ + { + "maximum": 90, + "minimum": 24, + "type": "integer", + "default": 90, + "description": "持续时间 (小时或天数)`", + "name": "duration", + "in": "query" + }, + { + "enum": [ + "hour", + "day" + ], + "type": "string", + "default": "day", + "description": "精度: \"hour\", \"day\"", + "name": "precision", + "in": "query", + "required": true + }, + { + "type": "string", + "description": "用户ID,可选参数", + "name": "user_id", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.UserStat" + } + } + } + ] + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "type": "string" + } + } + } + } + }, + "/api/v1/user/delete": { + "delete": { + "description": "删除用户", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User" + ], + "summary": "删除用户", + "operationId": "delete-user", + "parameters": [ + { + "type": "string", + "description": "用户ID", + "name": "id", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "type": "object" + } + } + } + ] + } + } + } + } + }, + "/api/v1/user/invite": { + "get": { + "description": "获取用户邀请码", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User" + ], + "summary": "获取用户邀请码", + "operationId": "invite", + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.InviteResp" + } + } + } + ] + } + } + } + } + }, + "/api/v1/user/list": { + "get": { + "description": "获取用户列表", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User" + ], + "summary": "获取用户列表", + "operationId": "list-user", + "parameters": [ + { + "type": "string", + "description": "下一页标识", + "name": "next_token", + "in": "query" + }, + { + "type": "integer", + "description": "分页", + "name": "page", + "in": "query" + }, + { + "type": "integer", + "description": "每页多少条记录", + "name": "size", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.ListUserResp" + } + } + } + ] + } + } + } + } + }, + "/api/v1/user/login": { + "post": { + "description": "用户登录", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User" + ], + "summary": "用户登录", + "operationId": "login", + "parameters": [ + { + "description": "登录参数", + "name": "param", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.LoginReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.LoginResp" + } + } + } + ] + } + } + } + } + }, + "/api/v1/user/login-history": { + "get": { + "description": "获取用户登录历史", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User" + ], + "summary": "获取用户登录历史", + "operationId": "login-history", + "parameters": [ + { + "type": "string", + "description": "下一页标识", + "name": "next_token", + "in": "query" + }, + { + "type": "integer", + "description": "分页", + "name": "page", + "in": "query" + }, + { + "type": "integer", + "description": "每页多少条记录", + "name": "size", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.ListLoginHistoryResp" + } + } + } + ] + } + } + } + } + }, + "/api/v1/user/logout": { + "post": { + "description": "用户登出", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User" + ], + "summary": "用户登出", + "operationId": "logout", + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/web.Resp" + } + } + } + } + }, + "/api/v1/user/oauth/callback": { + "get": { + "description": "用户 OAuth 回调", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User" + ], + "summary": "用户 OAuth 回调", + "operationId": "user-oauth-callback", + "parameters": [ + { + "type": "string", + "name": "code", + "in": "query", + "required": true + }, + { + "type": "string", + "name": "state", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "type": "string" + } + } + } + ] + } + } + } + } + }, + "/api/v1/user/oauth/signup-or-in": { + "get": { + "description": "用户 OAuth 登录或注册", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User" + ], + "summary": "用户 OAuth 登录或注册", + "operationId": "user-oauth-signup-or-in", + "parameters": [ + { + "type": "string", + "description": "邀请码", + "name": "inviate_code", + "in": "query" + }, + { + "enum": [ + "email", + "dingtalk", + "custom" + ], + "type": "string", + "x-enum-varnames": [ + "UserPlatformEmail", + "UserPlatformDingTalk", + "UserPlatformCustom" + ], + "description": "第三方平台 dingtalk", + "name": "platform", + "in": "query", + "required": true + }, + { + "type": "string", + "description": "登录成功后跳转的 URL", + "name": "redirect_url", + "in": "query" + }, + { + "type": "string", + "description": "会话ID", + "name": "session_id", + "in": "query" + }, + { + "enum": [ + "plugin", + "browser" + ], + "type": "string", + "default": "plugin", + "x-enum-varnames": [ + "LoginSourcePlugin", + "LoginSourceBrowser" + ], + "description": "登录来源 plugin: 插件 browser: 浏览器; 默认为 plugin", + "name": "source", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.OAuthURLResp" + } + } + } + ] + } + } + } + } + }, + "/api/v1/user/profile": { + "get": { + "description": "获取用户信息", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User Manage" + ], + "summary": "获取用户信息", + "operationId": "user-profile", + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.User" + } + } + } + ] + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/web.Resp" + } + } + } + }, + "put": { + "description": "更新用户信息", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User Manage" + ], + "summary": "更新用户信息", + "operationId": "user-update-profile", + "parameters": [ + { + "description": "param", + "name": "req", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.ProfileUpdateReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.User" + } + } + } + ] + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/web.Resp" + } + } + } + } + }, + "/api/v1/user/register": { + "post": { + "description": "注册用户", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User" + ], + "summary": "注册用户", + "operationId": "register", + "parameters": [ + { + "description": "注册参数", + "name": "param", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.RegisterReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.User" + } + } + } + ] + } + } + } + } + }, + "/api/v1/user/security/scanning": { + "get": { + "description": "获取用户扫描结果", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User Security Scanning" + ], + "summary": "获取用户扫描结果", + "operationId": "user-security-scanning-list", + "parameters": [ + { + "type": "string", + "description": "作者", + "name": "author", + "in": "query" + }, + { + "type": "string", + "description": "下一页标识", + "name": "next_token", + "in": "query" + }, + { + "type": "integer", + "description": "分页", + "name": "page", + "in": "query" + }, + { + "type": "string", + "description": "项目名称", + "name": "project_name", + "in": "query" + }, + { + "type": "integer", + "description": "每页多少条记录", + "name": "size", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.ListSecurityScanningResp" + } + } + } + ] + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "type": "string" + } + } + } + } + }, + "/api/v1/user/security/scanning/detail": { + "get": { + "description": "获取用户扫描风险详情", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User Security Scanning" + ], + "summary": "获取用户扫描风险详情", + "operationId": "user-security-scanning-detail", + "parameters": [ + { + "type": "string", + "description": "扫描任务id", + "name": "id", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.SecurityScanningRiskDetail" + } + } + } + } + ] + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "type": "string" + } + } + } + } + }, + "/api/v1/user/update": { + "put": { + "description": "更新用户", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User" + ], + "summary": "更新用户", + "operationId": "update-user", + "parameters": [ + { + "description": "更新用户参数", + "name": "param", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.UpdateUserReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.User" + } + } + } + ] + } + } + } + } + }, + "/api/v1/workspace/files": { + "get": { + "description": "分页获取工作区文件列表", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "WorkspaceFile" + ], + "summary": "获取工作区文件列表", + "operationId": "list-workspace-files", + "parameters": [ + { + "type": "string", + "description": "编程语言筛选", + "name": "language", + "in": "query" + }, + { + "type": "string", + "description": "下一页标识", + "name": "next_token", + "in": "query" + }, + { + "type": "integer", + "description": "分页", + "name": "page", + "in": "query" + }, + { + "type": "string", + "description": "搜索关键词(文件路径)", + "name": "search", + "in": "query" + }, + { + "type": "integer", + "description": "每页多少条记录", + "name": "size", + "in": "query" + }, + { + "type": "string", + "description": "用户ID", + "name": "user_id", + "in": "query" + }, + { + "type": "string", + "description": "工作区ID", + "name": "workspace_id", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.ListWorkspaceFileResp" + } + } + } + ] + } + } + } + }, + "post": { + "description": "创建一个新的工作区文件", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "WorkspaceFile" + ], + "summary": "创建工作区文件", + "operationId": "create-workspace-file", + "parameters": [ + { + "description": "文件信息", + "name": "file", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.CreateWorkspaceFileReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.WorkspaceFile" + } + } + } + ] + } + } + } + } + }, + "/api/v1/workspace/files/batch": { + "put": { + "description": "批量更新多个工作区文件", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "WorkspaceFile" + ], + "summary": "批量更新工作区文件", + "operationId": "batch-update-workspace-files", + "parameters": [ + { + "description": "文件列表", + "name": "files", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.BatchUpdateWorkspaceFileReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.WorkspaceFile" + } + } + } + } + ] + } + } + } + }, + "post": { + "description": "批量创建多个工作区文件", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "WorkspaceFile" + ], + "summary": "批量创建工作区文件", + "operationId": "batch-create-workspace-files", + "parameters": [ + { + "description": "文件列表", + "name": "files", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.BatchCreateWorkspaceFileReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.WorkspaceFile" + } + } + } + } + ] + } + } + } + } + }, + "/api/v1/workspace/files/by-path": { + "get": { + "description": "根据用户ID、项目ID和文件路径获取工作区文件", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "WorkspaceFile" + ], + "summary": "根据路径获取工作区文件", + "operationId": "get-workspace-file-by-path", + "parameters": [ + { + "type": "string", + "description": "用户ID", + "name": "user_id", + "in": "query" + }, + { + "type": "string", + "description": "项目ID", + "name": "project_id", + "in": "query", + "required": true + }, + { + "type": "string", + "description": "文件路径", + "name": "path", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.WorkspaceFile" + } + } + } + ] + } + } + } + } + }, + "/api/v1/workspace/files/get-and-save": { + "post": { + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "WorkspaceFile" + ], + "summary": "获取并保存工作区文件", + "parameters": [ + { + "description": "请求参数", + "name": "req", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.GetAndSaveReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/web.Resp" + } + } + } + } + }, + "/api/v1/workspace/files/sync": { + "post": { + "description": "同步本地文件到工作区,智能检测新增、修改和删除", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "WorkspaceFile" + ], + "summary": "同步工作区文件", + "operationId": "sync-workspace-files", + "parameters": [ + { + "description": "同步信息", + "name": "sync", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.SyncWorkspaceFileReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.SyncWorkspaceFileResp" + } + } + } + ] + } + } + } + } + }, + "/api/v1/workspace/files/{id}": { + "get": { + "description": "根据文件ID获取工作区文件详情", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "WorkspaceFile" + ], + "summary": "根据ID获取工作区文件", + "operationId": "get-workspace-file-by-id", + "parameters": [ + { + "type": "string", + "description": "文件ID", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.WorkspaceFile" + } + } + } + ] + } + } + } + }, + "put": { + "description": "更新指定的工作区文件", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "WorkspaceFile" + ], + "summary": "更新工作区文件", + "operationId": "update-workspace-file", + "parameters": [ + { + "type": "string", + "description": "文件ID", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "更新信息", + "name": "file", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.UpdateWorkspaceFileReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.WorkspaceFile" + } + } + } + ] + } + } + } + }, + "delete": { + "description": "删除指定的工作区文件", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "WorkspaceFile" + ], + "summary": "删除工作区文件", + "operationId": "delete-workspace-file", + "parameters": [ + { + "type": "string", + "description": "文件ID", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/web.Resp" + } + } + } + } + }, + "/v1/chat/completions": { + "post": { + "description": "处理聊天补全请求", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "OpenAIV1" + ], + "summary": "处理聊天补全请求", + "operationId": "chat-completion", + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/web.Resp" + } + } + } + } + }, + "/v1/completion/accept": { + "post": { + "description": "接受补全请求", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "OpenAIV1" + ], + "summary": "接受补全请求", + "operationId": "accept-completion", + "parameters": [ + { + "description": "补全请求", + "name": "param", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.AcceptCompletionReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/web.Resp" + } + } + } + } + }, + "/v1/completions": { + "post": { + "description": "处理文本补全请求", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "OpenAIV1" + ], + "summary": "处理文本补全请求", + "operationId": "completions", + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/web.Resp" + } + } + } + } + }, + "/v1/embeddings": { + "post": { + "description": "处理嵌入请求", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "OpenAIV1" + ], + "summary": "处理嵌入请求", + "operationId": "embeddings", + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/web.Resp" + } + } + } + } + }, + "/v1/health": { + "get": { + "description": "固定回包 `{\"code\": 0, \"data\": \"MonkeyCode\"}`", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "OpenAIV1" + ], + "summary": "健康检查", + "operationId": "health", + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/web.Resp" + } + } + } + } + }, + "/v1/models": { + "get": { + "description": "模型列表", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "OpenAIV1" + ], + "summary": "模型列表", + "operationId": "model-list", + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.ModelListResp" + } + } + } + ] + } + } + } + } + }, + "/v1/report": { + "post": { + "description": "报告,支持多种操作:accept(接受补全)、suggest(建议)、reject(拒绝补全并记录用户输入)、file_written(文件写入)", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "OpenAIV1" + ], + "summary": "报告", + "operationId": "report", + "parameters": [ + { + "description": "报告请求", + "name": "param", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.ReportReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/web.Resp" + } + } + } + } + }, + "/v1/security/scanning": { + "get": { + "description": "扫描任务列表", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "OpenAIV1" + ], + "summary": "扫描任务列表", + "operationId": "list-security-scanning", + "parameters": [ + { + "description": "扫描任务列表请求", + "name": "param", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.ListSecurityScanningReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.ListSecurityScanningBriefResp" + } + } + } + ] + } + } + } + }, + "post": { + "description": "创建扫描任务", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "OpenAIV1" + ], + "summary": "创建扫描任务", + "operationId": "create-security-scanning", + "parameters": [ + { + "description": "创建扫描任务请求", + "name": "param", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.CreateSecurityScanningReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/web.Resp" + } + } + } + } + }, + "/v1/security/scanning/detail": { + "get": { + "description": "分页只支持 next_token; 首页传空,后续判断has_next_page是否为true,传入回包给的next_token", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "OpenAIV1" + ], + "summary": "获取扫描任务风险详情列表", + "operationId": "list-security-scanning-detail", + "parameters": [ + { + "type": "string", + "description": "扫描任务id", + "name": "id", + "in": "query" + }, + { + "type": "string", + "description": "下一页标识", + "name": "next_token", + "in": "query" + }, + { + "type": "integer", + "description": "分页", + "name": "page", + "in": "query" + }, + { + "type": "integer", + "description": "每页多少条记录", + "name": "size", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.ListSecurityScanningDetailResp" + } + } + } + ] + } + } + } + } + } + }, + "definitions": { + "consts.AdminStatus": { + "type": "string", + "enum": [ + "active", + "inactive" + ], + "x-enum-varnames": [ + "AdminStatusActive", + "AdminStatusInactive" + ] + }, + "consts.ChatRole": { + "type": "string", + "enum": [ + "user", + "assistant", + "system" + ], + "x-enum-varnames": [ + "ChatRoleUser", + "ChatRoleAssistant", + "ChatRoleSystem" + ] + }, + "consts.LoginSource": { + "type": "string", + "enum": [ + "plugin", + "browser" + ], + "x-enum-varnames": [ + "LoginSourcePlugin", + "LoginSourceBrowser" + ] + }, + "consts.ModelProvider": { + "type": "string", + "enum": [ + "SiliconFlow", + "OpenAI", + "Ollama", + "DeepSeek", + "Moonshot", + "AzureOpenAI", + "BaiZhiCloud", + "Hunyuan", + "BaiLian", + "Volcengine" + ], + "x-enum-varnames": [ + "ModelProviderSiliconFlow", + "ModelProviderOpenAI", + "ModelProviderOllama", + "ModelProviderDeepSeek", + "ModelProviderMoonshot", + "ModelProviderAzureOpenAI", + "ModelProviderBaiZhiCloud", + "ModelProviderHunyuan", + "ModelProviderBaiLian", + "ModelProviderVolcengine" + ] + }, + "consts.ModelStatus": { + "type": "string", + "enum": [ + "active", + "inactive" + ], + "x-enum-varnames": [ + "ModelStatusActive", + "ModelStatusInactive" + ] + }, + "consts.ModelType": { + "type": "string", + "enum": [ + "llm", + "coder", + "embedding", + "audio", + "reranker" + ], + "x-enum-varnames": [ + "ModelTypeLLM", + "ModelTypeCoder", + "ModelTypeEmbedding", + "ModelTypeAudio", + "ModelTypeReranker" + ] + }, + "consts.ReportAction": { + "type": "string", + "enum": [ + "accept", + "suggest", + "file_written", + "reject", + "new_task", + "feedback_task", + "abort_task" + ], + "x-enum-varnames": [ + "ReportActionAccept", + "ReportActionSuggest", + "ReportActionFileWritten", + "ReportActionReject", + "ReportActionNewTask", + "ReportActionFeedbackTask", + "ReportActionAbortTask" + ] + }, + "consts.SecurityScanningLanguage": { + "type": "string", + "enum": [ + "C/C++", + "Java", + "Python", + "JavaScript", + "Go", + "PHP", + "C#", + "Swift", + "Ruby", + "Rust", + "HTML", + "Objective-C/C++", + "OCaml", + "Kotlin", + "Scala", + "Solidity", + "COBOL", + "Shell", + "SQL", + "Fortran", + "Dart", + "Groovy", + "Lua", + "Secrets", + "IaC" + ], + "x-enum-varnames": [ + "SecurityScanningLanguageCpp", + "SecurityScanningLanguageJava", + "SecurityScanningLanguagePython", + "SecurityScanningLanguageJavaScript", + "SecurityScanningLanguageGo", + "SecurityScanningLanguagePHP", + "SecurityScanningLanguageCS", + "SecurityScanningLanguageSwift", + "SecurityScanningLanguageRuby", + "SecurityScanningLanguageRust", + "SecurityScanningLanguageHTML", + "SecurityScanningLanguageObjectiveC", + "SecurityScanningLanguageOCaml", + "SecurityScanningLanguageKotlin", + "SecurityScanningLanguageScala", + "SecurityScanningLanguageSolidity", + "SecurityScanningLanguageCOBOL", + "SecurityScanningLanguageShell", + "SecurityScanningLanguageSQL", + "SecurityScanningLanguageFortran", + "SecurityScanningLanguageDart", + "SecurityScanningLanguageGroovy", + "SecurityScanningLanguageLua", + "SecurityScanningLanguageSecrets", + "SecurityScanningLanguageIaC" + ] + }, + "consts.SecurityScanningRiskLevel": { + "type": "string", + "enum": [ + "severe", + "critical", + "suggest" + ], + "x-enum-comments": { + "SecurityScanningRiskLevelCritical": "高危", + "SecurityScanningRiskLevelSevere": "严重", + "SecurityScanningRiskLevelSuggest": "建议" + }, + "x-enum-varnames": [ + "SecurityScanningRiskLevelSevere", + "SecurityScanningRiskLevelCritical", + "SecurityScanningRiskLevelSuggest" + ] + }, + "consts.SecurityScanningStatus": { + "type": "string", + "enum": [ + "pending", + "running", + "success", + "failed" + ], + "x-enum-varnames": [ + "SecurityScanningStatusPending", + "SecurityScanningStatusRunning", + "SecurityScanningStatusSuccess", + "SecurityScanningStatusFailed" + ] + }, + "consts.UserPlatform": { + "type": "string", + "enum": [ + "email", + "dingtalk", + "custom" + ], + "x-enum-varnames": [ + "UserPlatformEmail", + "UserPlatformDingTalk", + "UserPlatformCustom" + ] + }, + "consts.UserStatus": { + "type": "string", + "enum": [ + "active", + "inactive", + "locked" + ], + "x-enum-varnames": [ + "UserStatusActive", + "UserStatusInactive", + "UserStatusLocked" + ] + }, + "domain.AcceptCompletionReq": { + "type": "object", + "properties": { + "completion": { + "description": "补全内容", + "type": "string" + }, + "id": { + "description": "记录ID", + "type": "string" + } + } + }, + "domain.AdminLoginHistory": { + "type": "object", + "properties": { + "client_version": { + "description": "客户端版本", + "type": "string" + }, + "created_at": { + "description": "登录时间", + "type": "integer" + }, + "device": { + "description": "设备信息", + "type": "string" + }, + "ip_info": { + "description": "IP信息", + "allOf": [ + { + "$ref": "#/definitions/domain.IPInfo" + } + ] + }, + "user": { + "description": "用户信息", + "allOf": [ + { + "$ref": "#/definitions/domain.AdminUser" + } + ] + } + } + }, + "domain.AdminUser": { + "type": "object", + "properties": { + "created_at": { + "description": "创建时间", + "type": "integer" + }, + "id": { + "description": "用户ID", + "type": "string" + }, + "last_active_at": { + "description": "最后活跃时间", + "type": "integer" + }, + "role": { + "description": "角色", + "allOf": [ + { + "$ref": "#/definitions/domain.Role" + } + ] + }, + "status": { + "description": "用户状态 active: 正常 inactive: 禁用", + "allOf": [ + { + "$ref": "#/definitions/consts.AdminStatus" + } + ] + }, + "username": { + "description": "用户名", + "type": "string" + } + } + }, + "domain.AllModelResp": { + "type": "object", + "properties": { + "providers": { + "description": "提供商列表", + "type": "array", + "items": { + "$ref": "#/definitions/domain.ProviderModel" + } + } + } + }, + "domain.BatchCreateWorkspaceFileReq": { + "type": "object", + "required": [ + "files", + "user_id", + "workspace_id" + ], + "properties": { + "files": { + "description": "文件列表", + "type": "array", + "items": { + "$ref": "#/definitions/domain.CreateWorkspaceFileReq" + } + }, + "user_id": { + "description": "用户ID", + "type": "string" + }, + "workspace_id": { + "description": "工作区ID", + "type": "string" + } + } + }, + "domain.BatchUpdateWorkspaceFileReq": { + "type": "object", + "required": [ + "files" + ], + "properties": { + "files": { + "description": "文件列表", + "type": "array", + "items": { + "$ref": "#/definitions/domain.UpdateWorkspaceFileReq" + } + } + } + }, + "domain.CategoryPoint": { + "type": "object", + "properties": { + "category": { + "description": "分类", + "type": "string" + }, + "value": { + "description": "值", + "type": "integer" + } + } + }, + "domain.CategoryStat": { + "type": "object", + "properties": { + "program_language": { + "description": "编程语言占比", + "type": "array", + "items": { + "$ref": "#/definitions/domain.CategoryPoint" + } + }, + "work_mode": { + "description": "工作模式占比", + "type": "array", + "items": { + "$ref": "#/definitions/domain.CategoryPoint" + } + } + } + }, + "domain.ChatContent": { + "type": "object", + "properties": { + "content": { + "description": "内容", + "type": "string" + }, + "created_at": { + "type": "integer" + }, + "role": { + "description": "角色,如user: 用户的提问 assistant: 机器人回复 system: 系统消息", + "allOf": [ + { + "$ref": "#/definitions/consts.ChatRole" + } + ] + } + } + }, + "domain.ChatInfo": { + "type": "object", + "properties": { + "contents": { + "description": "消息内容", + "type": "array", + "items": { + "$ref": "#/definitions/domain.ChatContent" + } + }, + "id": { + "type": "string" + } + } + }, + "domain.ChatRecord": { + "type": "object", + "properties": { + "created_at": { + "description": "创建时间", + "type": "integer" + }, + "id": { + "description": "记录ID", + "type": "string" + }, + "input_tokens": { + "description": "输入token", + "type": "integer" + }, + "model": { + "description": "模型", + "allOf": [ + { + "$ref": "#/definitions/domain.Model" + } + ] + }, + "output_tokens": { + "description": "输出token", + "type": "integer" + }, + "question": { + "description": "问题", + "type": "string" + }, + "user": { + "description": "用户", + "allOf": [ + { + "$ref": "#/definitions/domain.User" + } + ] + }, + "work_mode": { + "description": "工作模式", + "type": "string" + } + } + }, + "domain.CheckModelReq": { + "type": "object", + "required": [ + "api_base", + "model_name", + "provider", + "type" + ], + "properties": { + "api_base": { + "description": "接口地址", + "type": "string" + }, + "api_header": { + "type": "string" + }, + "api_key": { + "description": "接口密钥", + "type": "string" + }, + "api_version": { + "type": "string" + }, + "model_name": { + "description": "模型名称", + "type": "string" + }, + "provider": { + "description": "提供商", + "allOf": [ + { + "$ref": "#/definitions/consts.ModelProvider" + } + ] + }, + "type": { + "enum": [ + "llm", + "coder", + "embedding", + "rerank" + ], + "allOf": [ + { + "$ref": "#/definitions/consts.ModelType" + } + ] + } + } + }, + "domain.CodeLanguageType": { + "type": "string", + "enum": [ + "go", + "python", + "java", + "javascript", + "typescript", + "jsx", + "tsx", + "html", + "css", + "php", + "rust", + "swift", + "kotlin", + "c", + "cpp" + ], + "x-enum-varnames": [ + "CodeLanguageTypeGo", + "CodeLanguageTypePython", + "CodeLanguageTypeJava", + "CodeLanguageTypeJavaScript", + "CodeLanguageTypeTypeScript", + "CodeLanguageTypeJSX", + "CodeLanguageTypeTSX", + "CodeLanguageTypeHTML", + "CodeLanguageTypeCSS", + "CodeLanguageTypePHP", + "CodeLanguageTypeRust", + "CodeLanguageTypeSwift", + "CodeLanguageTypeKotlin", + "CodeLanguageTypeC", + "CodeLanguageTypeCpp" + ] + }, + "domain.CodeSnippet": { + "type": "object", + "properties": { + "definition": { + "description": "结构化信息", + "type": "object", + "additionalProperties": {} + }, + "definitionText": { + "description": "定义文本", + "type": "string" + }, + "dependencies": { + "description": "依赖项", + "type": "array", + "items": { + "type": "string" + } + }, + "embedding": { + "description": "向量嵌入", + "type": "array", + "items": { + "type": "number" + } + }, + "endColumn": { + "description": "结束列号", + "type": "integer" + }, + "endLine": { + "description": "结束行号", + "type": "integer" + }, + "field": { + "description": "容器名称", + "type": "string" + }, + "fileHash": { + "description": "内容哈希", + "type": "string" + }, + "filePath": { + "description": "文件路径", + "type": "string" + }, + "id": { + "description": "代码片段ID", + "type": "string" + }, + "language": { + "description": "编程语言", + "type": "string" + }, + "name": { + "description": "代码片段名称", + "type": "string" + }, + "namespace": { + "description": "命名空间", + "type": "string" + }, + "parameters": { + "description": "参数列表", + "type": "array", + "items": { + "type": "object", + "additionalProperties": {} + } + }, + "rangeText": { + "description": "代码片段内容", + "type": "string" + }, + "scope": { + "description": "作用域信息", + "type": "array", + "items": { + "type": "string" + } + }, + "signature": { + "description": "函数签名", + "type": "string" + }, + "startColumn": { + "description": "起始列号", + "type": "integer" + }, + "startLine": { + "description": "起始行号", + "type": "integer" + }, + "type": { + "description": "代码片段类型", + "type": "string" + }, + "workspace_file_id": { + "description": "关联的workspace file ID", + "type": "string" + } + } + }, + "domain.CompletionData": { + "type": "object", + "properties": { + "code_lines": { + "description": "代码行数", + "type": "integer" + }, + "completion": { + "description": "LLM生成的补全代码", + "type": "string" + }, + "created_at": { + "description": "创建时间戳", + "type": "integer" + }, + "cursor_position": { + "description": "光标位置 {\"line\": 10, \"column\": 5}", + "type": "object", + "additionalProperties": {} + }, + "input_tokens": { + "description": "输入token数", + "type": "integer" + }, + "is_accept": { + "description": "用户是否接受补全", + "type": "boolean" + }, + "is_suggested": { + "description": "是否为建议模式", + "type": "boolean" + }, + "model_id": { + "description": "模型ID", + "type": "string" + }, + "model_name": { + "description": "模型名称", + "type": "string" + }, + "model_type": { + "description": "模型类型", + "type": "string" + }, + "output_tokens": { + "description": "输出token数", + "type": "integer" + }, + "program_language": { + "description": "编程语言", + "type": "string" + }, + "prompt": { + "description": "用户输入的提示", + "type": "string" + }, + "request_id": { + "description": "请求ID", + "type": "string" + }, + "source_code": { + "description": "当前文件原文", + "type": "string" + }, + "task_id": { + "description": "任务ID", + "type": "string" + }, + "updated_at": { + "description": "更新时间戳", + "type": "integer" + }, + "user_id": { + "description": "用户ID", + "type": "string" + }, + "user_input": { + "description": "用户最终输入的内容", + "type": "string" + }, + "work_mode": { + "description": "工作模式", + "type": "string" + } + } + }, + "domain.CompletionInfo": { + "type": "object", + "properties": { + "content": { + "type": "string" + }, + "created_at": { + "type": "integer" + }, + "id": { + "type": "string" + }, + "prompt": { + "type": "string" + } + } + }, + "domain.CompletionRecord": { + "type": "object", + "properties": { + "created_at": { + "description": "创建时间", + "type": "integer" + }, + "id": { + "description": "记录ID", + "type": "string" + }, + "input_tokens": { + "description": "输入token", + "type": "integer" + }, + "is_accept": { + "description": "是否采纳", + "type": "boolean" + }, + "output_tokens": { + "description": "输出token", + "type": "integer" + }, + "program_language": { + "description": "编程语言", + "type": "string" + }, + "user": { + "description": "用户", + "allOf": [ + { + "$ref": "#/definitions/domain.User" + } + ] + } + } + }, + "domain.CreateAdminReq": { + "type": "object", + "required": [ + "password", + "role_id", + "username" + ], + "properties": { + "password": { + "description": "密码", + "type": "string" + }, + "role_id": { + "description": "角色ID", + "type": "integer" + }, + "username": { + "description": "用户名", + "type": "string" + } + } + }, + "domain.CreateModelReq": { + "type": "object", + "required": [ + "api_base", + "model_name", + "provider" + ], + "properties": { + "api_base": { + "description": "接口地址 如:https://api.qwen.com", + "type": "string" + }, + "api_header": { + "type": "string" + }, + "api_key": { + "description": "接口密钥 如:sk-xxxx", + "type": "string" + }, + "api_version": { + "type": "string" + }, + "model_name": { + "description": "模型名称 如: deepseek-v3", + "type": "string" + }, + "model_type": { + "description": "模型类型 llm:对话模型 coder:代码模型", + "allOf": [ + { + "$ref": "#/definitions/consts.ModelType" + } + ] + }, + "param": { + "description": "高级参数", + "allOf": [ + { + "$ref": "#/definitions/domain.ModelParam" + } + ] + }, + "provider": { + "description": "提供商", + "enum": [ + "SiliconFlow", + "OpenAI", + "Ollama", + "DeepSeek", + "Moonshot", + "AzureOpenAI", + "BaiZhiCloud", + "Hunyuan", + "BaiLian", + "Volcengine", + "Other" + ], + "allOf": [ + { + "$ref": "#/definitions/consts.ModelProvider" + } + ] + }, + "show_name": { + "description": "模型显示名称", + "type": "string" + } + } + }, + "domain.CreateSecurityScanningReq": { + "type": "object", + "properties": { + "language": { + "description": "扫描语言", + "allOf": [ + { + "$ref": "#/definitions/consts.SecurityScanningLanguage" + } + ] + }, + "user_id": { + "type": "string" + }, + "workspace": { + "description": "项目目录", + "type": "string" + } + } + }, + "domain.CreateUserGroupReq": { + "type": "object", + "required": [ + "name" + ], + "properties": { + "name": { + "description": "组名称", + "type": "string" + } + } + }, + "domain.CreateWorkspaceFileReq": { + "type": "object", + "required": [ + "hash", + "path", + "user_id", + "workspace_id" + ], + "properties": { + "content": { + "description": "文件内容", + "type": "string" + }, + "hash": { + "description": "文件哈希", + "type": "string" + }, + "language": { + "description": "编程语言", + "type": "string" + }, + "path": { + "description": "文件路径", + "type": "string" + }, + "size": { + "description": "文件大小", + "type": "integer" + }, + "user_id": { + "description": "用户ID", + "type": "string" + }, + "workspace_id": { + "description": "工作区ID", + "type": "string" + } + } + }, + "domain.CustomOAuth": { + "type": "object", + "properties": { + "access_token_url": { + "description": "自定义OAuth访问令牌URL", + "type": "string" + }, + "authorize_url": { + "description": "自定义OAuth授权URL", + "type": "string" + }, + "avatar_field": { + "description": "用户信息回包中的头像URL字段名", + "type": "string" + }, + "client_id": { + "description": "自定义客户端ID", + "type": "string" + }, + "client_secret": { + "description": "自定义客户端密钥", + "type": "string" + }, + "email_field": { + "description": "用户信息回包中的邮箱字段名", + "type": "string" + }, + "enable": { + "description": "自定义OAuth开关", + "type": "boolean" + }, + "id_field": { + "description": "用户信息回包中的ID字段名", + "type": "string" + }, + "name_field": { + "description": "用户信息回包中的用户名字段名", + "type": "string" + }, + "scopes": { + "description": "自定义OAuth Scope列表", + "type": "array", + "items": { + "type": "string" + } + }, + "userinfo_url": { + "description": "自定义OAuth用户信息URL", + "type": "string" + } + } + }, + "domain.CustomOAuthReq": { + "type": "object", + "properties": { + "access_token_url": { + "description": "自定义OAuth访问令牌URL", + "type": "string" + }, + "authorize_url": { + "description": "自定义OAuth授权URL", + "type": "string" + }, + "avatar_field": { + "description": "用户信息回包中的头像URL字段名", + "type": "string" + }, + "client_id": { + "description": "自定义客户端ID", + "type": "string" + }, + "client_secret": { + "description": "自定义客户端密钥", + "type": "string" + }, + "email_field": { + "description": "用户信息回包中的邮箱字段名", + "type": "string" + }, + "enable": { + "description": "自定义OAuth开关", + "type": "boolean" + }, + "id_field": { + "description": "用户信息回包中的ID字段名", + "type": "string" + }, + "name_field": { + "description": "用户信息回包中的用户名字段名", + "type": "string" + }, + "scopes": { + "description": "自定义OAuth Scope列表", + "type": "array", + "items": { + "type": "string" + } + }, + "userinfo_url": { + "description": "自定义OAuth用户信息URL", + "type": "string" + } + } + }, + "domain.DingtalkOAuth": { + "type": "object", + "properties": { + "client_id": { + "description": "钉钉客户端ID", + "type": "string" + }, + "client_secret": { + "description": "钉钉客户端密钥", + "type": "string" + }, + "enable": { + "description": "钉钉OAuth开关", + "type": "boolean" + } + } + }, + "domain.DingtalkOAuthReq": { + "type": "object", + "properties": { + "client_id": { + "description": "钉钉客户端ID", + "type": "string" + }, + "client_secret": { + "description": "钉钉客户端密钥", + "type": "string" + }, + "enable": { + "description": "钉钉OAuth开关", + "type": "boolean" + } + } + }, + "domain.ExportCompletionDataResp": { + "type": "object", + "properties": { + "data": { + "description": "补全数据列表", + "type": "array", + "items": { + "$ref": "#/definitions/domain.CompletionData" + } + }, + "total_count": { + "description": "总记录数", + "type": "integer" + } + } + }, + "domain.FileMeta": { + "type": "object", + "properties": { + "content": { + "description": "文件内容(可选)", + "type": "string" + }, + "fileExtension": { + "type": "string" + }, + "fileHash": { + "description": "文件哈希(可选)", + "type": "string" + }, + "filePath": { + "type": "string" + }, + "language": { + "description": "语言类型(可选)", + "allOf": [ + { + "$ref": "#/definitions/domain.CodeLanguageType" + } + ] + } + } + }, + "domain.GetAndSaveReq": { + "type": "object", + "required": [ + "code_files", + "user_id", + "workspace_id" + ], + "properties": { + "code_files": { + "description": "代码文件信息", + "type": "array", + "items": { + "$ref": "#/definitions/domain.FileMeta" + } + }, + "user_id": { + "description": "用户ID", + "type": "string" + }, + "workspace_id": { + "description": "项目ID", + "type": "string" + } + } + }, + "domain.GetProviderModelListResp": { + "type": "object", + "properties": { + "models": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.ProviderModelListItem" + } + } + } + }, + "domain.GrantGroupReq": { + "type": "object", + "required": [ + "admin_ids", + "group_ids" + ], + "properties": { + "admin_ids": { + "description": "管理员ID列表", + "type": "array", + "items": { + "type": "string" + } + }, + "group_ids": { + "description": "分组ID列表", + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "domain.GrantRoleReq": { + "type": "object", + "properties": { + "admin_id": { + "description": "管理员ID", + "type": "string" + }, + "role_ids": { + "description": "角色ID列表", + "type": "array", + "items": { + "type": "integer" + } + } + } + }, + "domain.GroupAddUserReq": { + "type": "object", + "required": [ + "group_ids", + "user_ids" + ], + "properties": { + "group_ids": { + "description": "分组ID列表", + "type": "array", + "items": { + "type": "string" + } + }, + "user_ids": { + "description": "用户ID列表", + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "domain.GroupRemoveAdminReq": { + "type": "object", + "required": [ + "admin_ids", + "group_id" + ], + "properties": { + "admin_ids": { + "description": "管理员ID列表", + "type": "array", + "items": { + "type": "string" + } + }, + "group_id": { + "description": "分组ID", + "type": "string" + } + } + }, + "domain.GroupRemoveUserReq": { + "type": "object", + "required": [ + "group_id", + "user_ids" + ], + "properties": { + "group_id": { + "description": "分组ID", + "type": "string" + }, + "user_ids": { + "description": "用户ID列表", + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "domain.IPInfo": { + "type": "object", + "properties": { + "asn": { + "description": "ASN", + "type": "string" + }, + "city": { + "description": "城市", + "type": "string" + }, + "country": { + "description": "国家", + "type": "string" + }, + "ip": { + "description": "IP地址", + "type": "string" + }, + "isp": { + "description": "运营商", + "type": "string" + }, + "province": { + "description": "省份", + "type": "string" + } + } + }, + "domain.IndexResult": { + "type": "object", + "properties": { + "definition": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "returnType": { + "type": "string" + }, + "type": { + "type": "string" + } + } + }, + "definitionText": { + "type": "string" + }, + "endLine": { + "type": "integer" + }, + "fileHash": { + "type": "string" + }, + "filePath": { + "type": "string" + }, + "implementText": { + "type": "string" + }, + "language": { + "type": "string" + }, + "name": { + "type": "string" + }, + "rangeText": { + "type": "string" + }, + "scope": {}, + "signature": { + "type": "string" + }, + "startLine": { + "type": "integer" + }, + "type": { + "type": "string" + } + } + }, + "domain.InviteResp": { + "type": "object", + "properties": { + "code": { + "description": "邀请码", + "type": "string" + } + } + }, + "domain.LicenseEdition": { + "type": "integer", + "enum": [ + 0, + 1, + 2 + ], + "x-enum-varnames": [ + "LicenseEditionFree", + "LicenseEditionContributor", + "LicenseEditionEnterprise" + ] + }, + "domain.LicenseResp": { + "type": "object", + "properties": { + "edition": { + "$ref": "#/definitions/domain.LicenseEdition" + }, + "expired_at": { + "type": "integer" + }, + "started_at": { + "type": "integer" + }, + "state": { + "type": "integer" + } + } + }, + "domain.ListAdminLoginHistoryResp": { + "type": "object", + "properties": { + "has_next_page": { + "type": "boolean" + }, + "login_histories": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AdminLoginHistory" + } + }, + "next_token": { + "type": "string" + }, + "total_count": { + "type": "integer" + } + } + }, + "domain.ListAdminUserResp": { + "type": "object", + "properties": { + "has_next_page": { + "type": "boolean" + }, + "next_token": { + "type": "string" + }, + "total_count": { + "type": "integer" + }, + "users": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AdminUser" + } + } + } + }, + "domain.ListChatRecordResp": { + "type": "object", + "properties": { + "has_next_page": { + "type": "boolean" + }, + "next_token": { + "type": "string" + }, + "records": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.ChatRecord" + } + }, + "total_count": { + "type": "integer" + } + } + }, + "domain.ListCompletionRecordResp": { + "type": "object", + "properties": { + "has_next_page": { + "type": "boolean" + }, + "next_token": { + "type": "string" + }, + "records": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.CompletionRecord" + } + }, + "total_count": { + "type": "integer" + } + } + }, + "domain.ListLoginHistoryResp": { + "type": "object", + "properties": { + "has_next_page": { + "type": "boolean" + }, + "login_histories": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.UserLoginHistory" + } + }, + "next_token": { + "type": "string" + }, + "total_count": { + "type": "integer" + } + } + }, + "domain.ListSecurityScanningBriefResp": { + "type": "object", + "properties": { + "has_next_page": { + "type": "boolean" + }, + "items": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.SecurityScanningBrief" + } + }, + "next_token": { + "type": "string" + }, + "total_count": { + "type": "integer" + } + } + }, + "domain.ListSecurityScanningDetailResp": { + "type": "object", + "properties": { + "has_next_page": { + "type": "boolean" + }, + "items": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.SecurityScanningRiskDetail" + } + }, + "next_token": { + "type": "string" + }, + "total_count": { + "type": "integer" + } + } + }, + "domain.ListSecurityScanningReq": { + "type": "object", + "properties": { + "author": { + "description": "作者", + "type": "string" + }, + "next_token": { + "description": "下一页标识", + "type": "string" + }, + "page": { + "description": "分页", + "type": "integer" + }, + "project_name": { + "description": "项目名称", + "type": "string" + }, + "size": { + "description": "每页多少条记录", + "type": "integer" + } + } + }, + "domain.ListSecurityScanningResp": { + "type": "object", + "properties": { + "has_next_page": { + "type": "boolean" + }, + "items": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.SecurityScanningResult" + } + }, + "next_token": { + "type": "string" + }, + "total_count": { + "type": "integer" + } + } + }, + "domain.ListUserGroupResp": { + "type": "object", + "properties": { + "groups": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.UserGroup" + } + }, + "has_next_page": { + "type": "boolean" + }, + "next_token": { + "type": "string" + }, + "total_count": { + "type": "integer" + } + } + }, + "domain.ListUserResp": { + "type": "object", + "properties": { + "has_next_page": { + "type": "boolean" + }, + "next_token": { + "type": "string" + }, + "total_count": { + "type": "integer" + }, + "users": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.User" + } + } + } + }, + "domain.ListWorkspaceFileResp": { + "type": "object", + "properties": { + "files": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.WorkspaceFile" + } + }, + "has_next_page": { + "type": "boolean" + }, + "next_token": { + "type": "string" + }, + "total_count": { + "type": "integer" + } + } + }, + "domain.LoginReq": { + "type": "object", + "required": [ + "source" + ], + "properties": { + "password": { + "description": "密码", + "type": "string" + }, + "session_id": { + "description": "会话Id插件登录时必填", + "type": "string" + }, + "source": { + "description": "登录来源 plugin: 插件 browser: 浏览器; 默认为 plugin", + "default": "plugin", + "allOf": [ + { + "$ref": "#/definitions/consts.LoginSource" + } + ] + }, + "username": { + "description": "用户名", + "type": "string" + } + } + }, + "domain.LoginResp": { + "type": "object", + "properties": { + "redirect_url": { + "description": "重定向URL", + "type": "string" + }, + "user": { + "description": "用户信息", + "allOf": [ + { + "$ref": "#/definitions/domain.User" + } + ] + } + } + }, + "domain.Model": { + "type": "object", + "properties": { + "api_base": { + "description": "接口地址 如:https://api.qwen.com", + "type": "string" + }, + "api_header": { + "description": "接口头 如:Authorization: Bearer sk-xxxx", + "type": "string" + }, + "api_key": { + "description": "接口密钥 如:sk-xxxx", + "type": "string" + }, + "api_version": { + "description": "接口版本 如:2023-05-15", + "type": "string" + }, + "created_at": { + "description": "创建时间", + "type": "integer" + }, + "id": { + "description": "模型ID", + "type": "string" + }, + "input": { + "description": "输入token数", + "type": "integer" + }, + "is_active": { + "description": "是否启用", + "type": "boolean" + }, + "is_internal": { + "description": "是否内部模型", + "type": "boolean" + }, + "model_name": { + "description": "模型名称 如: deepseek-v3", + "type": "string" + }, + "model_type": { + "description": "模型类型 llm:对话模型 coder:代码模型", + "allOf": [ + { + "$ref": "#/definitions/consts.ModelType" + } + ] + }, + "output": { + "description": "输出token数", + "type": "integer" + }, + "param": { + "description": "高级参数", + "allOf": [ + { + "$ref": "#/definitions/domain.ModelParam" + } + ] + }, + "provider": { + "description": "提供商", + "allOf": [ + { + "$ref": "#/definitions/consts.ModelProvider" + } + ] + }, + "show_name": { + "description": "模型显示名称", + "type": "string" + }, + "status": { + "description": "状态 active:启用 inactive:禁用", + "allOf": [ + { + "$ref": "#/definitions/consts.ModelStatus" + } + ] + }, + "updated_at": { + "description": "更新时间", + "type": "integer" + } + } + }, + "domain.ModelBasic": { + "type": "object", + "required": [ + "provider" + ], + "properties": { + "api_base": { + "description": "接口地址 如:https://api.qwen.com", + "type": "string" + }, + "name": { + "description": "模型名称", + "type": "string" + }, + "provider": { + "description": "提供商", + "enum": [ + "SiliconFlow", + "OpenAI", + "Ollama", + "DeepSeek", + "Moonshot", + "AzureOpenAI", + "BaiZhiCloud", + "Hunyuan", + "BaiLian", + "Volcengine", + "Other" + ], + "allOf": [ + { + "$ref": "#/definitions/consts.ModelProvider" + } + ] + } + } + }, + "domain.ModelData": { + "type": "object", + "properties": { + "api_base": { + "type": "string" + }, + "base_model": { + "type": "string" + }, + "created": { + "type": "integer" + }, + "id": { + "type": "string" + }, + "is_active": { + "type": "boolean" + }, + "name": { + "type": "string" + }, + "object": { + "type": "string" + }, + "owned_by": { + "type": "string" + }, + "type": { + "type": "string" + } + } + }, + "domain.ModelListResp": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.ModelData" + } + }, + "object": { + "type": "string" + } + } + }, + "domain.ModelParam": { + "type": "object", + "properties": { + "context_window": { + "type": "integer" + }, + "max_tokens": { + "type": "integer" + }, + "r1_enabled": { + "type": "boolean" + }, + "support_computer_use": { + "type": "boolean" + }, + "support_images": { + "type": "boolean" + }, + "support_prompt_cache": { + "type": "boolean" + } + } + }, + "domain.ModelTokenUsage": { + "type": "object", + "properties": { + "timestamp": { + "description": "时间戳", + "type": "integer" + }, + "tokens": { + "description": "使用token数", + "type": "integer" + } + } + }, + "domain.ModelTokenUsageResp": { + "type": "object", + "properties": { + "input_usage": { + "description": "输入token使用记录", + "type": "array", + "items": { + "$ref": "#/definitions/domain.ModelTokenUsage" + } + }, + "output_usage": { + "description": "输出token使用记录", + "type": "array", + "items": { + "$ref": "#/definitions/domain.ModelTokenUsage" + } + }, + "total_input": { + "description": "总输入token数", + "type": "integer" + }, + "total_output": { + "description": "总输出token数", + "type": "integer" + } + } + }, + "domain.OAuthURLResp": { + "type": "object", + "properties": { + "url": { + "type": "string" + } + } + }, + "domain.ProfileUpdateReq": { + "type": "object", + "properties": { + "avatar": { + "description": "头像", + "type": "string" + }, + "old_password": { + "description": "旧密码", + "type": "string" + }, + "password": { + "description": "密码", + "type": "string" + }, + "username": { + "description": "用户名", + "type": "string" + } + } + }, + "domain.ProviderModel": { + "type": "object", + "properties": { + "models": { + "description": "模型列表", + "type": "array", + "items": { + "$ref": "#/definitions/domain.ModelBasic" + } + }, + "provider": { + "description": "提供商", + "type": "string" + } + } + }, + "domain.ProviderModelListItem": { + "type": "object", + "properties": { + "model": { + "type": "string" + } + } + }, + "domain.RegisterReq": { + "type": "object", + "required": [ + "code", + "email", + "password", + "username" + ], + "properties": { + "code": { + "description": "邀请码", + "type": "string" + }, + "email": { + "description": "邮箱", + "type": "string" + }, + "password": { + "description": "密码", + "type": "string" + }, + "username": { + "description": "用户名", + "type": "string" + } + } + }, + "domain.ReportReq": { + "type": "object", + "properties": { + "action": { + "$ref": "#/definitions/consts.ReportAction" + }, + "content": { + "description": "内容", + "type": "string" + }, + "cursor_position": { + "description": "光标位置(用于reject action)", + "type": "object", + "additionalProperties": {} + }, + "id": { + "description": "task_id or resp_id", + "type": "string" + }, + "mode": { + "description": "模式", + "type": "string" + }, + "source_code": { + "description": "当前文件的原文(用于reject action)", + "type": "string" + }, + "tool": { + "description": "工具", + "type": "string" + }, + "user_input": { + "description": "用户输入的新文本(用于reject action)", + "type": "string" + } + } + }, + "domain.Role": { + "type": "object", + "properties": { + "description": { + "type": "string" + }, + "id": { + "type": "integer" + }, + "name": { + "type": "string" + } + } + }, + "domain.SecurityScanningBrief": { + "type": "object", + "properties": { + "created_at": { + "description": "创建时间", + "type": "integer" + }, + "id": { + "description": "扫描任务id", + "type": "string" + }, + "report_url": { + "description": "报告url", + "type": "string" + }, + "status": { + "description": "扫描状态", + "allOf": [ + { + "$ref": "#/definitions/consts.SecurityScanningStatus" + } + ] + }, + "workspace": { + "description": "项目目录", + "type": "string" + } + } + }, + "domain.SecurityScanningResult": { + "type": "object", + "properties": { + "created_at": { + "description": "扫描开始时间", + "type": "integer" + }, + "error": { + "description": "错误信息", + "type": "string" + }, + "id": { + "description": "扫描任务id", + "type": "string" + }, + "name": { + "description": "扫描任务", + "type": "string" + }, + "path": { + "description": "项目路径", + "type": "string" + }, + "project_name": { + "description": "项目名称", + "type": "string" + }, + "risk": { + "description": "风险结果", + "allOf": [ + { + "$ref": "#/definitions/domain.SecurityScanningRiskResult" + } + ] + }, + "status": { + "description": "扫描状态", + "allOf": [ + { + "$ref": "#/definitions/consts.SecurityScanningStatus" + } + ] + }, + "user": { + "description": "用户", + "allOf": [ + { + "$ref": "#/definitions/domain.User" + } + ] + } + } + }, + "domain.SecurityScanningRiskDetail": { + "type": "object", + "properties": { + "content": { + "description": "代码内容", + "type": "string" + }, + "desc": { + "description": "风险描述", + "type": "string" + }, + "end": { + "description": "风险代码行结束位置", + "allOf": [ + { + "$ref": "#/definitions/types.Position" + } + ] + }, + "filename": { + "description": "风险文件名", + "type": "string" + }, + "fix": { + "description": "修复建议", + "type": "string" + }, + "id": { + "description": "风险id", + "type": "string" + }, + "level": { + "description": "风险等级", + "allOf": [ + { + "$ref": "#/definitions/consts.SecurityScanningRiskLevel" + } + ] + }, + "lines": { + "description": "风险代码行", + "type": "string" + }, + "start": { + "description": "风险代码行开始位置", + "allOf": [ + { + "$ref": "#/definitions/types.Position" + } + ] + } + } + }, + "domain.SecurityScanningRiskResult": { + "type": "object", + "properties": { + "critical_count": { + "description": "高危数", + "type": "integer" + }, + "id": { + "type": "string" + }, + "severe_count": { + "description": "严重数", + "type": "integer" + }, + "suggest_count": { + "description": "建议数", + "type": "integer" + } + } + }, + "domain.Setting": { + "type": "object", + "properties": { + "base_url": { + "description": "base url 配置,为了支持前置代理", + "type": "string" + }, + "created_at": { + "description": "创建时间", + "type": "integer" + }, + "custom_oauth": { + "description": "自定义OAuth接入", + "allOf": [ + { + "$ref": "#/definitions/domain.CustomOAuth" + } + ] + }, + "dingtalk_oauth": { + "description": "钉钉OAuth接入", + "allOf": [ + { + "$ref": "#/definitions/domain.DingtalkOAuth" + } + ] + }, + "disable_password_login": { + "description": "是否禁用密码登录", + "type": "boolean" + }, + "enable_auto_login": { + "description": "是否开启自动登录", + "type": "boolean" + }, + "enable_sso": { + "description": "是否开启SSO", + "type": "boolean" + }, + "force_two_factor_auth": { + "description": "是否强制两步验证", + "type": "boolean" + }, + "updated_at": { + "description": "更新时间", + "type": "integer" + } + } + }, + "domain.Statistics": { + "type": "object", + "properties": { + "disabled_users": { + "description": "禁用用户数", + "type": "integer" + }, + "total_users": { + "description": "总用户数", + "type": "integer" + } + } + }, + "domain.SyncWorkspaceFileReq": { + "type": "object", + "required": [ + "files", + "user_id", + "workspace_id" + ], + "properties": { + "files": { + "description": "要同步的文件列表", + "type": "array", + "items": { + "$ref": "#/definitions/domain.CreateWorkspaceFileReq" + } + }, + "user_id": { + "description": "用户ID", + "type": "string" + }, + "workspace_id": { + "description": "工作区ID", + "type": "string" + } + } + }, + "domain.SyncWorkspaceFileResp": { + "type": "object", + "properties": { + "created": { + "description": "新创建的文件", + "type": "array", + "items": { + "$ref": "#/definitions/domain.WorkspaceFile" + } + }, + "deleted": { + "description": "删除的文件ID", + "type": "array", + "items": { + "type": "string" + } + }, + "total": { + "description": "处理的文件总数", + "type": "integer" + }, + "updated": { + "description": "更新的文件", + "type": "array", + "items": { + "$ref": "#/definitions/domain.WorkspaceFile" + } + } + } + }, + "domain.TimeStat": { + "type": "object", + "properties": { + "accepted_per": { + "description": "接受率统计", + "type": "array", + "items": { + "type": "object", + "properties": { + "timestamp": { + "description": "时间戳", + "type": "integer" + }, + "value": { + "description": "值", + "type": "number" + } + } + } + }, + "active_users": { + "description": "活跃用户数统计", + "type": "array", + "items": { + "type": "object", + "properties": { + "timestamp": { + "description": "时间戳", + "type": "integer" + }, + "value": { + "description": "值", + "type": "integer" + } + } + } + }, + "chats": { + "description": "对话任务数统计", + "type": "array", + "items": { + "type": "object", + "properties": { + "timestamp": { + "description": "时间戳", + "type": "integer" + }, + "value": { + "description": "值", + "type": "integer" + } + } + } + }, + "code_completions": { + "description": "补全任务数统计", + "type": "array", + "items": { + "type": "object", + "properties": { + "timestamp": { + "description": "时间戳", + "type": "integer" + }, + "value": { + "description": "值", + "type": "integer" + } + } + } + }, + "lines_of_code": { + "description": "代码行数统计", + "type": "array", + "items": { + "type": "object", + "properties": { + "timestamp": { + "description": "时间戳", + "type": "integer" + }, + "value": { + "description": "值", + "type": "integer" + } + } + } + }, + "real_time_tokens": { + "description": "实时token数统计", + "type": "array", + "items": { + "type": "object", + "properties": { + "timestamp": { + "description": "时间戳", + "type": "integer" + }, + "value": { + "description": "值", + "type": "integer" + } + } + } + }, + "total_accepted_per": { + "description": "近90天平均接受率", + "type": "number" + }, + "total_chats": { + "description": "近90天对话任务数", + "type": "integer" + }, + "total_completions": { + "description": "近90天补全任务数", + "type": "integer" + }, + "total_lines_of_code": { + "description": "近90天代码行数", + "type": "integer" + }, + "total_users": { + "description": "近90天活跃用户数", + "type": "integer" + } + } + }, + "domain.UpdateModelReq": { + "type": "object", + "required": [ + "provider" + ], + "properties": { + "api_base": { + "description": "接口地址 如:https://api.qwen.com", + "type": "string" + }, + "api_header": { + "type": "string" + }, + "api_key": { + "description": "接口密钥 如:sk-xxxx", + "type": "string" + }, + "api_version": { + "type": "string" + }, + "id": { + "description": "模型ID", + "type": "string" + }, + "model_name": { + "description": "模型名称", + "type": "string" + }, + "param": { + "description": "高级参数", + "allOf": [ + { + "$ref": "#/definitions/domain.ModelParam" + } + ] + }, + "provider": { + "description": "提供商", + "enum": [ + "SiliconFlow", + "OpenAI", + "Ollama", + "DeepSeek", + "Moonshot", + "AzureOpenAI", + "BaiZhiCloud", + "Hunyuan", + "BaiLian", + "Volcengine", + "Other" + ], + "allOf": [ + { + "$ref": "#/definitions/consts.ModelProvider" + } + ] + }, + "show_name": { + "description": "模型显示名称", + "type": "string" + }, + "status": { + "description": "状态 active:启用 inactive:禁用", + "allOf": [ + { + "$ref": "#/definitions/consts.ModelStatus" + } + ] + } + } + }, + "domain.UpdateSettingReq": { + "type": "object", + "properties": { + "base_url": { + "description": "base url 配置,为了支持前置代理", + "type": "string" + }, + "custom_oauth": { + "description": "自定义OAuth配置", + "allOf": [ + { + "$ref": "#/definitions/domain.CustomOAuthReq" + } + ] + }, + "dingtalk_oauth": { + "description": "钉钉OAuth配置", + "allOf": [ + { + "$ref": "#/definitions/domain.DingtalkOAuthReq" + } + ] + }, + "disable_password_login": { + "description": "是否禁用密码登录", + "type": "boolean" + }, + "enable_auto_login": { + "description": "是否开启自动登录", + "type": "boolean" + }, + "enable_sso": { + "description": "是否开启SSO", + "type": "boolean" + }, + "force_two_factor_auth": { + "description": "是否强制两步验证", + "type": "boolean" + } + } + }, + "domain.UpdateUserGroupReq": { + "type": "object", + "required": [ + "id", + "name" + ], + "properties": { + "id": { + "description": "分组id", + "type": "string" + }, + "name": { + "type": "string" + } + } + }, + "domain.UpdateUserReq": { + "type": "object", + "required": [ + "id" + ], + "properties": { + "id": { + "description": "用户ID", + "type": "string" + }, + "password": { + "description": "重置密码", + "type": "string" + }, + "status": { + "description": "用户状态 active: 正常 locked: 锁定 inactive: 禁用", + "allOf": [ + { + "$ref": "#/definitions/consts.UserStatus" + } + ] + } + } + }, + "domain.UpdateWorkspaceFileReq": { + "type": "object", + "required": [ + "id" + ], + "properties": { + "content": { + "description": "文件内容", + "type": "string" + }, + "hash": { + "description": "文件哈希", + "type": "string" + }, + "id": { + "description": "文件ID", + "type": "string" + }, + "language": { + "description": "编程语言", + "type": "string" + }, + "size": { + "description": "文件大小", + "type": "integer" + } + } + }, + "domain.User": { + "type": "object", + "properties": { + "avatar_url": { + "description": "头像URL", + "type": "string" + }, + "created_at": { + "description": "创建时间", + "type": "integer" + }, + "email": { + "description": "邮箱", + "type": "string" + }, + "id": { + "description": "用户ID", + "type": "string" + }, + "is_deleted": { + "description": "是否删除", + "type": "boolean" + }, + "last_active_at": { + "description": "最后活跃时间", + "type": "integer" + }, + "status": { + "description": "用户状态 active: 正常 locked: 锁定 inactive: 禁用", + "allOf": [ + { + "$ref": "#/definitions/consts.UserStatus" + } + ] + }, + "two_step_auth": { + "description": "是否开启两步验证", + "type": "boolean" + }, + "username": { + "description": "用户名", + "type": "string" + } + } + }, + "domain.UserCodeRank": { + "type": "object", + "properties": { + "lines": { + "description": "代码行数", + "type": "integer" + }, + "user": { + "description": "用户信息", + "allOf": [ + { + "$ref": "#/definitions/domain.User" + } + ] + }, + "username": { + "description": "用户名", + "type": "string" + } + } + }, + "domain.UserEvent": { + "type": "object", + "properties": { + "created_at": { + "description": "事件时间", + "type": "integer" + }, + "name": { + "description": "事件名称", + "type": "string" + } + } + }, + "domain.UserGroup": { + "type": "object", + "properties": { + "admins": { + "description": "关联的管理员", + "type": "array", + "items": { + "$ref": "#/definitions/domain.AdminUser" + } + }, + "id": { + "type": "string" + }, + "name": { + "description": "组名", + "type": "string" + }, + "users": { + "description": "关联的用户", + "type": "array", + "items": { + "$ref": "#/definitions/domain.User" + } + } + } + }, + "domain.UserHeatmap": { + "type": "object", + "properties": { + "count": { + "type": "integer" + }, + "date": { + "type": "integer" + } + } + }, + "domain.UserHeatmapResp": { + "type": "object", + "properties": { + "max_count": { + "type": "integer" + }, + "points": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.UserHeatmap" + } + } + } + }, + "domain.UserLoginHistory": { + "type": "object", + "properties": { + "client_id": { + "description": "插件ID vscode", + "type": "string" + }, + "client_version": { + "description": "客户端版本", + "type": "string" + }, + "created_at": { + "description": "登录时间", + "type": "integer" + }, + "device": { + "description": "设备信息", + "type": "string" + }, + "hostname": { + "description": "主机名", + "type": "string" + }, + "ip_info": { + "description": "IP信息", + "allOf": [ + { + "$ref": "#/definitions/domain.IPInfo" + } + ] + }, + "user": { + "description": "用户信息", + "allOf": [ + { + "$ref": "#/definitions/domain.User" + } + ] + } + } + }, + "domain.UserStat": { + "type": "object", + "properties": { + "accepted_per": { + "description": "接受率统计", + "type": "array", + "items": { + "type": "object", + "properties": { + "timestamp": { + "description": "时间戳", + "type": "integer" + }, + "value": { + "description": "值", + "type": "number" + } + } + } + }, + "chats": { + "description": "对话任务数统计", + "type": "array", + "items": { + "type": "object", + "properties": { + "timestamp": { + "description": "时间戳", + "type": "integer" + }, + "value": { + "description": "值", + "type": "integer" + } + } + } + }, + "code_completions": { + "description": "补全任务数统计", + "type": "array", + "items": { + "type": "object", + "properties": { + "timestamp": { + "description": "时间戳", + "type": "integer" + }, + "value": { + "description": "值", + "type": "integer" + } + } + } + }, + "lines_of_code": { + "description": "代码行数统计", + "type": "array", + "items": { + "type": "object", + "properties": { + "timestamp": { + "description": "时间戳", + "type": "integer" + }, + "value": { + "description": "值", + "type": "integer" + } + } + } + }, + "program_language": { + "description": "编程语言占比", + "type": "array", + "items": { + "$ref": "#/definitions/domain.CategoryPoint" + } + }, + "total_accepted_per": { + "description": "总接受率", + "type": "number" + }, + "total_chats": { + "description": "总对话任务数", + "type": "integer" + }, + "total_completions": { + "description": "总补全任务数", + "type": "integer" + }, + "total_lines_of_code": { + "description": "总代码行数", + "type": "integer" + }, + "work_mode": { + "description": "工作模式占比", + "type": "array", + "items": { + "$ref": "#/definitions/domain.CategoryPoint" + } + } + } + }, + "domain.WorkspaceFile": { + "type": "object", + "properties": { + "content": { + "description": "文件内容", + "type": "string" + }, + "created_at": { + "description": "创建时间", + "type": "integer" + }, + "hash": { + "description": "文件哈希", + "type": "string" + }, + "id": { + "description": "文件ID", + "type": "string" + }, + "language": { + "description": "编程语言", + "type": "string" + }, + "path": { + "description": "文件路径", + "type": "string" + }, + "size": { + "description": "文件大小", + "type": "integer" + }, + "updated_at": { + "description": "更新时间", + "type": "integer" + }, + "user_id": { + "description": "用户ID", + "type": "string" + }, + "workspace_id": { + "description": "工作区ID", + "type": "string" + } + } + }, + "types.Position": { + "type": "object", + "properties": { + "col": { + "type": "integer" + }, + "line": { + "type": "integer" + }, + "offset": { + "type": "integer" + } + } + }, + "v1.GetContextReq": { + "type": "object", + "properties": { + "limit": { + "description": "返回结果数量限制,默认10", + "type": "integer" + }, + "queries": { + "description": "批量查询参数", + "type": "array", + "items": { + "$ref": "#/definitions/v1.Query" + } + }, + "query": { + "description": "单个查询参数", + "allOf": [ + { + "$ref": "#/definitions/v1.Query" + } + ] + }, + "workspacePath": { + "description": "工作区路径(必填)", + "type": "string" + } + } + }, + "v1.GetSemanticContextReq": { + "type": "object", + "properties": { + "limit": { + "description": "返回结果数量限制,默认10", + "type": "integer" + }, + "query": { + "description": "搜索查询文本(必填)", + "type": "string" + }, + "workspacePath": { + "description": "工作区路径(必填)", + "type": "string" + } + } + }, + "v1.Query": { + "type": "object", + "properties": { + "language": { + "description": "编程语言(可选)", + "type": "string" + }, + "name": { + "description": "代码片段名称(可选)", + "type": "string" + }, + "snippetType": { + "description": "代码片段类型(可选)", + "type": "string" + } + } + }, + "web.Resp": { + "type": "object", + "properties": { + "code": { + "type": "integer" + }, + "data": {}, + "message": { + "type": "string" + } + } + } + } +} \ No newline at end of file diff --git a/backend/domain/admin.go b/backend/domain/admin.go new file mode 100644 index 00000000..b04b36da --- /dev/null +++ b/backend/domain/admin.go @@ -0,0 +1,28 @@ +package domain + +import ( + "github.com/google/uuid" + + "github.com/chaitin/MonkeyCode/backend/db" +) + +type GrantRoleReq struct { + AdminID uuid.UUID `json:"admin_id"` // 管理员ID + RoleIDs []int64 `json:"role_ids"` // 角色ID列表 +} + +type Role struct { + ID int64 `json:"id"` + Name string `json:"name"` + Description string `json:"description"` +} + +func (r *Role) From(e *db.Role) *Role { + if e == nil { + return r + } + r.ID = e.ID + r.Name = e.Name + r.Description = e.Description + return r +} diff --git a/backend/domain/model.go b/backend/domain/model.go index 855727b7..40c0ce4e 100644 --- a/backend/domain/model.go +++ b/backend/domain/model.go @@ -71,7 +71,6 @@ var ModelProviderBrandModelsList = map[consts.ModelProvider][]ProviderModelListI } type MyModelListReq struct { - UserID string `json:"-"` ModelType consts.ModelType `json:"model_type" query:"model_type"` // 模型类型 llm:对话模型 coder:代码模型 } @@ -115,7 +114,7 @@ type GetTokenUsageReq struct { } type CreateModelReq struct { - UserID string `json:"-"` + AdminID uuid.UUID `json:"-"` ShowName string `json:"show_name"` // 模型显示名称 ModelName string `json:"model_name" validate:"required"` // 模型名称 如: deepseek-v3 Provider consts.ModelProvider `json:"provider" validate:"required,oneof=SiliconFlow OpenAI Ollama DeepSeek Moonshot AzureOpenAI BaiZhiCloud Hunyuan BaiLian Volcengine Other"` // 提供商 diff --git a/backend/domain/user.go b/backend/domain/user.go index 647f5573..0e111f18 100644 --- a/backend/domain/user.go +++ b/backend/domain/user.go @@ -4,6 +4,7 @@ import ( "context" "github.com/GoYoko/web" + "github.com/google/uuid" "github.com/chaitin/MonkeyCode/backend/consts" "github.com/chaitin/MonkeyCode/backend/db" @@ -34,6 +35,9 @@ type UserUsecase interface { ExportCompletionData(ctx context.Context) (*ExportCompletionDataResp, error) GetUserByApiKey(ctx context.Context, apiKey string) (*db.User, error) GetUserCount(ctx context.Context) (int64, error) + ListRole(ctx context.Context) ([]*Role, error) + GrantRole(ctx context.Context, req *GrantRoleReq) error + GetPermissions(ctx context.Context, id uuid.UUID) (*Permissions, error) } type UserRepo interface { @@ -42,7 +46,7 @@ type UserRepo interface { Delete(ctx context.Context, id string) error InitAdmin(ctx context.Context, username, password string) error CreateUser(ctx context.Context, user *db.User) (*db.User, error) - CreateAdmin(ctx context.Context, admin *db.Admin) (*db.Admin, error) + CreateAdmin(ctx context.Context, admin *db.Admin, roleID int64) (*db.Admin, error) DeleteAdmin(ctx context.Context, id string) error AdminByName(ctx context.Context, username string) (*db.Admin, error) GetByName(ctx context.Context, username string) (*db.User, error) @@ -62,6 +66,10 @@ type UserRepo interface { SaveUserLoginHistory(ctx context.Context, userID, ip string, session *VSCodeSession) error ExportCompletionData(ctx context.Context) ([]*CompletionData, error) GetUserCount(ctx context.Context) (int64, error) + ListRole(ctx context.Context) ([]*db.Role, error) + GrantRole(ctx context.Context, req *GrantRoleReq) error + GetPermissions(ctx context.Context, id uuid.UUID) (*Permissions, error) + CleanPermissionCache(ctx context.Context, id uuid.UUID) } type ProfileUpdateReq struct { @@ -79,8 +87,9 @@ type UpdateUserReq struct { } type CreateAdminReq struct { - Username string `json:"username"` // 用户名 - Password string `json:"password"` // 密码 + Username string `json:"username" validate:"required"` // 用户名 + Password string `json:"password" validate:"required"` // 密码 + RoleID int64 `json:"role_id" validate:"required"` // 角色ID } type VSCodeAuthInitReq struct { @@ -257,21 +266,34 @@ func (u *User) From(e *db.User) *User { } type AdminUser struct { - ID string `json:"id"` // 用户ID + ID uuid.UUID `json:"id"` // 用户ID Username string `json:"username"` // 用户名 LastActiveAt int64 `json:"last_active_at"` // 最后活跃时间 Status consts.AdminStatus `json:"status"` // 用户状态 active: 正常 inactive: 禁用 + Role *Role `json:"role"` // 角色 CreatedAt int64 `json:"created_at"` // 创建时间 } +func (a *AdminUser) IsAdmin() bool { + return a.Username == "admin" +} + func (a *AdminUser) From(e *db.Admin) *AdminUser { if e == nil { return a } - a.ID = e.ID.String() + a.ID = e.ID a.Username = e.Username a.Status = e.Status + if e.Username == "admin" { + a.Role = &Role{ + ID: 1, + Name: "超级管理员", + } + } else if l := len(e.Edges.Roles); l > 0 { + a.Role = cvt.From(e.Edges.Roles[l-1], &Role{}) + } a.CreatedAt = e.CreatedAt.Unix() return a @@ -427,3 +449,11 @@ type ExportCompletionDataResp struct { TotalCount int64 `json:"total_count"` // 总记录数 Data []*CompletionData `json:"data"` // 补全数据列表 } + +type Permissions struct { + AdminID uuid.UUID + IsAdmin bool + Roles []*Role + UserIDs []uuid.UUID + GroupIDs []uuid.UUID +} diff --git a/backend/ent/rule/rule.go b/backend/ent/rule/rule.go new file mode 100644 index 00000000..bc42c1fa --- /dev/null +++ b/backend/ent/rule/rule.go @@ -0,0 +1,157 @@ +package rule + +import ( + "context" + "fmt" + "log/slog" + "slices" + + "entgo.io/ent" + "github.com/google/uuid" + + "github.com/chaitin/MonkeyCode/backend/db" + "github.com/chaitin/MonkeyCode/backend/db/adminloginhistory" + "github.com/chaitin/MonkeyCode/backend/db/securityscanning" + "github.com/chaitin/MonkeyCode/backend/db/task" + "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/usergroup" + "github.com/chaitin/MonkeyCode/backend/db/usergroupadmin" + "github.com/chaitin/MonkeyCode/backend/db/userloginhistory" + "github.com/chaitin/MonkeyCode/backend/domain" + "github.com/chaitin/MonkeyCode/backend/errcode" +) + +type PermissionKey struct{} +type skipPermissionCheckKey struct{} + +func SkipPermission(ctx context.Context) context.Context { + return context.WithValue(ctx, skipPermissionCheckKey{}, struct{}{}) +} + +type PermissionHook struct { + next ent.Mutator +} + +// Mutate implements ent.Mutator. +func (p PermissionHook) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + slog.With("mType", fmt.Sprintf("%T", m)).With("op", m.Op().String()).With("type", m.Type()).InfoContext(ctx, "[PermissionHook] mutate") + if v := ctx.Value(skipPermissionCheckKey{}); v != nil { + return p.next.Mutate(ctx, m) + } + + perm, ok := ctx.Value(PermissionKey{}).(*domain.Permissions) + if !ok { + return nil, errcode.ErrPermission.Wrap(fmt.Errorf("failed to get permission")) + } + + if perm.IsAdmin { + return p.next.Mutate(ctx, m) + } + + switch m.Op() { + case ent.OpCreate, ent.OpUpdate, ent.OpDelete, ent.OpDeleteOne, ent.OpUpdateOne: + switch m.Type() { + case "Model", "Admin", "Setting", "AdminRole", "UserGroup", "UserGroupUser": + return nil, errcode.ErrPermission.Wrap(fmt.Errorf("model mutation is not allowed")) + } + } + + if val, ok := m.Field("user_id"); ok { + id, ok := val.(uuid.UUID) + if !ok { + return nil, fmt.Errorf("user_id is not uuid") + } + if !slices.Contains(perm.UserIDs, id) { + return nil, fmt.Errorf("no user:[%s] permission", id) + } + } + if val, ok := m.Field("user_group_id"); ok { + id, ok := val.(uuid.UUID) + if !ok { + return nil, fmt.Errorf("user_group_id is not uuid") + } + if !slices.Contains(perm.GroupIDs, id) { + return nil, fmt.Errorf("no user_group:[%s] permission", id) + } + } + return p.next.Mutate(ctx, m) +} + +var _ ent.Mutator = PermissionHook{} + +func PermissionHookFunc() ent.Hook { + return func(next ent.Mutator) ent.Mutator { + return PermissionHook{next: next} + } +} + +func WithPermission(ctx context.Context, next ent.Querier, q ent.Query, fn func(context.Context, *domain.Permissions) error) (ent.Value, error) { + perm, ok := ctx.Value(PermissionKey{}).(*domain.Permissions) + if !ok { + return nil, fmt.Errorf("no permission by interceptor") + } + if perm.IsAdmin { + return next.Query(ctx, q) + } + if err := fn(ctx, perm); err != nil { + return nil, err + } + return next.Query(ctx, q) +} + +func PermissionInterceptor(logger *slog.Logger) ent.Interceptor { + return ent.InterceptFunc(func(next ent.Querier) ent.Querier { + return ent.QuerierFunc(func(ctx context.Context, q ent.Query) (ent.Value, error) { + if v := ctx.Value(skipPermissionCheckKey{}); v != nil { + return next.Query(ctx, q) + } + + logger = logger.With("type", fmt.Sprintf("%T", q)) + + switch qq := q.(type) { + case *db.UserGroupQuery: + return WithPermission(ctx, next, q, func(ctx context.Context, p *domain.Permissions) error { + qq.Where( + usergroup.Or( + usergroup.AdminID(p.AdminID), + usergroup.HasUserGroupAdminsWith(usergroupadmin.AdminID(p.AdminID)), + ), + ) + return nil + }) + + case *db.TaskQuery: + return WithPermission(ctx, next, q, func(ctx context.Context, p *domain.Permissions) error { + qq.Where(task.UserIDIn(p.UserIDs...)) + return nil + }) + + case *db.SecurityScanningQuery: + return WithPermission(ctx, next, q, func(ctx context.Context, p *domain.Permissions) error { + qq.Where(securityscanning.UserIDIn(p.UserIDs...)) + return nil + }) + + case *db.UserLoginHistoryQuery: + return WithPermission(ctx, next, q, func(ctx context.Context, p *domain.Permissions) error { + qq.Where(userloginhistory.UserIDIn(p.UserIDs...)) + return nil + }) + + case *db.AdminLoginHistoryQuery: + return WithPermission(ctx, next, q, func(ctx context.Context, p *domain.Permissions) error { + // 普通管理员登录历史记录只能查询自己的 + qq.Where(adminloginhistory.AdminID(p.AdminID)) + return nil + }) + + case *db.UserQuery: + admin, ok := ctx.Value(PermissionKey{}).(*domain.Permissions) + if ok && admin.AdminID != uuid.Nil && !admin.IsAdmin { + qq.Where(user.IDIn(admin.UserIDs...)) + } + } + return next.Query(ctx, q) + }) + }) +} diff --git a/backend/ent/schema/admin.go b/backend/ent/schema/admin.go index 18754df3..779a179e 100644 --- a/backend/ent/schema/admin.go +++ b/backend/ent/schema/admin.go @@ -43,5 +43,8 @@ func (Admin) Fields() []ent.Field { func (Admin) Edges() []ent.Edge { return []ent.Edge{ edge.To("login_histories", AdminLoginHistory.Type), + edge.To("myusergroups", UserGroup.Type), + edge.From("usergroups", UserGroup.Type).Ref("admins").Through("user_group_admins", UserGroupAdmin.Type), + edge.From("roles", Role.Type).Ref("admins").Through("admin_roles", AdminRole.Type), } } diff --git a/backend/ent/schema/adminrole.go b/backend/ent/schema/adminrole.go new file mode 100644 index 00000000..88fbedfb --- /dev/null +++ b/backend/ent/schema/adminrole.go @@ -0,0 +1,38 @@ +package schema + +import ( + "entgo.io/ent" + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/schema" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" + "github.com/google/uuid" +) + +// AdminRole holds the schema definition for the AdminRole entity. +type AdminRole struct { + ent.Schema +} + +func (AdminRole) Annotations() []schema.Annotation { + return []schema.Annotation{ + entsql.Annotation{Table: "admin_roles"}, + } +} + +// Fields of the AdminRole. +func (AdminRole) Fields() []ent.Field { + return []ent.Field{ + field.UUID("id", uuid.UUID{}), + field.UUID("admin_id", uuid.UUID{}), + field.Int64("role_id"), + } +} + +// Edges of the AdminRole. +func (AdminRole) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("admin", Admin.Type).Field("admin_id").Unique().Required(), + edge.To("role", Role.Type).Field("role_id").Unique().Required(), + } +} diff --git a/backend/ent/schema/role.go b/backend/ent/schema/role.go new file mode 100644 index 00000000..80d702a8 --- /dev/null +++ b/backend/ent/schema/role.go @@ -0,0 +1,39 @@ +package schema + +import ( + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/schema" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" +) + +// Role holds the schema definition for the Role entity. +type Role struct { + ent.Schema +} + +func (Role) Annotations() []schema.Annotation { + return []schema.Annotation{ + entsql.Annotation{Table: "roles"}, + } +} + +// Fields of the Role. +func (Role) Fields() []ent.Field { + return []ent.Field{ + field.Int64("id"), + field.String("name"), + field.Text("description"), + field.Time("created_at").Default(time.Now), + } +} + +// Edges of the Role. +func (Role) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("admins", Admin.Type).Through("admin_roles", AdminRole.Type), + } +} diff --git a/backend/ent/schema/user.go b/backend/ent/schema/user.go index 4b851eca..b2dcfb97 100644 --- a/backend/ent/schema/user.go +++ b/backend/ent/schema/user.go @@ -59,5 +59,6 @@ func (User) Edges() []ent.Edge { edge.To("workspace_files", WorkspaceFile.Type), edge.To("api_keys", ApiKey.Type), edge.To("security_scannings", SecurityScanning.Type), + edge.From("groups", UserGroup.Type).Ref("users").Through("user_groups", UserGroupUser.Type), } } diff --git a/backend/ent/schema/usergroup.go b/backend/ent/schema/usergroup.go new file mode 100644 index 00000000..30e20522 --- /dev/null +++ b/backend/ent/schema/usergroup.go @@ -0,0 +1,42 @@ +package schema + +import ( + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/schema" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" + "github.com/google/uuid" +) + +// UserGroup holds the schema definition for the UserGroup entity. +type UserGroup struct { + ent.Schema +} + +func (UserGroup) Annotations() []schema.Annotation { + return []schema.Annotation{ + entsql.Annotation{Table: "user_groups"}, + } +} + +// Fields of the UserGroup. +func (UserGroup) Fields() []ent.Field { + return []ent.Field{ + field.UUID("id", uuid.UUID{}), + field.UUID("admin_id", uuid.UUID{}), + field.String("name").NotEmpty(), + field.Time("created_at").Default(time.Now), + } +} + +// Edges of the UserGroup. +func (UserGroup) Edges() []ent.Edge { + return []ent.Edge{ + edge.From("owner", Admin.Type).Ref("myusergroups").Field("admin_id").Unique().Required(), + edge.To("users", User.Type).Through("user_groups", UserGroupUser.Type), + edge.To("admins", Admin.Type).Through("user_group_admins", UserGroupAdmin.Type), + } +} diff --git a/backend/ent/schema/usergroupadmin.go b/backend/ent/schema/usergroupadmin.go new file mode 100644 index 00000000..8139899d --- /dev/null +++ b/backend/ent/schema/usergroupadmin.go @@ -0,0 +1,47 @@ +package schema + +import ( + "entgo.io/ent" + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/schema" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/index" + "github.com/google/uuid" +) + +// UserGroupAdmin holds the schema definition for the UserGroupAdmin entity. +type UserGroupAdmin struct { + ent.Schema +} + +// Annotations of the UserGroupAdmin. +func (UserGroupAdmin) Annotations() []schema.Annotation { + return []schema.Annotation{ + entsql.Annotation{Table: "user_group_admins"}, + } +} + +// Fields of the UserGroupAdmin. +func (UserGroupAdmin) Fields() []ent.Field { + return []ent.Field{ + field.UUID("id", uuid.UUID{}), + field.UUID("user_group_id", uuid.UUID{}), + field.UUID("admin_id", uuid.UUID{}), + } +} + +// Indexes of the UserGroupAdmin. +func (UserGroupAdmin) Indexes() []ent.Index { + return []ent.Index{ + index.Fields("user_group_id", "admin_id").Unique(), + } +} + +// Edges of the UserGroupAdmin. +func (UserGroupAdmin) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("user_group", UserGroup.Type).Field("user_group_id").Unique().Required(), + edge.To("admin", Admin.Type).Field("admin_id").Unique().Required(), + } +} diff --git a/backend/ent/schema/usergroupuser.go b/backend/ent/schema/usergroupuser.go new file mode 100644 index 00000000..435fed96 --- /dev/null +++ b/backend/ent/schema/usergroupuser.go @@ -0,0 +1,46 @@ +package schema + +import ( + "entgo.io/ent" + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/schema" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/index" + "github.com/google/uuid" +) + +// UserGroupUser holds the schema definition for the UserGroupUser entity. +type UserGroupUser struct { + ent.Schema +} + +// Annotations of the UserGroupUser. +func (UserGroupUser) Annotations() []schema.Annotation { + return []schema.Annotation{ + entsql.Annotation{Table: "user_group_users"}, + } +} + +// Fields of the UserGroupUser. +func (UserGroupUser) Fields() []ent.Field { + return []ent.Field{ + field.UUID("id", uuid.UUID{}), + field.UUID("user_group_id", uuid.UUID{}), + field.UUID("user_id", uuid.UUID{}), + } +} + +func (UserGroupUser) Indexes() []ent.Index { + return []ent.Index{ + index.Fields("user_group_id", "user_id").Unique(), + } +} + +// Edges of the UserGroupUser. +func (UserGroupUser) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("user_group", UserGroup.Type).Field("user_group_id").Unique().Required(), + edge.To("user", User.Type).Field("user_id").Unique().Required(), + } +} diff --git a/backend/errcode/errcode.go b/backend/errcode/errcode.go index ad726896..c527fe33 100644 --- a/backend/errcode/errcode.go +++ b/backend/errcode/errcode.go @@ -22,4 +22,5 @@ var ( ErrDingtalkNotEnabled = web.NewBadRequestErr("err-dingtalk-not-enabled") ErrCustomNotEnabled = web.NewBadRequestErr("err-custom-not-enabled") ErrUserLimit = web.NewBadRequestErr("err-user-limit") + ErrOnlyAdmin = web.NewBadRequestErr("err-only-admin") ) diff --git a/backend/errcode/locale.en.toml b/backend/errcode/locale.en.toml index a4399b2b..d829e6b7 100644 --- a/backend/errcode/locale.en.toml +++ b/backend/errcode/locale.en.toml @@ -10,6 +10,9 @@ other = "User is locked" [err-password] other = "Incorrect password" +[err-only-admin] +other = "Only admin can perform this operation" + [err-invite-code-invalid] other = "Invalid invitation code" diff --git a/backend/errcode/locale.zh.toml b/backend/errcode/locale.zh.toml index 6dab11d5..b5c23ae9 100644 --- a/backend/errcode/locale.zh.toml +++ b/backend/errcode/locale.zh.toml @@ -7,6 +7,9 @@ other = "用户不存在" [err-user-lock] other = "用户已锁定" +[err-only-admin] +other = "仅管理员可操作" + [err-password] other = "密码错误" diff --git a/backend/internal/middleware/auth.go b/backend/internal/middleware/auth.go index 61fc56b7..f877b69b 100644 --- a/backend/internal/middleware/auth.go +++ b/backend/internal/middleware/auth.go @@ -1,6 +1,7 @@ package middleware import ( + "context" "log/slog" "net/http" @@ -8,6 +9,7 @@ import ( "github.com/chaitin/MonkeyCode/backend/consts" "github.com/chaitin/MonkeyCode/backend/domain" + "github.com/chaitin/MonkeyCode/backend/ent/rule" "github.com/chaitin/MonkeyCode/backend/pkg/session" ) @@ -17,12 +19,18 @@ const ( ) type AuthMiddleware struct { + usecase domain.UserUsecase session *session.Session logger *slog.Logger } -func NewAuthMiddleware(session *session.Session, logger *slog.Logger) *AuthMiddleware { +func NewAuthMiddleware( + usecase domain.UserUsecase, + session *session.Session, + logger *slog.Logger, +) *AuthMiddleware { return &AuthMiddleware{ + usecase: usecase, session: session, logger: logger, } @@ -37,6 +45,8 @@ func (m *AuthMiddleware) UserAuth() echo.MiddlewareFunc { return c.String(http.StatusUnauthorized, "Unauthorized") } c.Set(userKey, &user) + ctx := rule.SkipPermission(c.Request().Context()) + c.SetRequest(c.Request().WithContext(ctx)) return next(c) } } @@ -45,12 +55,22 @@ func (m *AuthMiddleware) UserAuth() echo.MiddlewareFunc { func (m *AuthMiddleware) Auth() echo.MiddlewareFunc { return func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { - user, err := session.Get[domain.AdminUser](m.session, c, consts.SessionName) + admin, err := session.Get[domain.AdminUser](m.session, c, consts.SessionName) if err != nil { m.logger.Error("auth failed", "error", err) return c.String(http.StatusUnauthorized, "Unauthorized") } - c.Set(adminKey, &user) + c.Set(adminKey, &admin) + if permissions, err := m.usecase.GetPermissions(c.Request().Context(), admin.ID); err == nil { + ctx := context.WithValue(c.Request().Context(), rule.PermissionKey{}, permissions) + c.SetRequest(c.Request().WithContext(ctx)) + } else { + ctx := context.WithValue(c.Request().Context(), rule.PermissionKey{}, &domain.Permissions{ + AdminID: admin.ID, + IsAdmin: admin.IsAdmin(), + }) + c.SetRequest(c.Request().WithContext(ctx)) + } return next(c) } } diff --git a/backend/internal/middleware/proxy.go b/backend/internal/middleware/proxy.go index ee800df7..702dc08e 100644 --- a/backend/internal/middleware/proxy.go +++ b/backend/internal/middleware/proxy.go @@ -8,6 +8,7 @@ import ( "github.com/labstack/echo/v4" "github.com/chaitin/MonkeyCode/backend/domain" + "github.com/chaitin/MonkeyCode/backend/ent/rule" "github.com/chaitin/MonkeyCode/backend/pkg/logger" ) @@ -45,6 +46,7 @@ func (p *ProxyMiddleware) Auth() echo.MiddlewareFunc { ctx := c.Request().Context() ctx = context.WithValue(ctx, logger.UserIDKey{}, key.UserID) + ctx = rule.SkipPermission(ctx) c.SetRequest(c.Request().WithContext(ctx)) c.Set(ApiContextKey, key) return next(c) diff --git a/backend/internal/model/handler/http/v1/model.go b/backend/internal/model/handler/http/v1/model.go index a49a2e78..7f6a0a12 100644 --- a/backend/internal/model/handler/http/v1/model.go +++ b/backend/internal/model/handler/http/v1/model.go @@ -90,8 +90,6 @@ func (h *ModelHandler) List(c *web.Context) error { // @Success 200 {object} web.Resp{data=[]domain.Model} // @Router /api/v1/model/my [get] func (h *ModelHandler) MyModelList(c *web.Context, req domain.MyModelListReq) error { - user := middleware.GetAdmin(c) - req.UserID = user.ID models, err := h.usecase.MyModelList(c.Request().Context(), &req) if err != nil { return err @@ -111,8 +109,8 @@ func (h *ModelHandler) MyModelList(c *web.Context, req domain.MyModelListReq) er // @Success 200 {object} web.Resp{data=domain.Model} // @Router /api/v1/model [post] func (h *ModelHandler) Create(c *web.Context, req domain.CreateModelReq) error { - user := middleware.GetAdmin(c) - req.UserID = user.ID + admin := middleware.GetAdmin(c) + req.AdminID = admin.ID req.APIBase = strings.TrimSuffix(req.APIBase, "/") m, err := h.usecase.Create(c.Request().Context(), &req) if err != nil { diff --git a/backend/internal/model/repo/model.go b/backend/internal/model/repo/model.go index 12435c09..50c0fd96 100644 --- a/backend/internal/model/repo/model.go +++ b/backend/internal/model/repo/model.go @@ -48,11 +48,6 @@ func (r *ModelRepo) GetWithCache(ctx context.Context, modelType consts.ModelType } func (r *ModelRepo) Create(ctx context.Context, m *domain.CreateModelReq) (*db.Model, error) { - uid, err := uuid.Parse(m.UserID) - if err != nil { - return nil, err - } - n, err := r.db.Model.Query().Where(model.ModelType(m.ModelType)).Count(ctx) if err != nil { return nil, err @@ -64,7 +59,7 @@ func (r *ModelRepo) Create(ctx context.Context, m *domain.CreateModelReq) (*db.M r.cache.Delete(string(m.ModelType)) create := r.db.Model.Create(). - SetUserID(uid). + SetUserID(m.AdminID). SetShowName(m.ShowName). SetModelName(m.ModelName). SetProvider(m.Provider). diff --git a/backend/internal/proxy/usecase/proxy.go b/backend/internal/proxy/usecase/proxy.go index 5a13c950..4970ce9b 100644 --- a/backend/internal/proxy/usecase/proxy.go +++ b/backend/internal/proxy/usecase/proxy.go @@ -15,6 +15,7 @@ import ( "github.com/chaitin/MonkeyCode/backend/consts" "github.com/chaitin/MonkeyCode/backend/db" "github.com/chaitin/MonkeyCode/backend/domain" + "github.com/chaitin/MonkeyCode/backend/ent/rule" "github.com/chaitin/MonkeyCode/backend/pkg/cvt" "github.com/chaitin/MonkeyCode/backend/pkg/queuerunner" "github.com/chaitin/MonkeyCode/backend/pkg/request" @@ -69,7 +70,7 @@ func (p *ProxyUsecase) requeue() { p.queuerunner.Enqueue(context.Background(), scanning.ID.String(), domain.CreateSecurityScanningReq{ UserID: scanning.UserID.String(), Workspace: scanning.Workspace, - Language: consts.SecurityScanningLanguage(scanning.Rule), + Language: scanning.Language, }, p.TaskHandle) } } @@ -121,6 +122,7 @@ func (p *ProxyUsecase) CreateSecurityScanning(ctx context.Context, req *domain.C } func (p *ProxyUsecase) TaskHandle(ctx context.Context, task *queuerunner.Task[domain.CreateSecurityScanningReq]) error { + ctx = rule.SkipPermission(ctx) id := task.ID if err := p.securityRepo.Update(ctx, id, nil, consts.SecurityScanningStatusRunning, nil); err != nil { p.logger.With("id", task.ID).With("error", err).ErrorContext(ctx, "failed to update security scanning") diff --git a/backend/internal/security/repo/security.go b/backend/internal/security/repo/security.go index 902c31c8..994716fa 100644 --- a/backend/internal/security/repo/security.go +++ b/backend/internal/security/repo/security.go @@ -15,6 +15,7 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/workspace" "github.com/chaitin/MonkeyCode/backend/db/workspacefile" "github.com/chaitin/MonkeyCode/backend/domain" + "github.com/chaitin/MonkeyCode/backend/ent/rule" "github.com/chaitin/MonkeyCode/backend/ent/types" "github.com/chaitin/MonkeyCode/backend/pkg/cvt" "github.com/chaitin/MonkeyCode/backend/pkg/entx" @@ -193,7 +194,7 @@ func (s *SecurityScanningRepo) ListBrief(ctx context.Context, req domain.ListSec scannings, p, err := query. Order(securityscanning.ByCreatedAt(sql.OrderDesc())). - Page(context.Background(), int(req.Page), int(req.Size)) + Page(ctx, int(req.Page), int(req.Size)) if err != nil { return nil, err @@ -267,6 +268,7 @@ func (s *SecurityScanningRepo) RiskCountByIDs(ctx context.Context, ids []uuid.UU // AllRunning implements domain.SecurityScanningRepo. func (s *SecurityScanningRepo) AllRunning(ctx context.Context) ([]*db.SecurityScanning, error) { + ctx = rule.SkipPermission(ctx) return s.db.SecurityScanning.Query(). Where(securityscanning.Status(consts.SecurityScanningStatusRunning)). Order(securityscanning.ByCreatedAt(sql.OrderAsc())). diff --git a/backend/internal/user/handler/v1/user.go b/backend/internal/user/handler/v1/user.go index a157f121..f80310eb 100644 --- a/backend/internal/user/handler/v1/user.go +++ b/backend/internal/user/handler/v1/user.go @@ -79,6 +79,7 @@ func NewUserHandler( admin := w.Group("/api/v1/admin") admin.POST("/login", web.BindHandler(u.AdminLogin)) admin.GET("/setting", web.BaseHandler(u.GetSetting)) + admin.GET("/role", web.BaseHandler(u.ListRole)) admin.Use(auth.Auth(), active.Active("admin"), readonly.Guard()) admin.GET("/profile", web.BaseHandler(u.AdminProfile)) @@ -89,6 +90,7 @@ func NewUserHandler( admin.POST("/logout", web.BaseHandler(u.AdminLogout)) admin.DELETE("/delete", web.BaseHandler(u.DeleteAdmin)) admin.GET("/export-completion-data", web.BaseHandler(u.ExportCompletionData)) + admin.POST("/role", web.BindHandler(u.GrantRole)) // user g := w.Group("/api/v1/user") @@ -439,7 +441,7 @@ func (h *UserHandler) LoginHistory(c *web.Context) error { // @Success 200 {object} web.Resp{data=domain.InviteResp} // @Router /api/v1/user/invite [get] func (h *UserHandler) Invite(c *web.Context) error { - user := middleware.GetAdmin(c) + admin := middleware.GetAdmin(c) edition := c.Get("edition") if edition == nil { @@ -457,7 +459,7 @@ func (h *UserHandler) Invite(c *web.Context) error { } } - resp, err := h.usecase.Invite(c.Request().Context(), user.ID) + resp, err := h.usecase.Invite(c.Request().Context(), admin.ID.String()) if err != nil { return err } @@ -545,6 +547,42 @@ func (h *UserHandler) AdminLoginHistory(c *web.Context) error { return c.Success(resp) } +// ListRole 获取系统角色列表 +// +// @Tags Admin +// @Summary 获取角色列表 +// @Description 获取角色列表 +// @ID list-role +// @Accept json +// @Produce json +// @Success 200 {object} web.Resp{data=[]domain.Role} +// @Router /api/v1/admin/role [get] +func (h *UserHandler) ListRole(c *web.Context) error { + roles, err := h.usecase.ListRole(c.Request().Context()) + if err != nil { + return err + } + return c.Success(roles) +} + +// GrantRole 授权角色 +// +// @Tags Admin +// @Summary 授权角色 +// @Description 授权角色 +// @ID grant-role +// @Accept json +// @Produce json +// @Param param body domain.GrantRoleReq true "授权角色参数" +// @Success 200 {object} web.Resp +// @Router /api/v1/admin/role [post] +func (h *UserHandler) GrantRole(c *web.Context, req domain.GrantRoleReq) error { + if err := h.usecase.GrantRole(c.Request().Context(), &req); err != nil { + return err + } + return c.Success(nil) +} + // GetSetting 获取系统设置 // // @Tags Admin diff --git a/backend/internal/user/repo/user.go b/backend/internal/user/repo/user.go index b29db674..061d801b 100644 --- a/backend/internal/user/repo/user.go +++ b/backend/internal/user/repo/user.go @@ -8,24 +8,29 @@ import ( "time" "entgo.io/ent/dialect/sql" + "github.com/GoYoko/web" "github.com/google/uuid" + "github.com/patrickmn/go-cache" "github.com/redis/go-redis/v9" - "github.com/GoYoko/web" - "github.com/chaitin/MonkeyCode/backend/config" "github.com/chaitin/MonkeyCode/backend/consts" "github.com/chaitin/MonkeyCode/backend/db" "github.com/chaitin/MonkeyCode/backend/db/admin" "github.com/chaitin/MonkeyCode/backend/db/adminloginhistory" + "github.com/chaitin/MonkeyCode/backend/db/adminrole" "github.com/chaitin/MonkeyCode/backend/db/apikey" "github.com/chaitin/MonkeyCode/backend/db/invitecode" "github.com/chaitin/MonkeyCode/backend/db/model" "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/usergroup" + "github.com/chaitin/MonkeyCode/backend/db/usergroupadmin" "github.com/chaitin/MonkeyCode/backend/db/useridentity" "github.com/chaitin/MonkeyCode/backend/db/userloginhistory" "github.com/chaitin/MonkeyCode/backend/domain" + "github.com/chaitin/MonkeyCode/backend/ent/rule" "github.com/chaitin/MonkeyCode/backend/errcode" + "github.com/chaitin/MonkeyCode/backend/pkg/cvt" "github.com/chaitin/MonkeyCode/backend/pkg/entx" "github.com/chaitin/MonkeyCode/backend/pkg/ipdb" ) @@ -35,6 +40,7 @@ type UserRepo struct { ipdb *ipdb.IPDB redis *redis.Client cfg *config.Config + cache *cache.Cache } func NewUserRepo( @@ -43,7 +49,8 @@ func NewUserRepo( redis *redis.Client, cfg *config.Config, ) domain.UserRepo { - return &UserRepo{db: db, ipdb: ipdb, redis: redis, cfg: cfg} + cache := cache.New(5*time.Minute, 10*time.Minute) + return &UserRepo{db: db, ipdb: ipdb, redis: redis, cfg: cfg, cache: cache} } func (r *UserRepo) InitAdmin(ctx context.Context, username, password string) error { @@ -53,7 +60,7 @@ func (r *UserRepo) InitAdmin(ctx context.Context, username, password string) err Username: username, Password: password, Status: consts.AdminStatusActive, - }) + }, 1) } if err != nil { return err @@ -61,12 +68,21 @@ func (r *UserRepo) InitAdmin(ctx context.Context, username, password string) err return nil } -func (r *UserRepo) CreateAdmin(ctx context.Context, admin *db.Admin) (*db.Admin, error) { - return r.db.Admin.Create(). - SetUsername(admin.Username). - SetPassword(admin.Password). - SetStatus(admin.Status). - Save(ctx) +func (r *UserRepo) CreateAdmin(ctx context.Context, admin *db.Admin, roleID int64) (*db.Admin, error) { + var a *db.Admin + err := entx.WithTx(ctx, r.db, func(tx *db.Tx) error { + new, err := r.db.Admin.Create(). + SetUsername(admin.Username). + SetPassword(admin.Password). + SetStatus(admin.Status). + Save(ctx) + if err != nil { + return err + } + a = new + return tx.AdminRole.Create().SetAdminID(new.ID).SetRoleID(roleID).Exec(ctx) + }) + return a, err } func (r *UserRepo) AdminByName(ctx context.Context, username string) (*db.Admin, error) { @@ -168,7 +184,7 @@ func (r *UserRepo) CreateInviteCode(ctx context.Context, userID string, code str } func (r *UserRepo) AdminList(ctx context.Context, page *web.Pagination) ([]*db.Admin, *db.PageInfo, error) { - q := r.db.Admin.Query().Order(admin.ByCreatedAt(sql.OrderDesc())) + q := r.db.Admin.Query().WithRoles().Order(admin.ByCreatedAt(sql.OrderDesc())) return q.Page(ctx, page.Page, page.Size) } @@ -611,3 +627,80 @@ func (r *UserRepo) GetUserCount(ctx context.Context) (int64, error) { } return int64(count), nil } + +func (r *UserRepo) GetPermissions(ctx context.Context, id uuid.UUID) (*domain.Permissions, error) { + key := fmt.Sprintf("user_permissions:%s", id.String()) + if cached, found := r.cache.Get(key); found { + return cached.(*domain.Permissions), nil + } + + admin, err := r.db.Admin.Query(). + WithRoles(). + Where(admin.ID(id)). + First(ctx) + if err != nil { + return nil, err + } + + ctx = rule.SkipPermission(ctx) + usergroups, err := r.db.UserGroup.Query(). + WithUsers(). + Where(usergroup.Or( + usergroup.AdminID(id), + usergroup.HasUserGroupAdminsWith(usergroupadmin.AdminID(id)), + )). + All(ctx) + if err != nil { + return nil, err + } + res := &domain.Permissions{ + AdminID: admin.ID, + IsAdmin: admin.Username == "admin", + } + for _, ug := range usergroups { + res.GroupIDs = append(res.GroupIDs, ug.ID) + for _, u := range ug.Edges.Users { + res.UserIDs = append(res.UserIDs, u.ID) + } + } + res.UserIDs = cvt.Unique(res.UserIDs) + res.GroupIDs = cvt.Unique(res.GroupIDs) + + for _, r := range admin.Edges.Roles { + if r.ID == 1 { + res.IsAdmin = true + } + res.Roles = append(res.Roles, cvt.From(r, &domain.Role{})) + } + + r.cache.Set(key, res, 5*time.Minute) + return res, nil +} + +func (r *UserRepo) ListRole(ctx context.Context) ([]*db.Role, error) { + return r.db.Role.Query().All(ctx) +} + +func (r *UserRepo) GrantRole(ctx context.Context, req *domain.GrantRoleReq) error { + return entx.WithTx(ctx, r.db, func(tx *db.Tx) error { + if _, err := tx.AdminRole.Delete(). + Where(adminrole.AdminID(req.AdminID)). + Exec(ctx); err != nil { + return err + } + for _, rid := range req.RoleIDs { + if err := tx.AdminRole.Create(). + SetAdminID(req.AdminID). + SetRoleID(rid). + Exec(ctx); err != nil { + return err + } + } + return nil + }) +} + +func (r *UserRepo) CleanPermissionCache(ctx context.Context, id uuid.UUID) { + key := fmt.Sprintf("user_permissions:%s", id.String()) + r.cache.Delete(key) +} diff --git a/backend/internal/user/usecase/user.go b/backend/internal/user/usecase/user.go index 5b3ab6b5..7fc6c8c2 100644 --- a/backend/internal/user/usecase/user.go +++ b/backend/internal/user/usecase/user.go @@ -308,12 +308,12 @@ func (u *UserUsecase) CreateAdmin(ctx context.Context, req *domain.CreateAdminRe Username: req.Username, Password: string(hash), } - n, err := u.repo.CreateAdmin(ctx, admin) + n, err := u.repo.CreateAdmin(ctx, admin, req.RoleID) if err != nil { return nil, err } return &domain.AdminUser{ - ID: n.ID.String(), + ID: n.ID, Username: n.Username, CreatedAt: n.CreatedAt.Unix(), }, nil @@ -690,3 +690,21 @@ func (u *UserUsecase) ExportCompletionData(ctx context.Context) (*domain.ExportC func (u *UserUsecase) GetUserCount(ctx context.Context) (int64, error) { return u.repo.GetUserCount(ctx) } + +func (u *UserUsecase) GetPermissions(ctx context.Context, id uuid.UUID) (*domain.Permissions, error) { + return u.repo.GetPermissions(ctx, id) +} + +func (u *UserUsecase) ListRole(ctx context.Context) ([]*domain.Role, error) { + roles, err := u.repo.ListRole(ctx) + if err != nil { + return nil, err + } + return cvt.Iter(roles, func(i int, role *db.Role) *domain.Role { + return cvt.From(role, &domain.Role{}) + }), nil +} + +func (u *UserUsecase) GrantRole(ctx context.Context, req *domain.GrantRoleReq) error { + return u.repo.GrantRole(ctx, req) +} diff --git a/backend/migration/000018_create_user_group_table.down.sql b/backend/migration/000018_create_user_group_table.down.sql new file mode 100644 index 00000000..e69de29b diff --git a/backend/migration/000018_create_user_group_table.up.sql b/backend/migration/000018_create_user_group_table.up.sql new file mode 100644 index 00000000..47f2fd2f --- /dev/null +++ b/backend/migration/000018_create_user_group_table.up.sql @@ -0,0 +1,55 @@ +CREATE TABLE IF NOT EXISTS user_groups ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + admin_id UUID NOT NULL, + name VARCHAR(255) NOT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); + +CREATE UNIQUE INDEX IF NOT EXISTS idx_user_groups_admin_id_name ON user_groups (admin_id, name); + +CREATE TABLE IF NOT EXISTS user_group_users ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_group_id UUID NOT NULL, + user_id UUID NOT NULL, + FOREIGN KEY (user_group_id) REFERENCES user_groups (id) ON DELETE CASCADE, + FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE +); + +CREATE UNIQUE INDEX IF NOT EXISTS idx_user_group_users_user_group_id_user_id ON user_group_users (user_group_id, user_id); + +CREATE TABLE IF NOT EXISTS user_group_admins ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_group_id UUID NOT NULL, + admin_id UUID NOT NULL, + FOREIGN KEY (user_group_id) REFERENCES user_groups (id) ON DELETE CASCADE, + FOREIGN KEY (admin_id) REFERENCES admins (id) ON DELETE CASCADE +); + +CREATE UNIQUE INDEX IF NOT EXISTS idx_user_group_admins_user_group_id_admin_id ON user_group_admins (user_group_id, admin_id); + +CREATE TABLE IF NOT EXISTS roles ( + id BIGSERIAL PRIMARY KEY, + name VARCHAR(255) NOT NULL, + description TEXT, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); + +CREATE UNIQUE INDEX IF NOT EXISTS idx_roles_name ON roles (name); + +CREATE TABLE IF NOT EXISTS admin_roles ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + admin_id UUID NOT NULL, + role_id BIGINT NOT NULL, + FOREIGN KEY (admin_id) REFERENCES admins (id) ON DELETE CASCADE, + FOREIGN KEY (role_id) REFERENCES roles (id) ON DELETE CASCADE +); + +INSERT INTO roles (id, name, description) VALUES + (1, '超级管理员', '具有所有权限'), + (2, '普通管理员', '管理组内成员的权限') +ON CONFLICT (id) DO NOTHING; + +INSERT INTO admin_roles (admin_id, role_id) +SELECT a.id, 1 +FROM admins a +ON CONFLICT DO NOTHING; \ No newline at end of file diff --git a/backend/pro b/backend/pro index d31a906d..6fc2307d 160000 --- a/backend/pro +++ b/backend/pro @@ -1 +1 @@ -Subproject commit d31a906d45eec449e3b2c7bb00ba1bc1ac2b1ee1 +Subproject commit 6fc2307dbf9348b868375a951baae6c1ede485de diff --git a/ui/Makefile b/ui/Makefile index 59557ef0..f74ddac4 100644 --- a/ui/Makefile +++ b/ui/Makefile @@ -1,7 +1,7 @@ PLATFORM=linux/amd64 TAG=main -REGISTRY=monkeycode - +REGISTRY=monkeycode.chaitin.cn/monkeycode +OUTPUT=type=docker,dest=${HOME}/tmp/monkeycode_frontend.tar # 构建前端代码 build: @@ -13,9 +13,5 @@ image: build -f .Dockerfile \ --platform ${PLATFORM} \ --tag ${REGISTRY}/frontend:${TAG} \ - --load \ + --output ${OUTPUT} \ . - -save: image - docker save -o /tmp/monkeycode_frontend.tar monkeycode/frontend:main - \ No newline at end of file