diff --git a/cmd/ent/ent_test.go b/cmd/ent/ent_test.go index b6e325a30..3a7b38346 100644 --- a/cmd/ent/ent_test.go +++ b/cmd/ent/ent_test.go @@ -18,7 +18,8 @@ func TestCmd(t *testing.T) { cmd := exec.Command("go", "run", "entgo.io/ent/cmd/ent", "init", "User") stderr := bytes.NewBuffer(nil) cmd.Stderr = stderr - require.NoError(t, cmd.Run(), stderr.String()) + require.NoError(t, cmd.Run()) + require.Zero(t, stderr.String()) cmd = exec.Command("go", "run", "entgo.io/ent/cmd/ent", "init", "User") require.Error(t, cmd.Run()) @@ -30,7 +31,8 @@ func TestCmd(t *testing.T) { cmd = exec.Command("go", "run", "entgo.io/ent/cmd/ent", "generate", "./ent/schema") stderr = bytes.NewBuffer(nil) cmd.Stderr = stderr - require.NoError(t, cmd.Run(), stderr.String()) + require.NoError(t, cmd.Run()) + require.Zero(t, stderr.String()) _, err = os.Stat("ent/user.go") require.NoError(t, err) diff --git a/dialect/sql/schema/atlas.go b/dialect/sql/schema/atlas.go index 0f5f8ef26..f4eadfaaa 100644 --- a/dialect/sql/schema/atlas.go +++ b/dialect/sql/schema/atlas.go @@ -12,12 +12,11 @@ import ( "sort" "strings" + "ariga.io/atlas/sql/migrate" + "ariga.io/atlas/sql/schema" "entgo.io/ent/dialect" entsql "entgo.io/ent/dialect/sql" "entgo.io/ent/schema/field" - - "ariga.io/atlas/sql/migrate" - "ariga.io/atlas/sql/schema" ) type ( @@ -61,8 +60,8 @@ func WithDiffHook(hooks ...DiffHook) MigrateOption { } } -// SkipChanges allows skipping/filtering list of changes -// returned by the differ before executing migration planning. +// WithSkipChanges allows skipping/filtering list of changes +// returned by the Differ before executing migration planning. // // SkipChanges(schema.DropTable|schema.DropColumn) // @@ -72,7 +71,7 @@ func WithSkipChanges(skip ChangeKind) MigrateOption { } } -// A Change of schema. +// A ChangeKind denotes the kind of schema change. type ChangeKind uint // List of change types. @@ -173,15 +172,15 @@ func filterChanges(skip ChangeKind) DiffHook { type ( // Applier is the interface that wraps the Apply method. Applier interface { - // Diff creates the given tables in the database. + // Apply applies the given migrate.Plan on the database. Apply(context.Context, dialect.ExecQuerier, *migrate.Plan) error } // The ApplyFunc type is an adapter to allow the use of ordinary function as Applier. - // If f is a function with the appropriate signature, ApplyFunc(f) is a Applier that calls f. + // If f is a function with the appropriate signature, ApplyFunc(f) is an Applier that calls f. ApplyFunc func(context.Context, dialect.ExecQuerier, *migrate.Plan) error - // ApplyHook defines the "migration applying middleware". A function that gets a Applier and returns a Applier. + // ApplyHook defines the "migration applying middleware". A function that gets an Applier and returns an Applier. ApplyHook func(Applier) Applier ) @@ -190,7 +189,7 @@ func (f ApplyFunc) Apply(ctx context.Context, conn dialect.ExecQuerier, plan *mi return f(ctx, conn, plan) } -// func adds a list of ApplyHook to the schema migration. +// WithApplyHook adds a list of ApplyHook to the schema migration. // // schema.WithApplyHook(func(next schema.Applier) schema.Applier { // return schema.ApplyFunc(func(ctx context.Context, conn dialect.ExecQuerier, plan *migrate.Plan) error { @@ -221,6 +220,20 @@ func WithAtlas(b bool) MigrateOption { } } +// WithDir sets the atlas migration directory to use to store migration files. +func WithDir(dir migrate.Dir) MigrateOption { + return func(m *Migrate) { + m.atlas.dir = dir + } +} + +// WithFormatter sets atlas formatter to use to write changes to migration files. +func WithFormatter(fmt migrate.Formatter) MigrateOption { + return func(m *Migrate) { + m.atlas.fmt = fmt + } +} + type ( // atlasOptions describes the options for atlas. atlasOptions struct { @@ -228,6 +241,8 @@ type ( diff []DiffHook apply []ApplyHook skip ChangeKind + dir migrate.Dir + fmt migrate.Formatter } // atBuilder must be implemented by the different drivers in @@ -245,7 +260,7 @@ type ( func (m *Migrate) setupAtlas() error { // Using one of the Atlas options, opt-in to Atlas migration. - if !m.atlas.enabled && (m.atlas.skip != NoChange || len(m.atlas.diff) > 0 || len(m.atlas.apply) > 0) { + if !m.atlas.enabled && (m.atlas.skip != NoChange || len(m.atlas.diff) > 0 || len(m.atlas.apply) > 0) || m.atlas.dir != nil { m.atlas.enabled = true } if !m.atlas.enabled { @@ -270,6 +285,9 @@ func (m *Migrate) setupAtlas() error { if k == NoChange { m.atlas.diff = append(m.atlas.diff, filterChanges(k)) } + if m.atlas.dir != nil && m.atlas.fmt == nil { + m.atlas.fmt = migrate.DefaultFormatter + } return nil } @@ -289,36 +307,7 @@ func (m *Migrate) atCreate(ctx context.Context, tables ...*Table) error { return err } } - drv, err := m.atOpen(tx) - if err != nil { - return err - } - current, err := drv.InspectSchema(ctx, "", &schema.InspectOptions{ - Tables: func() (t []string) { - for i := range tables { - t = append(t, tables[i].Name) - } - return t - }(), - }) - if err != nil { - return err - } - tt, err := m.aTables(ctx, m, tx, tables) - if err != nil { - return err - } - // Diff changes. - var differ Differ = DiffFunc(drv.SchemaDiff) - for i := len(m.atlas.diff) - 1; i >= 0; i-- { - differ = m.atlas.diff[i](differ) - } - changes, err := differ.Diff(current, &schema.Schema{Name: current.Name, Attrs: current.Attrs, Tables: tt}) - if err != nil { - return err - } - // Plan changes. - plan, err := drv.PlanChanges(ctx, "plan", changes) + plan, err := m.atDiff(ctx, tx, tables...) if err != nil { return err } @@ -344,6 +333,39 @@ func (m *Migrate) atCreate(ctx context.Context, tables ...*Table) error { return tx.Commit() } +func (m *Migrate) atDiff(ctx context.Context, conn dialect.ExecQuerier, tables ...*Table) (*migrate.Plan, error) { + drv, err := m.atOpen(conn) + if err != nil { + return nil, err + } + current, err := drv.InspectSchema(ctx, "", &schema.InspectOptions{ + Tables: func() (t []string) { + for i := range tables { + t = append(t, tables[i].Name) + } + return t + }(), + }) + if err != nil { + return nil, err + } + tt, err := m.aTables(ctx, m, conn, tables) + if err != nil { + return nil, err + } + // Diff changes. + var differ Differ = DiffFunc(drv.SchemaDiff) + for i := len(m.atlas.diff) - 1; i >= 0; i-- { + differ = m.atlas.diff[i](differ) + } + changes, err := differ.Diff(current, &schema.Schema{Name: current.Name, Attrs: current.Attrs, Tables: tt}) + if err != nil { + return nil, err + } + // Plan changes. + return drv.PlanChanges(ctx, "", changes) +} + type db struct{ dialect.ExecQuerier } func (d *db) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) { diff --git a/dialect/sql/schema/migrate.go b/dialect/sql/schema/migrate.go index 4cf3ffec7..80c4b2515 100644 --- a/dialect/sql/schema/migrate.go +++ b/dialect/sql/schema/migrate.go @@ -7,9 +7,11 @@ package schema import ( "context" "crypto/md5" + "errors" "fmt" "math" + "ariga.io/atlas/sql/migrate" "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" "entgo.io/ent/schema/field" @@ -137,7 +139,7 @@ func NewMigrate(d dialect.Driver, opts ...MigrateOption) (*Migrate, error) { } // Create creates all schema resources in the database. It works in an "append-only" -// mode, which means, it only create tables, append column to tables or modifying column type. +// mode, which means, it only creates tables, appends columns to tables or modifies column types. // // Column can be modified by turning into a NULL from NOT NULL, or having a type conversion not // resulting data altering. From example, changing varchar(255) to varchar(120) is invalid, but @@ -159,6 +161,19 @@ func (m *Migrate) Create(ctx context.Context, tables ...*Table) error { return creator.Create(ctx, tables...) } +// Diff compares the state read from the StateReader with the state defined by Ent. +// Changes will be written to migration files by the configures Planner. +func (m *Migrate) Diff(ctx context.Context, tables ...*Table) error { + if m.atlas.dir == nil { + return errors.New("no migration directory given") + } + plan, err := m.atDiff(ctx, m, tables...) + if err != nil { + return err + } + return migrate.New(nil, m.atlas.dir, m.atlas.fmt).WritePlan(plan) +} + func (m *Migrate) create(ctx context.Context, tables ...*Table) error { tx, err := m.Tx(ctx) if err != nil { @@ -383,7 +398,6 @@ func (m *Migrate) changeSet(curr, new *Table) (*changes, error) { change.column.modify = append(change.column.modify, c1) } } - // Drop columns. for _, c1 := range curr.Columns { // If a column was dropped, multi-columns indexes that are associated with this column will @@ -394,7 +408,6 @@ func (m *Migrate) changeSet(curr, new *Table) (*changes, error) { change.column.drop = append(change.column.drop, c1) } } - // Add or modify indexes. for _, idx1 := range new.Indexes { switch idx2, ok := curr.index(idx1.Name); { @@ -413,7 +426,6 @@ func (m *Migrate) changeSet(curr, new *Table) (*changes, error) { } } } - // Drop indexes. for _, idx := range curr.Indexes { if _, isFK := new.fk(idx.Name); !isFK && !new.hasIndex(idx.Name, idx.realname) { diff --git a/entc/gen/feature.go b/entc/gen/feature.go index bf0f6a057..c50964c07 100644 --- a/entc/gen/feature.go +++ b/entc/gen/feature.go @@ -92,6 +92,13 @@ var ( Description: "Allows users to configure the `ON CONFLICT`/`ON DUPLICATE KEY` clause for `INSERT` statements", } + FeatureVersionedMigrations = Feature{ + Name: "sql/versioned-migrations", + Stage: Experimental, + Default: false, + Description: "Allows users to work with versioned migrations / migration files", + } + // AllFeatures holds a list of all feature-flags. AllFeatures = []Feature{ FeaturePrivacy, @@ -101,6 +108,7 @@ var ( FeatureLock, FeatureModifier, FeatureUpsert, + FeatureVersionedMigrations, } ) diff --git a/entc/gen/template/dialect/sql/feature/migrate_diff.tmpl b/entc/gen/template/dialect/sql/feature/migrate_diff.tmpl new file mode 100644 index 000000000..df879f873 --- /dev/null +++ b/entc/gen/template/dialect/sql/feature/migrate_diff.tmpl @@ -0,0 +1,19 @@ +{{/* +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. +*/}} + +{{/* gotype: entgo.io/ent/entc/gen.Graph */}} + +{{ define "migrate/diff" }} +// Diff creates a migration file containing the statements to resolve the diff +// between the Ent schema and the connected database. +func (s *Schema) Diff(ctx context.Context, opts ...schema.MigrateOption) error { + migrate, err := schema.NewMigrate(s.drv, opts...) + if err != nil { + return fmt.Errorf("ent/migrate: %w", err) + } + return migrate.Diff(ctx, Tables...) +} +{{ end }} \ No newline at end of file diff --git a/entc/gen/template/migrate/migrate.tmpl b/entc/gen/template/migrate/migrate.tmpl index 1c5972366..c9fb5b4a4 100644 --- a/entc/gen/template/migrate/migrate.tmpl +++ b/entc/gen/template/migrate/migrate.tmpl @@ -61,6 +61,8 @@ func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error return migrate.Create(ctx, Tables...) } +{{ if $.Config.FeatureEnabled "sql/versioned-migrations" }}{{ template "migrate/diff" $ }}{{ end }} + // WriteTo writes the schema changes to w instead of running them against the database. // // if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil { diff --git a/entc/integration/migrate/versioned/car.go b/entc/integration/migrate/versioned/car.go new file mode 100644 index 000000000..8194c7511 --- /dev/null +++ b/entc/integration/migrate/versioned/car.go @@ -0,0 +1,133 @@ +// 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 versioned + +import ( + "fmt" + "strings" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/entc/integration/migrate/versioned/car" + "entgo.io/ent/entc/integration/migrate/versioned/user" +) + +// Car is the model entity for the Car schema. +type Car 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 CarQuery when eager-loading is set. + Edges CarEdges `json:"edges"` + user_car *int +} + +// CarEdges holds the relations/edges for other nodes in the graph. +type CarEdges struct { + // Owner holds the value of the owner edge. + Owner *User `json:"owner,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// OwnerOrErr returns the Owner value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e CarEdges) OwnerOrErr() (*User, error) { + if e.loadedTypes[0] { + if e.Owner == nil { + // The edge owner was loaded in eager-loading, + // but was not found. + return nil, &NotFoundError{label: user.Label} + } + return e.Owner, nil + } + return nil, &NotLoadedError{edge: "owner"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Car) scanValues(columns []string) ([]interface{}, error) { + values := make([]interface{}, len(columns)) + for i := range columns { + switch columns[i] { + case car.FieldID: + values[i] = new(sql.NullInt64) + case car.ForeignKeys[0]: // user_car + values[i] = new(sql.NullInt64) + default: + return nil, fmt.Errorf("unexpected column %q for type Car", columns[i]) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the Car fields. +func (c *Car) 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 i := range columns { + switch columns[i] { + case car.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + c.ID = int(value.Int64) + case car.ForeignKeys[0]: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for edge-field user_car", value) + } else if value.Valid { + c.user_car = new(int) + *c.user_car = int(value.Int64) + } + } + } + return nil +} + +// QueryOwner queries the "owner" edge of the Car entity. +func (c *Car) QueryOwner() *UserQuery { + return (&CarClient{config: c.config}).QueryOwner(c) +} + +// Update returns a builder for updating this Car. +// Note that you need to call Car.Unwrap() before calling this method if this Car +// was returned from a transaction, and the transaction was committed or rolled back. +func (c *Car) Update() *CarUpdateOne { + return (&CarClient{config: c.config}).UpdateOne(c) +} + +// Unwrap unwraps the Car 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 (c *Car) Unwrap() *Car { + tx, ok := c.config.driver.(*txDriver) + if !ok { + panic("versioned: Car is not a transactional entity") + } + c.config.driver = tx.drv + return c +} + +// String implements the fmt.Stringer. +func (c *Car) String() string { + var builder strings.Builder + builder.WriteString("Car(") + builder.WriteString(fmt.Sprintf("id=%v", c.ID)) + builder.WriteByte(')') + return builder.String() +} + +// Cars is a parsable slice of Car. +type Cars []*Car + +func (c Cars) config(cfg config) { + for _i := range c { + c[_i].config = cfg + } +} diff --git a/entc/integration/migrate/versioned/car/car.go b/entc/integration/migrate/versioned/car/car.go new file mode 100644 index 000000000..3e601f7db --- /dev/null +++ b/entc/integration/migrate/versioned/car/car.go @@ -0,0 +1,53 @@ +// 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 car + +const ( + // Label holds the string label denoting the car type in the database. + Label = "car" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // EdgeOwner holds the string denoting the owner edge name in mutations. + EdgeOwner = "owner" + // UserFieldID holds the string denoting the ID field of the User. + UserFieldID = "oid" + // Table holds the table name of the car in the database. + Table = "cars" + // OwnerTable is the table that holds the owner relation/edge. + OwnerTable = "cars" + // OwnerInverseTable is the table name for the User entity. + // It exists in this package in order to avoid circular dependency with the "user" package. + OwnerInverseTable = "users" + // OwnerColumn is the table column denoting the owner relation/edge. + OwnerColumn = "user_car" +) + +// Columns holds all SQL columns for car fields. +var Columns = []string{ + FieldID, +} + +// ForeignKeys holds the SQL foreign-keys that are owned by the "cars" +// table and are not defined as standalone fields in the schema. +var ForeignKeys = []string{ + "user_car", +} + +// 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 + } + } + for i := range ForeignKeys { + if column == ForeignKeys[i] { + return true + } + } + return false +} diff --git a/entc/integration/migrate/versioned/car/where.go b/entc/integration/migrate/versioned/car/where.go new file mode 100644 index 000000000..caf27b28f --- /dev/null +++ b/entc/integration/migrate/versioned/car/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 car + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/migrate/versioned/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.Car { + return predicate.Car(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.Car { + return predicate.Car(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.Car { + return predicate.Car(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.Car { + return predicate.Car(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.Car { + return predicate.Car(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.Car { + return predicate.Car(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.Car { + return predicate.Car(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.Car { + return predicate.Car(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.Car { + return predicate.Car(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldID), id)) + }) +} + +// HasOwner applies the HasEdge predicate on the "owner" edge. +func HasOwner() predicate.Car { + return predicate.Car(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(OwnerTable, UserFieldID), + sqlgraph.Edge(sqlgraph.O2O, true, OwnerTable, OwnerColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasOwnerWith applies the HasEdge predicate on the "owner" edge with a given conditions (other predicates). +func HasOwnerWith(preds ...predicate.User) predicate.Car { + return predicate.Car(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(OwnerInverseTable, UserFieldID), + sqlgraph.Edge(sqlgraph.O2O, true, OwnerTable, OwnerColumn), + ) + 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.Car) predicate.Car { + return predicate.Car(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.Car) predicate.Car { + return predicate.Car(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.Car) predicate.Car { + return predicate.Car(func(s *sql.Selector) { + p(s.Not()) + }) +} diff --git a/entc/integration/migrate/versioned/car_create.go b/entc/integration/migrate/versioned/car_create.go new file mode 100644 index 000000000..c50a85d52 --- /dev/null +++ b/entc/integration/migrate/versioned/car_create.go @@ -0,0 +1,246 @@ +// 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 versioned + +import ( + "context" + "fmt" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/migrate/versioned/car" + "entgo.io/ent/entc/integration/migrate/versioned/user" + "entgo.io/ent/schema/field" +) + +// CarCreate is the builder for creating a Car entity. +type CarCreate struct { + config + mutation *CarMutation + hooks []Hook +} + +// SetOwnerID sets the "owner" edge to the User entity by ID. +func (cc *CarCreate) SetOwnerID(id int) *CarCreate { + cc.mutation.SetOwnerID(id) + return cc +} + +// SetNillableOwnerID sets the "owner" edge to the User entity by ID if the given value is not nil. +func (cc *CarCreate) SetNillableOwnerID(id *int) *CarCreate { + if id != nil { + cc = cc.SetOwnerID(*id) + } + return cc +} + +// SetOwner sets the "owner" edge to the User entity. +func (cc *CarCreate) SetOwner(u *User) *CarCreate { + return cc.SetOwnerID(u.ID) +} + +// Mutation returns the CarMutation object of the builder. +func (cc *CarCreate) Mutation() *CarMutation { + return cc.mutation +} + +// Save creates the Car in the database. +func (cc *CarCreate) Save(ctx context.Context) (*Car, error) { + var ( + err error + node *Car + ) + if len(cc.hooks) == 0 { + if err = cc.check(); err != nil { + return nil, err + } + node, err = cc.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*CarMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = cc.check(); err != nil { + return nil, err + } + cc.mutation = mutation + if node, err = cc.sqlSave(ctx); err != nil { + return nil, err + } + mutation.id = &node.ID + mutation.done = true + return node, err + }) + for i := len(cc.hooks) - 1; i >= 0; i-- { + if cc.hooks[i] == nil { + return nil, fmt.Errorf("versioned: uninitialized hook (forgotten import versioned/runtime?)") + } + mut = cc.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, cc.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX calls Save and panics if Save returns an error. +func (cc *CarCreate) SaveX(ctx context.Context) *Car { + v, err := cc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (cc *CarCreate) Exec(ctx context.Context) error { + _, err := cc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (cc *CarCreate) ExecX(ctx context.Context) { + if err := cc.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (cc *CarCreate) check() error { + return nil +} + +func (cc *CarCreate) sqlSave(ctx context.Context) (*Car, error) { + _node, _spec := cc.createSpec() + if err := sqlgraph.CreateNode(ctx, cc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + return _node, nil +} + +func (cc *CarCreate) createSpec() (*Car, *sqlgraph.CreateSpec) { + var ( + _node = &Car{config: cc.config} + _spec = &sqlgraph.CreateSpec{ + Table: car.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: car.FieldID, + }, + } + ) + if nodes := cc.mutation.OwnerIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: true, + Table: car.OwnerTable, + Columns: []string{car.OwnerColumn}, + 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) + } + _node.user_car = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// CarCreateBulk is the builder for creating many Car entities in bulk. +type CarCreateBulk struct { + config + builders []*CarCreate +} + +// Save creates the Car entities in the database. +func (ccb *CarCreateBulk) Save(ctx context.Context) ([]*Car, error) { + specs := make([]*sqlgraph.CreateSpec, len(ccb.builders)) + nodes := make([]*Car, len(ccb.builders)) + mutators := make([]Mutator, len(ccb.builders)) + for i := range ccb.builders { + func(i int, root context.Context) { + builder := ccb.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*CarMutation) + 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, ccb.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, ccb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + mutation.done = true + if specs[i].ID.Value != nil { + 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, ccb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (ccb *CarCreateBulk) SaveX(ctx context.Context) []*Car { + v, err := ccb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (ccb *CarCreateBulk) Exec(ctx context.Context) error { + _, err := ccb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ccb *CarCreateBulk) ExecX(ctx context.Context) { + if err := ccb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entc/integration/migrate/versioned/car_delete.go b/entc/integration/migrate/versioned/car_delete.go new file mode 100644 index 000000000..886d3f9ad --- /dev/null +++ b/entc/integration/migrate/versioned/car_delete.go @@ -0,0 +1,115 @@ +// 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 versioned + +import ( + "context" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/migrate/versioned/car" + "entgo.io/ent/entc/integration/migrate/versioned/predicate" + "entgo.io/ent/schema/field" +) + +// CarDelete is the builder for deleting a Car entity. +type CarDelete struct { + config + hooks []Hook + mutation *CarMutation +} + +// Where appends a list predicates to the CarDelete builder. +func (cd *CarDelete) Where(ps ...predicate.Car) *CarDelete { + cd.mutation.Where(ps...) + return cd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (cd *CarDelete) Exec(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(cd.hooks) == 0 { + affected, err = cd.sqlExec(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*CarMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + cd.mutation = mutation + affected, err = cd.sqlExec(ctx) + mutation.done = true + return affected, err + }) + for i := len(cd.hooks) - 1; i >= 0; i-- { + if cd.hooks[i] == nil { + return 0, fmt.Errorf("versioned: uninitialized hook (forgotten import versioned/runtime?)") + } + mut = cd.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, cd.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// ExecX is like Exec, but panics if an error occurs. +func (cd *CarDelete) ExecX(ctx context.Context) int { + n, err := cd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (cd *CarDelete) sqlExec(ctx context.Context) (int, error) { + _spec := &sqlgraph.DeleteSpec{ + Node: &sqlgraph.NodeSpec{ + Table: car.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: car.FieldID, + }, + }, + } + if ps := cd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return sqlgraph.DeleteNodes(ctx, cd.driver, _spec) +} + +// CarDeleteOne is the builder for deleting a single Car entity. +type CarDeleteOne struct { + cd *CarDelete +} + +// Exec executes the deletion query. +func (cdo *CarDeleteOne) Exec(ctx context.Context) error { + n, err := cdo.cd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{car.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (cdo *CarDeleteOne) ExecX(ctx context.Context) { + cdo.cd.ExecX(ctx) +} diff --git a/entc/integration/migrate/versioned/car_query.go b/entc/integration/migrate/versioned/car_query.go new file mode 100644 index 000000000..86837a98b --- /dev/null +++ b/entc/integration/migrate/versioned/car_query.go @@ -0,0 +1,980 @@ +// 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 versioned + +import ( + "context" + "errors" + "fmt" + "math" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/migrate/versioned/car" + "entgo.io/ent/entc/integration/migrate/versioned/predicate" + "entgo.io/ent/entc/integration/migrate/versioned/user" + "entgo.io/ent/schema/field" +) + +// CarQuery is the builder for querying Car entities. +type CarQuery struct { + config + limit *int + offset *int + unique *bool + order []OrderFunc + fields []string + predicates []predicate.Car + // eager-loading edges. + withOwner *UserQuery + withFKs bool + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the CarQuery builder. +func (cq *CarQuery) Where(ps ...predicate.Car) *CarQuery { + cq.predicates = append(cq.predicates, ps...) + return cq +} + +// Limit adds a limit step to the query. +func (cq *CarQuery) Limit(limit int) *CarQuery { + cq.limit = &limit + return cq +} + +// Offset adds an offset step to the query. +func (cq *CarQuery) Offset(offset int) *CarQuery { + cq.offset = &offset + return cq +} + +// 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 (cq *CarQuery) Unique(unique bool) *CarQuery { + cq.unique = &unique + return cq +} + +// Order adds an order step to the query. +func (cq *CarQuery) Order(o ...OrderFunc) *CarQuery { + cq.order = append(cq.order, o...) + return cq +} + +// QueryOwner chains the current query on the "owner" edge. +func (cq *CarQuery) QueryOwner() *UserQuery { + query := &UserQuery{config: cq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := cq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := cq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(car.Table, car.FieldID, selector), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, car.OwnerTable, car.OwnerColumn), + ) + fromU = sqlgraph.SetNeighbors(cq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first Car entity from the query. +// Returns a *NotFoundError when no Car was found. +func (cq *CarQuery) First(ctx context.Context) (*Car, error) { + nodes, err := cq.Limit(1).All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{car.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (cq *CarQuery) FirstX(ctx context.Context) *Car { + node, err := cq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Car ID from the query. +// Returns a *NotFoundError when no Car ID was found. +func (cq *CarQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = cq.Limit(1).IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{car.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (cq *CarQuery) FirstIDX(ctx context.Context) int { + id, err := cq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Car entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Car entity is found. +// Returns a *NotFoundError when no Car entities are found. +func (cq *CarQuery) Only(ctx context.Context) (*Car, error) { + nodes, err := cq.Limit(2).All(ctx) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{car.Label} + default: + return nil, &NotSingularError{car.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (cq *CarQuery) OnlyX(ctx context.Context) *Car { + node, err := cq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Car ID in the query. +// Returns a *NotSingularError when more than one Car ID is found. +// Returns a *NotFoundError when no entities are found. +func (cq *CarQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = cq.Limit(2).IDs(ctx); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{car.Label} + default: + err = &NotSingularError{car.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (cq *CarQuery) OnlyIDX(ctx context.Context) int { + id, err := cq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Cars. +func (cq *CarQuery) All(ctx context.Context) ([]*Car, error) { + if err := cq.prepareQuery(ctx); err != nil { + return nil, err + } + return cq.sqlAll(ctx) +} + +// AllX is like All, but panics if an error occurs. +func (cq *CarQuery) AllX(ctx context.Context) []*Car { + nodes, err := cq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Car IDs. +func (cq *CarQuery) IDs(ctx context.Context) ([]int, error) { + var ids []int + if err := cq.Select(car.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (cq *CarQuery) IDsX(ctx context.Context) []int { + ids, err := cq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (cq *CarQuery) Count(ctx context.Context) (int, error) { + if err := cq.prepareQuery(ctx); err != nil { + return 0, err + } + return cq.sqlCount(ctx) +} + +// CountX is like Count, but panics if an error occurs. +func (cq *CarQuery) CountX(ctx context.Context) int { + count, err := cq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (cq *CarQuery) Exist(ctx context.Context) (bool, error) { + if err := cq.prepareQuery(ctx); err != nil { + return false, err + } + return cq.sqlExist(ctx) +} + +// ExistX is like Exist, but panics if an error occurs. +func (cq *CarQuery) ExistX(ctx context.Context) bool { + exist, err := cq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the CarQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (cq *CarQuery) Clone() *CarQuery { + if cq == nil { + return nil + } + return &CarQuery{ + config: cq.config, + limit: cq.limit, + offset: cq.offset, + order: append([]OrderFunc{}, cq.order...), + predicates: append([]predicate.Car{}, cq.predicates...), + withOwner: cq.withOwner.Clone(), + // clone intermediate query. + sql: cq.sql.Clone(), + path: cq.path, + unique: cq.unique, + } +} + +// WithOwner tells the query-builder to eager-load the nodes that are connected to +// the "owner" edge. The optional arguments are used to configure the query builder of the edge. +func (cq *CarQuery) WithOwner(opts ...func(*UserQuery)) *CarQuery { + query := &UserQuery{config: cq.config} + for _, opt := range opts { + opt(query) + } + cq.withOwner = query + return cq +} + +// 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 (cq *CarQuery) GroupBy(field string, fields ...string) *CarGroupBy { + group := &CarGroupBy{config: cq.config} + group.fields = append([]string{field}, fields...) + group.path = func(ctx context.Context) (prev *sql.Selector, err error) { + if err := cq.prepareQuery(ctx); err != nil { + return nil, err + } + return cq.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. +func (cq *CarQuery) Select(fields ...string) *CarSelect { + cq.fields = append(cq.fields, fields...) + return &CarSelect{CarQuery: cq} +} + +func (cq *CarQuery) prepareQuery(ctx context.Context) error { + for _, f := range cq.fields { + if !car.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("versioned: invalid field %q for query", f)} + } + } + if cq.path != nil { + prev, err := cq.path(ctx) + if err != nil { + return err + } + cq.sql = prev + } + return nil +} + +func (cq *CarQuery) sqlAll(ctx context.Context) ([]*Car, error) { + var ( + nodes = []*Car{} + withFKs = cq.withFKs + _spec = cq.querySpec() + loadedTypes = [1]bool{ + cq.withOwner != nil, + } + ) + if cq.withOwner != nil { + withFKs = true + } + if withFKs { + _spec.Node.Columns = append(_spec.Node.Columns, car.ForeignKeys...) + } + _spec.ScanValues = func(columns []string) ([]interface{}, error) { + node := &Car{config: cq.config} + nodes = append(nodes, node) + return node.scanValues(columns) + } + _spec.Assign = func(columns []string, values []interface{}) error { + if len(nodes) == 0 { + return fmt.Errorf("versioned: Assign called without calling ScanValues") + } + node := nodes[len(nodes)-1] + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if err := sqlgraph.QueryNodes(ctx, cq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + + if query := cq.withOwner; query != nil { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*Car) + for i := range nodes { + if nodes[i].user_car == nil { + continue + } + fk := *nodes[i].user_car + if _, ok := nodeids[fk]; !ok { + 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 "user_car" returned %v`, n.ID) + } + for i := range nodes { + nodes[i].Edges.Owner = n + } + } + } + + return nodes, nil +} + +func (cq *CarQuery) sqlCount(ctx context.Context) (int, error) { + _spec := cq.querySpec() + _spec.Node.Columns = cq.fields + if len(cq.fields) > 0 { + _spec.Unique = cq.unique != nil && *cq.unique + } + return sqlgraph.CountNodes(ctx, cq.driver, _spec) +} + +func (cq *CarQuery) sqlExist(ctx context.Context) (bool, error) { + n, err := cq.sqlCount(ctx) + if err != nil { + return false, fmt.Errorf("versioned: check existence: %w", err) + } + return n > 0, nil +} + +func (cq *CarQuery) querySpec() *sqlgraph.QuerySpec { + _spec := &sqlgraph.QuerySpec{ + Node: &sqlgraph.NodeSpec{ + Table: car.Table, + Columns: car.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: car.FieldID, + }, + }, + From: cq.sql, + Unique: true, + } + if unique := cq.unique; unique != nil { + _spec.Unique = *unique + } + if fields := cq.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, car.FieldID) + for i := range fields { + if fields[i] != car.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := cq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := cq.limit; limit != nil { + _spec.Limit = *limit + } + if offset := cq.offset; offset != nil { + _spec.Offset = *offset + } + if ps := cq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (cq *CarQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(cq.driver.Dialect()) + t1 := builder.Table(car.Table) + columns := cq.fields + if len(columns) == 0 { + columns = car.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if cq.sql != nil { + selector = cq.sql + selector.Select(selector.Columns(columns...)...) + } + if cq.unique != nil && *cq.unique { + selector.Distinct() + } + for _, p := range cq.predicates { + p(selector) + } + for _, p := range cq.order { + p(selector) + } + if offset := cq.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 := cq.limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// CarGroupBy is the group-by builder for Car entities. +type CarGroupBy 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 (cgb *CarGroupBy) Aggregate(fns ...AggregateFunc) *CarGroupBy { + cgb.fns = append(cgb.fns, fns...) + return cgb +} + +// Scan applies the group-by query and scans the result into the given value. +func (cgb *CarGroupBy) Scan(ctx context.Context, v interface{}) error { + query, err := cgb.path(ctx) + if err != nil { + return err + } + cgb.sql = query + return cgb.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (cgb *CarGroupBy) ScanX(ctx context.Context, v interface{}) { + if err := cgb.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 (cgb *CarGroupBy) Strings(ctx context.Context) ([]string, error) { + if len(cgb.fields) > 1 { + return nil, errors.New("versioned: CarGroupBy.Strings is not achievable when grouping more than 1 field") + } + var v []string + if err := cgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (cgb *CarGroupBy) StringsX(ctx context.Context) []string { + v, err := cgb.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 (cgb *CarGroupBy) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = cgb.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{car.Label} + default: + err = fmt.Errorf("versioned: CarGroupBy.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (cgb *CarGroupBy) StringX(ctx context.Context) string { + v, err := cgb.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 (cgb *CarGroupBy) Ints(ctx context.Context) ([]int, error) { + if len(cgb.fields) > 1 { + return nil, errors.New("versioned: CarGroupBy.Ints is not achievable when grouping more than 1 field") + } + var v []int + if err := cgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (cgb *CarGroupBy) IntsX(ctx context.Context) []int { + v, err := cgb.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 (cgb *CarGroupBy) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = cgb.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{car.Label} + default: + err = fmt.Errorf("versioned: CarGroupBy.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (cgb *CarGroupBy) IntX(ctx context.Context) int { + v, err := cgb.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 (cgb *CarGroupBy) Float64s(ctx context.Context) ([]float64, error) { + if len(cgb.fields) > 1 { + return nil, errors.New("versioned: CarGroupBy.Float64s is not achievable when grouping more than 1 field") + } + var v []float64 + if err := cgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (cgb *CarGroupBy) Float64sX(ctx context.Context) []float64 { + v, err := cgb.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 (cgb *CarGroupBy) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = cgb.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{car.Label} + default: + err = fmt.Errorf("versioned: CarGroupBy.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (cgb *CarGroupBy) Float64X(ctx context.Context) float64 { + v, err := cgb.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 (cgb *CarGroupBy) Bools(ctx context.Context) ([]bool, error) { + if len(cgb.fields) > 1 { + return nil, errors.New("versioned: CarGroupBy.Bools is not achievable when grouping more than 1 field") + } + var v []bool + if err := cgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (cgb *CarGroupBy) BoolsX(ctx context.Context) []bool { + v, err := cgb.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 (cgb *CarGroupBy) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = cgb.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{car.Label} + default: + err = fmt.Errorf("versioned: CarGroupBy.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (cgb *CarGroupBy) BoolX(ctx context.Context) bool { + v, err := cgb.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (cgb *CarGroupBy) sqlScan(ctx context.Context, v interface{}) error { + for _, f := range cgb.fields { + if !car.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + } + } + selector := cgb.sqlQuery() + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := cgb.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +func (cgb *CarGroupBy) sqlQuery() *sql.Selector { + selector := cgb.sql.Select() + aggregation := make([]string, 0, len(cgb.fns)) + for _, fn := range cgb.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(cgb.fields)+len(cgb.fns)) + for _, f := range cgb.fields { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + return selector.GroupBy(selector.Columns(cgb.fields...)...) +} + +// CarSelect is the builder for selecting fields of Car entities. +type CarSelect struct { + *CarQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector +} + +// Scan applies the selector query and scans the result into the given value. +func (cs *CarSelect) Scan(ctx context.Context, v interface{}) error { + if err := cs.prepareQuery(ctx); err != nil { + return err + } + cs.sql = cs.CarQuery.sqlQuery(ctx) + return cs.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (cs *CarSelect) ScanX(ctx context.Context, v interface{}) { + if err := cs.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from a selector. It is only allowed when selecting one field. +func (cs *CarSelect) Strings(ctx context.Context) ([]string, error) { + if len(cs.fields) > 1 { + return nil, errors.New("versioned: CarSelect.Strings is not achievable when selecting more than 1 field") + } + var v []string + if err := cs.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (cs *CarSelect) StringsX(ctx context.Context) []string { + v, err := cs.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 (cs *CarSelect) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = cs.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{car.Label} + default: + err = fmt.Errorf("versioned: CarSelect.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (cs *CarSelect) StringX(ctx context.Context) string { + v, err := cs.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 (cs *CarSelect) Ints(ctx context.Context) ([]int, error) { + if len(cs.fields) > 1 { + return nil, errors.New("versioned: CarSelect.Ints is not achievable when selecting more than 1 field") + } + var v []int + if err := cs.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (cs *CarSelect) IntsX(ctx context.Context) []int { + v, err := cs.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 (cs *CarSelect) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = cs.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{car.Label} + default: + err = fmt.Errorf("versioned: CarSelect.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (cs *CarSelect) IntX(ctx context.Context) int { + v, err := cs.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 (cs *CarSelect) Float64s(ctx context.Context) ([]float64, error) { + if len(cs.fields) > 1 { + return nil, errors.New("versioned: CarSelect.Float64s is not achievable when selecting more than 1 field") + } + var v []float64 + if err := cs.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (cs *CarSelect) Float64sX(ctx context.Context) []float64 { + v, err := cs.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 (cs *CarSelect) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = cs.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{car.Label} + default: + err = fmt.Errorf("versioned: CarSelect.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (cs *CarSelect) Float64X(ctx context.Context) float64 { + v, err := cs.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 (cs *CarSelect) Bools(ctx context.Context) ([]bool, error) { + if len(cs.fields) > 1 { + return nil, errors.New("versioned: CarSelect.Bools is not achievable when selecting more than 1 field") + } + var v []bool + if err := cs.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (cs *CarSelect) BoolsX(ctx context.Context) []bool { + v, err := cs.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 (cs *CarSelect) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = cs.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{car.Label} + default: + err = fmt.Errorf("versioned: CarSelect.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (cs *CarSelect) BoolX(ctx context.Context) bool { + v, err := cs.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (cs *CarSelect) sqlScan(ctx context.Context, v interface{}) error { + rows := &sql.Rows{} + query, args := cs.sql.Query() + if err := cs.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/entc/integration/migrate/versioned/car_update.go b/entc/integration/migrate/versioned/car_update.go new file mode 100644 index 000000000..63f0bd622 --- /dev/null +++ b/entc/integration/migrate/versioned/car_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 versioned + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/migrate/versioned/car" + "entgo.io/ent/entc/integration/migrate/versioned/predicate" + "entgo.io/ent/entc/integration/migrate/versioned/user" + "entgo.io/ent/schema/field" +) + +// CarUpdate is the builder for updating Car entities. +type CarUpdate struct { + config + hooks []Hook + mutation *CarMutation +} + +// Where appends a list predicates to the CarUpdate builder. +func (cu *CarUpdate) Where(ps ...predicate.Car) *CarUpdate { + cu.mutation.Where(ps...) + return cu +} + +// SetOwnerID sets the "owner" edge to the User entity by ID. +func (cu *CarUpdate) SetOwnerID(id int) *CarUpdate { + cu.mutation.SetOwnerID(id) + return cu +} + +// SetNillableOwnerID sets the "owner" edge to the User entity by ID if the given value is not nil. +func (cu *CarUpdate) SetNillableOwnerID(id *int) *CarUpdate { + if id != nil { + cu = cu.SetOwnerID(*id) + } + return cu +} + +// SetOwner sets the "owner" edge to the User entity. +func (cu *CarUpdate) SetOwner(u *User) *CarUpdate { + return cu.SetOwnerID(u.ID) +} + +// Mutation returns the CarMutation object of the builder. +func (cu *CarUpdate) Mutation() *CarMutation { + return cu.mutation +} + +// ClearOwner clears the "owner" edge to the User entity. +func (cu *CarUpdate) ClearOwner() *CarUpdate { + cu.mutation.ClearOwner() + return cu +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (cu *CarUpdate) Save(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(cu.hooks) == 0 { + affected, err = cu.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*CarMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + cu.mutation = mutation + affected, err = cu.sqlSave(ctx) + mutation.done = true + return affected, err + }) + for i := len(cu.hooks) - 1; i >= 0; i-- { + if cu.hooks[i] == nil { + return 0, fmt.Errorf("versioned: uninitialized hook (forgotten import versioned/runtime?)") + } + mut = cu.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, cu.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// SaveX is like Save, but panics if an error occurs. +func (cu *CarUpdate) SaveX(ctx context.Context) int { + affected, err := cu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (cu *CarUpdate) Exec(ctx context.Context) error { + _, err := cu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (cu *CarUpdate) ExecX(ctx context.Context) { + if err := cu.Exec(ctx); err != nil { + panic(err) + } +} + +func (cu *CarUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: car.Table, + Columns: car.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: car.FieldID, + }, + }, + } + if ps := cu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if cu.mutation.OwnerCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: true, + Table: car.OwnerTable, + Columns: []string{car.OwnerColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := cu.mutation.OwnerIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: true, + Table: car.OwnerTable, + Columns: []string{car.OwnerColumn}, + 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, cu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{car.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return 0, err + } + return n, nil +} + +// CarUpdateOne is the builder for updating a single Car entity. +type CarUpdateOne struct { + config + fields []string + hooks []Hook + mutation *CarMutation +} + +// SetOwnerID sets the "owner" edge to the User entity by ID. +func (cuo *CarUpdateOne) SetOwnerID(id int) *CarUpdateOne { + cuo.mutation.SetOwnerID(id) + return cuo +} + +// SetNillableOwnerID sets the "owner" edge to the User entity by ID if the given value is not nil. +func (cuo *CarUpdateOne) SetNillableOwnerID(id *int) *CarUpdateOne { + if id != nil { + cuo = cuo.SetOwnerID(*id) + } + return cuo +} + +// SetOwner sets the "owner" edge to the User entity. +func (cuo *CarUpdateOne) SetOwner(u *User) *CarUpdateOne { + return cuo.SetOwnerID(u.ID) +} + +// Mutation returns the CarMutation object of the builder. +func (cuo *CarUpdateOne) Mutation() *CarMutation { + return cuo.mutation +} + +// ClearOwner clears the "owner" edge to the User entity. +func (cuo *CarUpdateOne) ClearOwner() *CarUpdateOne { + cuo.mutation.ClearOwner() + return cuo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (cuo *CarUpdateOne) Select(field string, fields ...string) *CarUpdateOne { + cuo.fields = append([]string{field}, fields...) + return cuo +} + +// Save executes the query and returns the updated Car entity. +func (cuo *CarUpdateOne) Save(ctx context.Context) (*Car, error) { + var ( + err error + node *Car + ) + if len(cuo.hooks) == 0 { + node, err = cuo.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*CarMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + cuo.mutation = mutation + node, err = cuo.sqlSave(ctx) + mutation.done = true + return node, err + }) + for i := len(cuo.hooks) - 1; i >= 0; i-- { + if cuo.hooks[i] == nil { + return nil, fmt.Errorf("versioned: uninitialized hook (forgotten import versioned/runtime?)") + } + mut = cuo.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, cuo.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX is like Save, but panics if an error occurs. +func (cuo *CarUpdateOne) SaveX(ctx context.Context) *Car { + node, err := cuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (cuo *CarUpdateOne) Exec(ctx context.Context) error { + _, err := cuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (cuo *CarUpdateOne) ExecX(ctx context.Context) { + if err := cuo.Exec(ctx); err != nil { + panic(err) + } +} + +func (cuo *CarUpdateOne) sqlSave(ctx context.Context) (_node *Car, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: car.Table, + Columns: car.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: car.FieldID, + }, + }, + } + id, ok := cuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`versioned: missing "Car.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := cuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, car.FieldID) + for _, f := range fields { + if !car.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("versioned: invalid field %q for query", f)} + } + if f != car.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := cuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if cuo.mutation.OwnerCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: true, + Table: car.OwnerTable, + Columns: []string{car.OwnerColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := cuo.mutation.OwnerIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: true, + Table: car.OwnerTable, + Columns: []string{car.OwnerColumn}, + 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 = &Car{config: cuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, cuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{car.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + return _node, nil +} diff --git a/entc/integration/migrate/versioned/client.go b/entc/integration/migrate/versioned/client.go new file mode 100644 index 000000000..5d4573771 --- /dev/null +++ b/entc/integration/migrate/versioned/client.go @@ -0,0 +1,395 @@ +// 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 versioned + +import ( + "context" + "fmt" + "log" + + "entgo.io/ent/entc/integration/migrate/versioned/migrate" + + "entgo.io/ent/entc/integration/migrate/versioned/car" + "entgo.io/ent/entc/integration/migrate/versioned/user" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +// Client is the client that holds all ent builders. +type Client struct { + config + // Schema is the client for creating, migrating and dropping schema. + Schema *migrate.Schema + // Car is the client for interacting with the Car builders. + Car *CarClient + // User is the client for interacting with the User builders. + User *UserClient +} + +// NewClient creates a new client configured with the given options. +func NewClient(opts ...Option) *Client { + cfg := config{log: log.Println, hooks: &hooks{}} + cfg.options(opts...) + client := &Client{config: cfg} + client.init() + return client +} + +func (c *Client) init() { + c.Schema = migrate.NewSchema(c.driver) + c.Car = NewCarClient(c.config) + c.User = NewUserClient(c.config) +} + +// Open opens a database/sql.DB specified by the driver name and +// the data source name, and returns a new client attached to it. +// Optional parameters can be added for configuring the client. +func Open(driverName, dataSourceName string, options ...Option) (*Client, error) { + switch driverName { + case dialect.MySQL, dialect.Postgres, dialect.SQLite: + drv, err := sql.Open(driverName, dataSourceName) + if err != nil { + return nil, err + } + return NewClient(append(options, Driver(drv))...), nil + default: + return nil, fmt.Errorf("unsupported driver: %q", driverName) + } +} + +// Tx returns a new transactional client. The provided context +// is used until the transaction is committed or rolled back. +func (c *Client) Tx(ctx context.Context) (*Tx, error) { + if _, ok := c.driver.(*txDriver); ok { + return nil, fmt.Errorf("versioned: cannot start a transaction within a transaction") + } + tx, err := newTx(ctx, c.driver) + if err != nil { + return nil, fmt.Errorf("versioned: starting a transaction: %w", err) + } + cfg := c.config + cfg.driver = tx + return &Tx{ + ctx: ctx, + config: cfg, + Car: NewCarClient(cfg), + User: NewUserClient(cfg), + }, nil +} + +// BeginTx returns a transactional client with specified options. +func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) { + if _, ok := c.driver.(*txDriver); ok { + return nil, fmt.Errorf("ent: cannot start a transaction within a transaction") + } + tx, err := c.driver.(interface { + BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error) + }).BeginTx(ctx, opts) + if err != nil { + return nil, fmt.Errorf("ent: starting a transaction: %w", err) + } + cfg := c.config + cfg.driver = &txDriver{tx: tx, drv: c.driver} + return &Tx{ + ctx: ctx, + config: cfg, + Car: NewCarClient(cfg), + User: NewUserClient(cfg), + }, nil +} + +// Debug returns a new debug-client. It's used to get verbose logging on specific operations. +// +// client.Debug(). +// Car. +// Query(). +// Count(ctx) +// +func (c *Client) Debug() *Client { + if c.debug { + return c + } + cfg := c.config + cfg.driver = dialect.Debug(c.driver, c.log) + client := &Client{config: cfg} + client.init() + return client +} + +// Close closes the database connection and prevents new queries from starting. +func (c *Client) Close() error { + return c.driver.Close() +} + +// 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.Car.Use(hooks...) + c.User.Use(hooks...) +} + +// CarClient is a client for the Car schema. +type CarClient struct { + config +} + +// NewCarClient returns a client for the Car from the given config. +func NewCarClient(c config) *CarClient { + return &CarClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `car.Hooks(f(g(h())))`. +func (c *CarClient) Use(hooks ...Hook) { + c.hooks.Car = append(c.hooks.Car, hooks...) +} + +// Create returns a create builder for Car. +func (c *CarClient) Create() *CarCreate { + mutation := newCarMutation(c.config, OpCreate) + return &CarCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Car entities. +func (c *CarClient) CreateBulk(builders ...*CarCreate) *CarCreateBulk { + return &CarCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Car. +func (c *CarClient) Update() *CarUpdate { + mutation := newCarMutation(c.config, OpUpdate) + return &CarUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *CarClient) UpdateOne(ca *Car) *CarUpdateOne { + mutation := newCarMutation(c.config, OpUpdateOne, withCar(ca)) + return &CarUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *CarClient) UpdateOneID(id int) *CarUpdateOne { + mutation := newCarMutation(c.config, OpUpdateOne, withCarID(id)) + return &CarUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Car. +func (c *CarClient) Delete() *CarDelete { + mutation := newCarMutation(c.config, OpDelete) + return &CarDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a delete builder for the given entity. +func (c *CarClient) DeleteOne(ca *Car) *CarDeleteOne { + return c.DeleteOneID(ca.ID) +} + +// DeleteOneID returns a delete builder for the given id. +func (c *CarClient) DeleteOneID(id int) *CarDeleteOne { + builder := c.Delete().Where(car.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &CarDeleteOne{builder} +} + +// Query returns a query builder for Car. +func (c *CarClient) Query() *CarQuery { + return &CarQuery{ + config: c.config, + } +} + +// Get returns a Car entity by its id. +func (c *CarClient) Get(ctx context.Context, id int) (*Car, error) { + return c.Query().Where(car.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *CarClient) GetX(ctx context.Context, id int) *Car { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryOwner queries the owner edge of a Car. +func (c *CarClient) QueryOwner(ca *Car) *UserQuery { + query := &UserQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := ca.ID + step := sqlgraph.NewStep( + sqlgraph.From(car.Table, car.FieldID, id), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.O2O, true, car.OwnerTable, car.OwnerColumn), + ) + fromV = sqlgraph.Neighbors(ca.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *CarClient) Hooks() []Hook { + return c.hooks.Car +} + +// UserClient is a client for the User schema. +type UserClient struct { + config +} + +// NewUserClient returns a client for the User from the given config. +func NewUserClient(c config) *UserClient { + return &UserClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `user.Hooks(f(g(h())))`. +func (c *UserClient) Use(hooks ...Hook) { + c.hooks.User = append(c.hooks.User, hooks...) +} + +// Create returns a create builder for User. +func (c *UserClient) Create() *UserCreate { + mutation := newUserMutation(c.config, OpCreate) + return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of User entities. +func (c *UserClient) CreateBulk(builders ...*UserCreate) *UserCreateBulk { + return &UserCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for User. +func (c *UserClient) Update() *UserUpdate { + mutation := newUserMutation(c.config, OpUpdate) + return &UserUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *UserClient) UpdateOne(u *User) *UserUpdateOne { + mutation := newUserMutation(c.config, OpUpdateOne, withUser(u)) + return &UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *UserClient) UpdateOneID(id int) *UserUpdateOne { + mutation := newUserMutation(c.config, OpUpdateOne, withUserID(id)) + return &UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for User. +func (c *UserClient) Delete() *UserDelete { + mutation := newUserMutation(c.config, OpDelete) + return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a delete builder for the given entity. +func (c *UserClient) DeleteOne(u *User) *UserDeleteOne { + return c.DeleteOneID(u.ID) +} + +// DeleteOneID returns a delete builder for the given id. +func (c *UserClient) DeleteOneID(id int) *UserDeleteOne { + builder := c.Delete().Where(user.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &UserDeleteOne{builder} +} + +// Query returns a query builder for User. +func (c *UserClient) Query() *UserQuery { + return &UserQuery{ + config: c.config, + } +} + +// Get returns a User entity by its id. +func (c *UserClient) Get(ctx context.Context, id int) (*User, error) { + return c.Query().Where(user.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *UserClient) GetX(ctx context.Context, id int) *User { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryParent queries the parent edge of a User. +func (c *UserClient) QueryParent(u *User) *UserQuery { + query := &UserQuery{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(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, user.ParentTable, user.ParentColumn), + ) + fromV = sqlgraph.Neighbors(u.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryChildren queries the children edge of a User. +func (c *UserClient) QueryChildren(u *User) *UserQuery { + query := &UserQuery{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(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, user.ChildrenTable, user.ChildrenColumn), + ) + fromV = sqlgraph.Neighbors(u.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QuerySpouse queries the spouse edge of a User. +func (c *UserClient) QuerySpouse(u *User) *UserQuery { + query := &UserQuery{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(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, user.SpouseTable, user.SpouseColumn), + ) + fromV = sqlgraph.Neighbors(u.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryCar queries the car edge of a User. +func (c *UserClient) QueryCar(u *User) *CarQuery { + query := &CarQuery{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(car.Table, car.FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, user.CarTable, user.CarColumn), + ) + 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/migrate/versioned/config.go b/entc/integration/migrate/versioned/config.go new file mode 100644 index 000000000..4919e5a73 --- /dev/null +++ b/entc/integration/migrate/versioned/config.go @@ -0,0 +1,64 @@ +// 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 versioned + +import ( + "entgo.io/ent" + "entgo.io/ent/dialect" +) + +// Option function to configure the client. +type Option func(*config) + +// Config is the configuration for the client and its builder. +type config struct { + // driver used for executing database requests. + driver dialect.Driver + // debug enable a debug logging. + debug bool + // log used for logging on debug mode. + log func(...interface{}) + // hooks to execute on mutations. + hooks *hooks +} + +// hooks per client, for fast access. +type hooks struct { + Car []ent.Hook + User []ent.Hook +} + +// Options applies the options on the config object. +func (c *config) options(opts ...Option) { + for _, opt := range opts { + opt(c) + } + if c.debug { + c.driver = dialect.Debug(c.driver, c.log) + } +} + +// Debug enables debug logging on the ent.Driver. +func Debug() Option { + return func(c *config) { + c.debug = true + } +} + +// Log sets the logging function for debug mode. +func Log(fn func(...interface{})) Option { + return func(c *config) { + c.log = fn + } +} + +// Driver configures the client driver. +func Driver(driver dialect.Driver) Option { + return func(c *config) { + c.driver = driver + } +} diff --git a/entc/integration/migrate/versioned/context.go b/entc/integration/migrate/versioned/context.go new file mode 100644 index 000000000..542db0680 --- /dev/null +++ b/entc/integration/migrate/versioned/context.go @@ -0,0 +1,37 @@ +// 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 versioned + +import ( + "context" +) + +type clientCtxKey struct{} + +// FromContext returns a Client stored inside a context, or nil if there isn't one. +func FromContext(ctx context.Context) *Client { + c, _ := ctx.Value(clientCtxKey{}).(*Client) + return c +} + +// NewContext returns a new context with the given Client attached. +func NewContext(parent context.Context, c *Client) context.Context { + return context.WithValue(parent, clientCtxKey{}, c) +} + +type txCtxKey struct{} + +// TxFromContext returns a Tx stored inside a context, or nil if there isn't one. +func TxFromContext(ctx context.Context) *Tx { + tx, _ := ctx.Value(txCtxKey{}).(*Tx) + return tx +} + +// NewTxContext returns a new context with the given Tx attached. +func NewTxContext(parent context.Context, tx *Tx) context.Context { + return context.WithValue(parent, txCtxKey{}, tx) +} diff --git a/entc/integration/migrate/versioned/ent.go b/entc/integration/migrate/versioned/ent.go new file mode 100644 index 000000000..d4ee5e897 --- /dev/null +++ b/entc/integration/migrate/versioned/ent.go @@ -0,0 +1,265 @@ +// 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 versioned + +import ( + "errors" + "fmt" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/entc/integration/migrate/versioned/car" + "entgo.io/ent/entc/integration/migrate/versioned/user" +) + +// ent aliases to avoid import conflicts in user's code. +type ( + Op = ent.Op + Hook = ent.Hook + Value = ent.Value + Query = ent.Query + Policy = ent.Policy + Mutator = ent.Mutator + Mutation = ent.Mutation + MutateFunc = ent.MutateFunc +) + +// OrderFunc applies an ordering on the sql selector. +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{ + car.Table: car.ValidColumn, + user.Table: user.ValidColumn, + } + check, ok := checks[table] + if !ok { + return func(string) error { + return fmt.Errorf("unknown table %q", table) + } + } + return func(column string) error { + if !check(column) { + return fmt.Errorf("unknown column %q for table %q", column, table) + } + return nil + } +} + +// Asc applies the given fields in ASC order. +func Asc(fields ...string) OrderFunc { + return func(s *sql.Selector) { + check := columnChecker(s.TableName()) + for _, f := range fields { + if err := check(f); err != nil { + s.AddError(&ValidationError{Name: f, err: fmt.Errorf("versioned: %w", err)}) + } + s.OrderBy(sql.Asc(s.C(f))) + } + } +} + +// Desc applies the given fields in DESC order. +func Desc(fields ...string) OrderFunc { + return func(s *sql.Selector) { + check := columnChecker(s.TableName()) + for _, f := range fields { + if err := check(f); err != nil { + s.AddError(&ValidationError{Name: f, err: fmt.Errorf("versioned: %w", err)}) + } + s.OrderBy(sql.Desc(s.C(f))) + } + } +} + +// AggregateFunc applies an aggregation step on the group-by traversal/selector. +type AggregateFunc func(*sql.Selector) string + +// As is a pseudo aggregation function for renaming another other functions with custom names. For example: +// +// GroupBy(field1, field2). +// Aggregate(versioned.As(versioned.Sum(field1), "sum_field1"), (versioned.As(versioned.Sum(field2), "sum_field2")). +// Scan(ctx, &v) +// +func As(fn AggregateFunc, end string) AggregateFunc { + return func(s *sql.Selector) string { + return sql.As(fn(s), end) + } +} + +// Count applies the "count" aggregation function on each group. +func Count() AggregateFunc { + return func(s *sql.Selector) string { + return sql.Count("*") + } +} + +// Max applies the "max" aggregation function on the given field of each group. +func Max(field string) AggregateFunc { + return func(s *sql.Selector) string { + check := columnChecker(s.TableName()) + if err := check(field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("versioned: %w", err)}) + return "" + } + return sql.Max(s.C(field)) + } +} + +// Mean applies the "mean" aggregation function on the given field of each group. +func Mean(field string) AggregateFunc { + return func(s *sql.Selector) string { + check := columnChecker(s.TableName()) + if err := check(field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("versioned: %w", err)}) + return "" + } + return sql.Avg(s.C(field)) + } +} + +// Min applies the "min" aggregation function on the given field of each group. +func Min(field string) AggregateFunc { + return func(s *sql.Selector) string { + check := columnChecker(s.TableName()) + if err := check(field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("versioned: %w", err)}) + return "" + } + return sql.Min(s.C(field)) + } +} + +// Sum applies the "sum" aggregation function on the given field of each group. +func Sum(field string) AggregateFunc { + return func(s *sql.Selector) string { + check := columnChecker(s.TableName()) + if err := check(field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("versioned: %w", err)}) + return "" + } + return sql.Sum(s.C(field)) + } +} + +// ValidationError returns when validating a field or edge fails. +type ValidationError struct { + Name string // Field or edge name. + err error +} + +// Error implements the error interface. +func (e *ValidationError) Error() string { + return e.err.Error() +} + +// Unwrap implements the errors.Wrapper interface. +func (e *ValidationError) Unwrap() error { + return e.err +} + +// IsValidationError returns a boolean indicating whether the error is a validation error. +func IsValidationError(err error) bool { + if err == nil { + return false + } + var e *ValidationError + return errors.As(err, &e) +} + +// NotFoundError returns when trying to fetch a specific entity and it was not found in the database. +type NotFoundError struct { + label string +} + +// Error implements the error interface. +func (e *NotFoundError) Error() string { + return "versioned: " + e.label + " not found" +} + +// IsNotFound returns a boolean indicating whether the error is a not found error. +func IsNotFound(err error) bool { + if err == nil { + return false + } + var e *NotFoundError + return errors.As(err, &e) +} + +// MaskNotFound masks not found error. +func MaskNotFound(err error) error { + if IsNotFound(err) { + return nil + } + return err +} + +// NotSingularError returns when trying to fetch a singular entity and more then one was found in the database. +type NotSingularError struct { + label string +} + +// Error implements the error interface. +func (e *NotSingularError) Error() string { + return "versioned: " + e.label + " not singular" +} + +// IsNotSingular returns a boolean indicating whether the error is a not singular error. +func IsNotSingular(err error) bool { + if err == nil { + return false + } + var e *NotSingularError + return errors.As(err, &e) +} + +// NotLoadedError returns when trying to get a node that was not loaded by the query. +type NotLoadedError struct { + edge string +} + +// Error implements the error interface. +func (e *NotLoadedError) Error() string { + return "versioned: " + e.edge + " edge was not loaded" +} + +// IsNotLoaded returns a boolean indicating whether the error is a not loaded error. +func IsNotLoaded(err error) bool { + if err == nil { + return false + } + var e *NotLoadedError + return errors.As(err, &e) +} + +// ConstraintError returns when trying to create/update one or more entities and +// one or more of their constraints failed. For example, violation of edge or +// field uniqueness. +type ConstraintError struct { + msg string + wrap error +} + +// Error implements the error interface. +func (e ConstraintError) Error() string { + return "versioned: constraint failed: " + e.msg +} + +// Unwrap implements the errors.Wrapper interface. +func (e *ConstraintError) Unwrap() error { + return e.wrap +} + +// IsConstraintError returns a boolean indicating whether the error is a constraint failure. +func IsConstraintError(err error) bool { + if err == nil { + return false + } + var e *ConstraintError + return errors.As(err, &e) +} diff --git a/entc/integration/migrate/versioned/enttest/enttest.go b/entc/integration/migrate/versioned/enttest/enttest.go new file mode 100644 index 000000000..9ffcb9548 --- /dev/null +++ b/entc/integration/migrate/versioned/enttest/enttest.go @@ -0,0 +1,82 @@ +// 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 enttest + +import ( + "context" + + "entgo.io/ent/entc/integration/migrate/versioned" + // required by schema hooks. + _ "entgo.io/ent/entc/integration/migrate/versioned/runtime" + + "entgo.io/ent/dialect/sql/schema" +) + +type ( + // TestingT is the interface that is shared between + // testing.T and testing.B and used by enttest. + TestingT interface { + FailNow() + Error(...interface{}) + } + + // Option configures client creation. + Option func(*options) + + options struct { + opts []versioned.Option + migrateOpts []schema.MigrateOption + } +) + +// WithOptions forwards options to client creation. +func WithOptions(opts ...versioned.Option) Option { + return func(o *options) { + o.opts = append(o.opts, opts...) + } +} + +// WithMigrateOptions forwards options to auto migration. +func WithMigrateOptions(opts ...schema.MigrateOption) Option { + return func(o *options) { + o.migrateOpts = append(o.migrateOpts, opts...) + } +} + +func newOptions(opts []Option) *options { + o := &options{} + for _, opt := range opts { + opt(o) + } + return o +} + +// Open calls versioned.Open and auto-run migration. +func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *versioned.Client { + o := newOptions(opts) + c, err := versioned.Open(driverName, dataSourceName, o.opts...) + if err != nil { + t.Error(err) + t.FailNow() + } + if err := c.Schema.Create(context.Background(), o.migrateOpts...); err != nil { + t.Error(err) + t.FailNow() + } + return c +} + +// NewClient calls versioned.NewClient and auto-run migration. +func NewClient(t TestingT, opts ...Option) *versioned.Client { + o := newOptions(opts) + c := versioned.NewClient(o.opts...) + if err := c.Schema.Create(context.Background(), o.migrateOpts...); err != nil { + t.Error(err) + t.FailNow() + } + return c +} diff --git a/entc/integration/migrate/versioned/generate.go b/entc/integration/migrate/versioned/generate.go new file mode 100644 index 000000000..60ded724c --- /dev/null +++ b/entc/integration/migrate/versioned/generate.go @@ -0,0 +1,7 @@ +// 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 versioned + +//go:generate go run -mod=mod entgo.io/ent/cmd/ent generate --feature sql/versioned-migrations --header "// Copyright 2019-present Facebook Inc. All rights reserved.\n// This source code is licensed under the Apache 2.0 license found\n// in the LICENSE file in the root directory of this source tree.\n\n// Code generated by entc, DO NOT EDIT." ./schema diff --git a/entc/integration/migrate/versioned/hook/hook.go b/entc/integration/migrate/versioned/hook/hook.go new file mode 100644 index 000000000..e2d028e23 --- /dev/null +++ b/entc/integration/migrate/versioned/hook/hook.go @@ -0,0 +1,221 @@ +// 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 hook + +import ( + "context" + "fmt" + + "entgo.io/ent/entc/integration/migrate/versioned" +) + +// The CarFunc type is an adapter to allow the use of ordinary +// function as Car mutator. +type CarFunc func(context.Context, *versioned.CarMutation) (versioned.Value, error) + +// Mutate calls f(ctx, m). +func (f CarFunc) Mutate(ctx context.Context, m versioned.Mutation) (versioned.Value, error) { + mv, ok := m.(*versioned.CarMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T. expect *versioned.CarMutation", m) + } + return f(ctx, mv) +} + +// The UserFunc type is an adapter to allow the use of ordinary +// function as User mutator. +type UserFunc func(context.Context, *versioned.UserMutation) (versioned.Value, error) + +// Mutate calls f(ctx, m). +func (f UserFunc) Mutate(ctx context.Context, m versioned.Mutation) (versioned.Value, error) { + mv, ok := m.(*versioned.UserMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T. expect *versioned.UserMutation", m) + } + return f(ctx, mv) +} + +// Condition is a hook condition function. +type Condition func(context.Context, versioned.Mutation) bool + +// And groups conditions with the AND operator. +func And(first, second Condition, rest ...Condition) Condition { + return func(ctx context.Context, m versioned.Mutation) bool { + if !first(ctx, m) || !second(ctx, m) { + return false + } + for _, cond := range rest { + if !cond(ctx, m) { + return false + } + } + return true + } +} + +// Or groups conditions with the OR operator. +func Or(first, second Condition, rest ...Condition) Condition { + return func(ctx context.Context, m versioned.Mutation) bool { + if first(ctx, m) || second(ctx, m) { + return true + } + for _, cond := range rest { + if cond(ctx, m) { + return true + } + } + return false + } +} + +// Not negates a given condition. +func Not(cond Condition) Condition { + return func(ctx context.Context, m versioned.Mutation) bool { + return !cond(ctx, m) + } +} + +// HasOp is a condition testing mutation operation. +func HasOp(op versioned.Op) Condition { + return func(_ context.Context, m versioned.Mutation) bool { + return m.Op().Is(op) + } +} + +// HasAddedFields is a condition validating `.AddedField` on fields. +func HasAddedFields(field string, fields ...string) Condition { + return func(_ context.Context, m versioned.Mutation) bool { + if _, exists := m.AddedField(field); !exists { + return false + } + for _, field := range fields { + if _, exists := m.AddedField(field); !exists { + return false + } + } + return true + } +} + +// HasClearedFields is a condition validating `.FieldCleared` on fields. +func HasClearedFields(field string, fields ...string) Condition { + return func(_ context.Context, m versioned.Mutation) bool { + if exists := m.FieldCleared(field); !exists { + return false + } + for _, field := range fields { + if exists := m.FieldCleared(field); !exists { + return false + } + } + return true + } +} + +// HasFields is a condition validating `.Field` on fields. +func HasFields(field string, fields ...string) Condition { + return func(_ context.Context, m versioned.Mutation) bool { + if _, exists := m.Field(field); !exists { + return false + } + for _, field := range fields { + if _, exists := m.Field(field); !exists { + return false + } + } + return true + } +} + +// If executes the given hook under condition. +// +// hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...))) +// +func If(hk versioned.Hook, cond Condition) versioned.Hook { + return func(next versioned.Mutator) versioned.Mutator { + return versioned.MutateFunc(func(ctx context.Context, m versioned.Mutation) (versioned.Value, error) { + if cond(ctx, m) { + return hk(next).Mutate(ctx, m) + } + return next.Mutate(ctx, m) + }) + } +} + +// On executes the given hook only for the given operation. +// +// hook.On(Log, versioned.Delete|versioned.Create) +// +func On(hk versioned.Hook, op versioned.Op) versioned.Hook { + return If(hk, HasOp(op)) +} + +// Unless skips the given hook only for the given operation. +// +// hook.Unless(Log, versioned.Update|versioned.UpdateOne) +// +func Unless(hk versioned.Hook, op versioned.Op) versioned.Hook { + return If(hk, Not(HasOp(op))) +} + +// FixedError is a hook returning a fixed error. +func FixedError(err error) versioned.Hook { + return func(versioned.Mutator) versioned.Mutator { + return versioned.MutateFunc(func(context.Context, versioned.Mutation) (versioned.Value, error) { + return nil, err + }) + } +} + +// Reject returns a hook that rejects all operations that match op. +// +// func (T) Hooks() []versioned.Hook { +// return []versioned.Hook{ +// Reject(versioned.Delete|versioned.Update), +// } +// } +// +func Reject(op versioned.Op) versioned.Hook { + hk := FixedError(fmt.Errorf("%s operation is not allowed", op)) + return On(hk, op) +} + +// Chain acts as a list of hooks and is effectively immutable. +// Once created, it will always hold the same set of hooks in the same order. +type Chain struct { + hooks []versioned.Hook +} + +// NewChain creates a new chain of hooks. +func NewChain(hooks ...versioned.Hook) Chain { + return Chain{append([]versioned.Hook(nil), hooks...)} +} + +// Hook chains the list of hooks and returns the final hook. +func (c Chain) Hook() versioned.Hook { + return func(mutator versioned.Mutator) versioned.Mutator { + for i := len(c.hooks) - 1; i >= 0; i-- { + mutator = c.hooks[i](mutator) + } + return mutator + } +} + +// Append extends a chain, adding the specified hook +// as the last ones in the mutation flow. +func (c Chain) Append(hooks ...versioned.Hook) Chain { + newHooks := make([]versioned.Hook, 0, len(c.hooks)+len(hooks)) + newHooks = append(newHooks, c.hooks...) + newHooks = append(newHooks, hooks...) + return Chain{newHooks} +} + +// Extend extends a chain, adding the specified chain +// as the last ones in the mutation flow. +func (c Chain) Extend(chain Chain) Chain { + return c.Append(chain.hooks...) +} diff --git a/entc/integration/migrate/versioned/migrate/migrate.go b/entc/integration/migrate/versioned/migrate/migrate.go new file mode 100644 index 000000000..9641fc261 --- /dev/null +++ b/entc/integration/migrate/versioned/migrate/migrate.go @@ -0,0 +1,85 @@ +// 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 migrate + +import ( + "context" + "fmt" + "io" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql/schema" +) + +var ( + // WithGlobalUniqueID sets the universal ids options to the migration. + // If this option is enabled, ent migration will allocate a 1<<32 range + // for the ids of each entity (table). + // Note that this option cannot be applied on tables that already exist. + WithGlobalUniqueID = schema.WithGlobalUniqueID + // WithDropColumn sets the drop column option to the migration. + // If this option is enabled, ent migration will drop old columns + // that were used for both fields and edges. This defaults to false. + WithDropColumn = schema.WithDropColumn + // WithDropIndex sets the drop index option to the migration. + // If this option is enabled, ent migration will drop old indexes + // that were defined in the schema. This defaults to false. + // Note that unique constraints are defined using `UNIQUE INDEX`, + // and therefore, it's recommended to enable this option to get more + // flexibility in the schema changes. + WithDropIndex = schema.WithDropIndex + // WithFixture sets the foreign-key renaming option to the migration when upgrading + // ent from v0.1.0 (issue-#285). Defaults to false. + WithFixture = schema.WithFixture + // WithForeignKeys enables creating foreign-key in schema DDL. This defaults to true. + WithForeignKeys = schema.WithForeignKeys +) + +// Schema is the API for creating, migrating and dropping a schema. +type Schema struct { + drv dialect.Driver +} + +// NewSchema creates a new schema client. +func NewSchema(drv dialect.Driver) *Schema { return &Schema{drv: drv} } + +// Create creates all schema resources. +func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error { + migrate, err := schema.NewMigrate(s.drv, opts...) + if err != nil { + return fmt.Errorf("ent/migrate: %w", err) + } + return migrate.Create(ctx, Tables...) +} + +// Diff creates a migration file containing the statements to resolve the diff +// between the Ent schema and the connected database. +func (s *Schema) Diff(ctx context.Context, opts ...schema.MigrateOption) error { + migrate, err := schema.NewMigrate(s.drv, opts...) + if err != nil { + return fmt.Errorf("ent/migrate: %w", err) + } + return migrate.Diff(ctx, Tables...) +} + +// WriteTo writes the schema changes to w instead of running them against the database. +// +// if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil { +// log.Fatal(err) +// } +// +func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error { + drv := &schema.WriteDriver{ + Writer: w, + Driver: s.drv, + } + migrate, err := schema.NewMigrate(drv, opts...) + if err != nil { + return fmt.Errorf("ent/migrate: %w", err) + } + return migrate.Create(ctx, Tables...) +} diff --git a/entc/integration/migrate/versioned/migrate/schema.go b/entc/integration/migrate/versioned/migrate/schema.go new file mode 100644 index 000000000..96784d675 --- /dev/null +++ b/entc/integration/migrate/versioned/migrate/schema.go @@ -0,0 +1,97 @@ +// 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 migrate + +import ( + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/dialect/sql/schema" + "entgo.io/ent/schema/field" +) + +var ( + // CarsColumns holds the columns for the "cars" table. + CarsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "user_car", Type: field.TypeInt, Unique: true, Nullable: true}, + } + // CarsTable holds the schema information for the "cars" table. + CarsTable = &schema.Table{ + Name: "cars", + Columns: CarsColumns, + PrimaryKey: []*schema.Column{CarsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "cars_users_car", + Columns: []*schema.Column{CarsColumns[1]}, + RefColumns: []*schema.Column{UsersColumns[0]}, + OnDelete: schema.SetNull, + }, + }, + } + // UsersColumns holds the columns for the "users" table. + UsersColumns = []*schema.Column{ + {Name: "oid", Type: field.TypeInt, Increment: true}, + {Name: "age", Type: field.TypeInt32}, + {Name: "name", Type: field.TypeString, Size: 10}, + {Name: "description", Type: field.TypeString, Nullable: true, Size: 2147483647}, + {Name: "nickname", Type: field.TypeString, Unique: true}, + {Name: "address", Type: field.TypeString, Nullable: true}, + {Name: "renamed", Type: field.TypeString, Nullable: true}, + {Name: "blob", Type: field.TypeBytes, Nullable: true, Size: 255}, + {Name: "state", Type: field.TypeEnum, Nullable: true, Enums: []string{"logged_in", "logged_out"}}, + {Name: "status", Type: field.TypeString, Nullable: true}, + {Name: "workplace", Type: field.TypeString, Nullable: true, Size: 30}, + {Name: "user_children", Type: field.TypeInt, Nullable: true}, + {Name: "user_spouse", Type: field.TypeInt, Unique: true, Nullable: true}, + } + // 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_users_children", + Columns: []*schema.Column{UsersColumns[11]}, + RefColumns: []*schema.Column{UsersColumns[0]}, + OnDelete: schema.SetNull, + }, + { + Symbol: "users_users_spouse", + Columns: []*schema.Column{UsersColumns[12]}, + RefColumns: []*schema.Column{UsersColumns[0]}, + OnDelete: schema.SetNull, + }, + }, + Indexes: []*schema.Index{ + { + Name: "user_description", + Unique: false, + Columns: []*schema.Column{UsersColumns[3]}, + Annotation: &entsql.IndexAnnotation{ + Prefix: 50, + }, + }, + { + Name: "user_name_address", + Unique: true, + Columns: []*schema.Column{UsersColumns[2], UsersColumns[5]}, + }, + }, + } + // Tables holds all the tables in the schema. + Tables = []*schema.Table{ + CarsTable, + UsersTable, + } +) + +func init() { + CarsTable.ForeignKeys[0].RefTable = UsersTable + UsersTable.ForeignKeys[0].RefTable = UsersTable + UsersTable.ForeignKeys[1].RefTable = UsersTable +} diff --git a/entc/integration/migrate/versioned/mutation.go b/entc/integration/migrate/versioned/mutation.go new file mode 100644 index 000000000..1627ab467 --- /dev/null +++ b/entc/integration/migrate/versioned/mutation.go @@ -0,0 +1,1596 @@ +// 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 versioned + +import ( + "context" + "errors" + "fmt" + "sync" + + "entgo.io/ent/entc/integration/migrate/versioned/car" + "entgo.io/ent/entc/integration/migrate/versioned/predicate" + "entgo.io/ent/entc/integration/migrate/versioned/user" + + "entgo.io/ent" +) + +const ( + // Operation types. + OpCreate = ent.OpCreate + OpDelete = ent.OpDelete + OpDeleteOne = ent.OpDeleteOne + OpUpdate = ent.OpUpdate + OpUpdateOne = ent.OpUpdateOne + + // Node types. + TypeCar = "Car" + TypeUser = "User" +) + +// CarMutation represents an operation that mutates the Car nodes in the graph. +type CarMutation struct { + config + op Op + typ string + id *int + clearedFields map[string]struct{} + owner *int + clearedowner bool + done bool + oldValue func(context.Context) (*Car, error) + predicates []predicate.Car +} + +var _ ent.Mutation = (*CarMutation)(nil) + +// carOption allows management of the mutation configuration using functional options. +type carOption func(*CarMutation) + +// newCarMutation creates new mutation for the Car entity. +func newCarMutation(c config, op Op, opts ...carOption) *CarMutation { + m := &CarMutation{ + config: c, + op: op, + typ: TypeCar, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withCarID sets the ID field of the mutation. +func withCarID(id int) carOption { + return func(m *CarMutation) { + var ( + err error + once sync.Once + value *Car + ) + m.oldValue = func(ctx context.Context) (*Car, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Car.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withCar sets the old Car of the mutation. +func withCar(node *Car) carOption { + return func(m *CarMutation) { + m.oldValue = func(context.Context) (*Car, 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 CarMutation) 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 CarMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("versioned: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *CarMutation) 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 *CarMutation) 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().Car.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetOwnerID sets the "owner" edge to the User entity by id. +func (m *CarMutation) SetOwnerID(id int) { + m.owner = &id +} + +// ClearOwner clears the "owner" edge to the User entity. +func (m *CarMutation) ClearOwner() { + m.clearedowner = true +} + +// OwnerCleared reports if the "owner" edge to the User entity was cleared. +func (m *CarMutation) OwnerCleared() bool { + return m.clearedowner +} + +// OwnerID returns the "owner" edge ID in the mutation. +func (m *CarMutation) OwnerID() (id int, exists bool) { + if m.owner != nil { + return *m.owner, true + } + return +} + +// OwnerIDs returns the "owner" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// OwnerID instead. It exists only for internal usage by the builders. +func (m *CarMutation) OwnerIDs() (ids []int) { + if id := m.owner; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetOwner resets all changes to the "owner" edge. +func (m *CarMutation) ResetOwner() { + m.owner = nil + m.clearedowner = false +} + +// Where appends a list predicates to the CarMutation builder. +func (m *CarMutation) Where(ps ...predicate.Car) { + m.predicates = append(m.predicates, ps...) +} + +// Op returns the operation name. +func (m *CarMutation) Op() Op { + return m.op +} + +// Type returns the node type of this mutation (Car). +func (m *CarMutation) 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 *CarMutation) 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 *CarMutation) 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 *CarMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + return nil, fmt.Errorf("unknown Car 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 *CarMutation) SetField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown Car field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *CarMutation) 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 *CarMutation) 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 *CarMutation) AddField(name string, value ent.Value) error { + return fmt.Errorf("unknown Car numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *CarMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *CarMutation) 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 *CarMutation) ClearField(name string) error { + return fmt.Errorf("unknown Car 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 *CarMutation) ResetField(name string) error { + return fmt.Errorf("unknown Car field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *CarMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.owner != nil { + edges = append(edges, car.EdgeOwner) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *CarMutation) AddedIDs(name string) []ent.Value { + switch name { + case car.EdgeOwner: + if id := m.owner; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *CarMutation) 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 *CarMutation) RemovedIDs(name string) []ent.Value { + switch name { + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *CarMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedowner { + edges = append(edges, car.EdgeOwner) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *CarMutation) EdgeCleared(name string) bool { + switch name { + case car.EdgeOwner: + return m.clearedowner + } + 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 *CarMutation) ClearEdge(name string) error { + switch name { + case car.EdgeOwner: + m.ClearOwner() + return nil + } + return fmt.Errorf("unknown Car 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 *CarMutation) ResetEdge(name string) error { + switch name { + case car.EdgeOwner: + m.ResetOwner() + return nil + } + return fmt.Errorf("unknown Car edge %s", name) +} + +// UserMutation represents an operation that mutates the User nodes in the graph. +type UserMutation struct { + config + op Op + typ string + id *int + age *int32 + addage *int32 + name *string + description *string + nickname *string + address *string + renamed *string + blob *[]byte + state *user.State + status *string + workplace *string + clearedFields map[string]struct{} + parent *int + clearedparent bool + children map[int]struct{} + removedchildren map[int]struct{} + clearedchildren bool + spouse *int + clearedspouse bool + car *int + clearedcar bool + done bool + oldValue func(context.Context) (*User, error) + predicates []predicate.User +} + +var _ ent.Mutation = (*UserMutation)(nil) + +// userOption allows management of the mutation configuration using functional options. +type userOption func(*UserMutation) + +// newUserMutation creates new mutation for the User entity. +func newUserMutation(c config, op Op, opts ...userOption) *UserMutation { + m := &UserMutation{ + config: c, + op: op, + typ: TypeUser, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withUserID sets the ID field of the mutation. +func withUserID(id int) userOption { + return func(m *UserMutation) { + var ( + err error + once sync.Once + value *User + ) + m.oldValue = func(ctx context.Context) (*User, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().User.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withUser sets the old User of the mutation. +func withUser(node *User) userOption { + return func(m *UserMutation) { + m.oldValue = func(context.Context) (*User, error) { + return node, nil + } + m.id = &node.ID + } +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m UserMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m UserMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("versioned: 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 User entities. +func (m *UserMutation) 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 *UserMutation) 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 *UserMutation) 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().User.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetAge sets the "age" field. +func (m *UserMutation) SetAge(i int32) { + m.age = &i + m.addage = nil +} + +// Age returns the value of the "age" field in the mutation. +func (m *UserMutation) Age() (r int32, exists bool) { + v := m.age + if v == nil { + return + } + return *v, true +} + +// OldAge returns the old "age" field's value of the User entity. +// If the User object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserMutation) OldAge(ctx context.Context) (v int32, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAge is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAge requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAge: %w", err) + } + return oldValue.Age, nil +} + +// AddAge adds i to the "age" field. +func (m *UserMutation) AddAge(i int32) { + if m.addage != nil { + *m.addage += i + } else { + m.addage = &i + } +} + +// AddedAge returns the value that was added to the "age" field in this mutation. +func (m *UserMutation) AddedAge() (r int32, exists bool) { + v := m.addage + if v == nil { + return + } + return *v, true +} + +// ResetAge resets all changes to the "age" field. +func (m *UserMutation) ResetAge() { + m.age = nil + m.addage = nil +} + +// SetName sets the "name" field. +func (m *UserMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *UserMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the User entity. +// If the User object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *UserMutation) ResetName() { + m.name = nil +} + +// SetDescription sets the "description" field. +func (m *UserMutation) SetDescription(s string) { + m.description = &s +} + +// Description returns the value of the "description" field in the mutation. +func (m *UserMutation) Description() (r string, exists bool) { + v := m.description + if v == nil { + return + } + return *v, true +} + +// OldDescription returns the old "description" field's value of the User entity. +// If the User object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserMutation) OldDescription(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDescription is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDescription requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDescription: %w", err) + } + return oldValue.Description, nil +} + +// ClearDescription clears the value of the "description" field. +func (m *UserMutation) ClearDescription() { + m.description = nil + m.clearedFields[user.FieldDescription] = struct{}{} +} + +// DescriptionCleared returns if the "description" field was cleared in this mutation. +func (m *UserMutation) DescriptionCleared() bool { + _, ok := m.clearedFields[user.FieldDescription] + return ok +} + +// ResetDescription resets all changes to the "description" field. +func (m *UserMutation) ResetDescription() { + m.description = nil + delete(m.clearedFields, user.FieldDescription) +} + +// SetNickname sets the "nickname" field. +func (m *UserMutation) SetNickname(s string) { + m.nickname = &s +} + +// Nickname returns the value of the "nickname" field in the mutation. +func (m *UserMutation) Nickname() (r string, exists bool) { + v := m.nickname + if v == nil { + return + } + return *v, true +} + +// OldNickname returns the old "nickname" field's value of the User entity. +// If the User object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserMutation) OldNickname(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldNickname is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldNickname requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldNickname: %w", err) + } + return oldValue.Nickname, nil +} + +// ResetNickname resets all changes to the "nickname" field. +func (m *UserMutation) ResetNickname() { + m.nickname = nil +} + +// SetAddress sets the "address" field. +func (m *UserMutation) SetAddress(s string) { + m.address = &s +} + +// Address returns the value of the "address" field in the mutation. +func (m *UserMutation) Address() (r string, exists bool) { + v := m.address + if v == nil { + return + } + return *v, true +} + +// OldAddress returns the old "address" field's value of the User entity. +// If the User object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserMutation) OldAddress(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAddress is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAddress requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAddress: %w", err) + } + return oldValue.Address, nil +} + +// ClearAddress clears the value of the "address" field. +func (m *UserMutation) ClearAddress() { + m.address = nil + m.clearedFields[user.FieldAddress] = struct{}{} +} + +// AddressCleared returns if the "address" field was cleared in this mutation. +func (m *UserMutation) AddressCleared() bool { + _, ok := m.clearedFields[user.FieldAddress] + return ok +} + +// ResetAddress resets all changes to the "address" field. +func (m *UserMutation) ResetAddress() { + m.address = nil + delete(m.clearedFields, user.FieldAddress) +} + +// SetRenamed sets the "renamed" field. +func (m *UserMutation) SetRenamed(s string) { + m.renamed = &s +} + +// Renamed returns the value of the "renamed" field in the mutation. +func (m *UserMutation) Renamed() (r string, exists bool) { + v := m.renamed + if v == nil { + return + } + return *v, true +} + +// OldRenamed returns the old "renamed" field's value of the User entity. +// If the User object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserMutation) OldRenamed(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRenamed is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRenamed requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRenamed: %w", err) + } + return oldValue.Renamed, nil +} + +// ClearRenamed clears the value of the "renamed" field. +func (m *UserMutation) ClearRenamed() { + m.renamed = nil + m.clearedFields[user.FieldRenamed] = struct{}{} +} + +// RenamedCleared returns if the "renamed" field was cleared in this mutation. +func (m *UserMutation) RenamedCleared() bool { + _, ok := m.clearedFields[user.FieldRenamed] + return ok +} + +// ResetRenamed resets all changes to the "renamed" field. +func (m *UserMutation) ResetRenamed() { + m.renamed = nil + delete(m.clearedFields, user.FieldRenamed) +} + +// SetBlob sets the "blob" field. +func (m *UserMutation) SetBlob(b []byte) { + m.blob = &b +} + +// Blob returns the value of the "blob" field in the mutation. +func (m *UserMutation) Blob() (r []byte, exists bool) { + v := m.blob + if v == nil { + return + } + return *v, true +} + +// OldBlob returns the old "blob" field's value of the User entity. +// If the User object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserMutation) OldBlob(ctx context.Context) (v []byte, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldBlob is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldBlob requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldBlob: %w", err) + } + return oldValue.Blob, nil +} + +// ClearBlob clears the value of the "blob" field. +func (m *UserMutation) ClearBlob() { + m.blob = nil + m.clearedFields[user.FieldBlob] = struct{}{} +} + +// BlobCleared returns if the "blob" field was cleared in this mutation. +func (m *UserMutation) BlobCleared() bool { + _, ok := m.clearedFields[user.FieldBlob] + return ok +} + +// ResetBlob resets all changes to the "blob" field. +func (m *UserMutation) ResetBlob() { + m.blob = nil + delete(m.clearedFields, user.FieldBlob) +} + +// SetState sets the "state" field. +func (m *UserMutation) SetState(u user.State) { + m.state = &u +} + +// State returns the value of the "state" field in the mutation. +func (m *UserMutation) State() (r user.State, exists bool) { + v := m.state + if v == nil { + return + } + return *v, true +} + +// OldState returns the old "state" field's value of the User entity. +// If the User object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserMutation) OldState(ctx context.Context) (v user.State, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldState is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldState requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldState: %w", err) + } + return oldValue.State, nil +} + +// ClearState clears the value of the "state" field. +func (m *UserMutation) ClearState() { + m.state = nil + m.clearedFields[user.FieldState] = struct{}{} +} + +// StateCleared returns if the "state" field was cleared in this mutation. +func (m *UserMutation) StateCleared() bool { + _, ok := m.clearedFields[user.FieldState] + return ok +} + +// ResetState resets all changes to the "state" field. +func (m *UserMutation) ResetState() { + m.state = nil + delete(m.clearedFields, user.FieldState) +} + +// SetStatus sets the "status" field. +func (m *UserMutation) SetStatus(s string) { + m.status = &s +} + +// Status returns the value of the "status" field in the mutation. +func (m *UserMutation) Status() (r string, exists bool) { + v := m.status + if v == nil { + return + } + return *v, true +} + +// OldStatus returns the old "status" field's value of the User entity. +// If the User object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserMutation) OldStatus(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldStatus is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldStatus requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldStatus: %w", err) + } + return oldValue.Status, nil +} + +// ClearStatus clears the value of the "status" field. +func (m *UserMutation) ClearStatus() { + m.status = nil + m.clearedFields[user.FieldStatus] = struct{}{} +} + +// StatusCleared returns if the "status" field was cleared in this mutation. +func (m *UserMutation) StatusCleared() bool { + _, ok := m.clearedFields[user.FieldStatus] + return ok +} + +// ResetStatus resets all changes to the "status" field. +func (m *UserMutation) ResetStatus() { + m.status = nil + delete(m.clearedFields, user.FieldStatus) +} + +// SetWorkplace sets the "workplace" field. +func (m *UserMutation) SetWorkplace(s string) { + m.workplace = &s +} + +// Workplace returns the value of the "workplace" field in the mutation. +func (m *UserMutation) Workplace() (r string, exists bool) { + v := m.workplace + if v == nil { + return + } + return *v, true +} + +// OldWorkplace returns the old "workplace" field's value of the User entity. +// If the User object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserMutation) OldWorkplace(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldWorkplace is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldWorkplace requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldWorkplace: %w", err) + } + return oldValue.Workplace, nil +} + +// ClearWorkplace clears the value of the "workplace" field. +func (m *UserMutation) ClearWorkplace() { + m.workplace = nil + m.clearedFields[user.FieldWorkplace] = struct{}{} +} + +// WorkplaceCleared returns if the "workplace" field was cleared in this mutation. +func (m *UserMutation) WorkplaceCleared() bool { + _, ok := m.clearedFields[user.FieldWorkplace] + return ok +} + +// ResetWorkplace resets all changes to the "workplace" field. +func (m *UserMutation) ResetWorkplace() { + m.workplace = nil + delete(m.clearedFields, user.FieldWorkplace) +} + +// SetParentID sets the "parent" edge to the User entity by id. +func (m *UserMutation) SetParentID(id int) { + m.parent = &id +} + +// ClearParent clears the "parent" edge to the User entity. +func (m *UserMutation) ClearParent() { + m.clearedparent = true +} + +// ParentCleared reports if the "parent" edge to the User entity was cleared. +func (m *UserMutation) ParentCleared() bool { + return m.clearedparent +} + +// ParentID returns the "parent" edge ID in the mutation. +func (m *UserMutation) ParentID() (id int, exists bool) { + if m.parent != nil { + return *m.parent, true + } + return +} + +// ParentIDs returns the "parent" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// ParentID instead. It exists only for internal usage by the builders. +func (m *UserMutation) ParentIDs() (ids []int) { + if id := m.parent; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetParent resets all changes to the "parent" edge. +func (m *UserMutation) ResetParent() { + m.parent = nil + m.clearedparent = false +} + +// AddChildIDs adds the "children" edge to the User entity by ids. +func (m *UserMutation) AddChildIDs(ids ...int) { + if m.children == nil { + m.children = make(map[int]struct{}) + } + for i := range ids { + m.children[ids[i]] = struct{}{} + } +} + +// ClearChildren clears the "children" edge to the User entity. +func (m *UserMutation) ClearChildren() { + m.clearedchildren = true +} + +// ChildrenCleared reports if the "children" edge to the User entity was cleared. +func (m *UserMutation) ChildrenCleared() bool { + return m.clearedchildren +} + +// RemoveChildIDs removes the "children" edge to the User entity by IDs. +func (m *UserMutation) RemoveChildIDs(ids ...int) { + if m.removedchildren == nil { + m.removedchildren = make(map[int]struct{}) + } + for i := range ids { + delete(m.children, ids[i]) + m.removedchildren[ids[i]] = struct{}{} + } +} + +// RemovedChildren returns the removed IDs of the "children" edge to the User entity. +func (m *UserMutation) RemovedChildrenIDs() (ids []int) { + for id := range m.removedchildren { + ids = append(ids, id) + } + return +} + +// ChildrenIDs returns the "children" edge IDs in the mutation. +func (m *UserMutation) ChildrenIDs() (ids []int) { + for id := range m.children { + ids = append(ids, id) + } + return +} + +// ResetChildren resets all changes to the "children" edge. +func (m *UserMutation) ResetChildren() { + m.children = nil + m.clearedchildren = false + m.removedchildren = nil +} + +// SetSpouseID sets the "spouse" edge to the User entity by id. +func (m *UserMutation) SetSpouseID(id int) { + m.spouse = &id +} + +// ClearSpouse clears the "spouse" edge to the User entity. +func (m *UserMutation) ClearSpouse() { + m.clearedspouse = true +} + +// SpouseCleared reports if the "spouse" edge to the User entity was cleared. +func (m *UserMutation) SpouseCleared() bool { + return m.clearedspouse +} + +// SpouseID returns the "spouse" edge ID in the mutation. +func (m *UserMutation) SpouseID() (id int, exists bool) { + if m.spouse != nil { + return *m.spouse, true + } + return +} + +// SpouseIDs returns the "spouse" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// SpouseID instead. It exists only for internal usage by the builders. +func (m *UserMutation) SpouseIDs() (ids []int) { + if id := m.spouse; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetSpouse resets all changes to the "spouse" edge. +func (m *UserMutation) ResetSpouse() { + m.spouse = nil + m.clearedspouse = false +} + +// SetCarID sets the "car" edge to the Car entity by id. +func (m *UserMutation) SetCarID(id int) { + m.car = &id +} + +// ClearCar clears the "car" edge to the Car entity. +func (m *UserMutation) ClearCar() { + m.clearedcar = true +} + +// CarCleared reports if the "car" edge to the Car entity was cleared. +func (m *UserMutation) CarCleared() bool { + return m.clearedcar +} + +// CarID returns the "car" edge ID in the mutation. +func (m *UserMutation) CarID() (id int, exists bool) { + if m.car != nil { + return *m.car, true + } + return +} + +// CarIDs returns the "car" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// CarID instead. It exists only for internal usage by the builders. +func (m *UserMutation) CarIDs() (ids []int) { + if id := m.car; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetCar resets all changes to the "car" edge. +func (m *UserMutation) ResetCar() { + m.car = nil + m.clearedcar = false +} + +// Where appends a list predicates to the UserMutation builder. +func (m *UserMutation) Where(ps ...predicate.User) { + m.predicates = append(m.predicates, ps...) +} + +// Op returns the operation name. +func (m *UserMutation) Op() Op { + return m.op +} + +// Type returns the node type of this mutation (User). +func (m *UserMutation) Type() string { + return m.typ +} + +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *UserMutation) Fields() []string { + fields := make([]string, 0, 10) + if m.age != nil { + fields = append(fields, user.FieldAge) + } + if m.name != nil { + fields = append(fields, user.FieldName) + } + if m.description != nil { + fields = append(fields, user.FieldDescription) + } + if m.nickname != nil { + fields = append(fields, user.FieldNickname) + } + if m.address != nil { + fields = append(fields, user.FieldAddress) + } + if m.renamed != nil { + fields = append(fields, user.FieldRenamed) + } + if m.blob != nil { + fields = append(fields, user.FieldBlob) + } + if m.state != nil { + fields = append(fields, user.FieldState) + } + if m.status != nil { + fields = append(fields, user.FieldStatus) + } + if m.workplace != nil { + fields = append(fields, user.FieldWorkplace) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *UserMutation) Field(name string) (ent.Value, bool) { + switch name { + case user.FieldAge: + return m.Age() + case user.FieldName: + return m.Name() + case user.FieldDescription: + return m.Description() + case user.FieldNickname: + return m.Nickname() + case user.FieldAddress: + return m.Address() + case user.FieldRenamed: + return m.Renamed() + case user.FieldBlob: + return m.Blob() + case user.FieldState: + return m.State() + case user.FieldStatus: + return m.Status() + case user.FieldWorkplace: + return m.Workplace() + } + 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 *UserMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case user.FieldAge: + return m.OldAge(ctx) + case user.FieldName: + return m.OldName(ctx) + case user.FieldDescription: + return m.OldDescription(ctx) + case user.FieldNickname: + return m.OldNickname(ctx) + case user.FieldAddress: + return m.OldAddress(ctx) + case user.FieldRenamed: + return m.OldRenamed(ctx) + case user.FieldBlob: + return m.OldBlob(ctx) + case user.FieldState: + return m.OldState(ctx) + case user.FieldStatus: + return m.OldStatus(ctx) + case user.FieldWorkplace: + return m.OldWorkplace(ctx) + } + return nil, fmt.Errorf("unknown User field %s", name) +} + +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *UserMutation) SetField(name string, value ent.Value) error { + switch name { + case user.FieldAge: + v, ok := value.(int32) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAge(v) + return nil + case user.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case user.FieldDescription: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDescription(v) + return nil + case user.FieldNickname: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNickname(v) + return nil + case user.FieldAddress: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAddress(v) + return nil + case user.FieldRenamed: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRenamed(v) + return nil + case user.FieldBlob: + v, ok := value.([]byte) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetBlob(v) + return nil + case user.FieldState: + v, ok := value.(user.State) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetState(v) + return nil + case user.FieldStatus: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStatus(v) + return nil + case user.FieldWorkplace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetWorkplace(v) + return nil + } + return fmt.Errorf("unknown User field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *UserMutation) AddedFields() []string { + var fields []string + if m.addage != nil { + fields = append(fields, user.FieldAge) + } + return fields +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *UserMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case user.FieldAge: + return m.AddedAge() + } + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *UserMutation) AddField(name string, value ent.Value) error { + switch name { + case user.FieldAge: + v, ok := value.(int32) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddAge(v) + return nil + } + return fmt.Errorf("unknown User numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *UserMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(user.FieldDescription) { + fields = append(fields, user.FieldDescription) + } + if m.FieldCleared(user.FieldAddress) { + fields = append(fields, user.FieldAddress) + } + if m.FieldCleared(user.FieldRenamed) { + fields = append(fields, user.FieldRenamed) + } + if m.FieldCleared(user.FieldBlob) { + fields = append(fields, user.FieldBlob) + } + if m.FieldCleared(user.FieldState) { + fields = append(fields, user.FieldState) + } + if m.FieldCleared(user.FieldStatus) { + fields = append(fields, user.FieldStatus) + } + if m.FieldCleared(user.FieldWorkplace) { + fields = append(fields, user.FieldWorkplace) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *UserMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *UserMutation) ClearField(name string) error { + switch name { + case user.FieldDescription: + m.ClearDescription() + return nil + case user.FieldAddress: + m.ClearAddress() + return nil + case user.FieldRenamed: + m.ClearRenamed() + return nil + case user.FieldBlob: + m.ClearBlob() + return nil + case user.FieldState: + m.ClearState() + return nil + case user.FieldStatus: + m.ClearStatus() + return nil + case user.FieldWorkplace: + m.ClearWorkplace() + return nil + } + return fmt.Errorf("unknown User nullable field %s", name) +} + +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *UserMutation) ResetField(name string) error { + switch name { + case user.FieldAge: + m.ResetAge() + return nil + case user.FieldName: + m.ResetName() + return nil + case user.FieldDescription: + m.ResetDescription() + return nil + case user.FieldNickname: + m.ResetNickname() + return nil + case user.FieldAddress: + m.ResetAddress() + return nil + case user.FieldRenamed: + m.ResetRenamed() + return nil + case user.FieldBlob: + m.ResetBlob() + return nil + case user.FieldState: + m.ResetState() + return nil + case user.FieldStatus: + m.ResetStatus() + return nil + case user.FieldWorkplace: + m.ResetWorkplace() + return nil + } + return fmt.Errorf("unknown User field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *UserMutation) AddedEdges() []string { + edges := make([]string, 0, 4) + if m.parent != nil { + edges = append(edges, user.EdgeParent) + } + if m.children != nil { + edges = append(edges, user.EdgeChildren) + } + if m.spouse != nil { + edges = append(edges, user.EdgeSpouse) + } + if m.car != nil { + edges = append(edges, user.EdgeCar) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *UserMutation) AddedIDs(name string) []ent.Value { + switch name { + case user.EdgeParent: + if id := m.parent; id != nil { + return []ent.Value{*id} + } + case user.EdgeChildren: + ids := make([]ent.Value, 0, len(m.children)) + for id := range m.children { + ids = append(ids, id) + } + return ids + case user.EdgeSpouse: + if id := m.spouse; id != nil { + return []ent.Value{*id} + } + case user.EdgeCar: + if id := m.car; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *UserMutation) RemovedEdges() []string { + edges := make([]string, 0, 4) + if m.removedchildren != nil { + edges = append(edges, user.EdgeChildren) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *UserMutation) RemovedIDs(name string) []ent.Value { + switch name { + case user.EdgeChildren: + ids := make([]ent.Value, 0, len(m.removedchildren)) + for id := range m.removedchildren { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *UserMutation) ClearedEdges() []string { + edges := make([]string, 0, 4) + if m.clearedparent { + edges = append(edges, user.EdgeParent) + } + if m.clearedchildren { + edges = append(edges, user.EdgeChildren) + } + if m.clearedspouse { + edges = append(edges, user.EdgeSpouse) + } + if m.clearedcar { + edges = append(edges, user.EdgeCar) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *UserMutation) EdgeCleared(name string) bool { + switch name { + case user.EdgeParent: + return m.clearedparent + case user.EdgeChildren: + return m.clearedchildren + case user.EdgeSpouse: + return m.clearedspouse + case user.EdgeCar: + return m.clearedcar + } + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *UserMutation) ClearEdge(name string) error { + switch name { + case user.EdgeParent: + m.ClearParent() + return nil + case user.EdgeSpouse: + m.ClearSpouse() + return nil + case user.EdgeCar: + m.ClearCar() + return nil + } + return fmt.Errorf("unknown User unique edge %s", name) +} + +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. +func (m *UserMutation) ResetEdge(name string) error { + switch name { + case user.EdgeParent: + m.ResetParent() + return nil + case user.EdgeChildren: + m.ResetChildren() + return nil + case user.EdgeSpouse: + m.ResetSpouse() + return nil + case user.EdgeCar: + m.ResetCar() + return nil + } + return fmt.Errorf("unknown User edge %s", name) +} diff --git a/entc/integration/migrate/versioned/predicate/predicate.go b/entc/integration/migrate/versioned/predicate/predicate.go new file mode 100644 index 000000000..4297b5a4e --- /dev/null +++ b/entc/integration/migrate/versioned/predicate/predicate.go @@ -0,0 +1,17 @@ +// 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 predicate + +import ( + "entgo.io/ent/dialect/sql" +) + +// Car is the predicate function for car builders. +type Car func(*sql.Selector) + +// User is the predicate function for user builders. +type User func(*sql.Selector) diff --git a/entc/integration/migrate/versioned/runtime.go b/entc/integration/migrate/versioned/runtime.go new file mode 100644 index 000000000..bacd4d67d --- /dev/null +++ b/entc/integration/migrate/versioned/runtime.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. + +// Code generated by entc, DO NOT EDIT. + +package versioned + +import ( + "entgo.io/ent/entc/integration/migrate/versioned/schema" + "entgo.io/ent/entc/integration/migrate/versioned/user" +) + +// The init function reads all schema descriptors with runtime code +// (default values, validators, hooks and policies) and stitches it +// to their package variables. +func init() { + userFields := schema.User{}.Fields() + _ = userFields + // userDescName is the schema descriptor for name field. + userDescName := userFields[2].Descriptor() + // user.NameValidator is a validator for the "name" field. It is called by the builders before save. + user.NameValidator = userDescName.Validators[0].(func(string) error) + // userDescBlob is the schema descriptor for blob field. + userDescBlob := userFields[7].Descriptor() + // user.BlobValidator is a validator for the "blob" field. It is called by the builders before save. + user.BlobValidator = userDescBlob.Validators[0].(func([]byte) error) + // userDescWorkplace is the schema descriptor for workplace field. + userDescWorkplace := userFields[10].Descriptor() + // user.WorkplaceValidator is a validator for the "workplace" field. It is called by the builders before save. + user.WorkplaceValidator = userDescWorkplace.Validators[0].(func(string) error) +} diff --git a/entc/integration/migrate/versioned/runtime/runtime.go b/entc/integration/migrate/versioned/runtime/runtime.go new file mode 100644 index 000000000..5900de73d --- /dev/null +++ b/entc/integration/migrate/versioned/runtime/runtime.go @@ -0,0 +1,13 @@ +// 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 runtime + +// The schema-stitching logic is generated in entgo.io/ent/entc/integration/migrate/versioned/runtime.go + +const ( + Version = "(devel)" // Version of ent codegen. +) diff --git a/entc/integration/migrate/versioned/schema/user.go b/entc/integration/migrate/versioned/schema/user.go new file mode 100644 index 000000000..1e3777679 --- /dev/null +++ b/entc/integration/migrate/versioned/schema/user.go @@ -0,0 +1,81 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +package schema + +import ( + "entgo.io/ent" + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/index" +) + +// User holds the schema definition for the User entity. +type User struct { + ent.Schema +} + +// Fields of the User. +func (User) Fields() []ent.Field { + return []ent.Field{ + field.Int("id"). + StorageKey("oid"), + field.Int32("age"), + field.String("name"). + MaxLen(10), + field.Text("description"). + Optional(), + field.String("nickname"). + Unique(), + field.String("address"). + Optional(), + field.String("renamed"). + Optional(), + field.Bytes("blob"). + Optional(). + MaxLen(255), + field.Enum("state"). + Optional(). + Values("logged_in", "logged_out"), + field.String("status"). + Optional(), + field.String("workplace"). + MaxLen(30). + Optional(), + } +} + +func (User) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("children", User.Type). + From("parent"). + Unique(), + edge.To("spouse", User.Type). + Unique(), + edge.To("car", Car.Type). + Unique(), + } +} + +func (User) Indexes() []ent.Index { + return []ent.Index{ + index.Fields("description"). + Annotations(entsql.Prefix(50)), + index.Fields("name", "address"). + Unique(), + } +} + +type Car struct { + ent.Schema +} + +func (Car) Edges() []ent.Edge { + return []ent.Edge{ + edge.From("owner", User.Type). + Ref("car"). + Unique(), + } +} diff --git a/entc/integration/migrate/versioned/tx.go b/entc/integration/migrate/versioned/tx.go new file mode 100644 index 000000000..b8feb9ad7 --- /dev/null +++ b/entc/integration/migrate/versioned/tx.go @@ -0,0 +1,217 @@ +// 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 versioned + +import ( + "context" + "sync" + + "entgo.io/ent/dialect" +) + +// Tx is a transactional client that is created by calling Client.Tx(). +type Tx struct { + config + // Car is the client for interacting with the Car builders. + Car *CarClient + // User is the client for interacting with the User builders. + User *UserClient + + // lazily loaded. + client *Client + clientOnce sync.Once + + // completion callbacks. + mu sync.Mutex + onCommit []CommitHook + onRollback []RollbackHook + + // ctx lives for the life of the transaction. It is + // the same context used by the underlying connection. + ctx context.Context +} + +type ( + // Committer is the interface that wraps the Commit method. + Committer interface { + Commit(context.Context, *Tx) error + } + + // The CommitFunc type is an adapter to allow the use of ordinary + // function as a Committer. If f is a function with the appropriate + // signature, CommitFunc(f) is a Committer that calls f. + CommitFunc func(context.Context, *Tx) error + + // CommitHook defines the "commit middleware". A function that gets a Committer + // and returns a Committer. For example: + // + // hook := func(next ent.Committer) ent.Committer { + // return ent.CommitFunc(func(ctx context.Context, tx *ent.Tx) error { + // // Do some stuff before. + // if err := next.Commit(ctx, tx); err != nil { + // return err + // } + // // Do some stuff after. + // return nil + // }) + // } + // + CommitHook func(Committer) Committer +) + +// Commit calls f(ctx, m). +func (f CommitFunc) Commit(ctx context.Context, tx *Tx) error { + return f(ctx, tx) +} + +// Commit commits the transaction. +func (tx *Tx) Commit() error { + txDriver := tx.config.driver.(*txDriver) + var fn Committer = CommitFunc(func(context.Context, *Tx) error { + return txDriver.tx.Commit() + }) + tx.mu.Lock() + hooks := append([]CommitHook(nil), tx.onCommit...) + tx.mu.Unlock() + for i := len(hooks) - 1; i >= 0; i-- { + fn = hooks[i](fn) + } + return fn.Commit(tx.ctx, tx) +} + +// OnCommit adds a hook to call on commit. +func (tx *Tx) OnCommit(f CommitHook) { + tx.mu.Lock() + defer tx.mu.Unlock() + tx.onCommit = append(tx.onCommit, f) +} + +type ( + // Rollbacker is the interface that wraps the Rollback method. + Rollbacker interface { + Rollback(context.Context, *Tx) error + } + + // The RollbackFunc type is an adapter to allow the use of ordinary + // function as a Rollbacker. If f is a function with the appropriate + // signature, RollbackFunc(f) is a Rollbacker that calls f. + RollbackFunc func(context.Context, *Tx) error + + // RollbackHook defines the "rollback middleware". A function that gets a Rollbacker + // and returns a Rollbacker. For example: + // + // hook := func(next ent.Rollbacker) ent.Rollbacker { + // return ent.RollbackFunc(func(ctx context.Context, tx *ent.Tx) error { + // // Do some stuff before. + // if err := next.Rollback(ctx, tx); err != nil { + // return err + // } + // // Do some stuff after. + // return nil + // }) + // } + // + RollbackHook func(Rollbacker) Rollbacker +) + +// Rollback calls f(ctx, m). +func (f RollbackFunc) Rollback(ctx context.Context, tx *Tx) error { + return f(ctx, tx) +} + +// Rollback rollbacks the transaction. +func (tx *Tx) Rollback() error { + txDriver := tx.config.driver.(*txDriver) + var fn Rollbacker = RollbackFunc(func(context.Context, *Tx) error { + return txDriver.tx.Rollback() + }) + tx.mu.Lock() + hooks := append([]RollbackHook(nil), tx.onRollback...) + tx.mu.Unlock() + for i := len(hooks) - 1; i >= 0; i-- { + fn = hooks[i](fn) + } + return fn.Rollback(tx.ctx, tx) +} + +// OnRollback adds a hook to call on rollback. +func (tx *Tx) OnRollback(f RollbackHook) { + tx.mu.Lock() + defer tx.mu.Unlock() + tx.onRollback = append(tx.onRollback, f) +} + +// Client returns a Client that binds to current transaction. +func (tx *Tx) Client() *Client { + tx.clientOnce.Do(func() { + tx.client = &Client{config: tx.config} + tx.client.init() + }) + return tx.client +} + +func (tx *Tx) init() { + tx.Car = NewCarClient(tx.config) + tx.User = NewUserClient(tx.config) +} + +// txDriver wraps the given dialect.Tx with a nop dialect.Driver implementation. +// The idea is to support transactions without adding any extra code to the builders. +// When a builder calls to driver.Tx(), it gets the same dialect.Tx instance. +// Commit and Rollback are nop for the internal builders and the user must call one +// 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 +// through the driver which created this transaction. +// +// Note that txDriver is not goroutine safe. +type txDriver struct { + // the driver we started the transaction from. + drv dialect.Driver + // tx is the underlying transaction. + tx dialect.Tx +} + +// newTx creates a new transactional driver. +func newTx(ctx context.Context, drv dialect.Driver) (*txDriver, error) { + tx, err := drv.Tx(ctx) + if err != nil { + return nil, err + } + return &txDriver{tx: tx, drv: drv}, nil +} + +// Tx returns the transaction wrapper (txDriver) to avoid Commit or Rollback calls +// from the internal builders. Should be called only by the internal builders. +func (tx *txDriver) Tx(context.Context) (dialect.Tx, error) { return tx, nil } + +// Dialect returns the dialect of the driver we started the transaction from. +func (tx *txDriver) Dialect() string { return tx.drv.Dialect() } + +// Close is a nop close. +func (*txDriver) Close() error { return nil } + +// Commit is a nop commit for the internal builders. +// User must call `Tx.Commit` in order to commit the transaction. +func (*txDriver) Commit() error { return nil } + +// Rollback is a nop rollback for the internal builders. +// User must call `Tx.Rollback` in order to rollback the transaction. +func (*txDriver) Rollback() error { return nil } + +// Exec calls tx.Exec. +func (tx *txDriver) Exec(ctx context.Context, query string, args, v interface{}) error { + return tx.tx.Exec(ctx, query, args, v) +} + +// Query calls tx.Query. +func (tx *txDriver) Query(ctx context.Context, query string, args, v interface{}) error { + return tx.tx.Query(ctx, query, args, v) +} + +var _ dialect.Driver = (*txDriver)(nil) diff --git a/entc/integration/migrate/versioned/user.go b/entc/integration/migrate/versioned/user.go new file mode 100644 index 000000000..67e36cb62 --- /dev/null +++ b/entc/integration/migrate/versioned/user.go @@ -0,0 +1,305 @@ +// 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 versioned + +import ( + "fmt" + "strings" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/entc/integration/migrate/versioned/car" + "entgo.io/ent/entc/integration/migrate/versioned/user" +) + +// User is the model entity for the User schema. +type User struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // Age holds the value of the "age" field. + Age int32 `json:"age,omitempty"` + // Name holds the value of the "name" field. + Name string `json:"name,omitempty"` + // Description holds the value of the "description" field. + Description string `json:"description,omitempty"` + // Nickname holds the value of the "nickname" field. + Nickname string `json:"nickname,omitempty"` + // Address holds the value of the "address" field. + Address string `json:"address,omitempty"` + // Renamed holds the value of the "renamed" field. + Renamed string `json:"renamed,omitempty"` + // Blob holds the value of the "blob" field. + Blob []byte `json:"blob,omitempty"` + // State holds the value of the "state" field. + State user.State `json:"state,omitempty"` + // Status holds the value of the "status" field. + Status string `json:"status,omitempty"` + // Workplace holds the value of the "workplace" field. + Workplace string `json:"workplace,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"` + user_children *int + user_spouse *int +} + +// UserEdges holds the relations/edges for other nodes in the graph. +type UserEdges struct { + // Parent holds the value of the parent edge. + Parent *User `json:"parent,omitempty"` + // Children holds the value of the children edge. + Children []*User `json:"children,omitempty"` + // Spouse holds the value of the spouse edge. + Spouse *User `json:"spouse,omitempty"` + // Car holds the value of the car edge. + Car *Car `json:"car,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [4]bool +} + +// ParentOrErr returns the Parent value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e UserEdges) ParentOrErr() (*User, error) { + if e.loadedTypes[0] { + if e.Parent == nil { + // The edge parent was loaded in eager-loading, + // but was not found. + return nil, &NotFoundError{label: user.Label} + } + return e.Parent, nil + } + return nil, &NotLoadedError{edge: "parent"} +} + +// ChildrenOrErr returns the Children value or an error if the edge +// was not loaded in eager-loading. +func (e UserEdges) ChildrenOrErr() ([]*User, error) { + if e.loadedTypes[1] { + return e.Children, nil + } + return nil, &NotLoadedError{edge: "children"} +} + +// SpouseOrErr returns the Spouse value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e UserEdges) SpouseOrErr() (*User, error) { + if e.loadedTypes[2] { + if e.Spouse == nil { + // The edge spouse was loaded in eager-loading, + // but was not found. + return nil, &NotFoundError{label: user.Label} + } + return e.Spouse, nil + } + return nil, &NotLoadedError{edge: "spouse"} +} + +// CarOrErr returns the Car value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e UserEdges) CarOrErr() (*Car, error) { + if e.loadedTypes[3] { + if e.Car == nil { + // The edge car was loaded in eager-loading, + // but was not found. + return nil, &NotFoundError{label: car.Label} + } + return e.Car, nil + } + return nil, &NotLoadedError{edge: "car"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*User) scanValues(columns []string) ([]interface{}, error) { + values := make([]interface{}, len(columns)) + for i := range columns { + switch columns[i] { + case user.FieldBlob: + values[i] = new([]byte) + case user.FieldID, user.FieldAge: + values[i] = new(sql.NullInt64) + case user.FieldName, user.FieldDescription, user.FieldNickname, user.FieldAddress, user.FieldRenamed, user.FieldState, user.FieldStatus, user.FieldWorkplace: + values[i] = new(sql.NullString) + case user.ForeignKeys[0]: // user_children + values[i] = new(sql.NullInt64) + case user.ForeignKeys[1]: // user_spouse + values[i] = new(sql.NullInt64) + default: + return nil, fmt.Errorf("unexpected column %q for type User", columns[i]) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the User fields. +func (u *User) 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 i := range columns { + switch columns[i] { + case user.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + u.ID = int(value.Int64) + case user.FieldAge: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field age", values[i]) + } else if value.Valid { + u.Age = int32(value.Int64) + } + case user.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + u.Name = value.String + } + case user.FieldDescription: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field description", values[i]) + } else if value.Valid { + u.Description = value.String + } + case user.FieldNickname: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field nickname", values[i]) + } else if value.Valid { + u.Nickname = value.String + } + case user.FieldAddress: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field address", values[i]) + } else if value.Valid { + u.Address = value.String + } + case user.FieldRenamed: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field renamed", values[i]) + } else if value.Valid { + u.Renamed = value.String + } + case user.FieldBlob: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field blob", values[i]) + } else if value != nil { + u.Blob = *value + } + case user.FieldState: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field state", values[i]) + } else if value.Valid { + u.State = user.State(value.String) + } + case user.FieldStatus: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field status", values[i]) + } else if value.Valid { + u.Status = value.String + } + case user.FieldWorkplace: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field workplace", values[i]) + } else if value.Valid { + u.Workplace = value.String + } + case user.ForeignKeys[0]: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for edge-field user_children", value) + } else if value.Valid { + u.user_children = new(int) + *u.user_children = int(value.Int64) + } + case user.ForeignKeys[1]: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for edge-field user_spouse", value) + } else if value.Valid { + u.user_spouse = new(int) + *u.user_spouse = int(value.Int64) + } + } + } + return nil +} + +// QueryParent queries the "parent" edge of the User entity. +func (u *User) QueryParent() *UserQuery { + return (&UserClient{config: u.config}).QueryParent(u) +} + +// QueryChildren queries the "children" edge of the User entity. +func (u *User) QueryChildren() *UserQuery { + return (&UserClient{config: u.config}).QueryChildren(u) +} + +// QuerySpouse queries the "spouse" edge of the User entity. +func (u *User) QuerySpouse() *UserQuery { + return (&UserClient{config: u.config}).QuerySpouse(u) +} + +// QueryCar queries the "car" edge of the User entity. +func (u *User) QueryCar() *CarQuery { + return (&UserClient{config: u.config}).QueryCar(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. +func (u *User) Update() *UserUpdateOne { + return (&UserClient{config: u.config}).UpdateOne(u) +} + +// Unwrap unwraps the User 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 (u *User) Unwrap() *User { + tx, ok := u.config.driver.(*txDriver) + if !ok { + panic("versioned: User is not a transactional entity") + } + u.config.driver = tx.drv + return u +} + +// String implements the fmt.Stringer. +func (u *User) String() string { + var builder strings.Builder + builder.WriteString("User(") + builder.WriteString(fmt.Sprintf("id=%v", u.ID)) + builder.WriteString(", age=") + builder.WriteString(fmt.Sprintf("%v", u.Age)) + builder.WriteString(", name=") + builder.WriteString(u.Name) + builder.WriteString(", description=") + builder.WriteString(u.Description) + builder.WriteString(", nickname=") + builder.WriteString(u.Nickname) + builder.WriteString(", address=") + builder.WriteString(u.Address) + builder.WriteString(", renamed=") + builder.WriteString(u.Renamed) + builder.WriteString(", blob=") + builder.WriteString(fmt.Sprintf("%v", u.Blob)) + builder.WriteString(", state=") + builder.WriteString(fmt.Sprintf("%v", u.State)) + builder.WriteString(", status=") + builder.WriteString(u.Status) + builder.WriteString(", workplace=") + builder.WriteString(u.Workplace) + builder.WriteByte(')') + return builder.String() +} + +// Users is a parsable slice of User. +type Users []*User + +func (u Users) config(cfg config) { + for _i := range u { + u[_i].config = cfg + } +} diff --git a/entc/integration/migrate/versioned/user/user.go b/entc/integration/migrate/versioned/user/user.go new file mode 100644 index 000000000..a614853f3 --- /dev/null +++ b/entc/integration/migrate/versioned/user/user.go @@ -0,0 +1,138 @@ +// 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 user + +import ( + "fmt" +) + +const ( + // Label holds the string label denoting the user type in the database. + Label = "user" + // FieldID holds the string denoting the id field in the database. + FieldID = "oid" + // FieldAge holds the string denoting the age field in the database. + FieldAge = "age" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldDescription holds the string denoting the description field in the database. + FieldDescription = "description" + // FieldNickname holds the string denoting the nickname field in the database. + FieldNickname = "nickname" + // FieldAddress holds the string denoting the address field in the database. + FieldAddress = "address" + // FieldRenamed holds the string denoting the renamed field in the database. + FieldRenamed = "renamed" + // FieldBlob holds the string denoting the blob field in the database. + FieldBlob = "blob" + // FieldState holds the string denoting the state field in the database. + FieldState = "state" + // FieldStatus holds the string denoting the status field in the database. + FieldStatus = "status" + // FieldWorkplace holds the string denoting the workplace field in the database. + FieldWorkplace = "workplace" + // EdgeParent holds the string denoting the parent edge name in mutations. + EdgeParent = "parent" + // EdgeChildren holds the string denoting the children edge name in mutations. + EdgeChildren = "children" + // EdgeSpouse holds the string denoting the spouse edge name in mutations. + EdgeSpouse = "spouse" + // EdgeCar holds the string denoting the car edge name in mutations. + EdgeCar = "car" + // CarFieldID holds the string denoting the ID field of the Car. + CarFieldID = "id" + // Table holds the table name of the user in the database. + Table = "users" + // ParentTable is the table that holds the parent relation/edge. + ParentTable = "users" + // ParentColumn is the table column denoting the parent relation/edge. + ParentColumn = "user_children" + // ChildrenTable is the table that holds the children relation/edge. + ChildrenTable = "users" + // ChildrenColumn is the table column denoting the children relation/edge. + ChildrenColumn = "user_children" + // SpouseTable is the table that holds the spouse relation/edge. + SpouseTable = "users" + // SpouseColumn is the table column denoting the spouse relation/edge. + SpouseColumn = "user_spouse" + // CarTable is the table that holds the car relation/edge. + CarTable = "cars" + // CarInverseTable is the table name for the Car entity. + // It exists in this package in order to avoid circular dependency with the "car" package. + CarInverseTable = "cars" + // CarColumn is the table column denoting the car relation/edge. + CarColumn = "user_car" +) + +// Columns holds all SQL columns for user fields. +var Columns = []string{ + FieldID, + FieldAge, + FieldName, + FieldDescription, + FieldNickname, + FieldAddress, + FieldRenamed, + FieldBlob, + FieldState, + FieldStatus, + FieldWorkplace, +} + +// 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{ + "user_children", + "user_spouse", +} + +// 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 + } + } + for i := range ForeignKeys { + if column == ForeignKeys[i] { + return true + } + } + return false +} + +var ( + // NameValidator is a validator for the "name" field. It is called by the builders before save. + NameValidator func(string) error + // BlobValidator is a validator for the "blob" field. It is called by the builders before save. + BlobValidator func([]byte) error + // WorkplaceValidator is a validator for the "workplace" field. It is called by the builders before save. + WorkplaceValidator func(string) error +) + +// State defines the type for the "state" enum field. +type State string + +// State values. +const ( + StateLoggedIn State = "logged_in" + StateLoggedOut State = "logged_out" +) + +func (s State) String() string { + return string(s) +} + +// StateValidator is a validator for the "state" field enum values. It is called by the builders before save. +func StateValidator(s State) error { + switch s { + case StateLoggedIn, StateLoggedOut: + return nil + default: + return fmt.Errorf("user: invalid enum value for state field: %q", s) + } +} diff --git a/entc/integration/migrate/versioned/user/where.go b/entc/integration/migrate/versioned/user/where.go new file mode 100644 index 000000000..979e26e2e --- /dev/null +++ b/entc/integration/migrate/versioned/user/where.go @@ -0,0 +1,1378 @@ +// 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 user + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/migrate/versioned/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.User { + return predicate.User(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.User { + return predicate.User(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.User { + return predicate.User(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.User { + return predicate.User(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.User { + return predicate.User(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.User { + return predicate.User(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.User { + return predicate.User(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.User { + return predicate.User(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.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldID), id)) + }) +} + +// Age applies equality check predicate on the "age" field. It's identical to AgeEQ. +func Age(v int32) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldAge), v)) + }) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldName), v)) + }) +} + +// Description applies equality check predicate on the "description" field. It's identical to DescriptionEQ. +func Description(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldDescription), v)) + }) +} + +// Nickname applies equality check predicate on the "nickname" field. It's identical to NicknameEQ. +func Nickname(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldNickname), v)) + }) +} + +// Address applies equality check predicate on the "address" field. It's identical to AddressEQ. +func Address(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldAddress), v)) + }) +} + +// Renamed applies equality check predicate on the "renamed" field. It's identical to RenamedEQ. +func Renamed(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldRenamed), v)) + }) +} + +// Blob applies equality check predicate on the "blob" field. It's identical to BlobEQ. +func Blob(v []byte) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldBlob), v)) + }) +} + +// Status applies equality check predicate on the "status" field. It's identical to StatusEQ. +func Status(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldStatus), v)) + }) +} + +// Workplace applies equality check predicate on the "workplace" field. It's identical to WorkplaceEQ. +func Workplace(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldWorkplace), v)) + }) +} + +// AgeEQ applies the EQ predicate on the "age" field. +func AgeEQ(v int32) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldAge), v)) + }) +} + +// AgeNEQ applies the NEQ predicate on the "age" field. +func AgeNEQ(v int32) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldAge), v)) + }) +} + +// AgeIn applies the In predicate on the "age" field. +func AgeIn(vs ...int32) predicate.User { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.User(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(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldAge), v...)) + }) +} + +// AgeNotIn applies the NotIn predicate on the "age" field. +func AgeNotIn(vs ...int32) predicate.User { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.User(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(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldAge), v...)) + }) +} + +// AgeGT applies the GT predicate on the "age" field. +func AgeGT(v int32) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldAge), v)) + }) +} + +// AgeGTE applies the GTE predicate on the "age" field. +func AgeGTE(v int32) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldAge), v)) + }) +} + +// AgeLT applies the LT predicate on the "age" field. +func AgeLT(v int32) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldAge), v)) + }) +} + +// AgeLTE applies the LTE predicate on the "age" field. +func AgeLTE(v int32) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldAge), v)) + }) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldName), v)) + }) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldName), v)) + }) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.User { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.User(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(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldName), v...)) + }) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.User { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.User(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(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldName), v...)) + }) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldName), v)) + }) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldName), v)) + }) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldName), v)) + }) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldName), v)) + }) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldName), v)) + }) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldName), v)) + }) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldName), v)) + }) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldName), v)) + }) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldName), v)) + }) +} + +// DescriptionEQ applies the EQ predicate on the "description" field. +func DescriptionEQ(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldDescription), v)) + }) +} + +// DescriptionNEQ applies the NEQ predicate on the "description" field. +func DescriptionNEQ(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldDescription), v)) + }) +} + +// DescriptionIn applies the In predicate on the "description" field. +func DescriptionIn(vs ...string) predicate.User { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.User(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(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldDescription), v...)) + }) +} + +// DescriptionNotIn applies the NotIn predicate on the "description" field. +func DescriptionNotIn(vs ...string) predicate.User { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.User(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(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldDescription), v...)) + }) +} + +// DescriptionGT applies the GT predicate on the "description" field. +func DescriptionGT(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldDescription), v)) + }) +} + +// DescriptionGTE applies the GTE predicate on the "description" field. +func DescriptionGTE(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldDescription), v)) + }) +} + +// DescriptionLT applies the LT predicate on the "description" field. +func DescriptionLT(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldDescription), v)) + }) +} + +// DescriptionLTE applies the LTE predicate on the "description" field. +func DescriptionLTE(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldDescription), v)) + }) +} + +// DescriptionContains applies the Contains predicate on the "description" field. +func DescriptionContains(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldDescription), v)) + }) +} + +// DescriptionHasPrefix applies the HasPrefix predicate on the "description" field. +func DescriptionHasPrefix(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldDescription), v)) + }) +} + +// DescriptionHasSuffix applies the HasSuffix predicate on the "description" field. +func DescriptionHasSuffix(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldDescription), v)) + }) +} + +// DescriptionIsNil applies the IsNil predicate on the "description" field. +func DescriptionIsNil() predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.IsNull(s.C(FieldDescription))) + }) +} + +// DescriptionNotNil applies the NotNil predicate on the "description" field. +func DescriptionNotNil() predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.NotNull(s.C(FieldDescription))) + }) +} + +// DescriptionEqualFold applies the EqualFold predicate on the "description" field. +func DescriptionEqualFold(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldDescription), v)) + }) +} + +// DescriptionContainsFold applies the ContainsFold predicate on the "description" field. +func DescriptionContainsFold(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldDescription), v)) + }) +} + +// NicknameEQ applies the EQ predicate on the "nickname" field. +func NicknameEQ(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldNickname), v)) + }) +} + +// NicknameNEQ applies the NEQ predicate on the "nickname" field. +func NicknameNEQ(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldNickname), v)) + }) +} + +// NicknameIn applies the In predicate on the "nickname" field. +func NicknameIn(vs ...string) predicate.User { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.User(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(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldNickname), v...)) + }) +} + +// NicknameNotIn applies the NotIn predicate on the "nickname" field. +func NicknameNotIn(vs ...string) predicate.User { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.User(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(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldNickname), v...)) + }) +} + +// NicknameGT applies the GT predicate on the "nickname" field. +func NicknameGT(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldNickname), v)) + }) +} + +// NicknameGTE applies the GTE predicate on the "nickname" field. +func NicknameGTE(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldNickname), v)) + }) +} + +// NicknameLT applies the LT predicate on the "nickname" field. +func NicknameLT(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldNickname), v)) + }) +} + +// NicknameLTE applies the LTE predicate on the "nickname" field. +func NicknameLTE(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldNickname), v)) + }) +} + +// NicknameContains applies the Contains predicate on the "nickname" field. +func NicknameContains(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldNickname), v)) + }) +} + +// NicknameHasPrefix applies the HasPrefix predicate on the "nickname" field. +func NicknameHasPrefix(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldNickname), v)) + }) +} + +// NicknameHasSuffix applies the HasSuffix predicate on the "nickname" field. +func NicknameHasSuffix(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldNickname), v)) + }) +} + +// NicknameEqualFold applies the EqualFold predicate on the "nickname" field. +func NicknameEqualFold(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldNickname), v)) + }) +} + +// NicknameContainsFold applies the ContainsFold predicate on the "nickname" field. +func NicknameContainsFold(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldNickname), v)) + }) +} + +// AddressEQ applies the EQ predicate on the "address" field. +func AddressEQ(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldAddress), v)) + }) +} + +// AddressNEQ applies the NEQ predicate on the "address" field. +func AddressNEQ(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldAddress), v)) + }) +} + +// AddressIn applies the In predicate on the "address" field. +func AddressIn(vs ...string) predicate.User { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.User(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(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldAddress), v...)) + }) +} + +// AddressNotIn applies the NotIn predicate on the "address" field. +func AddressNotIn(vs ...string) predicate.User { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.User(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(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldAddress), v...)) + }) +} + +// AddressGT applies the GT predicate on the "address" field. +func AddressGT(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldAddress), v)) + }) +} + +// AddressGTE applies the GTE predicate on the "address" field. +func AddressGTE(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldAddress), v)) + }) +} + +// AddressLT applies the LT predicate on the "address" field. +func AddressLT(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldAddress), v)) + }) +} + +// AddressLTE applies the LTE predicate on the "address" field. +func AddressLTE(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldAddress), v)) + }) +} + +// AddressContains applies the Contains predicate on the "address" field. +func AddressContains(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldAddress), v)) + }) +} + +// AddressHasPrefix applies the HasPrefix predicate on the "address" field. +func AddressHasPrefix(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldAddress), v)) + }) +} + +// AddressHasSuffix applies the HasSuffix predicate on the "address" field. +func AddressHasSuffix(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldAddress), v)) + }) +} + +// AddressIsNil applies the IsNil predicate on the "address" field. +func AddressIsNil() predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.IsNull(s.C(FieldAddress))) + }) +} + +// AddressNotNil applies the NotNil predicate on the "address" field. +func AddressNotNil() predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.NotNull(s.C(FieldAddress))) + }) +} + +// AddressEqualFold applies the EqualFold predicate on the "address" field. +func AddressEqualFold(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldAddress), v)) + }) +} + +// AddressContainsFold applies the ContainsFold predicate on the "address" field. +func AddressContainsFold(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldAddress), v)) + }) +} + +// RenamedEQ applies the EQ predicate on the "renamed" field. +func RenamedEQ(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldRenamed), v)) + }) +} + +// RenamedNEQ applies the NEQ predicate on the "renamed" field. +func RenamedNEQ(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldRenamed), v)) + }) +} + +// RenamedIn applies the In predicate on the "renamed" field. +func RenamedIn(vs ...string) predicate.User { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.User(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(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldRenamed), v...)) + }) +} + +// RenamedNotIn applies the NotIn predicate on the "renamed" field. +func RenamedNotIn(vs ...string) predicate.User { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.User(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(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldRenamed), v...)) + }) +} + +// RenamedGT applies the GT predicate on the "renamed" field. +func RenamedGT(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldRenamed), v)) + }) +} + +// RenamedGTE applies the GTE predicate on the "renamed" field. +func RenamedGTE(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldRenamed), v)) + }) +} + +// RenamedLT applies the LT predicate on the "renamed" field. +func RenamedLT(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldRenamed), v)) + }) +} + +// RenamedLTE applies the LTE predicate on the "renamed" field. +func RenamedLTE(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldRenamed), v)) + }) +} + +// RenamedContains applies the Contains predicate on the "renamed" field. +func RenamedContains(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldRenamed), v)) + }) +} + +// RenamedHasPrefix applies the HasPrefix predicate on the "renamed" field. +func RenamedHasPrefix(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldRenamed), v)) + }) +} + +// RenamedHasSuffix applies the HasSuffix predicate on the "renamed" field. +func RenamedHasSuffix(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldRenamed), v)) + }) +} + +// RenamedIsNil applies the IsNil predicate on the "renamed" field. +func RenamedIsNil() predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.IsNull(s.C(FieldRenamed))) + }) +} + +// RenamedNotNil applies the NotNil predicate on the "renamed" field. +func RenamedNotNil() predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.NotNull(s.C(FieldRenamed))) + }) +} + +// RenamedEqualFold applies the EqualFold predicate on the "renamed" field. +func RenamedEqualFold(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldRenamed), v)) + }) +} + +// RenamedContainsFold applies the ContainsFold predicate on the "renamed" field. +func RenamedContainsFold(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldRenamed), v)) + }) +} + +// BlobEQ applies the EQ predicate on the "blob" field. +func BlobEQ(v []byte) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldBlob), v)) + }) +} + +// BlobNEQ applies the NEQ predicate on the "blob" field. +func BlobNEQ(v []byte) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldBlob), v)) + }) +} + +// BlobIn applies the In predicate on the "blob" field. +func BlobIn(vs ...[]byte) predicate.User { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.User(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(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldBlob), v...)) + }) +} + +// BlobNotIn applies the NotIn predicate on the "blob" field. +func BlobNotIn(vs ...[]byte) predicate.User { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.User(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(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldBlob), v...)) + }) +} + +// BlobGT applies the GT predicate on the "blob" field. +func BlobGT(v []byte) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldBlob), v)) + }) +} + +// BlobGTE applies the GTE predicate on the "blob" field. +func BlobGTE(v []byte) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldBlob), v)) + }) +} + +// BlobLT applies the LT predicate on the "blob" field. +func BlobLT(v []byte) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldBlob), v)) + }) +} + +// BlobLTE applies the LTE predicate on the "blob" field. +func BlobLTE(v []byte) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldBlob), v)) + }) +} + +// BlobIsNil applies the IsNil predicate on the "blob" field. +func BlobIsNil() predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.IsNull(s.C(FieldBlob))) + }) +} + +// BlobNotNil applies the NotNil predicate on the "blob" field. +func BlobNotNil() predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.NotNull(s.C(FieldBlob))) + }) +} + +// StateEQ applies the EQ predicate on the "state" field. +func StateEQ(v State) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldState), v)) + }) +} + +// StateNEQ applies the NEQ predicate on the "state" field. +func StateNEQ(v State) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldState), v)) + }) +} + +// StateIn applies the In predicate on the "state" field. +func StateIn(vs ...State) predicate.User { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.User(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(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldState), v...)) + }) +} + +// StateNotIn applies the NotIn predicate on the "state" field. +func StateNotIn(vs ...State) predicate.User { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.User(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(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldState), v...)) + }) +} + +// StateIsNil applies the IsNil predicate on the "state" field. +func StateIsNil() predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.IsNull(s.C(FieldState))) + }) +} + +// StateNotNil applies the NotNil predicate on the "state" field. +func StateNotNil() predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.NotNull(s.C(FieldState))) + }) +} + +// StatusEQ applies the EQ predicate on the "status" field. +func StatusEQ(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldStatus), v)) + }) +} + +// StatusNEQ applies the NEQ predicate on the "status" field. +func StatusNEQ(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldStatus), v)) + }) +} + +// StatusIn applies the In predicate on the "status" field. +func StatusIn(vs ...string) predicate.User { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.User(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(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldStatus), v...)) + }) +} + +// StatusNotIn applies the NotIn predicate on the "status" field. +func StatusNotIn(vs ...string) predicate.User { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.User(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(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldStatus), v...)) + }) +} + +// StatusGT applies the GT predicate on the "status" field. +func StatusGT(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldStatus), v)) + }) +} + +// StatusGTE applies the GTE predicate on the "status" field. +func StatusGTE(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldStatus), v)) + }) +} + +// StatusLT applies the LT predicate on the "status" field. +func StatusLT(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldStatus), v)) + }) +} + +// StatusLTE applies the LTE predicate on the "status" field. +func StatusLTE(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldStatus), v)) + }) +} + +// StatusContains applies the Contains predicate on the "status" field. +func StatusContains(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldStatus), v)) + }) +} + +// StatusHasPrefix applies the HasPrefix predicate on the "status" field. +func StatusHasPrefix(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldStatus), v)) + }) +} + +// StatusHasSuffix applies the HasSuffix predicate on the "status" field. +func StatusHasSuffix(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldStatus), v)) + }) +} + +// StatusIsNil applies the IsNil predicate on the "status" field. +func StatusIsNil() predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.IsNull(s.C(FieldStatus))) + }) +} + +// StatusNotNil applies the NotNil predicate on the "status" field. +func StatusNotNil() predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.NotNull(s.C(FieldStatus))) + }) +} + +// StatusEqualFold applies the EqualFold predicate on the "status" field. +func StatusEqualFold(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldStatus), v)) + }) +} + +// StatusContainsFold applies the ContainsFold predicate on the "status" field. +func StatusContainsFold(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldStatus), v)) + }) +} + +// WorkplaceEQ applies the EQ predicate on the "workplace" field. +func WorkplaceEQ(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldWorkplace), v)) + }) +} + +// WorkplaceNEQ applies the NEQ predicate on the "workplace" field. +func WorkplaceNEQ(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldWorkplace), v)) + }) +} + +// WorkplaceIn applies the In predicate on the "workplace" field. +func WorkplaceIn(vs ...string) predicate.User { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.User(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(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldWorkplace), v...)) + }) +} + +// WorkplaceNotIn applies the NotIn predicate on the "workplace" field. +func WorkplaceNotIn(vs ...string) predicate.User { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.User(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(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldWorkplace), v...)) + }) +} + +// WorkplaceGT applies the GT predicate on the "workplace" field. +func WorkplaceGT(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldWorkplace), v)) + }) +} + +// WorkplaceGTE applies the GTE predicate on the "workplace" field. +func WorkplaceGTE(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldWorkplace), v)) + }) +} + +// WorkplaceLT applies the LT predicate on the "workplace" field. +func WorkplaceLT(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldWorkplace), v)) + }) +} + +// WorkplaceLTE applies the LTE predicate on the "workplace" field. +func WorkplaceLTE(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldWorkplace), v)) + }) +} + +// WorkplaceContains applies the Contains predicate on the "workplace" field. +func WorkplaceContains(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldWorkplace), v)) + }) +} + +// WorkplaceHasPrefix applies the HasPrefix predicate on the "workplace" field. +func WorkplaceHasPrefix(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldWorkplace), v)) + }) +} + +// WorkplaceHasSuffix applies the HasSuffix predicate on the "workplace" field. +func WorkplaceHasSuffix(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldWorkplace), v)) + }) +} + +// WorkplaceIsNil applies the IsNil predicate on the "workplace" field. +func WorkplaceIsNil() predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.IsNull(s.C(FieldWorkplace))) + }) +} + +// WorkplaceNotNil applies the NotNil predicate on the "workplace" field. +func WorkplaceNotNil() predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.NotNull(s.C(FieldWorkplace))) + }) +} + +// WorkplaceEqualFold applies the EqualFold predicate on the "workplace" field. +func WorkplaceEqualFold(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldWorkplace), v)) + }) +} + +// WorkplaceContainsFold applies the ContainsFold predicate on the "workplace" field. +func WorkplaceContainsFold(v string) predicate.User { + return predicate.User(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldWorkplace), v)) + }) +} + +// HasParent applies the HasEdge predicate on the "parent" edge. +func HasParent() predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ParentTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ParentTable, ParentColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasParentWith applies the HasEdge predicate on the "parent" edge with a given conditions (other predicates). +func HasParentWith(preds ...predicate.User) predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ParentTable, ParentColumn), + ) + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasChildren applies the HasEdge predicate on the "children" edge. +func HasChildren() predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ChildrenTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ChildrenTable, ChildrenColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasChildrenWith applies the HasEdge predicate on the "children" edge with a given conditions (other predicates). +func HasChildrenWith(preds ...predicate.User) predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ChildrenTable, ChildrenColumn), + ) + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasSpouse applies the HasEdge predicate on the "spouse" edge. +func HasSpouse() predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(SpouseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, SpouseTable, SpouseColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasSpouseWith applies the HasEdge predicate on the "spouse" edge with a given conditions (other predicates). +func HasSpouseWith(preds ...predicate.User) predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, SpouseTable, SpouseColumn), + ) + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasCar applies the HasEdge predicate on the "car" edge. +func HasCar() predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(CarTable, CarFieldID), + sqlgraph.Edge(sqlgraph.O2O, false, CarTable, CarColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasCarWith applies the HasEdge predicate on the "car" edge with a given conditions (other predicates). +func HasCarWith(preds ...predicate.Car) predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(CarInverseTable, CarFieldID), + sqlgraph.Edge(sqlgraph.O2O, false, CarTable, CarColumn), + ) + 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) { + 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.User) predicate.User { + return predicate.User(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.User) predicate.User { + return predicate.User(func(s *sql.Selector) { + p(s.Not()) + }) +} diff --git a/entc/integration/migrate/versioned/user_create.go b/entc/integration/migrate/versioned/user_create.go new file mode 100644 index 000000000..913df0623 --- /dev/null +++ b/entc/integration/migrate/versioned/user_create.go @@ -0,0 +1,587 @@ +// 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 versioned + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/migrate/versioned/car" + "entgo.io/ent/entc/integration/migrate/versioned/user" + "entgo.io/ent/schema/field" +) + +// UserCreate is the builder for creating a User entity. +type UserCreate struct { + config + mutation *UserMutation + hooks []Hook +} + +// SetAge sets the "age" field. +func (uc *UserCreate) SetAge(i int32) *UserCreate { + uc.mutation.SetAge(i) + return uc +} + +// SetName sets the "name" field. +func (uc *UserCreate) SetName(s string) *UserCreate { + uc.mutation.SetName(s) + return uc +} + +// SetDescription sets the "description" field. +func (uc *UserCreate) SetDescription(s string) *UserCreate { + uc.mutation.SetDescription(s) + return uc +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (uc *UserCreate) SetNillableDescription(s *string) *UserCreate { + if s != nil { + uc.SetDescription(*s) + } + return uc +} + +// SetNickname sets the "nickname" field. +func (uc *UserCreate) SetNickname(s string) *UserCreate { + uc.mutation.SetNickname(s) + return uc +} + +// SetAddress sets the "address" field. +func (uc *UserCreate) SetAddress(s string) *UserCreate { + uc.mutation.SetAddress(s) + return uc +} + +// SetNillableAddress sets the "address" field if the given value is not nil. +func (uc *UserCreate) SetNillableAddress(s *string) *UserCreate { + if s != nil { + uc.SetAddress(*s) + } + return uc +} + +// SetRenamed sets the "renamed" field. +func (uc *UserCreate) SetRenamed(s string) *UserCreate { + uc.mutation.SetRenamed(s) + return uc +} + +// SetNillableRenamed sets the "renamed" field if the given value is not nil. +func (uc *UserCreate) SetNillableRenamed(s *string) *UserCreate { + if s != nil { + uc.SetRenamed(*s) + } + return uc +} + +// SetBlob sets the "blob" field. +func (uc *UserCreate) SetBlob(b []byte) *UserCreate { + uc.mutation.SetBlob(b) + return uc +} + +// SetState sets the "state" field. +func (uc *UserCreate) SetState(u user.State) *UserCreate { + uc.mutation.SetState(u) + return uc +} + +// SetNillableState sets the "state" field if the given value is not nil. +func (uc *UserCreate) SetNillableState(u *user.State) *UserCreate { + if u != nil { + uc.SetState(*u) + } + return uc +} + +// SetStatus sets the "status" field. +func (uc *UserCreate) SetStatus(s string) *UserCreate { + uc.mutation.SetStatus(s) + return uc +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (uc *UserCreate) SetNillableStatus(s *string) *UserCreate { + if s != nil { + uc.SetStatus(*s) + } + return uc +} + +// SetWorkplace sets the "workplace" field. +func (uc *UserCreate) SetWorkplace(s string) *UserCreate { + uc.mutation.SetWorkplace(s) + return uc +} + +// SetNillableWorkplace sets the "workplace" field if the given value is not nil. +func (uc *UserCreate) SetNillableWorkplace(s *string) *UserCreate { + if s != nil { + uc.SetWorkplace(*s) + } + return uc +} + +// SetID sets the "id" field. +func (uc *UserCreate) SetID(i int) *UserCreate { + uc.mutation.SetID(i) + return uc +} + +// SetParentID sets the "parent" edge to the User entity by ID. +func (uc *UserCreate) SetParentID(id int) *UserCreate { + uc.mutation.SetParentID(id) + return uc +} + +// SetNillableParentID sets the "parent" edge to the User entity by ID if the given value is not nil. +func (uc *UserCreate) SetNillableParentID(id *int) *UserCreate { + if id != nil { + uc = uc.SetParentID(*id) + } + return uc +} + +// SetParent sets the "parent" edge to the User entity. +func (uc *UserCreate) SetParent(u *User) *UserCreate { + return uc.SetParentID(u.ID) +} + +// AddChildIDs adds the "children" edge to the User entity by IDs. +func (uc *UserCreate) AddChildIDs(ids ...int) *UserCreate { + uc.mutation.AddChildIDs(ids...) + return uc +} + +// AddChildren adds the "children" edges to the User entity. +func (uc *UserCreate) AddChildren(u ...*User) *UserCreate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uc.AddChildIDs(ids...) +} + +// SetSpouseID sets the "spouse" edge to the User entity by ID. +func (uc *UserCreate) SetSpouseID(id int) *UserCreate { + uc.mutation.SetSpouseID(id) + return uc +} + +// SetNillableSpouseID sets the "spouse" edge to the User entity by ID if the given value is not nil. +func (uc *UserCreate) SetNillableSpouseID(id *int) *UserCreate { + if id != nil { + uc = uc.SetSpouseID(*id) + } + return uc +} + +// SetSpouse sets the "spouse" edge to the User entity. +func (uc *UserCreate) SetSpouse(u *User) *UserCreate { + return uc.SetSpouseID(u.ID) +} + +// SetCarID sets the "car" edge to the Car entity by ID. +func (uc *UserCreate) SetCarID(id int) *UserCreate { + uc.mutation.SetCarID(id) + return uc +} + +// SetNillableCarID sets the "car" edge to the Car entity by ID if the given value is not nil. +func (uc *UserCreate) SetNillableCarID(id *int) *UserCreate { + if id != nil { + uc = uc.SetCarID(*id) + } + return uc +} + +// SetCar sets the "car" edge to the Car entity. +func (uc *UserCreate) SetCar(c *Car) *UserCreate { + return uc.SetCarID(c.ID) +} + +// Mutation returns the UserMutation object of the builder. +func (uc *UserCreate) Mutation() *UserMutation { + return uc.mutation +} + +// Save creates the User in the database. +func (uc *UserCreate) Save(ctx context.Context) (*User, error) { + var ( + err error + node *User + ) + if len(uc.hooks) == 0 { + if err = uc.check(); err != nil { + return nil, err + } + node, err = uc.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*UserMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = uc.check(); err != nil { + return nil, err + } + uc.mutation = mutation + if node, err = uc.sqlSave(ctx); err != nil { + return nil, err + } + mutation.id = &node.ID + mutation.done = true + return node, err + }) + for i := len(uc.hooks) - 1; i >= 0; i-- { + if uc.hooks[i] == nil { + return nil, fmt.Errorf("versioned: uninitialized hook (forgotten import versioned/runtime?)") + } + mut = uc.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, uc.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX calls Save and panics if Save returns an error. +func (uc *UserCreate) SaveX(ctx context.Context) *User { + v, err := uc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (uc *UserCreate) Exec(ctx context.Context) error { + _, err := uc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (uc *UserCreate) ExecX(ctx context.Context) { + if err := uc.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (uc *UserCreate) check() error { + if _, ok := uc.mutation.Age(); !ok { + return &ValidationError{Name: "age", err: errors.New(`versioned: missing required field "User.age"`)} + } + if _, ok := uc.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`versioned: missing required field "User.name"`)} + } + if v, ok := uc.mutation.Name(); ok { + if err := user.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`versioned: validator failed for field "User.name": %w`, err)} + } + } + if _, ok := uc.mutation.Nickname(); !ok { + return &ValidationError{Name: "nickname", err: errors.New(`versioned: missing required field "User.nickname"`)} + } + if v, ok := uc.mutation.Blob(); ok { + if err := user.BlobValidator(v); err != nil { + return &ValidationError{Name: "blob", err: fmt.Errorf(`versioned: validator failed for field "User.blob": %w`, err)} + } + } + if v, ok := uc.mutation.State(); ok { + if err := user.StateValidator(v); err != nil { + return &ValidationError{Name: "state", err: fmt.Errorf(`versioned: validator failed for field "User.state": %w`, err)} + } + } + if v, ok := uc.mutation.Workplace(); ok { + if err := user.WorkplaceValidator(v); err != nil { + return &ValidationError{Name: "workplace", err: fmt.Errorf(`versioned: validator failed for field "User.workplace": %w`, err)} + } + } + return nil +} + +func (uc *UserCreate) sqlSave(ctx context.Context) (*User, error) { + _node, _spec := uc.createSpec() + if err := sqlgraph.CreateNode(ctx, uc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + if _spec.ID.Value != _node.ID { + id := _spec.ID.Value.(int64) + _node.ID = int(id) + } + return _node, nil +} + +func (uc *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) { + var ( + _node = &User{config: uc.config} + _spec = &sqlgraph.CreateSpec{ + Table: user.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + } + ) + if id, ok := uc.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = id + } + if value, ok := uc.mutation.Age(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeInt32, + Value: value, + Column: user.FieldAge, + }) + _node.Age = value + } + if value, ok := uc.mutation.Name(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: user.FieldName, + }) + _node.Name = value + } + if value, ok := uc.mutation.Description(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: user.FieldDescription, + }) + _node.Description = value + } + if value, ok := uc.mutation.Nickname(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: user.FieldNickname, + }) + _node.Nickname = value + } + if value, ok := uc.mutation.Address(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: user.FieldAddress, + }) + _node.Address = value + } + if value, ok := uc.mutation.Renamed(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: user.FieldRenamed, + }) + _node.Renamed = value + } + if value, ok := uc.mutation.Blob(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeBytes, + Value: value, + Column: user.FieldBlob, + }) + _node.Blob = value + } + if value, ok := uc.mutation.State(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeEnum, + Value: value, + Column: user.FieldState, + }) + _node.State = value + } + if value, ok := uc.mutation.Status(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: user.FieldStatus, + }) + _node.Status = value + } + if value, ok := uc.mutation.Workplace(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: user.FieldWorkplace, + }) + _node.Workplace = value + } + if nodes := uc.mutation.ParentIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: user.ParentTable, + Columns: []string{user.ParentColumn}, + 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) + } + _node.user_children = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := uc.mutation.ChildrenIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.ChildrenTable, + Columns: []string{user.ChildrenColumn}, + 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) + } + if nodes := uc.mutation.SpouseIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: user.SpouseTable, + Columns: []string{user.SpouseColumn}, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.user_spouse = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := uc.mutation.CarIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: user.CarTable, + Columns: []string{user.CarColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: car.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// UserCreateBulk is the builder for creating many User entities in bulk. +type UserCreateBulk struct { + config + builders []*UserCreate +} + +// Save creates the User entities in the database. +func (ucb *UserCreateBulk) Save(ctx context.Context) ([]*User, error) { + specs := make([]*sqlgraph.CreateSpec, len(ucb.builders)) + nodes := make([]*User, len(ucb.builders)) + mutators := make([]Mutator, len(ucb.builders)) + for i := range ucb.builders { + func(i int, root context.Context) { + builder := ucb.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*UserMutation) + 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, ucb.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, ucb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + mutation.done = true + if specs[i].ID.Value != nil && 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, ucb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (ucb *UserCreateBulk) SaveX(ctx context.Context) []*User { + v, err := ucb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (ucb *UserCreateBulk) Exec(ctx context.Context) error { + _, err := ucb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ucb *UserCreateBulk) ExecX(ctx context.Context) { + if err := ucb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entc/integration/migrate/versioned/user_delete.go b/entc/integration/migrate/versioned/user_delete.go new file mode 100644 index 000000000..43ce4d9fa --- /dev/null +++ b/entc/integration/migrate/versioned/user_delete.go @@ -0,0 +1,115 @@ +// 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 versioned + +import ( + "context" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/migrate/versioned/predicate" + "entgo.io/ent/entc/integration/migrate/versioned/user" + "entgo.io/ent/schema/field" +) + +// UserDelete is the builder for deleting a User entity. +type UserDelete struct { + config + hooks []Hook + mutation *UserMutation +} + +// Where appends a list predicates to the UserDelete builder. +func (ud *UserDelete) Where(ps ...predicate.User) *UserDelete { + ud.mutation.Where(ps...) + return ud +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (ud *UserDelete) Exec(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(ud.hooks) == 0 { + affected, err = ud.sqlExec(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*UserMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + ud.mutation = mutation + affected, err = ud.sqlExec(ctx) + mutation.done = true + return affected, err + }) + for i := len(ud.hooks) - 1; i >= 0; i-- { + if ud.hooks[i] == nil { + return 0, fmt.Errorf("versioned: uninitialized hook (forgotten import versioned/runtime?)") + } + mut = ud.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, ud.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ud *UserDelete) ExecX(ctx context.Context) int { + n, err := ud.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (ud *UserDelete) sqlExec(ctx context.Context) (int, error) { + _spec := &sqlgraph.DeleteSpec{ + Node: &sqlgraph.NodeSpec{ + Table: user.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + if ps := ud.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return sqlgraph.DeleteNodes(ctx, ud.driver, _spec) +} + +// UserDeleteOne is the builder for deleting a single User entity. +type UserDeleteOne struct { + ud *UserDelete +} + +// Exec executes the deletion query. +func (udo *UserDeleteOne) Exec(ctx context.Context) error { + n, err := udo.ud.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{user.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (udo *UserDeleteOne) ExecX(ctx context.Context) { + udo.ud.ExecX(ctx) +} diff --git a/entc/integration/migrate/versioned/user_query.go b/entc/integration/migrate/versioned/user_query.go new file mode 100644 index 000000000..4c29b5e1e --- /dev/null +++ b/entc/integration/migrate/versioned/user_query.go @@ -0,0 +1,1199 @@ +// 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 versioned + +import ( + "context" + "database/sql/driver" + "errors" + "fmt" + "math" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/migrate/versioned/car" + "entgo.io/ent/entc/integration/migrate/versioned/predicate" + "entgo.io/ent/entc/integration/migrate/versioned/user" + "entgo.io/ent/schema/field" +) + +// UserQuery is the builder for querying User entities. +type UserQuery struct { + config + limit *int + offset *int + unique *bool + order []OrderFunc + fields []string + predicates []predicate.User + // eager-loading edges. + withParent *UserQuery + withChildren *UserQuery + withSpouse *UserQuery + withCar *CarQuery + withFKs bool + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the UserQuery builder. +func (uq *UserQuery) Where(ps ...predicate.User) *UserQuery { + uq.predicates = append(uq.predicates, ps...) + return uq +} + +// Limit adds a limit step to the query. +func (uq *UserQuery) Limit(limit int) *UserQuery { + uq.limit = &limit + return uq +} + +// Offset adds an offset step to the query. +func (uq *UserQuery) Offset(offset int) *UserQuery { + uq.offset = &offset + return uq +} + +// 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 (uq *UserQuery) Unique(unique bool) *UserQuery { + uq.unique = &unique + return uq +} + +// Order adds an order step to the query. +func (uq *UserQuery) Order(o ...OrderFunc) *UserQuery { + uq.order = append(uq.order, o...) + return uq +} + +// QueryParent chains the current query on the "parent" edge. +func (uq *UserQuery) QueryParent() *UserQuery { + query := &UserQuery{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(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, user.ParentTable, user.ParentColumn), + ) + fromU = sqlgraph.SetNeighbors(uq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryChildren chains the current query on the "children" edge. +func (uq *UserQuery) QueryChildren() *UserQuery { + query := &UserQuery{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(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, user.ChildrenTable, user.ChildrenColumn), + ) + fromU = sqlgraph.SetNeighbors(uq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QuerySpouse chains the current query on the "spouse" edge. +func (uq *UserQuery) QuerySpouse() *UserQuery { + query := &UserQuery{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(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, user.SpouseTable, user.SpouseColumn), + ) + fromU = sqlgraph.SetNeighbors(uq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryCar chains the current query on the "car" edge. +func (uq *UserQuery) QueryCar() *CarQuery { + query := &CarQuery{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(car.Table, car.FieldID), + sqlgraph.Edge(sqlgraph.O2O, false, user.CarTable, user.CarColumn), + ) + 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) { + nodes, err := uq.Limit(1).All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{user.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (uq *UserQuery) FirstX(ctx context.Context) *User { + node, err := uq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first User ID from the query. +// Returns a *NotFoundError when no User ID was found. +func (uq *UserQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = uq.Limit(1).IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{user.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (uq *UserQuery) FirstIDX(ctx context.Context) int { + id, err := uq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single User entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one User entity is found. +// Returns a *NotFoundError when no User entities are found. +func (uq *UserQuery) Only(ctx context.Context) (*User, error) { + nodes, err := uq.Limit(2).All(ctx) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{user.Label} + default: + return nil, &NotSingularError{user.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (uq *UserQuery) OnlyX(ctx context.Context) *User { + node, err := uq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only User ID in the query. +// Returns a *NotSingularError when more than one User ID is found. +// Returns a *NotFoundError when no entities are found. +func (uq *UserQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = uq.Limit(2).IDs(ctx); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{user.Label} + default: + err = &NotSingularError{user.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (uq *UserQuery) OnlyIDX(ctx context.Context) int { + id, err := uq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Users. +func (uq *UserQuery) All(ctx context.Context) ([]*User, error) { + if err := uq.prepareQuery(ctx); err != nil { + return nil, err + } + return uq.sqlAll(ctx) +} + +// AllX is like All, but panics if an error occurs. +func (uq *UserQuery) AllX(ctx context.Context) []*User { + nodes, err := uq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of User IDs. +func (uq *UserQuery) IDs(ctx context.Context) ([]int, error) { + var ids []int + if err := uq.Select(user.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (uq *UserQuery) IDsX(ctx context.Context) []int { + ids, err := uq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (uq *UserQuery) Count(ctx context.Context) (int, error) { + if err := uq.prepareQuery(ctx); err != nil { + return 0, err + } + return uq.sqlCount(ctx) +} + +// CountX is like Count, but panics if an error occurs. +func (uq *UserQuery) CountX(ctx context.Context) int { + count, err := uq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (uq *UserQuery) Exist(ctx context.Context) (bool, error) { + if err := uq.prepareQuery(ctx); err != nil { + return false, err + } + return uq.sqlExist(ctx) +} + +// ExistX is like Exist, but panics if an error occurs. +func (uq *UserQuery) ExistX(ctx context.Context) bool { + exist, err := uq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the UserQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (uq *UserQuery) Clone() *UserQuery { + if uq == nil { + return nil + } + return &UserQuery{ + config: uq.config, + limit: uq.limit, + offset: uq.offset, + order: append([]OrderFunc{}, uq.order...), + predicates: append([]predicate.User{}, uq.predicates...), + withParent: uq.withParent.Clone(), + withChildren: uq.withChildren.Clone(), + withSpouse: uq.withSpouse.Clone(), + withCar: uq.withCar.Clone(), + // clone intermediate query. + sql: uq.sql.Clone(), + path: uq.path, + unique: uq.unique, + } +} + +// WithParent tells the query-builder to eager-load the nodes that are connected to +// the "parent" edge. The optional arguments are used to configure the query builder of the edge. +func (uq *UserQuery) WithParent(opts ...func(*UserQuery)) *UserQuery { + query := &UserQuery{config: uq.config} + for _, opt := range opts { + opt(query) + } + uq.withParent = query + return uq +} + +// WithChildren tells the query-builder to eager-load the nodes that are connected to +// the "children" edge. The optional arguments are used to configure the query builder of the edge. +func (uq *UserQuery) WithChildren(opts ...func(*UserQuery)) *UserQuery { + query := &UserQuery{config: uq.config} + for _, opt := range opts { + opt(query) + } + uq.withChildren = query + return uq +} + +// WithSpouse tells the query-builder to eager-load the nodes that are connected to +// the "spouse" edge. The optional arguments are used to configure the query builder of the edge. +func (uq *UserQuery) WithSpouse(opts ...func(*UserQuery)) *UserQuery { + query := &UserQuery{config: uq.config} + for _, opt := range opts { + opt(query) + } + uq.withSpouse = query + return uq +} + +// WithCar tells the query-builder to eager-load the nodes that are connected to +// the "car" edge. The optional arguments are used to configure the query builder of the edge. +func (uq *UserQuery) WithCar(opts ...func(*CarQuery)) *UserQuery { + query := &CarQuery{config: uq.config} + for _, opt := range opts { + opt(query) + } + uq.withCar = 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. +// +// Example: +// +// var v []struct { +// Age int32 `json:"age,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.User.Query(). +// GroupBy(user.FieldAge). +// Aggregate(versioned.Count()). +// Scan(ctx, &v) +// +func (uq *UserQuery) GroupBy(field string, fields ...string) *UserGroupBy { + group := &UserGroupBy{config: uq.config} + group.fields = append([]string{field}, fields...) + group.path = func(ctx context.Context) (prev *sql.Selector, err error) { + if err := uq.prepareQuery(ctx); err != nil { + return nil, err + } + return uq.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 { +// Age int32 `json:"age,omitempty"` +// } +// +// client.User.Query(). +// Select(user.FieldAge). +// Scan(ctx, &v) +// +func (uq *UserQuery) Select(fields ...string) *UserSelect { + uq.fields = append(uq.fields, fields...) + return &UserSelect{UserQuery: uq} +} + +func (uq *UserQuery) prepareQuery(ctx context.Context) error { + for _, f := range uq.fields { + if !user.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("versioned: invalid field %q for query", f)} + } + } + if uq.path != nil { + prev, err := uq.path(ctx) + if err != nil { + return err + } + uq.sql = prev + } + return nil +} + +func (uq *UserQuery) sqlAll(ctx context.Context) ([]*User, error) { + var ( + nodes = []*User{} + withFKs = uq.withFKs + _spec = uq.querySpec() + loadedTypes = [4]bool{ + uq.withParent != nil, + uq.withChildren != nil, + uq.withSpouse != nil, + uq.withCar != nil, + } + ) + if uq.withParent != nil || uq.withSpouse != nil { + withFKs = true + } + if withFKs { + _spec.Node.Columns = append(_spec.Node.Columns, user.ForeignKeys...) + } + _spec.ScanValues = func(columns []string) ([]interface{}, error) { + node := &User{config: uq.config} + nodes = append(nodes, node) + return node.scanValues(columns) + } + _spec.Assign = func(columns []string, values []interface{}) error { + if len(nodes) == 0 { + return fmt.Errorf("versioned: Assign called without calling ScanValues") + } + node := nodes[len(nodes)-1] + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if err := sqlgraph.QueryNodes(ctx, uq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + + if query := uq.withParent; query != nil { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*User) + for i := range nodes { + if nodes[i].user_children == nil { + continue + } + fk := *nodes[i].user_children + if _, ok := nodeids[fk]; !ok { + 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 "user_children" returned %v`, n.ID) + } + for i := range nodes { + nodes[i].Edges.Parent = n + } + } + } + + if query := uq.withChildren; 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.Children = []*User{} + } + query.withFKs = true + query.Where(predicate.User(func(s *sql.Selector) { + s.Where(sql.InValues(user.ChildrenColumn, fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, n := range neighbors { + fk := n.user_children + if fk == nil { + return nil, fmt.Errorf(`foreign-key "user_children" is nil for node %v`, n.ID) + } + node, ok := nodeids[*fk] + if !ok { + return nil, fmt.Errorf(`unexpected foreign-key "user_children" returned %v for node %v`, *fk, n.ID) + } + node.Edges.Children = append(node.Edges.Children, n) + } + } + + if query := uq.withSpouse; query != nil { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*User) + for i := range nodes { + if nodes[i].user_spouse == nil { + continue + } + fk := *nodes[i].user_spouse + if _, ok := nodeids[fk]; !ok { + 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 "user_spouse" returned %v`, n.ID) + } + for i := range nodes { + nodes[i].Edges.Spouse = n + } + } + } + + if query := uq.withCar; 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] + } + query.withFKs = true + query.Where(predicate.Car(func(s *sql.Selector) { + s.Where(sql.InValues(user.CarColumn, fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, n := range neighbors { + fk := n.user_car + if fk == nil { + return nil, fmt.Errorf(`foreign-key "user_car" is nil for node %v`, n.ID) + } + node, ok := nodeids[*fk] + if !ok { + return nil, fmt.Errorf(`unexpected foreign-key "user_car" returned %v for node %v`, *fk, n.ID) + } + node.Edges.Car = n + } + } + + return nodes, nil +} + +func (uq *UserQuery) sqlCount(ctx context.Context) (int, error) { + _spec := uq.querySpec() + _spec.Node.Columns = uq.fields + if len(uq.fields) > 0 { + _spec.Unique = uq.unique != nil && *uq.unique + } + return sqlgraph.CountNodes(ctx, uq.driver, _spec) +} + +func (uq *UserQuery) sqlExist(ctx context.Context) (bool, error) { + n, err := uq.sqlCount(ctx) + if err != nil { + return false, fmt.Errorf("versioned: check existence: %w", err) + } + return n > 0, nil +} + +func (uq *UserQuery) querySpec() *sqlgraph.QuerySpec { + _spec := &sqlgraph.QuerySpec{ + Node: &sqlgraph.NodeSpec{ + Table: user.Table, + Columns: user.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + From: uq.sql, + Unique: true, + } + if unique := uq.unique; unique != nil { + _spec.Unique = *unique + } + if fields := uq.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, user.FieldID) + for i := range fields { + if fields[i] != user.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := uq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := uq.limit; limit != nil { + _spec.Limit = *limit + } + if offset := uq.offset; offset != nil { + _spec.Offset = *offset + } + if ps := uq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (uq *UserQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(uq.driver.Dialect()) + t1 := builder.Table(user.Table) + columns := uq.fields + if len(columns) == 0 { + columns = user.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if uq.sql != nil { + selector = uq.sql + selector.Select(selector.Columns(columns...)...) + } + if uq.unique != nil && *uq.unique { + selector.Distinct() + } + for _, p := range uq.predicates { + p(selector) + } + for _, p := range uq.order { + p(selector) + } + if offset := uq.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 := uq.limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// UserGroupBy is the group-by builder for User entities. +type UserGroupBy 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 (ugb *UserGroupBy) Aggregate(fns ...AggregateFunc) *UserGroupBy { + ugb.fns = append(ugb.fns, fns...) + return ugb +} + +// Scan applies the group-by query and scans the result into the given value. +func (ugb *UserGroupBy) Scan(ctx context.Context, v interface{}) error { + query, err := ugb.path(ctx) + if err != nil { + return err + } + ugb.sql = query + return ugb.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (ugb *UserGroupBy) ScanX(ctx context.Context, v interface{}) { + if err := ugb.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 (ugb *UserGroupBy) Strings(ctx context.Context) ([]string, error) { + if len(ugb.fields) > 1 { + return nil, errors.New("versioned: UserGroupBy.Strings is not achievable when grouping more than 1 field") + } + var v []string + if err := ugb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (ugb *UserGroupBy) StringsX(ctx context.Context) []string { + v, err := ugb.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 (ugb *UserGroupBy) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = ugb.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{user.Label} + default: + err = fmt.Errorf("versioned: UserGroupBy.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (ugb *UserGroupBy) StringX(ctx context.Context) string { + v, err := ugb.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 (ugb *UserGroupBy) Ints(ctx context.Context) ([]int, error) { + if len(ugb.fields) > 1 { + return nil, errors.New("versioned: UserGroupBy.Ints is not achievable when grouping more than 1 field") + } + var v []int + if err := ugb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (ugb *UserGroupBy) IntsX(ctx context.Context) []int { + v, err := ugb.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 (ugb *UserGroupBy) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = ugb.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{user.Label} + default: + err = fmt.Errorf("versioned: UserGroupBy.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (ugb *UserGroupBy) IntX(ctx context.Context) int { + v, err := ugb.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 (ugb *UserGroupBy) Float64s(ctx context.Context) ([]float64, error) { + if len(ugb.fields) > 1 { + return nil, errors.New("versioned: UserGroupBy.Float64s is not achievable when grouping more than 1 field") + } + var v []float64 + if err := ugb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (ugb *UserGroupBy) Float64sX(ctx context.Context) []float64 { + v, err := ugb.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 (ugb *UserGroupBy) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = ugb.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{user.Label} + default: + err = fmt.Errorf("versioned: UserGroupBy.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (ugb *UserGroupBy) Float64X(ctx context.Context) float64 { + v, err := ugb.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 (ugb *UserGroupBy) Bools(ctx context.Context) ([]bool, error) { + if len(ugb.fields) > 1 { + return nil, errors.New("versioned: UserGroupBy.Bools is not achievable when grouping more than 1 field") + } + var v []bool + if err := ugb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (ugb *UserGroupBy) BoolsX(ctx context.Context) []bool { + v, err := ugb.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 (ugb *UserGroupBy) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = ugb.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{user.Label} + default: + err = fmt.Errorf("versioned: UserGroupBy.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (ugb *UserGroupBy) BoolX(ctx context.Context) bool { + v, err := ugb.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (ugb *UserGroupBy) sqlScan(ctx context.Context, v interface{}) error { + for _, f := range ugb.fields { + if !user.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + } + } + selector := ugb.sqlQuery() + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := ugb.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +func (ugb *UserGroupBy) sqlQuery() *sql.Selector { + selector := ugb.sql.Select() + aggregation := make([]string, 0, len(ugb.fns)) + for _, fn := range ugb.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(ugb.fields)+len(ugb.fns)) + for _, f := range ugb.fields { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + return selector.GroupBy(selector.Columns(ugb.fields...)...) +} + +// UserSelect is the builder for selecting fields of User entities. +type UserSelect struct { + *UserQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector +} + +// Scan applies the selector query and scans the result into the given value. +func (us *UserSelect) Scan(ctx context.Context, v interface{}) error { + if err := us.prepareQuery(ctx); err != nil { + return err + } + us.sql = us.UserQuery.sqlQuery(ctx) + return us.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (us *UserSelect) ScanX(ctx context.Context, v interface{}) { + if err := us.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from a selector. It is only allowed when selecting one field. +func (us *UserSelect) Strings(ctx context.Context) ([]string, error) { + if len(us.fields) > 1 { + return nil, errors.New("versioned: UserSelect.Strings is not achievable when selecting more than 1 field") + } + var v []string + if err := us.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (us *UserSelect) StringsX(ctx context.Context) []string { + v, err := us.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 (us *UserSelect) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = us.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{user.Label} + default: + err = fmt.Errorf("versioned: UserSelect.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (us *UserSelect) StringX(ctx context.Context) string { + v, err := us.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 (us *UserSelect) Ints(ctx context.Context) ([]int, error) { + if len(us.fields) > 1 { + return nil, errors.New("versioned: UserSelect.Ints is not achievable when selecting more than 1 field") + } + var v []int + if err := us.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (us *UserSelect) IntsX(ctx context.Context) []int { + v, err := us.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 (us *UserSelect) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = us.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{user.Label} + default: + err = fmt.Errorf("versioned: UserSelect.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (us *UserSelect) IntX(ctx context.Context) int { + v, err := us.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 (us *UserSelect) Float64s(ctx context.Context) ([]float64, error) { + if len(us.fields) > 1 { + return nil, errors.New("versioned: UserSelect.Float64s is not achievable when selecting more than 1 field") + } + var v []float64 + if err := us.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (us *UserSelect) Float64sX(ctx context.Context) []float64 { + v, err := us.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 (us *UserSelect) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = us.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{user.Label} + default: + err = fmt.Errorf("versioned: UserSelect.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (us *UserSelect) Float64X(ctx context.Context) float64 { + v, err := us.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 (us *UserSelect) Bools(ctx context.Context) ([]bool, error) { + if len(us.fields) > 1 { + return nil, errors.New("versioned: UserSelect.Bools is not achievable when selecting more than 1 field") + } + var v []bool + if err := us.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (us *UserSelect) BoolsX(ctx context.Context) []bool { + v, err := us.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 (us *UserSelect) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = us.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{user.Label} + default: + err = fmt.Errorf("versioned: UserSelect.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (us *UserSelect) BoolX(ctx context.Context) bool { + v, err := us.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (us *UserSelect) sqlScan(ctx context.Context, v interface{}) error { + rows := &sql.Rows{} + query, args := us.sql.Query() + if err := us.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/entc/integration/migrate/versioned/user_update.go b/entc/integration/migrate/versioned/user_update.go new file mode 100644 index 000000000..572b296e9 --- /dev/null +++ b/entc/integration/migrate/versioned/user_update.go @@ -0,0 +1,1398 @@ +// 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 versioned + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/migrate/versioned/car" + "entgo.io/ent/entc/integration/migrate/versioned/predicate" + "entgo.io/ent/entc/integration/migrate/versioned/user" + "entgo.io/ent/schema/field" +) + +// UserUpdate is the builder for updating User entities. +type UserUpdate struct { + config + hooks []Hook + mutation *UserMutation +} + +// Where appends a list predicates to the UserUpdate builder. +func (uu *UserUpdate) Where(ps ...predicate.User) *UserUpdate { + uu.mutation.Where(ps...) + return uu +} + +// SetAge sets the "age" field. +func (uu *UserUpdate) SetAge(i int32) *UserUpdate { + uu.mutation.ResetAge() + uu.mutation.SetAge(i) + return uu +} + +// AddAge adds i to the "age" field. +func (uu *UserUpdate) AddAge(i int32) *UserUpdate { + uu.mutation.AddAge(i) + return uu +} + +// SetName sets the "name" field. +func (uu *UserUpdate) SetName(s string) *UserUpdate { + uu.mutation.SetName(s) + return uu +} + +// SetDescription sets the "description" field. +func (uu *UserUpdate) SetDescription(s string) *UserUpdate { + uu.mutation.SetDescription(s) + return uu +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (uu *UserUpdate) SetNillableDescription(s *string) *UserUpdate { + if s != nil { + uu.SetDescription(*s) + } + return uu +} + +// ClearDescription clears the value of the "description" field. +func (uu *UserUpdate) ClearDescription() *UserUpdate { + uu.mutation.ClearDescription() + return uu +} + +// SetNickname sets the "nickname" field. +func (uu *UserUpdate) SetNickname(s string) *UserUpdate { + uu.mutation.SetNickname(s) + return uu +} + +// SetAddress sets the "address" field. +func (uu *UserUpdate) SetAddress(s string) *UserUpdate { + uu.mutation.SetAddress(s) + return uu +} + +// SetNillableAddress sets the "address" field if the given value is not nil. +func (uu *UserUpdate) SetNillableAddress(s *string) *UserUpdate { + if s != nil { + uu.SetAddress(*s) + } + return uu +} + +// ClearAddress clears the value of the "address" field. +func (uu *UserUpdate) ClearAddress() *UserUpdate { + uu.mutation.ClearAddress() + return uu +} + +// SetRenamed sets the "renamed" field. +func (uu *UserUpdate) SetRenamed(s string) *UserUpdate { + uu.mutation.SetRenamed(s) + return uu +} + +// SetNillableRenamed sets the "renamed" field if the given value is not nil. +func (uu *UserUpdate) SetNillableRenamed(s *string) *UserUpdate { + if s != nil { + uu.SetRenamed(*s) + } + return uu +} + +// ClearRenamed clears the value of the "renamed" field. +func (uu *UserUpdate) ClearRenamed() *UserUpdate { + uu.mutation.ClearRenamed() + return uu +} + +// SetBlob sets the "blob" field. +func (uu *UserUpdate) SetBlob(b []byte) *UserUpdate { + uu.mutation.SetBlob(b) + return uu +} + +// ClearBlob clears the value of the "blob" field. +func (uu *UserUpdate) ClearBlob() *UserUpdate { + uu.mutation.ClearBlob() + return uu +} + +// SetState sets the "state" field. +func (uu *UserUpdate) SetState(u user.State) *UserUpdate { + uu.mutation.SetState(u) + return uu +} + +// SetNillableState sets the "state" field if the given value is not nil. +func (uu *UserUpdate) SetNillableState(u *user.State) *UserUpdate { + if u != nil { + uu.SetState(*u) + } + return uu +} + +// ClearState clears the value of the "state" field. +func (uu *UserUpdate) ClearState() *UserUpdate { + uu.mutation.ClearState() + return uu +} + +// SetStatus sets the "status" field. +func (uu *UserUpdate) SetStatus(s string) *UserUpdate { + uu.mutation.SetStatus(s) + return uu +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (uu *UserUpdate) SetNillableStatus(s *string) *UserUpdate { + if s != nil { + uu.SetStatus(*s) + } + return uu +} + +// ClearStatus clears the value of the "status" field. +func (uu *UserUpdate) ClearStatus() *UserUpdate { + uu.mutation.ClearStatus() + return uu +} + +// SetWorkplace sets the "workplace" field. +func (uu *UserUpdate) SetWorkplace(s string) *UserUpdate { + uu.mutation.SetWorkplace(s) + return uu +} + +// SetNillableWorkplace sets the "workplace" field if the given value is not nil. +func (uu *UserUpdate) SetNillableWorkplace(s *string) *UserUpdate { + if s != nil { + uu.SetWorkplace(*s) + } + return uu +} + +// ClearWorkplace clears the value of the "workplace" field. +func (uu *UserUpdate) ClearWorkplace() *UserUpdate { + uu.mutation.ClearWorkplace() + return uu +} + +// SetParentID sets the "parent" edge to the User entity by ID. +func (uu *UserUpdate) SetParentID(id int) *UserUpdate { + uu.mutation.SetParentID(id) + return uu +} + +// SetNillableParentID sets the "parent" edge to the User entity by ID if the given value is not nil. +func (uu *UserUpdate) SetNillableParentID(id *int) *UserUpdate { + if id != nil { + uu = uu.SetParentID(*id) + } + return uu +} + +// SetParent sets the "parent" edge to the User entity. +func (uu *UserUpdate) SetParent(u *User) *UserUpdate { + return uu.SetParentID(u.ID) +} + +// AddChildIDs adds the "children" edge to the User entity by IDs. +func (uu *UserUpdate) AddChildIDs(ids ...int) *UserUpdate { + uu.mutation.AddChildIDs(ids...) + return uu +} + +// AddChildren adds the "children" edges to the User entity. +func (uu *UserUpdate) AddChildren(u ...*User) *UserUpdate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uu.AddChildIDs(ids...) +} + +// SetSpouseID sets the "spouse" edge to the User entity by ID. +func (uu *UserUpdate) SetSpouseID(id int) *UserUpdate { + uu.mutation.SetSpouseID(id) + return uu +} + +// SetNillableSpouseID sets the "spouse" edge to the User entity by ID if the given value is not nil. +func (uu *UserUpdate) SetNillableSpouseID(id *int) *UserUpdate { + if id != nil { + uu = uu.SetSpouseID(*id) + } + return uu +} + +// SetSpouse sets the "spouse" edge to the User entity. +func (uu *UserUpdate) SetSpouse(u *User) *UserUpdate { + return uu.SetSpouseID(u.ID) +} + +// SetCarID sets the "car" edge to the Car entity by ID. +func (uu *UserUpdate) SetCarID(id int) *UserUpdate { + uu.mutation.SetCarID(id) + return uu +} + +// SetNillableCarID sets the "car" edge to the Car entity by ID if the given value is not nil. +func (uu *UserUpdate) SetNillableCarID(id *int) *UserUpdate { + if id != nil { + uu = uu.SetCarID(*id) + } + return uu +} + +// SetCar sets the "car" edge to the Car entity. +func (uu *UserUpdate) SetCar(c *Car) *UserUpdate { + return uu.SetCarID(c.ID) +} + +// Mutation returns the UserMutation object of the builder. +func (uu *UserUpdate) Mutation() *UserMutation { + return uu.mutation +} + +// ClearParent clears the "parent" edge to the User entity. +func (uu *UserUpdate) ClearParent() *UserUpdate { + uu.mutation.ClearParent() + return uu +} + +// ClearChildren clears all "children" edges to the User entity. +func (uu *UserUpdate) ClearChildren() *UserUpdate { + uu.mutation.ClearChildren() + return uu +} + +// RemoveChildIDs removes the "children" edge to User entities by IDs. +func (uu *UserUpdate) RemoveChildIDs(ids ...int) *UserUpdate { + uu.mutation.RemoveChildIDs(ids...) + return uu +} + +// RemoveChildren removes "children" edges to User entities. +func (uu *UserUpdate) RemoveChildren(u ...*User) *UserUpdate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uu.RemoveChildIDs(ids...) +} + +// ClearSpouse clears the "spouse" edge to the User entity. +func (uu *UserUpdate) ClearSpouse() *UserUpdate { + uu.mutation.ClearSpouse() + return uu +} + +// ClearCar clears the "car" edge to the Car entity. +func (uu *UserUpdate) ClearCar() *UserUpdate { + uu.mutation.ClearCar() + return uu +} + +// 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 ( + err error + affected int + ) + if len(uu.hooks) == 0 { + if err = uu.check(); err != nil { + return 0, err + } + affected, err = uu.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*UserMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = uu.check(); err != nil { + return 0, err + } + uu.mutation = mutation + affected, err = uu.sqlSave(ctx) + mutation.done = true + return affected, err + }) + for i := len(uu.hooks) - 1; i >= 0; i-- { + if uu.hooks[i] == nil { + return 0, fmt.Errorf("versioned: uninitialized hook (forgotten import versioned/runtime?)") + } + mut = uu.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, uu.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// SaveX is like Save, but panics if an error occurs. +func (uu *UserUpdate) SaveX(ctx context.Context) int { + affected, err := uu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (uu *UserUpdate) Exec(ctx context.Context) error { + _, err := uu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (uu *UserUpdate) ExecX(ctx context.Context) { + if err := uu.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (uu *UserUpdate) check() error { + if v, ok := uu.mutation.Name(); ok { + if err := user.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`versioned: validator failed for field "User.name": %w`, err)} + } + } + if v, ok := uu.mutation.Blob(); ok { + if err := user.BlobValidator(v); err != nil { + return &ValidationError{Name: "blob", err: fmt.Errorf(`versioned: validator failed for field "User.blob": %w`, err)} + } + } + if v, ok := uu.mutation.State(); ok { + if err := user.StateValidator(v); err != nil { + return &ValidationError{Name: "state", err: fmt.Errorf(`versioned: validator failed for field "User.state": %w`, err)} + } + } + if v, ok := uu.mutation.Workplace(); ok { + if err := user.WorkplaceValidator(v); err != nil { + return &ValidationError{Name: "workplace", err: fmt.Errorf(`versioned: validator failed for field "User.workplace": %w`, err)} + } + } + return nil +} + +func (uu *UserUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: user.Table, + Columns: user.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + if ps := uu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := uu.mutation.Age(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeInt32, + Value: value, + Column: user.FieldAge, + }) + } + if value, ok := uu.mutation.AddedAge(); ok { + _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ + Type: field.TypeInt32, + Value: value, + Column: user.FieldAge, + }) + } + if value, ok := uu.mutation.Name(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: user.FieldName, + }) + } + if value, ok := uu.mutation.Description(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: user.FieldDescription, + }) + } + if uu.mutation.DescriptionCleared() { + _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Column: user.FieldDescription, + }) + } + if value, ok := uu.mutation.Nickname(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: user.FieldNickname, + }) + } + if value, ok := uu.mutation.Address(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: user.FieldAddress, + }) + } + if uu.mutation.AddressCleared() { + _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Column: user.FieldAddress, + }) + } + if value, ok := uu.mutation.Renamed(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: user.FieldRenamed, + }) + } + if uu.mutation.RenamedCleared() { + _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Column: user.FieldRenamed, + }) + } + if value, ok := uu.mutation.Blob(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeBytes, + Value: value, + Column: user.FieldBlob, + }) + } + if uu.mutation.BlobCleared() { + _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ + Type: field.TypeBytes, + Column: user.FieldBlob, + }) + } + if value, ok := uu.mutation.State(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeEnum, + Value: value, + Column: user.FieldState, + }) + } + if uu.mutation.StateCleared() { + _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ + Type: field.TypeEnum, + Column: user.FieldState, + }) + } + if value, ok := uu.mutation.Status(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: user.FieldStatus, + }) + } + if uu.mutation.StatusCleared() { + _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Column: user.FieldStatus, + }) + } + if value, ok := uu.mutation.Workplace(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: user.FieldWorkplace, + }) + } + if uu.mutation.WorkplaceCleared() { + _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Column: user.FieldWorkplace, + }) + } + if uu.mutation.ParentCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: user.ParentTable, + Columns: []string{user.ParentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uu.mutation.ParentIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: user.ParentTable, + Columns: []string{user.ParentColumn}, + 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 uu.mutation.ChildrenCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.ChildrenTable, + Columns: []string{user.ChildrenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uu.mutation.RemovedChildrenIDs(); len(nodes) > 0 && !uu.mutation.ChildrenCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.ChildrenTable, + Columns: []string{user.ChildrenColumn}, + 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 := uu.mutation.ChildrenIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.ChildrenTable, + Columns: []string{user.ChildrenColumn}, + 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 uu.mutation.SpouseCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: user.SpouseTable, + Columns: []string{user.SpouseColumn}, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uu.mutation.SpouseIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: user.SpouseTable, + Columns: []string{user.SpouseColumn}, + Bidi: true, + 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 uu.mutation.CarCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: user.CarTable, + Columns: []string{user.CarColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: car.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uu.mutation.CarIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: user.CarTable, + Columns: []string{user.CarColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: car.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} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return 0, err + } + return n, nil +} + +// UserUpdateOne is the builder for updating a single User entity. +type UserUpdateOne struct { + config + fields []string + hooks []Hook + mutation *UserMutation +} + +// SetAge sets the "age" field. +func (uuo *UserUpdateOne) SetAge(i int32) *UserUpdateOne { + uuo.mutation.ResetAge() + uuo.mutation.SetAge(i) + return uuo +} + +// AddAge adds i to the "age" field. +func (uuo *UserUpdateOne) AddAge(i int32) *UserUpdateOne { + uuo.mutation.AddAge(i) + return uuo +} + +// SetName sets the "name" field. +func (uuo *UserUpdateOne) SetName(s string) *UserUpdateOne { + uuo.mutation.SetName(s) + return uuo +} + +// SetDescription sets the "description" field. +func (uuo *UserUpdateOne) SetDescription(s string) *UserUpdateOne { + uuo.mutation.SetDescription(s) + return uuo +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (uuo *UserUpdateOne) SetNillableDescription(s *string) *UserUpdateOne { + if s != nil { + uuo.SetDescription(*s) + } + return uuo +} + +// ClearDescription clears the value of the "description" field. +func (uuo *UserUpdateOne) ClearDescription() *UserUpdateOne { + uuo.mutation.ClearDescription() + return uuo +} + +// SetNickname sets the "nickname" field. +func (uuo *UserUpdateOne) SetNickname(s string) *UserUpdateOne { + uuo.mutation.SetNickname(s) + return uuo +} + +// SetAddress sets the "address" field. +func (uuo *UserUpdateOne) SetAddress(s string) *UserUpdateOne { + uuo.mutation.SetAddress(s) + return uuo +} + +// SetNillableAddress sets the "address" field if the given value is not nil. +func (uuo *UserUpdateOne) SetNillableAddress(s *string) *UserUpdateOne { + if s != nil { + uuo.SetAddress(*s) + } + return uuo +} + +// ClearAddress clears the value of the "address" field. +func (uuo *UserUpdateOne) ClearAddress() *UserUpdateOne { + uuo.mutation.ClearAddress() + return uuo +} + +// SetRenamed sets the "renamed" field. +func (uuo *UserUpdateOne) SetRenamed(s string) *UserUpdateOne { + uuo.mutation.SetRenamed(s) + return uuo +} + +// SetNillableRenamed sets the "renamed" field if the given value is not nil. +func (uuo *UserUpdateOne) SetNillableRenamed(s *string) *UserUpdateOne { + if s != nil { + uuo.SetRenamed(*s) + } + return uuo +} + +// ClearRenamed clears the value of the "renamed" field. +func (uuo *UserUpdateOne) ClearRenamed() *UserUpdateOne { + uuo.mutation.ClearRenamed() + return uuo +} + +// SetBlob sets the "blob" field. +func (uuo *UserUpdateOne) SetBlob(b []byte) *UserUpdateOne { + uuo.mutation.SetBlob(b) + return uuo +} + +// ClearBlob clears the value of the "blob" field. +func (uuo *UserUpdateOne) ClearBlob() *UserUpdateOne { + uuo.mutation.ClearBlob() + return uuo +} + +// SetState sets the "state" field. +func (uuo *UserUpdateOne) SetState(u user.State) *UserUpdateOne { + uuo.mutation.SetState(u) + return uuo +} + +// SetNillableState sets the "state" field if the given value is not nil. +func (uuo *UserUpdateOne) SetNillableState(u *user.State) *UserUpdateOne { + if u != nil { + uuo.SetState(*u) + } + return uuo +} + +// ClearState clears the value of the "state" field. +func (uuo *UserUpdateOne) ClearState() *UserUpdateOne { + uuo.mutation.ClearState() + return uuo +} + +// SetStatus sets the "status" field. +func (uuo *UserUpdateOne) SetStatus(s string) *UserUpdateOne { + uuo.mutation.SetStatus(s) + return uuo +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (uuo *UserUpdateOne) SetNillableStatus(s *string) *UserUpdateOne { + if s != nil { + uuo.SetStatus(*s) + } + return uuo +} + +// ClearStatus clears the value of the "status" field. +func (uuo *UserUpdateOne) ClearStatus() *UserUpdateOne { + uuo.mutation.ClearStatus() + return uuo +} + +// SetWorkplace sets the "workplace" field. +func (uuo *UserUpdateOne) SetWorkplace(s string) *UserUpdateOne { + uuo.mutation.SetWorkplace(s) + return uuo +} + +// SetNillableWorkplace sets the "workplace" field if the given value is not nil. +func (uuo *UserUpdateOne) SetNillableWorkplace(s *string) *UserUpdateOne { + if s != nil { + uuo.SetWorkplace(*s) + } + return uuo +} + +// ClearWorkplace clears the value of the "workplace" field. +func (uuo *UserUpdateOne) ClearWorkplace() *UserUpdateOne { + uuo.mutation.ClearWorkplace() + return uuo +} + +// SetParentID sets the "parent" edge to the User entity by ID. +func (uuo *UserUpdateOne) SetParentID(id int) *UserUpdateOne { + uuo.mutation.SetParentID(id) + return uuo +} + +// SetNillableParentID sets the "parent" edge to the User entity by ID if the given value is not nil. +func (uuo *UserUpdateOne) SetNillableParentID(id *int) *UserUpdateOne { + if id != nil { + uuo = uuo.SetParentID(*id) + } + return uuo +} + +// SetParent sets the "parent" edge to the User entity. +func (uuo *UserUpdateOne) SetParent(u *User) *UserUpdateOne { + return uuo.SetParentID(u.ID) +} + +// AddChildIDs adds the "children" edge to the User entity by IDs. +func (uuo *UserUpdateOne) AddChildIDs(ids ...int) *UserUpdateOne { + uuo.mutation.AddChildIDs(ids...) + return uuo +} + +// AddChildren adds the "children" edges to the User entity. +func (uuo *UserUpdateOne) AddChildren(u ...*User) *UserUpdateOne { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uuo.AddChildIDs(ids...) +} + +// SetSpouseID sets the "spouse" edge to the User entity by ID. +func (uuo *UserUpdateOne) SetSpouseID(id int) *UserUpdateOne { + uuo.mutation.SetSpouseID(id) + return uuo +} + +// SetNillableSpouseID sets the "spouse" edge to the User entity by ID if the given value is not nil. +func (uuo *UserUpdateOne) SetNillableSpouseID(id *int) *UserUpdateOne { + if id != nil { + uuo = uuo.SetSpouseID(*id) + } + return uuo +} + +// SetSpouse sets the "spouse" edge to the User entity. +func (uuo *UserUpdateOne) SetSpouse(u *User) *UserUpdateOne { + return uuo.SetSpouseID(u.ID) +} + +// SetCarID sets the "car" edge to the Car entity by ID. +func (uuo *UserUpdateOne) SetCarID(id int) *UserUpdateOne { + uuo.mutation.SetCarID(id) + return uuo +} + +// SetNillableCarID sets the "car" edge to the Car entity by ID if the given value is not nil. +func (uuo *UserUpdateOne) SetNillableCarID(id *int) *UserUpdateOne { + if id != nil { + uuo = uuo.SetCarID(*id) + } + return uuo +} + +// SetCar sets the "car" edge to the Car entity. +func (uuo *UserUpdateOne) SetCar(c *Car) *UserUpdateOne { + return uuo.SetCarID(c.ID) +} + +// Mutation returns the UserMutation object of the builder. +func (uuo *UserUpdateOne) Mutation() *UserMutation { + return uuo.mutation +} + +// ClearParent clears the "parent" edge to the User entity. +func (uuo *UserUpdateOne) ClearParent() *UserUpdateOne { + uuo.mutation.ClearParent() + return uuo +} + +// ClearChildren clears all "children" edges to the User entity. +func (uuo *UserUpdateOne) ClearChildren() *UserUpdateOne { + uuo.mutation.ClearChildren() + return uuo +} + +// RemoveChildIDs removes the "children" edge to User entities by IDs. +func (uuo *UserUpdateOne) RemoveChildIDs(ids ...int) *UserUpdateOne { + uuo.mutation.RemoveChildIDs(ids...) + return uuo +} + +// RemoveChildren removes "children" edges to User entities. +func (uuo *UserUpdateOne) RemoveChildren(u ...*User) *UserUpdateOne { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uuo.RemoveChildIDs(ids...) +} + +// ClearSpouse clears the "spouse" edge to the User entity. +func (uuo *UserUpdateOne) ClearSpouse() *UserUpdateOne { + uuo.mutation.ClearSpouse() + return uuo +} + +// ClearCar clears the "car" edge to the Car entity. +func (uuo *UserUpdateOne) ClearCar() *UserUpdateOne { + uuo.mutation.ClearCar() + return uuo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (uuo *UserUpdateOne) Select(field string, fields ...string) *UserUpdateOne { + uuo.fields = append([]string{field}, fields...) + return uuo +} + +// Save executes the query and returns the updated User entity. +func (uuo *UserUpdateOne) Save(ctx context.Context) (*User, error) { + var ( + err error + node *User + ) + if len(uuo.hooks) == 0 { + if err = uuo.check(); err != nil { + return nil, err + } + node, err = uuo.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*UserMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = uuo.check(); err != nil { + return nil, err + } + uuo.mutation = mutation + node, err = uuo.sqlSave(ctx) + mutation.done = true + return node, err + }) + for i := len(uuo.hooks) - 1; i >= 0; i-- { + if uuo.hooks[i] == nil { + return nil, fmt.Errorf("versioned: uninitialized hook (forgotten import versioned/runtime?)") + } + mut = uuo.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, uuo.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX is like Save, but panics if an error occurs. +func (uuo *UserUpdateOne) SaveX(ctx context.Context) *User { + node, err := uuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (uuo *UserUpdateOne) Exec(ctx context.Context) error { + _, err := uuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (uuo *UserUpdateOne) ExecX(ctx context.Context) { + if err := uuo.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (uuo *UserUpdateOne) check() error { + if v, ok := uuo.mutation.Name(); ok { + if err := user.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`versioned: validator failed for field "User.name": %w`, err)} + } + } + if v, ok := uuo.mutation.Blob(); ok { + if err := user.BlobValidator(v); err != nil { + return &ValidationError{Name: "blob", err: fmt.Errorf(`versioned: validator failed for field "User.blob": %w`, err)} + } + } + if v, ok := uuo.mutation.State(); ok { + if err := user.StateValidator(v); err != nil { + return &ValidationError{Name: "state", err: fmt.Errorf(`versioned: validator failed for field "User.state": %w`, err)} + } + } + if v, ok := uuo.mutation.Workplace(); ok { + if err := user.WorkplaceValidator(v); err != nil { + return &ValidationError{Name: "workplace", err: fmt.Errorf(`versioned: validator failed for field "User.workplace": %w`, err)} + } + } + return nil +} + +func (uuo *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: user.Table, + Columns: user.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + id, ok := uuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`versioned: missing "User.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := uuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, user.FieldID) + for _, f := range fields { + if !user.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("versioned: invalid field %q for query", f)} + } + if f != user.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := uuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := uuo.mutation.Age(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeInt32, + Value: value, + Column: user.FieldAge, + }) + } + if value, ok := uuo.mutation.AddedAge(); ok { + _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ + Type: field.TypeInt32, + Value: value, + Column: user.FieldAge, + }) + } + if value, ok := uuo.mutation.Name(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: user.FieldName, + }) + } + if value, ok := uuo.mutation.Description(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: user.FieldDescription, + }) + } + if uuo.mutation.DescriptionCleared() { + _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Column: user.FieldDescription, + }) + } + if value, ok := uuo.mutation.Nickname(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: user.FieldNickname, + }) + } + if value, ok := uuo.mutation.Address(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: user.FieldAddress, + }) + } + if uuo.mutation.AddressCleared() { + _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Column: user.FieldAddress, + }) + } + if value, ok := uuo.mutation.Renamed(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: user.FieldRenamed, + }) + } + if uuo.mutation.RenamedCleared() { + _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Column: user.FieldRenamed, + }) + } + if value, ok := uuo.mutation.Blob(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeBytes, + Value: value, + Column: user.FieldBlob, + }) + } + if uuo.mutation.BlobCleared() { + _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ + Type: field.TypeBytes, + Column: user.FieldBlob, + }) + } + if value, ok := uuo.mutation.State(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeEnum, + Value: value, + Column: user.FieldState, + }) + } + if uuo.mutation.StateCleared() { + _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ + Type: field.TypeEnum, + Column: user.FieldState, + }) + } + if value, ok := uuo.mutation.Status(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: user.FieldStatus, + }) + } + if uuo.mutation.StatusCleared() { + _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Column: user.FieldStatus, + }) + } + if value, ok := uuo.mutation.Workplace(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: user.FieldWorkplace, + }) + } + if uuo.mutation.WorkplaceCleared() { + _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Column: user.FieldWorkplace, + }) + } + if uuo.mutation.ParentCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: user.ParentTable, + Columns: []string{user.ParentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uuo.mutation.ParentIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: user.ParentTable, + Columns: []string{user.ParentColumn}, + 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 uuo.mutation.ChildrenCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.ChildrenTable, + Columns: []string{user.ChildrenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uuo.mutation.RemovedChildrenIDs(); len(nodes) > 0 && !uuo.mutation.ChildrenCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.ChildrenTable, + Columns: []string{user.ChildrenColumn}, + 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 := uuo.mutation.ChildrenIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.ChildrenTable, + Columns: []string{user.ChildrenColumn}, + 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 uuo.mutation.SpouseCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: user.SpouseTable, + Columns: []string{user.SpouseColumn}, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: user.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uuo.mutation.SpouseIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: user.SpouseTable, + Columns: []string{user.SpouseColumn}, + Bidi: true, + 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 uuo.mutation.CarCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: user.CarTable, + Columns: []string{user.CarColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: car.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uuo.mutation.CarIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2O, + Inverse: false, + Table: user.CarTable, + Columns: []string{user.CarColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: car.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 + if err = sqlgraph.UpdateNode(ctx, uuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{user.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + return _node, nil +} diff --git a/go.mod b/go.mod index cf849487d..e9250a209 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module entgo.io/ent go 1.17 require ( - ariga.io/atlas v0.3.4-0.20220209093922-b6680bb15369 + ariga.io/atlas v0.3.5-0.20220215131223-8043663b4223 github.com/DATA-DOG/go-sqlmock v1.5.0 github.com/go-openapi/inflect v0.19.0 github.com/go-sql-driver/mysql v1.6.0 @@ -32,6 +32,7 @@ require ( github.com/google/go-cmp v0.5.6 // indirect github.com/hashicorp/hcl/v2 v2.10.0 // indirect github.com/inconshreveable/mousetrap v1.0.0 // indirect + github.com/kr/pretty v0.2.1 // indirect github.com/mattn/go-runewidth v0.0.9 // indirect github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect @@ -42,5 +43,6 @@ require ( golang.org/x/sys v0.0.0-20211205182925-97ca703d548d // indirect golang.org/x/text v0.3.7 // indirect golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect + gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect ) diff --git a/go.sum b/go.sum index 38224f044..805727269 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,5 @@ -ariga.io/atlas v0.3.4-0.20220209093922-b6680bb15369 h1:Gqv5aaKYPfeu4kivgE4DwQ23rqk8f53i6oW2O8piWA0= -ariga.io/atlas v0.3.4-0.20220209093922-b6680bb15369/go.mod h1:XcLUpQX7Cq4qtagEHIleq3MJaBeeJ76BS8doc4gkOJk= +ariga.io/atlas v0.3.5-0.20220215131223-8043663b4223 h1:kthcdfUZLRcoVeZetK8gJ0FGaw2D5zrr3h2nP/TuXCw= +ariga.io/atlas v0.3.5-0.20220215131223-8043663b4223/go.mod h1:XcLUpQX7Cq4qtagEHIleq3MJaBeeJ76BS8doc4gkOJk= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU= @@ -268,8 +268,9 @@ github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxv github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= -github.com/kr/pretty v0.2.0 h1:s5hAObm+yFO5uHYt5dYjxi2rXrsnmRpJx4OYvIWUaQs= github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= +github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI= +github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= @@ -815,8 +816,9 @@ google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQ gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/ini.v1 v1.66.2/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=