diff --git a/entc/gen/template/dialect/sql/decode.tmpl b/entc/gen/template/dialect/sql/decode.tmpl index 31750f345..25fe5baab 100644 --- a/entc/gen/template/dialect/sql/decode.tmpl +++ b/entc/gen/template/dialect/sql/decode.tmpl @@ -71,7 +71,7 @@ func ({{ $receiver }} *{{ $.Name }}) assignValues(columns []string, values []int {{- range $i, $fk := $.UnexportedForeignKeys }} {{- $f := $fk.Field }} case {{ if $fk.UserDefined }}{{ $.Package }}.{{ $.ID.Constant }}{{ else }}{{ $.Package }}.ForeignKeys[{{ $i }}]{{ end }}: - {{- if or $fk.UserDefined (and $f.UserDefined (or $f.IsString $f.IsUUID $f.IsBytes)) }} + {{- if or $fk.UserDefined (and $f.UserDefined (or $f.IsString $f.IsUUID $f.IsBytes $f.IsOther)) }} {{- with extend $ "Idx" $idx "Field" $f "Rec" $receiver "StructField" $fk.StructField }} {{ template "dialect/sql/decode/field" . }} {{- end }} diff --git a/entc/integration/customid/customid_test.go b/entc/integration/customid/customid_test.go index 4319195ba..2d86ca333 100644 --- a/entc/integration/customid/customid_test.go +++ b/entc/integration/customid/customid_test.go @@ -18,6 +18,7 @@ import ( "entgo.io/ent/entc/integration/customid/ent/blob" "entgo.io/ent/entc/integration/customid/ent/doc" "entgo.io/ent/entc/integration/customid/ent/pet" + "entgo.io/ent/entc/integration/customid/ent/token" "entgo.io/ent/entc/integration/customid/ent/user" "entgo.io/ent/entc/integration/customid/sid" "entgo.io/ent/schema/field" @@ -198,12 +199,25 @@ func CustomID(t *testing.T, client *ent.Client) { require.Equal(t, "Hello World", client.Doc.GetX(ctx, d.ID).Text) }) - t.Run("OtherID", func(t *testing.T) { - other := client.Other.Create().SaveX(ctx) - require.NotEmpty(t, other.ID.String()) + t.Run("Other ID", func(t *testing.T) { + o := client.Other.Create().SaveX(ctx) + require.NotEmpty(t, o.ID.String()) - other = client.Other.Create().SetID(sid.NewLength(15)).SaveX(ctx) - require.NotEmpty(t, other.ID.String()) + o = client.Other.Create().SetID(sid.NewLength(15)).SaveX(ctx) + require.NotEmpty(t, o.ID.String()) + }) + + t.Run("CustomID edge", func(t *testing.T) { + a := client.Account.Create().SetEmail("test@example.org").SaveX(ctx) + require.NotEmpty(t, a.ID) + + tk := client.Token.Create().SetAccountID(a.ID).SetBody("token").SaveX(ctx) + require.NotEmpty(t, tk.ID) + + ta := client.Token.Query().Where(token.Body("token")).WithAccount().FirstX(ctx) + require.Equal(t, tk.ID, ta.ID) + require.NotNil(t, ta.Edges.Account) + require.Equal(t, a.ID, ta.Edges.Account.ID) }) } @@ -220,7 +234,7 @@ func BytesID(t *testing.T, client *ent.Client) { // clearDefault clears the id's default for non-postgres dialects. func clearDefault(c schema.Creator) schema.Creator { return schema.CreateFunc(func(ctx context.Context, tables ...*schema.Table) error { - tables[0].Columns[0].Default = nil + tables[1].Columns[0].Default = nil return c.Create(ctx, tables...) }) } diff --git a/entc/integration/customid/ent/account.go b/entc/integration/customid/ent/account.go new file mode 100644 index 000000000..16b5e103a --- /dev/null +++ b/entc/integration/customid/ent/account.go @@ -0,0 +1,130 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/entc/integration/customid/ent/account" + "entgo.io/ent/entc/integration/customid/sid" +) + +// Account is the model entity for the Account schema. +type Account struct { + config `json:"-"` + // ID of the ent. + ID sid.ID `json:"id,omitempty"` + // Email holds the value of the "email" field. + Email string `json:"email,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the AccountQuery when eager-loading is set. + Edges AccountEdges `json:"edges"` +} + +// AccountEdges holds the relations/edges for other nodes in the graph. +type AccountEdges struct { + // Token holds the value of the token edge. + Token []*Token `json:"token,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// TokenOrErr returns the Token value or an error if the edge +// was not loaded in eager-loading. +func (e AccountEdges) TokenOrErr() ([]*Token, error) { + if e.loadedTypes[0] { + return e.Token, nil + } + return nil, &NotLoadedError{edge: "token"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Account) scanValues(columns []string) ([]interface{}, error) { + values := make([]interface{}, len(columns)) + for i := range columns { + switch columns[i] { + case account.FieldID: + values[i] = new(sid.ID) + case account.FieldEmail: + values[i] = new(sql.NullString) + default: + return nil, fmt.Errorf("unexpected column %q for type Account", columns[i]) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the Account fields. +func (a *Account) 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 account.FieldID: + if value, ok := values[i].(*sid.ID); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value != nil { + a.ID = *value + } + case account.FieldEmail: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field email", values[i]) + } else if value.Valid { + a.Email = value.String + } + } + } + return nil +} + +// QueryToken queries the "token" edge of the Account entity. +func (a *Account) QueryToken() *TokenQuery { + return (&AccountClient{config: a.config}).QueryToken(a) +} + +// Update returns a builder for updating this Account. +// Note that you need to call Account.Unwrap() before calling this method if this Account +// was returned from a transaction, and the transaction was committed or rolled back. +func (a *Account) Update() *AccountUpdateOne { + return (&AccountClient{config: a.config}).UpdateOne(a) +} + +// Unwrap unwraps the Account 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 (a *Account) Unwrap() *Account { + tx, ok := a.config.driver.(*txDriver) + if !ok { + panic("ent: Account is not a transactional entity") + } + a.config.driver = tx.drv + return a +} + +// String implements the fmt.Stringer. +func (a *Account) String() string { + var builder strings.Builder + builder.WriteString("Account(") + builder.WriteString(fmt.Sprintf("id=%v", a.ID)) + builder.WriteString(", email=") + builder.WriteString(a.Email) + builder.WriteByte(')') + return builder.String() +} + +// Accounts is a parsable slice of Account. +type Accounts []*Account + +func (a Accounts) config(cfg config) { + for _i := range a { + a[_i].config = cfg + } +} diff --git a/entc/integration/customid/ent/account/account.go b/entc/integration/customid/ent/account/account.go new file mode 100644 index 000000000..37a377a8d --- /dev/null +++ b/entc/integration/customid/ent/account/account.go @@ -0,0 +1,54 @@ +// 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 account + +import ( + "entgo.io/ent/entc/integration/customid/sid" +) + +const ( + // Label holds the string label denoting the account type in the database. + Label = "account" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldEmail holds the string denoting the email field in the database. + FieldEmail = "email" + // EdgeToken holds the string denoting the token edge name in mutations. + EdgeToken = "token" + // Table holds the table name of the account in the database. + Table = "accounts" + // TokenTable is the table that holds the token relation/edge. + TokenTable = "tokens" + // TokenInverseTable is the table name for the Token entity. + // It exists in this package in order to avoid circular dependency with the "token" package. + TokenInverseTable = "tokens" + // TokenColumn is the table column denoting the token relation/edge. + TokenColumn = "account_token" +) + +// Columns holds all SQL columns for account fields. +var Columns = []string{ + FieldID, + FieldEmail, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // EmailValidator is a validator for the "email" field. It is called by the builders before save. + EmailValidator func(string) error + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() sid.ID +) diff --git a/entc/integration/customid/ent/account/where.go b/entc/integration/customid/ent/account/where.go new file mode 100644 index 000000000..71b6c2784 --- /dev/null +++ b/entc/integration/customid/ent/account/where.go @@ -0,0 +1,275 @@ +// 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 account + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/customid/ent/predicate" + "entgo.io/ent/entc/integration/customid/sid" +) + +// ID filters vertices based on their ID field. +func ID(id sid.ID) predicate.Account { + return predicate.Account(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id sid.ID) predicate.Account { + return predicate.Account(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id sid.ID) predicate.Account { + return predicate.Account(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldID), id)) + }) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...sid.ID) predicate.Account { + return predicate.Account(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 ...sid.ID) predicate.Account { + return predicate.Account(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 sid.ID) predicate.Account { + return predicate.Account(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldID), id)) + }) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id sid.ID) predicate.Account { + return predicate.Account(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldID), id)) + }) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id sid.ID) predicate.Account { + return predicate.Account(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldID), id)) + }) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id sid.ID) predicate.Account { + return predicate.Account(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldID), id)) + }) +} + +// Email applies equality check predicate on the "email" field. It's identical to EmailEQ. +func Email(v string) predicate.Account { + return predicate.Account(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldEmail), v)) + }) +} + +// EmailEQ applies the EQ predicate on the "email" field. +func EmailEQ(v string) predicate.Account { + return predicate.Account(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldEmail), v)) + }) +} + +// EmailNEQ applies the NEQ predicate on the "email" field. +func EmailNEQ(v string) predicate.Account { + return predicate.Account(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldEmail), v)) + }) +} + +// EmailIn applies the In predicate on the "email" field. +func EmailIn(vs ...string) predicate.Account { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Account(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(FieldEmail), v...)) + }) +} + +// EmailNotIn applies the NotIn predicate on the "email" field. +func EmailNotIn(vs ...string) predicate.Account { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Account(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(FieldEmail), v...)) + }) +} + +// EmailGT applies the GT predicate on the "email" field. +func EmailGT(v string) predicate.Account { + return predicate.Account(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldEmail), v)) + }) +} + +// EmailGTE applies the GTE predicate on the "email" field. +func EmailGTE(v string) predicate.Account { + return predicate.Account(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldEmail), v)) + }) +} + +// EmailLT applies the LT predicate on the "email" field. +func EmailLT(v string) predicate.Account { + return predicate.Account(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldEmail), v)) + }) +} + +// EmailLTE applies the LTE predicate on the "email" field. +func EmailLTE(v string) predicate.Account { + return predicate.Account(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldEmail), v)) + }) +} + +// EmailContains applies the Contains predicate on the "email" field. +func EmailContains(v string) predicate.Account { + return predicate.Account(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldEmail), v)) + }) +} + +// EmailHasPrefix applies the HasPrefix predicate on the "email" field. +func EmailHasPrefix(v string) predicate.Account { + return predicate.Account(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldEmail), v)) + }) +} + +// EmailHasSuffix applies the HasSuffix predicate on the "email" field. +func EmailHasSuffix(v string) predicate.Account { + return predicate.Account(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldEmail), v)) + }) +} + +// EmailEqualFold applies the EqualFold predicate on the "email" field. +func EmailEqualFold(v string) predicate.Account { + return predicate.Account(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldEmail), v)) + }) +} + +// EmailContainsFold applies the ContainsFold predicate on the "email" field. +func EmailContainsFold(v string) predicate.Account { + return predicate.Account(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldEmail), v)) + }) +} + +// HasToken applies the HasEdge predicate on the "token" edge. +func HasToken() predicate.Account { + return predicate.Account(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(TokenTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, TokenTable, TokenColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasTokenWith applies the HasEdge predicate on the "token" edge with a given conditions (other predicates). +func HasTokenWith(preds ...predicate.Token) predicate.Account { + return predicate.Account(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(TokenInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, TokenTable, TokenColumn), + ) + 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.Account) predicate.Account { + return predicate.Account(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.Account) predicate.Account { + return predicate.Account(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.Account) predicate.Account { + return predicate.Account(func(s *sql.Selector) { + p(s.Not()) + }) +} diff --git a/entc/integration/customid/ent/account_create.go b/entc/integration/customid/ent/account_create.go new file mode 100644 index 000000000..02c243ef3 --- /dev/null +++ b/entc/integration/customid/ent/account_create.go @@ -0,0 +1,595 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/customid/ent/account" + "entgo.io/ent/entc/integration/customid/ent/token" + "entgo.io/ent/entc/integration/customid/sid" + "entgo.io/ent/schema/field" +) + +// AccountCreate is the builder for creating a Account entity. +type AccountCreate struct { + config + mutation *AccountMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetEmail sets the "email" field. +func (ac *AccountCreate) SetEmail(s string) *AccountCreate { + ac.mutation.SetEmail(s) + return ac +} + +// SetID sets the "id" field. +func (ac *AccountCreate) SetID(s sid.ID) *AccountCreate { + ac.mutation.SetID(s) + return ac +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (ac *AccountCreate) SetNillableID(s *sid.ID) *AccountCreate { + if s != nil { + ac.SetID(*s) + } + return ac +} + +// AddTokenIDs adds the "token" edge to the Token entity by IDs. +func (ac *AccountCreate) AddTokenIDs(ids ...sid.ID) *AccountCreate { + ac.mutation.AddTokenIDs(ids...) + return ac +} + +// AddToken adds the "token" edges to the Token entity. +func (ac *AccountCreate) AddToken(t ...*Token) *AccountCreate { + ids := make([]sid.ID, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return ac.AddTokenIDs(ids...) +} + +// Mutation returns the AccountMutation object of the builder. +func (ac *AccountCreate) Mutation() *AccountMutation { + return ac.mutation +} + +// Save creates the Account in the database. +func (ac *AccountCreate) Save(ctx context.Context) (*Account, error) { + var ( + err error + node *Account + ) + ac.defaults() + if len(ac.hooks) == 0 { + if err = ac.check(); err != nil { + return nil, err + } + node, err = ac.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*AccountMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = ac.check(); err != nil { + return nil, err + } + ac.mutation = mutation + if node, err = ac.sqlSave(ctx); err != nil { + return nil, err + } + mutation.id = &node.ID + mutation.done = true + return node, err + }) + for i := len(ac.hooks) - 1; i >= 0; i-- { + if ac.hooks[i] == nil { + return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = ac.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, ac.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX calls Save and panics if Save returns an error. +func (ac *AccountCreate) SaveX(ctx context.Context) *Account { + v, err := ac.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (ac *AccountCreate) Exec(ctx context.Context) error { + _, err := ac.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ac *AccountCreate) ExecX(ctx context.Context) { + if err := ac.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (ac *AccountCreate) defaults() { + if _, ok := ac.mutation.ID(); !ok { + v := account.DefaultID() + ac.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (ac *AccountCreate) check() error { + if _, ok := ac.mutation.Email(); !ok { + return &ValidationError{Name: "email", err: errors.New(`ent: missing required field "Account.email"`)} + } + if v, ok := ac.mutation.Email(); ok { + if err := account.EmailValidator(v); err != nil { + return &ValidationError{Name: "email", err: fmt.Errorf(`ent: validator failed for field "Account.email": %w`, err)} + } + } + return nil +} + +func (ac *AccountCreate) sqlSave(ctx context.Context) (*Account, error) { + _node, _spec := ac.createSpec() + if err := sqlgraph.CreateNode(ctx, ac.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + if _spec.ID.Value != nil { + if id, ok := _spec.ID.Value.(*sid.ID); ok { + _node.ID = *id + } else if err := _node.ID.Scan(_spec.ID.Value); err != nil { + return nil, err + } + } + return _node, nil +} + +func (ac *AccountCreate) createSpec() (*Account, *sqlgraph.CreateSpec) { + var ( + _node = &Account{config: ac.config} + _spec = &sqlgraph.CreateSpec{ + Table: account.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeOther, + Column: account.FieldID, + }, + } + ) + _spec.OnConflict = ac.conflict + if id, ok := ac.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = &id + } + if value, ok := ac.mutation.Email(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: account.FieldEmail, + }) + _node.Email = value + } + if nodes := ac.mutation.TokenIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: account.TokenTable, + Columns: []string{account.TokenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeOther, + Column: token.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.Account.Create(). +// SetEmail(v). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.AccountUpsert) { +// SetEmail(v+v). +// }). +// Exec(ctx) +// +func (ac *AccountCreate) OnConflict(opts ...sql.ConflictOption) *AccountUpsertOne { + ac.conflict = opts + return &AccountUpsertOne{ + create: ac, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.Account.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +// +func (ac *AccountCreate) OnConflictColumns(columns ...string) *AccountUpsertOne { + ac.conflict = append(ac.conflict, sql.ConflictColumns(columns...)) + return &AccountUpsertOne{ + create: ac, + } +} + +type ( + // AccountUpsertOne is the builder for "upsert"-ing + // one Account node. + AccountUpsertOne struct { + create *AccountCreate + } + + // AccountUpsert is the "OnConflict" setter. + AccountUpsert struct { + *sql.UpdateSet + } +) + +// SetEmail sets the "email" field. +func (u *AccountUpsert) SetEmail(v string) *AccountUpsert { + u.Set(account.FieldEmail, v) + return u +} + +// UpdateEmail sets the "email" field to the value that was provided on create. +func (u *AccountUpsert) UpdateEmail() *AccountUpsert { + u.SetExcluded(account.FieldEmail) + return u +} + +// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field. +// Using this option is equivalent to using: +// +// client.Account.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(account.FieldID) +// }), +// ). +// Exec(ctx) +// +func (u *AccountUpsertOne) UpdateNewValues() *AccountUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + if _, exists := u.create.mutation.ID(); exists { + s.SetIgnore(account.FieldID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.Account.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +// +func (u *AccountUpsertOne) Ignore() *AccountUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *AccountUpsertOne) DoNothing() *AccountUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the AccountCreate.OnConflict +// documentation for more info. +func (u *AccountUpsertOne) Update(set func(*AccountUpsert)) *AccountUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&AccountUpsert{UpdateSet: update}) + })) + return u +} + +// SetEmail sets the "email" field. +func (u *AccountUpsertOne) SetEmail(v string) *AccountUpsertOne { + return u.Update(func(s *AccountUpsert) { + s.SetEmail(v) + }) +} + +// UpdateEmail sets the "email" field to the value that was provided on create. +func (u *AccountUpsertOne) UpdateEmail() *AccountUpsertOne { + return u.Update(func(s *AccountUpsert) { + s.UpdateEmail() + }) +} + +// Exec executes the query. +func (u *AccountUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("ent: missing options for AccountCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *AccountUpsertOne) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} + +// Exec executes the UPSERT query and returns the inserted/updated ID. +func (u *AccountUpsertOne) ID(ctx context.Context) (id sid.ID, err error) { + if u.create.driver.Dialect() == dialect.MySQL { + // In case of "ON CONFLICT", there is no way to get back non-numeric ID + // fields from the database since MySQL does not support the RETURNING clause. + return id, errors.New("ent: AccountUpsertOne.ID is not supported by MySQL driver. Use AccountUpsertOne.Exec instead") + } + node, err := u.create.Save(ctx) + if err != nil { + return id, err + } + return node.ID, nil +} + +// IDX is like ID, but panics if an error occurs. +func (u *AccountUpsertOne) IDX(ctx context.Context) sid.ID { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// AccountCreateBulk is the builder for creating many Account entities in bulk. +type AccountCreateBulk struct { + config + builders []*AccountCreate + conflict []sql.ConflictOption +} + +// Save creates the Account entities in the database. +func (acb *AccountCreateBulk) Save(ctx context.Context) ([]*Account, error) { + specs := make([]*sqlgraph.CreateSpec, len(acb.builders)) + nodes := make([]*Account, len(acb.builders)) + mutators := make([]Mutator, len(acb.builders)) + for i := range acb.builders { + func(i int, root context.Context) { + builder := acb.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*AccountMutation) + 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, acb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = acb.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, acb.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 + 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, acb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (acb *AccountCreateBulk) SaveX(ctx context.Context) []*Account { + v, err := acb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (acb *AccountCreateBulk) Exec(ctx context.Context) error { + _, err := acb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (acb *AccountCreateBulk) ExecX(ctx context.Context) { + if err := acb.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.Account.CreateBulk(builders...). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.AccountUpsert) { +// SetEmail(v+v). +// }). +// Exec(ctx) +// +func (acb *AccountCreateBulk) OnConflict(opts ...sql.ConflictOption) *AccountUpsertBulk { + acb.conflict = opts + return &AccountUpsertBulk{ + create: acb, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.Account.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +// +func (acb *AccountCreateBulk) OnConflictColumns(columns ...string) *AccountUpsertBulk { + acb.conflict = append(acb.conflict, sql.ConflictColumns(columns...)) + return &AccountUpsertBulk{ + create: acb, + } +} + +// AccountUpsertBulk is the builder for "upsert"-ing +// a bulk of Account nodes. +type AccountUpsertBulk struct { + create *AccountCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.Account.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(account.FieldID) +// }), +// ). +// Exec(ctx) +// +func (u *AccountUpsertBulk) UpdateNewValues() *AccountUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + for _, b := range u.create.builders { + if _, exists := b.mutation.ID(); exists { + s.SetIgnore(account.FieldID) + return + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.Account.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +// +func (u *AccountUpsertBulk) Ignore() *AccountUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *AccountUpsertBulk) DoNothing() *AccountUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the AccountCreateBulk.OnConflict +// documentation for more info. +func (u *AccountUpsertBulk) Update(set func(*AccountUpsert)) *AccountUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&AccountUpsert{UpdateSet: update}) + })) + return u +} + +// SetEmail sets the "email" field. +func (u *AccountUpsertBulk) SetEmail(v string) *AccountUpsertBulk { + return u.Update(func(s *AccountUpsert) { + s.SetEmail(v) + }) +} + +// UpdateEmail sets the "email" field to the value that was provided on create. +func (u *AccountUpsertBulk) UpdateEmail() *AccountUpsertBulk { + return u.Update(func(s *AccountUpsert) { + s.UpdateEmail() + }) +} + +// Exec executes the query. +func (u *AccountUpsertBulk) Exec(ctx context.Context) error { + for i, b := range u.create.builders { + if len(b.conflict) != 0 { + return fmt.Errorf("ent: OnConflict was set for builder %d. Set it on the AccountCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("ent: missing options for AccountCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *AccountUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entc/integration/customid/ent/account_delete.go b/entc/integration/customid/ent/account_delete.go new file mode 100644 index 000000000..3928a5080 --- /dev/null +++ b/entc/integration/customid/ent/account_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 ent + +import ( + "context" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/customid/ent/account" + "entgo.io/ent/entc/integration/customid/ent/predicate" + "entgo.io/ent/schema/field" +) + +// AccountDelete is the builder for deleting a Account entity. +type AccountDelete struct { + config + hooks []Hook + mutation *AccountMutation +} + +// Where appends a list predicates to the AccountDelete builder. +func (ad *AccountDelete) Where(ps ...predicate.Account) *AccountDelete { + ad.mutation.Where(ps...) + return ad +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (ad *AccountDelete) Exec(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(ad.hooks) == 0 { + affected, err = ad.sqlExec(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*AccountMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + ad.mutation = mutation + affected, err = ad.sqlExec(ctx) + mutation.done = true + return affected, err + }) + for i := len(ad.hooks) - 1; i >= 0; i-- { + if ad.hooks[i] == nil { + return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = ad.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, ad.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ad *AccountDelete) ExecX(ctx context.Context) int { + n, err := ad.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (ad *AccountDelete) sqlExec(ctx context.Context) (int, error) { + _spec := &sqlgraph.DeleteSpec{ + Node: &sqlgraph.NodeSpec{ + Table: account.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeOther, + Column: account.FieldID, + }, + }, + } + if ps := ad.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return sqlgraph.DeleteNodes(ctx, ad.driver, _spec) +} + +// AccountDeleteOne is the builder for deleting a single Account entity. +type AccountDeleteOne struct { + ad *AccountDelete +} + +// Exec executes the deletion query. +func (ado *AccountDeleteOne) Exec(ctx context.Context) error { + n, err := ado.ad.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{account.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (ado *AccountDeleteOne) ExecX(ctx context.Context) { + ado.ad.ExecX(ctx) +} diff --git a/entc/integration/customid/ent/account_query.go b/entc/integration/customid/ent/account_query.go new file mode 100644 index 000000000..d5e1c896a --- /dev/null +++ b/entc/integration/customid/ent/account_query.go @@ -0,0 +1,998 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "database/sql/driver" + "errors" + "fmt" + "math" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/customid/ent/account" + "entgo.io/ent/entc/integration/customid/ent/predicate" + "entgo.io/ent/entc/integration/customid/ent/token" + "entgo.io/ent/entc/integration/customid/sid" + "entgo.io/ent/schema/field" +) + +// AccountQuery is the builder for querying Account entities. +type AccountQuery struct { + config + limit *int + offset *int + unique *bool + order []OrderFunc + fields []string + predicates []predicate.Account + // eager-loading edges. + withToken *TokenQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the AccountQuery builder. +func (aq *AccountQuery) Where(ps ...predicate.Account) *AccountQuery { + aq.predicates = append(aq.predicates, ps...) + return aq +} + +// Limit adds a limit step to the query. +func (aq *AccountQuery) Limit(limit int) *AccountQuery { + aq.limit = &limit + return aq +} + +// Offset adds an offset step to the query. +func (aq *AccountQuery) Offset(offset int) *AccountQuery { + aq.offset = &offset + return aq +} + +// 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 (aq *AccountQuery) Unique(unique bool) *AccountQuery { + aq.unique = &unique + return aq +} + +// Order adds an order step to the query. +func (aq *AccountQuery) Order(o ...OrderFunc) *AccountQuery { + aq.order = append(aq.order, o...) + return aq +} + +// QueryToken chains the current query on the "token" edge. +func (aq *AccountQuery) QueryToken() *TokenQuery { + query := &TokenQuery{config: aq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := aq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := aq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(account.Table, account.FieldID, selector), + sqlgraph.To(token.Table, token.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, account.TokenTable, account.TokenColumn), + ) + fromU = sqlgraph.SetNeighbors(aq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first Account entity from the query. +// Returns a *NotFoundError when no Account was found. +func (aq *AccountQuery) First(ctx context.Context) (*Account, error) { + nodes, err := aq.Limit(1).All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{account.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (aq *AccountQuery) FirstX(ctx context.Context) *Account { + node, err := aq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Account ID from the query. +// Returns a *NotFoundError when no Account ID was found. +func (aq *AccountQuery) FirstID(ctx context.Context) (id sid.ID, err error) { + var ids []sid.ID + if ids, err = aq.Limit(1).IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{account.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (aq *AccountQuery) FirstIDX(ctx context.Context) sid.ID { + id, err := aq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Account entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Account entity is found. +// Returns a *NotFoundError when no Account entities are found. +func (aq *AccountQuery) Only(ctx context.Context) (*Account, error) { + nodes, err := aq.Limit(2).All(ctx) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{account.Label} + default: + return nil, &NotSingularError{account.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (aq *AccountQuery) OnlyX(ctx context.Context) *Account { + node, err := aq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Account ID in the query. +// Returns a *NotSingularError when more than one Account ID is found. +// Returns a *NotFoundError when no entities are found. +func (aq *AccountQuery) OnlyID(ctx context.Context) (id sid.ID, err error) { + var ids []sid.ID + if ids, err = aq.Limit(2).IDs(ctx); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{account.Label} + default: + err = &NotSingularError{account.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (aq *AccountQuery) OnlyIDX(ctx context.Context) sid.ID { + id, err := aq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Accounts. +func (aq *AccountQuery) All(ctx context.Context) ([]*Account, error) { + if err := aq.prepareQuery(ctx); err != nil { + return nil, err + } + return aq.sqlAll(ctx) +} + +// AllX is like All, but panics if an error occurs. +func (aq *AccountQuery) AllX(ctx context.Context) []*Account { + nodes, err := aq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Account IDs. +func (aq *AccountQuery) IDs(ctx context.Context) ([]sid.ID, error) { + var ids []sid.ID + if err := aq.Select(account.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (aq *AccountQuery) IDsX(ctx context.Context) []sid.ID { + ids, err := aq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (aq *AccountQuery) Count(ctx context.Context) (int, error) { + if err := aq.prepareQuery(ctx); err != nil { + return 0, err + } + return aq.sqlCount(ctx) +} + +// CountX is like Count, but panics if an error occurs. +func (aq *AccountQuery) CountX(ctx context.Context) int { + count, err := aq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (aq *AccountQuery) Exist(ctx context.Context) (bool, error) { + if err := aq.prepareQuery(ctx); err != nil { + return false, err + } + return aq.sqlExist(ctx) +} + +// ExistX is like Exist, but panics if an error occurs. +func (aq *AccountQuery) ExistX(ctx context.Context) bool { + exist, err := aq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the AccountQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (aq *AccountQuery) Clone() *AccountQuery { + if aq == nil { + return nil + } + return &AccountQuery{ + config: aq.config, + limit: aq.limit, + offset: aq.offset, + order: append([]OrderFunc{}, aq.order...), + predicates: append([]predicate.Account{}, aq.predicates...), + withToken: aq.withToken.Clone(), + // clone intermediate query. + sql: aq.sql.Clone(), + path: aq.path, + unique: aq.unique, + } +} + +// WithToken tells the query-builder to eager-load the nodes that are connected to +// the "token" edge. The optional arguments are used to configure the query builder of the edge. +func (aq *AccountQuery) WithToken(opts ...func(*TokenQuery)) *AccountQuery { + query := &TokenQuery{config: aq.config} + for _, opt := range opts { + opt(query) + } + aq.withToken = query + return aq +} + +// 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 { +// Email string `json:"email,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Account.Query(). +// GroupBy(account.FieldEmail). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +// +func (aq *AccountQuery) GroupBy(field string, fields ...string) *AccountGroupBy { + group := &AccountGroupBy{config: aq.config} + group.fields = append([]string{field}, fields...) + group.path = func(ctx context.Context) (prev *sql.Selector, err error) { + if err := aq.prepareQuery(ctx); err != nil { + return nil, err + } + return aq.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 { +// Email string `json:"email,omitempty"` +// } +// +// client.Account.Query(). +// Select(account.FieldEmail). +// Scan(ctx, &v) +// +func (aq *AccountQuery) Select(fields ...string) *AccountSelect { + aq.fields = append(aq.fields, fields...) + return &AccountSelect{AccountQuery: aq} +} + +func (aq *AccountQuery) prepareQuery(ctx context.Context) error { + for _, f := range aq.fields { + if !account.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if aq.path != nil { + prev, err := aq.path(ctx) + if err != nil { + return err + } + aq.sql = prev + } + return nil +} + +func (aq *AccountQuery) sqlAll(ctx context.Context) ([]*Account, error) { + var ( + nodes = []*Account{} + _spec = aq.querySpec() + loadedTypes = [1]bool{ + aq.withToken != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]interface{}, error) { + node := &Account{config: aq.config} + nodes = append(nodes, node) + return node.scanValues(columns) + } + _spec.Assign = func(columns []string, values []interface{}) error { + if len(nodes) == 0 { + return fmt.Errorf("ent: Assign called without calling ScanValues") + } + node := nodes[len(nodes)-1] + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if err := sqlgraph.QueryNodes(ctx, aq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + + if query := aq.withToken; query != nil { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[sid.ID]*Account) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + nodes[i].Edges.Token = []*Token{} + } + query.withFKs = true + query.Where(predicate.Token(func(s *sql.Selector) { + s.Where(sql.InValues(account.TokenColumn, fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, n := range neighbors { + fk := n.account_token + if fk == nil { + return nil, fmt.Errorf(`foreign-key "account_token" is nil for node %v`, n.ID) + } + node, ok := nodeids[*fk] + if !ok { + return nil, fmt.Errorf(`unexpected foreign-key "account_token" returned %v for node %v`, *fk, n.ID) + } + node.Edges.Token = append(node.Edges.Token, n) + } + } + + return nodes, nil +} + +func (aq *AccountQuery) sqlCount(ctx context.Context) (int, error) { + _spec := aq.querySpec() + _spec.Node.Columns = aq.fields + if len(aq.fields) > 0 { + _spec.Unique = aq.unique != nil && *aq.unique + } + return sqlgraph.CountNodes(ctx, aq.driver, _spec) +} + +func (aq *AccountQuery) sqlExist(ctx context.Context) (bool, error) { + n, err := aq.sqlCount(ctx) + if err != nil { + return false, fmt.Errorf("ent: check existence: %w", err) + } + return n > 0, nil +} + +func (aq *AccountQuery) querySpec() *sqlgraph.QuerySpec { + _spec := &sqlgraph.QuerySpec{ + Node: &sqlgraph.NodeSpec{ + Table: account.Table, + Columns: account.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeOther, + Column: account.FieldID, + }, + }, + From: aq.sql, + Unique: true, + } + if unique := aq.unique; unique != nil { + _spec.Unique = *unique + } + if fields := aq.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, account.FieldID) + for i := range fields { + if fields[i] != account.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := aq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := aq.limit; limit != nil { + _spec.Limit = *limit + } + if offset := aq.offset; offset != nil { + _spec.Offset = *offset + } + if ps := aq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (aq *AccountQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(aq.driver.Dialect()) + t1 := builder.Table(account.Table) + columns := aq.fields + if len(columns) == 0 { + columns = account.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if aq.sql != nil { + selector = aq.sql + selector.Select(selector.Columns(columns...)...) + } + if aq.unique != nil && *aq.unique { + selector.Distinct() + } + for _, p := range aq.predicates { + p(selector) + } + for _, p := range aq.order { + p(selector) + } + if offset := aq.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 := aq.limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// AccountGroupBy is the group-by builder for Account entities. +type AccountGroupBy 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 (agb *AccountGroupBy) Aggregate(fns ...AggregateFunc) *AccountGroupBy { + agb.fns = append(agb.fns, fns...) + return agb +} + +// Scan applies the group-by query and scans the result into the given value. +func (agb *AccountGroupBy) Scan(ctx context.Context, v interface{}) error { + query, err := agb.path(ctx) + if err != nil { + return err + } + agb.sql = query + return agb.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (agb *AccountGroupBy) ScanX(ctx context.Context, v interface{}) { + if err := agb.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 (agb *AccountGroupBy) Strings(ctx context.Context) ([]string, error) { + if len(agb.fields) > 1 { + return nil, errors.New("ent: AccountGroupBy.Strings is not achievable when grouping more than 1 field") + } + var v []string + if err := agb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (agb *AccountGroupBy) StringsX(ctx context.Context) []string { + v, err := agb.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 (agb *AccountGroupBy) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = agb.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{account.Label} + default: + err = fmt.Errorf("ent: AccountGroupBy.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (agb *AccountGroupBy) StringX(ctx context.Context) string { + v, err := agb.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 (agb *AccountGroupBy) Ints(ctx context.Context) ([]int, error) { + if len(agb.fields) > 1 { + return nil, errors.New("ent: AccountGroupBy.Ints is not achievable when grouping more than 1 field") + } + var v []int + if err := agb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (agb *AccountGroupBy) IntsX(ctx context.Context) []int { + v, err := agb.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 (agb *AccountGroupBy) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = agb.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{account.Label} + default: + err = fmt.Errorf("ent: AccountGroupBy.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (agb *AccountGroupBy) IntX(ctx context.Context) int { + v, err := agb.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 (agb *AccountGroupBy) Float64s(ctx context.Context) ([]float64, error) { + if len(agb.fields) > 1 { + return nil, errors.New("ent: AccountGroupBy.Float64s is not achievable when grouping more than 1 field") + } + var v []float64 + if err := agb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (agb *AccountGroupBy) Float64sX(ctx context.Context) []float64 { + v, err := agb.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 (agb *AccountGroupBy) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = agb.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{account.Label} + default: + err = fmt.Errorf("ent: AccountGroupBy.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (agb *AccountGroupBy) Float64X(ctx context.Context) float64 { + v, err := agb.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 (agb *AccountGroupBy) Bools(ctx context.Context) ([]bool, error) { + if len(agb.fields) > 1 { + return nil, errors.New("ent: AccountGroupBy.Bools is not achievable when grouping more than 1 field") + } + var v []bool + if err := agb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (agb *AccountGroupBy) BoolsX(ctx context.Context) []bool { + v, err := agb.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 (agb *AccountGroupBy) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = agb.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{account.Label} + default: + err = fmt.Errorf("ent: AccountGroupBy.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (agb *AccountGroupBy) BoolX(ctx context.Context) bool { + v, err := agb.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (agb *AccountGroupBy) sqlScan(ctx context.Context, v interface{}) error { + for _, f := range agb.fields { + if !account.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + } + } + selector := agb.sqlQuery() + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := agb.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +func (agb *AccountGroupBy) sqlQuery() *sql.Selector { + selector := agb.sql.Select() + aggregation := make([]string, 0, len(agb.fns)) + for _, fn := range agb.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(agb.fields)+len(agb.fns)) + for _, f := range agb.fields { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + return selector.GroupBy(selector.Columns(agb.fields...)...) +} + +// AccountSelect is the builder for selecting fields of Account entities. +type AccountSelect struct { + *AccountQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector +} + +// Scan applies the selector query and scans the result into the given value. +func (as *AccountSelect) Scan(ctx context.Context, v interface{}) error { + if err := as.prepareQuery(ctx); err != nil { + return err + } + as.sql = as.AccountQuery.sqlQuery(ctx) + return as.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (as *AccountSelect) ScanX(ctx context.Context, v interface{}) { + if err := as.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from a selector. It is only allowed when selecting one field. +func (as *AccountSelect) Strings(ctx context.Context) ([]string, error) { + if len(as.fields) > 1 { + return nil, errors.New("ent: AccountSelect.Strings is not achievable when selecting more than 1 field") + } + var v []string + if err := as.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (as *AccountSelect) StringsX(ctx context.Context) []string { + v, err := as.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 (as *AccountSelect) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = as.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{account.Label} + default: + err = fmt.Errorf("ent: AccountSelect.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (as *AccountSelect) StringX(ctx context.Context) string { + v, err := as.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 (as *AccountSelect) Ints(ctx context.Context) ([]int, error) { + if len(as.fields) > 1 { + return nil, errors.New("ent: AccountSelect.Ints is not achievable when selecting more than 1 field") + } + var v []int + if err := as.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (as *AccountSelect) IntsX(ctx context.Context) []int { + v, err := as.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 (as *AccountSelect) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = as.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{account.Label} + default: + err = fmt.Errorf("ent: AccountSelect.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (as *AccountSelect) IntX(ctx context.Context) int { + v, err := as.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 (as *AccountSelect) Float64s(ctx context.Context) ([]float64, error) { + if len(as.fields) > 1 { + return nil, errors.New("ent: AccountSelect.Float64s is not achievable when selecting more than 1 field") + } + var v []float64 + if err := as.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (as *AccountSelect) Float64sX(ctx context.Context) []float64 { + v, err := as.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 (as *AccountSelect) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = as.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{account.Label} + default: + err = fmt.Errorf("ent: AccountSelect.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (as *AccountSelect) Float64X(ctx context.Context) float64 { + v, err := as.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 (as *AccountSelect) Bools(ctx context.Context) ([]bool, error) { + if len(as.fields) > 1 { + return nil, errors.New("ent: AccountSelect.Bools is not achievable when selecting more than 1 field") + } + var v []bool + if err := as.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (as *AccountSelect) BoolsX(ctx context.Context) []bool { + v, err := as.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 (as *AccountSelect) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = as.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{account.Label} + default: + err = fmt.Errorf("ent: AccountSelect.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (as *AccountSelect) BoolX(ctx context.Context) bool { + v, err := as.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (as *AccountSelect) sqlScan(ctx context.Context, v interface{}) error { + rows := &sql.Rows{} + query, args := as.sql.Query() + if err := as.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/entc/integration/customid/ent/account_update.go b/entc/integration/customid/ent/account_update.go new file mode 100644 index 000000000..dd8cc4c8c --- /dev/null +++ b/entc/integration/customid/ent/account_update.go @@ -0,0 +1,483 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/customid/ent/account" + "entgo.io/ent/entc/integration/customid/ent/predicate" + "entgo.io/ent/entc/integration/customid/ent/token" + "entgo.io/ent/entc/integration/customid/sid" + "entgo.io/ent/schema/field" +) + +// AccountUpdate is the builder for updating Account entities. +type AccountUpdate struct { + config + hooks []Hook + mutation *AccountMutation +} + +// Where appends a list predicates to the AccountUpdate builder. +func (au *AccountUpdate) Where(ps ...predicate.Account) *AccountUpdate { + au.mutation.Where(ps...) + return au +} + +// SetEmail sets the "email" field. +func (au *AccountUpdate) SetEmail(s string) *AccountUpdate { + au.mutation.SetEmail(s) + return au +} + +// AddTokenIDs adds the "token" edge to the Token entity by IDs. +func (au *AccountUpdate) AddTokenIDs(ids ...sid.ID) *AccountUpdate { + au.mutation.AddTokenIDs(ids...) + return au +} + +// AddToken adds the "token" edges to the Token entity. +func (au *AccountUpdate) AddToken(t ...*Token) *AccountUpdate { + ids := make([]sid.ID, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return au.AddTokenIDs(ids...) +} + +// Mutation returns the AccountMutation object of the builder. +func (au *AccountUpdate) Mutation() *AccountMutation { + return au.mutation +} + +// ClearToken clears all "token" edges to the Token entity. +func (au *AccountUpdate) ClearToken() *AccountUpdate { + au.mutation.ClearToken() + return au +} + +// RemoveTokenIDs removes the "token" edge to Token entities by IDs. +func (au *AccountUpdate) RemoveTokenIDs(ids ...sid.ID) *AccountUpdate { + au.mutation.RemoveTokenIDs(ids...) + return au +} + +// RemoveToken removes "token" edges to Token entities. +func (au *AccountUpdate) RemoveToken(t ...*Token) *AccountUpdate { + ids := make([]sid.ID, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return au.RemoveTokenIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (au *AccountUpdate) Save(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(au.hooks) == 0 { + if err = au.check(); err != nil { + return 0, err + } + affected, err = au.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*AccountMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = au.check(); err != nil { + return 0, err + } + au.mutation = mutation + affected, err = au.sqlSave(ctx) + mutation.done = true + return affected, err + }) + for i := len(au.hooks) - 1; i >= 0; i-- { + if au.hooks[i] == nil { + return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = au.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, au.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// SaveX is like Save, but panics if an error occurs. +func (au *AccountUpdate) SaveX(ctx context.Context) int { + affected, err := au.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (au *AccountUpdate) Exec(ctx context.Context) error { + _, err := au.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (au *AccountUpdate) ExecX(ctx context.Context) { + if err := au.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (au *AccountUpdate) check() error { + if v, ok := au.mutation.Email(); ok { + if err := account.EmailValidator(v); err != nil { + return &ValidationError{Name: "email", err: fmt.Errorf(`ent: validator failed for field "Account.email": %w`, err)} + } + } + return nil +} + +func (au *AccountUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: account.Table, + Columns: account.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeOther, + Column: account.FieldID, + }, + }, + } + if ps := au.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := au.mutation.Email(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: account.FieldEmail, + }) + } + if au.mutation.TokenCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: account.TokenTable, + Columns: []string{account.TokenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeOther, + Column: token.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := au.mutation.RemovedTokenIDs(); len(nodes) > 0 && !au.mutation.TokenCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: account.TokenTable, + Columns: []string{account.TokenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeOther, + Column: token.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := au.mutation.TokenIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: account.TokenTable, + Columns: []string{account.TokenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeOther, + Column: token.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, au.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{account.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return 0, err + } + return n, nil +} + +// AccountUpdateOne is the builder for updating a single Account entity. +type AccountUpdateOne struct { + config + fields []string + hooks []Hook + mutation *AccountMutation +} + +// SetEmail sets the "email" field. +func (auo *AccountUpdateOne) SetEmail(s string) *AccountUpdateOne { + auo.mutation.SetEmail(s) + return auo +} + +// AddTokenIDs adds the "token" edge to the Token entity by IDs. +func (auo *AccountUpdateOne) AddTokenIDs(ids ...sid.ID) *AccountUpdateOne { + auo.mutation.AddTokenIDs(ids...) + return auo +} + +// AddToken adds the "token" edges to the Token entity. +func (auo *AccountUpdateOne) AddToken(t ...*Token) *AccountUpdateOne { + ids := make([]sid.ID, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return auo.AddTokenIDs(ids...) +} + +// Mutation returns the AccountMutation object of the builder. +func (auo *AccountUpdateOne) Mutation() *AccountMutation { + return auo.mutation +} + +// ClearToken clears all "token" edges to the Token entity. +func (auo *AccountUpdateOne) ClearToken() *AccountUpdateOne { + auo.mutation.ClearToken() + return auo +} + +// RemoveTokenIDs removes the "token" edge to Token entities by IDs. +func (auo *AccountUpdateOne) RemoveTokenIDs(ids ...sid.ID) *AccountUpdateOne { + auo.mutation.RemoveTokenIDs(ids...) + return auo +} + +// RemoveToken removes "token" edges to Token entities. +func (auo *AccountUpdateOne) RemoveToken(t ...*Token) *AccountUpdateOne { + ids := make([]sid.ID, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return auo.RemoveTokenIDs(ids...) +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (auo *AccountUpdateOne) Select(field string, fields ...string) *AccountUpdateOne { + auo.fields = append([]string{field}, fields...) + return auo +} + +// Save executes the query and returns the updated Account entity. +func (auo *AccountUpdateOne) Save(ctx context.Context) (*Account, error) { + var ( + err error + node *Account + ) + if len(auo.hooks) == 0 { + if err = auo.check(); err != nil { + return nil, err + } + node, err = auo.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*AccountMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = auo.check(); err != nil { + return nil, err + } + auo.mutation = mutation + node, err = auo.sqlSave(ctx) + mutation.done = true + return node, err + }) + for i := len(auo.hooks) - 1; i >= 0; i-- { + if auo.hooks[i] == nil { + return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = auo.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, auo.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX is like Save, but panics if an error occurs. +func (auo *AccountUpdateOne) SaveX(ctx context.Context) *Account { + node, err := auo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (auo *AccountUpdateOne) Exec(ctx context.Context) error { + _, err := auo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (auo *AccountUpdateOne) ExecX(ctx context.Context) { + if err := auo.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (auo *AccountUpdateOne) check() error { + if v, ok := auo.mutation.Email(); ok { + if err := account.EmailValidator(v); err != nil { + return &ValidationError{Name: "email", err: fmt.Errorf(`ent: validator failed for field "Account.email": %w`, err)} + } + } + return nil +} + +func (auo *AccountUpdateOne) sqlSave(ctx context.Context) (_node *Account, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: account.Table, + Columns: account.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeOther, + Column: account.FieldID, + }, + }, + } + id, ok := auo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Account.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := auo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, account.FieldID) + for _, f := range fields { + if !account.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != account.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := auo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := auo.mutation.Email(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: account.FieldEmail, + }) + } + if auo.mutation.TokenCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: account.TokenTable, + Columns: []string{account.TokenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeOther, + Column: token.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := auo.mutation.RemovedTokenIDs(); len(nodes) > 0 && !auo.mutation.TokenCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: account.TokenTable, + Columns: []string{account.TokenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeOther, + Column: token.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := auo.mutation.TokenIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: account.TokenTable, + Columns: []string{account.TokenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeOther, + Column: token.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &Account{config: auo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, auo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{account.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + return _node, nil +} diff --git a/entc/integration/customid/ent/client.go b/entc/integration/customid/ent/client.go index 9e234e26d..12b94a534 100644 --- a/entc/integration/customid/ent/client.go +++ b/entc/integration/customid/ent/client.go @@ -16,6 +16,7 @@ import ( "entgo.io/ent/entc/integration/customid/sid" "github.com/google/uuid" + "entgo.io/ent/entc/integration/customid/ent/account" "entgo.io/ent/entc/integration/customid/ent/blob" "entgo.io/ent/entc/integration/customid/ent/car" "entgo.io/ent/entc/integration/customid/ent/device" @@ -26,6 +27,7 @@ import ( "entgo.io/ent/entc/integration/customid/ent/other" "entgo.io/ent/entc/integration/customid/ent/pet" "entgo.io/ent/entc/integration/customid/ent/session" + "entgo.io/ent/entc/integration/customid/ent/token" "entgo.io/ent/entc/integration/customid/ent/user" "entgo.io/ent/dialect" @@ -38,6 +40,8 @@ type Client struct { config // Schema is the client for creating, migrating and dropping schema. Schema *migrate.Schema + // Account is the client for interacting with the Account builders. + Account *AccountClient // Blob is the client for interacting with the Blob builders. Blob *BlobClient // Car is the client for interacting with the Car builders. @@ -58,6 +62,8 @@ type Client struct { Pet *PetClient // Session is the client for interacting with the Session builders. Session *SessionClient + // Token is the client for interacting with the Token builders. + Token *TokenClient // User is the client for interacting with the User builders. User *UserClient } @@ -73,6 +79,7 @@ func NewClient(opts ...Option) *Client { func (c *Client) init() { c.Schema = migrate.NewSchema(c.driver) + c.Account = NewAccountClient(c.config) c.Blob = NewBlobClient(c.config) c.Car = NewCarClient(c.config) c.Device = NewDeviceClient(c.config) @@ -83,6 +90,7 @@ func (c *Client) init() { c.Other = NewOtherClient(c.config) c.Pet = NewPetClient(c.config) c.Session = NewSessionClient(c.config) + c.Token = NewTokenClient(c.config) c.User = NewUserClient(c.config) } @@ -117,6 +125,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { return &Tx{ ctx: ctx, config: cfg, + Account: NewAccountClient(cfg), Blob: NewBlobClient(cfg), Car: NewCarClient(cfg), Device: NewDeviceClient(cfg), @@ -127,6 +136,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { Other: NewOtherClient(cfg), Pet: NewPetClient(cfg), Session: NewSessionClient(cfg), + Token: NewTokenClient(cfg), User: NewUserClient(cfg), }, nil } @@ -147,6 +157,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) return &Tx{ ctx: ctx, config: cfg, + Account: NewAccountClient(cfg), Blob: NewBlobClient(cfg), Car: NewCarClient(cfg), Device: NewDeviceClient(cfg), @@ -157,6 +168,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) Other: NewOtherClient(cfg), Pet: NewPetClient(cfg), Session: NewSessionClient(cfg), + Token: NewTokenClient(cfg), User: NewUserClient(cfg), }, nil } @@ -164,7 +176,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) // Debug returns a new debug-client. It's used to get verbose logging on specific operations. // // client.Debug(). -// Blob. +// Account. // Query(). // Count(ctx) // @@ -187,6 +199,7 @@ func (c *Client) Close() error { // Use adds the mutation hooks to all the entity clients. // In order to add hooks to a specific client, call: `client.Node.Use(...)`. func (c *Client) Use(hooks ...Hook) { + c.Account.Use(hooks...) c.Blob.Use(hooks...) c.Car.Use(hooks...) c.Device.Use(hooks...) @@ -197,9 +210,116 @@ func (c *Client) Use(hooks ...Hook) { c.Other.Use(hooks...) c.Pet.Use(hooks...) c.Session.Use(hooks...) + c.Token.Use(hooks...) c.User.Use(hooks...) } +// AccountClient is a client for the Account schema. +type AccountClient struct { + config +} + +// NewAccountClient returns a client for the Account from the given config. +func NewAccountClient(c config) *AccountClient { + return &AccountClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `account.Hooks(f(g(h())))`. +func (c *AccountClient) Use(hooks ...Hook) { + c.hooks.Account = append(c.hooks.Account, hooks...) +} + +// Create returns a create builder for Account. +func (c *AccountClient) Create() *AccountCreate { + mutation := newAccountMutation(c.config, OpCreate) + return &AccountCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Account entities. +func (c *AccountClient) CreateBulk(builders ...*AccountCreate) *AccountCreateBulk { + return &AccountCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Account. +func (c *AccountClient) Update() *AccountUpdate { + mutation := newAccountMutation(c.config, OpUpdate) + return &AccountUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *AccountClient) UpdateOne(a *Account) *AccountUpdateOne { + mutation := newAccountMutation(c.config, OpUpdateOne, withAccount(a)) + return &AccountUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *AccountClient) UpdateOneID(id sid.ID) *AccountUpdateOne { + mutation := newAccountMutation(c.config, OpUpdateOne, withAccountID(id)) + return &AccountUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Account. +func (c *AccountClient) Delete() *AccountDelete { + mutation := newAccountMutation(c.config, OpDelete) + return &AccountDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a delete builder for the given entity. +func (c *AccountClient) DeleteOne(a *Account) *AccountDeleteOne { + return c.DeleteOneID(a.ID) +} + +// DeleteOneID returns a delete builder for the given id. +func (c *AccountClient) DeleteOneID(id sid.ID) *AccountDeleteOne { + builder := c.Delete().Where(account.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &AccountDeleteOne{builder} +} + +// Query returns a query builder for Account. +func (c *AccountClient) Query() *AccountQuery { + return &AccountQuery{ + config: c.config, + } +} + +// Get returns a Account entity by its id. +func (c *AccountClient) Get(ctx context.Context, id sid.ID) (*Account, error) { + return c.Query().Where(account.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *AccountClient) GetX(ctx context.Context, id sid.ID) *Account { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryToken queries the token edge of a Account. +func (c *AccountClient) QueryToken(a *Account) *TokenQuery { + query := &TokenQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := a.ID + step := sqlgraph.NewStep( + sqlgraph.From(account.Table, account.FieldID, id), + sqlgraph.To(token.Table, token.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, account.TokenTable, account.TokenColumn), + ) + fromV = sqlgraph.Neighbors(a.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *AccountClient) Hooks() []Hook { + return c.hooks.Account +} + // BlobClient is a client for the Blob schema. type BlobClient struct { config @@ -1340,6 +1460,112 @@ func (c *SessionClient) Hooks() []Hook { return c.hooks.Session } +// TokenClient is a client for the Token schema. +type TokenClient struct { + config +} + +// NewTokenClient returns a client for the Token from the given config. +func NewTokenClient(c config) *TokenClient { + return &TokenClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `token.Hooks(f(g(h())))`. +func (c *TokenClient) Use(hooks ...Hook) { + c.hooks.Token = append(c.hooks.Token, hooks...) +} + +// Create returns a create builder for Token. +func (c *TokenClient) Create() *TokenCreate { + mutation := newTokenMutation(c.config, OpCreate) + return &TokenCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Token entities. +func (c *TokenClient) CreateBulk(builders ...*TokenCreate) *TokenCreateBulk { + return &TokenCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Token. +func (c *TokenClient) Update() *TokenUpdate { + mutation := newTokenMutation(c.config, OpUpdate) + return &TokenUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *TokenClient) UpdateOne(t *Token) *TokenUpdateOne { + mutation := newTokenMutation(c.config, OpUpdateOne, withToken(t)) + return &TokenUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *TokenClient) UpdateOneID(id sid.ID) *TokenUpdateOne { + mutation := newTokenMutation(c.config, OpUpdateOne, withTokenID(id)) + return &TokenUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Token. +func (c *TokenClient) Delete() *TokenDelete { + mutation := newTokenMutation(c.config, OpDelete) + return &TokenDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a delete builder for the given entity. +func (c *TokenClient) DeleteOne(t *Token) *TokenDeleteOne { + return c.DeleteOneID(t.ID) +} + +// DeleteOneID returns a delete builder for the given id. +func (c *TokenClient) DeleteOneID(id sid.ID) *TokenDeleteOne { + builder := c.Delete().Where(token.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &TokenDeleteOne{builder} +} + +// Query returns a query builder for Token. +func (c *TokenClient) Query() *TokenQuery { + return &TokenQuery{ + config: c.config, + } +} + +// Get returns a Token entity by its id. +func (c *TokenClient) Get(ctx context.Context, id sid.ID) (*Token, error) { + return c.Query().Where(token.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *TokenClient) GetX(ctx context.Context, id sid.ID) *Token { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryAccount queries the account edge of a Token. +func (c *TokenClient) QueryAccount(t *Token) *AccountQuery { + query := &AccountQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := t.ID + step := sqlgraph.NewStep( + sqlgraph.From(token.Table, token.FieldID, id), + sqlgraph.To(account.Table, account.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, token.AccountTable, token.AccountColumn), + ) + fromV = sqlgraph.Neighbors(t.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *TokenClient) Hooks() []Hook { + return c.hooks.Token +} + // UserClient is a client for the User schema. type UserClient struct { config diff --git a/entc/integration/customid/ent/config.go b/entc/integration/customid/ent/config.go index f7e1ed5ad..6be4f7b6b 100644 --- a/entc/integration/customid/ent/config.go +++ b/entc/integration/customid/ent/config.go @@ -28,6 +28,7 @@ type config struct { // hooks per client, for fast access. type hooks struct { + Account []ent.Hook Blob []ent.Hook Car []ent.Hook Device []ent.Hook @@ -38,6 +39,7 @@ type hooks struct { Other []ent.Hook Pet []ent.Hook Session []ent.Hook + Token []ent.Hook User []ent.Hook } diff --git a/entc/integration/customid/ent/ent.go b/entc/integration/customid/ent/ent.go index 85cb4fe0a..8a1e03435 100644 --- a/entc/integration/customid/ent/ent.go +++ b/entc/integration/customid/ent/ent.go @@ -12,6 +12,7 @@ import ( "entgo.io/ent" "entgo.io/ent/dialect/sql" + "entgo.io/ent/entc/integration/customid/ent/account" "entgo.io/ent/entc/integration/customid/ent/blob" "entgo.io/ent/entc/integration/customid/ent/car" "entgo.io/ent/entc/integration/customid/ent/device" @@ -22,6 +23,7 @@ import ( "entgo.io/ent/entc/integration/customid/ent/other" "entgo.io/ent/entc/integration/customid/ent/pet" "entgo.io/ent/entc/integration/customid/ent/session" + "entgo.io/ent/entc/integration/customid/ent/token" "entgo.io/ent/entc/integration/customid/ent/user" ) @@ -43,6 +45,7 @@ type OrderFunc func(*sql.Selector) // columnChecker returns a function indicates if the column exists in the given column. func columnChecker(table string) func(string) error { checks := map[string]func(string) bool{ + account.Table: account.ValidColumn, blob.Table: blob.ValidColumn, car.Table: car.ValidColumn, device.Table: device.ValidColumn, @@ -53,6 +56,7 @@ func columnChecker(table string) func(string) error { other.Table: other.ValidColumn, pet.Table: pet.ValidColumn, session.Table: session.ValidColumn, + token.Table: token.ValidColumn, user.Table: user.ValidColumn, } check, ok := checks[table] diff --git a/entc/integration/customid/ent/entql.go b/entc/integration/customid/ent/entql.go index cd057790a..a1499b2fd 100644 --- a/entc/integration/customid/ent/entql.go +++ b/entc/integration/customid/ent/entql.go @@ -7,6 +7,7 @@ package ent import ( + "entgo.io/ent/entc/integration/customid/ent/account" "entgo.io/ent/entc/integration/customid/ent/blob" "entgo.io/ent/entc/integration/customid/ent/car" "entgo.io/ent/entc/integration/customid/ent/device" @@ -18,6 +19,7 @@ import ( "entgo.io/ent/entc/integration/customid/ent/pet" "entgo.io/ent/entc/integration/customid/ent/predicate" "entgo.io/ent/entc/integration/customid/ent/session" + "entgo.io/ent/entc/integration/customid/ent/token" "entgo.io/ent/entc/integration/customid/ent/user" "entgo.io/ent/dialect/sql" @@ -28,8 +30,22 @@ import ( // schemaGraph holds a representation of ent/schema at runtime. var schemaGraph = func() *sqlgraph.Schema { - graph := &sqlgraph.Schema{Nodes: make([]*sqlgraph.Node, 11)} + graph := &sqlgraph.Schema{Nodes: make([]*sqlgraph.Node, 13)} graph.Nodes[0] = &sqlgraph.Node{ + NodeSpec: sqlgraph.NodeSpec{ + Table: account.Table, + Columns: account.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeOther, + Column: account.FieldID, + }, + }, + Type: "Account", + Fields: map[string]*sqlgraph.FieldSpec{ + account.FieldEmail: {Type: field.TypeString, Column: account.FieldEmail}, + }, + } + graph.Nodes[1] = &sqlgraph.Node{ NodeSpec: sqlgraph.NodeSpec{ Table: blob.Table, Columns: blob.Columns, @@ -44,7 +60,7 @@ var schemaGraph = func() *sqlgraph.Schema { blob.FieldCount: {Type: field.TypeInt, Column: blob.FieldCount}, }, } - graph.Nodes[1] = &sqlgraph.Node{ + graph.Nodes[2] = &sqlgraph.Node{ NodeSpec: sqlgraph.NodeSpec{ Table: car.Table, Columns: car.Columns, @@ -60,7 +76,7 @@ var schemaGraph = func() *sqlgraph.Schema { car.FieldModel: {Type: field.TypeString, Column: car.FieldModel}, }, } - graph.Nodes[2] = &sqlgraph.Node{ + graph.Nodes[3] = &sqlgraph.Node{ NodeSpec: sqlgraph.NodeSpec{ Table: device.Table, Columns: device.Columns, @@ -72,7 +88,7 @@ var schemaGraph = func() *sqlgraph.Schema { Type: "Device", Fields: map[string]*sqlgraph.FieldSpec{}, } - graph.Nodes[3] = &sqlgraph.Node{ + graph.Nodes[4] = &sqlgraph.Node{ NodeSpec: sqlgraph.NodeSpec{ Table: doc.Table, Columns: doc.Columns, @@ -86,7 +102,7 @@ var schemaGraph = func() *sqlgraph.Schema { doc.FieldText: {Type: field.TypeString, Column: doc.FieldText}, }, } - graph.Nodes[4] = &sqlgraph.Node{ + graph.Nodes[5] = &sqlgraph.Node{ NodeSpec: sqlgraph.NodeSpec{ Table: group.Table, Columns: group.Columns, @@ -98,7 +114,7 @@ var schemaGraph = func() *sqlgraph.Schema { Type: "Group", Fields: map[string]*sqlgraph.FieldSpec{}, } - graph.Nodes[5] = &sqlgraph.Node{ + graph.Nodes[6] = &sqlgraph.Node{ NodeSpec: sqlgraph.NodeSpec{ Table: mixinid.Table, Columns: mixinid.Columns, @@ -113,7 +129,7 @@ var schemaGraph = func() *sqlgraph.Schema { mixinid.FieldMixinField: {Type: field.TypeString, Column: mixinid.FieldMixinField}, }, } - graph.Nodes[6] = &sqlgraph.Node{ + graph.Nodes[7] = &sqlgraph.Node{ NodeSpec: sqlgraph.NodeSpec{ Table: note.Table, Columns: note.Columns, @@ -127,7 +143,7 @@ var schemaGraph = func() *sqlgraph.Schema { note.FieldText: {Type: field.TypeString, Column: note.FieldText}, }, } - graph.Nodes[7] = &sqlgraph.Node{ + graph.Nodes[8] = &sqlgraph.Node{ NodeSpec: sqlgraph.NodeSpec{ Table: other.Table, Columns: other.Columns, @@ -139,7 +155,7 @@ var schemaGraph = func() *sqlgraph.Schema { Type: "Other", Fields: map[string]*sqlgraph.FieldSpec{}, } - graph.Nodes[8] = &sqlgraph.Node{ + graph.Nodes[9] = &sqlgraph.Node{ NodeSpec: sqlgraph.NodeSpec{ Table: pet.Table, Columns: pet.Columns, @@ -151,7 +167,7 @@ var schemaGraph = func() *sqlgraph.Schema { Type: "Pet", Fields: map[string]*sqlgraph.FieldSpec{}, } - graph.Nodes[9] = &sqlgraph.Node{ + graph.Nodes[10] = &sqlgraph.Node{ NodeSpec: sqlgraph.NodeSpec{ Table: session.Table, Columns: session.Columns, @@ -163,7 +179,21 @@ var schemaGraph = func() *sqlgraph.Schema { Type: "Session", Fields: map[string]*sqlgraph.FieldSpec{}, } - graph.Nodes[10] = &sqlgraph.Node{ + graph.Nodes[11] = &sqlgraph.Node{ + NodeSpec: sqlgraph.NodeSpec{ + Table: token.Table, + Columns: token.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeOther, + Column: token.FieldID, + }, + }, + Type: "Token", + Fields: map[string]*sqlgraph.FieldSpec{ + token.FieldBody: {Type: field.TypeString, Column: token.FieldBody}, + }, + } + graph.Nodes[12] = &sqlgraph.Node{ NodeSpec: sqlgraph.NodeSpec{ Table: user.Table, Columns: user.Columns, @@ -175,6 +205,18 @@ var schemaGraph = func() *sqlgraph.Schema { Type: "User", Fields: map[string]*sqlgraph.FieldSpec{}, } + graph.MustAddE( + "token", + &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: account.TokenTable, + Columns: []string{account.TokenColumn}, + Bidi: false, + }, + "Account", + "Token", + ) graph.MustAddE( "parent", &sqlgraph.EdgeSpec{ @@ -355,6 +397,18 @@ var schemaGraph = func() *sqlgraph.Schema { "Session", "Device", ) + graph.MustAddE( + "account", + &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: token.AccountTable, + Columns: []string{token.AccountColumn}, + Bidi: false, + }, + "Token", + "Account", + ) graph.MustAddE( "groups", &sqlgraph.EdgeSpec{ @@ -412,6 +466,64 @@ type predicateAdder interface { addPredicate(func(s *sql.Selector)) } +// addPredicate implements the predicateAdder interface. +func (aq *AccountQuery) addPredicate(pred func(s *sql.Selector)) { + aq.predicates = append(aq.predicates, pred) +} + +// Filter returns a Filter implementation to apply filters on the AccountQuery builder. +func (aq *AccountQuery) Filter() *AccountFilter { + return &AccountFilter{aq} +} + +// addPredicate implements the predicateAdder interface. +func (m *AccountMutation) addPredicate(pred func(s *sql.Selector)) { + m.predicates = append(m.predicates, pred) +} + +// Filter returns an entql.Where implementation to apply filters on the AccountMutation builder. +func (m *AccountMutation) Filter() *AccountFilter { + return &AccountFilter{m} +} + +// AccountFilter provides a generic filtering capability at runtime for AccountQuery. +type AccountFilter struct { + predicateAdder +} + +// Where applies the entql predicate on the query filter. +func (f *AccountFilter) Where(p entql.P) { + f.addPredicate(func(s *sql.Selector) { + if err := schemaGraph.EvalP(schemaGraph.Nodes[0].Type, p, s); err != nil { + s.AddError(err) + } + }) +} + +// WhereID applies the entql other predicate on the id field. +func (f *AccountFilter) WhereID(p entql.OtherP) { + f.Where(p.Field(account.FieldID)) +} + +// WhereEmail applies the entql string predicate on the email field. +func (f *AccountFilter) WhereEmail(p entql.StringP) { + f.Where(p.Field(account.FieldEmail)) +} + +// WhereHasToken applies a predicate to check if query has an edge token. +func (f *AccountFilter) WhereHasToken() { + f.Where(entql.HasEdge("token")) +} + +// WhereHasTokenWith applies a predicate to check if query has an edge token with a given conditions (other predicates). +func (f *AccountFilter) WhereHasTokenWith(preds ...predicate.Token) { + f.Where(entql.HasEdgeWith("token", sqlgraph.WrapFunc(func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }))) +} + // addPredicate implements the predicateAdder interface. func (bq *BlobQuery) addPredicate(pred func(s *sql.Selector)) { bq.predicates = append(bq.predicates, pred) @@ -440,7 +552,7 @@ type BlobFilter struct { // Where applies the entql predicate on the query filter. func (f *BlobFilter) Where(p entql.P) { f.addPredicate(func(s *sql.Selector) { - if err := schemaGraph.EvalP(schemaGraph.Nodes[0].Type, p, s); err != nil { + if err := schemaGraph.EvalP(schemaGraph.Nodes[1].Type, p, s); err != nil { s.AddError(err) } }) @@ -517,7 +629,7 @@ type CarFilter struct { // Where applies the entql predicate on the query filter. func (f *CarFilter) Where(p entql.P) { f.addPredicate(func(s *sql.Selector) { - if err := schemaGraph.EvalP(schemaGraph.Nodes[1].Type, p, s); err != nil { + if err := schemaGraph.EvalP(schemaGraph.Nodes[2].Type, p, s); err != nil { s.AddError(err) } }) @@ -585,7 +697,7 @@ type DeviceFilter struct { // Where applies the entql predicate on the query filter. func (f *DeviceFilter) Where(p entql.P) { f.addPredicate(func(s *sql.Selector) { - if err := schemaGraph.EvalP(schemaGraph.Nodes[2].Type, p, s); err != nil { + if err := schemaGraph.EvalP(schemaGraph.Nodes[3].Type, p, s); err != nil { s.AddError(err) } }) @@ -652,7 +764,7 @@ type DocFilter struct { // Where applies the entql predicate on the query filter. func (f *DocFilter) Where(p entql.P) { f.addPredicate(func(s *sql.Selector) { - if err := schemaGraph.EvalP(schemaGraph.Nodes[3].Type, p, s); err != nil { + if err := schemaGraph.EvalP(schemaGraph.Nodes[4].Type, p, s); err != nil { s.AddError(err) } }) @@ -724,7 +836,7 @@ type GroupFilter struct { // Where applies the entql predicate on the query filter. func (f *GroupFilter) Where(p entql.P) { f.addPredicate(func(s *sql.Selector) { - if err := schemaGraph.EvalP(schemaGraph.Nodes[4].Type, p, s); err != nil { + if err := schemaGraph.EvalP(schemaGraph.Nodes[5].Type, p, s); err != nil { s.AddError(err) } }) @@ -777,7 +889,7 @@ type MixinIDFilter struct { // Where applies the entql predicate on the query filter. func (f *MixinIDFilter) Where(p entql.P) { f.addPredicate(func(s *sql.Selector) { - if err := schemaGraph.EvalP(schemaGraph.Nodes[5].Type, p, s); err != nil { + if err := schemaGraph.EvalP(schemaGraph.Nodes[6].Type, p, s); err != nil { s.AddError(err) } }) @@ -826,7 +938,7 @@ type NoteFilter struct { // Where applies the entql predicate on the query filter. func (f *NoteFilter) Where(p entql.P) { f.addPredicate(func(s *sql.Selector) { - if err := schemaGraph.EvalP(schemaGraph.Nodes[6].Type, p, s); err != nil { + if err := schemaGraph.EvalP(schemaGraph.Nodes[7].Type, p, s); err != nil { s.AddError(err) } }) @@ -898,7 +1010,7 @@ type OtherFilter struct { // Where applies the entql predicate on the query filter. func (f *OtherFilter) Where(p entql.P) { f.addPredicate(func(s *sql.Selector) { - if err := schemaGraph.EvalP(schemaGraph.Nodes[7].Type, p, s); err != nil { + if err := schemaGraph.EvalP(schemaGraph.Nodes[8].Type, p, s); err != nil { s.AddError(err) } }) @@ -937,7 +1049,7 @@ type PetFilter struct { // Where applies the entql predicate on the query filter. func (f *PetFilter) Where(p entql.P) { f.addPredicate(func(s *sql.Selector) { - if err := schemaGraph.EvalP(schemaGraph.Nodes[8].Type, p, s); err != nil { + if err := schemaGraph.EvalP(schemaGraph.Nodes[9].Type, p, s); err != nil { s.AddError(err) } }) @@ -1032,7 +1144,7 @@ type SessionFilter struct { // Where applies the entql predicate on the query filter. func (f *SessionFilter) Where(p entql.P) { f.addPredicate(func(s *sql.Selector) { - if err := schemaGraph.EvalP(schemaGraph.Nodes[9].Type, p, s); err != nil { + if err := schemaGraph.EvalP(schemaGraph.Nodes[10].Type, p, s); err != nil { s.AddError(err) } }) @@ -1057,6 +1169,64 @@ func (f *SessionFilter) WhereHasDeviceWith(preds ...predicate.Device) { }))) } +// addPredicate implements the predicateAdder interface. +func (tq *TokenQuery) addPredicate(pred func(s *sql.Selector)) { + tq.predicates = append(tq.predicates, pred) +} + +// Filter returns a Filter implementation to apply filters on the TokenQuery builder. +func (tq *TokenQuery) Filter() *TokenFilter { + return &TokenFilter{tq} +} + +// addPredicate implements the predicateAdder interface. +func (m *TokenMutation) addPredicate(pred func(s *sql.Selector)) { + m.predicates = append(m.predicates, pred) +} + +// Filter returns an entql.Where implementation to apply filters on the TokenMutation builder. +func (m *TokenMutation) Filter() *TokenFilter { + return &TokenFilter{m} +} + +// TokenFilter provides a generic filtering capability at runtime for TokenQuery. +type TokenFilter struct { + predicateAdder +} + +// Where applies the entql predicate on the query filter. +func (f *TokenFilter) Where(p entql.P) { + f.addPredicate(func(s *sql.Selector) { + if err := schemaGraph.EvalP(schemaGraph.Nodes[11].Type, p, s); err != nil { + s.AddError(err) + } + }) +} + +// WhereID applies the entql other predicate on the id field. +func (f *TokenFilter) WhereID(p entql.OtherP) { + f.Where(p.Field(token.FieldID)) +} + +// WhereBody applies the entql string predicate on the body field. +func (f *TokenFilter) WhereBody(p entql.StringP) { + f.Where(p.Field(token.FieldBody)) +} + +// WhereHasAccount applies a predicate to check if query has an edge account. +func (f *TokenFilter) WhereHasAccount() { + f.Where(entql.HasEdge("account")) +} + +// WhereHasAccountWith applies a predicate to check if query has an edge account with a given conditions (other predicates). +func (f *TokenFilter) WhereHasAccountWith(preds ...predicate.Account) { + f.Where(entql.HasEdgeWith("account", sqlgraph.WrapFunc(func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }))) +} + // addPredicate implements the predicateAdder interface. func (uq *UserQuery) addPredicate(pred func(s *sql.Selector)) { uq.predicates = append(uq.predicates, pred) @@ -1085,7 +1255,7 @@ type UserFilter struct { // Where applies the entql predicate on the query filter. func (f *UserFilter) Where(p entql.P) { f.addPredicate(func(s *sql.Selector) { - if err := schemaGraph.EvalP(schemaGraph.Nodes[10].Type, p, s); err != nil { + if err := schemaGraph.EvalP(schemaGraph.Nodes[12].Type, p, s); err != nil { s.AddError(err) } }) diff --git a/entc/integration/customid/ent/hook/hook.go b/entc/integration/customid/ent/hook/hook.go index 594bac577..aef0d2ba2 100644 --- a/entc/integration/customid/ent/hook/hook.go +++ b/entc/integration/customid/ent/hook/hook.go @@ -13,6 +13,19 @@ import ( "entgo.io/ent/entc/integration/customid/ent" ) +// The AccountFunc type is an adapter to allow the use of ordinary +// function as Account mutator. +type AccountFunc func(context.Context, *ent.AccountMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f AccountFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + mv, ok := m.(*ent.AccountMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.AccountMutation", m) + } + return f(ctx, mv) +} + // The BlobFunc type is an adapter to allow the use of ordinary // function as Blob mutator. type BlobFunc func(context.Context, *ent.BlobMutation) (ent.Value, error) @@ -143,6 +156,19 @@ func (f SessionFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, err return f(ctx, mv) } +// The TokenFunc type is an adapter to allow the use of ordinary +// function as Token mutator. +type TokenFunc func(context.Context, *ent.TokenMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f TokenFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + mv, ok := m.(*ent.TokenMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.TokenMutation", 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, *ent.UserMutation) (ent.Value, error) diff --git a/entc/integration/customid/ent/migrate/schema.go b/entc/integration/customid/ent/migrate/schema.go index b9eaa8a66..8f2de6e6c 100644 --- a/entc/integration/customid/ent/migrate/schema.go +++ b/entc/integration/customid/ent/migrate/schema.go @@ -12,6 +12,17 @@ import ( ) var ( + // AccountsColumns holds the columns for the "accounts" table. + AccountsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeOther, SchemaType: map[string]string{"mysql": "bigint", "postgres": "bigint", "sqlite3": "integer"}}, + {Name: "email", Type: field.TypeString}, + } + // AccountsTable holds the schema information for the "accounts" table. + AccountsTable = &schema.Table{ + Name: "accounts", + Columns: AccountsColumns, + PrimaryKey: []*schema.Column{AccountsColumns[0]}, + } // BlobsColumns holds the columns for the "blobs" table. BlobsColumns = []*schema.Column{ {Name: "id", Type: field.TypeUUID, Unique: true, Default: "uuid_generate_v4()"}, @@ -213,6 +224,26 @@ var ( }, }, } + // TokensColumns holds the columns for the "tokens" table. + TokensColumns = []*schema.Column{ + {Name: "id", Type: field.TypeOther, SchemaType: map[string]string{"mysql": "bigint", "postgres": "bigint", "sqlite3": "integer"}}, + {Name: "body", Type: field.TypeString}, + {Name: "account_token", Type: field.TypeOther, SchemaType: map[string]string{"mysql": "bigint", "postgres": "bigint", "sqlite3": "integer"}}, + } + // TokensTable holds the schema information for the "tokens" table. + TokensTable = &schema.Table{ + Name: "tokens", + Columns: TokensColumns, + PrimaryKey: []*schema.Column{TokensColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "tokens_accounts_token", + Columns: []*schema.Column{TokensColumns[2]}, + RefColumns: []*schema.Column{AccountsColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + } // UsersColumns holds the columns for the "users" table. UsersColumns = []*schema.Column{ {Name: "oid", Type: field.TypeInt, Increment: true}, @@ -309,6 +340,7 @@ var ( } // Tables holds all the tables in the schema. Tables = []*schema.Table{ + AccountsTable, BlobsTable, CarsTable, DevicesTable, @@ -319,6 +351,7 @@ var ( OthersTable, PetsTable, SessionsTable, + TokensTable, UsersTable, BlobLinksTable, GroupUsersTable, @@ -335,6 +368,7 @@ func init() { PetsTable.ForeignKeys[0].RefTable = PetsTable PetsTable.ForeignKeys[1].RefTable = UsersTable SessionsTable.ForeignKeys[0].RefTable = DevicesTable + TokensTable.ForeignKeys[0].RefTable = AccountsTable UsersTable.ForeignKeys[0].RefTable = UsersTable BlobLinksTable.ForeignKeys[0].RefTable = BlobsTable BlobLinksTable.ForeignKeys[1].RefTable = BlobsTable diff --git a/entc/integration/customid/ent/mutation.go b/entc/integration/customid/ent/mutation.go index e33f9f9b3..fb5412656 100644 --- a/entc/integration/customid/ent/mutation.go +++ b/entc/integration/customid/ent/mutation.go @@ -12,6 +12,7 @@ import ( "fmt" "sync" + "entgo.io/ent/entc/integration/customid/ent/account" "entgo.io/ent/entc/integration/customid/ent/blob" "entgo.io/ent/entc/integration/customid/ent/car" "entgo.io/ent/entc/integration/customid/ent/device" @@ -23,6 +24,7 @@ import ( "entgo.io/ent/entc/integration/customid/ent/predicate" "entgo.io/ent/entc/integration/customid/ent/schema" "entgo.io/ent/entc/integration/customid/ent/session" + "entgo.io/ent/entc/integration/customid/ent/token" "entgo.io/ent/entc/integration/customid/ent/user" "entgo.io/ent/entc/integration/customid/sid" "github.com/google/uuid" @@ -39,6 +41,7 @@ const ( OpUpdateOne = ent.OpUpdateOne // Node types. + TypeAccount = "Account" TypeBlob = "Blob" TypeCar = "Car" TypeDevice = "Device" @@ -49,9 +52,420 @@ const ( TypeOther = "Other" TypePet = "Pet" TypeSession = "Session" + TypeToken = "Token" TypeUser = "User" ) +// AccountMutation represents an operation that mutates the Account nodes in the graph. +type AccountMutation struct { + config + op Op + typ string + id *sid.ID + email *string + clearedFields map[string]struct{} + token map[sid.ID]struct{} + removedtoken map[sid.ID]struct{} + clearedtoken bool + done bool + oldValue func(context.Context) (*Account, error) + predicates []predicate.Account +} + +var _ ent.Mutation = (*AccountMutation)(nil) + +// accountOption allows management of the mutation configuration using functional options. +type accountOption func(*AccountMutation) + +// newAccountMutation creates new mutation for the Account entity. +func newAccountMutation(c config, op Op, opts ...accountOption) *AccountMutation { + m := &AccountMutation{ + config: c, + op: op, + typ: TypeAccount, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withAccountID sets the ID field of the mutation. +func withAccountID(id sid.ID) accountOption { + return func(m *AccountMutation) { + var ( + err error + once sync.Once + value *Account + ) + m.oldValue = func(ctx context.Context) (*Account, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Account.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withAccount sets the old Account of the mutation. +func withAccount(node *Account) accountOption { + return func(m *AccountMutation) { + m.oldValue = func(context.Context) (*Account, 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 AccountMutation) 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 AccountMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("ent: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of Account entities. +func (m *AccountMutation) SetID(id sid.ID) { + 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 *AccountMutation) ID() (id sid.ID, 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 *AccountMutation) IDs(ctx context.Context) ([]sid.ID, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []sid.ID{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().Account.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetEmail sets the "email" field. +func (m *AccountMutation) SetEmail(s string) { + m.email = &s +} + +// Email returns the value of the "email" field in the mutation. +func (m *AccountMutation) Email() (r string, exists bool) { + v := m.email + if v == nil { + return + } + return *v, true +} + +// OldEmail returns the old "email" field's value of the Account entity. +// If the Account 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 *AccountMutation) OldEmail(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEmail is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEmail requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEmail: %w", err) + } + return oldValue.Email, nil +} + +// ResetEmail resets all changes to the "email" field. +func (m *AccountMutation) ResetEmail() { + m.email = nil +} + +// AddTokenIDs adds the "token" edge to the Token entity by ids. +func (m *AccountMutation) AddTokenIDs(ids ...sid.ID) { + if m.token == nil { + m.token = make(map[sid.ID]struct{}) + } + for i := range ids { + m.token[ids[i]] = struct{}{} + } +} + +// ClearToken clears the "token" edge to the Token entity. +func (m *AccountMutation) ClearToken() { + m.clearedtoken = true +} + +// TokenCleared reports if the "token" edge to the Token entity was cleared. +func (m *AccountMutation) TokenCleared() bool { + return m.clearedtoken +} + +// RemoveTokenIDs removes the "token" edge to the Token entity by IDs. +func (m *AccountMutation) RemoveTokenIDs(ids ...sid.ID) { + if m.removedtoken == nil { + m.removedtoken = make(map[sid.ID]struct{}) + } + for i := range ids { + delete(m.token, ids[i]) + m.removedtoken[ids[i]] = struct{}{} + } +} + +// RemovedToken returns the removed IDs of the "token" edge to the Token entity. +func (m *AccountMutation) RemovedTokenIDs() (ids []sid.ID) { + for id := range m.removedtoken { + ids = append(ids, id) + } + return +} + +// TokenIDs returns the "token" edge IDs in the mutation. +func (m *AccountMutation) TokenIDs() (ids []sid.ID) { + for id := range m.token { + ids = append(ids, id) + } + return +} + +// ResetToken resets all changes to the "token" edge. +func (m *AccountMutation) ResetToken() { + m.token = nil + m.clearedtoken = false + m.removedtoken = nil +} + +// Where appends a list predicates to the AccountMutation builder. +func (m *AccountMutation) Where(ps ...predicate.Account) { + m.predicates = append(m.predicates, ps...) +} + +// Op returns the operation name. +func (m *AccountMutation) Op() Op { + return m.op +} + +// Type returns the node type of this mutation (Account). +func (m *AccountMutation) 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 *AccountMutation) Fields() []string { + fields := make([]string, 0, 1) + if m.email != nil { + fields = append(fields, account.FieldEmail) + } + 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 *AccountMutation) Field(name string) (ent.Value, bool) { + switch name { + case account.FieldEmail: + return m.Email() + } + 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 *AccountMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case account.FieldEmail: + return m.OldEmail(ctx) + } + return nil, fmt.Errorf("unknown Account 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 *AccountMutation) SetField(name string, value ent.Value) error { + switch name { + case account.FieldEmail: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEmail(v) + return nil + } + return fmt.Errorf("unknown Account field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *AccountMutation) 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 *AccountMutation) 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 *AccountMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown Account numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *AccountMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *AccountMutation) 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 *AccountMutation) ClearField(name string) error { + return fmt.Errorf("unknown Account 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 *AccountMutation) ResetField(name string) error { + switch name { + case account.FieldEmail: + m.ResetEmail() + return nil + } + return fmt.Errorf("unknown Account field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *AccountMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.token != nil { + edges = append(edges, account.EdgeToken) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *AccountMutation) AddedIDs(name string) []ent.Value { + switch name { + case account.EdgeToken: + ids := make([]ent.Value, 0, len(m.token)) + for id := range m.token { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *AccountMutation) RemovedEdges() []string { + edges := make([]string, 0, 1) + if m.removedtoken != nil { + edges = append(edges, account.EdgeToken) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *AccountMutation) RemovedIDs(name string) []ent.Value { + switch name { + case account.EdgeToken: + ids := make([]ent.Value, 0, len(m.removedtoken)) + for id := range m.removedtoken { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *AccountMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedtoken { + edges = append(edges, account.EdgeToken) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *AccountMutation) EdgeCleared(name string) bool { + switch name { + case account.EdgeToken: + return m.clearedtoken + } + 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 *AccountMutation) ClearEdge(name string) error { + switch name { + } + return fmt.Errorf("unknown Account 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 *AccountMutation) ResetEdge(name string) error { + switch name { + case account.EdgeToken: + m.ResetToken() + return nil + } + return fmt.Errorf("unknown Account edge %s", name) +} + // BlobMutation represents an operation that mutates the Blob nodes in the graph. type BlobMutation struct { config @@ -4453,6 +4867,392 @@ func (m *SessionMutation) ResetEdge(name string) error { return fmt.Errorf("unknown Session edge %s", name) } +// TokenMutation represents an operation that mutates the Token nodes in the graph. +type TokenMutation struct { + config + op Op + typ string + id *sid.ID + body *string + clearedFields map[string]struct{} + account *sid.ID + clearedaccount bool + done bool + oldValue func(context.Context) (*Token, error) + predicates []predicate.Token +} + +var _ ent.Mutation = (*TokenMutation)(nil) + +// tokenOption allows management of the mutation configuration using functional options. +type tokenOption func(*TokenMutation) + +// newTokenMutation creates new mutation for the Token entity. +func newTokenMutation(c config, op Op, opts ...tokenOption) *TokenMutation { + m := &TokenMutation{ + config: c, + op: op, + typ: TypeToken, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withTokenID sets the ID field of the mutation. +func withTokenID(id sid.ID) tokenOption { + return func(m *TokenMutation) { + var ( + err error + once sync.Once + value *Token + ) + m.oldValue = func(ctx context.Context) (*Token, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Token.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withToken sets the old Token of the mutation. +func withToken(node *Token) tokenOption { + return func(m *TokenMutation) { + m.oldValue = func(context.Context) (*Token, 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 TokenMutation) 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 TokenMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("ent: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of Token entities. +func (m *TokenMutation) SetID(id sid.ID) { + 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 *TokenMutation) ID() (id sid.ID, 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 *TokenMutation) IDs(ctx context.Context) ([]sid.ID, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []sid.ID{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().Token.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetBody sets the "body" field. +func (m *TokenMutation) SetBody(s string) { + m.body = &s +} + +// Body returns the value of the "body" field in the mutation. +func (m *TokenMutation) Body() (r string, exists bool) { + v := m.body + if v == nil { + return + } + return *v, true +} + +// OldBody returns the old "body" field's value of the Token entity. +// If the Token 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 *TokenMutation) OldBody(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldBody is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldBody requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldBody: %w", err) + } + return oldValue.Body, nil +} + +// ResetBody resets all changes to the "body" field. +func (m *TokenMutation) ResetBody() { + m.body = nil +} + +// SetAccountID sets the "account" edge to the Account entity by id. +func (m *TokenMutation) SetAccountID(id sid.ID) { + m.account = &id +} + +// ClearAccount clears the "account" edge to the Account entity. +func (m *TokenMutation) ClearAccount() { + m.clearedaccount = true +} + +// AccountCleared reports if the "account" edge to the Account entity was cleared. +func (m *TokenMutation) AccountCleared() bool { + return m.clearedaccount +} + +// AccountID returns the "account" edge ID in the mutation. +func (m *TokenMutation) AccountID() (id sid.ID, exists bool) { + if m.account != nil { + return *m.account, true + } + return +} + +// AccountIDs returns the "account" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// AccountID instead. It exists only for internal usage by the builders. +func (m *TokenMutation) AccountIDs() (ids []sid.ID) { + if id := m.account; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetAccount resets all changes to the "account" edge. +func (m *TokenMutation) ResetAccount() { + m.account = nil + m.clearedaccount = false +} + +// Where appends a list predicates to the TokenMutation builder. +func (m *TokenMutation) Where(ps ...predicate.Token) { + m.predicates = append(m.predicates, ps...) +} + +// Op returns the operation name. +func (m *TokenMutation) Op() Op { + return m.op +} + +// Type returns the node type of this mutation (Token). +func (m *TokenMutation) 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 *TokenMutation) Fields() []string { + fields := make([]string, 0, 1) + if m.body != nil { + fields = append(fields, token.FieldBody) + } + 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 *TokenMutation) Field(name string) (ent.Value, bool) { + switch name { + case token.FieldBody: + return m.Body() + } + 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 *TokenMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case token.FieldBody: + return m.OldBody(ctx) + } + return nil, fmt.Errorf("unknown Token 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 *TokenMutation) SetField(name string, value ent.Value) error { + switch name { + case token.FieldBody: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetBody(v) + return nil + } + return fmt.Errorf("unknown Token field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *TokenMutation) 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 *TokenMutation) 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 *TokenMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown Token numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *TokenMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *TokenMutation) 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 *TokenMutation) ClearField(name string) error { + return fmt.Errorf("unknown Token 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 *TokenMutation) ResetField(name string) error { + switch name { + case token.FieldBody: + m.ResetBody() + return nil + } + return fmt.Errorf("unknown Token field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *TokenMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.account != nil { + edges = append(edges, token.EdgeAccount) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *TokenMutation) AddedIDs(name string) []ent.Value { + switch name { + case token.EdgeAccount: + if id := m.account; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *TokenMutation) 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 *TokenMutation) RemovedIDs(name string) []ent.Value { + switch name { + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *TokenMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedaccount { + edges = append(edges, token.EdgeAccount) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *TokenMutation) EdgeCleared(name string) bool { + switch name { + case token.EdgeAccount: + return m.clearedaccount + } + 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 *TokenMutation) ClearEdge(name string) error { + switch name { + case token.EdgeAccount: + m.ClearAccount() + return nil + } + return fmt.Errorf("unknown Token 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 *TokenMutation) ResetEdge(name string) error { + switch name { + case token.EdgeAccount: + m.ResetAccount() + return nil + } + return fmt.Errorf("unknown Token edge %s", name) +} + // UserMutation represents an operation that mutates the User nodes in the graph. type UserMutation struct { config diff --git a/entc/integration/customid/ent/predicate/predicate.go b/entc/integration/customid/ent/predicate/predicate.go index 25a67a47e..69e14e5b4 100644 --- a/entc/integration/customid/ent/predicate/predicate.go +++ b/entc/integration/customid/ent/predicate/predicate.go @@ -10,6 +10,9 @@ import ( "entgo.io/ent/dialect/sql" ) +// Account is the predicate function for account builders. +type Account func(*sql.Selector) + // Blob is the predicate function for blob builders. type Blob func(*sql.Selector) @@ -40,5 +43,8 @@ type Pet func(*sql.Selector) // Session is the predicate function for session builders. type Session func(*sql.Selector) +// Token is the predicate function for token builders. +type Token func(*sql.Selector) + // User is the predicate function for user builders. type User func(*sql.Selector) diff --git a/entc/integration/customid/ent/runtime.go b/entc/integration/customid/ent/runtime.go index b045aea16..40b576fa7 100644 --- a/entc/integration/customid/ent/runtime.go +++ b/entc/integration/customid/ent/runtime.go @@ -7,6 +7,7 @@ package ent import ( + "entgo.io/ent/entc/integration/customid/ent/account" "entgo.io/ent/entc/integration/customid/ent/blob" "entgo.io/ent/entc/integration/customid/ent/car" "entgo.io/ent/entc/integration/customid/ent/device" @@ -17,6 +18,7 @@ import ( "entgo.io/ent/entc/integration/customid/ent/pet" "entgo.io/ent/entc/integration/customid/ent/schema" "entgo.io/ent/entc/integration/customid/ent/session" + "entgo.io/ent/entc/integration/customid/ent/token" "entgo.io/ent/entc/integration/customid/sid" "github.com/google/uuid" ) @@ -25,6 +27,16 @@ import ( // (default values, validators, hooks and policies) and stitches it // to their package variables. func init() { + accountFields := schema.Account{}.Fields() + _ = accountFields + // accountDescEmail is the schema descriptor for email field. + accountDescEmail := accountFields[1].Descriptor() + // account.EmailValidator is a validator for the "email" field. It is called by the builders before save. + account.EmailValidator = accountDescEmail.Validators[0].(func(string) error) + // accountDescID is the schema descriptor for id field. + accountDescID := accountFields[0].Descriptor() + // account.DefaultID holds the default value on creation for the id field. + account.DefaultID = accountDescID.Default.(func() sid.ID) blobFields := schema.Blob{}.Fields() _ = blobFields // blobDescUUID is the schema descriptor for uuid field. @@ -153,4 +165,14 @@ func init() { session.DefaultID = sessionDescID.Default.(func() schema.ID) // session.IDValidator is a validator for the "id" field. It is called by the builders before save. session.IDValidator = sessionDescID.Validators[0].(func([]byte) error) + tokenFields := schema.Token{}.Fields() + _ = tokenFields + // tokenDescBody is the schema descriptor for body field. + tokenDescBody := tokenFields[1].Descriptor() + // token.BodyValidator is a validator for the "body" field. It is called by the builders before save. + token.BodyValidator = tokenDescBody.Validators[0].(func(string) error) + // tokenDescID is the schema descriptor for id field. + tokenDescID := tokenFields[0].Descriptor() + // token.DefaultID holds the default value on creation for the id field. + token.DefaultID = tokenDescID.Default.(func() sid.ID) } diff --git a/entc/integration/customid/ent/schema/accout.go b/entc/integration/customid/ent/schema/accout.go new file mode 100644 index 000000000..f9d083690 --- /dev/null +++ b/entc/integration/customid/ent/schema/accout.go @@ -0,0 +1,40 @@ +// 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" + "entgo.io/ent/entc/integration/customid/sid" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" +) + +// Account holds the schema definition for the Account entity. +type Account struct { + ent.Schema +} + +// Fields of the Account. +func (Account) Fields() []ent.Field { + return []ent.Field{ + field.Other("id", sid.ID("")). + SchemaType(map[string]string{ + dialect.MySQL: "bigint", + dialect.Postgres: "bigint", + dialect.SQLite: "integer", + }). + Default(sid.New). + Immutable(), + field.String("email").NotEmpty(), + } +} + +// Edges of the Account. +func (Account) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("token", Token.Type), + } +} diff --git a/entc/integration/customid/ent/schema/token.go b/entc/integration/customid/ent/schema/token.go new file mode 100644 index 000000000..41871906d --- /dev/null +++ b/entc/integration/customid/ent/schema/token.go @@ -0,0 +1,40 @@ +// 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" + "entgo.io/ent/entc/integration/customid/sid" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" +) + +// Token holds the schema definition for the Token entity. +type Token struct { + ent.Schema +} + +// Fields of the Token. +func (Token) Fields() []ent.Field { + return []ent.Field{ + field.Other("id", sid.ID("")). + SchemaType(map[string]string{ + dialect.MySQL: "bigint", + dialect.Postgres: "bigint", + dialect.SQLite: "integer", + }). + Default(sid.New). + Immutable(), + field.String("body").NotEmpty(), + } +} + +// Edges of the Token. +func (Token) Edges() []ent.Edge { + return []ent.Edge{ + edge.From("account", Account.Type).Ref("token").Required().Unique(), + } +} diff --git a/entc/integration/customid/ent/token.go b/entc/integration/customid/ent/token.go new file mode 100644 index 000000000..c9a836926 --- /dev/null +++ b/entc/integration/customid/ent/token.go @@ -0,0 +1,146 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/entc/integration/customid/ent/account" + "entgo.io/ent/entc/integration/customid/ent/token" + "entgo.io/ent/entc/integration/customid/sid" +) + +// Token is the model entity for the Token schema. +type Token struct { + config `json:"-"` + // ID of the ent. + ID sid.ID `json:"id,omitempty"` + // Body holds the value of the "body" field. + Body string `json:"body,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the TokenQuery when eager-loading is set. + Edges TokenEdges `json:"edges"` + account_token *sid.ID +} + +// TokenEdges holds the relations/edges for other nodes in the graph. +type TokenEdges struct { + // Account holds the value of the account edge. + Account *Account `json:"account,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// AccountOrErr returns the Account value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e TokenEdges) AccountOrErr() (*Account, error) { + if e.loadedTypes[0] { + if e.Account == nil { + // The edge account was loaded in eager-loading, + // but was not found. + return nil, &NotFoundError{label: account.Label} + } + return e.Account, nil + } + return nil, &NotLoadedError{edge: "account"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Token) scanValues(columns []string) ([]interface{}, error) { + values := make([]interface{}, len(columns)) + for i := range columns { + switch columns[i] { + case token.FieldID: + values[i] = new(sid.ID) + case token.FieldBody: + values[i] = new(sql.NullString) + case token.ForeignKeys[0]: // account_token + values[i] = &sql.NullScanner{S: new(sid.ID)} + default: + return nil, fmt.Errorf("unexpected column %q for type Token", columns[i]) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the Token fields. +func (t *Token) 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 token.FieldID: + if value, ok := values[i].(*sid.ID); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value != nil { + t.ID = *value + } + case token.FieldBody: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field body", values[i]) + } else if value.Valid { + t.Body = value.String + } + case token.ForeignKeys[0]: + if value, ok := values[i].(*sql.NullScanner); !ok { + return fmt.Errorf("unexpected type %T for field account_token", values[i]) + } else if value.Valid { + t.account_token = new(sid.ID) + *t.account_token = *value.S.(*sid.ID) + } + } + } + return nil +} + +// QueryAccount queries the "account" edge of the Token entity. +func (t *Token) QueryAccount() *AccountQuery { + return (&TokenClient{config: t.config}).QueryAccount(t) +} + +// Update returns a builder for updating this Token. +// Note that you need to call Token.Unwrap() before calling this method if this Token +// was returned from a transaction, and the transaction was committed or rolled back. +func (t *Token) Update() *TokenUpdateOne { + return (&TokenClient{config: t.config}).UpdateOne(t) +} + +// Unwrap unwraps the Token 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 (t *Token) Unwrap() *Token { + tx, ok := t.config.driver.(*txDriver) + if !ok { + panic("ent: Token is not a transactional entity") + } + t.config.driver = tx.drv + return t +} + +// String implements the fmt.Stringer. +func (t *Token) String() string { + var builder strings.Builder + builder.WriteString("Token(") + builder.WriteString(fmt.Sprintf("id=%v", t.ID)) + builder.WriteString(", body=") + builder.WriteString(t.Body) + builder.WriteByte(')') + return builder.String() +} + +// Tokens is a parsable slice of Token. +type Tokens []*Token + +func (t Tokens) config(cfg config) { + for _i := range t { + t[_i].config = cfg + } +} diff --git a/entc/integration/customid/ent/token/token.go b/entc/integration/customid/ent/token/token.go new file mode 100644 index 000000000..58aa4f454 --- /dev/null +++ b/entc/integration/customid/ent/token/token.go @@ -0,0 +1,65 @@ +// 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 token + +import ( + "entgo.io/ent/entc/integration/customid/sid" +) + +const ( + // Label holds the string label denoting the token type in the database. + Label = "token" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldBody holds the string denoting the body field in the database. + FieldBody = "body" + // EdgeAccount holds the string denoting the account edge name in mutations. + EdgeAccount = "account" + // Table holds the table name of the token in the database. + Table = "tokens" + // AccountTable is the table that holds the account relation/edge. + AccountTable = "tokens" + // AccountInverseTable is the table name for the Account entity. + // It exists in this package in order to avoid circular dependency with the "account" package. + AccountInverseTable = "accounts" + // AccountColumn is the table column denoting the account relation/edge. + AccountColumn = "account_token" +) + +// Columns holds all SQL columns for token fields. +var Columns = []string{ + FieldID, + FieldBody, +} + +// ForeignKeys holds the SQL foreign-keys that are owned by the "tokens" +// table and are not defined as standalone fields in the schema. +var ForeignKeys = []string{ + "account_token", +} + +// 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 ( + // BodyValidator is a validator for the "body" field. It is called by the builders before save. + BodyValidator func(string) error + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() sid.ID +) diff --git a/entc/integration/customid/ent/token/where.go b/entc/integration/customid/ent/token/where.go new file mode 100644 index 000000000..506ceb603 --- /dev/null +++ b/entc/integration/customid/ent/token/where.go @@ -0,0 +1,275 @@ +// 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 token + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/customid/ent/predicate" + "entgo.io/ent/entc/integration/customid/sid" +) + +// ID filters vertices based on their ID field. +func ID(id sid.ID) predicate.Token { + return predicate.Token(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id sid.ID) predicate.Token { + return predicate.Token(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id sid.ID) predicate.Token { + return predicate.Token(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldID), id)) + }) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...sid.ID) predicate.Token { + return predicate.Token(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 ...sid.ID) predicate.Token { + return predicate.Token(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 sid.ID) predicate.Token { + return predicate.Token(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldID), id)) + }) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id sid.ID) predicate.Token { + return predicate.Token(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldID), id)) + }) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id sid.ID) predicate.Token { + return predicate.Token(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldID), id)) + }) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id sid.ID) predicate.Token { + return predicate.Token(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldID), id)) + }) +} + +// Body applies equality check predicate on the "body" field. It's identical to BodyEQ. +func Body(v string) predicate.Token { + return predicate.Token(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldBody), v)) + }) +} + +// BodyEQ applies the EQ predicate on the "body" field. +func BodyEQ(v string) predicate.Token { + return predicate.Token(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldBody), v)) + }) +} + +// BodyNEQ applies the NEQ predicate on the "body" field. +func BodyNEQ(v string) predicate.Token { + return predicate.Token(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldBody), v)) + }) +} + +// BodyIn applies the In predicate on the "body" field. +func BodyIn(vs ...string) predicate.Token { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Token(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(FieldBody), v...)) + }) +} + +// BodyNotIn applies the NotIn predicate on the "body" field. +func BodyNotIn(vs ...string) predicate.Token { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Token(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(FieldBody), v...)) + }) +} + +// BodyGT applies the GT predicate on the "body" field. +func BodyGT(v string) predicate.Token { + return predicate.Token(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldBody), v)) + }) +} + +// BodyGTE applies the GTE predicate on the "body" field. +func BodyGTE(v string) predicate.Token { + return predicate.Token(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldBody), v)) + }) +} + +// BodyLT applies the LT predicate on the "body" field. +func BodyLT(v string) predicate.Token { + return predicate.Token(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldBody), v)) + }) +} + +// BodyLTE applies the LTE predicate on the "body" field. +func BodyLTE(v string) predicate.Token { + return predicate.Token(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldBody), v)) + }) +} + +// BodyContains applies the Contains predicate on the "body" field. +func BodyContains(v string) predicate.Token { + return predicate.Token(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldBody), v)) + }) +} + +// BodyHasPrefix applies the HasPrefix predicate on the "body" field. +func BodyHasPrefix(v string) predicate.Token { + return predicate.Token(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldBody), v)) + }) +} + +// BodyHasSuffix applies the HasSuffix predicate on the "body" field. +func BodyHasSuffix(v string) predicate.Token { + return predicate.Token(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldBody), v)) + }) +} + +// BodyEqualFold applies the EqualFold predicate on the "body" field. +func BodyEqualFold(v string) predicate.Token { + return predicate.Token(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldBody), v)) + }) +} + +// BodyContainsFold applies the ContainsFold predicate on the "body" field. +func BodyContainsFold(v string) predicate.Token { + return predicate.Token(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldBody), v)) + }) +} + +// HasAccount applies the HasEdge predicate on the "account" edge. +func HasAccount() predicate.Token { + return predicate.Token(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(AccountTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, AccountTable, AccountColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasAccountWith applies the HasEdge predicate on the "account" edge with a given conditions (other predicates). +func HasAccountWith(preds ...predicate.Account) predicate.Token { + return predicate.Token(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(AccountInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, AccountTable, AccountColumn), + ) + 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.Token) predicate.Token { + return predicate.Token(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.Token) predicate.Token { + return predicate.Token(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.Token) predicate.Token { + return predicate.Token(func(s *sql.Selector) { + p(s.Not()) + }) +} diff --git a/entc/integration/customid/ent/token_create.go b/entc/integration/customid/ent/token_create.go new file mode 100644 index 000000000..1a3c8911f --- /dev/null +++ b/entc/integration/customid/ent/token_create.go @@ -0,0 +1,595 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/customid/ent/account" + "entgo.io/ent/entc/integration/customid/ent/token" + "entgo.io/ent/entc/integration/customid/sid" + "entgo.io/ent/schema/field" +) + +// TokenCreate is the builder for creating a Token entity. +type TokenCreate struct { + config + mutation *TokenMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetBody sets the "body" field. +func (tc *TokenCreate) SetBody(s string) *TokenCreate { + tc.mutation.SetBody(s) + return tc +} + +// SetID sets the "id" field. +func (tc *TokenCreate) SetID(s sid.ID) *TokenCreate { + tc.mutation.SetID(s) + return tc +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (tc *TokenCreate) SetNillableID(s *sid.ID) *TokenCreate { + if s != nil { + tc.SetID(*s) + } + return tc +} + +// SetAccountID sets the "account" edge to the Account entity by ID. +func (tc *TokenCreate) SetAccountID(id sid.ID) *TokenCreate { + tc.mutation.SetAccountID(id) + return tc +} + +// SetAccount sets the "account" edge to the Account entity. +func (tc *TokenCreate) SetAccount(a *Account) *TokenCreate { + return tc.SetAccountID(a.ID) +} + +// Mutation returns the TokenMutation object of the builder. +func (tc *TokenCreate) Mutation() *TokenMutation { + return tc.mutation +} + +// Save creates the Token in the database. +func (tc *TokenCreate) Save(ctx context.Context) (*Token, error) { + var ( + err error + node *Token + ) + tc.defaults() + if len(tc.hooks) == 0 { + if err = tc.check(); err != nil { + return nil, err + } + node, err = tc.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*TokenMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = tc.check(); err != nil { + return nil, err + } + tc.mutation = mutation + if node, err = tc.sqlSave(ctx); err != nil { + return nil, err + } + mutation.id = &node.ID + mutation.done = true + return node, err + }) + for i := len(tc.hooks) - 1; i >= 0; i-- { + if tc.hooks[i] == nil { + return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = tc.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, tc.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX calls Save and panics if Save returns an error. +func (tc *TokenCreate) SaveX(ctx context.Context) *Token { + v, err := tc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (tc *TokenCreate) Exec(ctx context.Context) error { + _, err := tc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (tc *TokenCreate) ExecX(ctx context.Context) { + if err := tc.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (tc *TokenCreate) defaults() { + if _, ok := tc.mutation.ID(); !ok { + v := token.DefaultID() + tc.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (tc *TokenCreate) check() error { + if _, ok := tc.mutation.Body(); !ok { + return &ValidationError{Name: "body", err: errors.New(`ent: missing required field "Token.body"`)} + } + if v, ok := tc.mutation.Body(); ok { + if err := token.BodyValidator(v); err != nil { + return &ValidationError{Name: "body", err: fmt.Errorf(`ent: validator failed for field "Token.body": %w`, err)} + } + } + if _, ok := tc.mutation.AccountID(); !ok { + return &ValidationError{Name: "account", err: errors.New(`ent: missing required edge "Token.account"`)} + } + return nil +} + +func (tc *TokenCreate) sqlSave(ctx context.Context) (*Token, error) { + _node, _spec := tc.createSpec() + if err := sqlgraph.CreateNode(ctx, tc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + if _spec.ID.Value != nil { + if id, ok := _spec.ID.Value.(*sid.ID); ok { + _node.ID = *id + } else if err := _node.ID.Scan(_spec.ID.Value); err != nil { + return nil, err + } + } + return _node, nil +} + +func (tc *TokenCreate) createSpec() (*Token, *sqlgraph.CreateSpec) { + var ( + _node = &Token{config: tc.config} + _spec = &sqlgraph.CreateSpec{ + Table: token.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeOther, + Column: token.FieldID, + }, + } + ) + _spec.OnConflict = tc.conflict + if id, ok := tc.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = &id + } + if value, ok := tc.mutation.Body(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: token.FieldBody, + }) + _node.Body = value + } + if nodes := tc.mutation.AccountIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: token.AccountTable, + Columns: []string{token.AccountColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeOther, + Column: account.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.account_token = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.Token.Create(). +// SetBody(v). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.TokenUpsert) { +// SetBody(v+v). +// }). +// Exec(ctx) +// +func (tc *TokenCreate) OnConflict(opts ...sql.ConflictOption) *TokenUpsertOne { + tc.conflict = opts + return &TokenUpsertOne{ + create: tc, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.Token.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +// +func (tc *TokenCreate) OnConflictColumns(columns ...string) *TokenUpsertOne { + tc.conflict = append(tc.conflict, sql.ConflictColumns(columns...)) + return &TokenUpsertOne{ + create: tc, + } +} + +type ( + // TokenUpsertOne is the builder for "upsert"-ing + // one Token node. + TokenUpsertOne struct { + create *TokenCreate + } + + // TokenUpsert is the "OnConflict" setter. + TokenUpsert struct { + *sql.UpdateSet + } +) + +// SetBody sets the "body" field. +func (u *TokenUpsert) SetBody(v string) *TokenUpsert { + u.Set(token.FieldBody, v) + return u +} + +// UpdateBody sets the "body" field to the value that was provided on create. +func (u *TokenUpsert) UpdateBody() *TokenUpsert { + u.SetExcluded(token.FieldBody) + return u +} + +// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field. +// Using this option is equivalent to using: +// +// client.Token.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(token.FieldID) +// }), +// ). +// Exec(ctx) +// +func (u *TokenUpsertOne) UpdateNewValues() *TokenUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + if _, exists := u.create.mutation.ID(); exists { + s.SetIgnore(token.FieldID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.Token.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +// +func (u *TokenUpsertOne) Ignore() *TokenUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *TokenUpsertOne) DoNothing() *TokenUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the TokenCreate.OnConflict +// documentation for more info. +func (u *TokenUpsertOne) Update(set func(*TokenUpsert)) *TokenUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&TokenUpsert{UpdateSet: update}) + })) + return u +} + +// SetBody sets the "body" field. +func (u *TokenUpsertOne) SetBody(v string) *TokenUpsertOne { + return u.Update(func(s *TokenUpsert) { + s.SetBody(v) + }) +} + +// UpdateBody sets the "body" field to the value that was provided on create. +func (u *TokenUpsertOne) UpdateBody() *TokenUpsertOne { + return u.Update(func(s *TokenUpsert) { + s.UpdateBody() + }) +} + +// Exec executes the query. +func (u *TokenUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("ent: missing options for TokenCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *TokenUpsertOne) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} + +// Exec executes the UPSERT query and returns the inserted/updated ID. +func (u *TokenUpsertOne) ID(ctx context.Context) (id sid.ID, err error) { + if u.create.driver.Dialect() == dialect.MySQL { + // In case of "ON CONFLICT", there is no way to get back non-numeric ID + // fields from the database since MySQL does not support the RETURNING clause. + return id, errors.New("ent: TokenUpsertOne.ID is not supported by MySQL driver. Use TokenUpsertOne.Exec instead") + } + node, err := u.create.Save(ctx) + if err != nil { + return id, err + } + return node.ID, nil +} + +// IDX is like ID, but panics if an error occurs. +func (u *TokenUpsertOne) IDX(ctx context.Context) sid.ID { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// TokenCreateBulk is the builder for creating many Token entities in bulk. +type TokenCreateBulk struct { + config + builders []*TokenCreate + conflict []sql.ConflictOption +} + +// Save creates the Token entities in the database. +func (tcb *TokenCreateBulk) Save(ctx context.Context) ([]*Token, error) { + specs := make([]*sqlgraph.CreateSpec, len(tcb.builders)) + nodes := make([]*Token, len(tcb.builders)) + mutators := make([]Mutator, len(tcb.builders)) + for i := range tcb.builders { + func(i int, root context.Context) { + builder := tcb.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*TokenMutation) + 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, tcb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = tcb.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, tcb.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 + 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, tcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (tcb *TokenCreateBulk) SaveX(ctx context.Context) []*Token { + v, err := tcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (tcb *TokenCreateBulk) Exec(ctx context.Context) error { + _, err := tcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (tcb *TokenCreateBulk) ExecX(ctx context.Context) { + if err := tcb.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.Token.CreateBulk(builders...). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.TokenUpsert) { +// SetBody(v+v). +// }). +// Exec(ctx) +// +func (tcb *TokenCreateBulk) OnConflict(opts ...sql.ConflictOption) *TokenUpsertBulk { + tcb.conflict = opts + return &TokenUpsertBulk{ + create: tcb, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.Token.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +// +func (tcb *TokenCreateBulk) OnConflictColumns(columns ...string) *TokenUpsertBulk { + tcb.conflict = append(tcb.conflict, sql.ConflictColumns(columns...)) + return &TokenUpsertBulk{ + create: tcb, + } +} + +// TokenUpsertBulk is the builder for "upsert"-ing +// a bulk of Token nodes. +type TokenUpsertBulk struct { + create *TokenCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.Token.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(token.FieldID) +// }), +// ). +// Exec(ctx) +// +func (u *TokenUpsertBulk) UpdateNewValues() *TokenUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + for _, b := range u.create.builders { + if _, exists := b.mutation.ID(); exists { + s.SetIgnore(token.FieldID) + return + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.Token.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +// +func (u *TokenUpsertBulk) Ignore() *TokenUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *TokenUpsertBulk) DoNothing() *TokenUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the TokenCreateBulk.OnConflict +// documentation for more info. +func (u *TokenUpsertBulk) Update(set func(*TokenUpsert)) *TokenUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&TokenUpsert{UpdateSet: update}) + })) + return u +} + +// SetBody sets the "body" field. +func (u *TokenUpsertBulk) SetBody(v string) *TokenUpsertBulk { + return u.Update(func(s *TokenUpsert) { + s.SetBody(v) + }) +} + +// UpdateBody sets the "body" field to the value that was provided on create. +func (u *TokenUpsertBulk) UpdateBody() *TokenUpsertBulk { + return u.Update(func(s *TokenUpsert) { + s.UpdateBody() + }) +} + +// Exec executes the query. +func (u *TokenUpsertBulk) Exec(ctx context.Context) error { + for i, b := range u.create.builders { + if len(b.conflict) != 0 { + return fmt.Errorf("ent: OnConflict was set for builder %d. Set it on the TokenCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("ent: missing options for TokenCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *TokenUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entc/integration/customid/ent/token_delete.go b/entc/integration/customid/ent/token_delete.go new file mode 100644 index 000000000..b9b5d2e58 --- /dev/null +++ b/entc/integration/customid/ent/token_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 ent + +import ( + "context" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/customid/ent/predicate" + "entgo.io/ent/entc/integration/customid/ent/token" + "entgo.io/ent/schema/field" +) + +// TokenDelete is the builder for deleting a Token entity. +type TokenDelete struct { + config + hooks []Hook + mutation *TokenMutation +} + +// Where appends a list predicates to the TokenDelete builder. +func (td *TokenDelete) Where(ps ...predicate.Token) *TokenDelete { + td.mutation.Where(ps...) + return td +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (td *TokenDelete) Exec(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(td.hooks) == 0 { + affected, err = td.sqlExec(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*TokenMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + td.mutation = mutation + affected, err = td.sqlExec(ctx) + mutation.done = true + return affected, err + }) + for i := len(td.hooks) - 1; i >= 0; i-- { + if td.hooks[i] == nil { + return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = td.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, td.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// ExecX is like Exec, but panics if an error occurs. +func (td *TokenDelete) ExecX(ctx context.Context) int { + n, err := td.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (td *TokenDelete) sqlExec(ctx context.Context) (int, error) { + _spec := &sqlgraph.DeleteSpec{ + Node: &sqlgraph.NodeSpec{ + Table: token.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeOther, + Column: token.FieldID, + }, + }, + } + if ps := td.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return sqlgraph.DeleteNodes(ctx, td.driver, _spec) +} + +// TokenDeleteOne is the builder for deleting a single Token entity. +type TokenDeleteOne struct { + td *TokenDelete +} + +// Exec executes the deletion query. +func (tdo *TokenDeleteOne) Exec(ctx context.Context) error { + n, err := tdo.td.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{token.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (tdo *TokenDeleteOne) ExecX(ctx context.Context) { + tdo.td.ExecX(ctx) +} diff --git a/entc/integration/customid/ent/token_query.go b/entc/integration/customid/ent/token_query.go new file mode 100644 index 000000000..029bc73d8 --- /dev/null +++ b/entc/integration/customid/ent/token_query.go @@ -0,0 +1,1005 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "math" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/customid/ent/account" + "entgo.io/ent/entc/integration/customid/ent/predicate" + "entgo.io/ent/entc/integration/customid/ent/token" + "entgo.io/ent/entc/integration/customid/sid" + "entgo.io/ent/schema/field" +) + +// TokenQuery is the builder for querying Token entities. +type TokenQuery struct { + config + limit *int + offset *int + unique *bool + order []OrderFunc + fields []string + predicates []predicate.Token + // eager-loading edges. + withAccount *AccountQuery + 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 TokenQuery builder. +func (tq *TokenQuery) Where(ps ...predicate.Token) *TokenQuery { + tq.predicates = append(tq.predicates, ps...) + return tq +} + +// Limit adds a limit step to the query. +func (tq *TokenQuery) Limit(limit int) *TokenQuery { + tq.limit = &limit + return tq +} + +// Offset adds an offset step to the query. +func (tq *TokenQuery) Offset(offset int) *TokenQuery { + tq.offset = &offset + return tq +} + +// 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 (tq *TokenQuery) Unique(unique bool) *TokenQuery { + tq.unique = &unique + return tq +} + +// Order adds an order step to the query. +func (tq *TokenQuery) Order(o ...OrderFunc) *TokenQuery { + tq.order = append(tq.order, o...) + return tq +} + +// QueryAccount chains the current query on the "account" edge. +func (tq *TokenQuery) QueryAccount() *AccountQuery { + query := &AccountQuery{config: tq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := tq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := tq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(token.Table, token.FieldID, selector), + sqlgraph.To(account.Table, account.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, token.AccountTable, token.AccountColumn), + ) + fromU = sqlgraph.SetNeighbors(tq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first Token entity from the query. +// Returns a *NotFoundError when no Token was found. +func (tq *TokenQuery) First(ctx context.Context) (*Token, error) { + nodes, err := tq.Limit(1).All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{token.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (tq *TokenQuery) FirstX(ctx context.Context) *Token { + node, err := tq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Token ID from the query. +// Returns a *NotFoundError when no Token ID was found. +func (tq *TokenQuery) FirstID(ctx context.Context) (id sid.ID, err error) { + var ids []sid.ID + if ids, err = tq.Limit(1).IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{token.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (tq *TokenQuery) FirstIDX(ctx context.Context) sid.ID { + id, err := tq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Token entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Token entity is found. +// Returns a *NotFoundError when no Token entities are found. +func (tq *TokenQuery) Only(ctx context.Context) (*Token, error) { + nodes, err := tq.Limit(2).All(ctx) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{token.Label} + default: + return nil, &NotSingularError{token.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (tq *TokenQuery) OnlyX(ctx context.Context) *Token { + node, err := tq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Token ID in the query. +// Returns a *NotSingularError when more than one Token ID is found. +// Returns a *NotFoundError when no entities are found. +func (tq *TokenQuery) OnlyID(ctx context.Context) (id sid.ID, err error) { + var ids []sid.ID + if ids, err = tq.Limit(2).IDs(ctx); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{token.Label} + default: + err = &NotSingularError{token.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (tq *TokenQuery) OnlyIDX(ctx context.Context) sid.ID { + id, err := tq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Tokens. +func (tq *TokenQuery) All(ctx context.Context) ([]*Token, error) { + if err := tq.prepareQuery(ctx); err != nil { + return nil, err + } + return tq.sqlAll(ctx) +} + +// AllX is like All, but panics if an error occurs. +func (tq *TokenQuery) AllX(ctx context.Context) []*Token { + nodes, err := tq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Token IDs. +func (tq *TokenQuery) IDs(ctx context.Context) ([]sid.ID, error) { + var ids []sid.ID + if err := tq.Select(token.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (tq *TokenQuery) IDsX(ctx context.Context) []sid.ID { + ids, err := tq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (tq *TokenQuery) Count(ctx context.Context) (int, error) { + if err := tq.prepareQuery(ctx); err != nil { + return 0, err + } + return tq.sqlCount(ctx) +} + +// CountX is like Count, but panics if an error occurs. +func (tq *TokenQuery) CountX(ctx context.Context) int { + count, err := tq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (tq *TokenQuery) Exist(ctx context.Context) (bool, error) { + if err := tq.prepareQuery(ctx); err != nil { + return false, err + } + return tq.sqlExist(ctx) +} + +// ExistX is like Exist, but panics if an error occurs. +func (tq *TokenQuery) ExistX(ctx context.Context) bool { + exist, err := tq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the TokenQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (tq *TokenQuery) Clone() *TokenQuery { + if tq == nil { + return nil + } + return &TokenQuery{ + config: tq.config, + limit: tq.limit, + offset: tq.offset, + order: append([]OrderFunc{}, tq.order...), + predicates: append([]predicate.Token{}, tq.predicates...), + withAccount: tq.withAccount.Clone(), + // clone intermediate query. + sql: tq.sql.Clone(), + path: tq.path, + unique: tq.unique, + } +} + +// WithAccount tells the query-builder to eager-load the nodes that are connected to +// the "account" edge. The optional arguments are used to configure the query builder of the edge. +func (tq *TokenQuery) WithAccount(opts ...func(*AccountQuery)) *TokenQuery { + query := &AccountQuery{config: tq.config} + for _, opt := range opts { + opt(query) + } + tq.withAccount = query + return tq +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// Body string `json:"body,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Token.Query(). +// GroupBy(token.FieldBody). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +// +func (tq *TokenQuery) GroupBy(field string, fields ...string) *TokenGroupBy { + group := &TokenGroupBy{config: tq.config} + group.fields = append([]string{field}, fields...) + group.path = func(ctx context.Context) (prev *sql.Selector, err error) { + if err := tq.prepareQuery(ctx); err != nil { + return nil, err + } + return tq.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 { +// Body string `json:"body,omitempty"` +// } +// +// client.Token.Query(). +// Select(token.FieldBody). +// Scan(ctx, &v) +// +func (tq *TokenQuery) Select(fields ...string) *TokenSelect { + tq.fields = append(tq.fields, fields...) + return &TokenSelect{TokenQuery: tq} +} + +func (tq *TokenQuery) prepareQuery(ctx context.Context) error { + for _, f := range tq.fields { + if !token.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if tq.path != nil { + prev, err := tq.path(ctx) + if err != nil { + return err + } + tq.sql = prev + } + return nil +} + +func (tq *TokenQuery) sqlAll(ctx context.Context) ([]*Token, error) { + var ( + nodes = []*Token{} + withFKs = tq.withFKs + _spec = tq.querySpec() + loadedTypes = [1]bool{ + tq.withAccount != nil, + } + ) + if tq.withAccount != nil { + withFKs = true + } + if withFKs { + _spec.Node.Columns = append(_spec.Node.Columns, token.ForeignKeys...) + } + _spec.ScanValues = func(columns []string) ([]interface{}, error) { + node := &Token{config: tq.config} + nodes = append(nodes, node) + return node.scanValues(columns) + } + _spec.Assign = func(columns []string, values []interface{}) error { + if len(nodes) == 0 { + return fmt.Errorf("ent: Assign called without calling ScanValues") + } + node := nodes[len(nodes)-1] + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if err := sqlgraph.QueryNodes(ctx, tq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + + if query := tq.withAccount; query != nil { + ids := make([]sid.ID, 0, len(nodes)) + nodeids := make(map[sid.ID][]*Token) + for i := range nodes { + if nodes[i].account_token == nil { + continue + } + fk := *nodes[i].account_token + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + query.Where(account.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 "account_token" returned %v`, n.ID) + } + for i := range nodes { + nodes[i].Edges.Account = n + } + } + } + + return nodes, nil +} + +func (tq *TokenQuery) sqlCount(ctx context.Context) (int, error) { + _spec := tq.querySpec() + _spec.Node.Columns = tq.fields + if len(tq.fields) > 0 { + _spec.Unique = tq.unique != nil && *tq.unique + } + return sqlgraph.CountNodes(ctx, tq.driver, _spec) +} + +func (tq *TokenQuery) sqlExist(ctx context.Context) (bool, error) { + n, err := tq.sqlCount(ctx) + if err != nil { + return false, fmt.Errorf("ent: check existence: %w", err) + } + return n > 0, nil +} + +func (tq *TokenQuery) querySpec() *sqlgraph.QuerySpec { + _spec := &sqlgraph.QuerySpec{ + Node: &sqlgraph.NodeSpec{ + Table: token.Table, + Columns: token.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeOther, + Column: token.FieldID, + }, + }, + From: tq.sql, + Unique: true, + } + if unique := tq.unique; unique != nil { + _spec.Unique = *unique + } + if fields := tq.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, token.FieldID) + for i := range fields { + if fields[i] != token.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := tq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := tq.limit; limit != nil { + _spec.Limit = *limit + } + if offset := tq.offset; offset != nil { + _spec.Offset = *offset + } + if ps := tq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (tq *TokenQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(tq.driver.Dialect()) + t1 := builder.Table(token.Table) + columns := tq.fields + if len(columns) == 0 { + columns = token.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if tq.sql != nil { + selector = tq.sql + selector.Select(selector.Columns(columns...)...) + } + if tq.unique != nil && *tq.unique { + selector.Distinct() + } + for _, p := range tq.predicates { + p(selector) + } + for _, p := range tq.order { + p(selector) + } + if offset := tq.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 := tq.limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// TokenGroupBy is the group-by builder for Token entities. +type TokenGroupBy 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 (tgb *TokenGroupBy) Aggregate(fns ...AggregateFunc) *TokenGroupBy { + tgb.fns = append(tgb.fns, fns...) + return tgb +} + +// Scan applies the group-by query and scans the result into the given value. +func (tgb *TokenGroupBy) Scan(ctx context.Context, v interface{}) error { + query, err := tgb.path(ctx) + if err != nil { + return err + } + tgb.sql = query + return tgb.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (tgb *TokenGroupBy) ScanX(ctx context.Context, v interface{}) { + if err := tgb.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 (tgb *TokenGroupBy) Strings(ctx context.Context) ([]string, error) { + if len(tgb.fields) > 1 { + return nil, errors.New("ent: TokenGroupBy.Strings is not achievable when grouping more than 1 field") + } + var v []string + if err := tgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (tgb *TokenGroupBy) StringsX(ctx context.Context) []string { + v, err := tgb.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 (tgb *TokenGroupBy) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = tgb.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{token.Label} + default: + err = fmt.Errorf("ent: TokenGroupBy.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (tgb *TokenGroupBy) StringX(ctx context.Context) string { + v, err := tgb.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 (tgb *TokenGroupBy) Ints(ctx context.Context) ([]int, error) { + if len(tgb.fields) > 1 { + return nil, errors.New("ent: TokenGroupBy.Ints is not achievable when grouping more than 1 field") + } + var v []int + if err := tgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (tgb *TokenGroupBy) IntsX(ctx context.Context) []int { + v, err := tgb.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 (tgb *TokenGroupBy) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = tgb.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{token.Label} + default: + err = fmt.Errorf("ent: TokenGroupBy.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (tgb *TokenGroupBy) IntX(ctx context.Context) int { + v, err := tgb.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 (tgb *TokenGroupBy) Float64s(ctx context.Context) ([]float64, error) { + if len(tgb.fields) > 1 { + return nil, errors.New("ent: TokenGroupBy.Float64s is not achievable when grouping more than 1 field") + } + var v []float64 + if err := tgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (tgb *TokenGroupBy) Float64sX(ctx context.Context) []float64 { + v, err := tgb.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 (tgb *TokenGroupBy) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = tgb.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{token.Label} + default: + err = fmt.Errorf("ent: TokenGroupBy.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (tgb *TokenGroupBy) Float64X(ctx context.Context) float64 { + v, err := tgb.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 (tgb *TokenGroupBy) Bools(ctx context.Context) ([]bool, error) { + if len(tgb.fields) > 1 { + return nil, errors.New("ent: TokenGroupBy.Bools is not achievable when grouping more than 1 field") + } + var v []bool + if err := tgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (tgb *TokenGroupBy) BoolsX(ctx context.Context) []bool { + v, err := tgb.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 (tgb *TokenGroupBy) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = tgb.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{token.Label} + default: + err = fmt.Errorf("ent: TokenGroupBy.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (tgb *TokenGroupBy) BoolX(ctx context.Context) bool { + v, err := tgb.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (tgb *TokenGroupBy) sqlScan(ctx context.Context, v interface{}) error { + for _, f := range tgb.fields { + if !token.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + } + } + selector := tgb.sqlQuery() + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := tgb.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +func (tgb *TokenGroupBy) sqlQuery() *sql.Selector { + selector := tgb.sql.Select() + aggregation := make([]string, 0, len(tgb.fns)) + for _, fn := range tgb.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(tgb.fields)+len(tgb.fns)) + for _, f := range tgb.fields { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + return selector.GroupBy(selector.Columns(tgb.fields...)...) +} + +// TokenSelect is the builder for selecting fields of Token entities. +type TokenSelect struct { + *TokenQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector +} + +// Scan applies the selector query and scans the result into the given value. +func (ts *TokenSelect) Scan(ctx context.Context, v interface{}) error { + if err := ts.prepareQuery(ctx); err != nil { + return err + } + ts.sql = ts.TokenQuery.sqlQuery(ctx) + return ts.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (ts *TokenSelect) ScanX(ctx context.Context, v interface{}) { + if err := ts.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from a selector. It is only allowed when selecting one field. +func (ts *TokenSelect) Strings(ctx context.Context) ([]string, error) { + if len(ts.fields) > 1 { + return nil, errors.New("ent: TokenSelect.Strings is not achievable when selecting more than 1 field") + } + var v []string + if err := ts.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (ts *TokenSelect) StringsX(ctx context.Context) []string { + v, err := ts.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 (ts *TokenSelect) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = ts.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{token.Label} + default: + err = fmt.Errorf("ent: TokenSelect.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (ts *TokenSelect) StringX(ctx context.Context) string { + v, err := ts.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 (ts *TokenSelect) Ints(ctx context.Context) ([]int, error) { + if len(ts.fields) > 1 { + return nil, errors.New("ent: TokenSelect.Ints is not achievable when selecting more than 1 field") + } + var v []int + if err := ts.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (ts *TokenSelect) IntsX(ctx context.Context) []int { + v, err := ts.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 (ts *TokenSelect) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = ts.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{token.Label} + default: + err = fmt.Errorf("ent: TokenSelect.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (ts *TokenSelect) IntX(ctx context.Context) int { + v, err := ts.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 (ts *TokenSelect) Float64s(ctx context.Context) ([]float64, error) { + if len(ts.fields) > 1 { + return nil, errors.New("ent: TokenSelect.Float64s is not achievable when selecting more than 1 field") + } + var v []float64 + if err := ts.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (ts *TokenSelect) Float64sX(ctx context.Context) []float64 { + v, err := ts.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 (ts *TokenSelect) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = ts.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{token.Label} + default: + err = fmt.Errorf("ent: TokenSelect.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (ts *TokenSelect) Float64X(ctx context.Context) float64 { + v, err := ts.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 (ts *TokenSelect) Bools(ctx context.Context) ([]bool, error) { + if len(ts.fields) > 1 { + return nil, errors.New("ent: TokenSelect.Bools is not achievable when selecting more than 1 field") + } + var v []bool + if err := ts.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (ts *TokenSelect) BoolsX(ctx context.Context) []bool { + v, err := ts.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 (ts *TokenSelect) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = ts.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{token.Label} + default: + err = fmt.Errorf("ent: TokenSelect.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (ts *TokenSelect) BoolX(ctx context.Context) bool { + v, err := ts.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (ts *TokenSelect) sqlScan(ctx context.Context, v interface{}) error { + rows := &sql.Rows{} + query, args := ts.sql.Query() + if err := ts.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/entc/integration/customid/ent/token_update.go b/entc/integration/customid/ent/token_update.go new file mode 100644 index 000000000..cf4bba100 --- /dev/null +++ b/entc/integration/customid/ent/token_update.go @@ -0,0 +1,413 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/customid/ent/account" + "entgo.io/ent/entc/integration/customid/ent/predicate" + "entgo.io/ent/entc/integration/customid/ent/token" + "entgo.io/ent/entc/integration/customid/sid" + "entgo.io/ent/schema/field" +) + +// TokenUpdate is the builder for updating Token entities. +type TokenUpdate struct { + config + hooks []Hook + mutation *TokenMutation +} + +// Where appends a list predicates to the TokenUpdate builder. +func (tu *TokenUpdate) Where(ps ...predicate.Token) *TokenUpdate { + tu.mutation.Where(ps...) + return tu +} + +// SetBody sets the "body" field. +func (tu *TokenUpdate) SetBody(s string) *TokenUpdate { + tu.mutation.SetBody(s) + return tu +} + +// SetAccountID sets the "account" edge to the Account entity by ID. +func (tu *TokenUpdate) SetAccountID(id sid.ID) *TokenUpdate { + tu.mutation.SetAccountID(id) + return tu +} + +// SetAccount sets the "account" edge to the Account entity. +func (tu *TokenUpdate) SetAccount(a *Account) *TokenUpdate { + return tu.SetAccountID(a.ID) +} + +// Mutation returns the TokenMutation object of the builder. +func (tu *TokenUpdate) Mutation() *TokenMutation { + return tu.mutation +} + +// ClearAccount clears the "account" edge to the Account entity. +func (tu *TokenUpdate) ClearAccount() *TokenUpdate { + tu.mutation.ClearAccount() + return tu +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (tu *TokenUpdate) Save(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(tu.hooks) == 0 { + if err = tu.check(); err != nil { + return 0, err + } + affected, err = tu.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*TokenMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = tu.check(); err != nil { + return 0, err + } + tu.mutation = mutation + affected, err = tu.sqlSave(ctx) + mutation.done = true + return affected, err + }) + for i := len(tu.hooks) - 1; i >= 0; i-- { + if tu.hooks[i] == nil { + return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = tu.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, tu.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// SaveX is like Save, but panics if an error occurs. +func (tu *TokenUpdate) SaveX(ctx context.Context) int { + affected, err := tu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (tu *TokenUpdate) Exec(ctx context.Context) error { + _, err := tu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (tu *TokenUpdate) ExecX(ctx context.Context) { + if err := tu.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (tu *TokenUpdate) check() error { + if v, ok := tu.mutation.Body(); ok { + if err := token.BodyValidator(v); err != nil { + return &ValidationError{Name: "body", err: fmt.Errorf(`ent: validator failed for field "Token.body": %w`, err)} + } + } + if _, ok := tu.mutation.AccountID(); tu.mutation.AccountCleared() && !ok { + return errors.New(`ent: clearing a required unique edge "Token.account"`) + } + return nil +} + +func (tu *TokenUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: token.Table, + Columns: token.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeOther, + Column: token.FieldID, + }, + }, + } + if ps := tu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := tu.mutation.Body(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: token.FieldBody, + }) + } + if tu.mutation.AccountCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: token.AccountTable, + Columns: []string{token.AccountColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeOther, + Column: account.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tu.mutation.AccountIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: token.AccountTable, + Columns: []string{token.AccountColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeOther, + Column: account.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, tu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{token.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return 0, err + } + return n, nil +} + +// TokenUpdateOne is the builder for updating a single Token entity. +type TokenUpdateOne struct { + config + fields []string + hooks []Hook + mutation *TokenMutation +} + +// SetBody sets the "body" field. +func (tuo *TokenUpdateOne) SetBody(s string) *TokenUpdateOne { + tuo.mutation.SetBody(s) + return tuo +} + +// SetAccountID sets the "account" edge to the Account entity by ID. +func (tuo *TokenUpdateOne) SetAccountID(id sid.ID) *TokenUpdateOne { + tuo.mutation.SetAccountID(id) + return tuo +} + +// SetAccount sets the "account" edge to the Account entity. +func (tuo *TokenUpdateOne) SetAccount(a *Account) *TokenUpdateOne { + return tuo.SetAccountID(a.ID) +} + +// Mutation returns the TokenMutation object of the builder. +func (tuo *TokenUpdateOne) Mutation() *TokenMutation { + return tuo.mutation +} + +// ClearAccount clears the "account" edge to the Account entity. +func (tuo *TokenUpdateOne) ClearAccount() *TokenUpdateOne { + tuo.mutation.ClearAccount() + return tuo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (tuo *TokenUpdateOne) Select(field string, fields ...string) *TokenUpdateOne { + tuo.fields = append([]string{field}, fields...) + return tuo +} + +// Save executes the query and returns the updated Token entity. +func (tuo *TokenUpdateOne) Save(ctx context.Context) (*Token, error) { + var ( + err error + node *Token + ) + if len(tuo.hooks) == 0 { + if err = tuo.check(); err != nil { + return nil, err + } + node, err = tuo.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*TokenMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = tuo.check(); err != nil { + return nil, err + } + tuo.mutation = mutation + node, err = tuo.sqlSave(ctx) + mutation.done = true + return node, err + }) + for i := len(tuo.hooks) - 1; i >= 0; i-- { + if tuo.hooks[i] == nil { + return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = tuo.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, tuo.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX is like Save, but panics if an error occurs. +func (tuo *TokenUpdateOne) SaveX(ctx context.Context) *Token { + node, err := tuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (tuo *TokenUpdateOne) Exec(ctx context.Context) error { + _, err := tuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (tuo *TokenUpdateOne) ExecX(ctx context.Context) { + if err := tuo.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (tuo *TokenUpdateOne) check() error { + if v, ok := tuo.mutation.Body(); ok { + if err := token.BodyValidator(v); err != nil { + return &ValidationError{Name: "body", err: fmt.Errorf(`ent: validator failed for field "Token.body": %w`, err)} + } + } + if _, ok := tuo.mutation.AccountID(); tuo.mutation.AccountCleared() && !ok { + return errors.New(`ent: clearing a required unique edge "Token.account"`) + } + return nil +} + +func (tuo *TokenUpdateOne) sqlSave(ctx context.Context) (_node *Token, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: token.Table, + Columns: token.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeOther, + Column: token.FieldID, + }, + }, + } + id, ok := tuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Token.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := tuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, token.FieldID) + for _, f := range fields { + if !token.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != token.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := tuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := tuo.mutation.Body(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: token.FieldBody, + }) + } + if tuo.mutation.AccountCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: token.AccountTable, + Columns: []string{token.AccountColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeOther, + Column: account.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tuo.mutation.AccountIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: token.AccountTable, + Columns: []string{token.AccountColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeOther, + Column: account.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &Token{config: tuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, tuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{token.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + return _node, nil +} diff --git a/entc/integration/customid/ent/tx.go b/entc/integration/customid/ent/tx.go index 8be130ec2..f14d6c7f6 100644 --- a/entc/integration/customid/ent/tx.go +++ b/entc/integration/customid/ent/tx.go @@ -16,6 +16,8 @@ import ( // Tx is a transactional client that is created by calling Client.Tx(). type Tx struct { config + // Account is the client for interacting with the Account builders. + Account *AccountClient // Blob is the client for interacting with the Blob builders. Blob *BlobClient // Car is the client for interacting with the Car builders. @@ -36,6 +38,8 @@ type Tx struct { Pet *PetClient // Session is the client for interacting with the Session builders. Session *SessionClient + // Token is the client for interacting with the Token builders. + Token *TokenClient // User is the client for interacting with the User builders. User *UserClient @@ -173,6 +177,7 @@ func (tx *Tx) Client() *Client { } func (tx *Tx) init() { + tx.Account = NewAccountClient(tx.config) tx.Blob = NewBlobClient(tx.config) tx.Car = NewCarClient(tx.config) tx.Device = NewDeviceClient(tx.config) @@ -183,6 +188,7 @@ func (tx *Tx) init() { tx.Other = NewOtherClient(tx.config) tx.Pet = NewPetClient(tx.config) tx.Session = NewSessionClient(tx.config) + tx.Token = NewTokenClient(tx.config) tx.User = NewUserClient(tx.config) } @@ -193,7 +199,7 @@ func (tx *Tx) init() { // of them in order to commit or rollback the transaction. // // If a closed transaction is embedded in one of the generated entities, and the entity -// applies a query, for example: Blob.QueryXXX(), the query will be executed +// applies a query, for example: Account.QueryXXX(), the query will be executed // through the driver which created this transaction. // // Note that txDriver is not goroutine safe. diff --git a/entc/integration/customid/sid/sid.go b/entc/integration/customid/sid/sid.go index b24c885b5..8352dff7b 100644 --- a/entc/integration/customid/sid/sid.go +++ b/entc/integration/customid/sid/sid.go @@ -36,7 +36,7 @@ func (i *ID) Scan(src interface{}) error { *i = ID(fmt.Sprint(v)) return nil } - return errors.New("not a valid base62") + return errors.New("not a valid ID") } func New() ID { @@ -47,7 +47,7 @@ func NewLength(l int) ID { var out string for len(out) < l { result, _ := rand.Int(rand.Reader, big.NewInt(100)) - out += fmt.Sprint(result) + out += fmt.Sprint(result.Uint64() + 1) } return ID(out[:l]) }