diff --git a/db/ent/client.go b/db/ent/client.go index 77d4ace..d41392e 100644 --- a/db/ent/client.go +++ b/db/ent/client.go @@ -17,6 +17,7 @@ import ( "github.com/xmdhs/authlib-skin/db/ent/texture" "github.com/xmdhs/authlib-skin/db/ent/user" "github.com/xmdhs/authlib-skin/db/ent/userprofile" + "github.com/xmdhs/authlib-skin/db/ent/usertexture" "github.com/xmdhs/authlib-skin/db/ent/usertoken" ) @@ -31,6 +32,8 @@ type Client struct { User *UserClient // UserProfile is the client for interacting with the UserProfile builders. UserProfile *UserProfileClient + // UserTexture is the client for interacting with the UserTexture builders. + UserTexture *UserTextureClient // UserToken is the client for interacting with the UserToken builders. UserToken *UserTokenClient } @@ -49,6 +52,7 @@ func (c *Client) init() { c.Texture = NewTextureClient(c.config) c.User = NewUserClient(c.config) c.UserProfile = NewUserProfileClient(c.config) + c.UserTexture = NewUserTextureClient(c.config) c.UserToken = NewUserTokenClient(c.config) } @@ -135,6 +139,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { Texture: NewTextureClient(cfg), User: NewUserClient(cfg), UserProfile: NewUserProfileClient(cfg), + UserTexture: NewUserTextureClient(cfg), UserToken: NewUserTokenClient(cfg), }, nil } @@ -158,6 +163,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) Texture: NewTextureClient(cfg), User: NewUserClient(cfg), UserProfile: NewUserProfileClient(cfg), + UserTexture: NewUserTextureClient(cfg), UserToken: NewUserTokenClient(cfg), }, nil } @@ -190,6 +196,7 @@ func (c *Client) Use(hooks ...Hook) { c.Texture.Use(hooks...) c.User.Use(hooks...) c.UserProfile.Use(hooks...) + c.UserTexture.Use(hooks...) c.UserToken.Use(hooks...) } @@ -199,6 +206,7 @@ func (c *Client) Intercept(interceptors ...Interceptor) { c.Texture.Intercept(interceptors...) c.User.Intercept(interceptors...) c.UserProfile.Intercept(interceptors...) + c.UserTexture.Intercept(interceptors...) c.UserToken.Intercept(interceptors...) } @@ -211,6 +219,8 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { return c.User.mutate(ctx, m) case *UserProfileMutation: return c.UserProfile.mutate(ctx, m) + case *UserTextureMutation: + return c.UserTexture.mutate(ctx, m) case *UserTokenMutation: return c.UserToken.mutate(ctx, m) default: @@ -335,7 +345,23 @@ func (c *TextureClient) QueryUser(t *Texture) *UserProfileQuery { step := sqlgraph.NewStep( sqlgraph.From(texture.Table, texture.FieldID, id), sqlgraph.To(userprofile.Table, userprofile.FieldID), - sqlgraph.Edge(sqlgraph.M2O, true, texture.UserTable, texture.UserColumn), + sqlgraph.Edge(sqlgraph.M2M, true, texture.UserTable, texture.UserPrimaryKey...), + ) + fromV = sqlgraph.Neighbors(t.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryUsertexture queries the usertexture edge of a Texture. +func (c *TextureClient) QueryUsertexture(t *Texture) *UserTextureQuery { + query := (&UserTextureClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := t.ID + step := sqlgraph.NewStep( + sqlgraph.From(texture.Table, texture.FieldID, id), + sqlgraph.To(usertexture.Table, usertexture.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, texture.UsertextureTable, texture.UsertextureColumn), ) fromV = sqlgraph.Neighbors(t.driver.Dialect(), step) return fromV, nil @@ -651,7 +677,23 @@ func (c *UserProfileClient) QueryTexture(up *UserProfile) *TextureQuery { step := sqlgraph.NewStep( sqlgraph.From(userprofile.Table, userprofile.FieldID, id), sqlgraph.To(texture.Table, texture.FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, userprofile.TextureTable, userprofile.TextureColumn), + sqlgraph.Edge(sqlgraph.M2M, false, userprofile.TextureTable, userprofile.TexturePrimaryKey...), + ) + fromV = sqlgraph.Neighbors(up.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryUsertexture queries the usertexture edge of a UserProfile. +func (c *UserProfileClient) QueryUsertexture(up *UserProfile) *UserTextureQuery { + query := (&UserTextureClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := up.ID + step := sqlgraph.NewStep( + sqlgraph.From(userprofile.Table, userprofile.FieldID, id), + sqlgraph.To(usertexture.Table, usertexture.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, userprofile.UsertextureTable, userprofile.UsertextureColumn), ) fromV = sqlgraph.Neighbors(up.driver.Dialect(), step) return fromV, nil @@ -684,6 +726,156 @@ func (c *UserProfileClient) mutate(ctx context.Context, m *UserProfileMutation) } } +// UserTextureClient is a client for the UserTexture schema. +type UserTextureClient struct { + config +} + +// NewUserTextureClient returns a client for the UserTexture from the given config. +func NewUserTextureClient(c config) *UserTextureClient { + return &UserTextureClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `usertexture.Hooks(f(g(h())))`. +func (c *UserTextureClient) Use(hooks ...Hook) { + c.hooks.UserTexture = append(c.hooks.UserTexture, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `usertexture.Intercept(f(g(h())))`. +func (c *UserTextureClient) Intercept(interceptors ...Interceptor) { + c.inters.UserTexture = append(c.inters.UserTexture, interceptors...) +} + +// Create returns a builder for creating a UserTexture entity. +func (c *UserTextureClient) Create() *UserTextureCreate { + mutation := newUserTextureMutation(c.config, OpCreate) + return &UserTextureCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of UserTexture entities. +func (c *UserTextureClient) CreateBulk(builders ...*UserTextureCreate) *UserTextureCreateBulk { + return &UserTextureCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for UserTexture. +func (c *UserTextureClient) Update() *UserTextureUpdate { + mutation := newUserTextureMutation(c.config, OpUpdate) + return &UserTextureUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *UserTextureClient) UpdateOne(ut *UserTexture) *UserTextureUpdateOne { + mutation := newUserTextureMutation(c.config, OpUpdateOne, withUserTexture(ut)) + return &UserTextureUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *UserTextureClient) UpdateOneID(id int) *UserTextureUpdateOne { + mutation := newUserTextureMutation(c.config, OpUpdateOne, withUserTextureID(id)) + return &UserTextureUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for UserTexture. +func (c *UserTextureClient) Delete() *UserTextureDelete { + mutation := newUserTextureMutation(c.config, OpDelete) + return &UserTextureDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *UserTextureClient) DeleteOne(ut *UserTexture) *UserTextureDeleteOne { + return c.DeleteOneID(ut.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *UserTextureClient) DeleteOneID(id int) *UserTextureDeleteOne { + builder := c.Delete().Where(usertexture.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &UserTextureDeleteOne{builder} +} + +// Query returns a query builder for UserTexture. +func (c *UserTextureClient) Query() *UserTextureQuery { + return &UserTextureQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeUserTexture}, + inters: c.Interceptors(), + } +} + +// Get returns a UserTexture entity by its id. +func (c *UserTextureClient) Get(ctx context.Context, id int) (*UserTexture, error) { + return c.Query().Where(usertexture.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *UserTextureClient) GetX(ctx context.Context, id int) *UserTexture { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryUserProfile queries the user_profile edge of a UserTexture. +func (c *UserTextureClient) QueryUserProfile(ut *UserTexture) *UserProfileQuery { + query := (&UserProfileClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := ut.ID + step := sqlgraph.NewStep( + sqlgraph.From(usertexture.Table, usertexture.FieldID, id), + sqlgraph.To(userprofile.Table, userprofile.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, usertexture.UserProfileTable, usertexture.UserProfileColumn), + ) + fromV = sqlgraph.Neighbors(ut.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryTexture queries the texture edge of a UserTexture. +func (c *UserTextureClient) QueryTexture(ut *UserTexture) *TextureQuery { + query := (&TextureClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := ut.ID + step := sqlgraph.NewStep( + sqlgraph.From(usertexture.Table, usertexture.FieldID, id), + sqlgraph.To(texture.Table, texture.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, usertexture.TextureTable, usertexture.TextureColumn), + ) + fromV = sqlgraph.Neighbors(ut.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *UserTextureClient) Hooks() []Hook { + return c.hooks.UserTexture +} + +// Interceptors returns the client interceptors. +func (c *UserTextureClient) Interceptors() []Interceptor { + return c.inters.UserTexture +} + +func (c *UserTextureClient) mutate(ctx context.Context, m *UserTextureMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&UserTextureCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&UserTextureUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&UserTextureUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&UserTextureDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown UserTexture mutation op: %q", m.Op()) + } +} + // UserTokenClient is a client for the UserToken schema. type UserTokenClient struct { config @@ -821,9 +1013,9 @@ func (c *UserTokenClient) mutate(ctx context.Context, m *UserTokenMutation) (Val // hooks and interceptors per client, for fast access. type ( hooks struct { - Texture, User, UserProfile, UserToken []ent.Hook + Texture, User, UserProfile, UserTexture, UserToken []ent.Hook } inters struct { - Texture, User, UserProfile, UserToken []ent.Interceptor + Texture, User, UserProfile, UserTexture, UserToken []ent.Interceptor } ) diff --git a/db/ent/ent.go b/db/ent/ent.go index 991f663..8ef748e 100644 --- a/db/ent/ent.go +++ b/db/ent/ent.go @@ -15,6 +15,7 @@ import ( "github.com/xmdhs/authlib-skin/db/ent/texture" "github.com/xmdhs/authlib-skin/db/ent/user" "github.com/xmdhs/authlib-skin/db/ent/userprofile" + "github.com/xmdhs/authlib-skin/db/ent/usertexture" "github.com/xmdhs/authlib-skin/db/ent/usertoken" ) @@ -79,6 +80,7 @@ func checkColumn(table, column string) error { texture.Table: texture.ValidColumn, user.Table: user.ValidColumn, userprofile.Table: userprofile.ValidColumn, + usertexture.Table: usertexture.ValidColumn, usertoken.Table: usertoken.ValidColumn, }) }) diff --git a/db/ent/hook/hook.go b/db/ent/hook/hook.go index df736b9..b19ae4a 100644 --- a/db/ent/hook/hook.go +++ b/db/ent/hook/hook.go @@ -45,6 +45,18 @@ func (f UserProfileFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.UserProfileMutation", m) } +// The UserTextureFunc type is an adapter to allow the use of ordinary +// function as UserTexture mutator. +type UserTextureFunc func(context.Context, *ent.UserTextureMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f UserTextureFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.UserTextureMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.UserTextureMutation", m) +} + // The UserTokenFunc type is an adapter to allow the use of ordinary // function as UserToken mutator. type UserTokenFunc func(context.Context, *ent.UserTokenMutation) (ent.Value, error) diff --git a/db/ent/migrate/schema.go b/db/ent/migrate/schema.go index 5b7f42a..d88eac5 100644 --- a/db/ent/migrate/schema.go +++ b/db/ent/migrate/schema.go @@ -15,7 +15,6 @@ var ( {Name: "type", Type: field.TypeString, SchemaType: map[string]string{"mysql": "VARCHAR(10)"}}, {Name: "variant", Type: field.TypeString, SchemaType: map[string]string{"mysql": "VARCHAR(10)"}}, {Name: "texture_created_user", Type: field.TypeInt}, - {Name: "user_profile_texture", Type: field.TypeInt}, } // TexturesTable holds the schema information for the "textures" table. TexturesTable = &schema.Table{ @@ -29,19 +28,6 @@ var ( RefColumns: []*schema.Column{UsersColumns[0]}, OnDelete: schema.NoAction, }, - { - Symbol: "textures_user_profiles_texture", - Columns: []*schema.Column{TexturesColumns[5]}, - RefColumns: []*schema.Column{UserProfilesColumns[0]}, - OnDelete: schema.NoAction, - }, - }, - Indexes: []*schema.Index{ - { - Name: "texture_user_profile_texture", - Unique: false, - Columns: []*schema.Column{TexturesColumns[5]}, - }, }, } // UsersColumns holds the columns for the "users" table. @@ -100,6 +86,49 @@ var ( }, }, } + // UserTexturesColumns holds the columns for the "user_textures" table. + UserTexturesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "user_profile_id", Type: field.TypeInt}, + {Name: "texture_id", Type: field.TypeInt}, + } + // UserTexturesTable holds the schema information for the "user_textures" table. + UserTexturesTable = &schema.Table{ + Name: "user_textures", + Columns: UserTexturesColumns, + PrimaryKey: []*schema.Column{UserTexturesColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "user_textures_user_profiles_user_profile", + Columns: []*schema.Column{UserTexturesColumns[1]}, + RefColumns: []*schema.Column{UserProfilesColumns[0]}, + OnDelete: schema.NoAction, + }, + { + Symbol: "user_textures_textures_texture", + Columns: []*schema.Column{UserTexturesColumns[2]}, + RefColumns: []*schema.Column{TexturesColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + Indexes: []*schema.Index{ + { + Name: "usertexture_user_profile_id", + Unique: false, + Columns: []*schema.Column{UserTexturesColumns[1]}, + }, + { + Name: "usertexture_texture_id", + Unique: false, + Columns: []*schema.Column{UserTexturesColumns[2]}, + }, + { + Name: "usertexture_user_profile_id_texture_id", + Unique: true, + Columns: []*schema.Column{UserTexturesColumns[1], UserTexturesColumns[2]}, + }, + }, + } // UserTokensColumns holds the columns for the "user_tokens" table. UserTokensColumns = []*schema.Column{ {Name: "id", Type: field.TypeInt, Increment: true}, @@ -132,13 +161,15 @@ var ( TexturesTable, UsersTable, UserProfilesTable, + UserTexturesTable, UserTokensTable, } ) func init() { TexturesTable.ForeignKeys[0].RefTable = UsersTable - TexturesTable.ForeignKeys[1].RefTable = UserProfilesTable UserProfilesTable.ForeignKeys[0].RefTable = UsersTable + UserTexturesTable.ForeignKeys[0].RefTable = UserProfilesTable + UserTexturesTable.ForeignKeys[1].RefTable = TexturesTable UserTokensTable.ForeignKeys[0].RefTable = UsersTable } diff --git a/db/ent/mutation.go b/db/ent/mutation.go index 17fcbde..8c7d5b5 100644 --- a/db/ent/mutation.go +++ b/db/ent/mutation.go @@ -14,6 +14,7 @@ import ( "github.com/xmdhs/authlib-skin/db/ent/texture" "github.com/xmdhs/authlib-skin/db/ent/user" "github.com/xmdhs/authlib-skin/db/ent/userprofile" + "github.com/xmdhs/authlib-skin/db/ent/usertexture" "github.com/xmdhs/authlib-skin/db/ent/usertoken" ) @@ -29,6 +30,7 @@ const ( TypeTexture = "Texture" TypeUser = "User" TypeUserProfile = "UserProfile" + TypeUserTexture = "UserTexture" TypeUserToken = "UserToken" ) @@ -44,8 +46,12 @@ type TextureMutation struct { clearedFields map[string]struct{} created_user *int clearedcreated_user bool - user *int + user map[int]struct{} + removeduser map[int]struct{} cleareduser bool + usertexture map[int]struct{} + removedusertexture map[int]struct{} + clearedusertexture bool done bool oldValue func(context.Context) (*Texture, error) predicates []predicate.Texture @@ -296,9 +302,14 @@ func (m *TextureMutation) ResetCreatedUser() { m.clearedcreated_user = false } -// SetUserID sets the "user" edge to the UserProfile entity by id. -func (m *TextureMutation) SetUserID(id int) { - m.user = &id +// AddUserIDs adds the "user" edge to the UserProfile entity by ids. +func (m *TextureMutation) AddUserIDs(ids ...int) { + if m.user == nil { + m.user = make(map[int]struct{}) + } + for i := range ids { + m.user[ids[i]] = struct{}{} + } } // ClearUser clears the "user" edge to the UserProfile entity. @@ -311,20 +322,29 @@ func (m *TextureMutation) UserCleared() bool { return m.cleareduser } -// UserID returns the "user" edge ID in the mutation. -func (m *TextureMutation) UserID() (id int, exists bool) { - if m.user != nil { - return *m.user, true +// RemoveUserIDs removes the "user" edge to the UserProfile entity by IDs. +func (m *TextureMutation) RemoveUserIDs(ids ...int) { + if m.removeduser == nil { + m.removeduser = make(map[int]struct{}) + } + for i := range ids { + delete(m.user, ids[i]) + m.removeduser[ids[i]] = struct{}{} + } +} + +// RemovedUser returns the removed IDs of the "user" edge to the UserProfile entity. +func (m *TextureMutation) RemovedUserIDs() (ids []int) { + for id := range m.removeduser { + ids = append(ids, id) } return } // 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 *TextureMutation) UserIDs() (ids []int) { - if id := m.user; id != nil { - ids = append(ids, *id) + for id := range m.user { + ids = append(ids, id) } return } @@ -333,6 +353,61 @@ func (m *TextureMutation) UserIDs() (ids []int) { func (m *TextureMutation) ResetUser() { m.user = nil m.cleareduser = false + m.removeduser = nil +} + +// AddUsertextureIDs adds the "usertexture" edge to the UserTexture entity by ids. +func (m *TextureMutation) AddUsertextureIDs(ids ...int) { + if m.usertexture == nil { + m.usertexture = make(map[int]struct{}) + } + for i := range ids { + m.usertexture[ids[i]] = struct{}{} + } +} + +// ClearUsertexture clears the "usertexture" edge to the UserTexture entity. +func (m *TextureMutation) ClearUsertexture() { + m.clearedusertexture = true +} + +// UsertextureCleared reports if the "usertexture" edge to the UserTexture entity was cleared. +func (m *TextureMutation) UsertextureCleared() bool { + return m.clearedusertexture +} + +// RemoveUsertextureIDs removes the "usertexture" edge to the UserTexture entity by IDs. +func (m *TextureMutation) RemoveUsertextureIDs(ids ...int) { + if m.removedusertexture == nil { + m.removedusertexture = make(map[int]struct{}) + } + for i := range ids { + delete(m.usertexture, ids[i]) + m.removedusertexture[ids[i]] = struct{}{} + } +} + +// RemovedUsertexture returns the removed IDs of the "usertexture" edge to the UserTexture entity. +func (m *TextureMutation) RemovedUsertextureIDs() (ids []int) { + for id := range m.removedusertexture { + ids = append(ids, id) + } + return +} + +// UsertextureIDs returns the "usertexture" edge IDs in the mutation. +func (m *TextureMutation) UsertextureIDs() (ids []int) { + for id := range m.usertexture { + ids = append(ids, id) + } + return +} + +// ResetUsertexture resets all changes to the "usertexture" edge. +func (m *TextureMutation) ResetUsertexture() { + m.usertexture = nil + m.clearedusertexture = false + m.removedusertexture = nil } // Where appends a list predicates to the TextureMutation builder. @@ -502,13 +577,16 @@ func (m *TextureMutation) ResetField(name string) error { // AddedEdges returns all edge names that were set/added in this mutation. func (m *TextureMutation) AddedEdges() []string { - edges := make([]string, 0, 2) + edges := make([]string, 0, 3) if m.created_user != nil { edges = append(edges, texture.EdgeCreatedUser) } if m.user != nil { edges = append(edges, texture.EdgeUser) } + if m.usertexture != nil { + edges = append(edges, texture.EdgeUsertexture) + } return edges } @@ -521,34 +599,65 @@ func (m *TextureMutation) AddedIDs(name string) []ent.Value { return []ent.Value{*id} } case texture.EdgeUser: - if id := m.user; id != nil { - return []ent.Value{*id} + ids := make([]ent.Value, 0, len(m.user)) + for id := range m.user { + ids = append(ids, id) } + return ids + case texture.EdgeUsertexture: + ids := make([]ent.Value, 0, len(m.usertexture)) + for id := range m.usertexture { + ids = append(ids, id) + } + return ids } return nil } // RemovedEdges returns all edge names that were removed in this mutation. func (m *TextureMutation) RemovedEdges() []string { - edges := make([]string, 0, 2) + edges := make([]string, 0, 3) + if m.removeduser != nil { + edges = append(edges, texture.EdgeUser) + } + if m.removedusertexture != nil { + edges = append(edges, texture.EdgeUsertexture) + } return edges } // RemovedIDs returns all IDs (to other nodes) that were removed for the edge with // the given name in this mutation. func (m *TextureMutation) RemovedIDs(name string) []ent.Value { + switch name { + case texture.EdgeUser: + ids := make([]ent.Value, 0, len(m.removeduser)) + for id := range m.removeduser { + ids = append(ids, id) + } + return ids + case texture.EdgeUsertexture: + ids := make([]ent.Value, 0, len(m.removedusertexture)) + for id := range m.removedusertexture { + ids = append(ids, id) + } + return ids + } return nil } // ClearedEdges returns all edge names that were cleared in this mutation. func (m *TextureMutation) ClearedEdges() []string { - edges := make([]string, 0, 2) + edges := make([]string, 0, 3) if m.clearedcreated_user { edges = append(edges, texture.EdgeCreatedUser) } if m.cleareduser { edges = append(edges, texture.EdgeUser) } + if m.clearedusertexture { + edges = append(edges, texture.EdgeUsertexture) + } return edges } @@ -560,6 +669,8 @@ func (m *TextureMutation) EdgeCleared(name string) bool { return m.clearedcreated_user case texture.EdgeUser: return m.cleareduser + case texture.EdgeUsertexture: + return m.clearedusertexture } return false } @@ -571,9 +682,6 @@ func (m *TextureMutation) ClearEdge(name string) error { case texture.EdgeCreatedUser: m.ClearCreatedUser() return nil - case texture.EdgeUser: - m.ClearUser() - return nil } return fmt.Errorf("unknown Texture unique edge %s", name) } @@ -588,6 +696,9 @@ func (m *TextureMutation) ResetEdge(name string) error { case texture.EdgeUser: m.ResetUser() return nil + case texture.EdgeUsertexture: + m.ResetUsertexture() + return nil } return fmt.Errorf("unknown Texture edge %s", name) } @@ -1471,20 +1582,23 @@ func (m *UserMutation) ResetEdge(name string) error { // UserProfileMutation represents an operation that mutates the UserProfile nodes in the graph. type UserProfileMutation struct { config - op Op - typ string - id *int - name *string - uuid *string - clearedFields map[string]struct{} - user *int - cleareduser bool - texture map[int]struct{} - removedtexture map[int]struct{} - clearedtexture bool - done bool - oldValue func(context.Context) (*UserProfile, error) - predicates []predicate.UserProfile + op Op + typ string + id *int + name *string + uuid *string + clearedFields map[string]struct{} + user *int + cleareduser bool + texture map[int]struct{} + removedtexture map[int]struct{} + clearedtexture bool + usertexture map[int]struct{} + removedusertexture map[int]struct{} + clearedusertexture bool + done bool + oldValue func(context.Context) (*UserProfile, error) + predicates []predicate.UserProfile } var _ ent.Mutation = (*UserProfileMutation)(nil) @@ -1750,6 +1864,60 @@ func (m *UserProfileMutation) ResetTexture() { m.removedtexture = nil } +// AddUsertextureIDs adds the "usertexture" edge to the UserTexture entity by ids. +func (m *UserProfileMutation) AddUsertextureIDs(ids ...int) { + if m.usertexture == nil { + m.usertexture = make(map[int]struct{}) + } + for i := range ids { + m.usertexture[ids[i]] = struct{}{} + } +} + +// ClearUsertexture clears the "usertexture" edge to the UserTexture entity. +func (m *UserProfileMutation) ClearUsertexture() { + m.clearedusertexture = true +} + +// UsertextureCleared reports if the "usertexture" edge to the UserTexture entity was cleared. +func (m *UserProfileMutation) UsertextureCleared() bool { + return m.clearedusertexture +} + +// RemoveUsertextureIDs removes the "usertexture" edge to the UserTexture entity by IDs. +func (m *UserProfileMutation) RemoveUsertextureIDs(ids ...int) { + if m.removedusertexture == nil { + m.removedusertexture = make(map[int]struct{}) + } + for i := range ids { + delete(m.usertexture, ids[i]) + m.removedusertexture[ids[i]] = struct{}{} + } +} + +// RemovedUsertexture returns the removed IDs of the "usertexture" edge to the UserTexture entity. +func (m *UserProfileMutation) RemovedUsertextureIDs() (ids []int) { + for id := range m.removedusertexture { + ids = append(ids, id) + } + return +} + +// UsertextureIDs returns the "usertexture" edge IDs in the mutation. +func (m *UserProfileMutation) UsertextureIDs() (ids []int) { + for id := range m.usertexture { + ids = append(ids, id) + } + return +} + +// ResetUsertexture resets all changes to the "usertexture" edge. +func (m *UserProfileMutation) ResetUsertexture() { + m.usertexture = nil + m.clearedusertexture = false + m.removedusertexture = nil +} + // Where appends a list predicates to the UserProfileMutation builder. func (m *UserProfileMutation) Where(ps ...predicate.UserProfile) { m.predicates = append(m.predicates, ps...) @@ -1900,13 +2068,16 @@ func (m *UserProfileMutation) ResetField(name string) error { // AddedEdges returns all edge names that were set/added in this mutation. func (m *UserProfileMutation) AddedEdges() []string { - edges := make([]string, 0, 2) + edges := make([]string, 0, 3) if m.user != nil { edges = append(edges, userprofile.EdgeUser) } if m.texture != nil { edges = append(edges, userprofile.EdgeTexture) } + if m.usertexture != nil { + edges = append(edges, userprofile.EdgeUsertexture) + } return edges } @@ -1924,16 +2095,25 @@ func (m *UserProfileMutation) AddedIDs(name string) []ent.Value { ids = append(ids, id) } return ids + case userprofile.EdgeUsertexture: + ids := make([]ent.Value, 0, len(m.usertexture)) + for id := range m.usertexture { + ids = append(ids, id) + } + return ids } return nil } // RemovedEdges returns all edge names that were removed in this mutation. func (m *UserProfileMutation) RemovedEdges() []string { - edges := make([]string, 0, 2) + edges := make([]string, 0, 3) if m.removedtexture != nil { edges = append(edges, userprofile.EdgeTexture) } + if m.removedusertexture != nil { + edges = append(edges, userprofile.EdgeUsertexture) + } return edges } @@ -1947,19 +2127,28 @@ func (m *UserProfileMutation) RemovedIDs(name string) []ent.Value { ids = append(ids, id) } return ids + case userprofile.EdgeUsertexture: + ids := make([]ent.Value, 0, len(m.removedusertexture)) + for id := range m.removedusertexture { + ids = append(ids, id) + } + return ids } return nil } // ClearedEdges returns all edge names that were cleared in this mutation. func (m *UserProfileMutation) ClearedEdges() []string { - edges := make([]string, 0, 2) + edges := make([]string, 0, 3) if m.cleareduser { edges = append(edges, userprofile.EdgeUser) } if m.clearedtexture { edges = append(edges, userprofile.EdgeTexture) } + if m.clearedusertexture { + edges = append(edges, userprofile.EdgeUsertexture) + } return edges } @@ -1971,6 +2160,8 @@ func (m *UserProfileMutation) EdgeCleared(name string) bool { return m.cleareduser case userprofile.EdgeTexture: return m.clearedtexture + case userprofile.EdgeUsertexture: + return m.clearedusertexture } return false } @@ -1996,10 +2187,494 @@ func (m *UserProfileMutation) ResetEdge(name string) error { case userprofile.EdgeTexture: m.ResetTexture() return nil + case userprofile.EdgeUsertexture: + m.ResetUsertexture() + return nil } return fmt.Errorf("unknown UserProfile edge %s", name) } +// UserTextureMutation represents an operation that mutates the UserTexture nodes in the graph. +type UserTextureMutation struct { + config + op Op + typ string + id *int + clearedFields map[string]struct{} + user_profile *int + cleareduser_profile bool + texture *int + clearedtexture bool + done bool + oldValue func(context.Context) (*UserTexture, error) + predicates []predicate.UserTexture +} + +var _ ent.Mutation = (*UserTextureMutation)(nil) + +// usertextureOption allows management of the mutation configuration using functional options. +type usertextureOption func(*UserTextureMutation) + +// newUserTextureMutation creates new mutation for the UserTexture entity. +func newUserTextureMutation(c config, op Op, opts ...usertextureOption) *UserTextureMutation { + m := &UserTextureMutation{ + config: c, + op: op, + typ: TypeUserTexture, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withUserTextureID sets the ID field of the mutation. +func withUserTextureID(id int) usertextureOption { + return func(m *UserTextureMutation) { + var ( + err error + once sync.Once + value *UserTexture + ) + m.oldValue = func(ctx context.Context) (*UserTexture, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().UserTexture.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withUserTexture sets the old UserTexture of the mutation. +func withUserTexture(node *UserTexture) usertextureOption { + return func(m *UserTextureMutation) { + m.oldValue = func(context.Context) (*UserTexture, 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 UserTextureMutation) 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 UserTextureMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("ent: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, 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 *UserTextureMutation) ID() (id int, 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 *UserTextureMutation) IDs(ctx context.Context) ([]int, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().UserTexture.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetUserProfileID sets the "user_profile_id" field. +func (m *UserTextureMutation) SetUserProfileID(i int) { + m.user_profile = &i +} + +// UserProfileID returns the value of the "user_profile_id" field in the mutation. +func (m *UserTextureMutation) UserProfileID() (r int, exists bool) { + v := m.user_profile + if v == nil { + return + } + return *v, true +} + +// OldUserProfileID returns the old "user_profile_id" field's value of the UserTexture entity. +// If the UserTexture object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserTextureMutation) OldUserProfileID(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUserProfileID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUserProfileID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUserProfileID: %w", err) + } + return oldValue.UserProfileID, nil +} + +// ResetUserProfileID resets all changes to the "user_profile_id" field. +func (m *UserTextureMutation) ResetUserProfileID() { + m.user_profile = nil +} + +// SetTextureID sets the "texture_id" field. +func (m *UserTextureMutation) SetTextureID(i int) { + m.texture = &i +} + +// TextureID returns the value of the "texture_id" field in the mutation. +func (m *UserTextureMutation) TextureID() (r int, exists bool) { + v := m.texture + if v == nil { + return + } + return *v, true +} + +// OldTextureID returns the old "texture_id" field's value of the UserTexture entity. +// If the UserTexture object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserTextureMutation) OldTextureID(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTextureID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTextureID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTextureID: %w", err) + } + return oldValue.TextureID, nil +} + +// ResetTextureID resets all changes to the "texture_id" field. +func (m *UserTextureMutation) ResetTextureID() { + m.texture = nil +} + +// ClearUserProfile clears the "user_profile" edge to the UserProfile entity. +func (m *UserTextureMutation) ClearUserProfile() { + m.cleareduser_profile = true +} + +// UserProfileCleared reports if the "user_profile" edge to the UserProfile entity was cleared. +func (m *UserTextureMutation) UserProfileCleared() bool { + return m.cleareduser_profile +} + +// UserProfileIDs returns the "user_profile" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// UserProfileID instead. It exists only for internal usage by the builders. +func (m *UserTextureMutation) UserProfileIDs() (ids []int) { + if id := m.user_profile; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetUserProfile resets all changes to the "user_profile" edge. +func (m *UserTextureMutation) ResetUserProfile() { + m.user_profile = nil + m.cleareduser_profile = false +} + +// ClearTexture clears the "texture" edge to the Texture entity. +func (m *UserTextureMutation) ClearTexture() { + m.clearedtexture = true +} + +// TextureCleared reports if the "texture" edge to the Texture entity was cleared. +func (m *UserTextureMutation) TextureCleared() bool { + return m.clearedtexture +} + +// TextureIDs returns the "texture" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// TextureID instead. It exists only for internal usage by the builders. +func (m *UserTextureMutation) TextureIDs() (ids []int) { + if id := m.texture; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetTexture resets all changes to the "texture" edge. +func (m *UserTextureMutation) ResetTexture() { + m.texture = nil + m.clearedtexture = false +} + +// Where appends a list predicates to the UserTextureMutation builder. +func (m *UserTextureMutation) Where(ps ...predicate.UserTexture) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the UserTextureMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *UserTextureMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.UserTexture, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *UserTextureMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *UserTextureMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (UserTexture). +func (m *UserTextureMutation) 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 *UserTextureMutation) Fields() []string { + fields := make([]string, 0, 2) + if m.user_profile != nil { + fields = append(fields, usertexture.FieldUserProfileID) + } + if m.texture != nil { + fields = append(fields, usertexture.FieldTextureID) + } + 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 *UserTextureMutation) Field(name string) (ent.Value, bool) { + switch name { + case usertexture.FieldUserProfileID: + return m.UserProfileID() + case usertexture.FieldTextureID: + return m.TextureID() + } + 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 *UserTextureMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case usertexture.FieldUserProfileID: + return m.OldUserProfileID(ctx) + case usertexture.FieldTextureID: + return m.OldTextureID(ctx) + } + return nil, fmt.Errorf("unknown UserTexture 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 *UserTextureMutation) SetField(name string, value ent.Value) error { + switch name { + case usertexture.FieldUserProfileID: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUserProfileID(v) + return nil + case usertexture.FieldTextureID: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTextureID(v) + return nil + } + return fmt.Errorf("unknown UserTexture field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *UserTextureMutation) AddedFields() []string { + var fields []string + 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 *UserTextureMutation) AddedField(name string) (ent.Value, bool) { + switch name { + } + 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 *UserTextureMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown UserTexture numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *UserTextureMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *UserTextureMutation) 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 *UserTextureMutation) ClearField(name string) error { + return fmt.Errorf("unknown UserTexture 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 *UserTextureMutation) ResetField(name string) error { + switch name { + case usertexture.FieldUserProfileID: + m.ResetUserProfileID() + return nil + case usertexture.FieldTextureID: + m.ResetTextureID() + return nil + } + return fmt.Errorf("unknown UserTexture field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *UserTextureMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.user_profile != nil { + edges = append(edges, usertexture.EdgeUserProfile) + } + if m.texture != nil { + edges = append(edges, usertexture.EdgeTexture) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *UserTextureMutation) AddedIDs(name string) []ent.Value { + switch name { + case usertexture.EdgeUserProfile: + if id := m.user_profile; id != nil { + return []ent.Value{*id} + } + case usertexture.EdgeTexture: + if id := m.texture; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *UserTextureMutation) 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 *UserTextureMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *UserTextureMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.cleareduser_profile { + edges = append(edges, usertexture.EdgeUserProfile) + } + if m.clearedtexture { + edges = append(edges, usertexture.EdgeTexture) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *UserTextureMutation) EdgeCleared(name string) bool { + switch name { + case usertexture.EdgeUserProfile: + return m.cleareduser_profile + case usertexture.EdgeTexture: + return m.clearedtexture + } + 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 *UserTextureMutation) ClearEdge(name string) error { + switch name { + case usertexture.EdgeUserProfile: + m.ClearUserProfile() + return nil + case usertexture.EdgeTexture: + m.ClearTexture() + return nil + } + return fmt.Errorf("unknown UserTexture 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 *UserTextureMutation) ResetEdge(name string) error { + switch name { + case usertexture.EdgeUserProfile: + m.ResetUserProfile() + return nil + case usertexture.EdgeTexture: + m.ResetTexture() + return nil + } + return fmt.Errorf("unknown UserTexture edge %s", name) +} + // UserTokenMutation represents an operation that mutates the UserToken nodes in the graph. type UserTokenMutation struct { config diff --git a/db/ent/predicate/predicate.go b/db/ent/predicate/predicate.go index 887c3de..d18131d 100644 --- a/db/ent/predicate/predicate.go +++ b/db/ent/predicate/predicate.go @@ -15,5 +15,8 @@ type User func(*sql.Selector) // UserProfile is the predicate function for userprofile builders. type UserProfile func(*sql.Selector) +// UserTexture is the predicate function for usertexture builders. +type UserTexture func(*sql.Selector) + // UserToken is the predicate function for usertoken builders. type UserToken func(*sql.Selector) diff --git a/db/ent/schema/texture.go b/db/ent/schema/texture.go index ba76efe..20ba46d 100644 --- a/db/ent/schema/texture.go +++ b/db/ent/schema/texture.go @@ -5,7 +5,6 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/schema/edge" "entgo.io/ent/schema/field" - "entgo.io/ent/schema/index" ) // Texture holds the schema definition for the Texture entity. @@ -34,12 +33,10 @@ func (Texture) Fields() []ent.Field { func (Texture) Edges() []ent.Edge { return []ent.Edge{ edge.To("created_user", User.Type).Unique().Required(), - edge.From("user", UserProfile.Type).Ref("texture").Required().Unique(), + edge.From("user", UserProfile.Type).Ref("texture").Through("usertexture", UserTexture.Type), } } func (Texture) Indexes() []ent.Index { - return []ent.Index{ - index.Edges("user"), - } + return nil } diff --git a/db/ent/schema/userprofile.go b/db/ent/schema/userprofile.go index 69b4088..365f62b 100644 --- a/db/ent/schema/userprofile.go +++ b/db/ent/schema/userprofile.go @@ -29,7 +29,7 @@ func (UserProfile) Fields() []ent.Field { func (UserProfile) Edges() []ent.Edge { return []ent.Edge{ edge.From("user", User.Type).Ref("profile").Required().Unique(), - edge.To("texture", Texture.Type), + edge.To("texture", Texture.Type).Through("usertexture", UserTexture.Type), } } diff --git a/db/ent/schema/usertexture.go b/db/ent/schema/usertexture.go new file mode 100644 index 0000000..08488cd --- /dev/null +++ b/db/ent/schema/usertexture.go @@ -0,0 +1,42 @@ +package schema + +import ( + "entgo.io/ent" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/index" +) + +// UserTexture holds the schema definition for the UserTexture entity. +type UserTexture struct { + ent.Schema +} + +// Fields of the UserTexture. +func (UserTexture) Fields() []ent.Field { + return []ent.Field{ + field.Int("user_profile_id"), + field.Int("texture_id"), + } +} + +// Edges of the UserTexture. +func (UserTexture) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("user_profile", UserProfile.Type). + Unique(). + Required(). + Field("user_profile_id"), + edge.To("texture", Texture.Type). + Unique(). + Required(). + Field("texture_id"), + } +} + +func (UserTexture) Indexes() []ent.Index { + return []ent.Index{ + index.Edges("user_profile"), + index.Edges("texture"), + } +} diff --git a/db/ent/texture.go b/db/ent/texture.go index 8f0276d..e7565a9 100644 --- a/db/ent/texture.go +++ b/db/ent/texture.go @@ -10,7 +10,6 @@ import ( "entgo.io/ent/dialect/sql" "github.com/xmdhs/authlib-skin/db/ent/texture" "github.com/xmdhs/authlib-skin/db/ent/user" - "github.com/xmdhs/authlib-skin/db/ent/userprofile" ) // Texture is the model entity for the Texture schema. @@ -28,7 +27,6 @@ type Texture struct { // The values are being populated by the TextureQuery when eager-loading is set. Edges TextureEdges `json:"edges"` texture_created_user *int - user_profile_texture *int selectValues sql.SelectValues } @@ -37,10 +35,12 @@ type TextureEdges struct { // CreatedUser holds the value of the created_user edge. CreatedUser *User `json:"created_user,omitempty"` // User holds the value of the user edge. - User *UserProfile `json:"user,omitempty"` + User []*UserProfile `json:"user,omitempty"` + // Usertexture holds the value of the usertexture edge. + Usertexture []*UserTexture `json:"usertexture,omitempty"` // loadedTypes holds the information for reporting if a // type was loaded (or requested) in eager-loading or not. - loadedTypes [2]bool + loadedTypes [3]bool } // CreatedUserOrErr returns the CreatedUser value or an error if the edge @@ -57,18 +57,23 @@ func (e TextureEdges) CreatedUserOrErr() (*User, error) { } // 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 TextureEdges) UserOrErr() (*UserProfile, error) { +// was not loaded in eager-loading. +func (e TextureEdges) UserOrErr() ([]*UserProfile, error) { if e.loadedTypes[1] { - if e.User == nil { - // Edge was loaded but was not found. - return nil, &NotFoundError{label: userprofile.Label} - } return e.User, nil } return nil, &NotLoadedError{edge: "user"} } +// UsertextureOrErr returns the Usertexture value or an error if the edge +// was not loaded in eager-loading. +func (e TextureEdges) UsertextureOrErr() ([]*UserTexture, error) { + if e.loadedTypes[2] { + return e.Usertexture, nil + } + return nil, &NotLoadedError{edge: "usertexture"} +} + // scanValues returns the types for scanning values from sql.Rows. func (*Texture) scanValues(columns []string) ([]any, error) { values := make([]any, len(columns)) @@ -80,8 +85,6 @@ func (*Texture) scanValues(columns []string) ([]any, error) { values[i] = new(sql.NullString) case texture.ForeignKeys[0]: // texture_created_user values[i] = new(sql.NullInt64) - case texture.ForeignKeys[1]: // user_profile_texture - values[i] = new(sql.NullInt64) default: values[i] = new(sql.UnknownType) } @@ -128,13 +131,6 @@ func (t *Texture) assignValues(columns []string, values []any) error { t.texture_created_user = new(int) *t.texture_created_user = int(value.Int64) } - case texture.ForeignKeys[1]: - if value, ok := values[i].(*sql.NullInt64); !ok { - return fmt.Errorf("unexpected type %T for edge-field user_profile_texture", value) - } else if value.Valid { - t.user_profile_texture = new(int) - *t.user_profile_texture = int(value.Int64) - } default: t.selectValues.Set(columns[i], values[i]) } @@ -158,6 +154,11 @@ func (t *Texture) QueryUser() *UserProfileQuery { return NewTextureClient(t.config).QueryUser(t) } +// QueryUsertexture queries the "usertexture" edge of the Texture entity. +func (t *Texture) QueryUsertexture() *UserTextureQuery { + return NewTextureClient(t.config).QueryUsertexture(t) +} + // Update returns a builder for updating this Texture. // Note that you need to call Texture.Unwrap() before calling this method if this Texture // was returned from a transaction, and the transaction was committed or rolled back. diff --git a/db/ent/texture/texture.go b/db/ent/texture/texture.go index 44a1040..f5e2eef 100644 --- a/db/ent/texture/texture.go +++ b/db/ent/texture/texture.go @@ -22,6 +22,8 @@ const ( EdgeCreatedUser = "created_user" // EdgeUser holds the string denoting the user edge name in mutations. EdgeUser = "user" + // EdgeUsertexture holds the string denoting the usertexture edge name in mutations. + EdgeUsertexture = "usertexture" // Table holds the table name of the texture in the database. Table = "textures" // CreatedUserTable is the table that holds the created_user relation/edge. @@ -31,13 +33,18 @@ const ( CreatedUserInverseTable = "users" // CreatedUserColumn is the table column denoting the created_user relation/edge. CreatedUserColumn = "texture_created_user" - // UserTable is the table that holds the user relation/edge. - UserTable = "textures" + // UserTable is the table that holds the user relation/edge. The primary key declared below. + UserTable = "user_textures" // UserInverseTable is the table name for the UserProfile entity. // It exists in this package in order to avoid circular dependency with the "userprofile" package. UserInverseTable = "user_profiles" - // UserColumn is the table column denoting the user relation/edge. - UserColumn = "user_profile_texture" + // UsertextureTable is the table that holds the usertexture relation/edge. + UsertextureTable = "user_textures" + // UsertextureInverseTable is the table name for the UserTexture entity. + // It exists in this package in order to avoid circular dependency with the "usertexture" package. + UsertextureInverseTable = "user_textures" + // UsertextureColumn is the table column denoting the usertexture relation/edge. + UsertextureColumn = "texture_id" ) // Columns holds all SQL columns for texture fields. @@ -52,9 +59,14 @@ var Columns = []string{ // table and are not defined as standalone fields in the schema. var ForeignKeys = []string{ "texture_created_user", - "user_profile_texture", } +var ( + // UserPrimaryKey and UserColumn2 are the table columns denoting the + // primary key for the user relation (M2M). + UserPrimaryKey = []string{"user_profile_id", "texture_id"} +) + // ValidColumn reports if the column name is valid (part of the table columns). func ValidColumn(column string) bool { for i := range Columns { @@ -100,10 +112,31 @@ func ByCreatedUserField(field string, opts ...sql.OrderTermOption) OrderOption { } } -// ByUserField orders the results by user field. -func ByUserField(field string, opts ...sql.OrderTermOption) OrderOption { +// ByUserCount orders the results by user count. +func ByUserCount(opts ...sql.OrderTermOption) OrderOption { return func(s *sql.Selector) { - sqlgraph.OrderByNeighborTerms(s, newUserStep(), sql.OrderByField(field, opts...)) + sqlgraph.OrderByNeighborsCount(s, newUserStep(), opts...) + } +} + +// ByUser orders the results by user terms. +func ByUser(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newUserStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByUsertextureCount orders the results by usertexture count. +func ByUsertextureCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newUsertextureStep(), opts...) + } +} + +// ByUsertexture orders the results by usertexture terms. +func ByUsertexture(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newUsertextureStep(), append([]sql.OrderTerm{term}, terms...)...) } } func newCreatedUserStep() *sqlgraph.Step { @@ -117,6 +150,13 @@ func newUserStep() *sqlgraph.Step { return sqlgraph.NewStep( sqlgraph.From(Table, FieldID), sqlgraph.To(UserInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.M2O, true, UserTable, UserColumn), + sqlgraph.Edge(sqlgraph.M2M, true, UserTable, UserPrimaryKey...), + ) +} +func newUsertextureStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(UsertextureInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, UsertextureTable, UsertextureColumn), ) } diff --git a/db/ent/texture/where.go b/db/ent/texture/where.go index 2d9af22..032ef26 100644 --- a/db/ent/texture/where.go +++ b/db/ent/texture/where.go @@ -291,7 +291,7 @@ func HasUser() predicate.Texture { return predicate.Texture(func(s *sql.Selector) { step := sqlgraph.NewStep( sqlgraph.From(Table, FieldID), - sqlgraph.Edge(sqlgraph.M2O, true, UserTable, UserColumn), + sqlgraph.Edge(sqlgraph.M2M, true, UserTable, UserPrimaryKey...), ) sqlgraph.HasNeighbors(s, step) }) @@ -309,6 +309,29 @@ func HasUserWith(preds ...predicate.UserProfile) predicate.Texture { }) } +// HasUsertexture applies the HasEdge predicate on the "usertexture" edge. +func HasUsertexture() predicate.Texture { + return predicate.Texture(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, UsertextureTable, UsertextureColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasUsertextureWith applies the HasEdge predicate on the "usertexture" edge with a given conditions (other predicates). +func HasUsertextureWith(preds ...predicate.UserTexture) predicate.Texture { + return predicate.Texture(func(s *sql.Selector) { + step := newUsertextureStep() + 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.Texture) predicate.Texture { return predicate.Texture(func(s *sql.Selector) { diff --git a/db/ent/texture_create.go b/db/ent/texture_create.go index a1219dd..30841d0 100644 --- a/db/ent/texture_create.go +++ b/db/ent/texture_create.go @@ -12,6 +12,7 @@ import ( "github.com/xmdhs/authlib-skin/db/ent/texture" "github.com/xmdhs/authlib-skin/db/ent/user" "github.com/xmdhs/authlib-skin/db/ent/userprofile" + "github.com/xmdhs/authlib-skin/db/ent/usertexture" ) // TextureCreate is the builder for creating a Texture entity. @@ -50,15 +51,34 @@ func (tc *TextureCreate) SetCreatedUser(u *User) *TextureCreate { return tc.SetCreatedUserID(u.ID) } -// SetUserID sets the "user" edge to the UserProfile entity by ID. -func (tc *TextureCreate) SetUserID(id int) *TextureCreate { - tc.mutation.SetUserID(id) +// AddUserIDs adds the "user" edge to the UserProfile entity by IDs. +func (tc *TextureCreate) AddUserIDs(ids ...int) *TextureCreate { + tc.mutation.AddUserIDs(ids...) return tc } -// SetUser sets the "user" edge to the UserProfile entity. -func (tc *TextureCreate) SetUser(u *UserProfile) *TextureCreate { - return tc.SetUserID(u.ID) +// AddUser adds the "user" edges to the UserProfile entity. +func (tc *TextureCreate) AddUser(u ...*UserProfile) *TextureCreate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return tc.AddUserIDs(ids...) +} + +// AddUsertextureIDs adds the "usertexture" edge to the UserTexture entity by IDs. +func (tc *TextureCreate) AddUsertextureIDs(ids ...int) *TextureCreate { + tc.mutation.AddUsertextureIDs(ids...) + return tc +} + +// AddUsertexture adds the "usertexture" edges to the UserTexture entity. +func (tc *TextureCreate) AddUsertexture(u ...*UserTexture) *TextureCreate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return tc.AddUsertextureIDs(ids...) } // Mutation returns the TextureMutation object of the builder. @@ -107,9 +127,6 @@ func (tc *TextureCreate) check() error { if _, ok := tc.mutation.CreatedUserID(); !ok { return &ValidationError{Name: "created_user", err: errors.New(`ent: missing required edge "Texture.created_user"`)} } - if _, ok := tc.mutation.UserID(); !ok { - return &ValidationError{Name: "user", err: errors.New(`ent: missing required edge "Texture.user"`)} - } return nil } @@ -167,10 +184,10 @@ func (tc *TextureCreate) createSpec() (*Texture, *sqlgraph.CreateSpec) { } if nodes := tc.mutation.UserIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, + Rel: sqlgraph.M2M, Inverse: true, Table: texture.UserTable, - Columns: []string{texture.UserColumn}, + Columns: texture.UserPrimaryKey, Bidi: false, Target: &sqlgraph.EdgeTarget{ IDSpec: sqlgraph.NewFieldSpec(userprofile.FieldID, field.TypeInt), @@ -179,7 +196,22 @@ func (tc *TextureCreate) createSpec() (*Texture, *sqlgraph.CreateSpec) { for _, k := range nodes { edge.Target.Nodes = append(edge.Target.Nodes, k) } - _node.user_profile_texture = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := tc.mutation.UsertextureIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: texture.UsertextureTable, + Columns: []string{texture.UsertextureColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usertexture.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } _spec.Edges = append(_spec.Edges, edge) } return _node, _spec diff --git a/db/ent/texture_query.go b/db/ent/texture_query.go index da1aa1f..13b9e26 100644 --- a/db/ent/texture_query.go +++ b/db/ent/texture_query.go @@ -4,6 +4,7 @@ package ent import ( "context" + "database/sql/driver" "fmt" "math" @@ -15,6 +16,7 @@ import ( "github.com/xmdhs/authlib-skin/db/ent/texture" "github.com/xmdhs/authlib-skin/db/ent/user" "github.com/xmdhs/authlib-skin/db/ent/userprofile" + "github.com/xmdhs/authlib-skin/db/ent/usertexture" ) // TextureQuery is the builder for querying Texture entities. @@ -26,6 +28,7 @@ type TextureQuery struct { predicates []predicate.Texture withCreatedUser *UserQuery withUser *UserProfileQuery + withUsertexture *UserTextureQuery withFKs bool modifiers []func(*sql.Selector) // intermediate query (i.e. traversal path). @@ -100,7 +103,29 @@ func (tq *TextureQuery) QueryUser() *UserProfileQuery { step := sqlgraph.NewStep( sqlgraph.From(texture.Table, texture.FieldID, selector), sqlgraph.To(userprofile.Table, userprofile.FieldID), - sqlgraph.Edge(sqlgraph.M2O, true, texture.UserTable, texture.UserColumn), + sqlgraph.Edge(sqlgraph.M2M, true, texture.UserTable, texture.UserPrimaryKey...), + ) + fromU = sqlgraph.SetNeighbors(tq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryUsertexture chains the current query on the "usertexture" edge. +func (tq *TextureQuery) QueryUsertexture() *UserTextureQuery { + query := (&UserTextureClient{config: tq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := tq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := tq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(texture.Table, texture.FieldID, selector), + sqlgraph.To(usertexture.Table, usertexture.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, texture.UsertextureTable, texture.UsertextureColumn), ) fromU = sqlgraph.SetNeighbors(tq.driver.Dialect(), step) return fromU, nil @@ -302,6 +327,7 @@ func (tq *TextureQuery) Clone() *TextureQuery { predicates: append([]predicate.Texture{}, tq.predicates...), withCreatedUser: tq.withCreatedUser.Clone(), withUser: tq.withUser.Clone(), + withUsertexture: tq.withUsertexture.Clone(), // clone intermediate query. sql: tq.sql.Clone(), path: tq.path, @@ -330,6 +356,17 @@ func (tq *TextureQuery) WithUser(opts ...func(*UserProfileQuery)) *TextureQuery return tq } +// WithUsertexture tells the query-builder to eager-load the nodes that are connected to +// the "usertexture" edge. The optional arguments are used to configure the query builder of the edge. +func (tq *TextureQuery) WithUsertexture(opts ...func(*UserTextureQuery)) *TextureQuery { + query := (&UserTextureClient{config: tq.config}).Query() + for _, opt := range opts { + opt(query) + } + tq.withUsertexture = query + return tq +} + // GroupBy is used to group vertices by one or more fields/columns. // It is often used with aggregate functions, like: count, max, mean, min, sum. // @@ -409,12 +446,13 @@ func (tq *TextureQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Text nodes = []*Texture{} withFKs = tq.withFKs _spec = tq.querySpec() - loadedTypes = [2]bool{ + loadedTypes = [3]bool{ tq.withCreatedUser != nil, tq.withUser != nil, + tq.withUsertexture != nil, } ) - if tq.withCreatedUser != nil || tq.withUser != nil { + if tq.withCreatedUser != nil { withFKs = true } if withFKs { @@ -448,8 +486,16 @@ func (tq *TextureQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Text } } if query := tq.withUser; query != nil { - if err := tq.loadUser(ctx, query, nodes, nil, - func(n *Texture, e *UserProfile) { n.Edges.User = e }); err != nil { + if err := tq.loadUser(ctx, query, nodes, + func(n *Texture) { n.Edges.User = []*UserProfile{} }, + func(n *Texture, e *UserProfile) { n.Edges.User = append(n.Edges.User, e) }); err != nil { + return nil, err + } + } + if query := tq.withUsertexture; query != nil { + if err := tq.loadUsertexture(ctx, query, nodes, + func(n *Texture) { n.Edges.Usertexture = []*UserTexture{} }, + func(n *Texture, e *UserTexture) { n.Edges.Usertexture = append(n.Edges.Usertexture, e) }); err != nil { return nil, err } } @@ -489,34 +535,93 @@ func (tq *TextureQuery) loadCreatedUser(ctx context.Context, query *UserQuery, n return nil } func (tq *TextureQuery) loadUser(ctx context.Context, query *UserProfileQuery, nodes []*Texture, init func(*Texture), assign func(*Texture, *UserProfile)) error { - ids := make([]int, 0, len(nodes)) - nodeids := make(map[int][]*Texture) + edgeIDs := make([]driver.Value, len(nodes)) + byID := make(map[int]*Texture) + nids := make(map[int]map[*Texture]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(texture.UserTable) + s.Join(joinT).On(s.C(userprofile.FieldID), joinT.C(texture.UserPrimaryKey[0])) + s.Where(sql.InValues(joinT.C(texture.UserPrimaryKey[1]), edgeIDs...)) + columns := s.SelectedColumns() + s.Select(joinT.C(texture.UserPrimaryKey[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(sql.NullInt64)}, values...), nil + } + spec.Assign = func(columns []string, values []any) error { + outValue := int(values[0].(*sql.NullInt64).Int64) + inValue := int(values[1].(*sql.NullInt64).Int64) + if nids[inValue] == nil { + nids[inValue] = map[*Texture]struct{}{byID[outValue]: {}} + return assign(columns[1:], values[1:]) + } + nids[inValue][byID[outValue]] = struct{}{} + return nil + } + }) + }) + neighbors, err := withInterceptors[[]*UserProfile](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 "user" node returned %v`, n.ID) + } + for kn := range nodes { + assign(kn, n) + } + } + return nil +} +func (tq *TextureQuery) loadUsertexture(ctx context.Context, query *UserTextureQuery, nodes []*Texture, init func(*Texture), assign func(*Texture, *UserTexture)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int]*Texture) for i := range nodes { - if nodes[i].user_profile_texture == nil { - continue + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) } - fk := *nodes[i].user_profile_texture - if _, ok := nodeids[fk]; !ok { - ids = append(ids, fk) - } - nodeids[fk] = append(nodeids[fk], nodes[i]) } - if len(ids) == 0 { - return nil + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(usertexture.FieldTextureID) } - query.Where(userprofile.IDIn(ids...)) + query.Where(predicate.UserTexture(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(texture.UsertextureColumn), fks...)) + })) neighbors, err := query.All(ctx) if err != nil { return err } for _, n := range neighbors { - nodes, ok := nodeids[n.ID] + fk := n.TextureID + node, ok := nodeids[fk] if !ok { - return fmt.Errorf(`unexpected foreign-key "user_profile_texture" returned %v`, n.ID) - } - for i := range nodes { - assign(nodes[i], n) + return fmt.Errorf(`unexpected referenced foreign-key "texture_id" returned %v for node %v`, fk, n.ID) } + assign(node, n) } return nil } diff --git a/db/ent/texture_update.go b/db/ent/texture_update.go index 978027f..4f199d1 100644 --- a/db/ent/texture_update.go +++ b/db/ent/texture_update.go @@ -14,6 +14,7 @@ import ( "github.com/xmdhs/authlib-skin/db/ent/texture" "github.com/xmdhs/authlib-skin/db/ent/user" "github.com/xmdhs/authlib-skin/db/ent/userprofile" + "github.com/xmdhs/authlib-skin/db/ent/usertexture" ) // TextureUpdate is the builder for updating Texture entities. @@ -58,15 +59,34 @@ func (tu *TextureUpdate) SetCreatedUser(u *User) *TextureUpdate { return tu.SetCreatedUserID(u.ID) } -// SetUserID sets the "user" edge to the UserProfile entity by ID. -func (tu *TextureUpdate) SetUserID(id int) *TextureUpdate { - tu.mutation.SetUserID(id) +// AddUserIDs adds the "user" edge to the UserProfile entity by IDs. +func (tu *TextureUpdate) AddUserIDs(ids ...int) *TextureUpdate { + tu.mutation.AddUserIDs(ids...) return tu } -// SetUser sets the "user" edge to the UserProfile entity. -func (tu *TextureUpdate) SetUser(u *UserProfile) *TextureUpdate { - return tu.SetUserID(u.ID) +// AddUser adds the "user" edges to the UserProfile entity. +func (tu *TextureUpdate) AddUser(u ...*UserProfile) *TextureUpdate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return tu.AddUserIDs(ids...) +} + +// AddUsertextureIDs adds the "usertexture" edge to the UserTexture entity by IDs. +func (tu *TextureUpdate) AddUsertextureIDs(ids ...int) *TextureUpdate { + tu.mutation.AddUsertextureIDs(ids...) + return tu +} + +// AddUsertexture adds the "usertexture" edges to the UserTexture entity. +func (tu *TextureUpdate) AddUsertexture(u ...*UserTexture) *TextureUpdate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return tu.AddUsertextureIDs(ids...) } // Mutation returns the TextureMutation object of the builder. @@ -80,12 +100,48 @@ func (tu *TextureUpdate) ClearCreatedUser() *TextureUpdate { return tu } -// ClearUser clears the "user" edge to the UserProfile entity. +// ClearUser clears all "user" edges to the UserProfile entity. func (tu *TextureUpdate) ClearUser() *TextureUpdate { tu.mutation.ClearUser() return tu } +// RemoveUserIDs removes the "user" edge to UserProfile entities by IDs. +func (tu *TextureUpdate) RemoveUserIDs(ids ...int) *TextureUpdate { + tu.mutation.RemoveUserIDs(ids...) + return tu +} + +// RemoveUser removes "user" edges to UserProfile entities. +func (tu *TextureUpdate) RemoveUser(u ...*UserProfile) *TextureUpdate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return tu.RemoveUserIDs(ids...) +} + +// ClearUsertexture clears all "usertexture" edges to the UserTexture entity. +func (tu *TextureUpdate) ClearUsertexture() *TextureUpdate { + tu.mutation.ClearUsertexture() + return tu +} + +// RemoveUsertextureIDs removes the "usertexture" edge to UserTexture entities by IDs. +func (tu *TextureUpdate) RemoveUsertextureIDs(ids ...int) *TextureUpdate { + tu.mutation.RemoveUsertextureIDs(ids...) + return tu +} + +// RemoveUsertexture removes "usertexture" edges to UserTexture entities. +func (tu *TextureUpdate) RemoveUsertexture(u ...*UserTexture) *TextureUpdate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return tu.RemoveUsertextureIDs(ids...) +} + // Save executes the query and returns the number of nodes affected by the update operation. func (tu *TextureUpdate) Save(ctx context.Context) (int, error) { return withHooks(ctx, tu.sqlSave, tu.mutation, tu.hooks) @@ -118,9 +174,6 @@ func (tu *TextureUpdate) check() error { if _, ok := tu.mutation.CreatedUserID(); tu.mutation.CreatedUserCleared() && !ok { return errors.New(`ent: clearing a required unique edge "Texture.created_user"`) } - if _, ok := tu.mutation.UserID(); tu.mutation.UserCleared() && !ok { - return errors.New(`ent: clearing a required unique edge "Texture.user"`) - } return nil } @@ -176,10 +229,10 @@ func (tu *TextureUpdate) sqlSave(ctx context.Context) (n int, err error) { } if tu.mutation.UserCleared() { edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, + Rel: sqlgraph.M2M, Inverse: true, Table: texture.UserTable, - Columns: []string{texture.UserColumn}, + Columns: texture.UserPrimaryKey, Bidi: false, Target: &sqlgraph.EdgeTarget{ IDSpec: sqlgraph.NewFieldSpec(userprofile.FieldID, field.TypeInt), @@ -187,12 +240,12 @@ func (tu *TextureUpdate) sqlSave(ctx context.Context) (n int, err error) { } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) } - if nodes := tu.mutation.UserIDs(); len(nodes) > 0 { + if nodes := tu.mutation.RemovedUserIDs(); len(nodes) > 0 && !tu.mutation.UserCleared() { edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, + Rel: sqlgraph.M2M, Inverse: true, Table: texture.UserTable, - Columns: []string{texture.UserColumn}, + Columns: texture.UserPrimaryKey, Bidi: false, Target: &sqlgraph.EdgeTarget{ IDSpec: sqlgraph.NewFieldSpec(userprofile.FieldID, field.TypeInt), @@ -201,6 +254,67 @@ func (tu *TextureUpdate) sqlSave(ctx context.Context) (n int, err error) { for _, k := range nodes { edge.Target.Nodes = append(edge.Target.Nodes, k) } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tu.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: texture.UserTable, + Columns: texture.UserPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(userprofile.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if tu.mutation.UsertextureCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: texture.UsertextureTable, + Columns: []string{texture.UsertextureColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usertexture.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tu.mutation.RemovedUsertextureIDs(); len(nodes) > 0 && !tu.mutation.UsertextureCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: texture.UsertextureTable, + Columns: []string{texture.UsertextureColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usertexture.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tu.mutation.UsertextureIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: texture.UsertextureTable, + Columns: []string{texture.UsertextureColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usertexture.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } _spec.Edges.Add = append(_spec.Edges.Add, edge) } if n, err = sqlgraph.UpdateNodes(ctx, tu.driver, _spec); err != nil { @@ -252,15 +366,34 @@ func (tuo *TextureUpdateOne) SetCreatedUser(u *User) *TextureUpdateOne { return tuo.SetCreatedUserID(u.ID) } -// SetUserID sets the "user" edge to the UserProfile entity by ID. -func (tuo *TextureUpdateOne) SetUserID(id int) *TextureUpdateOne { - tuo.mutation.SetUserID(id) +// AddUserIDs adds the "user" edge to the UserProfile entity by IDs. +func (tuo *TextureUpdateOne) AddUserIDs(ids ...int) *TextureUpdateOne { + tuo.mutation.AddUserIDs(ids...) return tuo } -// SetUser sets the "user" edge to the UserProfile entity. -func (tuo *TextureUpdateOne) SetUser(u *UserProfile) *TextureUpdateOne { - return tuo.SetUserID(u.ID) +// AddUser adds the "user" edges to the UserProfile entity. +func (tuo *TextureUpdateOne) AddUser(u ...*UserProfile) *TextureUpdateOne { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return tuo.AddUserIDs(ids...) +} + +// AddUsertextureIDs adds the "usertexture" edge to the UserTexture entity by IDs. +func (tuo *TextureUpdateOne) AddUsertextureIDs(ids ...int) *TextureUpdateOne { + tuo.mutation.AddUsertextureIDs(ids...) + return tuo +} + +// AddUsertexture adds the "usertexture" edges to the UserTexture entity. +func (tuo *TextureUpdateOne) AddUsertexture(u ...*UserTexture) *TextureUpdateOne { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return tuo.AddUsertextureIDs(ids...) } // Mutation returns the TextureMutation object of the builder. @@ -274,12 +407,48 @@ func (tuo *TextureUpdateOne) ClearCreatedUser() *TextureUpdateOne { return tuo } -// ClearUser clears the "user" edge to the UserProfile entity. +// ClearUser clears all "user" edges to the UserProfile entity. func (tuo *TextureUpdateOne) ClearUser() *TextureUpdateOne { tuo.mutation.ClearUser() return tuo } +// RemoveUserIDs removes the "user" edge to UserProfile entities by IDs. +func (tuo *TextureUpdateOne) RemoveUserIDs(ids ...int) *TextureUpdateOne { + tuo.mutation.RemoveUserIDs(ids...) + return tuo +} + +// RemoveUser removes "user" edges to UserProfile entities. +func (tuo *TextureUpdateOne) RemoveUser(u ...*UserProfile) *TextureUpdateOne { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return tuo.RemoveUserIDs(ids...) +} + +// ClearUsertexture clears all "usertexture" edges to the UserTexture entity. +func (tuo *TextureUpdateOne) ClearUsertexture() *TextureUpdateOne { + tuo.mutation.ClearUsertexture() + return tuo +} + +// RemoveUsertextureIDs removes the "usertexture" edge to UserTexture entities by IDs. +func (tuo *TextureUpdateOne) RemoveUsertextureIDs(ids ...int) *TextureUpdateOne { + tuo.mutation.RemoveUsertextureIDs(ids...) + return tuo +} + +// RemoveUsertexture removes "usertexture" edges to UserTexture entities. +func (tuo *TextureUpdateOne) RemoveUsertexture(u ...*UserTexture) *TextureUpdateOne { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return tuo.RemoveUsertextureIDs(ids...) +} + // Where appends a list predicates to the TextureUpdate builder. func (tuo *TextureUpdateOne) Where(ps ...predicate.Texture) *TextureUpdateOne { tuo.mutation.Where(ps...) @@ -325,9 +494,6 @@ func (tuo *TextureUpdateOne) check() error { if _, ok := tuo.mutation.CreatedUserID(); tuo.mutation.CreatedUserCleared() && !ok { return errors.New(`ent: clearing a required unique edge "Texture.created_user"`) } - if _, ok := tuo.mutation.UserID(); tuo.mutation.UserCleared() && !ok { - return errors.New(`ent: clearing a required unique edge "Texture.user"`) - } return nil } @@ -400,10 +566,10 @@ func (tuo *TextureUpdateOne) sqlSave(ctx context.Context) (_node *Texture, err e } if tuo.mutation.UserCleared() { edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, + Rel: sqlgraph.M2M, Inverse: true, Table: texture.UserTable, - Columns: []string{texture.UserColumn}, + Columns: texture.UserPrimaryKey, Bidi: false, Target: &sqlgraph.EdgeTarget{ IDSpec: sqlgraph.NewFieldSpec(userprofile.FieldID, field.TypeInt), @@ -411,12 +577,12 @@ func (tuo *TextureUpdateOne) sqlSave(ctx context.Context) (_node *Texture, err e } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) } - if nodes := tuo.mutation.UserIDs(); len(nodes) > 0 { + if nodes := tuo.mutation.RemovedUserIDs(); len(nodes) > 0 && !tuo.mutation.UserCleared() { edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, + Rel: sqlgraph.M2M, Inverse: true, Table: texture.UserTable, - Columns: []string{texture.UserColumn}, + Columns: texture.UserPrimaryKey, Bidi: false, Target: &sqlgraph.EdgeTarget{ IDSpec: sqlgraph.NewFieldSpec(userprofile.FieldID, field.TypeInt), @@ -425,6 +591,67 @@ func (tuo *TextureUpdateOne) sqlSave(ctx context.Context) (_node *Texture, err e for _, k := range nodes { edge.Target.Nodes = append(edge.Target.Nodes, k) } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tuo.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: texture.UserTable, + Columns: texture.UserPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(userprofile.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if tuo.mutation.UsertextureCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: texture.UsertextureTable, + Columns: []string{texture.UsertextureColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usertexture.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tuo.mutation.RemovedUsertextureIDs(); len(nodes) > 0 && !tuo.mutation.UsertextureCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: texture.UsertextureTable, + Columns: []string{texture.UsertextureColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usertexture.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tuo.mutation.UsertextureIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: texture.UsertextureTable, + Columns: []string{texture.UsertextureColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usertexture.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } _spec.Edges.Add = append(_spec.Edges.Add, edge) } _node = &Texture{config: tuo.config} diff --git a/db/ent/tx.go b/db/ent/tx.go index 27f74ec..11b4d49 100644 --- a/db/ent/tx.go +++ b/db/ent/tx.go @@ -18,6 +18,8 @@ type Tx struct { User *UserClient // UserProfile is the client for interacting with the UserProfile builders. UserProfile *UserProfileClient + // UserTexture is the client for interacting with the UserTexture builders. + UserTexture *UserTextureClient // UserToken is the client for interacting with the UserToken builders. UserToken *UserTokenClient @@ -154,6 +156,7 @@ func (tx *Tx) init() { tx.Texture = NewTextureClient(tx.config) tx.User = NewUserClient(tx.config) tx.UserProfile = NewUserProfileClient(tx.config) + tx.UserTexture = NewUserTextureClient(tx.config) tx.UserToken = NewUserTokenClient(tx.config) } diff --git a/db/ent/userprofile.go b/db/ent/userprofile.go index db35522..f59359c 100644 --- a/db/ent/userprofile.go +++ b/db/ent/userprofile.go @@ -34,9 +34,11 @@ type UserProfileEdges struct { User *User `json:"user,omitempty"` // Texture holds the value of the texture edge. Texture []*Texture `json:"texture,omitempty"` + // Usertexture holds the value of the usertexture edge. + Usertexture []*UserTexture `json:"usertexture,omitempty"` // loadedTypes holds the information for reporting if a // type was loaded (or requested) in eager-loading or not. - loadedTypes [2]bool + loadedTypes [3]bool } // UserOrErr returns the User value or an error if the edge @@ -61,6 +63,15 @@ func (e UserProfileEdges) TextureOrErr() ([]*Texture, error) { return nil, &NotLoadedError{edge: "texture"} } +// UsertextureOrErr returns the Usertexture value or an error if the edge +// was not loaded in eager-loading. +func (e UserProfileEdges) UsertextureOrErr() ([]*UserTexture, error) { + if e.loadedTypes[2] { + return e.Usertexture, nil + } + return nil, &NotLoadedError{edge: "usertexture"} +} + // scanValues returns the types for scanning values from sql.Rows. func (*UserProfile) scanValues(columns []string) ([]any, error) { values := make([]any, len(columns)) @@ -135,6 +146,11 @@ func (up *UserProfile) QueryTexture() *TextureQuery { return NewUserProfileClient(up.config).QueryTexture(up) } +// QueryUsertexture queries the "usertexture" edge of the UserProfile entity. +func (up *UserProfile) QueryUsertexture() *UserTextureQuery { + return NewUserProfileClient(up.config).QueryUsertexture(up) +} + // Update returns a builder for updating this UserProfile. // Note that you need to call UserProfile.Unwrap() before calling this method if this UserProfile // was returned from a transaction, and the transaction was committed or rolled back. diff --git a/db/ent/userprofile/userprofile.go b/db/ent/userprofile/userprofile.go index 0cd0e09..62cf5c2 100644 --- a/db/ent/userprofile/userprofile.go +++ b/db/ent/userprofile/userprofile.go @@ -20,6 +20,8 @@ const ( EdgeUser = "user" // EdgeTexture holds the string denoting the texture edge name in mutations. EdgeTexture = "texture" + // EdgeUsertexture holds the string denoting the usertexture edge name in mutations. + EdgeUsertexture = "usertexture" // Table holds the table name of the userprofile in the database. Table = "user_profiles" // UserTable is the table that holds the user relation/edge. @@ -29,13 +31,18 @@ const ( UserInverseTable = "users" // UserColumn is the table column denoting the user relation/edge. UserColumn = "user_profile" - // TextureTable is the table that holds the texture relation/edge. - TextureTable = "textures" + // TextureTable is the table that holds the texture relation/edge. The primary key declared below. + TextureTable = "user_textures" // TextureInverseTable is the table name for the Texture entity. // It exists in this package in order to avoid circular dependency with the "texture" package. TextureInverseTable = "textures" - // TextureColumn is the table column denoting the texture relation/edge. - TextureColumn = "user_profile_texture" + // UsertextureTable is the table that holds the usertexture relation/edge. + UsertextureTable = "user_textures" + // UsertextureInverseTable is the table name for the UserTexture entity. + // It exists in this package in order to avoid circular dependency with the "usertexture" package. + UsertextureInverseTable = "user_textures" + // UsertextureColumn is the table column denoting the usertexture relation/edge. + UsertextureColumn = "user_profile_id" ) // Columns holds all SQL columns for userprofile fields. @@ -51,6 +58,12 @@ var ForeignKeys = []string{ "user_profile", } +var ( + // TexturePrimaryKey and TextureColumn2 are the table columns denoting the + // primary key for the texture relation (M2M). + TexturePrimaryKey = []string{"user_profile_id", "texture_id"} +) + // ValidColumn reports if the column name is valid (part of the table columns). func ValidColumn(column string) bool { for i := range Columns { @@ -104,6 +117,20 @@ func ByTexture(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { sqlgraph.OrderByNeighborTerms(s, newTextureStep(), append([]sql.OrderTerm{term}, terms...)...) } } + +// ByUsertextureCount orders the results by usertexture count. +func ByUsertextureCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newUsertextureStep(), opts...) + } +} + +// ByUsertexture orders the results by usertexture terms. +func ByUsertexture(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newUsertextureStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} func newUserStep() *sqlgraph.Step { return sqlgraph.NewStep( sqlgraph.From(Table, FieldID), @@ -115,6 +142,13 @@ func newTextureStep() *sqlgraph.Step { return sqlgraph.NewStep( sqlgraph.From(Table, FieldID), sqlgraph.To(TextureInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, TextureTable, TextureColumn), + sqlgraph.Edge(sqlgraph.M2M, false, TextureTable, TexturePrimaryKey...), + ) +} +func newUsertextureStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(UsertextureInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, UsertextureTable, UsertextureColumn), ) } diff --git a/db/ent/userprofile/where.go b/db/ent/userprofile/where.go index c4d6aab..0f5a82d 100644 --- a/db/ent/userprofile/where.go +++ b/db/ent/userprofile/where.go @@ -221,7 +221,7 @@ func HasTexture() predicate.UserProfile { return predicate.UserProfile(func(s *sql.Selector) { step := sqlgraph.NewStep( sqlgraph.From(Table, FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, TextureTable, TextureColumn), + sqlgraph.Edge(sqlgraph.M2M, false, TextureTable, TexturePrimaryKey...), ) sqlgraph.HasNeighbors(s, step) }) @@ -239,6 +239,29 @@ func HasTextureWith(preds ...predicate.Texture) predicate.UserProfile { }) } +// HasUsertexture applies the HasEdge predicate on the "usertexture" edge. +func HasUsertexture() predicate.UserProfile { + return predicate.UserProfile(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, UsertextureTable, UsertextureColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasUsertextureWith applies the HasEdge predicate on the "usertexture" edge with a given conditions (other predicates). +func HasUsertextureWith(preds ...predicate.UserTexture) predicate.UserProfile { + return predicate.UserProfile(func(s *sql.Selector) { + step := newUsertextureStep() + 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.UserProfile) predicate.UserProfile { return predicate.UserProfile(func(s *sql.Selector) { diff --git a/db/ent/userprofile_create.go b/db/ent/userprofile_create.go index 8bd0707..17b348e 100644 --- a/db/ent/userprofile_create.go +++ b/db/ent/userprofile_create.go @@ -12,6 +12,7 @@ import ( "github.com/xmdhs/authlib-skin/db/ent/texture" "github.com/xmdhs/authlib-skin/db/ent/user" "github.com/xmdhs/authlib-skin/db/ent/userprofile" + "github.com/xmdhs/authlib-skin/db/ent/usertexture" ) // UserProfileCreate is the builder for creating a UserProfile entity. @@ -59,6 +60,21 @@ func (upc *UserProfileCreate) AddTexture(t ...*Texture) *UserProfileCreate { return upc.AddTextureIDs(ids...) } +// AddUsertextureIDs adds the "usertexture" edge to the UserTexture entity by IDs. +func (upc *UserProfileCreate) AddUsertextureIDs(ids ...int) *UserProfileCreate { + upc.mutation.AddUsertextureIDs(ids...) + return upc +} + +// AddUsertexture adds the "usertexture" edges to the UserTexture entity. +func (upc *UserProfileCreate) AddUsertexture(u ...*UserTexture) *UserProfileCreate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return upc.AddUsertextureIDs(ids...) +} + // Mutation returns the UserProfileMutation object of the builder. func (upc *UserProfileCreate) Mutation() *UserProfileMutation { return upc.mutation @@ -155,10 +171,10 @@ func (upc *UserProfileCreate) createSpec() (*UserProfile, *sqlgraph.CreateSpec) } if nodes := upc.mutation.TextureIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, + Rel: sqlgraph.M2M, Inverse: false, Table: userprofile.TextureTable, - Columns: []string{userprofile.TextureColumn}, + Columns: userprofile.TexturePrimaryKey, Bidi: false, Target: &sqlgraph.EdgeTarget{ IDSpec: sqlgraph.NewFieldSpec(texture.FieldID, field.TypeInt), @@ -169,6 +185,22 @@ func (upc *UserProfileCreate) createSpec() (*UserProfile, *sqlgraph.CreateSpec) } _spec.Edges = append(_spec.Edges, edge) } + if nodes := upc.mutation.UsertextureIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: userprofile.UsertextureTable, + Columns: []string{userprofile.UsertextureColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usertexture.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } return _node, _spec } diff --git a/db/ent/userprofile_query.go b/db/ent/userprofile_query.go index e8595ee..90fce59 100644 --- a/db/ent/userprofile_query.go +++ b/db/ent/userprofile_query.go @@ -16,19 +16,21 @@ import ( "github.com/xmdhs/authlib-skin/db/ent/texture" "github.com/xmdhs/authlib-skin/db/ent/user" "github.com/xmdhs/authlib-skin/db/ent/userprofile" + "github.com/xmdhs/authlib-skin/db/ent/usertexture" ) // UserProfileQuery is the builder for querying UserProfile entities. type UserProfileQuery struct { config - ctx *QueryContext - order []userprofile.OrderOption - inters []Interceptor - predicates []predicate.UserProfile - withUser *UserQuery - withTexture *TextureQuery - withFKs bool - modifiers []func(*sql.Selector) + ctx *QueryContext + order []userprofile.OrderOption + inters []Interceptor + predicates []predicate.UserProfile + withUser *UserQuery + withTexture *TextureQuery + withUsertexture *UserTextureQuery + withFKs bool + modifiers []func(*sql.Selector) // intermediate query (i.e. traversal path). sql *sql.Selector path func(context.Context) (*sql.Selector, error) @@ -101,7 +103,29 @@ func (upq *UserProfileQuery) QueryTexture() *TextureQuery { step := sqlgraph.NewStep( sqlgraph.From(userprofile.Table, userprofile.FieldID, selector), sqlgraph.To(texture.Table, texture.FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, userprofile.TextureTable, userprofile.TextureColumn), + sqlgraph.Edge(sqlgraph.M2M, false, userprofile.TextureTable, userprofile.TexturePrimaryKey...), + ) + fromU = sqlgraph.SetNeighbors(upq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryUsertexture chains the current query on the "usertexture" edge. +func (upq *UserProfileQuery) QueryUsertexture() *UserTextureQuery { + query := (&UserTextureClient{config: upq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := upq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := upq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(userprofile.Table, userprofile.FieldID, selector), + sqlgraph.To(usertexture.Table, usertexture.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, userprofile.UsertextureTable, userprofile.UsertextureColumn), ) fromU = sqlgraph.SetNeighbors(upq.driver.Dialect(), step) return fromU, nil @@ -296,13 +320,14 @@ func (upq *UserProfileQuery) Clone() *UserProfileQuery { return nil } return &UserProfileQuery{ - config: upq.config, - ctx: upq.ctx.Clone(), - order: append([]userprofile.OrderOption{}, upq.order...), - inters: append([]Interceptor{}, upq.inters...), - predicates: append([]predicate.UserProfile{}, upq.predicates...), - withUser: upq.withUser.Clone(), - withTexture: upq.withTexture.Clone(), + config: upq.config, + ctx: upq.ctx.Clone(), + order: append([]userprofile.OrderOption{}, upq.order...), + inters: append([]Interceptor{}, upq.inters...), + predicates: append([]predicate.UserProfile{}, upq.predicates...), + withUser: upq.withUser.Clone(), + withTexture: upq.withTexture.Clone(), + withUsertexture: upq.withUsertexture.Clone(), // clone intermediate query. sql: upq.sql.Clone(), path: upq.path, @@ -331,6 +356,17 @@ func (upq *UserProfileQuery) WithTexture(opts ...func(*TextureQuery)) *UserProfi return upq } +// WithUsertexture tells the query-builder to eager-load the nodes that are connected to +// the "usertexture" edge. The optional arguments are used to configure the query builder of the edge. +func (upq *UserProfileQuery) WithUsertexture(opts ...func(*UserTextureQuery)) *UserProfileQuery { + query := (&UserTextureClient{config: upq.config}).Query() + for _, opt := range opts { + opt(query) + } + upq.withUsertexture = query + return upq +} + // GroupBy is used to group vertices by one or more fields/columns. // It is often used with aggregate functions, like: count, max, mean, min, sum. // @@ -410,9 +446,10 @@ func (upq *UserProfileQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([] nodes = []*UserProfile{} withFKs = upq.withFKs _spec = upq.querySpec() - loadedTypes = [2]bool{ + loadedTypes = [3]bool{ upq.withUser != nil, upq.withTexture != nil, + upq.withUsertexture != nil, } ) if upq.withUser != nil { @@ -455,6 +492,13 @@ func (upq *UserProfileQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([] return nil, err } } + if query := upq.withUsertexture; query != nil { + if err := upq.loadUsertexture(ctx, query, nodes, + func(n *UserProfile) { n.Edges.Usertexture = []*UserTexture{} }, + func(n *UserProfile, e *UserTexture) { n.Edges.Usertexture = append(n.Edges.Usertexture, e) }); err != nil { + return nil, err + } + } return nodes, nil } @@ -491,6 +535,67 @@ func (upq *UserProfileQuery) loadUser(ctx context.Context, query *UserQuery, nod return nil } func (upq *UserProfileQuery) loadTexture(ctx context.Context, query *TextureQuery, nodes []*UserProfile, init func(*UserProfile), assign func(*UserProfile, *Texture)) error { + edgeIDs := make([]driver.Value, len(nodes)) + byID := make(map[int]*UserProfile) + nids := make(map[int]map[*UserProfile]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(userprofile.TextureTable) + s.Join(joinT).On(s.C(texture.FieldID), joinT.C(userprofile.TexturePrimaryKey[1])) + s.Where(sql.InValues(joinT.C(userprofile.TexturePrimaryKey[0]), edgeIDs...)) + columns := s.SelectedColumns() + s.Select(joinT.C(userprofile.TexturePrimaryKey[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 := int(values[0].(*sql.NullInt64).Int64) + inValue := int(values[1].(*sql.NullInt64).Int64) + if nids[inValue] == nil { + nids[inValue] = map[*UserProfile]struct{}{byID[outValue]: {}} + return assign(columns[1:], values[1:]) + } + nids[inValue][byID[outValue]] = struct{}{} + return nil + } + }) + }) + neighbors, err := withInterceptors[[]*Texture](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 "texture" node returned %v`, n.ID) + } + for kn := range nodes { + assign(kn, n) + } + } + return nil +} +func (upq *UserProfileQuery) loadUsertexture(ctx context.Context, query *UserTextureQuery, nodes []*UserProfile, init func(*UserProfile), assign func(*UserProfile, *UserTexture)) error { fks := make([]driver.Value, 0, len(nodes)) nodeids := make(map[int]*UserProfile) for i := range nodes { @@ -500,22 +605,21 @@ func (upq *UserProfileQuery) loadTexture(ctx context.Context, query *TextureQuer init(nodes[i]) } } - query.withFKs = true - query.Where(predicate.Texture(func(s *sql.Selector) { - s.Where(sql.InValues(s.C(userprofile.TextureColumn), fks...)) + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(usertexture.FieldUserProfileID) + } + query.Where(predicate.UserTexture(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(userprofile.UsertextureColumn), fks...)) })) neighbors, err := query.All(ctx) if err != nil { return err } for _, n := range neighbors { - fk := n.user_profile_texture - if fk == nil { - return fmt.Errorf(`foreign-key "user_profile_texture" is nil for node %v`, n.ID) - } - node, ok := nodeids[*fk] + fk := n.UserProfileID + node, ok := nodeids[fk] if !ok { - return fmt.Errorf(`unexpected referenced foreign-key "user_profile_texture" returned %v for node %v`, *fk, n.ID) + return fmt.Errorf(`unexpected referenced foreign-key "user_profile_id" returned %v for node %v`, fk, n.ID) } assign(node, n) } diff --git a/db/ent/userprofile_update.go b/db/ent/userprofile_update.go index 816baee..3cc70ce 100644 --- a/db/ent/userprofile_update.go +++ b/db/ent/userprofile_update.go @@ -14,6 +14,7 @@ import ( "github.com/xmdhs/authlib-skin/db/ent/texture" "github.com/xmdhs/authlib-skin/db/ent/user" "github.com/xmdhs/authlib-skin/db/ent/userprofile" + "github.com/xmdhs/authlib-skin/db/ent/usertexture" ) // UserProfileUpdate is the builder for updating UserProfile entities. @@ -67,6 +68,21 @@ func (upu *UserProfileUpdate) AddTexture(t ...*Texture) *UserProfileUpdate { return upu.AddTextureIDs(ids...) } +// AddUsertextureIDs adds the "usertexture" edge to the UserTexture entity by IDs. +func (upu *UserProfileUpdate) AddUsertextureIDs(ids ...int) *UserProfileUpdate { + upu.mutation.AddUsertextureIDs(ids...) + return upu +} + +// AddUsertexture adds the "usertexture" edges to the UserTexture entity. +func (upu *UserProfileUpdate) AddUsertexture(u ...*UserTexture) *UserProfileUpdate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return upu.AddUsertextureIDs(ids...) +} + // Mutation returns the UserProfileMutation object of the builder. func (upu *UserProfileUpdate) Mutation() *UserProfileMutation { return upu.mutation @@ -99,6 +115,27 @@ func (upu *UserProfileUpdate) RemoveTexture(t ...*Texture) *UserProfileUpdate { return upu.RemoveTextureIDs(ids...) } +// ClearUsertexture clears all "usertexture" edges to the UserTexture entity. +func (upu *UserProfileUpdate) ClearUsertexture() *UserProfileUpdate { + upu.mutation.ClearUsertexture() + return upu +} + +// RemoveUsertextureIDs removes the "usertexture" edge to UserTexture entities by IDs. +func (upu *UserProfileUpdate) RemoveUsertextureIDs(ids ...int) *UserProfileUpdate { + upu.mutation.RemoveUsertextureIDs(ids...) + return upu +} + +// RemoveUsertexture removes "usertexture" edges to UserTexture entities. +func (upu *UserProfileUpdate) RemoveUsertexture(u ...*UserTexture) *UserProfileUpdate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return upu.RemoveUsertextureIDs(ids...) +} + // Save executes the query and returns the number of nodes affected by the update operation. func (upu *UserProfileUpdate) Save(ctx context.Context) (int, error) { return withHooks(ctx, upu.sqlSave, upu.mutation, upu.hooks) @@ -183,10 +220,10 @@ func (upu *UserProfileUpdate) sqlSave(ctx context.Context) (n int, err error) { } if upu.mutation.TextureCleared() { edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, + Rel: sqlgraph.M2M, Inverse: false, Table: userprofile.TextureTable, - Columns: []string{userprofile.TextureColumn}, + Columns: userprofile.TexturePrimaryKey, Bidi: false, Target: &sqlgraph.EdgeTarget{ IDSpec: sqlgraph.NewFieldSpec(texture.FieldID, field.TypeInt), @@ -196,10 +233,10 @@ func (upu *UserProfileUpdate) sqlSave(ctx context.Context) (n int, err error) { } if nodes := upu.mutation.RemovedTextureIDs(); len(nodes) > 0 && !upu.mutation.TextureCleared() { edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, + Rel: sqlgraph.M2M, Inverse: false, Table: userprofile.TextureTable, - Columns: []string{userprofile.TextureColumn}, + Columns: userprofile.TexturePrimaryKey, Bidi: false, Target: &sqlgraph.EdgeTarget{ IDSpec: sqlgraph.NewFieldSpec(texture.FieldID, field.TypeInt), @@ -212,10 +249,10 @@ func (upu *UserProfileUpdate) sqlSave(ctx context.Context) (n int, err error) { } if nodes := upu.mutation.TextureIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, + Rel: sqlgraph.M2M, Inverse: false, Table: userprofile.TextureTable, - Columns: []string{userprofile.TextureColumn}, + Columns: userprofile.TexturePrimaryKey, Bidi: false, Target: &sqlgraph.EdgeTarget{ IDSpec: sqlgraph.NewFieldSpec(texture.FieldID, field.TypeInt), @@ -226,6 +263,51 @@ func (upu *UserProfileUpdate) sqlSave(ctx context.Context) (n int, err error) { } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if upu.mutation.UsertextureCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: userprofile.UsertextureTable, + Columns: []string{userprofile.UsertextureColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usertexture.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := upu.mutation.RemovedUsertextureIDs(); len(nodes) > 0 && !upu.mutation.UsertextureCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: userprofile.UsertextureTable, + Columns: []string{userprofile.UsertextureColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usertexture.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := upu.mutation.UsertextureIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: userprofile.UsertextureTable, + Columns: []string{userprofile.UsertextureColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usertexture.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } if n, err = sqlgraph.UpdateNodes(ctx, upu.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{userprofile.Label} @@ -284,6 +366,21 @@ func (upuo *UserProfileUpdateOne) AddTexture(t ...*Texture) *UserProfileUpdateOn return upuo.AddTextureIDs(ids...) } +// AddUsertextureIDs adds the "usertexture" edge to the UserTexture entity by IDs. +func (upuo *UserProfileUpdateOne) AddUsertextureIDs(ids ...int) *UserProfileUpdateOne { + upuo.mutation.AddUsertextureIDs(ids...) + return upuo +} + +// AddUsertexture adds the "usertexture" edges to the UserTexture entity. +func (upuo *UserProfileUpdateOne) AddUsertexture(u ...*UserTexture) *UserProfileUpdateOne { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return upuo.AddUsertextureIDs(ids...) +} + // Mutation returns the UserProfileMutation object of the builder. func (upuo *UserProfileUpdateOne) Mutation() *UserProfileMutation { return upuo.mutation @@ -316,6 +413,27 @@ func (upuo *UserProfileUpdateOne) RemoveTexture(t ...*Texture) *UserProfileUpdat return upuo.RemoveTextureIDs(ids...) } +// ClearUsertexture clears all "usertexture" edges to the UserTexture entity. +func (upuo *UserProfileUpdateOne) ClearUsertexture() *UserProfileUpdateOne { + upuo.mutation.ClearUsertexture() + return upuo +} + +// RemoveUsertextureIDs removes the "usertexture" edge to UserTexture entities by IDs. +func (upuo *UserProfileUpdateOne) RemoveUsertextureIDs(ids ...int) *UserProfileUpdateOne { + upuo.mutation.RemoveUsertextureIDs(ids...) + return upuo +} + +// RemoveUsertexture removes "usertexture" edges to UserTexture entities. +func (upuo *UserProfileUpdateOne) RemoveUsertexture(u ...*UserTexture) *UserProfileUpdateOne { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return upuo.RemoveUsertextureIDs(ids...) +} + // Where appends a list predicates to the UserProfileUpdate builder. func (upuo *UserProfileUpdateOne) Where(ps ...predicate.UserProfile) *UserProfileUpdateOne { upuo.mutation.Where(ps...) @@ -430,10 +548,10 @@ func (upuo *UserProfileUpdateOne) sqlSave(ctx context.Context) (_node *UserProfi } if upuo.mutation.TextureCleared() { edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, + Rel: sqlgraph.M2M, Inverse: false, Table: userprofile.TextureTable, - Columns: []string{userprofile.TextureColumn}, + Columns: userprofile.TexturePrimaryKey, Bidi: false, Target: &sqlgraph.EdgeTarget{ IDSpec: sqlgraph.NewFieldSpec(texture.FieldID, field.TypeInt), @@ -443,10 +561,10 @@ func (upuo *UserProfileUpdateOne) sqlSave(ctx context.Context) (_node *UserProfi } if nodes := upuo.mutation.RemovedTextureIDs(); len(nodes) > 0 && !upuo.mutation.TextureCleared() { edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, + Rel: sqlgraph.M2M, Inverse: false, Table: userprofile.TextureTable, - Columns: []string{userprofile.TextureColumn}, + Columns: userprofile.TexturePrimaryKey, Bidi: false, Target: &sqlgraph.EdgeTarget{ IDSpec: sqlgraph.NewFieldSpec(texture.FieldID, field.TypeInt), @@ -459,10 +577,10 @@ func (upuo *UserProfileUpdateOne) sqlSave(ctx context.Context) (_node *UserProfi } if nodes := upuo.mutation.TextureIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, + Rel: sqlgraph.M2M, Inverse: false, Table: userprofile.TextureTable, - Columns: []string{userprofile.TextureColumn}, + Columns: userprofile.TexturePrimaryKey, Bidi: false, Target: &sqlgraph.EdgeTarget{ IDSpec: sqlgraph.NewFieldSpec(texture.FieldID, field.TypeInt), @@ -473,6 +591,51 @@ func (upuo *UserProfileUpdateOne) sqlSave(ctx context.Context) (_node *UserProfi } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if upuo.mutation.UsertextureCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: userprofile.UsertextureTable, + Columns: []string{userprofile.UsertextureColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usertexture.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := upuo.mutation.RemovedUsertextureIDs(); len(nodes) > 0 && !upuo.mutation.UsertextureCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: userprofile.UsertextureTable, + Columns: []string{userprofile.UsertextureColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usertexture.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := upuo.mutation.UsertextureIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: userprofile.UsertextureTable, + Columns: []string{userprofile.UsertextureColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(usertexture.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } _node = &UserProfile{config: upuo.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues diff --git a/db/ent/usertexture.go b/db/ent/usertexture.go new file mode 100644 index 0000000..e73d208 --- /dev/null +++ b/db/ent/usertexture.go @@ -0,0 +1,164 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/xmdhs/authlib-skin/db/ent/texture" + "github.com/xmdhs/authlib-skin/db/ent/userprofile" + "github.com/xmdhs/authlib-skin/db/ent/usertexture" +) + +// UserTexture is the model entity for the UserTexture schema. +type UserTexture struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // UserProfileID holds the value of the "user_profile_id" field. + UserProfileID int `json:"user_profile_id,omitempty"` + // TextureID holds the value of the "texture_id" field. + TextureID int `json:"texture_id,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the UserTextureQuery when eager-loading is set. + Edges UserTextureEdges `json:"edges"` + selectValues sql.SelectValues +} + +// UserTextureEdges holds the relations/edges for other nodes in the graph. +type UserTextureEdges struct { + // UserProfile holds the value of the user_profile edge. + UserProfile *UserProfile `json:"user_profile,omitempty"` + // Texture holds the value of the texture edge. + Texture *Texture `json:"texture,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool +} + +// UserProfileOrErr returns the UserProfile value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e UserTextureEdges) UserProfileOrErr() (*UserProfile, error) { + if e.loadedTypes[0] { + if e.UserProfile == nil { + // Edge was loaded but was not found. + return nil, &NotFoundError{label: userprofile.Label} + } + return e.UserProfile, nil + } + return nil, &NotLoadedError{edge: "user_profile"} +} + +// TextureOrErr returns the Texture value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e UserTextureEdges) TextureOrErr() (*Texture, error) { + if e.loadedTypes[1] { + if e.Texture == nil { + // Edge was loaded but was not found. + return nil, &NotFoundError{label: texture.Label} + } + return e.Texture, nil + } + return nil, &NotLoadedError{edge: "texture"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*UserTexture) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case usertexture.FieldID, usertexture.FieldUserProfileID, usertexture.FieldTextureID: + values[i] = new(sql.NullInt64) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the UserTexture fields. +func (ut *UserTexture) 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 usertexture.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + ut.ID = int(value.Int64) + case usertexture.FieldUserProfileID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field user_profile_id", values[i]) + } else if value.Valid { + ut.UserProfileID = int(value.Int64) + } + case usertexture.FieldTextureID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field texture_id", values[i]) + } else if value.Valid { + ut.TextureID = int(value.Int64) + } + default: + ut.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the UserTexture. +// This includes values selected through modifiers, order, etc. +func (ut *UserTexture) Value(name string) (ent.Value, error) { + return ut.selectValues.Get(name) +} + +// QueryUserProfile queries the "user_profile" edge of the UserTexture entity. +func (ut *UserTexture) QueryUserProfile() *UserProfileQuery { + return NewUserTextureClient(ut.config).QueryUserProfile(ut) +} + +// QueryTexture queries the "texture" edge of the UserTexture entity. +func (ut *UserTexture) QueryTexture() *TextureQuery { + return NewUserTextureClient(ut.config).QueryTexture(ut) +} + +// Update returns a builder for updating this UserTexture. +// Note that you need to call UserTexture.Unwrap() before calling this method if this UserTexture +// was returned from a transaction, and the transaction was committed or rolled back. +func (ut *UserTexture) Update() *UserTextureUpdateOne { + return NewUserTextureClient(ut.config).UpdateOne(ut) +} + +// Unwrap unwraps the UserTexture 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 (ut *UserTexture) Unwrap() *UserTexture { + _tx, ok := ut.config.driver.(*txDriver) + if !ok { + panic("ent: UserTexture is not a transactional entity") + } + ut.config.driver = _tx.drv + return ut +} + +// String implements the fmt.Stringer. +func (ut *UserTexture) String() string { + var builder strings.Builder + builder.WriteString("UserTexture(") + builder.WriteString(fmt.Sprintf("id=%v, ", ut.ID)) + builder.WriteString("user_profile_id=") + builder.WriteString(fmt.Sprintf("%v", ut.UserProfileID)) + builder.WriteString(", ") + builder.WriteString("texture_id=") + builder.WriteString(fmt.Sprintf("%v", ut.TextureID)) + builder.WriteByte(')') + return builder.String() +} + +// UserTextures is a parsable slice of UserTexture. +type UserTextures []*UserTexture diff --git a/db/ent/usertexture/usertexture.go b/db/ent/usertexture/usertexture.go new file mode 100644 index 0000000..225cf96 --- /dev/null +++ b/db/ent/usertexture/usertexture.go @@ -0,0 +1,102 @@ +// Code generated by ent, DO NOT EDIT. + +package usertexture + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the usertexture type in the database. + Label = "user_texture" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldUserProfileID holds the string denoting the user_profile_id field in the database. + FieldUserProfileID = "user_profile_id" + // FieldTextureID holds the string denoting the texture_id field in the database. + FieldTextureID = "texture_id" + // EdgeUserProfile holds the string denoting the user_profile edge name in mutations. + EdgeUserProfile = "user_profile" + // EdgeTexture holds the string denoting the texture edge name in mutations. + EdgeTexture = "texture" + // Table holds the table name of the usertexture in the database. + Table = "user_textures" + // UserProfileTable is the table that holds the user_profile relation/edge. + UserProfileTable = "user_textures" + // UserProfileInverseTable is the table name for the UserProfile entity. + // It exists in this package in order to avoid circular dependency with the "userprofile" package. + UserProfileInverseTable = "user_profiles" + // UserProfileColumn is the table column denoting the user_profile relation/edge. + UserProfileColumn = "user_profile_id" + // TextureTable is the table that holds the texture relation/edge. + TextureTable = "user_textures" + // TextureInverseTable is the table name for the Texture entity. + // It exists in this package in order to avoid circular dependency with the "texture" package. + TextureInverseTable = "textures" + // TextureColumn is the table column denoting the texture relation/edge. + TextureColumn = "texture_id" +) + +// Columns holds all SQL columns for usertexture fields. +var Columns = []string{ + FieldID, + FieldUserProfileID, + FieldTextureID, +} + +// 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 UserTexture 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() +} + +// ByUserProfileID orders the results by the user_profile_id field. +func ByUserProfileID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUserProfileID, opts...).ToFunc() +} + +// ByTextureID orders the results by the texture_id field. +func ByTextureID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTextureID, opts...).ToFunc() +} + +// ByUserProfileField orders the results by user_profile field. +func ByUserProfileField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newUserProfileStep(), sql.OrderByField(field, opts...)) + } +} + +// ByTextureField orders the results by texture field. +func ByTextureField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newTextureStep(), sql.OrderByField(field, opts...)) + } +} +func newUserProfileStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(UserProfileInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, UserProfileTable, UserProfileColumn), + ) +} +func newTextureStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(TextureInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, TextureTable, TextureColumn), + ) +} diff --git a/db/ent/usertexture/where.go b/db/ent/usertexture/where.go new file mode 100644 index 0000000..192cc5e --- /dev/null +++ b/db/ent/usertexture/where.go @@ -0,0 +1,182 @@ +// Code generated by ent, DO NOT EDIT. + +package usertexture + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/xmdhs/authlib-skin/db/ent/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.UserTexture { + return predicate.UserTexture(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.UserTexture { + return predicate.UserTexture(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.UserTexture { + return predicate.UserTexture(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.UserTexture { + return predicate.UserTexture(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.UserTexture { + return predicate.UserTexture(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.UserTexture { + return predicate.UserTexture(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.UserTexture { + return predicate.UserTexture(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.UserTexture { + return predicate.UserTexture(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.UserTexture { + return predicate.UserTexture(sql.FieldLTE(FieldID, id)) +} + +// UserProfileID applies equality check predicate on the "user_profile_id" field. It's identical to UserProfileIDEQ. +func UserProfileID(v int) predicate.UserTexture { + return predicate.UserTexture(sql.FieldEQ(FieldUserProfileID, v)) +} + +// TextureID applies equality check predicate on the "texture_id" field. It's identical to TextureIDEQ. +func TextureID(v int) predicate.UserTexture { + return predicate.UserTexture(sql.FieldEQ(FieldTextureID, v)) +} + +// UserProfileIDEQ applies the EQ predicate on the "user_profile_id" field. +func UserProfileIDEQ(v int) predicate.UserTexture { + return predicate.UserTexture(sql.FieldEQ(FieldUserProfileID, v)) +} + +// UserProfileIDNEQ applies the NEQ predicate on the "user_profile_id" field. +func UserProfileIDNEQ(v int) predicate.UserTexture { + return predicate.UserTexture(sql.FieldNEQ(FieldUserProfileID, v)) +} + +// UserProfileIDIn applies the In predicate on the "user_profile_id" field. +func UserProfileIDIn(vs ...int) predicate.UserTexture { + return predicate.UserTexture(sql.FieldIn(FieldUserProfileID, vs...)) +} + +// UserProfileIDNotIn applies the NotIn predicate on the "user_profile_id" field. +func UserProfileIDNotIn(vs ...int) predicate.UserTexture { + return predicate.UserTexture(sql.FieldNotIn(FieldUserProfileID, vs...)) +} + +// TextureIDEQ applies the EQ predicate on the "texture_id" field. +func TextureIDEQ(v int) predicate.UserTexture { + return predicate.UserTexture(sql.FieldEQ(FieldTextureID, v)) +} + +// TextureIDNEQ applies the NEQ predicate on the "texture_id" field. +func TextureIDNEQ(v int) predicate.UserTexture { + return predicate.UserTexture(sql.FieldNEQ(FieldTextureID, v)) +} + +// TextureIDIn applies the In predicate on the "texture_id" field. +func TextureIDIn(vs ...int) predicate.UserTexture { + return predicate.UserTexture(sql.FieldIn(FieldTextureID, vs...)) +} + +// TextureIDNotIn applies the NotIn predicate on the "texture_id" field. +func TextureIDNotIn(vs ...int) predicate.UserTexture { + return predicate.UserTexture(sql.FieldNotIn(FieldTextureID, vs...)) +} + +// HasUserProfile applies the HasEdge predicate on the "user_profile" edge. +func HasUserProfile() predicate.UserTexture { + return predicate.UserTexture(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, UserProfileTable, UserProfileColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasUserProfileWith applies the HasEdge predicate on the "user_profile" edge with a given conditions (other predicates). +func HasUserProfileWith(preds ...predicate.UserProfile) predicate.UserTexture { + return predicate.UserTexture(func(s *sql.Selector) { + step := newUserProfileStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasTexture applies the HasEdge predicate on the "texture" edge. +func HasTexture() predicate.UserTexture { + return predicate.UserTexture(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, TextureTable, TextureColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasTextureWith applies the HasEdge predicate on the "texture" edge with a given conditions (other predicates). +func HasTextureWith(preds ...predicate.Texture) predicate.UserTexture { + return predicate.UserTexture(func(s *sql.Selector) { + step := newTextureStep() + 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.UserTexture) predicate.UserTexture { + return predicate.UserTexture(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for _, p := range predicates { + p(s1) + } + s.Where(s1.P()) + }) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.UserTexture) predicate.UserTexture { + return predicate.UserTexture(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for i, p := range predicates { + if i > 0 { + s1.Or() + } + p(s1) + } + s.Where(s1.P()) + }) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.UserTexture) predicate.UserTexture { + return predicate.UserTexture(func(s *sql.Selector) { + p(s.Not()) + }) +} diff --git a/db/ent/usertexture_create.go b/db/ent/usertexture_create.go new file mode 100644 index 0000000..80c2487 --- /dev/null +++ b/db/ent/usertexture_create.go @@ -0,0 +1,236 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/xmdhs/authlib-skin/db/ent/texture" + "github.com/xmdhs/authlib-skin/db/ent/userprofile" + "github.com/xmdhs/authlib-skin/db/ent/usertexture" +) + +// UserTextureCreate is the builder for creating a UserTexture entity. +type UserTextureCreate struct { + config + mutation *UserTextureMutation + hooks []Hook +} + +// SetUserProfileID sets the "user_profile_id" field. +func (utc *UserTextureCreate) SetUserProfileID(i int) *UserTextureCreate { + utc.mutation.SetUserProfileID(i) + return utc +} + +// SetTextureID sets the "texture_id" field. +func (utc *UserTextureCreate) SetTextureID(i int) *UserTextureCreate { + utc.mutation.SetTextureID(i) + return utc +} + +// SetUserProfile sets the "user_profile" edge to the UserProfile entity. +func (utc *UserTextureCreate) SetUserProfile(u *UserProfile) *UserTextureCreate { + return utc.SetUserProfileID(u.ID) +} + +// SetTexture sets the "texture" edge to the Texture entity. +func (utc *UserTextureCreate) SetTexture(t *Texture) *UserTextureCreate { + return utc.SetTextureID(t.ID) +} + +// Mutation returns the UserTextureMutation object of the builder. +func (utc *UserTextureCreate) Mutation() *UserTextureMutation { + return utc.mutation +} + +// Save creates the UserTexture in the database. +func (utc *UserTextureCreate) Save(ctx context.Context) (*UserTexture, error) { + return withHooks(ctx, utc.sqlSave, utc.mutation, utc.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (utc *UserTextureCreate) SaveX(ctx context.Context) *UserTexture { + v, err := utc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (utc *UserTextureCreate) Exec(ctx context.Context) error { + _, err := utc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (utc *UserTextureCreate) ExecX(ctx context.Context) { + if err := utc.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (utc *UserTextureCreate) check() error { + if _, ok := utc.mutation.UserProfileID(); !ok { + return &ValidationError{Name: "user_profile_id", err: errors.New(`ent: missing required field "UserTexture.user_profile_id"`)} + } + if _, ok := utc.mutation.TextureID(); !ok { + return &ValidationError{Name: "texture_id", err: errors.New(`ent: missing required field "UserTexture.texture_id"`)} + } + if _, ok := utc.mutation.UserProfileID(); !ok { + return &ValidationError{Name: "user_profile", err: errors.New(`ent: missing required edge "UserTexture.user_profile"`)} + } + if _, ok := utc.mutation.TextureID(); !ok { + return &ValidationError{Name: "texture", err: errors.New(`ent: missing required edge "UserTexture.texture"`)} + } + return nil +} + +func (utc *UserTextureCreate) sqlSave(ctx context.Context) (*UserTexture, error) { + if err := utc.check(); err != nil { + return nil, err + } + _node, _spec := utc.createSpec() + if err := sqlgraph.CreateNode(ctx, utc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + utc.mutation.id = &_node.ID + utc.mutation.done = true + return _node, nil +} + +func (utc *UserTextureCreate) createSpec() (*UserTexture, *sqlgraph.CreateSpec) { + var ( + _node = &UserTexture{config: utc.config} + _spec = sqlgraph.NewCreateSpec(usertexture.Table, sqlgraph.NewFieldSpec(usertexture.FieldID, field.TypeInt)) + ) + if nodes := utc.mutation.UserProfileIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: usertexture.UserProfileTable, + Columns: []string{usertexture.UserProfileColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(userprofile.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.UserProfileID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := utc.mutation.TextureIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: usertexture.TextureTable, + Columns: []string{usertexture.TextureColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(texture.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.TextureID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// UserTextureCreateBulk is the builder for creating many UserTexture entities in bulk. +type UserTextureCreateBulk struct { + config + builders []*UserTextureCreate +} + +// Save creates the UserTexture entities in the database. +func (utcb *UserTextureCreateBulk) Save(ctx context.Context) ([]*UserTexture, error) { + specs := make([]*sqlgraph.CreateSpec, len(utcb.builders)) + nodes := make([]*UserTexture, len(utcb.builders)) + mutators := make([]Mutator, len(utcb.builders)) + for i := range utcb.builders { + func(i int, root context.Context) { + builder := utcb.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*UserTextureMutation) + 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, utcb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, utcb.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 { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(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, utcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (utcb *UserTextureCreateBulk) SaveX(ctx context.Context) []*UserTexture { + v, err := utcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (utcb *UserTextureCreateBulk) Exec(ctx context.Context) error { + _, err := utcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (utcb *UserTextureCreateBulk) ExecX(ctx context.Context) { + if err := utcb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/db/ent/usertexture_delete.go b/db/ent/usertexture_delete.go new file mode 100644 index 0000000..62b7bb0 --- /dev/null +++ b/db/ent/usertexture_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/xmdhs/authlib-skin/db/ent/predicate" + "github.com/xmdhs/authlib-skin/db/ent/usertexture" +) + +// UserTextureDelete is the builder for deleting a UserTexture entity. +type UserTextureDelete struct { + config + hooks []Hook + mutation *UserTextureMutation +} + +// Where appends a list predicates to the UserTextureDelete builder. +func (utd *UserTextureDelete) Where(ps ...predicate.UserTexture) *UserTextureDelete { + utd.mutation.Where(ps...) + return utd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (utd *UserTextureDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, utd.sqlExec, utd.mutation, utd.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (utd *UserTextureDelete) ExecX(ctx context.Context) int { + n, err := utd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (utd *UserTextureDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(usertexture.Table, sqlgraph.NewFieldSpec(usertexture.FieldID, field.TypeInt)) + if ps := utd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, utd.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + utd.mutation.done = true + return affected, err +} + +// UserTextureDeleteOne is the builder for deleting a single UserTexture entity. +type UserTextureDeleteOne struct { + utd *UserTextureDelete +} + +// Where appends a list predicates to the UserTextureDelete builder. +func (utdo *UserTextureDeleteOne) Where(ps ...predicate.UserTexture) *UserTextureDeleteOne { + utdo.utd.mutation.Where(ps...) + return utdo +} + +// Exec executes the deletion query. +func (utdo *UserTextureDeleteOne) Exec(ctx context.Context) error { + n, err := utdo.utd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{usertexture.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (utdo *UserTextureDeleteOne) ExecX(ctx context.Context) { + if err := utdo.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/db/ent/usertexture_query.go b/db/ent/usertexture_query.go new file mode 100644 index 0000000..2ea3e9f --- /dev/null +++ b/db/ent/usertexture_query.go @@ -0,0 +1,717 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + "math" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/xmdhs/authlib-skin/db/ent/predicate" + "github.com/xmdhs/authlib-skin/db/ent/texture" + "github.com/xmdhs/authlib-skin/db/ent/userprofile" + "github.com/xmdhs/authlib-skin/db/ent/usertexture" +) + +// UserTextureQuery is the builder for querying UserTexture entities. +type UserTextureQuery struct { + config + ctx *QueryContext + order []usertexture.OrderOption + inters []Interceptor + predicates []predicate.UserTexture + withUserProfile *UserProfileQuery + withTexture *TextureQuery + 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 UserTextureQuery builder. +func (utq *UserTextureQuery) Where(ps ...predicate.UserTexture) *UserTextureQuery { + utq.predicates = append(utq.predicates, ps...) + return utq +} + +// Limit the number of records to be returned by this query. +func (utq *UserTextureQuery) Limit(limit int) *UserTextureQuery { + utq.ctx.Limit = &limit + return utq +} + +// Offset to start from. +func (utq *UserTextureQuery) Offset(offset int) *UserTextureQuery { + utq.ctx.Offset = &offset + return utq +} + +// 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 (utq *UserTextureQuery) Unique(unique bool) *UserTextureQuery { + utq.ctx.Unique = &unique + return utq +} + +// Order specifies how the records should be ordered. +func (utq *UserTextureQuery) Order(o ...usertexture.OrderOption) *UserTextureQuery { + utq.order = append(utq.order, o...) + return utq +} + +// QueryUserProfile chains the current query on the "user_profile" edge. +func (utq *UserTextureQuery) QueryUserProfile() *UserProfileQuery { + query := (&UserProfileClient{config: utq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := utq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := utq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(usertexture.Table, usertexture.FieldID, selector), + sqlgraph.To(userprofile.Table, userprofile.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, usertexture.UserProfileTable, usertexture.UserProfileColumn), + ) + fromU = sqlgraph.SetNeighbors(utq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryTexture chains the current query on the "texture" edge. +func (utq *UserTextureQuery) QueryTexture() *TextureQuery { + query := (&TextureClient{config: utq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := utq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := utq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(usertexture.Table, usertexture.FieldID, selector), + sqlgraph.To(texture.Table, texture.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, usertexture.TextureTable, usertexture.TextureColumn), + ) + fromU = sqlgraph.SetNeighbors(utq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first UserTexture entity from the query. +// Returns a *NotFoundError when no UserTexture was found. +func (utq *UserTextureQuery) First(ctx context.Context) (*UserTexture, error) { + nodes, err := utq.Limit(1).All(setContextOp(ctx, utq.ctx, "First")) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{usertexture.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (utq *UserTextureQuery) FirstX(ctx context.Context) *UserTexture { + node, err := utq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first UserTexture ID from the query. +// Returns a *NotFoundError when no UserTexture ID was found. +func (utq *UserTextureQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = utq.Limit(1).IDs(setContextOp(ctx, utq.ctx, "FirstID")); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{usertexture.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (utq *UserTextureQuery) FirstIDX(ctx context.Context) int { + id, err := utq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single UserTexture entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one UserTexture entity is found. +// Returns a *NotFoundError when no UserTexture entities are found. +func (utq *UserTextureQuery) Only(ctx context.Context) (*UserTexture, error) { + nodes, err := utq.Limit(2).All(setContextOp(ctx, utq.ctx, "Only")) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{usertexture.Label} + default: + return nil, &NotSingularError{usertexture.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (utq *UserTextureQuery) OnlyX(ctx context.Context) *UserTexture { + node, err := utq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only UserTexture ID in the query. +// Returns a *NotSingularError when more than one UserTexture ID is found. +// Returns a *NotFoundError when no entities are found. +func (utq *UserTextureQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = utq.Limit(2).IDs(setContextOp(ctx, utq.ctx, "OnlyID")); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{usertexture.Label} + default: + err = &NotSingularError{usertexture.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (utq *UserTextureQuery) OnlyIDX(ctx context.Context) int { + id, err := utq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of UserTextures. +func (utq *UserTextureQuery) All(ctx context.Context) ([]*UserTexture, error) { + ctx = setContextOp(ctx, utq.ctx, "All") + if err := utq.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*UserTexture, *UserTextureQuery]() + return withInterceptors[[]*UserTexture](ctx, utq, qr, utq.inters) +} + +// AllX is like All, but panics if an error occurs. +func (utq *UserTextureQuery) AllX(ctx context.Context) []*UserTexture { + nodes, err := utq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of UserTexture IDs. +func (utq *UserTextureQuery) IDs(ctx context.Context) (ids []int, err error) { + if utq.ctx.Unique == nil && utq.path != nil { + utq.Unique(true) + } + ctx = setContextOp(ctx, utq.ctx, "IDs") + if err = utq.Select(usertexture.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (utq *UserTextureQuery) IDsX(ctx context.Context) []int { + ids, err := utq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (utq *UserTextureQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, utq.ctx, "Count") + if err := utq.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, utq, querierCount[*UserTextureQuery](), utq.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (utq *UserTextureQuery) CountX(ctx context.Context) int { + count, err := utq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (utq *UserTextureQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, utq.ctx, "Exist") + switch _, err := utq.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("ent: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (utq *UserTextureQuery) ExistX(ctx context.Context) bool { + exist, err := utq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the UserTextureQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (utq *UserTextureQuery) Clone() *UserTextureQuery { + if utq == nil { + return nil + } + return &UserTextureQuery{ + config: utq.config, + ctx: utq.ctx.Clone(), + order: append([]usertexture.OrderOption{}, utq.order...), + inters: append([]Interceptor{}, utq.inters...), + predicates: append([]predicate.UserTexture{}, utq.predicates...), + withUserProfile: utq.withUserProfile.Clone(), + withTexture: utq.withTexture.Clone(), + // clone intermediate query. + sql: utq.sql.Clone(), + path: utq.path, + } +} + +// WithUserProfile tells the query-builder to eager-load the nodes that are connected to +// the "user_profile" edge. The optional arguments are used to configure the query builder of the edge. +func (utq *UserTextureQuery) WithUserProfile(opts ...func(*UserProfileQuery)) *UserTextureQuery { + query := (&UserProfileClient{config: utq.config}).Query() + for _, opt := range opts { + opt(query) + } + utq.withUserProfile = query + return utq +} + +// WithTexture tells the query-builder to eager-load the nodes that are connected to +// the "texture" edge. The optional arguments are used to configure the query builder of the edge. +func (utq *UserTextureQuery) WithTexture(opts ...func(*TextureQuery)) *UserTextureQuery { + query := (&TextureClient{config: utq.config}).Query() + for _, opt := range opts { + opt(query) + } + utq.withTexture = query + return utq +} + +// 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 { +// UserProfileID int `json:"user_profile_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.UserTexture.Query(). +// GroupBy(usertexture.FieldUserProfileID). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (utq *UserTextureQuery) GroupBy(field string, fields ...string) *UserTextureGroupBy { + utq.ctx.Fields = append([]string{field}, fields...) + grbuild := &UserTextureGroupBy{build: utq} + grbuild.flds = &utq.ctx.Fields + grbuild.label = usertexture.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 { +// UserProfileID int `json:"user_profile_id,omitempty"` +// } +// +// client.UserTexture.Query(). +// Select(usertexture.FieldUserProfileID). +// Scan(ctx, &v) +func (utq *UserTextureQuery) Select(fields ...string) *UserTextureSelect { + utq.ctx.Fields = append(utq.ctx.Fields, fields...) + sbuild := &UserTextureSelect{UserTextureQuery: utq} + sbuild.label = usertexture.Label + sbuild.flds, sbuild.scan = &utq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a UserTextureSelect configured with the given aggregations. +func (utq *UserTextureQuery) Aggregate(fns ...AggregateFunc) *UserTextureSelect { + return utq.Select().Aggregate(fns...) +} + +func (utq *UserTextureQuery) prepareQuery(ctx context.Context) error { + for _, inter := range utq.inters { + if inter == nil { + return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, utq); err != nil { + return err + } + } + } + for _, f := range utq.ctx.Fields { + if !usertexture.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if utq.path != nil { + prev, err := utq.path(ctx) + if err != nil { + return err + } + utq.sql = prev + } + return nil +} + +func (utq *UserTextureQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*UserTexture, error) { + var ( + nodes = []*UserTexture{} + _spec = utq.querySpec() + loadedTypes = [2]bool{ + utq.withUserProfile != nil, + utq.withTexture != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*UserTexture).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &UserTexture{config: utq.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(utq.modifiers) > 0 { + _spec.Modifiers = utq.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, utq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := utq.withUserProfile; query != nil { + if err := utq.loadUserProfile(ctx, query, nodes, nil, + func(n *UserTexture, e *UserProfile) { n.Edges.UserProfile = e }); err != nil { + return nil, err + } + } + if query := utq.withTexture; query != nil { + if err := utq.loadTexture(ctx, query, nodes, nil, + func(n *UserTexture, e *Texture) { n.Edges.Texture = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (utq *UserTextureQuery) loadUserProfile(ctx context.Context, query *UserProfileQuery, nodes []*UserTexture, init func(*UserTexture), assign func(*UserTexture, *UserProfile)) error { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*UserTexture) + for i := range nodes { + fk := nodes[i].UserProfileID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(userprofile.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_profile_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (utq *UserTextureQuery) loadTexture(ctx context.Context, query *TextureQuery, nodes []*UserTexture, init func(*UserTexture), assign func(*UserTexture, *Texture)) error { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*UserTexture) + for i := range nodes { + fk := nodes[i].TextureID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(texture.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 "texture_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (utq *UserTextureQuery) sqlCount(ctx context.Context) (int, error) { + _spec := utq.querySpec() + if len(utq.modifiers) > 0 { + _spec.Modifiers = utq.modifiers + } + _spec.Node.Columns = utq.ctx.Fields + if len(utq.ctx.Fields) > 0 { + _spec.Unique = utq.ctx.Unique != nil && *utq.ctx.Unique + } + return sqlgraph.CountNodes(ctx, utq.driver, _spec) +} + +func (utq *UserTextureQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(usertexture.Table, usertexture.Columns, sqlgraph.NewFieldSpec(usertexture.FieldID, field.TypeInt)) + _spec.From = utq.sql + if unique := utq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if utq.path != nil { + _spec.Unique = true + } + if fields := utq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, usertexture.FieldID) + for i := range fields { + if fields[i] != usertexture.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if utq.withUserProfile != nil { + _spec.Node.AddColumnOnce(usertexture.FieldUserProfileID) + } + if utq.withTexture != nil { + _spec.Node.AddColumnOnce(usertexture.FieldTextureID) + } + } + if ps := utq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := utq.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := utq.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := utq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (utq *UserTextureQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(utq.driver.Dialect()) + t1 := builder.Table(usertexture.Table) + columns := utq.ctx.Fields + if len(columns) == 0 { + columns = usertexture.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if utq.sql != nil { + selector = utq.sql + selector.Select(selector.Columns(columns...)...) + } + if utq.ctx.Unique != nil && *utq.ctx.Unique { + selector.Distinct() + } + for _, m := range utq.modifiers { + m(selector) + } + for _, p := range utq.predicates { + p(selector) + } + for _, p := range utq.order { + p(selector) + } + if offset := utq.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 := utq.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 (utq *UserTextureQuery) ForUpdate(opts ...sql.LockOption) *UserTextureQuery { + if utq.driver.Dialect() == dialect.Postgres { + utq.Unique(false) + } + utq.modifiers = append(utq.modifiers, func(s *sql.Selector) { + s.ForUpdate(opts...) + }) + return utq +} + +// 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 (utq *UserTextureQuery) ForShare(opts ...sql.LockOption) *UserTextureQuery { + if utq.driver.Dialect() == dialect.Postgres { + utq.Unique(false) + } + utq.modifiers = append(utq.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return utq +} + +// UserTextureGroupBy is the group-by builder for UserTexture entities. +type UserTextureGroupBy struct { + selector + build *UserTextureQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (utgb *UserTextureGroupBy) Aggregate(fns ...AggregateFunc) *UserTextureGroupBy { + utgb.fns = append(utgb.fns, fns...) + return utgb +} + +// Scan applies the selector query and scans the result into the given value. +func (utgb *UserTextureGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, utgb.build.ctx, "GroupBy") + if err := utgb.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*UserTextureQuery, *UserTextureGroupBy](ctx, utgb.build, utgb, utgb.build.inters, v) +} + +func (utgb *UserTextureGroupBy) sqlScan(ctx context.Context, root *UserTextureQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(utgb.fns)) + for _, fn := range utgb.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*utgb.flds)+len(utgb.fns)) + for _, f := range *utgb.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*utgb.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := utgb.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// UserTextureSelect is the builder for selecting fields of UserTexture entities. +type UserTextureSelect struct { + *UserTextureQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (uts *UserTextureSelect) Aggregate(fns ...AggregateFunc) *UserTextureSelect { + uts.fns = append(uts.fns, fns...) + return uts +} + +// Scan applies the selector query and scans the result into the given value. +func (uts *UserTextureSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, uts.ctx, "Select") + if err := uts.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*UserTextureQuery, *UserTextureSelect](ctx, uts.UserTextureQuery, uts, uts.inters, v) +} + +func (uts *UserTextureSelect) sqlScan(ctx context.Context, root *UserTextureQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(uts.fns)) + for _, fn := range uts.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*uts.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 := uts.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/db/ent/usertexture_update.go b/db/ent/usertexture_update.go new file mode 100644 index 0000000..1bf55ad --- /dev/null +++ b/db/ent/usertexture_update.go @@ -0,0 +1,389 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/xmdhs/authlib-skin/db/ent/predicate" + "github.com/xmdhs/authlib-skin/db/ent/texture" + "github.com/xmdhs/authlib-skin/db/ent/userprofile" + "github.com/xmdhs/authlib-skin/db/ent/usertexture" +) + +// UserTextureUpdate is the builder for updating UserTexture entities. +type UserTextureUpdate struct { + config + hooks []Hook + mutation *UserTextureMutation +} + +// Where appends a list predicates to the UserTextureUpdate builder. +func (utu *UserTextureUpdate) Where(ps ...predicate.UserTexture) *UserTextureUpdate { + utu.mutation.Where(ps...) + return utu +} + +// SetUserProfileID sets the "user_profile_id" field. +func (utu *UserTextureUpdate) SetUserProfileID(i int) *UserTextureUpdate { + utu.mutation.SetUserProfileID(i) + return utu +} + +// SetTextureID sets the "texture_id" field. +func (utu *UserTextureUpdate) SetTextureID(i int) *UserTextureUpdate { + utu.mutation.SetTextureID(i) + return utu +} + +// SetUserProfile sets the "user_profile" edge to the UserProfile entity. +func (utu *UserTextureUpdate) SetUserProfile(u *UserProfile) *UserTextureUpdate { + return utu.SetUserProfileID(u.ID) +} + +// SetTexture sets the "texture" edge to the Texture entity. +func (utu *UserTextureUpdate) SetTexture(t *Texture) *UserTextureUpdate { + return utu.SetTextureID(t.ID) +} + +// Mutation returns the UserTextureMutation object of the builder. +func (utu *UserTextureUpdate) Mutation() *UserTextureMutation { + return utu.mutation +} + +// ClearUserProfile clears the "user_profile" edge to the UserProfile entity. +func (utu *UserTextureUpdate) ClearUserProfile() *UserTextureUpdate { + utu.mutation.ClearUserProfile() + return utu +} + +// ClearTexture clears the "texture" edge to the Texture entity. +func (utu *UserTextureUpdate) ClearTexture() *UserTextureUpdate { + utu.mutation.ClearTexture() + return utu +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (utu *UserTextureUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, utu.sqlSave, utu.mutation, utu.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (utu *UserTextureUpdate) SaveX(ctx context.Context) int { + affected, err := utu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (utu *UserTextureUpdate) Exec(ctx context.Context) error { + _, err := utu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (utu *UserTextureUpdate) ExecX(ctx context.Context) { + if err := utu.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (utu *UserTextureUpdate) check() error { + if _, ok := utu.mutation.UserProfileID(); utu.mutation.UserProfileCleared() && !ok { + return errors.New(`ent: clearing a required unique edge "UserTexture.user_profile"`) + } + if _, ok := utu.mutation.TextureID(); utu.mutation.TextureCleared() && !ok { + return errors.New(`ent: clearing a required unique edge "UserTexture.texture"`) + } + return nil +} + +func (utu *UserTextureUpdate) sqlSave(ctx context.Context) (n int, err error) { + if err := utu.check(); err != nil { + return n, err + } + _spec := sqlgraph.NewUpdateSpec(usertexture.Table, usertexture.Columns, sqlgraph.NewFieldSpec(usertexture.FieldID, field.TypeInt)) + if ps := utu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if utu.mutation.UserProfileCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: usertexture.UserProfileTable, + Columns: []string{usertexture.UserProfileColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(userprofile.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := utu.mutation.UserProfileIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: usertexture.UserProfileTable, + Columns: []string{usertexture.UserProfileColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(userprofile.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if utu.mutation.TextureCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: usertexture.TextureTable, + Columns: []string{usertexture.TextureColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(texture.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := utu.mutation.TextureIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: usertexture.TextureTable, + Columns: []string{usertexture.TextureColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(texture.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if n, err = sqlgraph.UpdateNodes(ctx, utu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{usertexture.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + utu.mutation.done = true + return n, nil +} + +// UserTextureUpdateOne is the builder for updating a single UserTexture entity. +type UserTextureUpdateOne struct { + config + fields []string + hooks []Hook + mutation *UserTextureMutation +} + +// SetUserProfileID sets the "user_profile_id" field. +func (utuo *UserTextureUpdateOne) SetUserProfileID(i int) *UserTextureUpdateOne { + utuo.mutation.SetUserProfileID(i) + return utuo +} + +// SetTextureID sets the "texture_id" field. +func (utuo *UserTextureUpdateOne) SetTextureID(i int) *UserTextureUpdateOne { + utuo.mutation.SetTextureID(i) + return utuo +} + +// SetUserProfile sets the "user_profile" edge to the UserProfile entity. +func (utuo *UserTextureUpdateOne) SetUserProfile(u *UserProfile) *UserTextureUpdateOne { + return utuo.SetUserProfileID(u.ID) +} + +// SetTexture sets the "texture" edge to the Texture entity. +func (utuo *UserTextureUpdateOne) SetTexture(t *Texture) *UserTextureUpdateOne { + return utuo.SetTextureID(t.ID) +} + +// Mutation returns the UserTextureMutation object of the builder. +func (utuo *UserTextureUpdateOne) Mutation() *UserTextureMutation { + return utuo.mutation +} + +// ClearUserProfile clears the "user_profile" edge to the UserProfile entity. +func (utuo *UserTextureUpdateOne) ClearUserProfile() *UserTextureUpdateOne { + utuo.mutation.ClearUserProfile() + return utuo +} + +// ClearTexture clears the "texture" edge to the Texture entity. +func (utuo *UserTextureUpdateOne) ClearTexture() *UserTextureUpdateOne { + utuo.mutation.ClearTexture() + return utuo +} + +// Where appends a list predicates to the UserTextureUpdate builder. +func (utuo *UserTextureUpdateOne) Where(ps ...predicate.UserTexture) *UserTextureUpdateOne { + utuo.mutation.Where(ps...) + return utuo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (utuo *UserTextureUpdateOne) Select(field string, fields ...string) *UserTextureUpdateOne { + utuo.fields = append([]string{field}, fields...) + return utuo +} + +// Save executes the query and returns the updated UserTexture entity. +func (utuo *UserTextureUpdateOne) Save(ctx context.Context) (*UserTexture, error) { + return withHooks(ctx, utuo.sqlSave, utuo.mutation, utuo.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (utuo *UserTextureUpdateOne) SaveX(ctx context.Context) *UserTexture { + node, err := utuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (utuo *UserTextureUpdateOne) Exec(ctx context.Context) error { + _, err := utuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (utuo *UserTextureUpdateOne) ExecX(ctx context.Context) { + if err := utuo.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (utuo *UserTextureUpdateOne) check() error { + if _, ok := utuo.mutation.UserProfileID(); utuo.mutation.UserProfileCleared() && !ok { + return errors.New(`ent: clearing a required unique edge "UserTexture.user_profile"`) + } + if _, ok := utuo.mutation.TextureID(); utuo.mutation.TextureCleared() && !ok { + return errors.New(`ent: clearing a required unique edge "UserTexture.texture"`) + } + return nil +} + +func (utuo *UserTextureUpdateOne) sqlSave(ctx context.Context) (_node *UserTexture, err error) { + if err := utuo.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(usertexture.Table, usertexture.Columns, sqlgraph.NewFieldSpec(usertexture.FieldID, field.TypeInt)) + id, ok := utuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "UserTexture.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := utuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, usertexture.FieldID) + for _, f := range fields { + if !usertexture.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != usertexture.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := utuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if utuo.mutation.UserProfileCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: usertexture.UserProfileTable, + Columns: []string{usertexture.UserProfileColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(userprofile.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := utuo.mutation.UserProfileIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: usertexture.UserProfileTable, + Columns: []string{usertexture.UserProfileColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(userprofile.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if utuo.mutation.TextureCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: usertexture.TextureTable, + Columns: []string{usertexture.TextureColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(texture.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := utuo.mutation.TextureIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: usertexture.TextureTable, + Columns: []string{usertexture.TextureColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(texture.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &UserTexture{config: utuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, utuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{usertexture.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + utuo.mutation.done = true + return _node, nil +} diff --git a/service/yggdrasil/texture.go b/service/yggdrasil/texture.go index 9caf612..6e7f692 100644 --- a/service/yggdrasil/texture.go +++ b/service/yggdrasil/texture.go @@ -13,6 +13,7 @@ import ( "github.com/xmdhs/authlib-skin/db/ent/texture" "github.com/xmdhs/authlib-skin/db/ent/user" "github.com/xmdhs/authlib-skin/db/ent/userprofile" + "github.com/xmdhs/authlib-skin/db/ent/usertexture" "github.com/xmdhs/authlib-skin/model/yggdrasil" utilsService "github.com/xmdhs/authlib-skin/service/utils" "github.com/xmdhs/authlib-skin/utils" @@ -36,7 +37,10 @@ func (y *Yggdrasil) PutTexture(ctx context.Context, token string, texturebyte [] err = utils.WithTx(ctx, y.client, func(tx *ent.Tx) error { // 查找此用户该类型下是否已经存在皮肤 - tl, err := tx.UserProfile.QueryTexture(up).Where(texture.TypeEQ(textureType)).ForUpdate().All(ctx) + tl, err := tx.UserTexture.Query().Where(usertexture.And( + usertexture.UserProfileID(up.ID), + usertexture.HasTextureWith(texture.Type(textureType)), + )).ForUpdate().All(ctx) if err != nil { return err } @@ -45,27 +49,34 @@ func (y *Yggdrasil) PutTexture(ctx context.Context, token string, texturebyte [] } // 若存在,查找是否被引用 for _, v := range tl { - c, err := tx.UserProfile.Query().Where(userprofile.HasTextureWith(texture.IDEQ(v.ID))).Count(ctx) + c, err := tx.UserTexture.Query().Where(usertexture.TextureID(v.TextureID)).ForUpdate().Count(ctx) if err != nil { return err } if c == 1 { // 若没有其他用户使用该皮肤,删除文件和记录 - path := filepath.Join(y.TexturePath, v.TextureHash[:2], v.TextureHash[2:4], v.TextureHash) + t, err := tx.Texture.Query().Where(texture.ID(v.TextureID)).Only(ctx) + if err != nil { + return err + } + path := filepath.Join(y.TexturePath, t.TextureHash[:2], t.TextureHash[2:4], t.TextureHash) err = os.Remove(path) if err != nil { return err } - err = tx.Texture.DeleteOneID(v.ID).Exec(ctx) + // Texture 表中删除记录 + err = tx.Texture.DeleteOneID(v.TextureID).Exec(ctx) if err != nil { return err } } } - ids := lo.Map[*ent.Texture, int](tl, func(item *ent.Texture, index int) int { - return item.ID + ids := lo.Map[*ent.UserTexture, int](tl, func(item *ent.UserTexture, index int) int { + return item.UserProfileID }) - return tx.UserProfile.UpdateOne(up).RemoveTextureIDs(ids...).Exec(ctx) + // 中间表删除记录 + _, err = tx.UserTexture.Delete().Where(usertexture.UserProfileIDIn(ids...)).Exec(ctx) + return err }) hashstr, err := createTextureFile(y.config.TexturePath, texturebyte) @@ -73,25 +84,12 @@ func (y *Yggdrasil) PutTexture(ctx context.Context, token string, texturebyte [] return fmt.Errorf("PutTexture: %w", err) } - var textureEnt *ent.Texture err = utils.WithTx(ctx, y.client, func(tx *ent.Tx) error { - textureEnt, err = tx.Texture.Query().Where(texture.TextureHashEQ(hashstr)).ForUpdate().First(ctx) - var nr *ent.NotFoundError - if err != nil && !errors.As(err, &nr) { - return err - } - if textureEnt == nil { - textureEnt, err = tx.Texture.Create().SetCreatedUser(up.Edges.User). - SetTextureHash(hashstr). - SetType(textureType). - SetVariant(model). - Save(ctx) - if err != nil { - return err - } - } - return tx.UserProfile.UpdateOne(up).AddTexture(textureEnt).Exec(ctx) + tx.Texture. + + }) + if err != nil { return fmt.Errorf("PutTexture: %w", err) } diff --git a/service/yggdrasil/user.go b/service/yggdrasil/user.go index 53b7faa..f297b8d 100644 --- a/service/yggdrasil/user.go +++ b/service/yggdrasil/user.go @@ -67,10 +67,6 @@ func (y *Yggdrasil) Authenticate(cxt context.Context, auth yggdrasil.Authenticat if err != nil { return err } - err = tx.User.UpdateOne(u).SetToken(ut).Exec(cxt) - if err != nil { - return err - } utoken = ut } return nil