From 6e3637703675aa954e42d4a8866ea2f1befa79d3 Mon Sep 17 00:00:00 2001 From: Ariel Mashraki Date: Mon, 26 Sep 2022 21:05:10 +0300 Subject: [PATCH] dialect/sql/schema: use serial underlying types for fks --- dialect/sql/schema/postgres.go | 3 + entc/integration/migrate/entv2/blog.go | 117 ++++ entc/integration/migrate/entv2/blog/blog.go | 42 ++ entc/integration/migrate/entv2/blog/where.go | 144 +++++ entc/integration/migrate/entv2/blog_create.go | 259 ++++++++ entc/integration/migrate/entv2/blog_delete.go | 119 ++++ entc/integration/migrate/entv2/blog_query.go | 591 ++++++++++++++++++ entc/integration/migrate/entv2/blog_update.go | 430 +++++++++++++ entc/integration/migrate/entv2/client.go | 115 +++- entc/integration/migrate/entv2/config.go | 1 + entc/integration/migrate/entv2/ent.go | 2 + entc/integration/migrate/entv2/hook/hook.go | 13 + .../migrate/entv2/migrate/schema.go | 21 + entc/integration/migrate/entv2/mutation.go | 350 +++++++++++ .../migrate/entv2/predicate/predicate.go | 3 + entc/integration/migrate/entv2/schema/user.go | 26 +- entc/integration/migrate/entv2/tx.go | 5 +- entc/integration/migrate/entv2/user.go | 12 +- entc/integration/migrate/entv2/user/user.go | 11 + entc/integration/migrate/entv2/user_query.go | 5 + entc/integration/migrate/migrate_test.go | 56 +- 21 files changed, 2302 insertions(+), 23 deletions(-) create mode 100644 entc/integration/migrate/entv2/blog.go create mode 100644 entc/integration/migrate/entv2/blog/blog.go create mode 100644 entc/integration/migrate/entv2/blog/where.go create mode 100644 entc/integration/migrate/entv2/blog_create.go create mode 100644 entc/integration/migrate/entv2/blog_delete.go create mode 100644 entc/integration/migrate/entv2/blog_query.go create mode 100644 entc/integration/migrate/entv2/blog_update.go diff --git a/dialect/sql/schema/postgres.go b/dialect/sql/schema/postgres.go index ea68272b76..140b3f5a3b 100644 --- a/dialect/sql/schema/postgres.go +++ b/dialect/sql/schema/postgres.go @@ -690,6 +690,9 @@ func (d *Postgres) atTypeC(c1 *Column, c2 *schema.Column) error { return err } c2.Type.Type = t + if s, ok := t.(*postgres.SerialType); c1.foreign != nil && ok { + c2.Type.Type = s.IntegerType() + } return nil } var t schema.Type diff --git a/entc/integration/migrate/entv2/blog.go b/entc/integration/migrate/entv2/blog.go new file mode 100644 index 0000000000..8aeac8f5f6 --- /dev/null +++ b/entc/integration/migrate/entv2/blog.go @@ -0,0 +1,117 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package entv2 + +import ( + "fmt" + "strings" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/entc/integration/migrate/entv2/blog" +) + +// Blog is the model entity for the Blog schema. +type Blog struct { + config + // ID of the ent. + ID int `json:"id,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the BlogQuery when eager-loading is set. + Edges BlogEdges `json:"edges"` +} + +// BlogEdges holds the relations/edges for other nodes in the graph. +type BlogEdges struct { + // Admins holds the value of the admins edge. + Admins []*User `json:"admins,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// AdminsOrErr returns the Admins value or an error if the edge +// was not loaded in eager-loading. +func (e BlogEdges) AdminsOrErr() ([]*User, error) { + if e.loadedTypes[0] { + return e.Admins, nil + } + return nil, &NotLoadedError{edge: "admins"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Blog) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case blog.FieldID: + values[i] = new(sql.NullInt64) + default: + return nil, fmt.Errorf("unexpected column %q for type Blog", columns[i]) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the Blog fields. +func (b *Blog) assignValues(columns []string, values []any) error { + if m, n := len(values), len(columns); m < n { + return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) + } + for i := range columns { + switch columns[i] { + case blog.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + b.ID = int(value.Int64) + } + } + return nil +} + +// QueryAdmins queries the "admins" edge of the Blog entity. +func (b *Blog) QueryAdmins() *UserQuery { + return (&BlogClient{config: b.config}).QueryAdmins(b) +} + +// Update returns a builder for updating this Blog. +// Note that you need to call Blog.Unwrap() before calling this method if this Blog +// was returned from a transaction, and the transaction was committed or rolled back. +func (b *Blog) Update() *BlogUpdateOne { + return (&BlogClient{config: b.config}).UpdateOne(b) +} + +// Unwrap unwraps the Blog 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 (b *Blog) Unwrap() *Blog { + _tx, ok := b.config.driver.(*txDriver) + if !ok { + panic("entv2: Blog is not a transactional entity") + } + b.config.driver = _tx.drv + return b +} + +// String implements the fmt.Stringer. +func (b *Blog) String() string { + var builder strings.Builder + builder.WriteString("Blog(") + builder.WriteString(fmt.Sprintf("id=%v", b.ID)) + builder.WriteByte(')') + return builder.String() +} + +// Blogs is a parsable slice of Blog. +type Blogs []*Blog + +func (b Blogs) config(cfg config) { + for _i := range b { + b[_i].config = cfg + } +} diff --git a/entc/integration/migrate/entv2/blog/blog.go b/entc/integration/migrate/entv2/blog/blog.go new file mode 100644 index 0000000000..5d4302ee31 --- /dev/null +++ b/entc/integration/migrate/entv2/blog/blog.go @@ -0,0 +1,42 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package blog + +const ( + // Label holds the string label denoting the blog type in the database. + Label = "blog" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // EdgeAdmins holds the string denoting the admins edge name in mutations. + EdgeAdmins = "admins" + // UserFieldID holds the string denoting the ID field of the User. + UserFieldID = "oid" + // Table holds the table name of the blog in the database. + Table = "blogs" + // AdminsTable is the table that holds the admins relation/edge. + AdminsTable = "users" + // AdminsInverseTable is the table name for the User entity. + // It exists in this package in order to avoid circular dependency with the "user" package. + AdminsInverseTable = "users" + // AdminsColumn is the table column denoting the admins relation/edge. + AdminsColumn = "blog_admins" +) + +// Columns holds all SQL columns for blog fields. +var Columns = []string{ + FieldID, +} + +// 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/migrate/entv2/blog/where.go b/entc/integration/migrate/entv2/blog/where.go new file mode 100644 index 0000000000..5ffe94d794 --- /dev/null +++ b/entc/integration/migrate/entv2/blog/where.go @@ -0,0 +1,144 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package blog + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/migrate/entv2/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.Blog { + return predicate.Blog(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.Blog { + return predicate.Blog(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.Blog { + return predicate.Blog(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.Blog { + return predicate.Blog(func(s *sql.Selector) { + v := make([]any, 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.Blog { + return predicate.Blog(func(s *sql.Selector) { + v := make([]any, 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.Blog { + return predicate.Blog(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.Blog { + return predicate.Blog(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.Blog { + return predicate.Blog(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.Blog { + return predicate.Blog(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldID), id)) + }) +} + +// HasAdmins applies the HasEdge predicate on the "admins" edge. +func HasAdmins() predicate.Blog { + return predicate.Blog(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(AdminsTable, UserFieldID), + sqlgraph.Edge(sqlgraph.O2M, false, AdminsTable, AdminsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasAdminsWith applies the HasEdge predicate on the "admins" edge with a given conditions (other predicates). +func HasAdminsWith(preds ...predicate.User) predicate.Blog { + return predicate.Blog(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(AdminsInverseTable, UserFieldID), + sqlgraph.Edge(sqlgraph.O2M, false, AdminsTable, AdminsColumn), + ) + 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.Blog) predicate.Blog { + return predicate.Blog(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.Blog) predicate.Blog { + return predicate.Blog(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.Blog) predicate.Blog { + return predicate.Blog(func(s *sql.Selector) { + p(s.Not()) + }) +} diff --git a/entc/integration/migrate/entv2/blog_create.go b/entc/integration/migrate/entv2/blog_create.go new file mode 100644 index 0000000000..2d27580421 --- /dev/null +++ b/entc/integration/migrate/entv2/blog_create.go @@ -0,0 +1,259 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package entv2 + +import ( + "context" + "fmt" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/migrate/entv2/blog" + "entgo.io/ent/entc/integration/migrate/entv2/user" + "entgo.io/ent/schema/field" +) + +// BlogCreate is the builder for creating a Blog entity. +type BlogCreate struct { + config + mutation *BlogMutation + hooks []Hook +} + +// SetID sets the "id" field. +func (bc *BlogCreate) SetID(i int) *BlogCreate { + bc.mutation.SetID(i) + return bc +} + +// AddAdminIDs adds the "admins" edge to the User entity by IDs. +func (bc *BlogCreate) AddAdminIDs(ids ...int) *BlogCreate { + bc.mutation.AddAdminIDs(ids...) + return bc +} + +// AddAdmins adds the "admins" edges to the User entity. +func (bc *BlogCreate) AddAdmins(u ...*User) *BlogCreate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return bc.AddAdminIDs(ids...) +} + +// Mutation returns the BlogMutation object of the builder. +func (bc *BlogCreate) Mutation() *BlogMutation { + return bc.mutation +} + +// Save creates the Blog in the database. +func (bc *BlogCreate) Save(ctx context.Context) (*Blog, error) { + var ( + err error + node *Blog + ) + if len(bc.hooks) == 0 { + if err = bc.check(); err != nil { + return nil, err + } + node, err = bc.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*BlogMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = bc.check(); err != nil { + return nil, err + } + bc.mutation = mutation + if node, err = bc.sqlSave(ctx); err != nil { + return nil, err + } + mutation.id = &node.ID + mutation.done = true + return node, err + }) + for i := len(bc.hooks) - 1; i >= 0; i-- { + if bc.hooks[i] == nil { + return nil, fmt.Errorf("entv2: uninitialized hook (forgotten import entv2/runtime?)") + } + mut = bc.hooks[i](mut) + } + v, err := mut.Mutate(ctx, bc.mutation) + if err != nil { + return nil, err + } + nv, ok := v.(*Blog) + if !ok { + return nil, fmt.Errorf("unexpected node type %T returned from BlogMutation", v) + } + node = nv + } + return node, err +} + +// SaveX calls Save and panics if Save returns an error. +func (bc *BlogCreate) SaveX(ctx context.Context) *Blog { + v, err := bc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (bc *BlogCreate) Exec(ctx context.Context) error { + _, err := bc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (bc *BlogCreate) ExecX(ctx context.Context) { + if err := bc.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (bc *BlogCreate) check() error { + return nil +} + +func (bc *BlogCreate) sqlSave(ctx context.Context) (*Blog, error) { + _node, _spec := bc.createSpec() + if err := sqlgraph.CreateNode(ctx, bc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + if _spec.ID.Value != _node.ID { + id := _spec.ID.Value.(int64) + _node.ID = int(id) + } + return _node, nil +} + +func (bc *BlogCreate) createSpec() (*Blog, *sqlgraph.CreateSpec) { + var ( + _node = &Blog{config: bc.config} + _spec = &sqlgraph.CreateSpec{ + Table: blog.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: blog.FieldID, + }, + } + ) + if id, ok := bc.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = id + } + if nodes := bc.mutation.AdminsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: blog.AdminsTable, + Columns: []string{blog.AdminsColumn}, + 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 +} + +// BlogCreateBulk is the builder for creating many Blog entities in bulk. +type BlogCreateBulk struct { + config + builders []*BlogCreate +} + +// Save creates the Blog entities in the database. +func (bcb *BlogCreateBulk) Save(ctx context.Context) ([]*Blog, error) { + specs := make([]*sqlgraph.CreateSpec, len(bcb.builders)) + nodes := make([]*Blog, len(bcb.builders)) + mutators := make([]Mutator, len(bcb.builders)) + for i := range bcb.builders { + func(i int, root context.Context) { + builder := bcb.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*BlogMutation) + 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, bcb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, bcb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + if specs[i].ID.Value != nil && nodes[i].ID == 0 { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, bcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (bcb *BlogCreateBulk) SaveX(ctx context.Context) []*Blog { + v, err := bcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (bcb *BlogCreateBulk) Exec(ctx context.Context) error { + _, err := bcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (bcb *BlogCreateBulk) ExecX(ctx context.Context) { + if err := bcb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entc/integration/migrate/entv2/blog_delete.go b/entc/integration/migrate/entv2/blog_delete.go new file mode 100644 index 0000000000..fa81ed58ee --- /dev/null +++ b/entc/integration/migrate/entv2/blog_delete.go @@ -0,0 +1,119 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package entv2 + +import ( + "context" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/migrate/entv2/blog" + "entgo.io/ent/entc/integration/migrate/entv2/predicate" + "entgo.io/ent/schema/field" +) + +// BlogDelete is the builder for deleting a Blog entity. +type BlogDelete struct { + config + hooks []Hook + mutation *BlogMutation +} + +// Where appends a list predicates to the BlogDelete builder. +func (bd *BlogDelete) Where(ps ...predicate.Blog) *BlogDelete { + bd.mutation.Where(ps...) + return bd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (bd *BlogDelete) Exec(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(bd.hooks) == 0 { + affected, err = bd.sqlExec(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*BlogMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + bd.mutation = mutation + affected, err = bd.sqlExec(ctx) + mutation.done = true + return affected, err + }) + for i := len(bd.hooks) - 1; i >= 0; i-- { + if bd.hooks[i] == nil { + return 0, fmt.Errorf("entv2: uninitialized hook (forgotten import entv2/runtime?)") + } + mut = bd.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, bd.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// ExecX is like Exec, but panics if an error occurs. +func (bd *BlogDelete) ExecX(ctx context.Context) int { + n, err := bd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (bd *BlogDelete) sqlExec(ctx context.Context) (int, error) { + _spec := &sqlgraph.DeleteSpec{ + Node: &sqlgraph.NodeSpec{ + Table: blog.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: blog.FieldID, + }, + }, + } + if ps := bd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, bd.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return affected, err +} + +// BlogDeleteOne is the builder for deleting a single Blog entity. +type BlogDeleteOne struct { + bd *BlogDelete +} + +// Exec executes the deletion query. +func (bdo *BlogDeleteOne) Exec(ctx context.Context) error { + n, err := bdo.bd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{blog.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (bdo *BlogDeleteOne) ExecX(ctx context.Context) { + bdo.bd.ExecX(ctx) +} diff --git a/entc/integration/migrate/entv2/blog_query.go b/entc/integration/migrate/entv2/blog_query.go new file mode 100644 index 0000000000..8643ecde41 --- /dev/null +++ b/entc/integration/migrate/entv2/blog_query.go @@ -0,0 +1,591 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package entv2 + +import ( + "context" + "database/sql/driver" + "fmt" + "math" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/migrate/entv2/blog" + "entgo.io/ent/entc/integration/migrate/entv2/predicate" + "entgo.io/ent/entc/integration/migrate/entv2/user" + "entgo.io/ent/schema/field" +) + +// BlogQuery is the builder for querying Blog entities. +type BlogQuery struct { + config + limit *int + offset *int + unique *bool + order []OrderFunc + fields []string + predicates []predicate.Blog + withAdmins *UserQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the BlogQuery builder. +func (bq *BlogQuery) Where(ps ...predicate.Blog) *BlogQuery { + bq.predicates = append(bq.predicates, ps...) + return bq +} + +// Limit adds a limit step to the query. +func (bq *BlogQuery) Limit(limit int) *BlogQuery { + bq.limit = &limit + return bq +} + +// Offset adds an offset step to the query. +func (bq *BlogQuery) Offset(offset int) *BlogQuery { + bq.offset = &offset + return bq +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (bq *BlogQuery) Unique(unique bool) *BlogQuery { + bq.unique = &unique + return bq +} + +// Order adds an order step to the query. +func (bq *BlogQuery) Order(o ...OrderFunc) *BlogQuery { + bq.order = append(bq.order, o...) + return bq +} + +// QueryAdmins chains the current query on the "admins" edge. +func (bq *BlogQuery) QueryAdmins() *UserQuery { + query := &UserQuery{config: bq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := bq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := bq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(blog.Table, blog.FieldID, selector), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, blog.AdminsTable, blog.AdminsColumn), + ) + fromU = sqlgraph.SetNeighbors(bq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first Blog entity from the query. +// Returns a *NotFoundError when no Blog was found. +func (bq *BlogQuery) First(ctx context.Context) (*Blog, error) { + nodes, err := bq.Limit(1).All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{blog.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (bq *BlogQuery) FirstX(ctx context.Context) *Blog { + node, err := bq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Blog ID from the query. +// Returns a *NotFoundError when no Blog ID was found. +func (bq *BlogQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = bq.Limit(1).IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{blog.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (bq *BlogQuery) FirstIDX(ctx context.Context) int { + id, err := bq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Blog entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Blog entity is found. +// Returns a *NotFoundError when no Blog entities are found. +func (bq *BlogQuery) Only(ctx context.Context) (*Blog, error) { + nodes, err := bq.Limit(2).All(ctx) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{blog.Label} + default: + return nil, &NotSingularError{blog.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (bq *BlogQuery) OnlyX(ctx context.Context) *Blog { + node, err := bq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Blog ID in the query. +// Returns a *NotSingularError when more than one Blog ID is found. +// Returns a *NotFoundError when no entities are found. +func (bq *BlogQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = bq.Limit(2).IDs(ctx); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{blog.Label} + default: + err = &NotSingularError{blog.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (bq *BlogQuery) OnlyIDX(ctx context.Context) int { + id, err := bq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Blogs. +func (bq *BlogQuery) All(ctx context.Context) ([]*Blog, error) { + if err := bq.prepareQuery(ctx); err != nil { + return nil, err + } + return bq.sqlAll(ctx) +} + +// AllX is like All, but panics if an error occurs. +func (bq *BlogQuery) AllX(ctx context.Context) []*Blog { + nodes, err := bq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Blog IDs. +func (bq *BlogQuery) IDs(ctx context.Context) ([]int, error) { + var ids []int + if err := bq.Select(blog.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (bq *BlogQuery) IDsX(ctx context.Context) []int { + ids, err := bq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (bq *BlogQuery) Count(ctx context.Context) (int, error) { + if err := bq.prepareQuery(ctx); err != nil { + return 0, err + } + return bq.sqlCount(ctx) +} + +// CountX is like Count, but panics if an error occurs. +func (bq *BlogQuery) CountX(ctx context.Context) int { + count, err := bq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (bq *BlogQuery) Exist(ctx context.Context) (bool, error) { + if err := bq.prepareQuery(ctx); err != nil { + return false, err + } + return bq.sqlExist(ctx) +} + +// ExistX is like Exist, but panics if an error occurs. +func (bq *BlogQuery) ExistX(ctx context.Context) bool { + exist, err := bq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the BlogQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (bq *BlogQuery) Clone() *BlogQuery { + if bq == nil { + return nil + } + return &BlogQuery{ + config: bq.config, + limit: bq.limit, + offset: bq.offset, + order: append([]OrderFunc{}, bq.order...), + predicates: append([]predicate.Blog{}, bq.predicates...), + withAdmins: bq.withAdmins.Clone(), + // clone intermediate query. + sql: bq.sql.Clone(), + path: bq.path, + unique: bq.unique, + } +} + +// WithAdmins tells the query-builder to eager-load the nodes that are connected to +// the "admins" edge. The optional arguments are used to configure the query builder of the edge. +func (bq *BlogQuery) WithAdmins(opts ...func(*UserQuery)) *BlogQuery { + query := &UserQuery{config: bq.config} + for _, opt := range opts { + opt(query) + } + bq.withAdmins = query + return bq +} + +// 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. +func (bq *BlogQuery) GroupBy(field string, fields ...string) *BlogGroupBy { + grbuild := &BlogGroupBy{config: bq.config} + grbuild.fields = append([]string{field}, fields...) + grbuild.path = func(ctx context.Context) (prev *sql.Selector, err error) { + if err := bq.prepareQuery(ctx); err != nil { + return nil, err + } + return bq.sqlQuery(ctx), nil + } + grbuild.label = blog.Label + grbuild.flds, grbuild.scan = &grbuild.fields, grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +func (bq *BlogQuery) Select(fields ...string) *BlogSelect { + bq.fields = append(bq.fields, fields...) + selbuild := &BlogSelect{BlogQuery: bq} + selbuild.label = blog.Label + selbuild.flds, selbuild.scan = &bq.fields, selbuild.Scan + return selbuild +} + +func (bq *BlogQuery) prepareQuery(ctx context.Context) error { + for _, f := range bq.fields { + if !blog.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("entv2: invalid field %q for query", f)} + } + } + if bq.path != nil { + prev, err := bq.path(ctx) + if err != nil { + return err + } + bq.sql = prev + } + return nil +} + +func (bq *BlogQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Blog, error) { + var ( + nodes = []*Blog{} + _spec = bq.querySpec() + loadedTypes = [1]bool{ + bq.withAdmins != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Blog).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Blog{config: bq.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, bq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := bq.withAdmins; query != nil { + if err := bq.loadAdmins(ctx, query, nodes, + func(n *Blog) { n.Edges.Admins = []*User{} }, + func(n *Blog, e *User) { n.Edges.Admins = append(n.Edges.Admins, e) }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (bq *BlogQuery) loadAdmins(ctx context.Context, query *UserQuery, nodes []*Blog, init func(*Blog), assign func(*Blog, *User)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int]*Blog) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) + } + } + query.withFKs = true + query.Where(predicate.User(func(s *sql.Selector) { + s.Where(sql.InValues(blog.AdminsColumn, fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.blog_admins + if fk == nil { + return fmt.Errorf(`foreign-key "blog_admins" is nil for node %v`, n.ID) + } + node, ok := nodeids[*fk] + if !ok { + return fmt.Errorf(`unexpected foreign-key "blog_admins" returned %v for node %v`, *fk, n.ID) + } + assign(node, n) + } + return nil +} + +func (bq *BlogQuery) sqlCount(ctx context.Context) (int, error) { + _spec := bq.querySpec() + _spec.Node.Columns = bq.fields + if len(bq.fields) > 0 { + _spec.Unique = bq.unique != nil && *bq.unique + } + return sqlgraph.CountNodes(ctx, bq.driver, _spec) +} + +func (bq *BlogQuery) sqlExist(ctx context.Context) (bool, error) { + switch _, err := bq.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("entv2: check existence: %w", err) + default: + return true, nil + } +} + +func (bq *BlogQuery) querySpec() *sqlgraph.QuerySpec { + _spec := &sqlgraph.QuerySpec{ + Node: &sqlgraph.NodeSpec{ + Table: blog.Table, + Columns: blog.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: blog.FieldID, + }, + }, + From: bq.sql, + Unique: true, + } + if unique := bq.unique; unique != nil { + _spec.Unique = *unique + } + if fields := bq.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, blog.FieldID) + for i := range fields { + if fields[i] != blog.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := bq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := bq.limit; limit != nil { + _spec.Limit = *limit + } + if offset := bq.offset; offset != nil { + _spec.Offset = *offset + } + if ps := bq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (bq *BlogQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(bq.driver.Dialect()) + t1 := builder.Table(blog.Table) + columns := bq.fields + if len(columns) == 0 { + columns = blog.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if bq.sql != nil { + selector = bq.sql + selector.Select(selector.Columns(columns...)...) + } + if bq.unique != nil && *bq.unique { + selector.Distinct() + } + for _, p := range bq.predicates { + p(selector) + } + for _, p := range bq.order { + p(selector) + } + if offset := bq.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 := bq.limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// BlogGroupBy is the group-by builder for Blog entities. +type BlogGroupBy struct { + config + selector + 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 (bgb *BlogGroupBy) Aggregate(fns ...AggregateFunc) *BlogGroupBy { + bgb.fns = append(bgb.fns, fns...) + return bgb +} + +// Scan applies the group-by query and scans the result into the given value. +func (bgb *BlogGroupBy) Scan(ctx context.Context, v any) error { + query, err := bgb.path(ctx) + if err != nil { + return err + } + bgb.sql = query + return bgb.sqlScan(ctx, v) +} + +func (bgb *BlogGroupBy) sqlScan(ctx context.Context, v any) error { + for _, f := range bgb.fields { + if !blog.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + } + } + selector := bgb.sqlQuery() + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := bgb.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +func (bgb *BlogGroupBy) sqlQuery() *sql.Selector { + selector := bgb.sql.Select() + aggregation := make([]string, 0, len(bgb.fns)) + for _, fn := range bgb.fns { + aggregation = append(aggregation, fn(selector)) + } + // If no columns were selected in a custom aggregation function, the default + // selection is the fields used for "group-by", and the aggregation functions. + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(bgb.fields)+len(bgb.fns)) + for _, f := range bgb.fields { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + return selector.GroupBy(selector.Columns(bgb.fields...)...) +} + +// BlogSelect is the builder for selecting fields of Blog entities. +type BlogSelect struct { + *BlogQuery + selector + // intermediate query (i.e. traversal path). + sql *sql.Selector +} + +// Scan applies the selector query and scans the result into the given value. +func (bs *BlogSelect) Scan(ctx context.Context, v any) error { + if err := bs.prepareQuery(ctx); err != nil { + return err + } + bs.sql = bs.BlogQuery.sqlQuery(ctx) + return bs.sqlScan(ctx, v) +} + +func (bs *BlogSelect) sqlScan(ctx context.Context, v any) error { + rows := &sql.Rows{} + query, args := bs.sql.Query() + if err := bs.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/entc/integration/migrate/entv2/blog_update.go b/entc/integration/migrate/entv2/blog_update.go new file mode 100644 index 0000000000..73f845b95a --- /dev/null +++ b/entc/integration/migrate/entv2/blog_update.go @@ -0,0 +1,430 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package entv2 + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/migrate/entv2/blog" + "entgo.io/ent/entc/integration/migrate/entv2/predicate" + "entgo.io/ent/entc/integration/migrate/entv2/user" + "entgo.io/ent/schema/field" +) + +// BlogUpdate is the builder for updating Blog entities. +type BlogUpdate struct { + config + hooks []Hook + mutation *BlogMutation +} + +// Where appends a list predicates to the BlogUpdate builder. +func (bu *BlogUpdate) Where(ps ...predicate.Blog) *BlogUpdate { + bu.mutation.Where(ps...) + return bu +} + +// AddAdminIDs adds the "admins" edge to the User entity by IDs. +func (bu *BlogUpdate) AddAdminIDs(ids ...int) *BlogUpdate { + bu.mutation.AddAdminIDs(ids...) + return bu +} + +// AddAdmins adds the "admins" edges to the User entity. +func (bu *BlogUpdate) AddAdmins(u ...*User) *BlogUpdate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return bu.AddAdminIDs(ids...) +} + +// Mutation returns the BlogMutation object of the builder. +func (bu *BlogUpdate) Mutation() *BlogMutation { + return bu.mutation +} + +// ClearAdmins clears all "admins" edges to the User entity. +func (bu *BlogUpdate) ClearAdmins() *BlogUpdate { + bu.mutation.ClearAdmins() + return bu +} + +// RemoveAdminIDs removes the "admins" edge to User entities by IDs. +func (bu *BlogUpdate) RemoveAdminIDs(ids ...int) *BlogUpdate { + bu.mutation.RemoveAdminIDs(ids...) + return bu +} + +// RemoveAdmins removes "admins" edges to User entities. +func (bu *BlogUpdate) RemoveAdmins(u ...*User) *BlogUpdate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return bu.RemoveAdminIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (bu *BlogUpdate) Save(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(bu.hooks) == 0 { + affected, err = bu.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*BlogMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + bu.mutation = mutation + affected, err = bu.sqlSave(ctx) + mutation.done = true + return affected, err + }) + for i := len(bu.hooks) - 1; i >= 0; i-- { + if bu.hooks[i] == nil { + return 0, fmt.Errorf("entv2: uninitialized hook (forgotten import entv2/runtime?)") + } + mut = bu.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, bu.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// SaveX is like Save, but panics if an error occurs. +func (bu *BlogUpdate) SaveX(ctx context.Context) int { + affected, err := bu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (bu *BlogUpdate) Exec(ctx context.Context) error { + _, err := bu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (bu *BlogUpdate) ExecX(ctx context.Context) { + if err := bu.Exec(ctx); err != nil { + panic(err) + } +} + +func (bu *BlogUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: blog.Table, + Columns: blog.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: blog.FieldID, + }, + }, + } + if ps := bu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if bu.mutation.AdminsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: blog.AdminsTable, + Columns: []string{blog.AdminsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := bu.mutation.RemovedAdminsIDs(); len(nodes) > 0 && !bu.mutation.AdminsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: blog.AdminsTable, + Columns: []string{blog.AdminsColumn}, + 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.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := bu.mutation.AdminsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: blog.AdminsTable, + Columns: []string{blog.AdminsColumn}, + 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, bu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{blog.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + return n, nil +} + +// BlogUpdateOne is the builder for updating a single Blog entity. +type BlogUpdateOne struct { + config + fields []string + hooks []Hook + mutation *BlogMutation +} + +// AddAdminIDs adds the "admins" edge to the User entity by IDs. +func (buo *BlogUpdateOne) AddAdminIDs(ids ...int) *BlogUpdateOne { + buo.mutation.AddAdminIDs(ids...) + return buo +} + +// AddAdmins adds the "admins" edges to the User entity. +func (buo *BlogUpdateOne) AddAdmins(u ...*User) *BlogUpdateOne { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return buo.AddAdminIDs(ids...) +} + +// Mutation returns the BlogMutation object of the builder. +func (buo *BlogUpdateOne) Mutation() *BlogMutation { + return buo.mutation +} + +// ClearAdmins clears all "admins" edges to the User entity. +func (buo *BlogUpdateOne) ClearAdmins() *BlogUpdateOne { + buo.mutation.ClearAdmins() + return buo +} + +// RemoveAdminIDs removes the "admins" edge to User entities by IDs. +func (buo *BlogUpdateOne) RemoveAdminIDs(ids ...int) *BlogUpdateOne { + buo.mutation.RemoveAdminIDs(ids...) + return buo +} + +// RemoveAdmins removes "admins" edges to User entities. +func (buo *BlogUpdateOne) RemoveAdmins(u ...*User) *BlogUpdateOne { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return buo.RemoveAdminIDs(ids...) +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (buo *BlogUpdateOne) Select(field string, fields ...string) *BlogUpdateOne { + buo.fields = append([]string{field}, fields...) + return buo +} + +// Save executes the query and returns the updated Blog entity. +func (buo *BlogUpdateOne) Save(ctx context.Context) (*Blog, error) { + var ( + err error + node *Blog + ) + if len(buo.hooks) == 0 { + node, err = buo.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*BlogMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + buo.mutation = mutation + node, err = buo.sqlSave(ctx) + mutation.done = true + return node, err + }) + for i := len(buo.hooks) - 1; i >= 0; i-- { + if buo.hooks[i] == nil { + return nil, fmt.Errorf("entv2: uninitialized hook (forgotten import entv2/runtime?)") + } + mut = buo.hooks[i](mut) + } + v, err := mut.Mutate(ctx, buo.mutation) + if err != nil { + return nil, err + } + nv, ok := v.(*Blog) + if !ok { + return nil, fmt.Errorf("unexpected node type %T returned from BlogMutation", v) + } + node = nv + } + return node, err +} + +// SaveX is like Save, but panics if an error occurs. +func (buo *BlogUpdateOne) SaveX(ctx context.Context) *Blog { + node, err := buo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (buo *BlogUpdateOne) Exec(ctx context.Context) error { + _, err := buo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (buo *BlogUpdateOne) ExecX(ctx context.Context) { + if err := buo.Exec(ctx); err != nil { + panic(err) + } +} + +func (buo *BlogUpdateOne) sqlSave(ctx context.Context) (_node *Blog, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: blog.Table, + Columns: blog.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: blog.FieldID, + }, + }, + } + id, ok := buo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`entv2: missing "Blog.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := buo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, blog.FieldID) + for _, f := range fields { + if !blog.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("entv2: invalid field %q for query", f)} + } + if f != blog.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := buo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if buo.mutation.AdminsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: blog.AdminsTable, + Columns: []string{blog.AdminsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := buo.mutation.RemovedAdminsIDs(); len(nodes) > 0 && !buo.mutation.AdminsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: blog.AdminsTable, + Columns: []string{blog.AdminsColumn}, + 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.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := buo.mutation.AdminsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: blog.AdminsTable, + Columns: []string{blog.AdminsColumn}, + 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 = &Blog{config: buo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, buo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{blog.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + return _node, nil +} diff --git a/entc/integration/migrate/entv2/client.go b/entc/integration/migrate/entv2/client.go index 7deeac9e86..cbaf069d8b 100644 --- a/entc/integration/migrate/entv2/client.go +++ b/entc/integration/migrate/entv2/client.go @@ -14,6 +14,7 @@ import ( "entgo.io/ent/entc/integration/migrate/entv2/migrate" + "entgo.io/ent/entc/integration/migrate/entv2/blog" "entgo.io/ent/entc/integration/migrate/entv2/car" "entgo.io/ent/entc/integration/migrate/entv2/conversion" "entgo.io/ent/entc/integration/migrate/entv2/customtype" @@ -32,6 +33,8 @@ type Client struct { config // Schema is the client for creating, migrating and dropping schema. Schema *migrate.Schema + // Blog is the client for interacting with the Blog builders. + Blog *BlogClient // Car is the client for interacting with the Car builders. Car *CarClient // Conversion is the client for interacting with the Conversion builders. @@ -59,6 +62,7 @@ func NewClient(opts ...Option) *Client { func (c *Client) init() { c.Schema = migrate.NewSchema(c.driver) + c.Blog = NewBlogClient(c.config) c.Car = NewCarClient(c.config) c.Conversion = NewConversionClient(c.config) c.CustomType = NewCustomTypeClient(c.config) @@ -99,6 +103,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { return &Tx{ ctx: ctx, config: cfg, + Blog: NewBlogClient(cfg), Car: NewCarClient(cfg), Conversion: NewConversionClient(cfg), CustomType: NewCustomTypeClient(cfg), @@ -125,6 +130,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) return &Tx{ ctx: ctx, config: cfg, + Blog: NewBlogClient(cfg), Car: NewCarClient(cfg), Conversion: NewConversionClient(cfg), CustomType: NewCustomTypeClient(cfg), @@ -138,7 +144,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(). -// Car. +// Blog. // Query(). // Count(ctx) func (c *Client) Debug() *Client { @@ -160,6 +166,7 @@ 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.Blog.Use(hooks...) c.Car.Use(hooks...) c.Conversion.Use(hooks...) c.CustomType.Use(hooks...) @@ -169,6 +176,112 @@ func (c *Client) Use(hooks ...Hook) { c.User.Use(hooks...) } +// BlogClient is a client for the Blog schema. +type BlogClient struct { + config +} + +// NewBlogClient returns a client for the Blog from the given config. +func NewBlogClient(c config) *BlogClient { + return &BlogClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `blog.Hooks(f(g(h())))`. +func (c *BlogClient) Use(hooks ...Hook) { + c.hooks.Blog = append(c.hooks.Blog, hooks...) +} + +// Create returns a builder for creating a Blog entity. +func (c *BlogClient) Create() *BlogCreate { + mutation := newBlogMutation(c.config, OpCreate) + return &BlogCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Blog entities. +func (c *BlogClient) CreateBulk(builders ...*BlogCreate) *BlogCreateBulk { + return &BlogCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Blog. +func (c *BlogClient) Update() *BlogUpdate { + mutation := newBlogMutation(c.config, OpUpdate) + return &BlogUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *BlogClient) UpdateOne(b *Blog) *BlogUpdateOne { + mutation := newBlogMutation(c.config, OpUpdateOne, withBlog(b)) + return &BlogUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *BlogClient) UpdateOneID(id int) *BlogUpdateOne { + mutation := newBlogMutation(c.config, OpUpdateOne, withBlogID(id)) + return &BlogUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Blog. +func (c *BlogClient) Delete() *BlogDelete { + mutation := newBlogMutation(c.config, OpDelete) + return &BlogDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *BlogClient) DeleteOne(b *Blog) *BlogDeleteOne { + return c.DeleteOneID(b.ID) +} + +// DeleteOne returns a builder for deleting the given entity by its id. +func (c *BlogClient) DeleteOneID(id int) *BlogDeleteOne { + builder := c.Delete().Where(blog.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &BlogDeleteOne{builder} +} + +// Query returns a query builder for Blog. +func (c *BlogClient) Query() *BlogQuery { + return &BlogQuery{ + config: c.config, + } +} + +// Get returns a Blog entity by its id. +func (c *BlogClient) Get(ctx context.Context, id int) (*Blog, error) { + return c.Query().Where(blog.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *BlogClient) GetX(ctx context.Context, id int) *Blog { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryAdmins queries the admins edge of a Blog. +func (c *BlogClient) QueryAdmins(b *Blog) *UserQuery { + query := &UserQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := b.ID + step := sqlgraph.NewStep( + sqlgraph.From(blog.Table, blog.FieldID, id), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, blog.AdminsTable, blog.AdminsColumn), + ) + fromV = sqlgraph.Neighbors(b.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *BlogClient) Hooks() []Hook { + return c.hooks.Blog +} + // CarClient is a client for the Car schema. type CarClient struct { config diff --git a/entc/integration/migrate/entv2/config.go b/entc/integration/migrate/entv2/config.go index a6a70085c9..368d401811 100644 --- a/entc/integration/migrate/entv2/config.go +++ b/entc/integration/migrate/entv2/config.go @@ -28,6 +28,7 @@ type config struct { // hooks per client, for fast access. type hooks struct { + Blog []ent.Hook Car []ent.Hook Conversion []ent.Hook CustomType []ent.Hook diff --git a/entc/integration/migrate/entv2/ent.go b/entc/integration/migrate/entv2/ent.go index 82e6ed6eba..d6f6e3be5c 100644 --- a/entc/integration/migrate/entv2/ent.go +++ b/entc/integration/migrate/entv2/ent.go @@ -14,6 +14,7 @@ import ( "entgo.io/ent" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/migrate/entv2/blog" "entgo.io/ent/entc/integration/migrate/entv2/car" "entgo.io/ent/entc/integration/migrate/entv2/conversion" "entgo.io/ent/entc/integration/migrate/entv2/customtype" @@ -41,6 +42,7 @@ type OrderFunc func(*sql.Selector) // columnChecker returns a function indicates if the column exists in the given column. func columnChecker(table string) func(string) error { checks := map[string]func(string) bool{ + blog.Table: blog.ValidColumn, car.Table: car.ValidColumn, conversion.Table: conversion.ValidColumn, customtype.Table: customtype.ValidColumn, diff --git a/entc/integration/migrate/entv2/hook/hook.go b/entc/integration/migrate/entv2/hook/hook.go index ebeb57de2e..fd4b487cb3 100644 --- a/entc/integration/migrate/entv2/hook/hook.go +++ b/entc/integration/migrate/entv2/hook/hook.go @@ -13,6 +13,19 @@ import ( "entgo.io/ent/entc/integration/migrate/entv2" ) +// The BlogFunc type is an adapter to allow the use of ordinary +// function as Blog mutator. +type BlogFunc func(context.Context, *entv2.BlogMutation) (entv2.Value, error) + +// Mutate calls f(ctx, m). +func (f BlogFunc) Mutate(ctx context.Context, m entv2.Mutation) (entv2.Value, error) { + mv, ok := m.(*entv2.BlogMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T. expect *entv2.BlogMutation", m) + } + return f(ctx, mv) +} + // The CarFunc type is an adapter to allow the use of ordinary // function as Car mutator. type CarFunc func(context.Context, *entv2.CarMutation) (entv2.Value, error) diff --git a/entc/integration/migrate/entv2/migrate/schema.go b/entc/integration/migrate/entv2/migrate/schema.go index 6b123526fb..1d7ac07861 100644 --- a/entc/integration/migrate/entv2/migrate/schema.go +++ b/entc/integration/migrate/entv2/migrate/schema.go @@ -13,6 +13,16 @@ import ( ) var ( + // BlogsColumns holds the columns for the "blogs" table. + BlogsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true, SchemaType: map[string]string{"postgres": "serial"}}, + } + // BlogsTable holds the schema information for the "blogs" table. + BlogsTable = &schema.Table{ + Name: "blogs", + Columns: BlogsColumns, + PrimaryKey: []*schema.Column{BlogsColumns[0]}, + } // CarColumns holds the columns for the "Car" table. CarColumns = []*schema.Column{ {Name: "id", Type: field.TypeInt, Increment: true}, @@ -149,12 +159,21 @@ var ( {Name: "workplace", Type: field.TypeString, Nullable: true}, {Name: "created_at", Type: field.TypeTime, Default: "CURRENT_TIMESTAMP"}, {Name: "drop_optional", Type: field.TypeString}, + {Name: "blog_admins", Type: field.TypeInt, Nullable: true, SchemaType: map[string]string{"postgres": "serial"}}, } // UsersTable holds the schema information for the "users" table. UsersTable = &schema.Table{ Name: "users", Columns: UsersColumns, PrimaryKey: []*schema.Column{UsersColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "users_blogs_admins", + Columns: []*schema.Column{UsersColumns[19]}, + RefColumns: []*schema.Column{BlogsColumns[0]}, + OnDelete: schema.SetNull, + }, + }, Indexes: []*schema.Index{ { Name: "user_description", @@ -234,6 +253,7 @@ var ( } // Tables holds all the tables in the schema. Tables = []*schema.Table{ + BlogsTable, CarTable, ConversionsTable, CustomTypesTable, @@ -257,6 +277,7 @@ func init() { "boring_check": "source_uri <> 'entgo.io'", } PetsTable.ForeignKeys[0].RefTable = UsersTable + UsersTable.ForeignKeys[0].RefTable = BlogsTable FriendsTable.ForeignKeys[0].RefTable = UsersTable FriendsTable.ForeignKeys[1].RefTable = UsersTable } diff --git a/entc/integration/migrate/entv2/mutation.go b/entc/integration/migrate/entv2/mutation.go index c4eb89a9a5..97ea530af6 100644 --- a/entc/integration/migrate/entv2/mutation.go +++ b/entc/integration/migrate/entv2/mutation.go @@ -13,6 +13,7 @@ import ( "sync" "time" + "entgo.io/ent/entc/integration/migrate/entv2/blog" "entgo.io/ent/entc/integration/migrate/entv2/car" "entgo.io/ent/entc/integration/migrate/entv2/conversion" "entgo.io/ent/entc/integration/migrate/entv2/customtype" @@ -33,6 +34,7 @@ const ( OpUpdateOne = ent.OpUpdateOne // Node types. + TypeBlog = "Blog" TypeCar = "Car" TypeConversion = "Conversion" TypeCustomType = "CustomType" @@ -42,6 +44,354 @@ const ( TypeUser = "User" ) +// BlogMutation represents an operation that mutates the Blog nodes in the graph. +type BlogMutation struct { + config + op Op + typ string + id *int + clearedFields map[string]struct{} + admins map[int]struct{} + removedadmins map[int]struct{} + clearedadmins bool + done bool + oldValue func(context.Context) (*Blog, error) + predicates []predicate.Blog +} + +var _ ent.Mutation = (*BlogMutation)(nil) + +// blogOption allows management of the mutation configuration using functional options. +type blogOption func(*BlogMutation) + +// newBlogMutation creates new mutation for the Blog entity. +func newBlogMutation(c config, op Op, opts ...blogOption) *BlogMutation { + m := &BlogMutation{ + config: c, + op: op, + typ: TypeBlog, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withBlogID sets the ID field of the mutation. +func withBlogID(id int) blogOption { + return func(m *BlogMutation) { + var ( + err error + once sync.Once + value *Blog + ) + m.oldValue = func(ctx context.Context) (*Blog, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Blog.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withBlog sets the old Blog of the mutation. +func withBlog(node *Blog) blogOption { + return func(m *BlogMutation) { + m.oldValue = func(context.Context) (*Blog, 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 BlogMutation) 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 BlogMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("entv2: 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 Blog entities. +func (m *BlogMutation) SetID(id int) { + m.id = &id +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *BlogMutation) ID() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *BlogMutation) IDs(ctx context.Context) ([]int, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().Blog.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// AddAdminIDs adds the "admins" edge to the User entity by ids. +func (m *BlogMutation) AddAdminIDs(ids ...int) { + if m.admins == nil { + m.admins = make(map[int]struct{}) + } + for i := range ids { + m.admins[ids[i]] = struct{}{} + } +} + +// ClearAdmins clears the "admins" edge to the User entity. +func (m *BlogMutation) ClearAdmins() { + m.clearedadmins = true +} + +// AdminsCleared reports if the "admins" edge to the User entity was cleared. +func (m *BlogMutation) AdminsCleared() bool { + return m.clearedadmins +} + +// RemoveAdminIDs removes the "admins" edge to the User entity by IDs. +func (m *BlogMutation) RemoveAdminIDs(ids ...int) { + if m.removedadmins == nil { + m.removedadmins = make(map[int]struct{}) + } + for i := range ids { + delete(m.admins, ids[i]) + m.removedadmins[ids[i]] = struct{}{} + } +} + +// RemovedAdmins returns the removed IDs of the "admins" edge to the User entity. +func (m *BlogMutation) RemovedAdminsIDs() (ids []int) { + for id := range m.removedadmins { + ids = append(ids, id) + } + return +} + +// AdminsIDs returns the "admins" edge IDs in the mutation. +func (m *BlogMutation) AdminsIDs() (ids []int) { + for id := range m.admins { + ids = append(ids, id) + } + return +} + +// ResetAdmins resets all changes to the "admins" edge. +func (m *BlogMutation) ResetAdmins() { + m.admins = nil + m.clearedadmins = false + m.removedadmins = nil +} + +// Where appends a list predicates to the BlogMutation builder. +func (m *BlogMutation) Where(ps ...predicate.Blog) { + m.predicates = append(m.predicates, ps...) +} + +// Op returns the operation name. +func (m *BlogMutation) Op() Op { + return m.op +} + +// Type returns the node type of this mutation (Blog). +func (m *BlogMutation) 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 *BlogMutation) Fields() []string { + fields := make([]string, 0, 0) + 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 *BlogMutation) Field(name string) (ent.Value, bool) { + 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 *BlogMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + return nil, fmt.Errorf("unknown Blog 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 *BlogMutation) SetField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown Blog field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *BlogMutation) 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 *BlogMutation) 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 *BlogMutation) AddField(name string, value ent.Value) error { + return fmt.Errorf("unknown Blog numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *BlogMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *BlogMutation) 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 *BlogMutation) ClearField(name string) error { + return fmt.Errorf("unknown Blog 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 *BlogMutation) ResetField(name string) error { + return fmt.Errorf("unknown Blog field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *BlogMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.admins != nil { + edges = append(edges, blog.EdgeAdmins) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *BlogMutation) AddedIDs(name string) []ent.Value { + switch name { + case blog.EdgeAdmins: + ids := make([]ent.Value, 0, len(m.admins)) + for id := range m.admins { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *BlogMutation) RemovedEdges() []string { + edges := make([]string, 0, 1) + if m.removedadmins != nil { + edges = append(edges, blog.EdgeAdmins) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *BlogMutation) RemovedIDs(name string) []ent.Value { + switch name { + case blog.EdgeAdmins: + ids := make([]ent.Value, 0, len(m.removedadmins)) + for id := range m.removedadmins { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *BlogMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedadmins { + edges = append(edges, blog.EdgeAdmins) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *BlogMutation) EdgeCleared(name string) bool { + switch name { + case blog.EdgeAdmins: + return m.clearedadmins + } + 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 *BlogMutation) ClearEdge(name string) error { + switch name { + } + return fmt.Errorf("unknown Blog 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 *BlogMutation) ResetEdge(name string) error { + switch name { + case blog.EdgeAdmins: + m.ResetAdmins() + return nil + } + return fmt.Errorf("unknown Blog edge %s", name) +} + // CarMutation represents an operation that mutates the Car nodes in the graph. type CarMutation struct { config diff --git a/entc/integration/migrate/entv2/predicate/predicate.go b/entc/integration/migrate/entv2/predicate/predicate.go index 23ba47be94..c2fec803bf 100644 --- a/entc/integration/migrate/entv2/predicate/predicate.go +++ b/entc/integration/migrate/entv2/predicate/predicate.go @@ -10,6 +10,9 @@ import ( "entgo.io/ent/dialect/sql" ) +// Blog is the predicate function for blog builders. +type Blog func(*sql.Selector) + // Car is the predicate function for car builders. type Car func(*sql.Selector) diff --git a/entc/integration/migrate/entv2/schema/user.go b/entc/integration/migrate/entv2/schema/user.go index 2583f4f9d9..9ac3f6ddb1 100644 --- a/entc/integration/migrate/entv2/schema/user.go +++ b/entc/integration/migrate/entv2/schema/user.go @@ -7,17 +7,17 @@ package schema import ( "time" - "github.com/google/uuid" - - "entgo.io/ent/schema" - "entgo.io/ent" "entgo.io/ent/dialect" "entgo.io/ent/dialect/entsql" + "entgo.io/ent/schema" "entgo.io/ent/schema/edge" "entgo.io/ent/schema/field" "entgo.io/ent/schema/index" "entgo.io/ent/schema/mixin" + + "ariga.io/atlas/sql/postgres" + "github.com/google/uuid" ) type Mixin struct { @@ -197,6 +197,24 @@ func (Car) Edges() []ent.Edge { // Group schema. type Group struct{ ent.Schema } +// Blog schema. +type Blog struct{ ent.Schema } + +func (Blog) Fields() []ent.Field { + return []ent.Field{ + field.Int("id"). + SchemaType(map[string]string{ + dialect.Postgres: postgres.TypeSerial, + }), + } +} + +func (Blog) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("admins", User.Type), + } +} + // Pet schema. type Pet struct { ent.Schema diff --git a/entc/integration/migrate/entv2/tx.go b/entc/integration/migrate/entv2/tx.go index 7e1160247d..490062da48 100644 --- a/entc/integration/migrate/entv2/tx.go +++ b/entc/integration/migrate/entv2/tx.go @@ -16,6 +16,8 @@ import ( // Tx is a transactional client that is created by calling Client.Tx(). type Tx struct { config + // Blog is the client for interacting with the Blog builders. + Blog *BlogClient // Car is the client for interacting with the Car builders. Car *CarClient // Conversion is the client for interacting with the Conversion builders. @@ -165,6 +167,7 @@ func (tx *Tx) Client() *Client { } func (tx *Tx) init() { + tx.Blog = NewBlogClient(tx.config) tx.Car = NewCarClient(tx.config) tx.Conversion = NewConversionClient(tx.config) tx.CustomType = NewCustomTypeClient(tx.config) @@ -181,7 +184,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: Car.QueryXXX(), the query will be executed +// applies a query, for example: Blog.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/migrate/entv2/user.go b/entc/integration/migrate/entv2/user.go index 83d4b71d96..e8a6e1501f 100644 --- a/entc/integration/migrate/entv2/user.go +++ b/entc/integration/migrate/entv2/user.go @@ -59,7 +59,8 @@ type User struct { DropOptional string `json:"drop_optional,omitempty"` // Edges holds the relations/edges for other nodes in the graph. // The values are being populated by the UserQuery when eager-loading is set. - Edges UserEdges `json:"edges"` + Edges UserEdges `json:"edges"` + blog_admins *int } // UserEdges holds the relations/edges for other nodes in the graph. @@ -121,6 +122,8 @@ func (*User) scanValues(columns []string) ([]any, error) { values[i] = new(sql.NullString) case user.FieldCreatedAt: values[i] = new(sql.NullTime) + case user.ForeignKeys[0]: // blog_admins + values[i] = new(sql.NullInt64) default: return nil, fmt.Errorf("unexpected column %q for type User", columns[i]) } @@ -250,6 +253,13 @@ func (u *User) assignValues(columns []string, values []any) error { } else if value.Valid { u.DropOptional = value.String } + case user.ForeignKeys[0]: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for edge-field blog_admins", value) + } else if value.Valid { + u.blog_admins = new(int) + *u.blog_admins = int(value.Int64) + } } } return nil diff --git a/entc/integration/migrate/entv2/user/user.go b/entc/integration/migrate/entv2/user/user.go index 7dd24e9927..8bf09a26e5 100644 --- a/entc/integration/migrate/entv2/user/user.go +++ b/entc/integration/migrate/entv2/user/user.go @@ -105,6 +105,12 @@ var Columns = []string{ FieldDropOptional, } +// ForeignKeys holds the SQL foreign-keys that are owned by the "users" +// table and are not defined as standalone fields in the schema. +var ForeignKeys = []string{ + "blog_admins", +} + var ( // FriendsPrimaryKey and FriendsColumn2 are the table columns denoting the // primary key for the friends relation (M2M). @@ -118,6 +124,11 @@ func ValidColumn(column string) bool { return true } } + for i := range ForeignKeys { + if column == ForeignKeys[i] { + return true + } + } return false } diff --git a/entc/integration/migrate/entv2/user_query.go b/entc/integration/migrate/entv2/user_query.go index b6bfbc9815..2313193725 100644 --- a/entc/integration/migrate/entv2/user_query.go +++ b/entc/integration/migrate/entv2/user_query.go @@ -33,6 +33,7 @@ type UserQuery struct { withCar *CarQuery withPets *PetQuery withFriends *UserQuery + withFKs bool // intermediate query (i.e. traversal path). sql *sql.Selector path func(context.Context) (*sql.Selector, error) @@ -426,6 +427,7 @@ func (uq *UserQuery) prepareQuery(ctx context.Context) error { func (uq *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, error) { var ( nodes = []*User{} + withFKs = uq.withFKs _spec = uq.querySpec() loadedTypes = [3]bool{ uq.withCar != nil, @@ -433,6 +435,9 @@ func (uq *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, e uq.withFriends != nil, } ) + if withFKs { + _spec.Node.Columns = append(_spec.Node.Columns, user.ForeignKeys...) + } _spec.ScanValues = func(columns []string) ([]any, error) { return (*User).scanValues(nil, columns) } diff --git a/entc/integration/migrate/migrate_test.go b/entc/integration/migrate/migrate_test.go index 9d60315984..2e44994962 100644 --- a/entc/integration/migrate/migrate_test.go +++ b/entc/integration/migrate/migrate_test.go @@ -19,9 +19,8 @@ import ( "testing" "text/template" - "ariga.io/atlas/sql/migrate" - atlas "ariga.io/atlas/sql/schema" - "ariga.io/atlas/sql/sqltool" + "entgo.io/ent/entc/integration/migrate/entv2/blog" + "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/schema" @@ -36,6 +35,11 @@ import ( "entgo.io/ent/entc/integration/migrate/entv2/user" "entgo.io/ent/entc/integration/migrate/versioned" vmigrate "entgo.io/ent/entc/integration/migrate/versioned/migrate" + + "ariga.io/atlas/sql/migrate" + "ariga.io/atlas/sql/postgres" + atlas "ariga.io/atlas/sql/schema" + "ariga.io/atlas/sql/sqltool" _ "github.com/go-sql-driver/mysql" _ "github.com/lib/pq" _ "github.com/mattn/go-sqlite3" @@ -106,7 +110,26 @@ func TestPostgres(t *testing.T) { clientv1 := entv1.NewClient(entv1.Driver(drv)) clientv2 := entv2.NewClient(entv2.Driver(drv)) - V1ToV2(t, drv.Dialect(), clientv1, clientv2) + V1ToV2( + t, drv.Dialect(), clientv1, clientv2, + // A diff hook to ensure foreign-keys that point to + // serial columns are configured to integer types. + func(next schema.Differ) schema.Differ { + return schema.DiffFunc(func(current, desired *atlas.Schema) ([]atlas.Change, error) { + blogs, ok := desired.Table(blog.Table) + require.True(t, ok) + id, ok := blogs.Column(blog.FieldID) + require.True(t, ok) + require.IsType(t, &postgres.SerialType{}, id.Type.Type) + users, ok := desired.Table(user.Table) + require.True(t, ok) + fk, ok := users.Column(blog.AdminsColumn) + require.True(t, ok) + require.IsType(t, &atlas.IntegerType{}, fk.Type.Type) + return next.Diff(current, desired) + }) + }, + ) CheckConstraint(t, clientv2) TimePrecision(t, drv, "SELECT datetime_precision FROM information_schema.columns WHERE table_name = $1 AND column_name = $2") PartialIndexes(t, drv, "select indexdef from pg_indexes where indexname=$1", "CREATE INDEX user_phone ON public.users USING btree (phone) WHERE active") @@ -178,13 +201,14 @@ func TestSQLite(t *testing.T) { SanityV2(t, drv.Dialect(), client) u := client.User.Create().SetAge(1).SetName("x").SetNickname("x'").SetPhone("y").SaveX(ctx) - idRange(t, client.Car.Create().SetOwner(u).SaveX(ctx).ID, 0, 1<<32) - idRange(t, client.Conversion.Create().SaveX(ctx).ID, 1<<32-1, 2<<32) - idRange(t, client.CustomType.Create().SaveX(ctx).ID, 2<<32-1, 3<<32) - idRange(t, client.Group.Create().SaveX(ctx).ID, 3<<32-1, 4<<32) - idRange(t, client.Media.Create().SaveX(ctx).ID, 4<<32-1, 5<<32) - idRange(t, client.Pet.Create().SaveX(ctx).ID, 5<<32-1, 6<<32) - idRange(t, u.ID, 6<<32-1, 7<<32) + idRange(t, client.Blog.Create().SaveX(ctx).ID, 0, 1<<32) + idRange(t, client.Car.Create().SetOwner(u).SaveX(ctx).ID, 1<<32-1, 2<<32) + idRange(t, client.Conversion.Create().SaveX(ctx).ID, 2<<32-1, 3<<32) + idRange(t, client.CustomType.Create().SaveX(ctx).ID, 3<<32-1, 4<<32) + idRange(t, client.Group.Create().SaveX(ctx).ID, 4<<32-1, 5<<32) + idRange(t, client.Media.Create().SaveX(ctx).ID, 5<<32-1, 6<<32) + idRange(t, client.Pet.Create().SaveX(ctx).ID, 6<<32-1, 7<<32) + idRange(t, u.ID, 7<<32-1, 8<<32) PartialIndexes(t, drv, "select sql from sqlite_master where name=?", "CREATE INDEX `user_phone` ON `users` (`phone`) WHERE active") // Override the default behavior of LIKE in SQLite. @@ -312,7 +336,7 @@ func Versioned(t *testing.T, drv sql.ExecQuerier, devURL string, client *version require.Equal(t, string(f1), string(f2)) } -func V1ToV2(t *testing.T, dialect string, clientv1 *entv1.Client, clientv2 *entv2.Client) { +func V1ToV2(t *testing.T, dialect string, clientv1 *entv1.Client, clientv2 *entv2.Client, hooks ...schema.DiffHook) { ctx := context.Background() // Run migration and execute queries on v1. @@ -328,7 +352,7 @@ func V1ToV2(t *testing.T, dialect string, clientv1 *entv1.Client, clientv2 *entv clientv1.Conversion.DeleteOne(c1).ExecX(ctx) // Run migration and execute queries on v2. - require.NoError(t, clientv2.Schema.Create(ctx, migratev2.WithGlobalUniqueID(true), migratev2.WithDropIndex(true), migratev2.WithDropColumn(true), schema.WithDiffHook(renameTokenColumn), schema.WithApplyHook(fillNulls(dialect)))) + require.NoError(t, clientv2.Schema.Create(ctx, migratev2.WithGlobalUniqueID(true), migratev2.WithDropIndex(true), migratev2.WithDropColumn(true), schema.WithDiffHook(append(hooks, renameTokenColumn)...), schema.WithApplyHook(fillNulls(dialect)))) require.NoError(t, clientv2.Schema.Create(ctx, migratev2.WithGlobalUniqueID(true), migratev2.WithDropIndex(true), migratev2.WithDropColumn(true)), "should not create additional resources on multiple runs") SanityV2(t, dialect, clientv2) clientv2.Conversion.CreateBulk(clientv2.Conversion.Create(), clientv2.Conversion.Create(), clientv2.Conversion.Create()).ExecX(ctx) @@ -339,9 +363,9 @@ func V1ToV2(t *testing.T, dialect string, clientv1 *entv1.Client, clientv2 *entv // Since "users" created in the migration of v1, it will occupy the range of 1<<32-1 ... 2<<32-1, // even though they are ordered differently in the migration of v2 (groups, pets, users). idRange(t, u.ID, 3<<32-1, 4<<32) - idRange(t, clientv2.Group.Create().SaveX(ctx).ID, 4<<32-1, 5<<32) - idRange(t, clientv2.Media.Create().SaveX(ctx).ID, 5<<32-1, 6<<32) - idRange(t, clientv2.Pet.Create().SaveX(ctx).ID, 6<<32-1, 7<<32) + idRange(t, clientv2.Group.Create().SaveX(ctx).ID, 5<<32-1, 6<<32) + idRange(t, clientv2.Media.Create().SaveX(ctx).ID, 6<<32-1, 7<<32) + idRange(t, clientv2.Pet.Create().SaveX(ctx).ID, 7<<32-1, 8<<32) // SQL specific predicates. EqualFold(t, clientv2)