From 3a64e2d20d1c5898743d76941a87666cc3e5e943 Mon Sep 17 00:00:00 2001 From: Ariel Mashraki <7413593+a8m@users.noreply.github.com> Date: Tue, 2 Mar 2021 17:42:52 +0200 Subject: [PATCH] entc/gen: use edge.owner for checking fk field (#1293) See issue 1288 --- entc/gen/type.go | 2 +- entc/integration/issue1288/ent/client.go | 129 ++- entc/integration/issue1288/ent/config.go | 1 + entc/integration/issue1288/ent/hook/hook.go | 13 + entc/integration/issue1288/ent/info.go | 139 +++ entc/integration/issue1288/ent/info/info.go | 45 + entc/integration/issue1288/ent/info/where.go | 156 +++ entc/integration/issue1288/ent/info_create.go | 242 +++++ entc/integration/issue1288/ent/info_delete.go | 112 ++ entc/integration/issue1288/ent/info_query.go | 965 ++++++++++++++++++ entc/integration/issue1288/ent/info_update.go | 364 +++++++ .../issue1288/ent/migrate/schema.go | 21 + entc/integration/issue1288/ent/mutation.go | 453 +++++++- .../issue1288/ent/predicate/predicate.go | 3 + entc/integration/issue1288/ent/schema/info.go | 32 + entc/integration/issue1288/ent/schema/user.go | 2 + entc/integration/issue1288/ent/tx.go | 5 +- entc/integration/issue1288/ent/user.go | 18 +- entc/integration/issue1288/ent/user/user.go | 9 + entc/integration/issue1288/ent/user/where.go | 28 + entc/integration/issue1288/ent/user_create.go | 35 + entc/integration/issue1288/ent/user_query.go | 64 +- entc/integration/issue1288/ent/user_update.go | 181 ++++ entc/integration/issue1288/issue_test.go | 6 + 24 files changed, 3017 insertions(+), 8 deletions(-) create mode 100644 entc/integration/issue1288/ent/info.go create mode 100644 entc/integration/issue1288/ent/info/info.go create mode 100644 entc/integration/issue1288/ent/info/where.go create mode 100644 entc/integration/issue1288/ent/info_create.go create mode 100644 entc/integration/issue1288/ent/info_delete.go create mode 100644 entc/integration/issue1288/ent/info_query.go create mode 100644 entc/integration/issue1288/ent/info_update.go create mode 100644 entc/integration/issue1288/ent/schema/info.go diff --git a/entc/gen/type.go b/entc/gen/type.go index 825737c90..b62cd630d 100644 --- a/entc/gen/type.go +++ b/entc/gen/type.go @@ -582,7 +582,7 @@ func (t *Type) resolveFKs() error { } // Special case for checking if the FK is already defined // in the field list (see issue 1288). - if fd, ok := e.Type.FieldBy(func(f *Field) bool { + if fd, ok := owner.FieldBy(func(f *Field) bool { return f.StorageKey() == e.Rel.Column() }); ok { fk.Field = fd diff --git a/entc/integration/issue1288/ent/client.go b/entc/integration/issue1288/ent/client.go index b22b21605..f5b242a91 100644 --- a/entc/integration/issue1288/ent/client.go +++ b/entc/integration/issue1288/ent/client.go @@ -13,6 +13,7 @@ import ( "entgo.io/ent/entc/integration/issue1288/ent/migrate" + "entgo.io/ent/entc/integration/issue1288/ent/info" "entgo.io/ent/entc/integration/issue1288/ent/metadata" "entgo.io/ent/entc/integration/issue1288/ent/user" @@ -26,6 +27,8 @@ type Client struct { config // Schema is the client for creating, migrating and dropping schema. Schema *migrate.Schema + // Info is the client for interacting with the Info builders. + Info *InfoClient // Metadata is the client for interacting with the Metadata builders. Metadata *MetadataClient // User is the client for interacting with the User builders. @@ -43,6 +46,7 @@ func NewClient(opts ...Option) *Client { func (c *Client) init() { c.Schema = migrate.NewSchema(c.driver) + c.Info = NewInfoClient(c.config) c.Metadata = NewMetadataClient(c.config) c.User = NewUserClient(c.config) } @@ -78,6 +82,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { return &Tx{ ctx: ctx, config: cfg, + Info: NewInfoClient(cfg), Metadata: NewMetadataClient(cfg), User: NewUserClient(cfg), }, nil @@ -98,6 +103,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) cfg.driver = &txDriver{tx: tx, drv: c.driver} return &Tx{ config: cfg, + Info: NewInfoClient(cfg), Metadata: NewMetadataClient(cfg), User: NewUserClient(cfg), }, nil @@ -106,7 +112,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) // Debug returns a new debug-client. It's used to get verbose logging on specific operations. // // client.Debug(). -// Metadata. +// Info. // Query(). // Count(ctx) // @@ -129,10 +135,115 @@ 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.Info.Use(hooks...) c.Metadata.Use(hooks...) c.User.Use(hooks...) } +// InfoClient is a client for the Info schema. +type InfoClient struct { + config +} + +// NewInfoClient returns a client for the Info from the given config. +func NewInfoClient(c config) *InfoClient { + return &InfoClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `info.Hooks(f(g(h())))`. +func (c *InfoClient) Use(hooks ...Hook) { + c.hooks.Info = append(c.hooks.Info, hooks...) +} + +// Create returns a create builder for Info. +func (c *InfoClient) Create() *InfoCreate { + mutation := newInfoMutation(c.config, OpCreate) + return &InfoCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Info entities. +func (c *InfoClient) CreateBulk(builders ...*InfoCreate) *InfoCreateBulk { + return &InfoCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Info. +func (c *InfoClient) Update() *InfoUpdate { + mutation := newInfoMutation(c.config, OpUpdate) + return &InfoUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *InfoClient) UpdateOne(i *Info) *InfoUpdateOne { + mutation := newInfoMutation(c.config, OpUpdateOne, withInfo(i)) + return &InfoUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *InfoClient) UpdateOneID(id int) *InfoUpdateOne { + mutation := newInfoMutation(c.config, OpUpdateOne, withInfoID(id)) + return &InfoUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Info. +func (c *InfoClient) Delete() *InfoDelete { + mutation := newInfoMutation(c.config, OpDelete) + return &InfoDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a delete builder for the given entity. +func (c *InfoClient) DeleteOne(i *Info) *InfoDeleteOne { + return c.DeleteOneID(i.ID) +} + +// DeleteOneID returns a delete builder for the given id. +func (c *InfoClient) DeleteOneID(id int) *InfoDeleteOne { + builder := c.Delete().Where(info.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &InfoDeleteOne{builder} +} + +// Query returns a query builder for Info. +func (c *InfoClient) Query() *InfoQuery { + return &InfoQuery{config: c.config} +} + +// Get returns a Info entity by its id. +func (c *InfoClient) Get(ctx context.Context, id int) (*Info, error) { + return c.Query().Where(info.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *InfoClient) GetX(ctx context.Context, id int) *Info { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryUser queries the user edge of a Info. +func (c *InfoClient) QueryUser(i *Info) *UserQuery { + query := &UserQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := i.ID + step := sqlgraph.NewStep( + sqlgraph.From(info.Table, info.FieldID, id), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, info.UserTable, info.UserColumn), + ) + fromV = sqlgraph.Neighbors(i.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *InfoClient) Hooks() []Hook { + return c.hooks.Info +} + // MetadataClient is a client for the Metadata schema. type MetadataClient struct { config @@ -336,6 +447,22 @@ func (c *UserClient) QueryMetadata(u *User) *MetadataQuery { return query } +// QueryInfo queries the info edge of a User. +func (c *UserClient) QueryInfo(u *User) *InfoQuery { + query := &InfoQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := u.ID + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, id), + sqlgraph.To(info.Table, info.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, user.InfoTable, user.InfoColumn), + ) + fromV = sqlgraph.Neighbors(u.driver.Dialect(), step) + return fromV, nil + } + return query +} + // Hooks returns the client hooks. func (c *UserClient) Hooks() []Hook { return c.hooks.User diff --git a/entc/integration/issue1288/ent/config.go b/entc/integration/issue1288/ent/config.go index 891af1727..e95db02f7 100644 --- a/entc/integration/issue1288/ent/config.go +++ b/entc/integration/issue1288/ent/config.go @@ -28,6 +28,7 @@ type config struct { // hooks per client, for fast access. type hooks struct { + Info []ent.Hook Metadata []ent.Hook User []ent.Hook } diff --git a/entc/integration/issue1288/ent/hook/hook.go b/entc/integration/issue1288/ent/hook/hook.go index 1e1a9156d..b423f6c55 100644 --- a/entc/integration/issue1288/ent/hook/hook.go +++ b/entc/integration/issue1288/ent/hook/hook.go @@ -13,6 +13,19 @@ import ( "entgo.io/ent/entc/integration/issue1288/ent" ) +// The InfoFunc type is an adapter to allow the use of ordinary +// function as Info mutator. +type InfoFunc func(context.Context, *ent.InfoMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f InfoFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + mv, ok := m.(*ent.InfoMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.InfoMutation", m) + } + return f(ctx, mv) +} + // The MetadataFunc type is an adapter to allow the use of ordinary // function as Metadata mutator. type MetadataFunc func(context.Context, *ent.MetadataMutation) (ent.Value, error) diff --git a/entc/integration/issue1288/ent/info.go b/entc/integration/issue1288/ent/info.go new file mode 100644 index 000000000..a527bb7fd --- /dev/null +++ b/entc/integration/issue1288/ent/info.go @@ -0,0 +1,139 @@ +// 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 entc, DO NOT EDIT. + +package ent + +import ( + "encoding/json" + "fmt" + "strings" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/entc/integration/issue1288/ent/info" + "entgo.io/ent/entc/integration/issue1288/ent/user" +) + +// Info is the model entity for the Info schema. +type Info struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // Content holds the value of the "content" field. + Content json.RawMessage `json:"content,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the InfoQuery when eager-loading is set. + Edges InfoEdges `json:"edges"` +} + +// InfoEdges holds the relations/edges for other nodes in the graph. +type InfoEdges struct { + // User holds the value of the user edge. + User *User `json:"user,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// UserOrErr returns the User value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e InfoEdges) UserOrErr() (*User, error) { + if e.loadedTypes[0] { + if e.User == nil { + // The edge user was loaded in eager-loading, + // but was not found. + return nil, &NotFoundError{label: user.Label} + } + return e.User, nil + } + return nil, &NotLoadedError{edge: "user"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Info) scanValues(columns []string) ([]interface{}, error) { + values := make([]interface{}, len(columns)) + for i := range columns { + switch columns[i] { + case info.FieldContent: + values[i] = &[]byte{} + case info.FieldID: + values[i] = &sql.NullInt64{} + default: + return nil, fmt.Errorf("unexpected column %q for type Info", columns[i]) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the Info fields. +func (i *Info) assignValues(columns []string, values []interface{}) error { + if m, n := len(values), len(columns); m < n { + return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) + } + for j := range columns { + switch columns[j] { + case info.FieldID: + value, ok := values[j].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + i.ID = int(value.Int64) + case info.FieldContent: + + if value, ok := values[j].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field content", values[j]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &i.Content); err != nil { + return fmt.Errorf("unmarshal field content: %v", err) + } + } + } + } + return nil +} + +// QueryUser queries the "user" edge of the Info entity. +func (i *Info) QueryUser() *UserQuery { + return (&InfoClient{config: i.config}).QueryUser(i) +} + +// Update returns a builder for updating this Info. +// Note that you need to call Info.Unwrap() before calling this method if this Info +// was returned from a transaction, and the transaction was committed or rolled back. +func (i *Info) Update() *InfoUpdateOne { + return (&InfoClient{config: i.config}).UpdateOne(i) +} + +// Unwrap unwraps the Info 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 (i *Info) Unwrap() *Info { + tx, ok := i.config.driver.(*txDriver) + if !ok { + panic("ent: Info is not a transactional entity") + } + i.config.driver = tx.drv + return i +} + +// String implements the fmt.Stringer. +func (i *Info) String() string { + var builder strings.Builder + builder.WriteString("Info(") + builder.WriteString(fmt.Sprintf("id=%v", i.ID)) + builder.WriteString(", content=") + builder.WriteString(fmt.Sprintf("%v", i.Content)) + builder.WriteByte(')') + return builder.String() +} + +// Infos is a parsable slice of Info. +type Infos []*Info + +func (i Infos) config(cfg config) { + for _i := range i { + i[_i].config = cfg + } +} diff --git a/entc/integration/issue1288/ent/info/info.go b/entc/integration/issue1288/ent/info/info.go new file mode 100644 index 000000000..50cff860a --- /dev/null +++ b/entc/integration/issue1288/ent/info/info.go @@ -0,0 +1,45 @@ +// 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 entc, DO NOT EDIT. + +package info + +const ( + // Label holds the string label denoting the info type in the database. + Label = "info" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldContent holds the string denoting the content field in the database. + FieldContent = "content" + + // EdgeUser holds the string denoting the user edge name in mutations. + EdgeUser = "user" + + // Table holds the table name of the info in the database. + Table = "infos" + // UserTable is the table the holds the user relation/edge. + UserTable = "infos" + // UserInverseTable is the table name for the User entity. + // It exists in this package in order to avoid circular dependency with the "user" package. + UserInverseTable = "users" + // UserColumn is the table column denoting the user relation/edge. + UserColumn = "id" +) + +// Columns holds all SQL columns for info fields. +var Columns = []string{ + FieldID, + FieldContent, +} + +// 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 +} diff --git a/entc/integration/issue1288/ent/info/where.go b/entc/integration/issue1288/ent/info/where.go new file mode 100644 index 000000000..d8bfeb887 --- /dev/null +++ b/entc/integration/issue1288/ent/info/where.go @@ -0,0 +1,156 @@ +// 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 entc, DO NOT EDIT. + +package info + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/issue1288/ent/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.Info { + return predicate.Info(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.Info { + return predicate.Info(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.Info { + return predicate.Info(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldID), id)) + }) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.Info { + return predicate.Info(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(ids) == 0 { + s.Where(sql.False()) + return + } + v := make([]interface{}, len(ids)) + for i := range v { + v[i] = ids[i] + } + s.Where(sql.In(s.C(FieldID), v...)) + }) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.Info { + return predicate.Info(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(ids) == 0 { + s.Where(sql.False()) + return + } + v := make([]interface{}, len(ids)) + for i := range v { + v[i] = ids[i] + } + s.Where(sql.NotIn(s.C(FieldID), v...)) + }) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.Info { + return predicate.Info(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldID), id)) + }) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.Info { + return predicate.Info(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldID), id)) + }) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.Info { + return predicate.Info(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldID), id)) + }) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.Info { + return predicate.Info(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldID), id)) + }) +} + +// HasUser applies the HasEdge predicate on the "user" edge. +func HasUser() predicate.Info { + return predicate.Info(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(UserTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, UserTable, UserColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasUserWith applies the HasEdge predicate on the "user" edge with a given conditions (other predicates). +func HasUserWith(preds ...predicate.User) predicate.Info { + return predicate.Info(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(UserInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, UserTable, UserColumn), + ) + 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.Info) predicate.Info { + return predicate.Info(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for _, p := range predicates { + p(s1) + } + s.Where(s1.P()) + }) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Info) predicate.Info { + return predicate.Info(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for i, p := range predicates { + if i > 0 { + s1.Or() + } + p(s1) + } + s.Where(s1.P()) + }) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Info) predicate.Info { + return predicate.Info(func(s *sql.Selector) { + p(s.Not()) + }) +} diff --git a/entc/integration/issue1288/ent/info_create.go b/entc/integration/issue1288/ent/info_create.go new file mode 100644 index 000000000..d75f9fb37 --- /dev/null +++ b/entc/integration/issue1288/ent/info_create.go @@ -0,0 +1,242 @@ +// 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 entc, DO NOT EDIT. + +package ent + +import ( + "context" + "encoding/json" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/issue1288/ent/info" + "entgo.io/ent/entc/integration/issue1288/ent/user" + "entgo.io/ent/schema/field" +) + +// InfoCreate is the builder for creating a Info entity. +type InfoCreate struct { + config + mutation *InfoMutation + hooks []Hook +} + +// SetContent sets the "content" field. +func (ic *InfoCreate) SetContent(jm json.RawMessage) *InfoCreate { + ic.mutation.SetContent(jm) + return ic +} + +// SetID sets the "id" field. +func (ic *InfoCreate) SetID(i int) *InfoCreate { + ic.mutation.SetID(i) + return ic +} + +// SetUserID sets the "user" edge to the User entity by ID. +func (ic *InfoCreate) SetUserID(id int) *InfoCreate { + ic.mutation.SetUserID(id) + return ic +} + +// SetNillableUserID sets the "user" edge to the User entity by ID if the given value is not nil. +func (ic *InfoCreate) SetNillableUserID(id *int) *InfoCreate { + if id != nil { + ic = ic.SetUserID(*id) + } + return ic +} + +// SetUser sets the "user" edge to the User entity. +func (ic *InfoCreate) SetUser(u *User) *InfoCreate { + return ic.SetUserID(u.ID) +} + +// Mutation returns the InfoMutation object of the builder. +func (ic *InfoCreate) Mutation() *InfoMutation { + return ic.mutation +} + +// Save creates the Info in the database. +func (ic *InfoCreate) Save(ctx context.Context) (*Info, error) { + var ( + err error + node *Info + ) + if len(ic.hooks) == 0 { + if err = ic.check(); err != nil { + return nil, err + } + node, err = ic.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*InfoMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = ic.check(); err != nil { + return nil, err + } + ic.mutation = mutation + node, err = ic.sqlSave(ctx) + mutation.done = true + return node, err + }) + for i := len(ic.hooks) - 1; i >= 0; i-- { + mut = ic.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, ic.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX calls Save and panics if Save returns an error. +func (ic *InfoCreate) SaveX(ctx context.Context) *Info { + v, err := ic.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// check runs all checks and user-defined validators on the builder. +func (ic *InfoCreate) check() error { + if _, ok := ic.mutation.Content(); !ok { + return &ValidationError{Name: "content", err: errors.New("ent: missing required field \"content\"")} + } + return nil +} + +func (ic *InfoCreate) sqlSave(ctx context.Context) (*Info, error) { + _node, _spec := ic.createSpec() + if err := sqlgraph.CreateNode(ctx, ic.driver, _spec); err != nil { + if cerr, ok := isSQLConstraintError(err); ok { + err = cerr + } + return nil, err + } + if _node.ID == 0 { + id := _spec.ID.Value.(int64) + _node.ID = int(id) + } + return _node, nil +} + +func (ic *InfoCreate) createSpec() (*Info, *sqlgraph.CreateSpec) { + var ( + _node = &Info{config: ic.config} + _spec = &sqlgraph.CreateSpec{ + Table: info.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: info.FieldID, + }, + } + ) + if id, ok := ic.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = id + } + if value, ok := ic.mutation.Content(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeJSON, + Value: value, + Column: info.FieldContent, + }) + _node.Content = value + } + if nodes := ic.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: info.UserTable, + Columns: []string{info.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// InfoCreateBulk is the builder for creating many Info entities in bulk. +type InfoCreateBulk struct { + config + builders []*InfoCreate +} + +// Save creates the Info entities in the database. +func (icb *InfoCreateBulk) Save(ctx context.Context) ([]*Info, error) { + specs := make([]*sqlgraph.CreateSpec, len(icb.builders)) + nodes := make([]*Info, len(icb.builders)) + mutators := make([]Mutator, len(icb.builders)) + for i := range icb.builders { + func(i int, root context.Context) { + builder := icb.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*InfoMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + nodes[i], specs[i] = builder.createSpec() + var err error + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, icb.builders[i+1].mutation) + } else { + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, icb.driver, &sqlgraph.BatchCreateSpec{Nodes: specs}); err != nil { + if cerr, ok := isSQLConstraintError(err); ok { + err = cerr + } + } + } + mutation.done = true + if err != nil { + return nil, err + } + if nodes[i].ID == 0 { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + 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, icb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (icb *InfoCreateBulk) SaveX(ctx context.Context) []*Info { + v, err := icb.Save(ctx) + if err != nil { + panic(err) + } + return v +} diff --git a/entc/integration/issue1288/ent/info_delete.go b/entc/integration/issue1288/ent/info_delete.go new file mode 100644 index 000000000..8f3916da9 --- /dev/null +++ b/entc/integration/issue1288/ent/info_delete.go @@ -0,0 +1,112 @@ +// 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 entc, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/issue1288/ent/info" + "entgo.io/ent/entc/integration/issue1288/ent/predicate" + "entgo.io/ent/schema/field" +) + +// InfoDelete is the builder for deleting a Info entity. +type InfoDelete struct { + config + hooks []Hook + mutation *InfoMutation +} + +// Where adds a new predicate to the InfoDelete builder. +func (id *InfoDelete) Where(ps ...predicate.Info) *InfoDelete { + id.mutation.predicates = append(id.mutation.predicates, ps...) + return id +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (id *InfoDelete) Exec(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(id.hooks) == 0 { + affected, err = id.sqlExec(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*InfoMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + id.mutation = mutation + affected, err = id.sqlExec(ctx) + mutation.done = true + return affected, err + }) + for i := len(id.hooks) - 1; i >= 0; i-- { + mut = id.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, id.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// ExecX is like Exec, but panics if an error occurs. +func (id *InfoDelete) ExecX(ctx context.Context) int { + n, err := id.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (id *InfoDelete) sqlExec(ctx context.Context) (int, error) { + _spec := &sqlgraph.DeleteSpec{ + Node: &sqlgraph.NodeSpec{ + Table: info.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: info.FieldID, + }, + }, + } + if ps := id.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return sqlgraph.DeleteNodes(ctx, id.driver, _spec) +} + +// InfoDeleteOne is the builder for deleting a single Info entity. +type InfoDeleteOne struct { + id *InfoDelete +} + +// Exec executes the deletion query. +func (ido *InfoDeleteOne) Exec(ctx context.Context) error { + n, err := ido.id.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{info.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (ido *InfoDeleteOne) ExecX(ctx context.Context) { + ido.id.ExecX(ctx) +} diff --git a/entc/integration/issue1288/ent/info_query.go b/entc/integration/issue1288/ent/info_query.go new file mode 100644 index 000000000..f456cb16a --- /dev/null +++ b/entc/integration/issue1288/ent/info_query.go @@ -0,0 +1,965 @@ +// 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 entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "math" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/issue1288/ent/info" + "entgo.io/ent/entc/integration/issue1288/ent/predicate" + "entgo.io/ent/entc/integration/issue1288/ent/user" + "entgo.io/ent/schema/field" +) + +// InfoQuery is the builder for querying Info entities. +type InfoQuery struct { + config + limit *int + offset *int + order []OrderFunc + fields []string + predicates []predicate.Info + // eager-loading edges. + withUser *UserQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the InfoQuery builder. +func (iq *InfoQuery) Where(ps ...predicate.Info) *InfoQuery { + iq.predicates = append(iq.predicates, ps...) + return iq +} + +// Limit adds a limit step to the query. +func (iq *InfoQuery) Limit(limit int) *InfoQuery { + iq.limit = &limit + return iq +} + +// Offset adds an offset step to the query. +func (iq *InfoQuery) Offset(offset int) *InfoQuery { + iq.offset = &offset + return iq +} + +// Order adds an order step to the query. +func (iq *InfoQuery) Order(o ...OrderFunc) *InfoQuery { + iq.order = append(iq.order, o...) + return iq +} + +// QueryUser chains the current query on the "user" edge. +func (iq *InfoQuery) QueryUser() *UserQuery { + query := &UserQuery{config: iq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := iq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := iq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(info.Table, info.FieldID, selector), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, info.UserTable, info.UserColumn), + ) + fromU = sqlgraph.SetNeighbors(iq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first Info entity from the query. +// Returns a *NotFoundError when no Info was found. +func (iq *InfoQuery) First(ctx context.Context) (*Info, error) { + nodes, err := iq.Limit(1).All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{info.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (iq *InfoQuery) FirstX(ctx context.Context) *Info { + node, err := iq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Info ID from the query. +// Returns a *NotFoundError when no Info ID was found. +func (iq *InfoQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = iq.Limit(1).IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{info.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (iq *InfoQuery) FirstIDX(ctx context.Context) int { + id, err := iq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Info entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when exactly one Info entity is not found. +// Returns a *NotFoundError when no Info entities are found. +func (iq *InfoQuery) Only(ctx context.Context) (*Info, error) { + nodes, err := iq.Limit(2).All(ctx) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{info.Label} + default: + return nil, &NotSingularError{info.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (iq *InfoQuery) OnlyX(ctx context.Context) *Info { + node, err := iq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Info ID in the query. +// Returns a *NotSingularError when exactly one Info ID is not found. +// Returns a *NotFoundError when no entities are found. +func (iq *InfoQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = iq.Limit(2).IDs(ctx); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{info.Label} + default: + err = &NotSingularError{info.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (iq *InfoQuery) OnlyIDX(ctx context.Context) int { + id, err := iq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Infos. +func (iq *InfoQuery) All(ctx context.Context) ([]*Info, error) { + if err := iq.prepareQuery(ctx); err != nil { + return nil, err + } + return iq.sqlAll(ctx) +} + +// AllX is like All, but panics if an error occurs. +func (iq *InfoQuery) AllX(ctx context.Context) []*Info { + nodes, err := iq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Info IDs. +func (iq *InfoQuery) IDs(ctx context.Context) ([]int, error) { + var ids []int + if err := iq.Select(info.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (iq *InfoQuery) IDsX(ctx context.Context) []int { + ids, err := iq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (iq *InfoQuery) Count(ctx context.Context) (int, error) { + if err := iq.prepareQuery(ctx); err != nil { + return 0, err + } + return iq.sqlCount(ctx) +} + +// CountX is like Count, but panics if an error occurs. +func (iq *InfoQuery) CountX(ctx context.Context) int { + count, err := iq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (iq *InfoQuery) Exist(ctx context.Context) (bool, error) { + if err := iq.prepareQuery(ctx); err != nil { + return false, err + } + return iq.sqlExist(ctx) +} + +// ExistX is like Exist, but panics if an error occurs. +func (iq *InfoQuery) ExistX(ctx context.Context) bool { + exist, err := iq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the InfoQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (iq *InfoQuery) Clone() *InfoQuery { + if iq == nil { + return nil + } + return &InfoQuery{ + config: iq.config, + limit: iq.limit, + offset: iq.offset, + order: append([]OrderFunc{}, iq.order...), + predicates: append([]predicate.Info{}, iq.predicates...), + withUser: iq.withUser.Clone(), + // clone intermediate query. + sql: iq.sql.Clone(), + path: iq.path, + } +} + +// WithUser tells the query-builder to eager-load the nodes that are connected to +// the "user" edge. The optional arguments are used to configure the query builder of the edge. +func (iq *InfoQuery) WithUser(opts ...func(*UserQuery)) *InfoQuery { + query := &UserQuery{config: iq.config} + for _, opt := range opts { + opt(query) + } + iq.withUser = query + return iq +} + +// 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 { +// Content json.RawMessage `json:"content,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Info.Query(). +// GroupBy(info.FieldContent). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +// +func (iq *InfoQuery) GroupBy(field string, fields ...string) *InfoGroupBy { + group := &InfoGroupBy{config: iq.config} + group.fields = append([]string{field}, fields...) + group.path = func(ctx context.Context) (prev *sql.Selector, err error) { + if err := iq.prepareQuery(ctx); err != nil { + return nil, err + } + return iq.sqlQuery(ctx), nil + } + return group +} + +// 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 { +// Content json.RawMessage `json:"content,omitempty"` +// } +// +// client.Info.Query(). +// Select(info.FieldContent). +// Scan(ctx, &v) +// +func (iq *InfoQuery) Select(field string, fields ...string) *InfoSelect { + iq.fields = append([]string{field}, fields...) + return &InfoSelect{InfoQuery: iq} +} + +func (iq *InfoQuery) prepareQuery(ctx context.Context) error { + for _, f := range iq.fields { + if !info.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if iq.path != nil { + prev, err := iq.path(ctx) + if err != nil { + return err + } + iq.sql = prev + } + return nil +} + +func (iq *InfoQuery) sqlAll(ctx context.Context) ([]*Info, error) { + var ( + nodes = []*Info{} + _spec = iq.querySpec() + loadedTypes = [1]bool{ + iq.withUser != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]interface{}, error) { + node := &Info{config: iq.config} + nodes = append(nodes, node) + return node.scanValues(columns) + } + _spec.Assign = func(columns []string, values []interface{}) error { + if len(nodes) == 0 { + return fmt.Errorf("ent: Assign called without calling ScanValues") + } + node := nodes[len(nodes)-1] + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if err := sqlgraph.QueryNodes(ctx, iq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + + if query := iq.withUser; query != nil { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*Info) + for i := range nodes { + fk := nodes[i].ID + ids = append(ids, fk) + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + query.Where(user.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return nil, fmt.Errorf(`unexpected foreign-key "id" returned %v`, n.ID) + } + for i := range nodes { + nodes[i].Edges.User = n + } + } + } + + return nodes, nil +} + +func (iq *InfoQuery) sqlCount(ctx context.Context) (int, error) { + _spec := iq.querySpec() + return sqlgraph.CountNodes(ctx, iq.driver, _spec) +} + +func (iq *InfoQuery) sqlExist(ctx context.Context) (bool, error) { + n, err := iq.sqlCount(ctx) + if err != nil { + return false, fmt.Errorf("ent: check existence: %v", err) + } + return n > 0, nil +} + +func (iq *InfoQuery) querySpec() *sqlgraph.QuerySpec { + _spec := &sqlgraph.QuerySpec{ + Node: &sqlgraph.NodeSpec{ + Table: info.Table, + Columns: info.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: info.FieldID, + }, + }, + From: iq.sql, + Unique: true, + } + if fields := iq.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, info.FieldID) + for i := range fields { + if fields[i] != info.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := iq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := iq.limit; limit != nil { + _spec.Limit = *limit + } + if offset := iq.offset; offset != nil { + _spec.Offset = *offset + } + if ps := iq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector, info.ValidColumn) + } + } + } + return _spec +} + +func (iq *InfoQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(iq.driver.Dialect()) + t1 := builder.Table(info.Table) + selector := builder.Select(t1.Columns(info.Columns...)...).From(t1) + if iq.sql != nil { + selector = iq.sql + selector.Select(selector.Columns(info.Columns...)...) + } + for _, p := range iq.predicates { + p(selector) + } + for _, p := range iq.order { + p(selector, info.ValidColumn) + } + if offset := iq.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 := iq.limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// InfoGroupBy is the group-by builder for Info entities. +type InfoGroupBy struct { + config + fields []string + fns []AggregateFunc + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (igb *InfoGroupBy) Aggregate(fns ...AggregateFunc) *InfoGroupBy { + igb.fns = append(igb.fns, fns...) + return igb +} + +// Scan applies the group-by query and scans the result into the given value. +func (igb *InfoGroupBy) Scan(ctx context.Context, v interface{}) error { + query, err := igb.path(ctx) + if err != nil { + return err + } + igb.sql = query + return igb.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (igb *InfoGroupBy) ScanX(ctx context.Context, v interface{}) { + if err := igb.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from group-by. +// It is only allowed when executing a group-by query with one field. +func (igb *InfoGroupBy) Strings(ctx context.Context) ([]string, error) { + if len(igb.fields) > 1 { + return nil, errors.New("ent: InfoGroupBy.Strings is not achievable when grouping more than 1 field") + } + var v []string + if err := igb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (igb *InfoGroupBy) StringsX(ctx context.Context) []string { + v, err := igb.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (igb *InfoGroupBy) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = igb.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{info.Label} + default: + err = fmt.Errorf("ent: InfoGroupBy.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (igb *InfoGroupBy) StringX(ctx context.Context) string { + v, err := igb.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from group-by. +// It is only allowed when executing a group-by query with one field. +func (igb *InfoGroupBy) Ints(ctx context.Context) ([]int, error) { + if len(igb.fields) > 1 { + return nil, errors.New("ent: InfoGroupBy.Ints is not achievable when grouping more than 1 field") + } + var v []int + if err := igb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (igb *InfoGroupBy) IntsX(ctx context.Context) []int { + v, err := igb.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (igb *InfoGroupBy) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = igb.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{info.Label} + default: + err = fmt.Errorf("ent: InfoGroupBy.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (igb *InfoGroupBy) IntX(ctx context.Context) int { + v, err := igb.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from group-by. +// It is only allowed when executing a group-by query with one field. +func (igb *InfoGroupBy) Float64s(ctx context.Context) ([]float64, error) { + if len(igb.fields) > 1 { + return nil, errors.New("ent: InfoGroupBy.Float64s is not achievable when grouping more than 1 field") + } + var v []float64 + if err := igb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (igb *InfoGroupBy) Float64sX(ctx context.Context) []float64 { + v, err := igb.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (igb *InfoGroupBy) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = igb.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{info.Label} + default: + err = fmt.Errorf("ent: InfoGroupBy.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (igb *InfoGroupBy) Float64X(ctx context.Context) float64 { + v, err := igb.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from group-by. +// It is only allowed when executing a group-by query with one field. +func (igb *InfoGroupBy) Bools(ctx context.Context) ([]bool, error) { + if len(igb.fields) > 1 { + return nil, errors.New("ent: InfoGroupBy.Bools is not achievable when grouping more than 1 field") + } + var v []bool + if err := igb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (igb *InfoGroupBy) BoolsX(ctx context.Context) []bool { + v, err := igb.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (igb *InfoGroupBy) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = igb.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{info.Label} + default: + err = fmt.Errorf("ent: InfoGroupBy.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (igb *InfoGroupBy) BoolX(ctx context.Context) bool { + v, err := igb.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (igb *InfoGroupBy) sqlScan(ctx context.Context, v interface{}) error { + for _, f := range igb.fields { + if !info.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + } + } + selector := igb.sqlQuery() + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := igb.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +func (igb *InfoGroupBy) sqlQuery() *sql.Selector { + selector := igb.sql + columns := make([]string, 0, len(igb.fields)+len(igb.fns)) + columns = append(columns, igb.fields...) + for _, fn := range igb.fns { + columns = append(columns, fn(selector, info.ValidColumn)) + } + return selector.Select(columns...).GroupBy(igb.fields...) +} + +// InfoSelect is the builder for selecting fields of Info entities. +type InfoSelect struct { + *InfoQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector +} + +// Scan applies the selector query and scans the result into the given value. +func (is *InfoSelect) Scan(ctx context.Context, v interface{}) error { + if err := is.prepareQuery(ctx); err != nil { + return err + } + is.sql = is.InfoQuery.sqlQuery(ctx) + return is.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (is *InfoSelect) ScanX(ctx context.Context, v interface{}) { + if err := is.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from a selector. It is only allowed when selecting one field. +func (is *InfoSelect) Strings(ctx context.Context) ([]string, error) { + if len(is.fields) > 1 { + return nil, errors.New("ent: InfoSelect.Strings is not achievable when selecting more than 1 field") + } + var v []string + if err := is.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (is *InfoSelect) StringsX(ctx context.Context) []string { + v, err := is.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a selector. It is only allowed when selecting one field. +func (is *InfoSelect) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = is.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{info.Label} + default: + err = fmt.Errorf("ent: InfoSelect.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (is *InfoSelect) StringX(ctx context.Context) string { + v, err := is.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from a selector. It is only allowed when selecting one field. +func (is *InfoSelect) Ints(ctx context.Context) ([]int, error) { + if len(is.fields) > 1 { + return nil, errors.New("ent: InfoSelect.Ints is not achievable when selecting more than 1 field") + } + var v []int + if err := is.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (is *InfoSelect) IntsX(ctx context.Context) []int { + v, err := is.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a selector. It is only allowed when selecting one field. +func (is *InfoSelect) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = is.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{info.Label} + default: + err = fmt.Errorf("ent: InfoSelect.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (is *InfoSelect) IntX(ctx context.Context) int { + v, err := is.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. +func (is *InfoSelect) Float64s(ctx context.Context) ([]float64, error) { + if len(is.fields) > 1 { + return nil, errors.New("ent: InfoSelect.Float64s is not achievable when selecting more than 1 field") + } + var v []float64 + if err := is.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (is *InfoSelect) Float64sX(ctx context.Context) []float64 { + v, err := is.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. +func (is *InfoSelect) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = is.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{info.Label} + default: + err = fmt.Errorf("ent: InfoSelect.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (is *InfoSelect) Float64X(ctx context.Context) float64 { + v, err := is.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from a selector. It is only allowed when selecting one field. +func (is *InfoSelect) Bools(ctx context.Context) ([]bool, error) { + if len(is.fields) > 1 { + return nil, errors.New("ent: InfoSelect.Bools is not achievable when selecting more than 1 field") + } + var v []bool + if err := is.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (is *InfoSelect) BoolsX(ctx context.Context) []bool { + v, err := is.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a selector. It is only allowed when selecting one field. +func (is *InfoSelect) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = is.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{info.Label} + default: + err = fmt.Errorf("ent: InfoSelect.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (is *InfoSelect) BoolX(ctx context.Context) bool { + v, err := is.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (is *InfoSelect) sqlScan(ctx context.Context, v interface{}) error { + rows := &sql.Rows{} + query, args := is.sqlQuery().Query() + if err := is.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +func (is *InfoSelect) sqlQuery() sql.Querier { + selector := is.sql + selector.Select(selector.Columns(is.fields...)...) + return selector +} diff --git a/entc/integration/issue1288/ent/info_update.go b/entc/integration/issue1288/ent/info_update.go new file mode 100644 index 000000000..3b996d47a --- /dev/null +++ b/entc/integration/issue1288/ent/info_update.go @@ -0,0 +1,364 @@ +// 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 entc, DO NOT EDIT. + +package ent + +import ( + "context" + "encoding/json" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/issue1288/ent/info" + "entgo.io/ent/entc/integration/issue1288/ent/predicate" + "entgo.io/ent/entc/integration/issue1288/ent/user" + "entgo.io/ent/schema/field" +) + +// InfoUpdate is the builder for updating Info entities. +type InfoUpdate struct { + config + hooks []Hook + mutation *InfoMutation +} + +// Where adds a new predicate for the InfoUpdate builder. +func (iu *InfoUpdate) Where(ps ...predicate.Info) *InfoUpdate { + iu.mutation.predicates = append(iu.mutation.predicates, ps...) + return iu +} + +// SetContent sets the "content" field. +func (iu *InfoUpdate) SetContent(jm json.RawMessage) *InfoUpdate { + iu.mutation.SetContent(jm) + return iu +} + +// SetUserID sets the "user" edge to the User entity by ID. +func (iu *InfoUpdate) SetUserID(id int) *InfoUpdate { + iu.mutation.SetUserID(id) + return iu +} + +// SetNillableUserID sets the "user" edge to the User entity by ID if the given value is not nil. +func (iu *InfoUpdate) SetNillableUserID(id *int) *InfoUpdate { + if id != nil { + iu = iu.SetUserID(*id) + } + return iu +} + +// SetUser sets the "user" edge to the User entity. +func (iu *InfoUpdate) SetUser(u *User) *InfoUpdate { + return iu.SetUserID(u.ID) +} + +// Mutation returns the InfoMutation object of the builder. +func (iu *InfoUpdate) Mutation() *InfoMutation { + return iu.mutation +} + +// ClearUser clears the "user" edge to the User entity. +func (iu *InfoUpdate) ClearUser() *InfoUpdate { + iu.mutation.ClearUser() + return iu +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (iu *InfoUpdate) Save(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(iu.hooks) == 0 { + affected, err = iu.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*InfoMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + iu.mutation = mutation + affected, err = iu.sqlSave(ctx) + mutation.done = true + return affected, err + }) + for i := len(iu.hooks) - 1; i >= 0; i-- { + mut = iu.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, iu.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// SaveX is like Save, but panics if an error occurs. +func (iu *InfoUpdate) SaveX(ctx context.Context) int { + affected, err := iu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (iu *InfoUpdate) Exec(ctx context.Context) error { + _, err := iu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (iu *InfoUpdate) ExecX(ctx context.Context) { + if err := iu.Exec(ctx); err != nil { + panic(err) + } +} + +func (iu *InfoUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: info.Table, + Columns: info.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: info.FieldID, + }, + }, + } + if ps := iu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := iu.mutation.Content(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeJSON, + Value: value, + Column: info.FieldContent, + }) + } + if iu.mutation.UserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: info.UserTable, + Columns: []string{info.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := iu.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: info.UserTable, + Columns: []string{info.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if n, err = sqlgraph.UpdateNodes(ctx, iu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{info.Label} + } else if cerr, ok := isSQLConstraintError(err); ok { + err = cerr + } + return 0, err + } + return n, nil +} + +// InfoUpdateOne is the builder for updating a single Info entity. +type InfoUpdateOne struct { + config + hooks []Hook + mutation *InfoMutation +} + +// SetContent sets the "content" field. +func (iuo *InfoUpdateOne) SetContent(jm json.RawMessage) *InfoUpdateOne { + iuo.mutation.SetContent(jm) + return iuo +} + +// SetUserID sets the "user" edge to the User entity by ID. +func (iuo *InfoUpdateOne) SetUserID(id int) *InfoUpdateOne { + iuo.mutation.SetUserID(id) + return iuo +} + +// SetNillableUserID sets the "user" edge to the User entity by ID if the given value is not nil. +func (iuo *InfoUpdateOne) SetNillableUserID(id *int) *InfoUpdateOne { + if id != nil { + iuo = iuo.SetUserID(*id) + } + return iuo +} + +// SetUser sets the "user" edge to the User entity. +func (iuo *InfoUpdateOne) SetUser(u *User) *InfoUpdateOne { + return iuo.SetUserID(u.ID) +} + +// Mutation returns the InfoMutation object of the builder. +func (iuo *InfoUpdateOne) Mutation() *InfoMutation { + return iuo.mutation +} + +// ClearUser clears the "user" edge to the User entity. +func (iuo *InfoUpdateOne) ClearUser() *InfoUpdateOne { + iuo.mutation.ClearUser() + return iuo +} + +// Save executes the query and returns the updated Info entity. +func (iuo *InfoUpdateOne) Save(ctx context.Context) (*Info, error) { + var ( + err error + node *Info + ) + if len(iuo.hooks) == 0 { + node, err = iuo.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*InfoMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + iuo.mutation = mutation + node, err = iuo.sqlSave(ctx) + mutation.done = true + return node, err + }) + for i := len(iuo.hooks) - 1; i >= 0; i-- { + mut = iuo.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, iuo.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX is like Save, but panics if an error occurs. +func (iuo *InfoUpdateOne) SaveX(ctx context.Context) *Info { + node, err := iuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (iuo *InfoUpdateOne) Exec(ctx context.Context) error { + _, err := iuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (iuo *InfoUpdateOne) ExecX(ctx context.Context) { + if err := iuo.Exec(ctx); err != nil { + panic(err) + } +} + +func (iuo *InfoUpdateOne) sqlSave(ctx context.Context) (_node *Info, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: info.Table, + Columns: info.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: info.FieldID, + }, + }, + } + id, ok := iuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing Info.ID for update")} + } + _spec.Node.ID.Value = id + if ps := iuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := iuo.mutation.Content(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeJSON, + Value: value, + Column: info.FieldContent, + }) + } + if iuo.mutation.UserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: info.UserTable, + Columns: []string{info.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := iuo.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: info.UserTable, + Columns: []string{info.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &Info{config: iuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, iuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{info.Label} + } else if cerr, ok := isSQLConstraintError(err); ok { + err = cerr + } + return nil, err + } + return _node, nil +} diff --git a/entc/integration/issue1288/ent/migrate/schema.go b/entc/integration/issue1288/ent/migrate/schema.go index 2d53717cc..8dfbfe931 100644 --- a/entc/integration/issue1288/ent/migrate/schema.go +++ b/entc/integration/issue1288/ent/migrate/schema.go @@ -12,6 +12,25 @@ import ( ) var ( + // InfosColumns holds the columns for the "infos" table. + InfosColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "content", Type: field.TypeJSON}, + } + // InfosTable holds the schema information for the "infos" table. + InfosTable = &schema.Table{ + Name: "infos", + Columns: InfosColumns, + PrimaryKey: []*schema.Column{InfosColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "infos_users_user", + Columns: []*schema.Column{InfosColumns[0]}, + RefColumns: []*schema.Column{UsersColumns[0]}, + OnDelete: schema.SetNull, + }, + }, + } // MetadataColumns holds the columns for the "metadata" table. MetadataColumns = []*schema.Column{ {Name: "id", Type: field.TypeInt, Increment: true}, @@ -45,11 +64,13 @@ var ( } // Tables holds all the tables in the schema. Tables = []*schema.Table{ + InfosTable, MetadataTable, UsersTable, } ) func init() { + InfosTable.ForeignKeys[0].RefTable = UsersTable MetadataTable.ForeignKeys[0].RefTable = UsersTable } diff --git a/entc/integration/issue1288/ent/mutation.go b/entc/integration/issue1288/ent/mutation.go index 8ca784ca2..3103b1966 100644 --- a/entc/integration/issue1288/ent/mutation.go +++ b/entc/integration/issue1288/ent/mutation.go @@ -8,9 +8,11 @@ package ent import ( "context" + "encoding/json" "fmt" "sync" + "entgo.io/ent/entc/integration/issue1288/ent/info" "entgo.io/ent/entc/integration/issue1288/ent/metadata" "entgo.io/ent/entc/integration/issue1288/ent/predicate" "entgo.io/ent/entc/integration/issue1288/ent/user" @@ -27,10 +29,373 @@ const ( OpUpdateOne = ent.OpUpdateOne // Node types. + TypeInfo = "Info" TypeMetadata = "Metadata" TypeUser = "User" ) +// InfoMutation represents an operation that mutates the Info nodes in the graph. +type InfoMutation struct { + config + op Op + typ string + id *int + content *json.RawMessage + clearedFields map[string]struct{} + user *int + cleareduser bool + done bool + oldValue func(context.Context) (*Info, error) + predicates []predicate.Info +} + +var _ ent.Mutation = (*InfoMutation)(nil) + +// infoOption allows management of the mutation configuration using functional options. +type infoOption func(*InfoMutation) + +// newInfoMutation creates new mutation for the Info entity. +func newInfoMutation(c config, op Op, opts ...infoOption) *InfoMutation { + m := &InfoMutation{ + config: c, + op: op, + typ: TypeInfo, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withInfoID sets the ID field of the mutation. +func withInfoID(id int) infoOption { + return func(m *InfoMutation) { + var ( + err error + once sync.Once + value *Info + ) + m.oldValue = func(ctx context.Context) (*Info, error) { + once.Do(func() { + if m.done { + err = fmt.Errorf("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Info.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withInfo sets the old Info of the mutation. +func withInfo(node *Info) infoOption { + return func(m *InfoMutation) { + m.oldValue = func(context.Context) (*Info, 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 InfoMutation) 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 InfoMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, fmt.Errorf("ent: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of Info entities. +func (m *InfoMutation) SetID(id int) { + m.id = &id +} + +// ID returns the ID value in the mutation. Note that the ID +// is only available if it was provided to the builder. +func (m *InfoMutation) ID() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// SetContent sets the "content" field. +func (m *InfoMutation) SetContent(jm json.RawMessage) { + m.content = &jm +} + +// Content returns the value of the "content" field in the mutation. +func (m *InfoMutation) Content() (r json.RawMessage, exists bool) { + v := m.content + if v == nil { + return + } + return *v, true +} + +// OldContent returns the old "content" field's value of the Info entity. +// If the Info object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *InfoMutation) OldContent(ctx context.Context) (v json.RawMessage, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldContent is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldContent requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldContent: %w", err) + } + return oldValue.Content, nil +} + +// ResetContent resets all changes to the "content" field. +func (m *InfoMutation) ResetContent() { + m.content = nil +} + +// SetUserID sets the "user" edge to the User entity by id. +func (m *InfoMutation) SetUserID(id int) { + m.user = &id +} + +// ClearUser clears the "user" edge to the User entity. +func (m *InfoMutation) ClearUser() { + m.cleareduser = true +} + +// UserCleared returns if the "user" edge to the User entity was cleared. +func (m *InfoMutation) UserCleared() bool { + return m.cleareduser +} + +// UserID returns the "user" edge ID in the mutation. +func (m *InfoMutation) UserID() (id int, exists bool) { + if m.user != nil { + return *m.user, true + } + return +} + +// UserIDs returns the "user" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// UserID instead. It exists only for internal usage by the builders. +func (m *InfoMutation) UserIDs() (ids []int) { + if id := m.user; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetUser resets all changes to the "user" edge. +func (m *InfoMutation) ResetUser() { + m.user = nil + m.cleareduser = false +} + +// Op returns the operation name. +func (m *InfoMutation) Op() Op { + return m.op +} + +// Type returns the node type of this mutation (Info). +func (m *InfoMutation) 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 *InfoMutation) Fields() []string { + fields := make([]string, 0, 1) + if m.content != nil { + fields = append(fields, info.FieldContent) + } + 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 *InfoMutation) Field(name string) (ent.Value, bool) { + switch name { + case info.FieldContent: + return m.Content() + } + 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 *InfoMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case info.FieldContent: + return m.OldContent(ctx) + } + return nil, fmt.Errorf("unknown Info 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 *InfoMutation) SetField(name string, value ent.Value) error { + switch name { + case info.FieldContent: + v, ok := value.(json.RawMessage) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetContent(v) + return nil + } + return fmt.Errorf("unknown Info field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *InfoMutation) AddedFields() []string { + return nil +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *InfoMutation) AddedField(name string) (ent.Value, bool) { + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *InfoMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown Info numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *InfoMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *InfoMutation) 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 *InfoMutation) ClearField(name string) error { + return fmt.Errorf("unknown Info 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 *InfoMutation) ResetField(name string) error { + switch name { + case info.FieldContent: + m.ResetContent() + return nil + } + return fmt.Errorf("unknown Info field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *InfoMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.user != nil { + edges = append(edges, info.EdgeUser) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *InfoMutation) AddedIDs(name string) []ent.Value { + switch name { + case info.EdgeUser: + if id := m.user; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *InfoMutation) RemovedEdges() []string { + edges := make([]string, 0, 1) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *InfoMutation) RemovedIDs(name string) []ent.Value { + switch name { + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *InfoMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.cleareduser { + edges = append(edges, info.EdgeUser) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *InfoMutation) EdgeCleared(name string) bool { + switch name { + case info.EdgeUser: + return m.cleareduser + } + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *InfoMutation) ClearEdge(name string) error { + switch name { + case info.EdgeUser: + m.ClearUser() + return nil + } + return fmt.Errorf("unknown Info 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 *InfoMutation) ResetEdge(name string) error { + switch name { + case info.EdgeUser: + m.ResetUser() + return nil + } + return fmt.Errorf("unknown Info edge %s", name) +} + // MetadataMutation represents an operation that mutates the Metadata nodes in the graph. type MetadataMutation struct { config @@ -439,6 +804,9 @@ type UserMutation struct { clearedFields map[string]struct{} metadata *int clearedmetadata bool + info map[int]struct{} + removedinfo map[int]struct{} + clearedinfo bool done bool oldValue func(context.Context) (*User, error) predicates []predicate.User @@ -604,6 +972,59 @@ func (m *UserMutation) ResetMetadata() { m.clearedmetadata = false } +// AddInfoIDs adds the "info" edge to the Info entity by ids. +func (m *UserMutation) AddInfoIDs(ids ...int) { + if m.info == nil { + m.info = make(map[int]struct{}) + } + for i := range ids { + m.info[ids[i]] = struct{}{} + } +} + +// ClearInfo clears the "info" edge to the Info entity. +func (m *UserMutation) ClearInfo() { + m.clearedinfo = true +} + +// InfoCleared returns if the "info" edge to the Info entity was cleared. +func (m *UserMutation) InfoCleared() bool { + return m.clearedinfo +} + +// RemoveInfoIDs removes the "info" edge to the Info entity by IDs. +func (m *UserMutation) RemoveInfoIDs(ids ...int) { + if m.removedinfo == nil { + m.removedinfo = make(map[int]struct{}) + } + for i := range ids { + m.removedinfo[ids[i]] = struct{}{} + } +} + +// RemovedInfo returns the removed IDs of the "info" edge to the Info entity. +func (m *UserMutation) RemovedInfoIDs() (ids []int) { + for id := range m.removedinfo { + ids = append(ids, id) + } + return +} + +// InfoIDs returns the "info" edge IDs in the mutation. +func (m *UserMutation) InfoIDs() (ids []int) { + for id := range m.info { + ids = append(ids, id) + } + return +} + +// ResetInfo resets all changes to the "info" edge. +func (m *UserMutation) ResetInfo() { + m.info = nil + m.clearedinfo = false + m.removedinfo = nil +} + // Op returns the operation name. func (m *UserMutation) Op() Op { return m.op @@ -717,10 +1138,13 @@ 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, 1) + edges := make([]string, 0, 2) if m.metadata != nil { edges = append(edges, user.EdgeMetadata) } + if m.info != nil { + edges = append(edges, user.EdgeInfo) + } return edges } @@ -732,13 +1156,22 @@ func (m *UserMutation) AddedIDs(name string) []ent.Value { if id := m.metadata; id != nil { return []ent.Value{*id} } + case user.EdgeInfo: + ids := make([]ent.Value, 0, len(m.info)) + for id := range m.info { + 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, 1) + edges := make([]string, 0, 2) + if m.removedinfo != nil { + edges = append(edges, user.EdgeInfo) + } return edges } @@ -746,16 +1179,25 @@ func (m *UserMutation) RemovedEdges() []string { // the given name in this mutation. func (m *UserMutation) RemovedIDs(name string) []ent.Value { switch name { + case user.EdgeInfo: + ids := make([]ent.Value, 0, len(m.removedinfo)) + for id := range m.removedinfo { + 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, 1) + edges := make([]string, 0, 2) if m.clearedmetadata { edges = append(edges, user.EdgeMetadata) } + if m.clearedinfo { + edges = append(edges, user.EdgeInfo) + } return edges } @@ -765,6 +1207,8 @@ func (m *UserMutation) EdgeCleared(name string) bool { switch name { case user.EdgeMetadata: return m.clearedmetadata + case user.EdgeInfo: + return m.clearedinfo } return false } @@ -787,6 +1231,9 @@ func (m *UserMutation) ResetEdge(name string) error { case user.EdgeMetadata: m.ResetMetadata() return nil + case user.EdgeInfo: + m.ResetInfo() + return nil } return fmt.Errorf("unknown User edge %s", name) } diff --git a/entc/integration/issue1288/ent/predicate/predicate.go b/entc/integration/issue1288/ent/predicate/predicate.go index d00cbde88..45dc17d3e 100644 --- a/entc/integration/issue1288/ent/predicate/predicate.go +++ b/entc/integration/issue1288/ent/predicate/predicate.go @@ -10,6 +10,9 @@ import ( "entgo.io/ent/dialect/sql" ) +// Info is the predicate function for info builders. +type Info func(*sql.Selector) + // Metadata is the predicate function for metadata builders. type Metadata func(*sql.Selector) diff --git a/entc/integration/issue1288/ent/schema/info.go b/entc/integration/issue1288/ent/schema/info.go new file mode 100644 index 000000000..1526d1122 --- /dev/null +++ b/entc/integration/issue1288/ent/schema/info.go @@ -0,0 +1,32 @@ +// 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 ( + "encoding/json" + + "entgo.io/ent" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" +) + +// Info holds the schema definition for the Info entity. +type Info struct { + ent.Schema +} + +func (Info) Fields() []ent.Field { + return []ent.Field{ + field.Int("id"), + field.JSON("content", json.RawMessage{}), + } +} +func (Info) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("user", User.Type). + Unique(). + StorageKey(edge.Column("id")), + } +} diff --git a/entc/integration/issue1288/ent/schema/user.go b/entc/integration/issue1288/ent/schema/user.go index df404a36a..c4119e9dd 100644 --- a/entc/integration/issue1288/ent/schema/user.go +++ b/entc/integration/issue1288/ent/schema/user.go @@ -26,5 +26,7 @@ func (User) Edges() []ent.Edge { edge.To("metadata", Metadata.Type). Unique(). StorageKey(edge.Column("id")), + edge.From("info", Info.Type). + Ref("user"), } } diff --git a/entc/integration/issue1288/ent/tx.go b/entc/integration/issue1288/ent/tx.go index 16cf82c44..c20ea0cb7 100644 --- a/entc/integration/issue1288/ent/tx.go +++ b/entc/integration/issue1288/ent/tx.go @@ -16,6 +16,8 @@ import ( // Tx is a transactional client that is created by calling Client.Tx(). type Tx struct { config + // Info is the client for interacting with the Info builders. + Info *InfoClient // Metadata is the client for interacting with the Metadata builders. Metadata *MetadataClient // User is the client for interacting with the User builders. @@ -155,6 +157,7 @@ func (tx *Tx) Client() *Client { } func (tx *Tx) init() { + tx.Info = NewInfoClient(tx.config) tx.Metadata = NewMetadataClient(tx.config) tx.User = NewUserClient(tx.config) } @@ -166,7 +169,7 @@ func (tx *Tx) init() { // of them in order to commit or rollback the transaction. // // If a closed transaction is embedded in one of the generated entities, and the entity -// applies a query, for example: Metadata.QueryXXX(), the query will be executed +// applies a query, for example: Info.QueryXXX(), the query will be executed // through the driver which created this transaction. // // Note that txDriver is not goroutine safe. diff --git a/entc/integration/issue1288/ent/user.go b/entc/integration/issue1288/ent/user.go index 3bd5c3ee4..d50987fb6 100644 --- a/entc/integration/issue1288/ent/user.go +++ b/entc/integration/issue1288/ent/user.go @@ -31,9 +31,11 @@ type User struct { type UserEdges struct { // Metadata holds the value of the metadata edge. Metadata *Metadata `json:"metadata,omitempty"` + // Info holds the value of the info edge. + Info []*Info `json:"info,omitempty"` // loadedTypes holds the information for reporting if a // type was loaded (or requested) in eager-loading or not. - loadedTypes [1]bool + loadedTypes [2]bool } // MetadataOrErr returns the Metadata value or an error if the edge @@ -50,6 +52,15 @@ func (e UserEdges) MetadataOrErr() (*Metadata, error) { return nil, &NotLoadedError{edge: "metadata"} } +// InfoOrErr returns the Info value or an error if the edge +// was not loaded in eager-loading. +func (e UserEdges) InfoOrErr() ([]*Info, error) { + if e.loadedTypes[1] { + return e.Info, nil + } + return nil, &NotLoadedError{edge: "info"} +} + // scanValues returns the types for scanning values from sql.Rows. func (*User) scanValues(columns []string) ([]interface{}, error) { values := make([]interface{}, len(columns)) @@ -96,6 +107,11 @@ func (u *User) QueryMetadata() *MetadataQuery { return (&UserClient{config: u.config}).QueryMetadata(u) } +// QueryInfo queries the "info" edge of the User entity. +func (u *User) QueryInfo() *InfoQuery { + return (&UserClient{config: u.config}).QueryInfo(u) +} + // Update returns a builder for updating this User. // Note that you need to call User.Unwrap() before calling this method if this User // was returned from a transaction, and the transaction was committed or rolled back. diff --git a/entc/integration/issue1288/ent/user/user.go b/entc/integration/issue1288/ent/user/user.go index fa4c64c87..b9916cbca 100644 --- a/entc/integration/issue1288/ent/user/user.go +++ b/entc/integration/issue1288/ent/user/user.go @@ -16,6 +16,8 @@ const ( // EdgeMetadata holds the string denoting the metadata edge name in mutations. EdgeMetadata = "metadata" + // EdgeInfo holds the string denoting the info edge name in mutations. + EdgeInfo = "info" // Table holds the table name of the user in the database. Table = "users" @@ -26,6 +28,13 @@ const ( MetadataInverseTable = "metadata" // MetadataColumn is the table column denoting the metadata relation/edge. MetadataColumn = "id" + // InfoTable is the table the holds the info relation/edge. + InfoTable = "infos" + // InfoInverseTable is the table name for the Info entity. + // It exists in this package in order to avoid circular dependency with the "info" package. + InfoInverseTable = "infos" + // InfoColumn is the table column denoting the info relation/edge. + InfoColumn = "id" ) // Columns holds all SQL columns for user fields. diff --git a/entc/integration/issue1288/ent/user/where.go b/entc/integration/issue1288/ent/user/where.go index 6627b26b1..bf2d37ca5 100644 --- a/entc/integration/issue1288/ent/user/where.go +++ b/entc/integration/issue1288/ent/user/where.go @@ -241,6 +241,34 @@ func HasMetadataWith(preds ...predicate.Metadata) predicate.User { }) } +// HasInfo applies the HasEdge predicate on the "info" edge. +func HasInfo() predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(InfoTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, InfoTable, InfoColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasInfoWith applies the HasEdge predicate on the "info" edge with a given conditions (other predicates). +func HasInfoWith(preds ...predicate.Info) predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(InfoInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, InfoTable, InfoColumn), + ) + 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(func(s *sql.Selector) { diff --git a/entc/integration/issue1288/ent/user_create.go b/entc/integration/issue1288/ent/user_create.go index 7fca4b276..2c0a4724c 100644 --- a/entc/integration/issue1288/ent/user_create.go +++ b/entc/integration/issue1288/ent/user_create.go @@ -12,6 +12,7 @@ import ( "fmt" "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/issue1288/ent/info" "entgo.io/ent/entc/integration/issue1288/ent/metadata" "entgo.io/ent/entc/integration/issue1288/ent/user" "entgo.io/ent/schema/field" @@ -55,6 +56,21 @@ func (uc *UserCreate) SetMetadata(m *Metadata) *UserCreate { return uc.SetMetadataID(m.ID) } +// AddInfoIDs adds the "info" edge to the Info entity by IDs. +func (uc *UserCreate) AddInfoIDs(ids ...int) *UserCreate { + uc.mutation.AddInfoIDs(ids...) + return uc +} + +// AddInfo adds the "info" edges to the Info entity. +func (uc *UserCreate) AddInfo(i ...*Info) *UserCreate { + ids := make([]int, len(i)) + for j := range i { + ids[j] = i[j].ID + } + return uc.AddInfoIDs(ids...) +} + // Mutation returns the UserMutation object of the builder. func (uc *UserCreate) Mutation() *UserMutation { return uc.mutation @@ -169,6 +185,25 @@ func (uc *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) { } _spec.Edges = append(_spec.Edges, edge) } + if nodes := uc.mutation.InfoIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.InfoTable, + Columns: []string{user.InfoColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: info.FieldID, + }, + }, + } + 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/issue1288/ent/user_query.go b/entc/integration/issue1288/ent/user_query.go index a67ee0b79..140a40fc6 100644 --- a/entc/integration/issue1288/ent/user_query.go +++ b/entc/integration/issue1288/ent/user_query.go @@ -15,6 +15,7 @@ import ( "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/issue1288/ent/info" "entgo.io/ent/entc/integration/issue1288/ent/metadata" "entgo.io/ent/entc/integration/issue1288/ent/predicate" "entgo.io/ent/entc/integration/issue1288/ent/user" @@ -31,6 +32,7 @@ type UserQuery struct { predicates []predicate.User // eager-loading edges. withMetadata *MetadataQuery + withInfo *InfoQuery // intermediate query (i.e. traversal path). sql *sql.Selector path func(context.Context) (*sql.Selector, error) @@ -82,6 +84,28 @@ func (uq *UserQuery) QueryMetadata() *MetadataQuery { return query } +// QueryInfo chains the current query on the "info" edge. +func (uq *UserQuery) QueryInfo() *InfoQuery { + query := &InfoQuery{config: uq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := uq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := uq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, selector), + sqlgraph.To(info.Table, info.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, user.InfoTable, user.InfoColumn), + ) + fromU = sqlgraph.SetNeighbors(uq.driver.Dialect(), step) + return fromU, nil + } + return query +} + // First returns the first User entity from the query. // Returns a *NotFoundError when no User was found. func (uq *UserQuery) First(ctx context.Context) (*User, error) { @@ -264,6 +288,7 @@ func (uq *UserQuery) Clone() *UserQuery { order: append([]OrderFunc{}, uq.order...), predicates: append([]predicate.User{}, uq.predicates...), withMetadata: uq.withMetadata.Clone(), + withInfo: uq.withInfo.Clone(), // clone intermediate query. sql: uq.sql.Clone(), path: uq.path, @@ -281,6 +306,17 @@ func (uq *UserQuery) WithMetadata(opts ...func(*MetadataQuery)) *UserQuery { return uq } +// WithInfo tells the query-builder to eager-load the nodes that are connected to +// the "info" edge. The optional arguments are used to configure the query builder of the edge. +func (uq *UserQuery) WithInfo(opts ...func(*InfoQuery)) *UserQuery { + query := &InfoQuery{config: uq.config} + for _, opt := range opts { + opt(query) + } + uq.withInfo = query + return uq +} + // GroupBy is used to group vertices by one or more fields/columns. // It is often used with aggregate functions, like: count, max, mean, min, sum. // @@ -346,8 +382,9 @@ func (uq *UserQuery) sqlAll(ctx context.Context) ([]*User, error) { var ( nodes = []*User{} _spec = uq.querySpec() - loadedTypes = [1]bool{ + loadedTypes = [2]bool{ uq.withMetadata != nil, + uq.withInfo != nil, } ) _spec.ScanValues = func(columns []string) ([]interface{}, error) { @@ -394,6 +431,31 @@ func (uq *UserQuery) sqlAll(ctx context.Context) ([]*User, error) { } } + if query := uq.withInfo; query != nil { + 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] + nodes[i].Edges.Info = []*Info{} + } + query.Where(predicate.Info(func(s *sql.Selector) { + s.Where(sql.InValues(user.InfoColumn, fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, n := range neighbors { + fk := n.ID + node, ok := nodeids[fk] + if !ok { + return nil, fmt.Errorf(`unexpected foreign-key "id" returned %v for node %v`, fk, n.ID) + } + node.Edges.Info = append(node.Edges.Info, n) + } + } + return nodes, nil } diff --git a/entc/integration/issue1288/ent/user_update.go b/entc/integration/issue1288/ent/user_update.go index 63a3d18d9..11d58252e 100644 --- a/entc/integration/issue1288/ent/user_update.go +++ b/entc/integration/issue1288/ent/user_update.go @@ -12,6 +12,7 @@ import ( "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/issue1288/ent/info" "entgo.io/ent/entc/integration/issue1288/ent/metadata" "entgo.io/ent/entc/integration/issue1288/ent/predicate" "entgo.io/ent/entc/integration/issue1288/ent/user" @@ -56,6 +57,21 @@ func (uu *UserUpdate) SetMetadata(m *Metadata) *UserUpdate { return uu.SetMetadataID(m.ID) } +// AddInfoIDs adds the "info" edge to the Info entity by IDs. +func (uu *UserUpdate) AddInfoIDs(ids ...int) *UserUpdate { + uu.mutation.AddInfoIDs(ids...) + return uu +} + +// AddInfo adds the "info" edges to the Info entity. +func (uu *UserUpdate) AddInfo(i ...*Info) *UserUpdate { + ids := make([]int, len(i)) + for j := range i { + ids[j] = i[j].ID + } + return uu.AddInfoIDs(ids...) +} + // Mutation returns the UserMutation object of the builder. func (uu *UserUpdate) Mutation() *UserMutation { return uu.mutation @@ -67,6 +83,27 @@ func (uu *UserUpdate) ClearMetadata() *UserUpdate { return uu } +// ClearInfo clears all "info" edges to the Info entity. +func (uu *UserUpdate) ClearInfo() *UserUpdate { + uu.mutation.ClearInfo() + return uu +} + +// RemoveInfoIDs removes the "info" edge to Info entities by IDs. +func (uu *UserUpdate) RemoveInfoIDs(ids ...int) *UserUpdate { + uu.mutation.RemoveInfoIDs(ids...) + return uu +} + +// RemoveInfo removes "info" edges to Info entities. +func (uu *UserUpdate) RemoveInfo(i ...*Info) *UserUpdate { + ids := make([]int, len(i)) + for j := range i { + ids[j] = i[j].ID + } + return uu.RemoveInfoIDs(ids...) +} + // Save executes the query and returns the number of nodes affected by the update operation. func (uu *UserUpdate) Save(ctx context.Context) (int, error) { var ( @@ -178,6 +215,60 @@ func (uu *UserUpdate) sqlSave(ctx context.Context) (n int, err error) { } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if uu.mutation.InfoCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.InfoTable, + Columns: []string{user.InfoColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: info.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uu.mutation.RemovedInfoIDs(); len(nodes) > 0 && !uu.mutation.InfoCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.InfoTable, + Columns: []string{user.InfoColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: info.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uu.mutation.InfoIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.InfoTable, + Columns: []string{user.InfoColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: info.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } if n, err = sqlgraph.UpdateNodes(ctx, uu.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{user.Label} @@ -221,6 +312,21 @@ func (uuo *UserUpdateOne) SetMetadata(m *Metadata) *UserUpdateOne { return uuo.SetMetadataID(m.ID) } +// AddInfoIDs adds the "info" edge to the Info entity by IDs. +func (uuo *UserUpdateOne) AddInfoIDs(ids ...int) *UserUpdateOne { + uuo.mutation.AddInfoIDs(ids...) + return uuo +} + +// AddInfo adds the "info" edges to the Info entity. +func (uuo *UserUpdateOne) AddInfo(i ...*Info) *UserUpdateOne { + ids := make([]int, len(i)) + for j := range i { + ids[j] = i[j].ID + } + return uuo.AddInfoIDs(ids...) +} + // Mutation returns the UserMutation object of the builder. func (uuo *UserUpdateOne) Mutation() *UserMutation { return uuo.mutation @@ -232,6 +338,27 @@ func (uuo *UserUpdateOne) ClearMetadata() *UserUpdateOne { return uuo } +// ClearInfo clears all "info" edges to the Info entity. +func (uuo *UserUpdateOne) ClearInfo() *UserUpdateOne { + uuo.mutation.ClearInfo() + return uuo +} + +// RemoveInfoIDs removes the "info" edge to Info entities by IDs. +func (uuo *UserUpdateOne) RemoveInfoIDs(ids ...int) *UserUpdateOne { + uuo.mutation.RemoveInfoIDs(ids...) + return uuo +} + +// RemoveInfo removes "info" edges to Info entities. +func (uuo *UserUpdateOne) RemoveInfo(i ...*Info) *UserUpdateOne { + ids := make([]int, len(i)) + for j := range i { + ids[j] = i[j].ID + } + return uuo.RemoveInfoIDs(ids...) +} + // Save executes the query and returns the updated User entity. func (uuo *UserUpdateOne) Save(ctx context.Context) (*User, error) { var ( @@ -348,6 +475,60 @@ func (uuo *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if uuo.mutation.InfoCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.InfoTable, + Columns: []string{user.InfoColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: info.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uuo.mutation.RemovedInfoIDs(); len(nodes) > 0 && !uuo.mutation.InfoCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.InfoTable, + Columns: []string{user.InfoColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: info.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uuo.mutation.InfoIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.InfoTable, + Columns: []string{user.InfoColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: info.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } _node = &User{config: uuo.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues diff --git a/entc/integration/issue1288/issue_test.go b/entc/integration/issue1288/issue_test.go index 726aeeadb..eb242b5b6 100644 --- a/entc/integration/issue1288/issue_test.go +++ b/entc/integration/issue1288/issue_test.go @@ -6,6 +6,7 @@ package issue1288 import ( "context" + "encoding/json" "testing" "entgo.io/ent/entc/integration/issue1288/ent" @@ -26,4 +27,9 @@ func TestSchemaConfig(t *testing.T) { require.Equal(t, a8m.ID, m1.ID) _, err = client.Metadata.Create().SetID(a8m.ID).SetAge(10).Save(ctx) require.True(t, ent.IsConstraintError(err), "UNIQUE constraint failed: metadata.id") + client.Info.Create().SetUser(a8m).SetContent(json.RawMessage("{}")).SaveX(ctx) + inf := a8m.QueryInfo().OnlyX(ctx) + require.Equal(t, a8m.ID, inf.ID) + _, err = client.Info.Create().SetID(a8m.ID).SetContent(json.RawMessage("10")).Save(ctx) + require.True(t, ent.IsConstraintError(err), "UNIQUE constraint failed: metadata.id") }