diff --git a/entc/gen/template/dialect/sql/feature/schemaconfig.tmpl b/entc/gen/template/dialect/sql/feature/schemaconfig.tmpl index 172ccf099..ce6b40443 100644 --- a/entc/gen/template/dialect/sql/feature/schemaconfig.tmpl +++ b/entc/gen/template/dialect/sql/feature/schemaconfig.tmpl @@ -19,7 +19,7 @@ type SchemaConfig struct { {{ $n.Name }} string // {{ $n.Name }} table. {{- range $e := $n.Edges }} {{- /* Skip adding join-table in case the edge is inverse or already defined as an edge-schema. */}} - {{- if and $e.M2M (not $e.Inverse) (not $e.Through) }} + {{- if and $e.M2M (not $e.Inverse) }} {{ $n.Name }}{{ $e.StructField }} string // {{ $n.Name }}-{{ $e.Name }}->{{ $e.Type.Name }} table. {{- end }} {{- end }} diff --git a/entc/integration/multischema/ent/client.go b/entc/integration/multischema/ent/client.go index 6eb0df813..50c593dd0 100644 --- a/entc/integration/multischema/ent/client.go +++ b/entc/integration/multischema/ent/client.go @@ -21,6 +21,7 @@ import ( "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/entc/integration/multischema/ent/friendship" "entgo.io/ent/entc/integration/multischema/ent/group" + "entgo.io/ent/entc/integration/multischema/ent/parent" "entgo.io/ent/entc/integration/multischema/ent/pet" "entgo.io/ent/entc/integration/multischema/ent/user" @@ -38,6 +39,8 @@ type Client struct { Friendship *FriendshipClient // Group is the client for interacting with the Group builders. Group *GroupClient + // Parent is the client for interacting with the Parent builders. + Parent *ParentClient // Pet is the client for interacting with the Pet builders. Pet *PetClient // User is the client for interacting with the User builders. @@ -56,6 +59,7 @@ func (c *Client) init() { c.CleanUser = NewCleanUserClient(c.config) c.Friendship = NewFriendshipClient(c.config) c.Group = NewGroupClient(c.config) + c.Parent = NewParentClient(c.config) c.Pet = NewPetClient(c.config) c.User = NewUserClient(c.config) } @@ -156,6 +160,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { CleanUser: NewCleanUserClient(cfg), Friendship: NewFriendshipClient(cfg), Group: NewGroupClient(cfg), + Parent: NewParentClient(cfg), Pet: NewPetClient(cfg), User: NewUserClient(cfg), }, nil @@ -180,6 +185,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) CleanUser: NewCleanUserClient(cfg), Friendship: NewFriendshipClient(cfg), Group: NewGroupClient(cfg), + Parent: NewParentClient(cfg), Pet: NewPetClient(cfg), User: NewUserClient(cfg), }, nil @@ -210,20 +216,21 @@ func (c *Client) Close() error { // Use adds the mutation hooks to all the entity clients. // In order to add hooks to a specific client, call: `client.Node.Use(...)`. func (c *Client) Use(hooks ...Hook) { - c.Friendship.Use(hooks...) - c.Group.Use(hooks...) - c.Pet.Use(hooks...) - c.User.Use(hooks...) + for _, n := range []interface{ Use(...Hook) }{ + c.Friendship, c.Group, c.Parent, c.Pet, c.User, + } { + n.Use(hooks...) + } } // Intercept adds the query interceptors to all the entity clients. // In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`. func (c *Client) Intercept(interceptors ...Interceptor) { - c.CleanUser.Intercept(interceptors...) - c.Friendship.Intercept(interceptors...) - c.Group.Intercept(interceptors...) - c.Pet.Intercept(interceptors...) - c.User.Intercept(interceptors...) + for _, n := range []interface{ Intercept(...Interceptor) }{ + c.CleanUser, c.Friendship, c.Group, c.Parent, c.Pet, c.User, + } { + n.Intercept(interceptors...) + } } // Mutate implements the ent.Mutator interface. @@ -233,6 +240,8 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { return c.Friendship.mutate(ctx, m) case *GroupMutation: return c.Group.mutate(ctx, m) + case *ParentMutation: + return c.Parent.mutate(ctx, m) case *PetMutation: return c.Pet.mutate(ctx, m) case *UserMutation: @@ -595,6 +604,177 @@ func (c *GroupClient) mutate(ctx context.Context, m *GroupMutation) (Value, erro } } +// ParentClient is a client for the Parent schema. +type ParentClient struct { + config +} + +// NewParentClient returns a client for the Parent from the given config. +func NewParentClient(c config) *ParentClient { + return &ParentClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `parent.Hooks(f(g(h())))`. +func (c *ParentClient) Use(hooks ...Hook) { + c.hooks.Parent = append(c.hooks.Parent, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `parent.Intercept(f(g(h())))`. +func (c *ParentClient) Intercept(interceptors ...Interceptor) { + c.inters.Parent = append(c.inters.Parent, interceptors...) +} + +// Create returns a builder for creating a Parent entity. +func (c *ParentClient) Create() *ParentCreate { + mutation := newParentMutation(c.config, OpCreate) + return &ParentCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Parent entities. +func (c *ParentClient) CreateBulk(builders ...*ParentCreate) *ParentCreateBulk { + return &ParentCreateBulk{config: c.config, builders: builders} +} + +// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates +// a builder and applies setFunc on it. +func (c *ParentClient) MapCreateBulk(slice any, setFunc func(*ParentCreate, int)) *ParentCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &ParentCreateBulk{err: fmt.Errorf("calling to ParentClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*ParentCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &ParentCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Parent. +func (c *ParentClient) Update() *ParentUpdate { + mutation := newParentMutation(c.config, OpUpdate) + return &ParentUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *ParentClient) UpdateOne(_m *Parent) *ParentUpdateOne { + mutation := newParentMutation(c.config, OpUpdateOne, withParent(_m)) + return &ParentUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *ParentClient) UpdateOneID(id int) *ParentUpdateOne { + mutation := newParentMutation(c.config, OpUpdateOne, withParentID(id)) + return &ParentUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Parent. +func (c *ParentClient) Delete() *ParentDelete { + mutation := newParentMutation(c.config, OpDelete) + return &ParentDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *ParentClient) DeleteOne(_m *Parent) *ParentDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *ParentClient) DeleteOneID(id int) *ParentDeleteOne { + builder := c.Delete().Where(parent.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &ParentDeleteOne{builder} +} + +// Query returns a query builder for Parent. +func (c *ParentClient) Query() *ParentQuery { + return &ParentQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeParent}, + inters: c.Interceptors(), + } +} + +// Get returns a Parent entity by its id. +func (c *ParentClient) Get(ctx context.Context, id int) (*Parent, error) { + return c.Query().Where(parent.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *ParentClient) GetX(ctx context.Context, id int) *Parent { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryChild queries the child edge of a Parent. +func (c *ParentClient) QueryChild(_m *Parent) *UserQuery { + query := (&UserClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(parent.Table, parent.FieldID, id), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, parent.ChildTable, parent.ChildColumn), + ) + schemaConfig := _m.schemaConfig + step.To.Schema = schemaConfig.User + step.Edge.Schema = schemaConfig.Parent + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryParent queries the parent edge of a Parent. +func (c *ParentClient) QueryParent(_m *Parent) *UserQuery { + query := (&UserClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(parent.Table, parent.FieldID, id), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, parent.ParentTable, parent.ParentColumn), + ) + schemaConfig := _m.schemaConfig + step.To.Schema = schemaConfig.User + step.Edge.Schema = schemaConfig.Parent + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *ParentClient) Hooks() []Hook { + return c.hooks.Parent +} + +// Interceptors returns the client interceptors. +func (c *ParentClient) Interceptors() []Interceptor { + return c.inters.Parent +} + +func (c *ParentClient) mutate(ctx context.Context, m *ParentMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&ParentCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&ParentUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&ParentUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&ParentDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown Parent mutation op: %q", m.Op()) + } +} + // PetClient is a client for the Pet schema. type PetClient struct { config @@ -912,6 +1092,44 @@ func (c *UserClient) QueryFriends(_m *User) *UserQuery { return query } +// QueryParents queries the parents edge of a User. +func (c *UserClient) QueryParents(_m *User) *UserQuery { + query := (&UserClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, id), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, user.ParentsTable, user.ParentsPrimaryKey...), + ) + schemaConfig := _m.schemaConfig + step.To.Schema = schemaConfig.User + step.Edge.Schema = schemaConfig.UserChildren + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryChildren queries the children edge of a User. +func (c *UserClient) QueryChildren(_m *User) *UserQuery { + query := (&UserClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, id), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, user.ChildrenTable, user.ChildrenPrimaryKey...), + ) + schemaConfig := _m.schemaConfig + step.To.Schema = schemaConfig.User + step.Edge.Schema = schemaConfig.Parent + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + // QueryFriendships queries the friendships edge of a User. func (c *UserClient) QueryFriendships(_m *User) *FriendshipQuery { query := (&FriendshipClient{config: c.config}).Query() @@ -931,6 +1149,25 @@ func (c *UserClient) QueryFriendships(_m *User) *FriendshipQuery { return query } +// QueryParentHood queries the parent_hood edge of a User. +func (c *UserClient) QueryParentHood(_m *User) *ParentQuery { + query := (&ParentClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, id), + sqlgraph.To(parent.Table, parent.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, user.ParentHoodTable, user.ParentHoodColumn), + ) + schemaConfig := _m.schemaConfig + step.To.Schema = schemaConfig.Parent + step.Edge.Schema = schemaConfig.Parent + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + // Hooks returns the client hooks. func (c *UserClient) Hooks() []Hook { return c.hooks.User @@ -959,10 +1196,10 @@ func (c *UserClient) mutate(ctx context.Context, m *UserMutation) (Value, error) // hooks and interceptors per client, for fast access. type ( hooks struct { - Friendship, Group, Pet, User []ent.Hook + Friendship, Group, Parent, Pet, User []ent.Hook } inters struct { - CleanUser, Friendship, Group, Pet, User []ent.Interceptor + CleanUser, Friendship, Group, Parent, Pet, User []ent.Interceptor } ) @@ -979,6 +1216,7 @@ var ( Friendship: tableSchemas[1], Group: tableSchemas[1], GroupUsers: tableSchemas[1], + Parent: tableSchemas[0], Pet: tableSchemas[0], User: tableSchemas[0], } diff --git a/entc/integration/multischema/ent/ent.go b/entc/integration/multischema/ent/ent.go index 66660fb50..10d77efb6 100644 --- a/entc/integration/multischema/ent/ent.go +++ b/entc/integration/multischema/ent/ent.go @@ -19,6 +19,7 @@ import ( "entgo.io/ent/entc/integration/multischema/ent/cleanuser" "entgo.io/ent/entc/integration/multischema/ent/friendship" "entgo.io/ent/entc/integration/multischema/ent/group" + "entgo.io/ent/entc/integration/multischema/ent/parent" "entgo.io/ent/entc/integration/multischema/ent/pet" "entgo.io/ent/entc/integration/multischema/ent/user" ) @@ -84,6 +85,7 @@ func checkColumn(t, c string) error { cleanuser.Table: cleanuser.ValidColumn, friendship.Table: friendship.ValidColumn, group.Table: group.ValidColumn, + parent.Table: parent.ValidColumn, pet.Table: pet.ValidColumn, user.Table: user.ValidColumn, }) diff --git a/entc/integration/multischema/ent/hook/hook.go b/entc/integration/multischema/ent/hook/hook.go index 52687ae66..ab4082ac1 100644 --- a/entc/integration/multischema/ent/hook/hook.go +++ b/entc/integration/multischema/ent/hook/hook.go @@ -37,6 +37,18 @@ func (f GroupFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.GroupMutation", m) } +// The ParentFunc type is an adapter to allow the use of ordinary +// function as Parent mutator. +type ParentFunc func(context.Context, *ent.ParentMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f ParentFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.ParentMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.ParentMutation", m) +} + // The PetFunc type is an adapter to allow the use of ordinary // function as Pet mutator. type PetFunc func(context.Context, *ent.PetMutation) (ent.Value, error) diff --git a/entc/integration/multischema/ent/internal/schemaconfig.go b/entc/integration/multischema/ent/internal/schemaconfig.go index 6dc2cea8a..02388ffe3 100644 --- a/entc/integration/multischema/ent/internal/schemaconfig.go +++ b/entc/integration/multischema/ent/internal/schemaconfig.go @@ -11,12 +11,15 @@ import "context" // SchemaConfig represents alternative schema names for all tables // that can be passed at runtime. type SchemaConfig struct { - CleanUser string // CleanUser table. - Friendship string // Friendship table. - Group string // Group table. - GroupUsers string // Group-users->User table. - Pet string // Pet table. - User string // User table. + CleanUser string // CleanUser table. + Friendship string // Friendship table. + Group string // Group table. + GroupUsers string // Group-users->User table. + Parent string // Parent table. + Pet string // Pet table. + User string // User table. + UserFriends string // User-friends->User table. + UserChildren string // User-children->User table. } type schemaCtxKey struct{} diff --git a/entc/integration/multischema/ent/migrate/schema.go b/entc/integration/multischema/ent/migrate/schema.go index f1acbff96..c836bba31 100644 --- a/entc/integration/multischema/ent/migrate/schema.go +++ b/entc/integration/multischema/ent/migrate/schema.go @@ -63,6 +63,40 @@ var ( Columns: GroupsColumns, PrimaryKey: []*schema.Column{GroupsColumns[0]}, } + // ParentsColumns holds the columns for the "parents" table. + ParentsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "by_adoption", Type: field.TypeBool, Default: false}, + {Name: "user_id", Type: field.TypeInt}, + {Name: "parent_id", Type: field.TypeInt}, + } + // ParentsTable holds the schema information for the "parents" table. + ParentsTable = &schema.Table{ + Name: "parents", + Columns: ParentsColumns, + PrimaryKey: []*schema.Column{ParentsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "parents_users_child", + Columns: []*schema.Column{ParentsColumns[2]}, + RefColumns: []*schema.Column{UsersColumns[0]}, + OnDelete: schema.NoAction, + }, + { + Symbol: "parents_users_parent", + Columns: []*schema.Column{ParentsColumns[3]}, + RefColumns: []*schema.Column{UsersColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + Indexes: []*schema.Index{ + { + Name: "parent_user_id_parent_id", + Unique: true, + Columns: []*schema.Column{ParentsColumns[2], ParentsColumns[3]}, + }, + }, + } // PetsColumns holds the columns for the "pets" table. PetsColumns = []*schema.Column{ {Name: "id", Type: field.TypeInt, Increment: true}, @@ -123,6 +157,7 @@ var ( Tables = []*schema.Table{ FriendshipsTable, GroupsTable, + ParentsTable, PetsTable, UsersTable, GroupUsersTable, @@ -132,6 +167,8 @@ var ( func init() { FriendshipsTable.ForeignKeys[0].RefTable = UsersTable FriendshipsTable.ForeignKeys[1].RefTable = UsersTable + ParentsTable.ForeignKeys[0].RefTable = UsersTable + ParentsTable.ForeignKeys[1].RefTable = UsersTable PetsTable.ForeignKeys[0].RefTable = UsersTable GroupUsersTable.ForeignKeys[0].RefTable = GroupsTable GroupUsersTable.ForeignKeys[1].RefTable = UsersTable diff --git a/entc/integration/multischema/ent/mutation.go b/entc/integration/multischema/ent/mutation.go index d928519c6..33c5d5825 100644 --- a/entc/integration/multischema/ent/mutation.go +++ b/entc/integration/multischema/ent/mutation.go @@ -17,6 +17,7 @@ import ( "entgo.io/ent/dialect/sql" "entgo.io/ent/entc/integration/multischema/ent/friendship" "entgo.io/ent/entc/integration/multischema/ent/group" + "entgo.io/ent/entc/integration/multischema/ent/parent" "entgo.io/ent/entc/integration/multischema/ent/pet" "entgo.io/ent/entc/integration/multischema/ent/predicate" "entgo.io/ent/entc/integration/multischema/ent/user" @@ -34,6 +35,7 @@ const ( TypeCleanUser = "CleanUser" TypeFriendship = "Friendship" TypeGroup = "Group" + TypeParent = "Parent" TypePet = "Pet" TypeUser = "User" ) @@ -1081,6 +1083,556 @@ func (m *GroupMutation) ResetEdge(name string) error { return fmt.Errorf("unknown Group edge %s", name) } +// ParentMutation represents an operation that mutates the Parent nodes in the graph. +type ParentMutation struct { + config + op Op + typ string + id *int + by_adoption *bool + clearedFields map[string]struct{} + child *int + clearedchild bool + parent *int + clearedparent bool + done bool + oldValue func(context.Context) (*Parent, error) + predicates []predicate.Parent +} + +var _ ent.Mutation = (*ParentMutation)(nil) + +// parentOption allows management of the mutation configuration using functional options. +type parentOption func(*ParentMutation) + +// newParentMutation creates new mutation for the Parent entity. +func newParentMutation(c config, op Op, opts ...parentOption) *ParentMutation { + m := &ParentMutation{ + config: c, + op: op, + typ: TypeParent, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withParentID sets the ID field of the mutation. +func withParentID(id int) parentOption { + return func(m *ParentMutation) { + var ( + err error + once sync.Once + value *Parent + ) + m.oldValue = func(ctx context.Context) (*Parent, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Parent.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withParent sets the old Parent of the mutation. +func withParent(node *Parent) parentOption { + return func(m *ParentMutation) { + m.oldValue = func(context.Context) (*Parent, 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 ParentMutation) 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 ParentMutation) 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 *ParentMutation) 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 *ParentMutation) 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().Parent.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetByAdoption sets the "by_adoption" field. +func (m *ParentMutation) SetByAdoption(b bool) { + m.by_adoption = &b +} + +// ByAdoption returns the value of the "by_adoption" field in the mutation. +func (m *ParentMutation) ByAdoption() (r bool, exists bool) { + v := m.by_adoption + if v == nil { + return + } + return *v, true +} + +// OldByAdoption returns the old "by_adoption" field's value of the Parent entity. +// If the Parent object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ParentMutation) OldByAdoption(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldByAdoption is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldByAdoption requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldByAdoption: %w", err) + } + return oldValue.ByAdoption, nil +} + +// ResetByAdoption resets all changes to the "by_adoption" field. +func (m *ParentMutation) ResetByAdoption() { + m.by_adoption = nil +} + +// SetUserID sets the "user_id" field. +func (m *ParentMutation) SetUserID(i int) { + m.child = &i +} + +// UserID returns the value of the "user_id" field in the mutation. +func (m *ParentMutation) UserID() (r int, exists bool) { + v := m.child + if v == nil { + return + } + return *v, true +} + +// OldUserID returns the old "user_id" field's value of the Parent entity. +// If the Parent object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ParentMutation) OldUserID(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUserID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUserID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUserID: %w", err) + } + return oldValue.UserID, nil +} + +// ResetUserID resets all changes to the "user_id" field. +func (m *ParentMutation) ResetUserID() { + m.child = nil +} + +// SetParentID sets the "parent_id" field. +func (m *ParentMutation) SetParentID(i int) { + m.parent = &i +} + +// ParentID returns the value of the "parent_id" field in the mutation. +func (m *ParentMutation) ParentID() (r int, exists bool) { + v := m.parent + if v == nil { + return + } + return *v, true +} + +// OldParentID returns the old "parent_id" field's value of the Parent entity. +// If the Parent object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ParentMutation) OldParentID(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldParentID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldParentID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldParentID: %w", err) + } + return oldValue.ParentID, nil +} + +// ResetParentID resets all changes to the "parent_id" field. +func (m *ParentMutation) ResetParentID() { + m.parent = nil +} + +// SetChildID sets the "child" edge to the User entity by id. +func (m *ParentMutation) SetChildID(id int) { + m.child = &id +} + +// ClearChild clears the "child" edge to the User entity. +func (m *ParentMutation) ClearChild() { + m.clearedchild = true + m.clearedFields[parent.FieldUserID] = struct{}{} +} + +// ChildCleared reports if the "child" edge to the User entity was cleared. +func (m *ParentMutation) ChildCleared() bool { + return m.clearedchild +} + +// ChildID returns the "child" edge ID in the mutation. +func (m *ParentMutation) ChildID() (id int, exists bool) { + if m.child != nil { + return *m.child, true + } + return +} + +// ChildIDs returns the "child" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// ChildID instead. It exists only for internal usage by the builders. +func (m *ParentMutation) ChildIDs() (ids []int) { + if id := m.child; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetChild resets all changes to the "child" edge. +func (m *ParentMutation) ResetChild() { + m.child = nil + m.clearedchild = false +} + +// ClearParent clears the "parent" edge to the User entity. +func (m *ParentMutation) ClearParent() { + m.clearedparent = true + m.clearedFields[parent.FieldParentID] = struct{}{} +} + +// ParentCleared reports if the "parent" edge to the User entity was cleared. +func (m *ParentMutation) ParentCleared() bool { + return m.clearedparent +} + +// ParentIDs returns the "parent" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// ParentID instead. It exists only for internal usage by the builders. +func (m *ParentMutation) ParentIDs() (ids []int) { + if id := m.parent; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetParent resets all changes to the "parent" edge. +func (m *ParentMutation) ResetParent() { + m.parent = nil + m.clearedparent = false +} + +// Where appends a list predicates to the ParentMutation builder. +func (m *ParentMutation) Where(ps ...predicate.Parent) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the ParentMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *ParentMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Parent, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *ParentMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *ParentMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Parent). +func (m *ParentMutation) 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 *ParentMutation) Fields() []string { + fields := make([]string, 0, 3) + if m.by_adoption != nil { + fields = append(fields, parent.FieldByAdoption) + } + if m.child != nil { + fields = append(fields, parent.FieldUserID) + } + if m.parent != nil { + fields = append(fields, parent.FieldParentID) + } + 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 *ParentMutation) Field(name string) (ent.Value, bool) { + switch name { + case parent.FieldByAdoption: + return m.ByAdoption() + case parent.FieldUserID: + return m.UserID() + case parent.FieldParentID: + return m.ParentID() + } + 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 *ParentMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case parent.FieldByAdoption: + return m.OldByAdoption(ctx) + case parent.FieldUserID: + return m.OldUserID(ctx) + case parent.FieldParentID: + return m.OldParentID(ctx) + } + return nil, fmt.Errorf("unknown Parent 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 *ParentMutation) SetField(name string, value ent.Value) error { + switch name { + case parent.FieldByAdoption: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetByAdoption(v) + return nil + case parent.FieldUserID: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUserID(v) + return nil + case parent.FieldParentID: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetParentID(v) + return nil + } + return fmt.Errorf("unknown Parent field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *ParentMutation) 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 *ParentMutation) 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 *ParentMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown Parent numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *ParentMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *ParentMutation) 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 *ParentMutation) ClearField(name string) error { + return fmt.Errorf("unknown Parent 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 *ParentMutation) ResetField(name string) error { + switch name { + case parent.FieldByAdoption: + m.ResetByAdoption() + return nil + case parent.FieldUserID: + m.ResetUserID() + return nil + case parent.FieldParentID: + m.ResetParentID() + return nil + } + return fmt.Errorf("unknown Parent field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *ParentMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.child != nil { + edges = append(edges, parent.EdgeChild) + } + if m.parent != nil { + edges = append(edges, parent.EdgeParent) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *ParentMutation) AddedIDs(name string) []ent.Value { + switch name { + case parent.EdgeChild: + if id := m.child; id != nil { + return []ent.Value{*id} + } + case parent.EdgeParent: + if id := m.parent; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *ParentMutation) 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 *ParentMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *ParentMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedchild { + edges = append(edges, parent.EdgeChild) + } + if m.clearedparent { + edges = append(edges, parent.EdgeParent) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *ParentMutation) EdgeCleared(name string) bool { + switch name { + case parent.EdgeChild: + return m.clearedchild + case parent.EdgeParent: + return m.clearedparent + } + 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 *ParentMutation) ClearEdge(name string) error { + switch name { + case parent.EdgeChild: + m.ClearChild() + return nil + case parent.EdgeParent: + m.ClearParent() + return nil + } + return fmt.Errorf("unknown Parent 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 *ParentMutation) ResetEdge(name string) error { + switch name { + case parent.EdgeChild: + m.ResetChild() + return nil + case parent.EdgeParent: + m.ResetParent() + return nil + } + return fmt.Errorf("unknown Parent edge %s", name) +} + // PetMutation represents an operation that mutates the Pet nodes in the graph. type PetMutation struct { config @@ -1557,9 +2109,18 @@ type UserMutation struct { friends map[int]struct{} removedfriends map[int]struct{} clearedfriends bool + parents map[int]struct{} + removedparents map[int]struct{} + clearedparents bool + children map[int]struct{} + removedchildren map[int]struct{} + clearedchildren bool friendships map[int]struct{} removedfriendships map[int]struct{} clearedfriendships bool + parent_hood map[int]struct{} + removedparent_hood map[int]struct{} + clearedparent_hood bool done bool oldValue func(context.Context) (*User, error) predicates []predicate.User @@ -1861,6 +2422,114 @@ func (m *UserMutation) ResetFriends() { m.removedfriends = nil } +// AddParentIDs adds the "parents" edge to the User entity by ids. +func (m *UserMutation) AddParentIDs(ids ...int) { + if m.parents == nil { + m.parents = make(map[int]struct{}) + } + for i := range ids { + m.parents[ids[i]] = struct{}{} + } +} + +// ClearParents clears the "parents" edge to the User entity. +func (m *UserMutation) ClearParents() { + m.clearedparents = true +} + +// ParentsCleared reports if the "parents" edge to the User entity was cleared. +func (m *UserMutation) ParentsCleared() bool { + return m.clearedparents +} + +// RemoveParentIDs removes the "parents" edge to the User entity by IDs. +func (m *UserMutation) RemoveParentIDs(ids ...int) { + if m.removedparents == nil { + m.removedparents = make(map[int]struct{}) + } + for i := range ids { + delete(m.parents, ids[i]) + m.removedparents[ids[i]] = struct{}{} + } +} + +// RemovedParents returns the removed IDs of the "parents" edge to the User entity. +func (m *UserMutation) RemovedParentsIDs() (ids []int) { + for id := range m.removedparents { + ids = append(ids, id) + } + return +} + +// ParentsIDs returns the "parents" edge IDs in the mutation. +func (m *UserMutation) ParentsIDs() (ids []int) { + for id := range m.parents { + ids = append(ids, id) + } + return +} + +// ResetParents resets all changes to the "parents" edge. +func (m *UserMutation) ResetParents() { + m.parents = nil + m.clearedparents = false + m.removedparents = nil +} + +// AddChildIDs adds the "children" edge to the User entity by ids. +func (m *UserMutation) AddChildIDs(ids ...int) { + if m.children == nil { + m.children = make(map[int]struct{}) + } + for i := range ids { + m.children[ids[i]] = struct{}{} + } +} + +// ClearChildren clears the "children" edge to the User entity. +func (m *UserMutation) ClearChildren() { + m.clearedchildren = true +} + +// ChildrenCleared reports if the "children" edge to the User entity was cleared. +func (m *UserMutation) ChildrenCleared() bool { + return m.clearedchildren +} + +// RemoveChildIDs removes the "children" edge to the User entity by IDs. +func (m *UserMutation) RemoveChildIDs(ids ...int) { + if m.removedchildren == nil { + m.removedchildren = make(map[int]struct{}) + } + for i := range ids { + delete(m.children, ids[i]) + m.removedchildren[ids[i]] = struct{}{} + } +} + +// RemovedChildren returns the removed IDs of the "children" edge to the User entity. +func (m *UserMutation) RemovedChildrenIDs() (ids []int) { + for id := range m.removedchildren { + ids = append(ids, id) + } + return +} + +// ChildrenIDs returns the "children" edge IDs in the mutation. +func (m *UserMutation) ChildrenIDs() (ids []int) { + for id := range m.children { + ids = append(ids, id) + } + return +} + +// ResetChildren resets all changes to the "children" edge. +func (m *UserMutation) ResetChildren() { + m.children = nil + m.clearedchildren = false + m.removedchildren = nil +} + // AddFriendshipIDs adds the "friendships" edge to the Friendship entity by ids. func (m *UserMutation) AddFriendshipIDs(ids ...int) { if m.friendships == nil { @@ -1915,6 +2584,60 @@ func (m *UserMutation) ResetFriendships() { m.removedfriendships = nil } +// AddParentHoodIDs adds the "parent_hood" edge to the Parent entity by ids. +func (m *UserMutation) AddParentHoodIDs(ids ...int) { + if m.parent_hood == nil { + m.parent_hood = make(map[int]struct{}) + } + for i := range ids { + m.parent_hood[ids[i]] = struct{}{} + } +} + +// ClearParentHood clears the "parent_hood" edge to the Parent entity. +func (m *UserMutation) ClearParentHood() { + m.clearedparent_hood = true +} + +// ParentHoodCleared reports if the "parent_hood" edge to the Parent entity was cleared. +func (m *UserMutation) ParentHoodCleared() bool { + return m.clearedparent_hood +} + +// RemoveParentHoodIDs removes the "parent_hood" edge to the Parent entity by IDs. +func (m *UserMutation) RemoveParentHoodIDs(ids ...int) { + if m.removedparent_hood == nil { + m.removedparent_hood = make(map[int]struct{}) + } + for i := range ids { + delete(m.parent_hood, ids[i]) + m.removedparent_hood[ids[i]] = struct{}{} + } +} + +// RemovedParentHood returns the removed IDs of the "parent_hood" edge to the Parent entity. +func (m *UserMutation) RemovedParentHoodIDs() (ids []int) { + for id := range m.removedparent_hood { + ids = append(ids, id) + } + return +} + +// ParentHoodIDs returns the "parent_hood" edge IDs in the mutation. +func (m *UserMutation) ParentHoodIDs() (ids []int) { + for id := range m.parent_hood { + ids = append(ids, id) + } + return +} + +// ResetParentHood resets all changes to the "parent_hood" edge. +func (m *UserMutation) ResetParentHood() { + m.parent_hood = nil + m.clearedparent_hood = false + m.removedparent_hood = nil +} + // Where appends a list predicates to the UserMutation builder. func (m *UserMutation) Where(ps ...predicate.User) { m.predicates = append(m.predicates, ps...) @@ -2048,7 +2771,7 @@ func (m *UserMutation) ResetField(name string) error { // AddedEdges returns all edge names that were set/added in this mutation. func (m *UserMutation) AddedEdges() []string { - edges := make([]string, 0, 4) + edges := make([]string, 0, 7) if m.pets != nil { edges = append(edges, user.EdgePets) } @@ -2058,9 +2781,18 @@ func (m *UserMutation) AddedEdges() []string { if m.friends != nil { edges = append(edges, user.EdgeFriends) } + if m.parents != nil { + edges = append(edges, user.EdgeParents) + } + if m.children != nil { + edges = append(edges, user.EdgeChildren) + } if m.friendships != nil { edges = append(edges, user.EdgeFriendships) } + if m.parent_hood != nil { + edges = append(edges, user.EdgeParentHood) + } return edges } @@ -2086,19 +2818,37 @@ func (m *UserMutation) AddedIDs(name string) []ent.Value { ids = append(ids, id) } return ids + case user.EdgeParents: + ids := make([]ent.Value, 0, len(m.parents)) + for id := range m.parents { + ids = append(ids, id) + } + return ids + case user.EdgeChildren: + ids := make([]ent.Value, 0, len(m.children)) + for id := range m.children { + ids = append(ids, id) + } + return ids case user.EdgeFriendships: ids := make([]ent.Value, 0, len(m.friendships)) for id := range m.friendships { ids = append(ids, id) } return ids + case user.EdgeParentHood: + ids := make([]ent.Value, 0, len(m.parent_hood)) + for id := range m.parent_hood { + ids = append(ids, id) + } + return ids } return nil } // RemovedEdges returns all edge names that were removed in this mutation. func (m *UserMutation) RemovedEdges() []string { - edges := make([]string, 0, 4) + edges := make([]string, 0, 7) if m.removedpets != nil { edges = append(edges, user.EdgePets) } @@ -2108,9 +2858,18 @@ func (m *UserMutation) RemovedEdges() []string { if m.removedfriends != nil { edges = append(edges, user.EdgeFriends) } + if m.removedparents != nil { + edges = append(edges, user.EdgeParents) + } + if m.removedchildren != nil { + edges = append(edges, user.EdgeChildren) + } if m.removedfriendships != nil { edges = append(edges, user.EdgeFriendships) } + if m.removedparent_hood != nil { + edges = append(edges, user.EdgeParentHood) + } return edges } @@ -2136,19 +2895,37 @@ func (m *UserMutation) RemovedIDs(name string) []ent.Value { ids = append(ids, id) } return ids + case user.EdgeParents: + ids := make([]ent.Value, 0, len(m.removedparents)) + for id := range m.removedparents { + ids = append(ids, id) + } + return ids + case user.EdgeChildren: + ids := make([]ent.Value, 0, len(m.removedchildren)) + for id := range m.removedchildren { + ids = append(ids, id) + } + return ids case user.EdgeFriendships: ids := make([]ent.Value, 0, len(m.removedfriendships)) for id := range m.removedfriendships { ids = append(ids, id) } return ids + case user.EdgeParentHood: + ids := make([]ent.Value, 0, len(m.removedparent_hood)) + for id := range m.removedparent_hood { + ids = append(ids, id) + } + return ids } return nil } // ClearedEdges returns all edge names that were cleared in this mutation. func (m *UserMutation) ClearedEdges() []string { - edges := make([]string, 0, 4) + edges := make([]string, 0, 7) if m.clearedpets { edges = append(edges, user.EdgePets) } @@ -2158,9 +2935,18 @@ func (m *UserMutation) ClearedEdges() []string { if m.clearedfriends { edges = append(edges, user.EdgeFriends) } + if m.clearedparents { + edges = append(edges, user.EdgeParents) + } + if m.clearedchildren { + edges = append(edges, user.EdgeChildren) + } if m.clearedfriendships { edges = append(edges, user.EdgeFriendships) } + if m.clearedparent_hood { + edges = append(edges, user.EdgeParentHood) + } return edges } @@ -2174,8 +2960,14 @@ func (m *UserMutation) EdgeCleared(name string) bool { return m.clearedgroups case user.EdgeFriends: return m.clearedfriends + case user.EdgeParents: + return m.clearedparents + case user.EdgeChildren: + return m.clearedchildren case user.EdgeFriendships: return m.clearedfriendships + case user.EdgeParentHood: + return m.clearedparent_hood } return false } @@ -2201,9 +2993,18 @@ func (m *UserMutation) ResetEdge(name string) error { case user.EdgeFriends: m.ResetFriends() return nil + case user.EdgeParents: + m.ResetParents() + return nil + case user.EdgeChildren: + m.ResetChildren() + return nil case user.EdgeFriendships: m.ResetFriendships() return nil + case user.EdgeParentHood: + m.ResetParentHood() + return nil } return fmt.Errorf("unknown User edge %s", name) } diff --git a/entc/integration/multischema/ent/parent.go b/entc/integration/multischema/ent/parent.go new file mode 100644 index 000000000..be93e6c8c --- /dev/null +++ b/entc/integration/multischema/ent/parent.go @@ -0,0 +1,176 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/entc/integration/multischema/ent/parent" + "entgo.io/ent/entc/integration/multischema/ent/user" +) + +// Parent is the model entity for the Parent schema. +type Parent struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // ByAdoption holds the value of the "by_adoption" field. + ByAdoption bool `json:"by_adoption,omitempty"` + // UserID holds the value of the "user_id" field. + UserID int `json:"user_id,omitempty"` + // ParentID holds the value of the "parent_id" field. + ParentID int `json:"parent_id,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the ParentQuery when eager-loading is set. + Edges ParentEdges `json:"edges"` + selectValues sql.SelectValues +} + +// ParentEdges holds the relations/edges for other nodes in the graph. +type ParentEdges struct { + // Child holds the value of the child edge. + Child *User `json:"child,omitempty"` + // Parent holds the value of the parent edge. + Parent *User `json:"parent,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool +} + +// ChildOrErr returns the Child value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ParentEdges) ChildOrErr() (*User, error) { + if e.Child != nil { + return e.Child, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: user.Label} + } + return nil, &NotLoadedError{edge: "child"} +} + +// ParentOrErr returns the Parent value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ParentEdges) ParentOrErr() (*User, error) { + if e.Parent != nil { + return e.Parent, nil + } else if e.loadedTypes[1] { + return nil, &NotFoundError{label: user.Label} + } + return nil, &NotLoadedError{edge: "parent"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Parent) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case parent.FieldByAdoption: + values[i] = new(sql.NullBool) + case parent.FieldID, parent.FieldUserID, parent.FieldParentID: + 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 Parent fields. +func (_m *Parent) 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 parent.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + _m.ID = int(value.Int64) + case parent.FieldByAdoption: + if value, ok := values[i].(*sql.NullBool); !ok { + return fmt.Errorf("unexpected type %T for field by_adoption", values[i]) + } else if value.Valid { + _m.ByAdoption = value.Bool + } + case parent.FieldUserID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field user_id", values[i]) + } else if value.Valid { + _m.UserID = int(value.Int64) + } + case parent.FieldParentID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field parent_id", values[i]) + } else if value.Valid { + _m.ParentID = int(value.Int64) + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the Parent. +// This includes values selected through modifiers, order, etc. +func (_m *Parent) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryChild queries the "child" edge of the Parent entity. +func (_m *Parent) QueryChild() *UserQuery { + return NewParentClient(_m.config).QueryChild(_m) +} + +// QueryParent queries the "parent" edge of the Parent entity. +func (_m *Parent) QueryParent() *UserQuery { + return NewParentClient(_m.config).QueryParent(_m) +} + +// Update returns a builder for updating this Parent. +// Note that you need to call Parent.Unwrap() before calling this method if this Parent +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *Parent) Update() *ParentUpdateOne { + return NewParentClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the Parent entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (_m *Parent) Unwrap() *Parent { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("ent: Parent is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *Parent) String() string { + var builder strings.Builder + builder.WriteString("Parent(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("by_adoption=") + builder.WriteString(fmt.Sprintf("%v", _m.ByAdoption)) + builder.WriteString(", ") + builder.WriteString("user_id=") + builder.WriteString(fmt.Sprintf("%v", _m.UserID)) + builder.WriteString(", ") + builder.WriteString("parent_id=") + builder.WriteString(fmt.Sprintf("%v", _m.ParentID)) + builder.WriteByte(')') + return builder.String() +} + +// Parents is a parsable slice of Parent. +type Parents []*Parent diff --git a/entc/integration/multischema/ent/parent/parent.go b/entc/integration/multischema/ent/parent/parent.go new file mode 100644 index 000000000..5a0fa03d7 --- /dev/null +++ b/entc/integration/multischema/ent/parent/parent.go @@ -0,0 +1,119 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package parent + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the parent type in the database. + Label = "parent" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldByAdoption holds the string denoting the by_adoption field in the database. + FieldByAdoption = "by_adoption" + // FieldUserID holds the string denoting the user_id field in the database. + FieldUserID = "user_id" + // FieldParentID holds the string denoting the parent_id field in the database. + FieldParentID = "parent_id" + // EdgeChild holds the string denoting the child edge name in mutations. + EdgeChild = "child" + // EdgeParent holds the string denoting the parent edge name in mutations. + EdgeParent = "parent" + // Table holds the table name of the parent in the database. + Table = "parents" + // ChildTable is the table that holds the child relation/edge. + ChildTable = "parents" + // ChildInverseTable is the table name for the User entity. + // It exists in this package in order to avoid circular dependency with the "user" package. + ChildInverseTable = "users" + // ChildColumn is the table column denoting the child relation/edge. + ChildColumn = "user_id" + // ParentTable is the table that holds the parent relation/edge. + ParentTable = "parents" + // ParentInverseTable is the table name for the User entity. + // It exists in this package in order to avoid circular dependency with the "user" package. + ParentInverseTable = "users" + // ParentColumn is the table column denoting the parent relation/edge. + ParentColumn = "parent_id" +) + +// Columns holds all SQL columns for parent fields. +var Columns = []string{ + FieldID, + FieldByAdoption, + FieldUserID, + FieldParentID, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // DefaultByAdoption holds the default value on creation for the "by_adoption" field. + DefaultByAdoption bool +) + +// OrderOption defines the ordering options for the Parent 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() +} + +// ByByAdoption orders the results by the by_adoption field. +func ByByAdoption(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldByAdoption, opts...).ToFunc() +} + +// ByUserID orders the results by the user_id field. +func ByUserID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUserID, opts...).ToFunc() +} + +// ByParentID orders the results by the parent_id field. +func ByParentID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldParentID, opts...).ToFunc() +} + +// ByChildField orders the results by child field. +func ByChildField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newChildStep(), sql.OrderByField(field, opts...)) + } +} + +// ByParentField orders the results by parent field. +func ByParentField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newParentStep(), sql.OrderByField(field, opts...)) + } +} +func newChildStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ChildInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, ChildTable, ChildColumn), + ) +} +func newParentStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ParentInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, ParentTable, ParentColumn), + ) +} diff --git a/entc/integration/multischema/ent/parent/where.go b/entc/integration/multischema/ent/parent/where.go new file mode 100644 index 000000000..d9de2ffc1 --- /dev/null +++ b/entc/integration/multischema/ent/parent/where.go @@ -0,0 +1,197 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package parent + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/multischema/ent/internal" + "entgo.io/ent/entc/integration/multischema/ent/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.Parent { + return predicate.Parent(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.Parent { + return predicate.Parent(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.Parent { + return predicate.Parent(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.Parent { + return predicate.Parent(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.Parent { + return predicate.Parent(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.Parent { + return predicate.Parent(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.Parent { + return predicate.Parent(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.Parent { + return predicate.Parent(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.Parent { + return predicate.Parent(sql.FieldLTE(FieldID, id)) +} + +// ByAdoption applies equality check predicate on the "by_adoption" field. It's identical to ByAdoptionEQ. +func ByAdoption(v bool) predicate.Parent { + return predicate.Parent(sql.FieldEQ(FieldByAdoption, v)) +} + +// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ. +func UserID(v int) predicate.Parent { + return predicate.Parent(sql.FieldEQ(FieldUserID, v)) +} + +// ParentID applies equality check predicate on the "parent_id" field. It's identical to ParentIDEQ. +func ParentID(v int) predicate.Parent { + return predicate.Parent(sql.FieldEQ(FieldParentID, v)) +} + +// ByAdoptionEQ applies the EQ predicate on the "by_adoption" field. +func ByAdoptionEQ(v bool) predicate.Parent { + return predicate.Parent(sql.FieldEQ(FieldByAdoption, v)) +} + +// ByAdoptionNEQ applies the NEQ predicate on the "by_adoption" field. +func ByAdoptionNEQ(v bool) predicate.Parent { + return predicate.Parent(sql.FieldNEQ(FieldByAdoption, v)) +} + +// UserIDEQ applies the EQ predicate on the "user_id" field. +func UserIDEQ(v int) predicate.Parent { + return predicate.Parent(sql.FieldEQ(FieldUserID, v)) +} + +// UserIDNEQ applies the NEQ predicate on the "user_id" field. +func UserIDNEQ(v int) predicate.Parent { + return predicate.Parent(sql.FieldNEQ(FieldUserID, v)) +} + +// UserIDIn applies the In predicate on the "user_id" field. +func UserIDIn(vs ...int) predicate.Parent { + return predicate.Parent(sql.FieldIn(FieldUserID, vs...)) +} + +// UserIDNotIn applies the NotIn predicate on the "user_id" field. +func UserIDNotIn(vs ...int) predicate.Parent { + return predicate.Parent(sql.FieldNotIn(FieldUserID, vs...)) +} + +// ParentIDEQ applies the EQ predicate on the "parent_id" field. +func ParentIDEQ(v int) predicate.Parent { + return predicate.Parent(sql.FieldEQ(FieldParentID, v)) +} + +// ParentIDNEQ applies the NEQ predicate on the "parent_id" field. +func ParentIDNEQ(v int) predicate.Parent { + return predicate.Parent(sql.FieldNEQ(FieldParentID, v)) +} + +// ParentIDIn applies the In predicate on the "parent_id" field. +func ParentIDIn(vs ...int) predicate.Parent { + return predicate.Parent(sql.FieldIn(FieldParentID, vs...)) +} + +// ParentIDNotIn applies the NotIn predicate on the "parent_id" field. +func ParentIDNotIn(vs ...int) predicate.Parent { + return predicate.Parent(sql.FieldNotIn(FieldParentID, vs...)) +} + +// HasChild applies the HasEdge predicate on the "child" edge. +func HasChild() predicate.Parent { + return predicate.Parent(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, ChildTable, ChildColumn), + ) + schemaConfig := internal.SchemaConfigFromContext(s.Context()) + step.To.Schema = schemaConfig.User + step.Edge.Schema = schemaConfig.Parent + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasChildWith applies the HasEdge predicate on the "child" edge with a given conditions (other predicates). +func HasChildWith(preds ...predicate.User) predicate.Parent { + return predicate.Parent(func(s *sql.Selector) { + step := newChildStep() + schemaConfig := internal.SchemaConfigFromContext(s.Context()) + step.To.Schema = schemaConfig.User + step.Edge.Schema = schemaConfig.Parent + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasParent applies the HasEdge predicate on the "parent" edge. +func HasParent() predicate.Parent { + return predicate.Parent(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, ParentTable, ParentColumn), + ) + schemaConfig := internal.SchemaConfigFromContext(s.Context()) + step.To.Schema = schemaConfig.User + step.Edge.Schema = schemaConfig.Parent + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasParentWith applies the HasEdge predicate on the "parent" edge with a given conditions (other predicates). +func HasParentWith(preds ...predicate.User) predicate.Parent { + return predicate.Parent(func(s *sql.Selector) { + step := newParentStep() + schemaConfig := internal.SchemaConfigFromContext(s.Context()) + step.To.Schema = schemaConfig.User + step.Edge.Schema = schemaConfig.Parent + 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.Parent) predicate.Parent { + return predicate.Parent(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Parent) predicate.Parent { + return predicate.Parent(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Parent) predicate.Parent { + return predicate.Parent(sql.NotPredicates(p)) +} diff --git a/entc/integration/multischema/ent/parent_create.go b/entc/integration/multischema/ent/parent_create.go new file mode 100644 index 000000000..109e2b4d6 --- /dev/null +++ b/entc/integration/multischema/ent/parent_create.go @@ -0,0 +1,283 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/multischema/ent/parent" + "entgo.io/ent/entc/integration/multischema/ent/user" + "entgo.io/ent/schema/field" +) + +// ParentCreate is the builder for creating a Parent entity. +type ParentCreate struct { + config + mutation *ParentMutation + hooks []Hook +} + +// SetByAdoption sets the "by_adoption" field. +func (_c *ParentCreate) SetByAdoption(v bool) *ParentCreate { + _c.mutation.SetByAdoption(v) + return _c +} + +// SetNillableByAdoption sets the "by_adoption" field if the given value is not nil. +func (_c *ParentCreate) SetNillableByAdoption(v *bool) *ParentCreate { + if v != nil { + _c.SetByAdoption(*v) + } + return _c +} + +// SetUserID sets the "user_id" field. +func (_c *ParentCreate) SetUserID(v int) *ParentCreate { + _c.mutation.SetUserID(v) + return _c +} + +// SetParentID sets the "parent_id" field. +func (_c *ParentCreate) SetParentID(v int) *ParentCreate { + _c.mutation.SetParentID(v) + return _c +} + +// SetChildID sets the "child" edge to the User entity by ID. +func (_c *ParentCreate) SetChildID(id int) *ParentCreate { + _c.mutation.SetChildID(id) + return _c +} + +// SetChild sets the "child" edge to the User entity. +func (_c *ParentCreate) SetChild(v *User) *ParentCreate { + return _c.SetChildID(v.ID) +} + +// SetParent sets the "parent" edge to the User entity. +func (_c *ParentCreate) SetParent(v *User) *ParentCreate { + return _c.SetParentID(v.ID) +} + +// Mutation returns the ParentMutation object of the builder. +func (_c *ParentCreate) Mutation() *ParentMutation { + return _c.mutation +} + +// Save creates the Parent in the database. +func (_c *ParentCreate) Save(ctx context.Context) (*Parent, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *ParentCreate) SaveX(ctx context.Context) *Parent { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ParentCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ParentCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *ParentCreate) defaults() { + if _, ok := _c.mutation.ByAdoption(); !ok { + v := parent.DefaultByAdoption + _c.mutation.SetByAdoption(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *ParentCreate) check() error { + if _, ok := _c.mutation.ByAdoption(); !ok { + return &ValidationError{Name: "by_adoption", err: errors.New(`ent: missing required field "Parent.by_adoption"`)} + } + if _, ok := _c.mutation.UserID(); !ok { + return &ValidationError{Name: "user_id", err: errors.New(`ent: missing required field "Parent.user_id"`)} + } + if _, ok := _c.mutation.ParentID(); !ok { + return &ValidationError{Name: "parent_id", err: errors.New(`ent: missing required field "Parent.parent_id"`)} + } + if len(_c.mutation.ChildIDs()) == 0 { + return &ValidationError{Name: "child", err: errors.New(`ent: missing required edge "Parent.child"`)} + } + if len(_c.mutation.ParentIDs()) == 0 { + return &ValidationError{Name: "parent", err: errors.New(`ent: missing required edge "Parent.parent"`)} + } + return nil +} + +func (_c *ParentCreate) sqlSave(ctx context.Context) (*Parent, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *ParentCreate) createSpec() (*Parent, *sqlgraph.CreateSpec) { + var ( + _node = &Parent{config: _c.config} + _spec = sqlgraph.NewCreateSpec(parent.Table, sqlgraph.NewFieldSpec(parent.FieldID, field.TypeInt)) + ) + _spec.Schema = _c.schemaConfig.Parent + if value, ok := _c.mutation.ByAdoption(); ok { + _spec.SetField(parent.FieldByAdoption, field.TypeBool, value) + _node.ByAdoption = value + } + if nodes := _c.mutation.ChildIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: parent.ChildTable, + Columns: []string{parent.ChildColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + edge.Schema = _c.schemaConfig.Parent + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.UserID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.ParentIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: parent.ParentTable, + Columns: []string{parent.ParentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + edge.Schema = _c.schemaConfig.Parent + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.ParentID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// ParentCreateBulk is the builder for creating many Parent entities in bulk. +type ParentCreateBulk struct { + config + err error + builders []*ParentCreate +} + +// Save creates the Parent entities in the database. +func (_c *ParentCreateBulk) Save(ctx context.Context) ([]*Parent, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*Parent, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*ParentMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + 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, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *ParentCreateBulk) SaveX(ctx context.Context) []*Parent { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ParentCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ParentCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entc/integration/multischema/ent/parent_delete.go b/entc/integration/multischema/ent/parent_delete.go new file mode 100644 index 000000000..a8b151632 --- /dev/null +++ b/entc/integration/multischema/ent/parent_delete.go @@ -0,0 +1,95 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// 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/entc/integration/multischema/ent/internal" + "entgo.io/ent/entc/integration/multischema/ent/parent" + "entgo.io/ent/entc/integration/multischema/ent/predicate" + "entgo.io/ent/schema/field" +) + +// ParentDelete is the builder for deleting a Parent entity. +type ParentDelete struct { + config + hooks []Hook + mutation *ParentMutation +} + +// Where appends a list predicates to the ParentDelete builder. +func (_d *ParentDelete) Where(ps ...predicate.Parent) *ParentDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *ParentDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *ParentDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *ParentDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(parent.Table, sqlgraph.NewFieldSpec(parent.FieldID, field.TypeInt)) + _spec.Node.Schema = _d.schemaConfig.Parent + ctx = internal.NewSchemaConfigContext(ctx, _d.schemaConfig) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// ParentDeleteOne is the builder for deleting a single Parent entity. +type ParentDeleteOne struct { + _d *ParentDelete +} + +// Where appends a list predicates to the ParentDelete builder. +func (_d *ParentDeleteOne) Where(ps ...predicate.Parent) *ParentDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *ParentDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{parent.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *ParentDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entc/integration/multischema/ent/parent_query.go b/entc/integration/multischema/ent/parent_query.go new file mode 100644 index 000000000..5a9feb2fb --- /dev/null +++ b/entc/integration/multischema/ent/parent_query.go @@ -0,0 +1,721 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/multischema/ent/internal" + "entgo.io/ent/entc/integration/multischema/ent/parent" + "entgo.io/ent/entc/integration/multischema/ent/predicate" + "entgo.io/ent/entc/integration/multischema/ent/user" + "entgo.io/ent/schema/field" +) + +// ParentQuery is the builder for querying Parent entities. +type ParentQuery struct { + config + ctx *QueryContext + order []parent.OrderOption + inters []Interceptor + predicates []predicate.Parent + withChild *UserQuery + withParent *UserQuery + modifiers []func(*sql.Selector) + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the ParentQuery builder. +func (_q *ParentQuery) Where(ps ...predicate.Parent) *ParentQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *ParentQuery) Limit(limit int) *ParentQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *ParentQuery) Offset(offset int) *ParentQuery { + _q.ctx.Offset = &offset + return _q +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (_q *ParentQuery) Unique(unique bool) *ParentQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *ParentQuery) Order(o ...parent.OrderOption) *ParentQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryChild chains the current query on the "child" edge. +func (_q *ParentQuery) QueryChild() *UserQuery { + query := (&UserClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(parent.Table, parent.FieldID, selector), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, parent.ChildTable, parent.ChildColumn), + ) + schemaConfig := _q.schemaConfig + step.To.Schema = schemaConfig.User + step.Edge.Schema = schemaConfig.Parent + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryParent chains the current query on the "parent" edge. +func (_q *ParentQuery) QueryParent() *UserQuery { + query := (&UserClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(parent.Table, parent.FieldID, selector), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, parent.ParentTable, parent.ParentColumn), + ) + schemaConfig := _q.schemaConfig + step.To.Schema = schemaConfig.User + step.Edge.Schema = schemaConfig.Parent + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first Parent entity from the query. +// Returns a *NotFoundError when no Parent was found. +func (_q *ParentQuery) First(ctx context.Context) (*Parent, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{parent.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *ParentQuery) FirstX(ctx context.Context) *Parent { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Parent ID from the query. +// Returns a *NotFoundError when no Parent ID was found. +func (_q *ParentQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{parent.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *ParentQuery) FirstIDX(ctx context.Context) int { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Parent entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Parent entity is found. +// Returns a *NotFoundError when no Parent entities are found. +func (_q *ParentQuery) Only(ctx context.Context) (*Parent, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{parent.Label} + default: + return nil, &NotSingularError{parent.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *ParentQuery) OnlyX(ctx context.Context) *Parent { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Parent ID in the query. +// Returns a *NotSingularError when more than one Parent ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *ParentQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{parent.Label} + default: + err = &NotSingularError{parent.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *ParentQuery) OnlyIDX(ctx context.Context) int { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Parents. +func (_q *ParentQuery) All(ctx context.Context) ([]*Parent, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Parent, *ParentQuery]() + return withInterceptors[[]*Parent](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *ParentQuery) AllX(ctx context.Context) []*Parent { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Parent IDs. +func (_q *ParentQuery) IDs(ctx context.Context) (ids []int, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(parent.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *ParentQuery) IDsX(ctx context.Context) []int { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *ParentQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*ParentQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *ParentQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *ParentQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("ent: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *ParentQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the ParentQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *ParentQuery) Clone() *ParentQuery { + if _q == nil { + return nil + } + return &ParentQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]parent.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.Parent{}, _q.predicates...), + withChild: _q.withChild.Clone(), + withParent: _q.withParent.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + modifiers: append([]func(*sql.Selector){}, _q.modifiers...), + } +} + +// WithChild tells the query-builder to eager-load the nodes that are connected to +// the "child" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ParentQuery) WithChild(opts ...func(*UserQuery)) *ParentQuery { + query := (&UserClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withChild = query + return _q +} + +// WithParent tells the query-builder to eager-load the nodes that are connected to +// the "parent" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ParentQuery) WithParent(opts ...func(*UserQuery)) *ParentQuery { + query := (&UserClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withParent = query + return _q +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// ByAdoption bool `json:"by_adoption,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Parent.Query(). +// GroupBy(parent.FieldByAdoption). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (_q *ParentQuery) GroupBy(field string, fields ...string) *ParentGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &ParentGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = parent.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 { +// ByAdoption bool `json:"by_adoption,omitempty"` +// } +// +// client.Parent.Query(). +// Select(parent.FieldByAdoption). +// Scan(ctx, &v) +func (_q *ParentQuery) Select(fields ...string) *ParentSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &ParentSelect{ParentQuery: _q} + sbuild.label = parent.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a ParentSelect configured with the given aggregations. +func (_q *ParentQuery) Aggregate(fns ...AggregateFunc) *ParentSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *ParentQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.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, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !parent.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *ParentQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Parent, error) { + var ( + nodes = []*Parent{} + _spec = _q.querySpec() + loadedTypes = [2]bool{ + _q.withChild != nil, + _q.withParent != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Parent).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Parent{config: _q.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + _spec.Node.Schema = _q.schemaConfig.Parent + ctx = internal.NewSchemaConfigContext(ctx, _q.schemaConfig) + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := _q.withChild; query != nil { + if err := _q.loadChild(ctx, query, nodes, nil, + func(n *Parent, e *User) { n.Edges.Child = e }); err != nil { + return nil, err + } + } + if query := _q.withParent; query != nil { + if err := _q.loadParent(ctx, query, nodes, nil, + func(n *Parent, e *User) { n.Edges.Parent = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *ParentQuery) loadChild(ctx context.Context, query *UserQuery, nodes []*Parent, init func(*Parent), assign func(*Parent, *User)) error { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*Parent) + for i := range nodes { + fk := nodes[i].UserID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(user.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return fmt.Errorf(`unexpected foreign-key "user_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *ParentQuery) loadParent(ctx context.Context, query *UserQuery, nodes []*Parent, init func(*Parent), assign func(*Parent, *User)) error { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*Parent) + for i := range nodes { + fk := nodes[i].ParentID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(user.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return fmt.Errorf(`unexpected foreign-key "parent_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *ParentQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + _spec.Node.Schema = _q.schemaConfig.Parent + ctx = internal.NewSchemaConfigContext(ctx, _q.schemaConfig) + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *ParentQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(parent.Table, parent.Columns, sqlgraph.NewFieldSpec(parent.FieldID, field.TypeInt)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, parent.FieldID) + for i := range fields { + if fields[i] != parent.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withChild != nil { + _spec.Node.AddColumnOnce(parent.FieldUserID) + } + if _q.withParent != nil { + _spec.Node.AddColumnOnce(parent.FieldParentID) + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *ParentQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(parent.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = parent.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + t1.Schema(_q.schemaConfig.Parent) + ctx = internal.NewSchemaConfigContext(ctx, _q.schemaConfig) + selector.WithContext(ctx) + for _, m := range _q.modifiers { + m(selector) + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.ctx.Offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := _q.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (_q *ParentQuery) Modify(modifiers ...func(s *sql.Selector)) *ParentSelect { + _q.modifiers = append(_q.modifiers, modifiers...) + return _q.Select() +} + +// ParentGroupBy is the group-by builder for Parent entities. +type ParentGroupBy struct { + selector + build *ParentQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (pgb *ParentGroupBy) Aggregate(fns ...AggregateFunc) *ParentGroupBy { + pgb.fns = append(pgb.fns, fns...) + return pgb +} + +// Scan applies the selector query and scans the result into the given value. +func (pgb *ParentGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, pgb.build.ctx, ent.OpQueryGroupBy) + if err := pgb.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*ParentQuery, *ParentGroupBy](ctx, pgb.build, pgb, pgb.build.inters, v) +} + +func (pgb *ParentGroupBy) sqlScan(ctx context.Context, root *ParentQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(pgb.fns)) + for _, fn := range pgb.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*pgb.flds)+len(pgb.fns)) + for _, f := range *pgb.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*pgb.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := pgb.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// ParentSelect is the builder for selecting fields of Parent entities. +type ParentSelect struct { + *ParentQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (ps *ParentSelect) Aggregate(fns ...AggregateFunc) *ParentSelect { + ps.fns = append(ps.fns, fns...) + return ps +} + +// Scan applies the selector query and scans the result into the given value. +func (ps *ParentSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, ps.ctx, ent.OpQuerySelect) + if err := ps.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*ParentQuery, *ParentSelect](ctx, ps.ParentQuery, ps, ps.inters, v) +} + +func (ps *ParentSelect) sqlScan(ctx context.Context, root *ParentQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(ps.fns)) + for _, fn := range ps.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*ps.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 := ps.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (ps *ParentSelect) Modify(modifiers ...func(s *sql.Selector)) *ParentSelect { + ps.modifiers = append(ps.modifiers, modifiers...) + return ps +} diff --git a/entc/integration/multischema/ent/parent_update.go b/entc/integration/multischema/ent/parent_update.go new file mode 100644 index 000000000..94ad8d241 --- /dev/null +++ b/entc/integration/multischema/ent/parent_update.go @@ -0,0 +1,262 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// 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/entc/integration/multischema/ent/internal" + "entgo.io/ent/entc/integration/multischema/ent/parent" + "entgo.io/ent/entc/integration/multischema/ent/predicate" + "entgo.io/ent/schema/field" +) + +// ParentUpdate is the builder for updating Parent entities. +type ParentUpdate struct { + config + hooks []Hook + mutation *ParentMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the ParentUpdate builder. +func (_u *ParentUpdate) Where(ps ...predicate.Parent) *ParentUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetByAdoption sets the "by_adoption" field. +func (_u *ParentUpdate) SetByAdoption(v bool) *ParentUpdate { + _u.mutation.SetByAdoption(v) + return _u +} + +// SetNillableByAdoption sets the "by_adoption" field if the given value is not nil. +func (_u *ParentUpdate) SetNillableByAdoption(v *bool) *ParentUpdate { + if v != nil { + _u.SetByAdoption(*v) + } + return _u +} + +// Mutation returns the ParentMutation object of the builder. +func (_u *ParentUpdate) Mutation() *ParentMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *ParentUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *ParentUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *ParentUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ParentUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ParentUpdate) check() error { + if _u.mutation.ChildCleared() && len(_u.mutation.ChildIDs()) > 0 { + return errors.New(`ent: clearing a required unique edge "Parent.child"`) + } + if _u.mutation.ParentCleared() && len(_u.mutation.ParentIDs()) > 0 { + return errors.New(`ent: clearing a required unique edge "Parent.parent"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (_u *ParentUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *ParentUpdate { + _u.modifiers = append(_u.modifiers, modifiers...) + return _u +} + +func (_u *ParentUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(parent.Table, parent.Columns, sqlgraph.NewFieldSpec(parent.FieldID, field.TypeInt)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.ByAdoption(); ok { + _spec.SetField(parent.FieldByAdoption, field.TypeBool, value) + } + _spec.Node.Schema = _u.schemaConfig.Parent + ctx = internal.NewSchemaConfigContext(ctx, _u.schemaConfig) + _spec.AddModifiers(_u.modifiers...) + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{parent.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// ParentUpdateOne is the builder for updating a single Parent entity. +type ParentUpdateOne struct { + config + fields []string + hooks []Hook + mutation *ParentMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetByAdoption sets the "by_adoption" field. +func (_u *ParentUpdateOne) SetByAdoption(v bool) *ParentUpdateOne { + _u.mutation.SetByAdoption(v) + return _u +} + +// SetNillableByAdoption sets the "by_adoption" field if the given value is not nil. +func (_u *ParentUpdateOne) SetNillableByAdoption(v *bool) *ParentUpdateOne { + if v != nil { + _u.SetByAdoption(*v) + } + return _u +} + +// Mutation returns the ParentMutation object of the builder. +func (_u *ParentUpdateOne) Mutation() *ParentMutation { + return _u.mutation +} + +// Where appends a list predicates to the ParentUpdate builder. +func (_u *ParentUpdateOne) Where(ps ...predicate.Parent) *ParentUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *ParentUpdateOne) Select(field string, fields ...string) *ParentUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated Parent entity. +func (_u *ParentUpdateOne) Save(ctx context.Context) (*Parent, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *ParentUpdateOne) SaveX(ctx context.Context) *Parent { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *ParentUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ParentUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ParentUpdateOne) check() error { + if _u.mutation.ChildCleared() && len(_u.mutation.ChildIDs()) > 0 { + return errors.New(`ent: clearing a required unique edge "Parent.child"`) + } + if _u.mutation.ParentCleared() && len(_u.mutation.ParentIDs()) > 0 { + return errors.New(`ent: clearing a required unique edge "Parent.parent"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (_u *ParentUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *ParentUpdateOne { + _u.modifiers = append(_u.modifiers, modifiers...) + return _u +} + +func (_u *ParentUpdateOne) sqlSave(ctx context.Context) (_node *Parent, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(parent.Table, parent.Columns, sqlgraph.NewFieldSpec(parent.FieldID, field.TypeInt)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Parent.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, parent.FieldID) + for _, f := range fields { + if !parent.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != parent.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.ByAdoption(); ok { + _spec.SetField(parent.FieldByAdoption, field.TypeBool, value) + } + _spec.Node.Schema = _u.schemaConfig.Parent + ctx = internal.NewSchemaConfigContext(ctx, _u.schemaConfig) + _spec.AddModifiers(_u.modifiers...) + _node = &Parent{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{parent.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/entc/integration/multischema/ent/predicate/predicate.go b/entc/integration/multischema/ent/predicate/predicate.go index de817ea25..3d74c59bf 100644 --- a/entc/integration/multischema/ent/predicate/predicate.go +++ b/entc/integration/multischema/ent/predicate/predicate.go @@ -19,6 +19,9 @@ type Friendship func(*sql.Selector) // Group is the predicate function for group builders. type Group func(*sql.Selector) +// Parent is the predicate function for parent builders. +type Parent func(*sql.Selector) + // Pet is the predicate function for pet builders. type Pet func(*sql.Selector) diff --git a/entc/integration/multischema/ent/runtime.go b/entc/integration/multischema/ent/runtime.go index 2a1fc8c0f..ee403f4ab 100644 --- a/entc/integration/multischema/ent/runtime.go +++ b/entc/integration/multischema/ent/runtime.go @@ -11,6 +11,7 @@ import ( "entgo.io/ent/entc/integration/multischema/ent/friendship" "entgo.io/ent/entc/integration/multischema/ent/group" + "entgo.io/ent/entc/integration/multischema/ent/parent" "entgo.io/ent/entc/integration/multischema/ent/pet" "entgo.io/ent/entc/integration/multischema/ent/schema" "entgo.io/ent/entc/integration/multischema/ent/user" @@ -36,6 +37,12 @@ func init() { groupDescName := groupFields[0].Descriptor() // group.DefaultName holds the default value on creation for the name field. group.DefaultName = groupDescName.Default.(string) + parentFields := schema.Parent{}.Fields() + _ = parentFields + // parentDescByAdoption is the schema descriptor for by_adoption field. + parentDescByAdoption := parentFields[0].Descriptor() + // parent.DefaultByAdoption holds the default value on creation for the by_adoption field. + parent.DefaultByAdoption = parentDescByAdoption.Default.(bool) petFields := schema.Pet{}.Fields() _ = petFields // petDescName is the schema descriptor for name field. diff --git a/entc/integration/multischema/ent/schema/parent.go b/entc/integration/multischema/ent/schema/parent.go new file mode 100644 index 000000000..462df995b --- /dev/null +++ b/entc/integration/multischema/ent/schema/parent.go @@ -0,0 +1,44 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +package schema + +import ( + "entgo.io/ent" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" +) + +// Parent holds the schema definition for the Parent entity. +type Parent struct { + base +} + +// Fields of the Parent. +func (Parent) Fields() []ent.Field { + return []ent.Field{ + field.Bool("by_adoption"). + Default(false), + field.Int("user_id"). + Immutable(), + field.Int("parent_id"). + Immutable(), + } +} + +// Edges of the Parent. +func (Parent) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("child", User.Type). + Unique(). + Required(). + Immutable(). + Field("user_id"), + edge.To("parent", User.Type). + Unique(). + Required(). + Immutable(). + Field("parent_id"), + } +} diff --git a/entc/integration/multischema/ent/schema/user.go b/entc/integration/multischema/ent/schema/user.go index 70be1781b..6500e9590 100644 --- a/entc/integration/multischema/ent/schema/user.go +++ b/entc/integration/multischema/ent/schema/user.go @@ -33,6 +33,9 @@ func (User) Edges() []ent.Edge { Ref("users"), edge.To("friends", User.Type). Through("friendships", Friendship.Type), + edge.To("children", User.Type). + Through("parent_hood", Parent.Type). + From("parents"), } } diff --git a/entc/integration/multischema/ent/tx.go b/entc/integration/multischema/ent/tx.go index 64d4eb4b1..02d259569 100644 --- a/entc/integration/multischema/ent/tx.go +++ b/entc/integration/multischema/ent/tx.go @@ -22,6 +22,8 @@ type Tx struct { Friendship *FriendshipClient // Group is the client for interacting with the Group builders. Group *GroupClient + // Parent is the client for interacting with the Parent builders. + Parent *ParentClient // Pet is the client for interacting with the Pet builders. Pet *PetClient // User is the client for interacting with the User builders. @@ -160,6 +162,7 @@ func (tx *Tx) init() { tx.CleanUser = NewCleanUserClient(tx.config) tx.Friendship = NewFriendshipClient(tx.config) tx.Group = NewGroupClient(tx.config) + tx.Parent = NewParentClient(tx.config) tx.Pet = NewPetClient(tx.config) tx.User = NewUserClient(tx.config) } diff --git a/entc/integration/multischema/ent/user.go b/entc/integration/multischema/ent/user.go index fd2658128..540f243e8 100644 --- a/entc/integration/multischema/ent/user.go +++ b/entc/integration/multischema/ent/user.go @@ -36,11 +36,17 @@ type UserEdges struct { Groups []*Group `json:"groups,omitempty"` // Friends holds the value of the friends edge. Friends []*User `json:"friends,omitempty"` + // Parents holds the value of the parents edge. + Parents []*User `json:"parents,omitempty"` + // Children holds the value of the children edge. + Children []*User `json:"children,omitempty"` // Friendships holds the value of the friendships edge. Friendships []*Friendship `json:"friendships,omitempty"` + // ParentHood holds the value of the parent_hood edge. + ParentHood []*Parent `json:"parent_hood,omitempty"` // loadedTypes holds the information for reporting if a // type was loaded (or requested) in eager-loading or not. - loadedTypes [4]bool + loadedTypes [7]bool } // PetsOrErr returns the Pets value or an error if the edge @@ -70,15 +76,42 @@ func (e UserEdges) FriendsOrErr() ([]*User, error) { return nil, &NotLoadedError{edge: "friends"} } +// ParentsOrErr returns the Parents value or an error if the edge +// was not loaded in eager-loading. +func (e UserEdges) ParentsOrErr() ([]*User, error) { + if e.loadedTypes[3] { + return e.Parents, nil + } + return nil, &NotLoadedError{edge: "parents"} +} + +// ChildrenOrErr returns the Children value or an error if the edge +// was not loaded in eager-loading. +func (e UserEdges) ChildrenOrErr() ([]*User, error) { + if e.loadedTypes[4] { + return e.Children, nil + } + return nil, &NotLoadedError{edge: "children"} +} + // FriendshipsOrErr returns the Friendships value or an error if the edge // was not loaded in eager-loading. func (e UserEdges) FriendshipsOrErr() ([]*Friendship, error) { - if e.loadedTypes[3] { + if e.loadedTypes[5] { return e.Friendships, nil } return nil, &NotLoadedError{edge: "friendships"} } +// ParentHoodOrErr returns the ParentHood value or an error if the edge +// was not loaded in eager-loading. +func (e UserEdges) ParentHoodOrErr() ([]*Parent, error) { + if e.loadedTypes[6] { + return e.ParentHood, nil + } + return nil, &NotLoadedError{edge: "parent_hood"} +} + // scanValues returns the types for scanning values from sql.Rows. func (*User) scanValues(columns []string) ([]any, error) { values := make([]any, len(columns)) @@ -143,11 +176,26 @@ func (_m *User) QueryFriends() *UserQuery { return NewUserClient(_m.config).QueryFriends(_m) } +// QueryParents queries the "parents" edge of the User entity. +func (_m *User) QueryParents() *UserQuery { + return NewUserClient(_m.config).QueryParents(_m) +} + +// QueryChildren queries the "children" edge of the User entity. +func (_m *User) QueryChildren() *UserQuery { + return NewUserClient(_m.config).QueryChildren(_m) +} + // QueryFriendships queries the "friendships" edge of the User entity. func (_m *User) QueryFriendships() *FriendshipQuery { return NewUserClient(_m.config).QueryFriendships(_m) } +// QueryParentHood queries the "parent_hood" edge of the User entity. +func (_m *User) QueryParentHood() *ParentQuery { + return NewUserClient(_m.config).QueryParentHood(_m) +} + // Update returns a builder for updating this User. // Note that you need to call User.Unwrap() before calling this method if this User // was returned from a transaction, and the transaction was committed or rolled back. diff --git a/entc/integration/multischema/ent/user/user.go b/entc/integration/multischema/ent/user/user.go index cc17a2eed..193284f20 100644 --- a/entc/integration/multischema/ent/user/user.go +++ b/entc/integration/multischema/ent/user/user.go @@ -24,8 +24,14 @@ const ( EdgeGroups = "groups" // EdgeFriends holds the string denoting the friends edge name in mutations. EdgeFriends = "friends" + // EdgeParents holds the string denoting the parents edge name in mutations. + EdgeParents = "parents" + // EdgeChildren holds the string denoting the children edge name in mutations. + EdgeChildren = "children" // EdgeFriendships holds the string denoting the friendships edge name in mutations. EdgeFriendships = "friendships" + // EdgeParentHood holds the string denoting the parent_hood edge name in mutations. + EdgeParentHood = "parent_hood" // Table holds the table name of the user in the database. Table = "users" // PetsTable is the table that holds the pets relation/edge. @@ -42,6 +48,10 @@ const ( GroupsInverseTable = "groups" // FriendsTable is the table that holds the friends relation/edge. The primary key declared below. FriendsTable = "friendships" + // ParentsTable is the table that holds the parents relation/edge. The primary key declared below. + ParentsTable = "parents" + // ChildrenTable is the table that holds the children relation/edge. The primary key declared below. + ChildrenTable = "parents" // FriendshipsTable is the table that holds the friendships relation/edge. FriendshipsTable = "friendships" // FriendshipsInverseTable is the table name for the Friendship entity. @@ -49,6 +59,13 @@ const ( FriendshipsInverseTable = "friendships" // FriendshipsColumn is the table column denoting the friendships relation/edge. FriendshipsColumn = "user_id" + // ParentHoodTable is the table that holds the parent_hood relation/edge. + ParentHoodTable = "parents" + // ParentHoodInverseTable is the table name for the Parent entity. + // It exists in this package in order to avoid circular dependency with the "parent" package. + ParentHoodInverseTable = "parents" + // ParentHoodColumn is the table column denoting the parent_hood relation/edge. + ParentHoodColumn = "user_id" ) // Columns holds all SQL columns for user fields. @@ -64,6 +81,12 @@ var ( // FriendsPrimaryKey and FriendsColumn2 are the table columns denoting the // primary key for the friends relation (M2M). FriendsPrimaryKey = []string{"user_id", "friend_id"} + // ParentsPrimaryKey and ParentsColumn2 are the table columns denoting the + // primary key for the parents relation (M2M). + ParentsPrimaryKey = []string{"user_id", "parent_id"} + // ChildrenPrimaryKey and ChildrenColumn2 are the table columns denoting the + // primary key for the children relation (M2M). + ChildrenPrimaryKey = []string{"user_id", "parent_id"} ) // ValidColumn reports if the column name is valid (part of the table columns). @@ -136,6 +159,34 @@ func ByFriends(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { } } +// ByParentsCount orders the results by parents count. +func ByParentsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newParentsStep(), opts...) + } +} + +// ByParents orders the results by parents terms. +func ByParents(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newParentsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByChildrenCount orders the results by children count. +func ByChildrenCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newChildrenStep(), opts...) + } +} + +// ByChildren orders the results by children terms. +func ByChildren(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newChildrenStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + // ByFriendshipsCount orders the results by friendships count. func ByFriendshipsCount(opts ...sql.OrderTermOption) OrderOption { return func(s *sql.Selector) { @@ -149,6 +200,20 @@ func ByFriendships(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { sqlgraph.OrderByNeighborTerms(s, newFriendshipsStep(), append([]sql.OrderTerm{term}, terms...)...) } } + +// ByParentHoodCount orders the results by parent_hood count. +func ByParentHoodCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newParentHoodStep(), opts...) + } +} + +// ByParentHood orders the results by parent_hood terms. +func ByParentHood(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newParentHoodStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} func newPetsStep() *sqlgraph.Step { return sqlgraph.NewStep( sqlgraph.From(Table, FieldID), @@ -170,6 +235,20 @@ func newFriendsStep() *sqlgraph.Step { sqlgraph.Edge(sqlgraph.M2M, false, FriendsTable, FriendsPrimaryKey...), ) } +func newParentsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, ParentsTable, ParentsPrimaryKey...), + ) +} +func newChildrenStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, ChildrenTable, ChildrenPrimaryKey...), + ) +} func newFriendshipsStep() *sqlgraph.Step { return sqlgraph.NewStep( sqlgraph.From(Table, FieldID), @@ -177,3 +256,10 @@ func newFriendshipsStep() *sqlgraph.Step { sqlgraph.Edge(sqlgraph.O2M, true, FriendshipsTable, FriendshipsColumn), ) } +func newParentHoodStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ParentHoodInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, ParentHoodTable, ParentHoodColumn), + ) +} diff --git a/entc/integration/multischema/ent/user/where.go b/entc/integration/multischema/ent/user/where.go index edbddcdbf..1b530efc7 100644 --- a/entc/integration/multischema/ent/user/where.go +++ b/entc/integration/multischema/ent/user/where.go @@ -215,6 +215,64 @@ func HasFriendsWith(preds ...predicate.User) predicate.User { }) } +// HasParents applies the HasEdge predicate on the "parents" edge. +func HasParents() predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, ParentsTable, ParentsPrimaryKey...), + ) + schemaConfig := internal.SchemaConfigFromContext(s.Context()) + step.To.Schema = schemaConfig.User + step.Edge.Schema = schemaConfig.UserChildren + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasParentsWith applies the HasEdge predicate on the "parents" edge with a given conditions (other predicates). +func HasParentsWith(preds ...predicate.User) predicate.User { + return predicate.User(func(s *sql.Selector) { + step := newParentsStep() + schemaConfig := internal.SchemaConfigFromContext(s.Context()) + step.To.Schema = schemaConfig.User + step.Edge.Schema = schemaConfig.UserChildren + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasChildren applies the HasEdge predicate on the "children" edge. +func HasChildren() predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, ChildrenTable, ChildrenPrimaryKey...), + ) + schemaConfig := internal.SchemaConfigFromContext(s.Context()) + step.To.Schema = schemaConfig.User + step.Edge.Schema = schemaConfig.Parent + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasChildrenWith applies the HasEdge predicate on the "children" edge with a given conditions (other predicates). +func HasChildrenWith(preds ...predicate.User) predicate.User { + return predicate.User(func(s *sql.Selector) { + step := newChildrenStep() + schemaConfig := internal.SchemaConfigFromContext(s.Context()) + step.To.Schema = schemaConfig.User + step.Edge.Schema = schemaConfig.Parent + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + // HasFriendships applies the HasEdge predicate on the "friendships" edge. func HasFriendships() predicate.User { return predicate.User(func(s *sql.Selector) { @@ -244,6 +302,35 @@ func HasFriendshipsWith(preds ...predicate.Friendship) predicate.User { }) } +// HasParentHood applies the HasEdge predicate on the "parent_hood" edge. +func HasParentHood() predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, ParentHoodTable, ParentHoodColumn), + ) + schemaConfig := internal.SchemaConfigFromContext(s.Context()) + step.To.Schema = schemaConfig.Parent + step.Edge.Schema = schemaConfig.Parent + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasParentHoodWith applies the HasEdge predicate on the "parent_hood" edge with a given conditions (other predicates). +func HasParentHoodWith(preds ...predicate.Parent) predicate.User { + return predicate.User(func(s *sql.Selector) { + step := newParentHoodStep() + schemaConfig := internal.SchemaConfigFromContext(s.Context()) + step.To.Schema = schemaConfig.Parent + step.Edge.Schema = schemaConfig.Parent + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + // And groups predicates with the AND operator between them. func And(predicates ...predicate.User) predicate.User { return predicate.User(sql.AndPredicates(predicates...)) diff --git a/entc/integration/multischema/ent/user_create.go b/entc/integration/multischema/ent/user_create.go index 588b3c1a4..ac882729a 100644 --- a/entc/integration/multischema/ent/user_create.go +++ b/entc/integration/multischema/ent/user_create.go @@ -14,6 +14,7 @@ import ( "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/entc/integration/multischema/ent/friendship" "entgo.io/ent/entc/integration/multischema/ent/group" + "entgo.io/ent/entc/integration/multischema/ent/parent" "entgo.io/ent/entc/integration/multischema/ent/pet" "entgo.io/ent/entc/integration/multischema/ent/user" "entgo.io/ent/schema/field" @@ -85,6 +86,36 @@ func (_c *UserCreate) AddFriends(v ...*User) *UserCreate { return _c.AddFriendIDs(ids...) } +// AddParentIDs adds the "parents" edge to the User entity by IDs. +func (_c *UserCreate) AddParentIDs(ids ...int) *UserCreate { + _c.mutation.AddParentIDs(ids...) + return _c +} + +// AddParents adds the "parents" edges to the User entity. +func (_c *UserCreate) AddParents(v ...*User) *UserCreate { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddParentIDs(ids...) +} + +// AddChildIDs adds the "children" edge to the User entity by IDs. +func (_c *UserCreate) AddChildIDs(ids ...int) *UserCreate { + _c.mutation.AddChildIDs(ids...) + return _c +} + +// AddChildren adds the "children" edges to the User entity. +func (_c *UserCreate) AddChildren(v ...*User) *UserCreate { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddChildIDs(ids...) +} + // AddFriendshipIDs adds the "friendships" edge to the Friendship entity by IDs. func (_c *UserCreate) AddFriendshipIDs(ids ...int) *UserCreate { _c.mutation.AddFriendshipIDs(ids...) @@ -100,6 +131,21 @@ func (_c *UserCreate) AddFriendships(v ...*Friendship) *UserCreate { return _c.AddFriendshipIDs(ids...) } +// AddParentHoodIDs adds the "parent_hood" edge to the Parent entity by IDs. +func (_c *UserCreate) AddParentHoodIDs(ids ...int) *UserCreate { + _c.mutation.AddParentHoodIDs(ids...) + return _c +} + +// AddParentHood adds the "parent_hood" edges to the Parent entity. +func (_c *UserCreate) AddParentHood(v ...*Parent) *UserCreate { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddParentHoodIDs(ids...) +} + // Mutation returns the UserMutation object of the builder. func (_c *UserCreate) Mutation() *UserMutation { return _c.mutation @@ -232,6 +278,44 @@ func (_c *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) { edge.Target.Fields = specE.Fields _spec.Edges = append(_spec.Edges, edge) } + if nodes := _c.mutation.ParentsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: user.ParentsTable, + Columns: user.ParentsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + edge.Schema = _c.schemaConfig.UserChildren + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.ChildrenIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.ChildrenTable, + Columns: user.ChildrenPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + edge.Schema = _c.schemaConfig.Parent + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &ParentCreate{config: _c.config, mutation: newParentMutation(_c.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges = append(_spec.Edges, edge) + } if nodes := _c.mutation.FriendshipsIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, @@ -249,6 +333,23 @@ func (_c *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) { } _spec.Edges = append(_spec.Edges, edge) } + if nodes := _c.mutation.ParentHoodIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.ParentHoodTable, + Columns: []string{user.ParentHoodColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(parent.FieldID, field.TypeInt), + }, + } + edge.Schema = _c.schemaConfig.Parent + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } return _node, _spec } diff --git a/entc/integration/multischema/ent/user_query.go b/entc/integration/multischema/ent/user_query.go index 59910d8f0..3b8d8dee5 100644 --- a/entc/integration/multischema/ent/user_query.go +++ b/entc/integration/multischema/ent/user_query.go @@ -18,6 +18,7 @@ import ( "entgo.io/ent/entc/integration/multischema/ent/friendship" "entgo.io/ent/entc/integration/multischema/ent/group" "entgo.io/ent/entc/integration/multischema/ent/internal" + "entgo.io/ent/entc/integration/multischema/ent/parent" "entgo.io/ent/entc/integration/multischema/ent/pet" "entgo.io/ent/entc/integration/multischema/ent/predicate" "entgo.io/ent/entc/integration/multischema/ent/user" @@ -34,7 +35,10 @@ type UserQuery struct { withPets *PetQuery withGroups *GroupQuery withFriends *UserQuery + withParents *UserQuery + withChildren *UserQuery withFriendships *FriendshipQuery + withParentHood *ParentQuery modifiers []func(*sql.Selector) // intermediate query (i.e. traversal path). sql *sql.Selector @@ -147,6 +151,56 @@ func (_q *UserQuery) QueryFriends() *UserQuery { return query } +// QueryParents chains the current query on the "parents" edge. +func (_q *UserQuery) QueryParents() *UserQuery { + query := (&UserClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, selector), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, user.ParentsTable, user.ParentsPrimaryKey...), + ) + schemaConfig := _q.schemaConfig + step.To.Schema = schemaConfig.User + step.Edge.Schema = schemaConfig.UserChildren + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryChildren chains the current query on the "children" edge. +func (_q *UserQuery) QueryChildren() *UserQuery { + query := (&UserClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, selector), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, user.ChildrenTable, user.ChildrenPrimaryKey...), + ) + schemaConfig := _q.schemaConfig + step.To.Schema = schemaConfig.User + step.Edge.Schema = schemaConfig.Parent + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + // QueryFriendships chains the current query on the "friendships" edge. func (_q *UserQuery) QueryFriendships() *FriendshipQuery { query := (&FriendshipClient{config: _q.config}).Query() @@ -172,6 +226,31 @@ func (_q *UserQuery) QueryFriendships() *FriendshipQuery { return query } +// QueryParentHood chains the current query on the "parent_hood" edge. +func (_q *UserQuery) QueryParentHood() *ParentQuery { + query := (&ParentClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, selector), + sqlgraph.To(parent.Table, parent.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, user.ParentHoodTable, user.ParentHoodColumn), + ) + schemaConfig := _q.schemaConfig + step.To.Schema = schemaConfig.Parent + step.Edge.Schema = schemaConfig.Parent + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + // First returns the first User entity from the query. // Returns a *NotFoundError when no User was found. func (_q *UserQuery) First(ctx context.Context) (*User, error) { @@ -367,7 +446,10 @@ func (_q *UserQuery) Clone() *UserQuery { withPets: _q.withPets.Clone(), withGroups: _q.withGroups.Clone(), withFriends: _q.withFriends.Clone(), + withParents: _q.withParents.Clone(), + withChildren: _q.withChildren.Clone(), withFriendships: _q.withFriendships.Clone(), + withParentHood: _q.withParentHood.Clone(), // clone intermediate query. sql: _q.sql.Clone(), path: _q.path, @@ -408,6 +490,28 @@ func (_q *UserQuery) WithFriends(opts ...func(*UserQuery)) *UserQuery { return _q } +// WithParents tells the query-builder to eager-load the nodes that are connected to +// the "parents" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *UserQuery) WithParents(opts ...func(*UserQuery)) *UserQuery { + query := (&UserClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withParents = query + return _q +} + +// WithChildren tells the query-builder to eager-load the nodes that are connected to +// the "children" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *UserQuery) WithChildren(opts ...func(*UserQuery)) *UserQuery { + query := (&UserClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withChildren = query + return _q +} + // WithFriendships tells the query-builder to eager-load the nodes that are connected to // the "friendships" edge. The optional arguments are used to configure the query builder of the edge. func (_q *UserQuery) WithFriendships(opts ...func(*FriendshipQuery)) *UserQuery { @@ -419,6 +523,17 @@ func (_q *UserQuery) WithFriendships(opts ...func(*FriendshipQuery)) *UserQuery return _q } +// WithParentHood tells the query-builder to eager-load the nodes that are connected to +// the "parent_hood" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *UserQuery) WithParentHood(opts ...func(*ParentQuery)) *UserQuery { + query := (&ParentClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withParentHood = query + return _q +} + // GroupBy is used to group vertices by one or more fields/columns. // It is often used with aggregate functions, like: count, max, mean, min, sum. // @@ -497,11 +612,14 @@ func (_q *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, e var ( nodes = []*User{} _spec = _q.querySpec() - loadedTypes = [4]bool{ + loadedTypes = [7]bool{ _q.withPets != nil, _q.withGroups != nil, _q.withFriends != nil, + _q.withParents != nil, + _q.withChildren != nil, _q.withFriendships != nil, + _q.withParentHood != nil, } ) _spec.ScanValues = func(columns []string) ([]any, error) { @@ -548,6 +666,20 @@ func (_q *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, e return nil, err } } + if query := _q.withParents; query != nil { + if err := _q.loadParents(ctx, query, nodes, + func(n *User) { n.Edges.Parents = []*User{} }, + func(n *User, e *User) { n.Edges.Parents = append(n.Edges.Parents, e) }); err != nil { + return nil, err + } + } + if query := _q.withChildren; query != nil { + if err := _q.loadChildren(ctx, query, nodes, + func(n *User) { n.Edges.Children = []*User{} }, + func(n *User, e *User) { n.Edges.Children = append(n.Edges.Children, e) }); err != nil { + return nil, err + } + } if query := _q.withFriendships; query != nil { if err := _q.loadFriendships(ctx, query, nodes, func(n *User) { n.Edges.Friendships = []*Friendship{} }, @@ -555,6 +687,13 @@ func (_q *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, e return nil, err } } + if query := _q.withParentHood; query != nil { + if err := _q.loadParentHood(ctx, query, nodes, + func(n *User) { n.Edges.ParentHood = []*Parent{} }, + func(n *User, e *Parent) { n.Edges.ParentHood = append(n.Edges.ParentHood, e) }); err != nil { + return nil, err + } + } return nodes, nil } @@ -712,6 +851,130 @@ func (_q *UserQuery) loadFriends(ctx context.Context, query *UserQuery, nodes [] } return nil } +func (_q *UserQuery) loadParents(ctx context.Context, query *UserQuery, nodes []*User, init func(*User), assign func(*User, *User)) error { + edgeIDs := make([]driver.Value, len(nodes)) + byID := make(map[int]*User) + nids := make(map[int]map[*User]struct{}) + for i, node := range nodes { + edgeIDs[i] = node.ID + byID[node.ID] = node + if init != nil { + init(node) + } + } + query.Where(func(s *sql.Selector) { + joinT := sql.Table(user.ParentsTable) + joinT.Schema(_q.schemaConfig.UserChildren) + s.Join(joinT).On(s.C(user.FieldID), joinT.C(user.ParentsPrimaryKey[0])) + s.Where(sql.InValues(joinT.C(user.ParentsPrimaryKey[1]), edgeIDs...)) + columns := s.SelectedColumns() + s.Select(joinT.C(user.ParentsPrimaryKey[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[*User]struct{}{byID[outValue]: {}} + return assign(columns[1:], values[1:]) + } + nids[inValue][byID[outValue]] = struct{}{} + return nil + } + }) + }) + neighbors, err := withInterceptors[[]*User](ctx, query, qr, query.inters) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nids[n.ID] + if !ok { + return fmt.Errorf(`unexpected "parents" node returned %v`, n.ID) + } + for kn := range nodes { + assign(kn, n) + } + } + return nil +} +func (_q *UserQuery) loadChildren(ctx context.Context, query *UserQuery, nodes []*User, init func(*User), assign func(*User, *User)) error { + edgeIDs := make([]driver.Value, len(nodes)) + byID := make(map[int]*User) + nids := make(map[int]map[*User]struct{}) + for i, node := range nodes { + edgeIDs[i] = node.ID + byID[node.ID] = node + if init != nil { + init(node) + } + } + query.Where(func(s *sql.Selector) { + joinT := sql.Table(user.ChildrenTable) + joinT.Schema(_q.schemaConfig.Parent) + s.Join(joinT).On(s.C(user.FieldID), joinT.C(user.ChildrenPrimaryKey[1])) + s.Where(sql.InValues(joinT.C(user.ChildrenPrimaryKey[0]), edgeIDs...)) + columns := s.SelectedColumns() + s.Select(joinT.C(user.ChildrenPrimaryKey[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[*User]struct{}{byID[outValue]: {}} + return assign(columns[1:], values[1:]) + } + nids[inValue][byID[outValue]] = struct{}{} + return nil + } + }) + }) + neighbors, err := withInterceptors[[]*User](ctx, query, qr, query.inters) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nids[n.ID] + if !ok { + return fmt.Errorf(`unexpected "children" node returned %v`, n.ID) + } + for kn := range nodes { + assign(kn, n) + } + } + return nil +} func (_q *UserQuery) loadFriendships(ctx context.Context, query *FriendshipQuery, nodes []*User, init func(*User), assign func(*User, *Friendship)) error { fks := make([]driver.Value, 0, len(nodes)) nodeids := make(map[int]*User) @@ -742,6 +1005,36 @@ func (_q *UserQuery) loadFriendships(ctx context.Context, query *FriendshipQuery } return nil } +func (_q *UserQuery) loadParentHood(ctx context.Context, query *ParentQuery, nodes []*User, init func(*User), assign func(*User, *Parent)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int]*User) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) + } + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(parent.FieldUserID) + } + query.Where(predicate.Parent(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(user.ParentHoodColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.UserID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "user_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} func (_q *UserQuery) sqlCount(ctx context.Context) (int, error) { _spec := _q.querySpec() diff --git a/entc/integration/multischema/ent/user_update.go b/entc/integration/multischema/ent/user_update.go index 3833bfba8..645d4f400 100644 --- a/entc/integration/multischema/ent/user_update.go +++ b/entc/integration/multischema/ent/user_update.go @@ -16,6 +16,7 @@ import ( "entgo.io/ent/entc/integration/multischema/ent/friendship" "entgo.io/ent/entc/integration/multischema/ent/group" "entgo.io/ent/entc/integration/multischema/ent/internal" + "entgo.io/ent/entc/integration/multischema/ent/parent" "entgo.io/ent/entc/integration/multischema/ent/pet" "entgo.io/ent/entc/integration/multischema/ent/predicate" "entgo.io/ent/entc/integration/multischema/ent/user" @@ -95,6 +96,36 @@ func (_u *UserUpdate) AddFriends(v ...*User) *UserUpdate { return _u.AddFriendIDs(ids...) } +// AddParentIDs adds the "parents" edge to the User entity by IDs. +func (_u *UserUpdate) AddParentIDs(ids ...int) *UserUpdate { + _u.mutation.AddParentIDs(ids...) + return _u +} + +// AddParents adds the "parents" edges to the User entity. +func (_u *UserUpdate) AddParents(v ...*User) *UserUpdate { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddParentIDs(ids...) +} + +// AddChildIDs adds the "children" edge to the User entity by IDs. +func (_u *UserUpdate) AddChildIDs(ids ...int) *UserUpdate { + _u.mutation.AddChildIDs(ids...) + return _u +} + +// AddChildren adds the "children" edges to the User entity. +func (_u *UserUpdate) AddChildren(v ...*User) *UserUpdate { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddChildIDs(ids...) +} + // AddFriendshipIDs adds the "friendships" edge to the Friendship entity by IDs. func (_u *UserUpdate) AddFriendshipIDs(ids ...int) *UserUpdate { _u.mutation.AddFriendshipIDs(ids...) @@ -110,6 +141,21 @@ func (_u *UserUpdate) AddFriendships(v ...*Friendship) *UserUpdate { return _u.AddFriendshipIDs(ids...) } +// AddParentHoodIDs adds the "parent_hood" edge to the Parent entity by IDs. +func (_u *UserUpdate) AddParentHoodIDs(ids ...int) *UserUpdate { + _u.mutation.AddParentHoodIDs(ids...) + return _u +} + +// AddParentHood adds the "parent_hood" edges to the Parent entity. +func (_u *UserUpdate) AddParentHood(v ...*Parent) *UserUpdate { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddParentHoodIDs(ids...) +} + // Mutation returns the UserMutation object of the builder. func (_u *UserUpdate) Mutation() *UserMutation { return _u.mutation @@ -178,6 +224,48 @@ func (_u *UserUpdate) RemoveFriends(v ...*User) *UserUpdate { return _u.RemoveFriendIDs(ids...) } +// ClearParents clears all "parents" edges to the User entity. +func (_u *UserUpdate) ClearParents() *UserUpdate { + _u.mutation.ClearParents() + return _u +} + +// RemoveParentIDs removes the "parents" edge to User entities by IDs. +func (_u *UserUpdate) RemoveParentIDs(ids ...int) *UserUpdate { + _u.mutation.RemoveParentIDs(ids...) + return _u +} + +// RemoveParents removes "parents" edges to User entities. +func (_u *UserUpdate) RemoveParents(v ...*User) *UserUpdate { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveParentIDs(ids...) +} + +// ClearChildren clears all "children" edges to the User entity. +func (_u *UserUpdate) ClearChildren() *UserUpdate { + _u.mutation.ClearChildren() + return _u +} + +// RemoveChildIDs removes the "children" edge to User entities by IDs. +func (_u *UserUpdate) RemoveChildIDs(ids ...int) *UserUpdate { + _u.mutation.RemoveChildIDs(ids...) + return _u +} + +// RemoveChildren removes "children" edges to User entities. +func (_u *UserUpdate) RemoveChildren(v ...*User) *UserUpdate { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveChildIDs(ids...) +} + // ClearFriendships clears all "friendships" edges to the Friendship entity. func (_u *UserUpdate) ClearFriendships() *UserUpdate { _u.mutation.ClearFriendships() @@ -199,6 +287,27 @@ func (_u *UserUpdate) RemoveFriendships(v ...*Friendship) *UserUpdate { return _u.RemoveFriendshipIDs(ids...) } +// ClearParentHood clears all "parent_hood" edges to the Parent entity. +func (_u *UserUpdate) ClearParentHood() *UserUpdate { + _u.mutation.ClearParentHood() + return _u +} + +// RemoveParentHoodIDs removes the "parent_hood" edge to Parent entities by IDs. +func (_u *UserUpdate) RemoveParentHoodIDs(ids ...int) *UserUpdate { + _u.mutation.RemoveParentHoodIDs(ids...) + return _u +} + +// RemoveParentHood removes "parent_hood" edges to Parent entities. +func (_u *UserUpdate) RemoveParentHood(v ...*Parent) *UserUpdate { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveParentHoodIDs(ids...) +} + // Save executes the query and returns the number of nodes affected by the update operation. func (_u *UserUpdate) Save(ctx context.Context) (int, error) { return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) @@ -400,6 +509,114 @@ func (_u *UserUpdate) sqlSave(ctx context.Context) (_node int, err error) { edge.Target.Fields = specE.Fields _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if _u.mutation.ParentsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: user.ParentsTable, + Columns: user.ParentsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + edge.Schema = _u.schemaConfig.UserChildren + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedParentsIDs(); len(nodes) > 0 && !_u.mutation.ParentsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: user.ParentsTable, + Columns: user.ParentsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + edge.Schema = _u.schemaConfig.UserChildren + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.ParentsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: user.ParentsTable, + Columns: user.ParentsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + edge.Schema = _u.schemaConfig.UserChildren + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.ChildrenCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.ChildrenTable, + Columns: user.ChildrenPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + edge.Schema = _u.schemaConfig.Parent + createE := &ParentCreate{config: _u.config, mutation: newParentMutation(_u.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedChildrenIDs(); len(nodes) > 0 && !_u.mutation.ChildrenCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.ChildrenTable, + Columns: user.ChildrenPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + edge.Schema = _u.schemaConfig.Parent + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &ParentCreate{config: _u.config, mutation: newParentMutation(_u.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.ChildrenIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.ChildrenTable, + Columns: user.ChildrenPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + edge.Schema = _u.schemaConfig.Parent + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &ParentCreate{config: _u.config, mutation: newParentMutation(_u.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } if _u.mutation.FriendshipsCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, @@ -448,6 +665,54 @@ func (_u *UserUpdate) sqlSave(ctx context.Context) (_node int, err error) { } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if _u.mutation.ParentHoodCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.ParentHoodTable, + Columns: []string{user.ParentHoodColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(parent.FieldID, field.TypeInt), + }, + } + edge.Schema = _u.schemaConfig.Parent + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedParentHoodIDs(); len(nodes) > 0 && !_u.mutation.ParentHoodCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.ParentHoodTable, + Columns: []string{user.ParentHoodColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(parent.FieldID, field.TypeInt), + }, + } + edge.Schema = _u.schemaConfig.Parent + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.ParentHoodIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.ParentHoodTable, + Columns: []string{user.ParentHoodColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(parent.FieldID, field.TypeInt), + }, + } + edge.Schema = _u.schemaConfig.Parent + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } _spec.Node.Schema = _u.schemaConfig.User ctx = internal.NewSchemaConfigContext(ctx, _u.schemaConfig) _spec.AddModifiers(_u.modifiers...) @@ -531,6 +796,36 @@ func (_u *UserUpdateOne) AddFriends(v ...*User) *UserUpdateOne { return _u.AddFriendIDs(ids...) } +// AddParentIDs adds the "parents" edge to the User entity by IDs. +func (_u *UserUpdateOne) AddParentIDs(ids ...int) *UserUpdateOne { + _u.mutation.AddParentIDs(ids...) + return _u +} + +// AddParents adds the "parents" edges to the User entity. +func (_u *UserUpdateOne) AddParents(v ...*User) *UserUpdateOne { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddParentIDs(ids...) +} + +// AddChildIDs adds the "children" edge to the User entity by IDs. +func (_u *UserUpdateOne) AddChildIDs(ids ...int) *UserUpdateOne { + _u.mutation.AddChildIDs(ids...) + return _u +} + +// AddChildren adds the "children" edges to the User entity. +func (_u *UserUpdateOne) AddChildren(v ...*User) *UserUpdateOne { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddChildIDs(ids...) +} + // AddFriendshipIDs adds the "friendships" edge to the Friendship entity by IDs. func (_u *UserUpdateOne) AddFriendshipIDs(ids ...int) *UserUpdateOne { _u.mutation.AddFriendshipIDs(ids...) @@ -546,6 +841,21 @@ func (_u *UserUpdateOne) AddFriendships(v ...*Friendship) *UserUpdateOne { return _u.AddFriendshipIDs(ids...) } +// AddParentHoodIDs adds the "parent_hood" edge to the Parent entity by IDs. +func (_u *UserUpdateOne) AddParentHoodIDs(ids ...int) *UserUpdateOne { + _u.mutation.AddParentHoodIDs(ids...) + return _u +} + +// AddParentHood adds the "parent_hood" edges to the Parent entity. +func (_u *UserUpdateOne) AddParentHood(v ...*Parent) *UserUpdateOne { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddParentHoodIDs(ids...) +} + // Mutation returns the UserMutation object of the builder. func (_u *UserUpdateOne) Mutation() *UserMutation { return _u.mutation @@ -614,6 +924,48 @@ func (_u *UserUpdateOne) RemoveFriends(v ...*User) *UserUpdateOne { return _u.RemoveFriendIDs(ids...) } +// ClearParents clears all "parents" edges to the User entity. +func (_u *UserUpdateOne) ClearParents() *UserUpdateOne { + _u.mutation.ClearParents() + return _u +} + +// RemoveParentIDs removes the "parents" edge to User entities by IDs. +func (_u *UserUpdateOne) RemoveParentIDs(ids ...int) *UserUpdateOne { + _u.mutation.RemoveParentIDs(ids...) + return _u +} + +// RemoveParents removes "parents" edges to User entities. +func (_u *UserUpdateOne) RemoveParents(v ...*User) *UserUpdateOne { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveParentIDs(ids...) +} + +// ClearChildren clears all "children" edges to the User entity. +func (_u *UserUpdateOne) ClearChildren() *UserUpdateOne { + _u.mutation.ClearChildren() + return _u +} + +// RemoveChildIDs removes the "children" edge to User entities by IDs. +func (_u *UserUpdateOne) RemoveChildIDs(ids ...int) *UserUpdateOne { + _u.mutation.RemoveChildIDs(ids...) + return _u +} + +// RemoveChildren removes "children" edges to User entities. +func (_u *UserUpdateOne) RemoveChildren(v ...*User) *UserUpdateOne { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveChildIDs(ids...) +} + // ClearFriendships clears all "friendships" edges to the Friendship entity. func (_u *UserUpdateOne) ClearFriendships() *UserUpdateOne { _u.mutation.ClearFriendships() @@ -635,6 +987,27 @@ func (_u *UserUpdateOne) RemoveFriendships(v ...*Friendship) *UserUpdateOne { return _u.RemoveFriendshipIDs(ids...) } +// ClearParentHood clears all "parent_hood" edges to the Parent entity. +func (_u *UserUpdateOne) ClearParentHood() *UserUpdateOne { + _u.mutation.ClearParentHood() + return _u +} + +// RemoveParentHoodIDs removes the "parent_hood" edge to Parent entities by IDs. +func (_u *UserUpdateOne) RemoveParentHoodIDs(ids ...int) *UserUpdateOne { + _u.mutation.RemoveParentHoodIDs(ids...) + return _u +} + +// RemoveParentHood removes "parent_hood" edges to Parent entities. +func (_u *UserUpdateOne) RemoveParentHood(v ...*Parent) *UserUpdateOne { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveParentHoodIDs(ids...) +} + // Where appends a list predicates to the UserUpdate builder. func (_u *UserUpdateOne) Where(ps ...predicate.User) *UserUpdateOne { _u.mutation.Where(ps...) @@ -866,6 +1239,114 @@ func (_u *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) { edge.Target.Fields = specE.Fields _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if _u.mutation.ParentsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: user.ParentsTable, + Columns: user.ParentsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + edge.Schema = _u.schemaConfig.UserChildren + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedParentsIDs(); len(nodes) > 0 && !_u.mutation.ParentsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: user.ParentsTable, + Columns: user.ParentsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + edge.Schema = _u.schemaConfig.UserChildren + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.ParentsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: user.ParentsTable, + Columns: user.ParentsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + edge.Schema = _u.schemaConfig.UserChildren + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.ChildrenCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.ChildrenTable, + Columns: user.ChildrenPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + edge.Schema = _u.schemaConfig.Parent + createE := &ParentCreate{config: _u.config, mutation: newParentMutation(_u.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedChildrenIDs(); len(nodes) > 0 && !_u.mutation.ChildrenCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.ChildrenTable, + Columns: user.ChildrenPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + edge.Schema = _u.schemaConfig.Parent + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &ParentCreate{config: _u.config, mutation: newParentMutation(_u.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.ChildrenIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.ChildrenTable, + Columns: user.ChildrenPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + edge.Schema = _u.schemaConfig.Parent + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &ParentCreate{config: _u.config, mutation: newParentMutation(_u.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } if _u.mutation.FriendshipsCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, @@ -914,6 +1395,54 @@ func (_u *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) { } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if _u.mutation.ParentHoodCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.ParentHoodTable, + Columns: []string{user.ParentHoodColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(parent.FieldID, field.TypeInt), + }, + } + edge.Schema = _u.schemaConfig.Parent + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedParentHoodIDs(); len(nodes) > 0 && !_u.mutation.ParentHoodCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.ParentHoodTable, + Columns: []string{user.ParentHoodColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(parent.FieldID, field.TypeInt), + }, + } + edge.Schema = _u.schemaConfig.Parent + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.ParentHoodIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.ParentHoodTable, + Columns: []string{user.ParentHoodColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(parent.FieldID, field.TypeInt), + }, + } + edge.Schema = _u.schemaConfig.Parent + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } _spec.Node.Schema = _u.schemaConfig.User ctx = internal.NewSchemaConfigContext(ctx, _u.schemaConfig) _spec.AddModifiers(_u.modifiers...) diff --git a/entc/integration/multischema/multischema_test.go b/entc/integration/multischema/multischema_test.go index c6fbdb3a7..1c1dbc4b3 100644 --- a/entc/integration/multischema/multischema_test.go +++ b/entc/integration/multischema/multischema_test.go @@ -9,6 +9,7 @@ import ( "fmt" "log" "os" + "slices" "testing" "ariga.io/atlas-go-sdk/atlasexec" @@ -41,6 +42,7 @@ func TestMySQL(t *testing.T) { db.Close() }) + migrate.ParentsTable.Schema = "db1" migrate.PetsTable.Schema = "db1" migrate.UsersTable.Schema = "db1" migrate.GroupsTable.Schema = "db2" @@ -150,6 +152,18 @@ func TestMySQL(t *testing.T) { require.Len(t, users[1].Edges.Friends, 1) require.Len(t, users[0].Edges.Friendships, 1) require.Len(t, users[1].Edges.Friendships, 1) + + ta := client.User.Create().SetName("ta").AddParents(a8m, nat).SaveX(ctx) + el := client.User.Create().SetName("el").AddParents(a8m, nat).SaveX(ctx) + jo := client.User.Create().SetName("be").AddParents(a8m, nat).SaveX(ctx) + + require.Equal(t, 3, client.User.Query().Where(user.HasParents()).CountX(ctx)) + require.Equal(t, 3, a8m.QueryChildren().CountX(ctx)) + + sib := ta.QueryParents().QueryChildren().Where(user.NameNEQ(ta.Name)).AllX(ctx) + require.Len(t, sib, 2) + require.True(t, slices.ContainsFunc(sib, func(u *ent.User) bool { return u.Name == el.Name })) + require.True(t, slices.ContainsFunc(sib, func(u *ent.User) bool { return u.Name == jo.Name })) } func TestVersionedMigration(t *testing.T) { diff --git a/entc/integration/multischema/versioned/internal/schemaconfig.go b/entc/integration/multischema/versioned/internal/schemaconfig.go index 6965547fc..3165909e2 100644 --- a/entc/integration/multischema/versioned/internal/schemaconfig.go +++ b/entc/integration/multischema/versioned/internal/schemaconfig.go @@ -16,6 +16,7 @@ type SchemaConfig struct { GroupUsers string // Group-users->User table. Pet string // Pet table. User string // User table. + UserFriends string // User-friends->User table. UserFollowing string // User-following->User table. }