From 00eb91d72a9f0ad4521a13cc7b17b9b2f1e66c31 Mon Sep 17 00:00:00 2001 From: Jannik C Date: Thu, 28 Apr 2022 13:13:47 +0200 Subject: [PATCH 1/2] dialect/sql: support string based pk for mysql56 indexes (prevent error 1071) --- dialect/sql/schema/mysql.go | 2 +- entc/integration/customid/ent/client.go | 157 ++++-- entc/integration/customid/ent/config.go | 27 +- entc/integration/customid/ent/ent.go | 28 +- entc/integration/customid/ent/entql.go | 65 ++- entc/integration/customid/ent/hook/hook.go | 13 + .../customid/ent/migrate/schema.go | 11 + entc/integration/customid/ent/mutation.go | 282 +++++++++- .../customid/ent/predicate/predicate.go | 3 + entc/integration/customid/ent/revision.go | 91 ++++ .../customid/ent/revision/revision.go | 31 ++ .../customid/ent/revision/where.go | 127 +++++ .../customid/ent/revision_create.go | 468 ++++++++++++++++ .../customid/ent/revision_delete.go | 115 ++++ .../customid/ent/revision_query.go | 508 ++++++++++++++++++ .../customid/ent/revision_update.go | 243 +++++++++ .../customid/ent/schema/revision.go | 21 + entc/integration/customid/ent/tx.go | 3 + 18 files changed, 2119 insertions(+), 76 deletions(-) create mode 100644 entc/integration/customid/ent/revision.go create mode 100644 entc/integration/customid/ent/revision/revision.go create mode 100644 entc/integration/customid/ent/revision/where.go create mode 100644 entc/integration/customid/ent/revision_create.go create mode 100644 entc/integration/customid/ent/revision_delete.go create mode 100644 entc/integration/customid/ent/revision_query.go create mode 100644 entc/integration/customid/ent/revision_update.go create mode 100644 entc/integration/customid/ent/schema/revision.go diff --git a/dialect/sql/schema/mysql.go b/dialect/sql/schema/mysql.go index f7a3f8a56d..f65236b440 100644 --- a/dialect/sql/schema/mysql.go +++ b/dialect/sql/schema/mysql.go @@ -736,7 +736,7 @@ func (d *MySQL) defaultSize(c *Column) int64 { case compareVersions(version, checked) != -1: // Column is non-unique, or not part of any index (reaching // the error 1071). - case !c.Unique && len(c.indexes) == 0: + case !c.Unique && len(c.indexes) == 0 && !c.PrimaryKey(): default: size = 191 } diff --git a/entc/integration/customid/ent/client.go b/entc/integration/customid/ent/client.go index 12b94a5348..d5c548e30c 100644 --- a/entc/integration/customid/ent/client.go +++ b/entc/integration/customid/ent/client.go @@ -26,6 +26,7 @@ import ( "entgo.io/ent/entc/integration/customid/ent/note" "entgo.io/ent/entc/integration/customid/ent/other" "entgo.io/ent/entc/integration/customid/ent/pet" + "entgo.io/ent/entc/integration/customid/ent/revision" "entgo.io/ent/entc/integration/customid/ent/session" "entgo.io/ent/entc/integration/customid/ent/token" "entgo.io/ent/entc/integration/customid/ent/user" @@ -60,6 +61,8 @@ type Client struct { Other *OtherClient // Pet is the client for interacting with the Pet builders. Pet *PetClient + // Revision is the client for interacting with the Revision builders. + Revision *RevisionClient // Session is the client for interacting with the Session builders. Session *SessionClient // Token is the client for interacting with the Token builders. @@ -89,6 +92,7 @@ func (c *Client) init() { c.Note = NewNoteClient(c.config) c.Other = NewOtherClient(c.config) c.Pet = NewPetClient(c.config) + c.Revision = NewRevisionClient(c.config) c.Session = NewSessionClient(c.config) c.Token = NewTokenClient(c.config) c.User = NewUserClient(c.config) @@ -123,21 +127,22 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { cfg := c.config cfg.driver = tx return &Tx{ - ctx: ctx, - config: cfg, - Account: NewAccountClient(cfg), - Blob: NewBlobClient(cfg), - Car: NewCarClient(cfg), - Device: NewDeviceClient(cfg), - Doc: NewDocClient(cfg), - Group: NewGroupClient(cfg), - MixinID: NewMixinIDClient(cfg), - Note: NewNoteClient(cfg), - Other: NewOtherClient(cfg), - Pet: NewPetClient(cfg), - Session: NewSessionClient(cfg), - Token: NewTokenClient(cfg), - User: NewUserClient(cfg), + ctx: ctx, + config: cfg, + Account: NewAccountClient(cfg), + Blob: NewBlobClient(cfg), + Car: NewCarClient(cfg), + Device: NewDeviceClient(cfg), + Doc: NewDocClient(cfg), + Group: NewGroupClient(cfg), + MixinID: NewMixinIDClient(cfg), + Note: NewNoteClient(cfg), + Other: NewOtherClient(cfg), + Pet: NewPetClient(cfg), + Revision: NewRevisionClient(cfg), + Session: NewSessionClient(cfg), + Token: NewTokenClient(cfg), + User: NewUserClient(cfg), }, nil } @@ -155,21 +160,22 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) cfg := c.config cfg.driver = &txDriver{tx: tx, drv: c.driver} return &Tx{ - ctx: ctx, - config: cfg, - Account: NewAccountClient(cfg), - Blob: NewBlobClient(cfg), - Car: NewCarClient(cfg), - Device: NewDeviceClient(cfg), - Doc: NewDocClient(cfg), - Group: NewGroupClient(cfg), - MixinID: NewMixinIDClient(cfg), - Note: NewNoteClient(cfg), - Other: NewOtherClient(cfg), - Pet: NewPetClient(cfg), - Session: NewSessionClient(cfg), - Token: NewTokenClient(cfg), - User: NewUserClient(cfg), + ctx: ctx, + config: cfg, + Account: NewAccountClient(cfg), + Blob: NewBlobClient(cfg), + Car: NewCarClient(cfg), + Device: NewDeviceClient(cfg), + Doc: NewDocClient(cfg), + Group: NewGroupClient(cfg), + MixinID: NewMixinIDClient(cfg), + Note: NewNoteClient(cfg), + Other: NewOtherClient(cfg), + Pet: NewPetClient(cfg), + Revision: NewRevisionClient(cfg), + Session: NewSessionClient(cfg), + Token: NewTokenClient(cfg), + User: NewUserClient(cfg), }, nil } @@ -209,6 +215,7 @@ func (c *Client) Use(hooks ...Hook) { c.Note.Use(hooks...) c.Other.Use(hooks...) c.Pet.Use(hooks...) + c.Revision.Use(hooks...) c.Session.Use(hooks...) c.Token.Use(hooks...) c.User.Use(hooks...) @@ -1354,6 +1361,96 @@ func (c *PetClient) Hooks() []Hook { return c.hooks.Pet } +// RevisionClient is a client for the Revision schema. +type RevisionClient struct { + config +} + +// NewRevisionClient returns a client for the Revision from the given config. +func NewRevisionClient(c config) *RevisionClient { + return &RevisionClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `revision.Hooks(f(g(h())))`. +func (c *RevisionClient) Use(hooks ...Hook) { + c.hooks.Revision = append(c.hooks.Revision, hooks...) +} + +// Create returns a create builder for Revision. +func (c *RevisionClient) Create() *RevisionCreate { + mutation := newRevisionMutation(c.config, OpCreate) + return &RevisionCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Revision entities. +func (c *RevisionClient) CreateBulk(builders ...*RevisionCreate) *RevisionCreateBulk { + return &RevisionCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Revision. +func (c *RevisionClient) Update() *RevisionUpdate { + mutation := newRevisionMutation(c.config, OpUpdate) + return &RevisionUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *RevisionClient) UpdateOne(r *Revision) *RevisionUpdateOne { + mutation := newRevisionMutation(c.config, OpUpdateOne, withRevision(r)) + return &RevisionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *RevisionClient) UpdateOneID(id string) *RevisionUpdateOne { + mutation := newRevisionMutation(c.config, OpUpdateOne, withRevisionID(id)) + return &RevisionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Revision. +func (c *RevisionClient) Delete() *RevisionDelete { + mutation := newRevisionMutation(c.config, OpDelete) + return &RevisionDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a delete builder for the given entity. +func (c *RevisionClient) DeleteOne(r *Revision) *RevisionDeleteOne { + return c.DeleteOneID(r.ID) +} + +// DeleteOneID returns a delete builder for the given id. +func (c *RevisionClient) DeleteOneID(id string) *RevisionDeleteOne { + builder := c.Delete().Where(revision.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &RevisionDeleteOne{builder} +} + +// Query returns a query builder for Revision. +func (c *RevisionClient) Query() *RevisionQuery { + return &RevisionQuery{ + config: c.config, + } +} + +// Get returns a Revision entity by its id. +func (c *RevisionClient) Get(ctx context.Context, id string) (*Revision, error) { + return c.Query().Where(revision.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *RevisionClient) GetX(ctx context.Context, id string) *Revision { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *RevisionClient) Hooks() []Hook { + return c.hooks.Revision +} + // SessionClient is a client for the Session schema. type SessionClient struct { config diff --git a/entc/integration/customid/ent/config.go b/entc/integration/customid/ent/config.go index 6be4f7b6bc..a311b3ad91 100644 --- a/entc/integration/customid/ent/config.go +++ b/entc/integration/customid/ent/config.go @@ -28,19 +28,20 @@ type config struct { // hooks per client, for fast access. type hooks struct { - Account []ent.Hook - Blob []ent.Hook - Car []ent.Hook - Device []ent.Hook - Doc []ent.Hook - Group []ent.Hook - MixinID []ent.Hook - Note []ent.Hook - Other []ent.Hook - Pet []ent.Hook - Session []ent.Hook - Token []ent.Hook - User []ent.Hook + Account []ent.Hook + Blob []ent.Hook + Car []ent.Hook + Device []ent.Hook + Doc []ent.Hook + Group []ent.Hook + MixinID []ent.Hook + Note []ent.Hook + Other []ent.Hook + Pet []ent.Hook + Revision []ent.Hook + Session []ent.Hook + Token []ent.Hook + User []ent.Hook } // Options applies the options on the config object. diff --git a/entc/integration/customid/ent/ent.go b/entc/integration/customid/ent/ent.go index b9082e1630..bb68095bc6 100644 --- a/entc/integration/customid/ent/ent.go +++ b/entc/integration/customid/ent/ent.go @@ -24,6 +24,7 @@ import ( "entgo.io/ent/entc/integration/customid/ent/note" "entgo.io/ent/entc/integration/customid/ent/other" "entgo.io/ent/entc/integration/customid/ent/pet" + "entgo.io/ent/entc/integration/customid/ent/revision" "entgo.io/ent/entc/integration/customid/ent/session" "entgo.io/ent/entc/integration/customid/ent/token" "entgo.io/ent/entc/integration/customid/ent/user" @@ -47,19 +48,20 @@ 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, - doc.Table: doc.ValidColumn, - group.Table: group.ValidColumn, - mixinid.Table: mixinid.ValidColumn, - note.Table: note.ValidColumn, - other.Table: other.ValidColumn, - pet.Table: pet.ValidColumn, - session.Table: session.ValidColumn, - token.Table: token.ValidColumn, - user.Table: user.ValidColumn, + account.Table: account.ValidColumn, + blob.Table: blob.ValidColumn, + car.Table: car.ValidColumn, + device.Table: device.ValidColumn, + doc.Table: doc.ValidColumn, + group.Table: group.ValidColumn, + mixinid.Table: mixinid.ValidColumn, + note.Table: note.ValidColumn, + other.Table: other.ValidColumn, + pet.Table: pet.ValidColumn, + revision.Table: revision.ValidColumn, + session.Table: session.ValidColumn, + token.Table: token.ValidColumn, + user.Table: user.ValidColumn, } check, ok := checks[table] if !ok { diff --git a/entc/integration/customid/ent/entql.go b/entc/integration/customid/ent/entql.go index f3180a3833..2d9a408971 100644 --- a/entc/integration/customid/ent/entql.go +++ b/entc/integration/customid/ent/entql.go @@ -18,6 +18,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/predicate" + "entgo.io/ent/entc/integration/customid/ent/revision" "entgo.io/ent/entc/integration/customid/ent/session" "entgo.io/ent/entc/integration/customid/ent/token" "entgo.io/ent/entc/integration/customid/ent/user" @@ -30,7 +31,7 @@ import ( // schemaGraph holds a representation of ent/schema at runtime. var schemaGraph = func() *sqlgraph.Schema { - graph := &sqlgraph.Schema{Nodes: make([]*sqlgraph.Node, 13)} + graph := &sqlgraph.Schema{Nodes: make([]*sqlgraph.Node, 14)} graph.Nodes[0] = &sqlgraph.Node{ NodeSpec: sqlgraph.NodeSpec{ Table: account.Table, @@ -168,6 +169,18 @@ var schemaGraph = func() *sqlgraph.Schema { Fields: map[string]*sqlgraph.FieldSpec{}, } graph.Nodes[10] = &sqlgraph.Node{ + NodeSpec: sqlgraph.NodeSpec{ + Table: revision.Table, + Columns: revision.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeString, + Column: revision.FieldID, + }, + }, + Type: "Revision", + Fields: map[string]*sqlgraph.FieldSpec{}, + } + graph.Nodes[11] = &sqlgraph.Node{ NodeSpec: sqlgraph.NodeSpec{ Table: session.Table, Columns: session.Columns, @@ -179,7 +192,7 @@ var schemaGraph = func() *sqlgraph.Schema { Type: "Session", Fields: map[string]*sqlgraph.FieldSpec{}, } - graph.Nodes[11] = &sqlgraph.Node{ + graph.Nodes[12] = &sqlgraph.Node{ NodeSpec: sqlgraph.NodeSpec{ Table: token.Table, Columns: token.Columns, @@ -193,7 +206,7 @@ var schemaGraph = func() *sqlgraph.Schema { token.FieldBody: {Type: field.TypeString, Column: token.FieldBody}, }, } - graph.Nodes[12] = &sqlgraph.Node{ + graph.Nodes[13] = &sqlgraph.Node{ NodeSpec: sqlgraph.NodeSpec{ Table: user.Table, Columns: user.Columns, @@ -1126,6 +1139,46 @@ func (f *PetFilter) WhereHasBestFriendWith(preds ...predicate.Pet) { }))) } +// addPredicate implements the predicateAdder interface. +func (rq *RevisionQuery) addPredicate(pred func(s *sql.Selector)) { + rq.predicates = append(rq.predicates, pred) +} + +// Filter returns a Filter implementation to apply filters on the RevisionQuery builder. +func (rq *RevisionQuery) Filter() *RevisionFilter { + return &RevisionFilter{rq.config, rq} +} + +// addPredicate implements the predicateAdder interface. +func (m *RevisionMutation) addPredicate(pred func(s *sql.Selector)) { + m.predicates = append(m.predicates, pred) +} + +// Filter returns an entql.Where implementation to apply filters on the RevisionMutation builder. +func (m *RevisionMutation) Filter() *RevisionFilter { + return &RevisionFilter{m.config, m} +} + +// RevisionFilter provides a generic filtering capability at runtime for RevisionQuery. +type RevisionFilter struct { + config + predicateAdder +} + +// Where applies the entql predicate on the query filter. +func (f *RevisionFilter) Where(p entql.P) { + f.addPredicate(func(s *sql.Selector) { + if err := schemaGraph.EvalP(schemaGraph.Nodes[10].Type, p, s); err != nil { + s.AddError(err) + } + }) +} + +// WhereID applies the entql string predicate on the id field. +func (f *RevisionFilter) WhereID(p entql.StringP) { + f.Where(p.Field(revision.FieldID)) +} + // addPredicate implements the predicateAdder interface. func (sq *SessionQuery) addPredicate(pred func(s *sql.Selector)) { sq.predicates = append(sq.predicates, pred) @@ -1155,7 +1208,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[10].Type, p, s); err != nil { + if err := schemaGraph.EvalP(schemaGraph.Nodes[11].Type, p, s); err != nil { s.AddError(err) } }) @@ -1209,7 +1262,7 @@ type TokenFilter struct { // 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 { + if err := schemaGraph.EvalP(schemaGraph.Nodes[12].Type, p, s); err != nil { s.AddError(err) } }) @@ -1268,7 +1321,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[12].Type, p, s); err != nil { + if err := schemaGraph.EvalP(schemaGraph.Nodes[13].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 aef0d2ba2a..5f9c287703 100644 --- a/entc/integration/customid/ent/hook/hook.go +++ b/entc/integration/customid/ent/hook/hook.go @@ -143,6 +143,19 @@ func (f PetFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) return f(ctx, mv) } +// The RevisionFunc type is an adapter to allow the use of ordinary +// function as Revision mutator. +type RevisionFunc func(context.Context, *ent.RevisionMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f RevisionFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + mv, ok := m.(*ent.RevisionMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.RevisionMutation", m) + } + return f(ctx, mv) +} + // The SessionFunc type is an adapter to allow the use of ordinary // function as Session mutator. type SessionFunc func(context.Context, *ent.SessionMutation) (ent.Value, error) diff --git a/entc/integration/customid/ent/migrate/schema.go b/entc/integration/customid/ent/migrate/schema.go index 8f2de6e6ca..22638c5436 100644 --- a/entc/integration/customid/ent/migrate/schema.go +++ b/entc/integration/customid/ent/migrate/schema.go @@ -205,6 +205,16 @@ var ( }, }, } + // RevisionsColumns holds the columns for the "revisions" table. + RevisionsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString}, + } + // RevisionsTable holds the schema information for the "revisions" table. + RevisionsTable = &schema.Table{ + Name: "revisions", + Columns: RevisionsColumns, + PrimaryKey: []*schema.Column{RevisionsColumns[0]}, + } // SessionsColumns holds the columns for the "sessions" table. SessionsColumns = []*schema.Column{ {Name: "id", Type: field.TypeBytes, Size: 64}, @@ -350,6 +360,7 @@ var ( NotesTable, OthersTable, PetsTable, + RevisionsTable, SessionsTable, TokensTable, UsersTable, diff --git a/entc/integration/customid/ent/mutation.go b/entc/integration/customid/ent/mutation.go index fb54126565..26ef7bc4a9 100644 --- a/entc/integration/customid/ent/mutation.go +++ b/entc/integration/customid/ent/mutation.go @@ -41,19 +41,20 @@ const ( OpUpdateOne = ent.OpUpdateOne // Node types. - TypeAccount = "Account" - TypeBlob = "Blob" - TypeCar = "Car" - TypeDevice = "Device" - TypeDoc = "Doc" - TypeGroup = "Group" - TypeMixinID = "MixinID" - TypeNote = "Note" - TypeOther = "Other" - TypePet = "Pet" - TypeSession = "Session" - TypeToken = "Token" - TypeUser = "User" + TypeAccount = "Account" + TypeBlob = "Blob" + TypeCar = "Car" + TypeDevice = "Device" + TypeDoc = "Doc" + TypeGroup = "Group" + TypeMixinID = "MixinID" + TypeNote = "Note" + TypeOther = "Other" + TypePet = "Pet" + TypeRevision = "Revision" + TypeSession = "Session" + TypeToken = "Token" + TypeUser = "User" ) // AccountMutation represents an operation that mutates the Account nodes in the graph. @@ -4543,6 +4544,261 @@ func (m *PetMutation) ResetEdge(name string) error { return fmt.Errorf("unknown Pet edge %s", name) } +// RevisionMutation represents an operation that mutates the Revision nodes in the graph. +type RevisionMutation struct { + config + op Op + typ string + id *string + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*Revision, error) + predicates []predicate.Revision +} + +var _ ent.Mutation = (*RevisionMutation)(nil) + +// revisionOption allows management of the mutation configuration using functional options. +type revisionOption func(*RevisionMutation) + +// newRevisionMutation creates new mutation for the Revision entity. +func newRevisionMutation(c config, op Op, opts ...revisionOption) *RevisionMutation { + m := &RevisionMutation{ + config: c, + op: op, + typ: TypeRevision, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withRevisionID sets the ID field of the mutation. +func withRevisionID(id string) revisionOption { + return func(m *RevisionMutation) { + var ( + err error + once sync.Once + value *Revision + ) + m.oldValue = func(ctx context.Context) (*Revision, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Revision.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withRevision sets the old Revision of the mutation. +func withRevision(node *Revision) revisionOption { + return func(m *RevisionMutation) { + m.oldValue = func(context.Context) (*Revision, 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 RevisionMutation) 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 RevisionMutation) 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 Revision entities. +func (m *RevisionMutation) SetID(id string) { + 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 *RevisionMutation) ID() (id string, 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 *RevisionMutation) IDs(ctx context.Context) ([]string, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []string{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().Revision.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// Where appends a list predicates to the RevisionMutation builder. +func (m *RevisionMutation) Where(ps ...predicate.Revision) { + m.predicates = append(m.predicates, ps...) +} + +// Op returns the operation name. +func (m *RevisionMutation) Op() Op { + return m.op +} + +// Type returns the node type of this mutation (Revision). +func (m *RevisionMutation) 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 *RevisionMutation) Fields() []string { + fields := make([]string, 0, 0) + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *RevisionMutation) Field(name string) (ent.Value, bool) { + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *RevisionMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + return nil, fmt.Errorf("unknown Revision 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 *RevisionMutation) SetField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown Revision field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *RevisionMutation) 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 *RevisionMutation) 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 *RevisionMutation) AddField(name string, value ent.Value) error { + return fmt.Errorf("unknown Revision numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *RevisionMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *RevisionMutation) 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 *RevisionMutation) ClearField(name string) error { + return fmt.Errorf("unknown Revision 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 *RevisionMutation) ResetField(name string) error { + return fmt.Errorf("unknown Revision field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *RevisionMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *RevisionMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *RevisionMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *RevisionMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *RevisionMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *RevisionMutation) EdgeCleared(name string) bool { + 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 *RevisionMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown Revision 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 *RevisionMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown Revision edge %s", name) +} + // SessionMutation represents an operation that mutates the Session nodes in the graph. type SessionMutation struct { config diff --git a/entc/integration/customid/ent/predicate/predicate.go b/entc/integration/customid/ent/predicate/predicate.go index 69e14e5b4a..751e2520c5 100644 --- a/entc/integration/customid/ent/predicate/predicate.go +++ b/entc/integration/customid/ent/predicate/predicate.go @@ -40,6 +40,9 @@ type Other func(*sql.Selector) // Pet is the predicate function for pet builders. type Pet func(*sql.Selector) +// Revision is the predicate function for revision builders. +type Revision func(*sql.Selector) + // Session is the predicate function for session builders. type Session func(*sql.Selector) diff --git a/entc/integration/customid/ent/revision.go b/entc/integration/customid/ent/revision.go new file mode 100644 index 0000000000..c189a71199 --- /dev/null +++ b/entc/integration/customid/ent/revision.go @@ -0,0 +1,91 @@ +// 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/revision" +) + +// Revision is the model entity for the Revision schema. +type Revision struct { + config + // ID of the ent. + ID string `json:"id,omitempty"` +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Revision) scanValues(columns []string) ([]interface{}, error) { + values := make([]interface{}, len(columns)) + for i := range columns { + switch columns[i] { + case revision.FieldID: + values[i] = new(sql.NullString) + default: + return nil, fmt.Errorf("unexpected column %q for type Revision", columns[i]) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the Revision fields. +func (r *Revision) 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 revision.FieldID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value.Valid { + r.ID = value.String + } + } + } + return nil +} + +// Update returns a builder for updating this Revision. +// Note that you need to call Revision.Unwrap() before calling this method if this Revision +// was returned from a transaction, and the transaction was committed or rolled back. +func (r *Revision) Update() *RevisionUpdateOne { + return (&RevisionClient{config: r.config}).UpdateOne(r) +} + +// Unwrap unwraps the Revision 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 (r *Revision) Unwrap() *Revision { + tx, ok := r.config.driver.(*txDriver) + if !ok { + panic("ent: Revision is not a transactional entity") + } + r.config.driver = tx.drv + return r +} + +// String implements the fmt.Stringer. +func (r *Revision) String() string { + var builder strings.Builder + builder.WriteString("Revision(") + builder.WriteString(fmt.Sprintf("id=%v", r.ID)) + builder.WriteByte(')') + return builder.String() +} + +// Revisions is a parsable slice of Revision. +type Revisions []*Revision + +func (r Revisions) config(cfg config) { + for _i := range r { + r[_i].config = cfg + } +} diff --git a/entc/integration/customid/ent/revision/revision.go b/entc/integration/customid/ent/revision/revision.go new file mode 100644 index 0000000000..56b8764a68 --- /dev/null +++ b/entc/integration/customid/ent/revision/revision.go @@ -0,0 +1,31 @@ +// 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 revision + +const ( + // Label holds the string label denoting the revision type in the database. + Label = "revision" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // Table holds the table name of the revision in the database. + Table = "revisions" +) + +// Columns holds all SQL columns for revision fields. +var Columns = []string{ + FieldID, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} diff --git a/entc/integration/customid/ent/revision/where.go b/entc/integration/customid/ent/revision/where.go new file mode 100644 index 0000000000..eb300a66c9 --- /dev/null +++ b/entc/integration/customid/ent/revision/where.go @@ -0,0 +1,127 @@ +// 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 revision + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/entc/integration/customid/ent/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.Revision { + return predicate.Revision(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.Revision { + return predicate.Revision(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.Revision { + return predicate.Revision(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldID), id)) + }) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.Revision { + return predicate.Revision(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 ...string) predicate.Revision { + return predicate.Revision(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 string) predicate.Revision { + return predicate.Revision(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldID), id)) + }) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.Revision { + return predicate.Revision(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldID), id)) + }) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.Revision { + return predicate.Revision(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldID), id)) + }) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.Revision { + return predicate.Revision(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldID), id)) + }) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.Revision) predicate.Revision { + return predicate.Revision(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.Revision) predicate.Revision { + return predicate.Revision(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.Revision) predicate.Revision { + return predicate.Revision(func(s *sql.Selector) { + p(s.Not()) + }) +} diff --git a/entc/integration/customid/ent/revision_create.go b/entc/integration/customid/ent/revision_create.go new file mode 100644 index 0000000000..b1d012734a --- /dev/null +++ b/entc/integration/customid/ent/revision_create.go @@ -0,0 +1,468 @@ +// 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/revision" + "entgo.io/ent/schema/field" +) + +// RevisionCreate is the builder for creating a Revision entity. +type RevisionCreate struct { + config + mutation *RevisionMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetID sets the "id" field. +func (rc *RevisionCreate) SetID(s string) *RevisionCreate { + rc.mutation.SetID(s) + return rc +} + +// Mutation returns the RevisionMutation object of the builder. +func (rc *RevisionCreate) Mutation() *RevisionMutation { + return rc.mutation +} + +// Save creates the Revision in the database. +func (rc *RevisionCreate) Save(ctx context.Context) (*Revision, error) { + var ( + err error + node *Revision + ) + if len(rc.hooks) == 0 { + if err = rc.check(); err != nil { + return nil, err + } + node, err = rc.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*RevisionMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = rc.check(); err != nil { + return nil, err + } + rc.mutation = mutation + if node, err = rc.sqlSave(ctx); err != nil { + return nil, err + } + mutation.id = &node.ID + mutation.done = true + return node, err + }) + for i := len(rc.hooks) - 1; i >= 0; i-- { + if rc.hooks[i] == nil { + return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = rc.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, rc.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX calls Save and panics if Save returns an error. +func (rc *RevisionCreate) SaveX(ctx context.Context) *Revision { + v, err := rc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (rc *RevisionCreate) Exec(ctx context.Context) error { + _, err := rc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (rc *RevisionCreate) ExecX(ctx context.Context) { + if err := rc.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (rc *RevisionCreate) check() error { + return nil +} + +func (rc *RevisionCreate) sqlSave(ctx context.Context) (*Revision, error) { + _node, _spec := rc.createSpec() + if err := sqlgraph.CreateNode(ctx, rc.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.(string); ok { + _node.ID = id + } else { + return nil, fmt.Errorf("unexpected Revision.ID type: %T", _spec.ID.Value) + } + } + return _node, nil +} + +func (rc *RevisionCreate) createSpec() (*Revision, *sqlgraph.CreateSpec) { + var ( + _node = &Revision{config: rc.config} + _spec = &sqlgraph.CreateSpec{ + Table: revision.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeString, + Column: revision.FieldID, + }, + } + ) + _spec.OnConflict = rc.conflict + if id, ok := rc.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = id + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.Revision.Create(). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// Exec(ctx) +// +func (rc *RevisionCreate) OnConflict(opts ...sql.ConflictOption) *RevisionUpsertOne { + rc.conflict = opts + return &RevisionUpsertOne{ + create: rc, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.Revision.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +// +func (rc *RevisionCreate) OnConflictColumns(columns ...string) *RevisionUpsertOne { + rc.conflict = append(rc.conflict, sql.ConflictColumns(columns...)) + return &RevisionUpsertOne{ + create: rc, + } +} + +type ( + // RevisionUpsertOne is the builder for "upsert"-ing + // one Revision node. + RevisionUpsertOne struct { + create *RevisionCreate + } + + // RevisionUpsert is the "OnConflict" setter. + RevisionUpsert struct { + *sql.UpdateSet + } +) + +// 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.Revision.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(revision.FieldID) +// }), +// ). +// Exec(ctx) +// +func (u *RevisionUpsertOne) UpdateNewValues() *RevisionUpsertOne { + 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(revision.FieldID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.Revision.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +// +func (u *RevisionUpsertOne) Ignore() *RevisionUpsertOne { + 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 *RevisionUpsertOne) DoNothing() *RevisionUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the RevisionCreate.OnConflict +// documentation for more info. +func (u *RevisionUpsertOne) Update(set func(*RevisionUpsert)) *RevisionUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&RevisionUpsert{UpdateSet: update}) + })) + return u +} + +// Exec executes the query. +func (u *RevisionUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("ent: missing options for RevisionCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *RevisionUpsertOne) 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 *RevisionUpsertOne) ID(ctx context.Context) (id string, 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: RevisionUpsertOne.ID is not supported by MySQL driver. Use RevisionUpsertOne.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 *RevisionUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// RevisionCreateBulk is the builder for creating many Revision entities in bulk. +type RevisionCreateBulk struct { + config + builders []*RevisionCreate + conflict []sql.ConflictOption +} + +// Save creates the Revision entities in the database. +func (rcb *RevisionCreateBulk) Save(ctx context.Context) ([]*Revision, error) { + specs := make([]*sqlgraph.CreateSpec, len(rcb.builders)) + nodes := make([]*Revision, len(rcb.builders)) + mutators := make([]Mutator, len(rcb.builders)) + for i := range rcb.builders { + func(i int, root context.Context) { + builder := rcb.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*RevisionMutation) + 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, rcb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = rcb.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, rcb.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, rcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (rcb *RevisionCreateBulk) SaveX(ctx context.Context) []*Revision { + v, err := rcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (rcb *RevisionCreateBulk) Exec(ctx context.Context) error { + _, err := rcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (rcb *RevisionCreateBulk) ExecX(ctx context.Context) { + if err := rcb.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.Revision.CreateBulk(builders...). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// Exec(ctx) +// +func (rcb *RevisionCreateBulk) OnConflict(opts ...sql.ConflictOption) *RevisionUpsertBulk { + rcb.conflict = opts + return &RevisionUpsertBulk{ + create: rcb, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.Revision.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +// +func (rcb *RevisionCreateBulk) OnConflictColumns(columns ...string) *RevisionUpsertBulk { + rcb.conflict = append(rcb.conflict, sql.ConflictColumns(columns...)) + return &RevisionUpsertBulk{ + create: rcb, + } +} + +// RevisionUpsertBulk is the builder for "upsert"-ing +// a bulk of Revision nodes. +type RevisionUpsertBulk struct { + create *RevisionCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.Revision.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(revision.FieldID) +// }), +// ). +// Exec(ctx) +// +func (u *RevisionUpsertBulk) UpdateNewValues() *RevisionUpsertBulk { + 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(revision.FieldID) + return + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.Revision.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +// +func (u *RevisionUpsertBulk) Ignore() *RevisionUpsertBulk { + 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 *RevisionUpsertBulk) DoNothing() *RevisionUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the RevisionCreateBulk.OnConflict +// documentation for more info. +func (u *RevisionUpsertBulk) Update(set func(*RevisionUpsert)) *RevisionUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&RevisionUpsert{UpdateSet: update}) + })) + return u +} + +// Exec executes the query. +func (u *RevisionUpsertBulk) 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 RevisionCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("ent: missing options for RevisionCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *RevisionUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entc/integration/customid/ent/revision_delete.go b/entc/integration/customid/ent/revision_delete.go new file mode 100644 index 0000000000..85b1f65b08 --- /dev/null +++ b/entc/integration/customid/ent/revision_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/revision" + "entgo.io/ent/schema/field" +) + +// RevisionDelete is the builder for deleting a Revision entity. +type RevisionDelete struct { + config + hooks []Hook + mutation *RevisionMutation +} + +// Where appends a list predicates to the RevisionDelete builder. +func (rd *RevisionDelete) Where(ps ...predicate.Revision) *RevisionDelete { + rd.mutation.Where(ps...) + return rd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (rd *RevisionDelete) Exec(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(rd.hooks) == 0 { + affected, err = rd.sqlExec(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*RevisionMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + rd.mutation = mutation + affected, err = rd.sqlExec(ctx) + mutation.done = true + return affected, err + }) + for i := len(rd.hooks) - 1; i >= 0; i-- { + if rd.hooks[i] == nil { + return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = rd.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, rd.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// ExecX is like Exec, but panics if an error occurs. +func (rd *RevisionDelete) ExecX(ctx context.Context) int { + n, err := rd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (rd *RevisionDelete) sqlExec(ctx context.Context) (int, error) { + _spec := &sqlgraph.DeleteSpec{ + Node: &sqlgraph.NodeSpec{ + Table: revision.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeString, + Column: revision.FieldID, + }, + }, + } + if ps := rd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return sqlgraph.DeleteNodes(ctx, rd.driver, _spec) +} + +// RevisionDeleteOne is the builder for deleting a single Revision entity. +type RevisionDeleteOne struct { + rd *RevisionDelete +} + +// Exec executes the deletion query. +func (rdo *RevisionDeleteOne) Exec(ctx context.Context) error { + n, err := rdo.rd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{revision.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (rdo *RevisionDeleteOne) ExecX(ctx context.Context) { + rdo.rd.ExecX(ctx) +} diff --git a/entc/integration/customid/ent/revision_query.go b/entc/integration/customid/ent/revision_query.go new file mode 100644 index 0000000000..d40c02a8c7 --- /dev/null +++ b/entc/integration/customid/ent/revision_query.go @@ -0,0 +1,508 @@ +// 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" + "math" + + "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/revision" + "entgo.io/ent/schema/field" +) + +// RevisionQuery is the builder for querying Revision entities. +type RevisionQuery struct { + config + limit *int + offset *int + unique *bool + order []OrderFunc + fields []string + predicates []predicate.Revision + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the RevisionQuery builder. +func (rq *RevisionQuery) Where(ps ...predicate.Revision) *RevisionQuery { + rq.predicates = append(rq.predicates, ps...) + return rq +} + +// Limit adds a limit step to the query. +func (rq *RevisionQuery) Limit(limit int) *RevisionQuery { + rq.limit = &limit + return rq +} + +// Offset adds an offset step to the query. +func (rq *RevisionQuery) Offset(offset int) *RevisionQuery { + rq.offset = &offset + return rq +} + +// 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 (rq *RevisionQuery) Unique(unique bool) *RevisionQuery { + rq.unique = &unique + return rq +} + +// Order adds an order step to the query. +func (rq *RevisionQuery) Order(o ...OrderFunc) *RevisionQuery { + rq.order = append(rq.order, o...) + return rq +} + +// First returns the first Revision entity from the query. +// Returns a *NotFoundError when no Revision was found. +func (rq *RevisionQuery) First(ctx context.Context) (*Revision, error) { + nodes, err := rq.Limit(1).All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{revision.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (rq *RevisionQuery) FirstX(ctx context.Context) *Revision { + node, err := rq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Revision ID from the query. +// Returns a *NotFoundError when no Revision ID was found. +func (rq *RevisionQuery) FirstID(ctx context.Context) (id string, err error) { + var ids []string + if ids, err = rq.Limit(1).IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{revision.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (rq *RevisionQuery) FirstIDX(ctx context.Context) string { + id, err := rq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Revision entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Revision entity is found. +// Returns a *NotFoundError when no Revision entities are found. +func (rq *RevisionQuery) Only(ctx context.Context) (*Revision, error) { + nodes, err := rq.Limit(2).All(ctx) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{revision.Label} + default: + return nil, &NotSingularError{revision.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (rq *RevisionQuery) OnlyX(ctx context.Context) *Revision { + node, err := rq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Revision ID in the query. +// Returns a *NotSingularError when more than one Revision ID is found. +// Returns a *NotFoundError when no entities are found. +func (rq *RevisionQuery) OnlyID(ctx context.Context) (id string, err error) { + var ids []string + if ids, err = rq.Limit(2).IDs(ctx); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{revision.Label} + default: + err = &NotSingularError{revision.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (rq *RevisionQuery) OnlyIDX(ctx context.Context) string { + id, err := rq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Revisions. +func (rq *RevisionQuery) All(ctx context.Context) ([]*Revision, error) { + if err := rq.prepareQuery(ctx); err != nil { + return nil, err + } + return rq.sqlAll(ctx) +} + +// AllX is like All, but panics if an error occurs. +func (rq *RevisionQuery) AllX(ctx context.Context) []*Revision { + nodes, err := rq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Revision IDs. +func (rq *RevisionQuery) IDs(ctx context.Context) ([]string, error) { + var ids []string + if err := rq.Select(revision.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (rq *RevisionQuery) IDsX(ctx context.Context) []string { + ids, err := rq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (rq *RevisionQuery) Count(ctx context.Context) (int, error) { + if err := rq.prepareQuery(ctx); err != nil { + return 0, err + } + return rq.sqlCount(ctx) +} + +// CountX is like Count, but panics if an error occurs. +func (rq *RevisionQuery) CountX(ctx context.Context) int { + count, err := rq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (rq *RevisionQuery) Exist(ctx context.Context) (bool, error) { + if err := rq.prepareQuery(ctx); err != nil { + return false, err + } + return rq.sqlExist(ctx) +} + +// ExistX is like Exist, but panics if an error occurs. +func (rq *RevisionQuery) ExistX(ctx context.Context) bool { + exist, err := rq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the RevisionQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (rq *RevisionQuery) Clone() *RevisionQuery { + if rq == nil { + return nil + } + return &RevisionQuery{ + config: rq.config, + limit: rq.limit, + offset: rq.offset, + order: append([]OrderFunc{}, rq.order...), + predicates: append([]predicate.Revision{}, rq.predicates...), + // clone intermediate query. + sql: rq.sql.Clone(), + path: rq.path, + unique: rq.unique, + } +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +func (rq *RevisionQuery) GroupBy(field string, fields ...string) *RevisionGroupBy { + grbuild := &RevisionGroupBy{config: rq.config} + grbuild.fields = append([]string{field}, fields...) + grbuild.path = func(ctx context.Context) (prev *sql.Selector, err error) { + if err := rq.prepareQuery(ctx); err != nil { + return nil, err + } + return rq.sqlQuery(ctx), nil + } + grbuild.label = revision.Label + grbuild.flds, grbuild.scan = &grbuild.fields, grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +func (rq *RevisionQuery) Select(fields ...string) *RevisionSelect { + rq.fields = append(rq.fields, fields...) + selbuild := &RevisionSelect{RevisionQuery: rq} + selbuild.label = revision.Label + selbuild.flds, selbuild.scan = &rq.fields, selbuild.Scan + return selbuild +} + +func (rq *RevisionQuery) prepareQuery(ctx context.Context) error { + for _, f := range rq.fields { + if !revision.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if rq.path != nil { + prev, err := rq.path(ctx) + if err != nil { + return err + } + rq.sql = prev + } + return nil +} + +func (rq *RevisionQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Revision, error) { + var ( + nodes = []*Revision{} + _spec = rq.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]interface{}, error) { + return (*Revision).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []interface{}) error { + node := &Revision{config: rq.config} + nodes = append(nodes, node) + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, rq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (rq *RevisionQuery) sqlCount(ctx context.Context) (int, error) { + _spec := rq.querySpec() + _spec.Node.Columns = rq.fields + if len(rq.fields) > 0 { + _spec.Unique = rq.unique != nil && *rq.unique + } + return sqlgraph.CountNodes(ctx, rq.driver, _spec) +} + +func (rq *RevisionQuery) sqlExist(ctx context.Context) (bool, error) { + n, err := rq.sqlCount(ctx) + if err != nil { + return false, fmt.Errorf("ent: check existence: %w", err) + } + return n > 0, nil +} + +func (rq *RevisionQuery) querySpec() *sqlgraph.QuerySpec { + _spec := &sqlgraph.QuerySpec{ + Node: &sqlgraph.NodeSpec{ + Table: revision.Table, + Columns: revision.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeString, + Column: revision.FieldID, + }, + }, + From: rq.sql, + Unique: true, + } + if unique := rq.unique; unique != nil { + _spec.Unique = *unique + } + if fields := rq.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, revision.FieldID) + for i := range fields { + if fields[i] != revision.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := rq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := rq.limit; limit != nil { + _spec.Limit = *limit + } + if offset := rq.offset; offset != nil { + _spec.Offset = *offset + } + if ps := rq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (rq *RevisionQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(rq.driver.Dialect()) + t1 := builder.Table(revision.Table) + columns := rq.fields + if len(columns) == 0 { + columns = revision.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if rq.sql != nil { + selector = rq.sql + selector.Select(selector.Columns(columns...)...) + } + if rq.unique != nil && *rq.unique { + selector.Distinct() + } + for _, p := range rq.predicates { + p(selector) + } + for _, p := range rq.order { + p(selector) + } + if offset := rq.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 := rq.limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// RevisionGroupBy is the group-by builder for Revision entities. +type RevisionGroupBy struct { + config + selector + fields []string + fns []AggregateFunc + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (rgb *RevisionGroupBy) Aggregate(fns ...AggregateFunc) *RevisionGroupBy { + rgb.fns = append(rgb.fns, fns...) + return rgb +} + +// Scan applies the group-by query and scans the result into the given value. +func (rgb *RevisionGroupBy) Scan(ctx context.Context, v interface{}) error { + query, err := rgb.path(ctx) + if err != nil { + return err + } + rgb.sql = query + return rgb.sqlScan(ctx, v) +} + +func (rgb *RevisionGroupBy) sqlScan(ctx context.Context, v interface{}) error { + for _, f := range rgb.fields { + if !revision.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + } + } + selector := rgb.sqlQuery() + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := rgb.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +func (rgb *RevisionGroupBy) sqlQuery() *sql.Selector { + selector := rgb.sql.Select() + aggregation := make([]string, 0, len(rgb.fns)) + for _, fn := range rgb.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(rgb.fields)+len(rgb.fns)) + for _, f := range rgb.fields { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + return selector.GroupBy(selector.Columns(rgb.fields...)...) +} + +// RevisionSelect is the builder for selecting fields of Revision entities. +type RevisionSelect struct { + *RevisionQuery + selector + // intermediate query (i.e. traversal path). + sql *sql.Selector +} + +// Scan applies the selector query and scans the result into the given value. +func (rs *RevisionSelect) Scan(ctx context.Context, v interface{}) error { + if err := rs.prepareQuery(ctx); err != nil { + return err + } + rs.sql = rs.RevisionQuery.sqlQuery(ctx) + return rs.sqlScan(ctx, v) +} + +func (rs *RevisionSelect) sqlScan(ctx context.Context, v interface{}) error { + rows := &sql.Rows{} + query, args := rs.sql.Query() + if err := rs.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/revision_update.go b/entc/integration/customid/ent/revision_update.go new file mode 100644 index 0000000000..6c9ac88e25 --- /dev/null +++ b/entc/integration/customid/ent/revision_update.go @@ -0,0 +1,243 @@ +// 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/predicate" + "entgo.io/ent/entc/integration/customid/ent/revision" + "entgo.io/ent/schema/field" +) + +// RevisionUpdate is the builder for updating Revision entities. +type RevisionUpdate struct { + config + hooks []Hook + mutation *RevisionMutation +} + +// Where appends a list predicates to the RevisionUpdate builder. +func (ru *RevisionUpdate) Where(ps ...predicate.Revision) *RevisionUpdate { + ru.mutation.Where(ps...) + return ru +} + +// Mutation returns the RevisionMutation object of the builder. +func (ru *RevisionUpdate) Mutation() *RevisionMutation { + return ru.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (ru *RevisionUpdate) Save(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(ru.hooks) == 0 { + affected, err = ru.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*RevisionMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + ru.mutation = mutation + affected, err = ru.sqlSave(ctx) + mutation.done = true + return affected, err + }) + for i := len(ru.hooks) - 1; i >= 0; i-- { + if ru.hooks[i] == nil { + return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = ru.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, ru.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// SaveX is like Save, but panics if an error occurs. +func (ru *RevisionUpdate) SaveX(ctx context.Context) int { + affected, err := ru.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (ru *RevisionUpdate) Exec(ctx context.Context) error { + _, err := ru.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ru *RevisionUpdate) ExecX(ctx context.Context) { + if err := ru.Exec(ctx); err != nil { + panic(err) + } +} + +func (ru *RevisionUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: revision.Table, + Columns: revision.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeString, + Column: revision.FieldID, + }, + }, + } + if ps := ru.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if n, err = sqlgraph.UpdateNodes(ctx, ru.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{revision.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return 0, err + } + return n, nil +} + +// RevisionUpdateOne is the builder for updating a single Revision entity. +type RevisionUpdateOne struct { + config + fields []string + hooks []Hook + mutation *RevisionMutation +} + +// Mutation returns the RevisionMutation object of the builder. +func (ruo *RevisionUpdateOne) Mutation() *RevisionMutation { + return ruo.mutation +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (ruo *RevisionUpdateOne) Select(field string, fields ...string) *RevisionUpdateOne { + ruo.fields = append([]string{field}, fields...) + return ruo +} + +// Save executes the query and returns the updated Revision entity. +func (ruo *RevisionUpdateOne) Save(ctx context.Context) (*Revision, error) { + var ( + err error + node *Revision + ) + if len(ruo.hooks) == 0 { + node, err = ruo.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*RevisionMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + ruo.mutation = mutation + node, err = ruo.sqlSave(ctx) + mutation.done = true + return node, err + }) + for i := len(ruo.hooks) - 1; i >= 0; i-- { + if ruo.hooks[i] == nil { + return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = ruo.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, ruo.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX is like Save, but panics if an error occurs. +func (ruo *RevisionUpdateOne) SaveX(ctx context.Context) *Revision { + node, err := ruo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (ruo *RevisionUpdateOne) Exec(ctx context.Context) error { + _, err := ruo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ruo *RevisionUpdateOne) ExecX(ctx context.Context) { + if err := ruo.Exec(ctx); err != nil { + panic(err) + } +} + +func (ruo *RevisionUpdateOne) sqlSave(ctx context.Context) (_node *Revision, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: revision.Table, + Columns: revision.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeString, + Column: revision.FieldID, + }, + }, + } + id, ok := ruo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Revision.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := ruo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, revision.FieldID) + for _, f := range fields { + if !revision.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != revision.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := ruo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + _node = &Revision{config: ruo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, ruo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{revision.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + return _node, nil +} diff --git a/entc/integration/customid/ent/schema/revision.go b/entc/integration/customid/ent/schema/revision.go new file mode 100644 index 0000000000..24136e0ea1 --- /dev/null +++ b/entc/integration/customid/ent/schema/revision.go @@ -0,0 +1,21 @@ +// 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 + +// User holds the schema definition for the User entity. +import ( + "entgo.io/ent" + "entgo.io/ent/schema/field" +) + +// Revision holds the schema definition for the Revision entity. +type Revision struct { + ent.Schema +} + +// Fields of the Revision. +func (Revision) Fields() []ent.Field { + return []ent.Field{field.String("id")} +} diff --git a/entc/integration/customid/ent/tx.go b/entc/integration/customid/ent/tx.go index f14d6c7f6b..dd7d5c0667 100644 --- a/entc/integration/customid/ent/tx.go +++ b/entc/integration/customid/ent/tx.go @@ -36,6 +36,8 @@ type Tx struct { Other *OtherClient // Pet is the client for interacting with the Pet builders. Pet *PetClient + // Revision is the client for interacting with the Revision builders. + Revision *RevisionClient // Session is the client for interacting with the Session builders. Session *SessionClient // Token is the client for interacting with the Token builders. @@ -187,6 +189,7 @@ func (tx *Tx) init() { tx.Note = NewNoteClient(tx.config) tx.Other = NewOtherClient(tx.config) tx.Pet = NewPetClient(tx.config) + tx.Revision = NewRevisionClient(tx.config) tx.Session = NewSessionClient(tx.config) tx.Token = NewTokenClient(tx.config) tx.User = NewUserClient(tx.config) From 0c8f9a977c99c9d768c9c1b0ca645f5667a4f836 Mon Sep 17 00:00:00 2001 From: MasseElch <12862103+masseelch@users.noreply.github.com> Date: Thu, 28 Apr 2022 13:42:25 +0200 Subject: [PATCH 2/2] Update entc/integration/customid/ent/schema/revision.go Co-authored-by: Ariel Mashraki <7413593+a8m@users.noreply.github.com> --- entc/integration/customid/ent/schema/revision.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/entc/integration/customid/ent/schema/revision.go b/entc/integration/customid/ent/schema/revision.go index 24136e0ea1..3b921af06f 100644 --- a/entc/integration/customid/ent/schema/revision.go +++ b/entc/integration/customid/ent/schema/revision.go @@ -17,5 +17,7 @@ type Revision struct { // Fields of the Revision. func (Revision) Fields() []ent.Field { - return []ent.Field{field.String("id")} + return []ent.Field{ + field.String("id"), + } }