From 91b643091fbad8c798960779bd902f0be70283fd Mon Sep 17 00:00:00 2001 From: Reiji Tokuda Date: Mon, 4 Jul 2022 13:50:51 +0800 Subject: [PATCH] entc/gen: support setting GoType for integer IDs (#2657) * Fix problem when model maps integer id to a GoType * Update generated files * apply suggestions from code review * Update generated files * Update generated files after merge from master * Cleanup test code in integration Co-authored-by: Ariel Mashraki <7413593+a8m@users.noreply.github.com> * Modify integration test IntSID. Wrapped tests of IntSID for avoid conflicts. * Modify tests in integrations Order of tests was changed. As a result, if-statement for difference in RDB is deleted. + force pushing same commit to invoke ci. Co-authored-by: Ariel Mashraki <7413593+a8m@users.noreply.github.com> --- entc/gen/template/dialect/sql/create.tmpl | 8 +- entc/gen/template/dialect/sql/decode.tmpl | 4 +- entc/integration/customid/customid_test.go | 19 + entc/integration/customid/ent/client.go | 129 ++++ entc/integration/customid/ent/config.go | 1 + entc/integration/customid/ent/ent.go | 2 + entc/integration/customid/ent/entql.go | 137 +++- entc/integration/customid/ent/hook/hook.go | 13 + entc/integration/customid/ent/intsid.go | 149 ++++ .../integration/customid/ent/intsid/intsid.go | 54 ++ entc/integration/customid/ent/intsid/where.go | 185 +++++ .../integration/customid/ent/intsid_create.go | 547 +++++++++++++++ .../integration/customid/ent/intsid_delete.go | 119 ++++ entc/integration/customid/ent/intsid_query.go | 653 ++++++++++++++++++ .../integration/customid/ent/intsid_update.go | 550 +++++++++++++++ .../customid/ent/migrate/schema.go | 21 + entc/integration/customid/ent/mutation.go | 409 +++++++++++ .../customid/ent/predicate/predicate.go | 3 + .../integration/customid/ent/schema/intsid.go | 37 + entc/integration/customid/ent/tx.go | 3 + 20 files changed, 3024 insertions(+), 19 deletions(-) create mode 100644 entc/integration/customid/ent/intsid.go create mode 100644 entc/integration/customid/ent/intsid/intsid.go create mode 100644 entc/integration/customid/ent/intsid/where.go create mode 100644 entc/integration/customid/ent/intsid_create.go create mode 100644 entc/integration/customid/ent/intsid_delete.go create mode 100644 entc/integration/customid/ent/intsid_query.go create mode 100644 entc/integration/customid/ent/intsid_update.go create mode 100644 entc/integration/customid/ent/schema/intsid.go diff --git a/entc/gen/template/dialect/sql/create.tmpl b/entc/gen/template/dialect/sql/create.tmpl index 4e4de92f2..bc960ebf0 100644 --- a/entc/gen/template/dialect/sql/create.tmpl +++ b/entc/gen/template/dialect/sql/create.tmpl @@ -180,7 +180,13 @@ func ({{ $receiver }} *{{ $builder }}) Save(ctx context.Context) ([]*{{ $.Name } {{- if $.HasOneFieldID }} mutation.{{ $.ID.BuilderField }} = &nodes[i].{{ $.ID.StructField }} {{- if or $.ID.IsString $.ID.IsUUID $.ID.IsBytes $.ID.IsOther }} - {{- /* Do nothing, because these 2 types must be supplied by the user. */ -}} + {{- /* Do nothing, because these 4 types must be supplied by the user. */ -}} + {{- else if or $.ID.Type.ValueScanner }} + if specs[i].ID.Value != nil { + if err := nodes[i].ID.Scan(specs[i].ID.Value); err != nil { + return nil, err + } + } {{- else }} if specs[i].ID.Value != nil {{ if $.ID.UserDefined }}&& nodes[i].ID == 0{{ end }} { id := specs[i].ID.Value.(int64) diff --git a/entc/gen/template/dialect/sql/decode.tmpl b/entc/gen/template/dialect/sql/decode.tmpl index 24edc7b53..11cfa3f2f 100644 --- a/entc/gen/template/dialect/sql/decode.tmpl +++ b/entc/gen/template/dialect/sql/decode.tmpl @@ -55,7 +55,7 @@ func ({{ $receiver }} *{{ $.Name }}) assignValues(columns []string, values []int switch columns[{{ $idx }}] { {{- if $.HasOneFieldID }} case {{ $.Package }}.{{ $.ID.Constant }}: - {{- if or $.ID.IsString $.ID.IsUUID $.ID.IsBytes $.ID.IsOther }} + {{- if or $.ID.IsString $.ID.IsBytes $.ID.HasGoType }} {{- with extend $ "Idx" $idx "Field" $.ID "Rec" $receiver }} {{ template "dialect/sql/decode/field" . }} {{- end }} @@ -76,7 +76,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 $f.IsOther)) }} + {{- if or $fk.UserDefined (and $f.UserDefined (or $f.IsString $f.IsBytes $f.HasGoType)) }} {{- 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 1a341f266..9eb5acd63 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" "entgo.io/ent/entc/integration/customid/ent/blob" "entgo.io/ent/entc/integration/customid/ent/doc" + "entgo.io/ent/entc/integration/customid/ent/intsid" "entgo.io/ent/entc/integration/customid/ent/pet" "entgo.io/ent/entc/integration/customid/ent/token" "entgo.io/ent/entc/integration/customid/ent/user" @@ -177,6 +178,24 @@ func CustomID(t *testing.T, client *ent.Client) { cdoc := client.Doc.Create().SetText("child").SetParent(pdoc).SaveX(ctx) require.NotEmpty(t, cdoc.QueryParent().OnlyIDX(ctx)) + t.Run("IntSID", func(t *testing.T) { + root := client.IntSID.Create().SaveX(ctx) + require.EqualValues(t, sid.ID("1"), root.ID) + children := client.IntSID.CreateBulk( + client.IntSID.Create().SetParent(root), + client.IntSID.Create().SetParent(root), + ).SaveX(ctx) + require.EqualValues(t, sid.ID("2"), children[0].ID) + require.EqualValues(t, sid.ID("3"), children[1].ID) + el := client.IntSID.Query().Where(intsid.ID(root.ID)).WithChildren().AllX(ctx) + require.EqualValues(t, 1, len(el)) + require.EqualValues(t, 2, len(el[0].Edges.Children)) + cid := sid.ID("100") + child := client.IntSID.Create().SetID(cid).SetParent(root).SaveX(ctx) + require.EqualValues(t, cid, child.ID) + require.EqualValues(t, root.ID, child.QueryParent().OnlyX(ctx).ID) + }) + t.Run("Upsert", func(t *testing.T) { id := uuid.New() client.Blob.Create(). diff --git a/entc/integration/customid/ent/client.go b/entc/integration/customid/ent/client.go index 5ba3b2e5c..497c75146 100644 --- a/entc/integration/customid/ent/client.go +++ b/entc/integration/customid/ent/client.go @@ -22,6 +22,7 @@ import ( "entgo.io/ent/entc/integration/customid/ent/device" "entgo.io/ent/entc/integration/customid/ent/doc" "entgo.io/ent/entc/integration/customid/ent/group" + "entgo.io/ent/entc/integration/customid/ent/intsid" "entgo.io/ent/entc/integration/customid/ent/mixinid" "entgo.io/ent/entc/integration/customid/ent/note" "entgo.io/ent/entc/integration/customid/ent/other" @@ -53,6 +54,8 @@ type Client struct { Doc *DocClient // Group is the client for interacting with the Group builders. Group *GroupClient + // IntSID is the client for interacting with the IntSID builders. + IntSID *IntSIDClient // MixinID is the client for interacting with the MixinID builders. MixinID *MixinIDClient // Note is the client for interacting with the Note builders. @@ -88,6 +91,7 @@ func (c *Client) init() { c.Device = NewDeviceClient(c.config) c.Doc = NewDocClient(c.config) c.Group = NewGroupClient(c.config) + c.IntSID = NewIntSIDClient(c.config) c.MixinID = NewMixinIDClient(c.config) c.Note = NewNoteClient(c.config) c.Other = NewOtherClient(c.config) @@ -135,6 +139,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { Device: NewDeviceClient(cfg), Doc: NewDocClient(cfg), Group: NewGroupClient(cfg), + IntSID: NewIntSIDClient(cfg), MixinID: NewMixinIDClient(cfg), Note: NewNoteClient(cfg), Other: NewOtherClient(cfg), @@ -168,6 +173,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) Device: NewDeviceClient(cfg), Doc: NewDocClient(cfg), Group: NewGroupClient(cfg), + IntSID: NewIntSIDClient(cfg), MixinID: NewMixinIDClient(cfg), Note: NewNoteClient(cfg), Other: NewOtherClient(cfg), @@ -211,6 +217,7 @@ func (c *Client) Use(hooks ...Hook) { c.Device.Use(hooks...) c.Doc.Use(hooks...) c.Group.Use(hooks...) + c.IntSID.Use(hooks...) c.MixinID.Use(hooks...) c.Note.Use(hooks...) c.Other.Use(hooks...) @@ -905,6 +912,128 @@ func (c *GroupClient) Hooks() []Hook { return c.hooks.Group } +// IntSIDClient is a client for the IntSID schema. +type IntSIDClient struct { + config +} + +// NewIntSIDClient returns a client for the IntSID from the given config. +func NewIntSIDClient(c config) *IntSIDClient { + return &IntSIDClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `intsid.Hooks(f(g(h())))`. +func (c *IntSIDClient) Use(hooks ...Hook) { + c.hooks.IntSID = append(c.hooks.IntSID, hooks...) +} + +// Create returns a builder for creating a IntSID entity. +func (c *IntSIDClient) Create() *IntSIDCreate { + mutation := newIntSIDMutation(c.config, OpCreate) + return &IntSIDCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of IntSID entities. +func (c *IntSIDClient) CreateBulk(builders ...*IntSIDCreate) *IntSIDCreateBulk { + return &IntSIDCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for IntSID. +func (c *IntSIDClient) Update() *IntSIDUpdate { + mutation := newIntSIDMutation(c.config, OpUpdate) + return &IntSIDUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *IntSIDClient) UpdateOne(is *IntSID) *IntSIDUpdateOne { + mutation := newIntSIDMutation(c.config, OpUpdateOne, withIntSID(is)) + return &IntSIDUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *IntSIDClient) UpdateOneID(id sid.ID) *IntSIDUpdateOne { + mutation := newIntSIDMutation(c.config, OpUpdateOne, withIntSIDID(id)) + return &IntSIDUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for IntSID. +func (c *IntSIDClient) Delete() *IntSIDDelete { + mutation := newIntSIDMutation(c.config, OpDelete) + return &IntSIDDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *IntSIDClient) DeleteOne(is *IntSID) *IntSIDDeleteOne { + return c.DeleteOneID(is.ID) +} + +// DeleteOne returns a builder for deleting the given entity by its id. +func (c *IntSIDClient) DeleteOneID(id sid.ID) *IntSIDDeleteOne { + builder := c.Delete().Where(intsid.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &IntSIDDeleteOne{builder} +} + +// Query returns a query builder for IntSID. +func (c *IntSIDClient) Query() *IntSIDQuery { + return &IntSIDQuery{ + config: c.config, + } +} + +// Get returns a IntSID entity by its id. +func (c *IntSIDClient) Get(ctx context.Context, id sid.ID) (*IntSID, error) { + return c.Query().Where(intsid.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *IntSIDClient) GetX(ctx context.Context, id sid.ID) *IntSID { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryParent queries the parent edge of a IntSID. +func (c *IntSIDClient) QueryParent(is *IntSID) *IntSIDQuery { + query := &IntSIDQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := is.ID + step := sqlgraph.NewStep( + sqlgraph.From(intsid.Table, intsid.FieldID, id), + sqlgraph.To(intsid.Table, intsid.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, intsid.ParentTable, intsid.ParentColumn), + ) + fromV = sqlgraph.Neighbors(is.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryChildren queries the children edge of a IntSID. +func (c *IntSIDClient) QueryChildren(is *IntSID) *IntSIDQuery { + query := &IntSIDQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := is.ID + step := sqlgraph.NewStep( + sqlgraph.From(intsid.Table, intsid.FieldID, id), + sqlgraph.To(intsid.Table, intsid.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, intsid.ChildrenTable, intsid.ChildrenColumn), + ) + fromV = sqlgraph.Neighbors(is.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *IntSIDClient) Hooks() []Hook { + return c.hooks.IntSID +} + // MixinIDClient is a client for the MixinID schema. type MixinIDClient struct { config diff --git a/entc/integration/customid/ent/config.go b/entc/integration/customid/ent/config.go index f3120b817..d4d4f2521 100644 --- a/entc/integration/customid/ent/config.go +++ b/entc/integration/customid/ent/config.go @@ -34,6 +34,7 @@ type hooks struct { Device []ent.Hook Doc []ent.Hook Group []ent.Hook + IntSID []ent.Hook MixinID []ent.Hook Note []ent.Hook Other []ent.Hook diff --git a/entc/integration/customid/ent/ent.go b/entc/integration/customid/ent/ent.go index d20fa415f..4f5bae55a 100644 --- a/entc/integration/customid/ent/ent.go +++ b/entc/integration/customid/ent/ent.go @@ -20,6 +20,7 @@ import ( "entgo.io/ent/entc/integration/customid/ent/device" "entgo.io/ent/entc/integration/customid/ent/doc" "entgo.io/ent/entc/integration/customid/ent/group" + "entgo.io/ent/entc/integration/customid/ent/intsid" "entgo.io/ent/entc/integration/customid/ent/mixinid" "entgo.io/ent/entc/integration/customid/ent/note" "entgo.io/ent/entc/integration/customid/ent/other" @@ -54,6 +55,7 @@ func columnChecker(table string) func(string) error { device.Table: device.ValidColumn, doc.Table: doc.ValidColumn, group.Table: group.ValidColumn, + intsid.Table: intsid.ValidColumn, mixinid.Table: mixinid.ValidColumn, note.Table: note.ValidColumn, other.Table: other.ValidColumn, diff --git a/entc/integration/customid/ent/entql.go b/entc/integration/customid/ent/entql.go index b3e79c74f..32de4ece0 100644 --- a/entc/integration/customid/ent/entql.go +++ b/entc/integration/customid/ent/entql.go @@ -13,6 +13,7 @@ import ( "entgo.io/ent/entc/integration/customid/ent/device" "entgo.io/ent/entc/integration/customid/ent/doc" "entgo.io/ent/entc/integration/customid/ent/group" + "entgo.io/ent/entc/integration/customid/ent/intsid" "entgo.io/ent/entc/integration/customid/ent/mixinid" "entgo.io/ent/entc/integration/customid/ent/note" "entgo.io/ent/entc/integration/customid/ent/other" @@ -31,7 +32,7 @@ import ( // schemaGraph holds a representation of ent/schema at runtime. var schemaGraph = func() *sqlgraph.Schema { - graph := &sqlgraph.Schema{Nodes: make([]*sqlgraph.Node, 14)} + graph := &sqlgraph.Schema{Nodes: make([]*sqlgraph.Node, 15)} graph.Nodes[0] = &sqlgraph.Node{ NodeSpec: sqlgraph.NodeSpec{ Table: account.Table, @@ -116,6 +117,18 @@ var schemaGraph = func() *sqlgraph.Schema { Fields: map[string]*sqlgraph.FieldSpec{}, } graph.Nodes[6] = &sqlgraph.Node{ + NodeSpec: sqlgraph.NodeSpec{ + Table: intsid.Table, + Columns: intsid.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt64, + Column: intsid.FieldID, + }, + }, + Type: "IntSID", + Fields: map[string]*sqlgraph.FieldSpec{}, + } + graph.Nodes[7] = &sqlgraph.Node{ NodeSpec: sqlgraph.NodeSpec{ Table: mixinid.Table, Columns: mixinid.Columns, @@ -130,7 +143,7 @@ var schemaGraph = func() *sqlgraph.Schema { mixinid.FieldMixinField: {Type: field.TypeString, Column: mixinid.FieldMixinField}, }, } - graph.Nodes[7] = &sqlgraph.Node{ + graph.Nodes[8] = &sqlgraph.Node{ NodeSpec: sqlgraph.NodeSpec{ Table: note.Table, Columns: note.Columns, @@ -144,7 +157,7 @@ var schemaGraph = func() *sqlgraph.Schema { note.FieldText: {Type: field.TypeString, Column: note.FieldText}, }, } - graph.Nodes[8] = &sqlgraph.Node{ + graph.Nodes[9] = &sqlgraph.Node{ NodeSpec: sqlgraph.NodeSpec{ Table: other.Table, Columns: other.Columns, @@ -156,7 +169,7 @@ var schemaGraph = func() *sqlgraph.Schema { Type: "Other", Fields: map[string]*sqlgraph.FieldSpec{}, } - graph.Nodes[9] = &sqlgraph.Node{ + graph.Nodes[10] = &sqlgraph.Node{ NodeSpec: sqlgraph.NodeSpec{ Table: pet.Table, Columns: pet.Columns, @@ -168,7 +181,7 @@ var schemaGraph = func() *sqlgraph.Schema { Type: "Pet", Fields: map[string]*sqlgraph.FieldSpec{}, } - graph.Nodes[10] = &sqlgraph.Node{ + graph.Nodes[11] = &sqlgraph.Node{ NodeSpec: sqlgraph.NodeSpec{ Table: revision.Table, Columns: revision.Columns, @@ -180,7 +193,7 @@ var schemaGraph = func() *sqlgraph.Schema { Type: "Revision", Fields: map[string]*sqlgraph.FieldSpec{}, } - graph.Nodes[11] = &sqlgraph.Node{ + graph.Nodes[12] = &sqlgraph.Node{ NodeSpec: sqlgraph.NodeSpec{ Table: session.Table, Columns: session.Columns, @@ -192,7 +205,7 @@ var schemaGraph = func() *sqlgraph.Schema { Type: "Session", Fields: map[string]*sqlgraph.FieldSpec{}, } - graph.Nodes[12] = &sqlgraph.Node{ + graph.Nodes[13] = &sqlgraph.Node{ NodeSpec: sqlgraph.NodeSpec{ Table: token.Table, Columns: token.Columns, @@ -206,7 +219,7 @@ var schemaGraph = func() *sqlgraph.Schema { token.FieldBody: {Type: field.TypeString, Column: token.FieldBody}, }, } - graph.Nodes[13] = &sqlgraph.Node{ + graph.Nodes[14] = &sqlgraph.Node{ NodeSpec: sqlgraph.NodeSpec{ Table: user.Table, Columns: user.Columns, @@ -326,6 +339,30 @@ var schemaGraph = func() *sqlgraph.Schema { "Group", "User", ) + graph.MustAddE( + "parent", + &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: intsid.ParentTable, + Columns: []string{intsid.ParentColumn}, + Bidi: true, + }, + "IntSID", + "IntSID", + ) + graph.MustAddE( + "children", + &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: intsid.ChildrenTable, + Columns: []string{intsid.ChildrenColumn}, + Bidi: false, + }, + "IntSID", + "IntSID", + ) graph.MustAddE( "parent", &sqlgraph.EdgeSpec{ @@ -880,6 +917,74 @@ func (f *GroupFilter) WhereHasUsersWith(preds ...predicate.User) { }))) } +// addPredicate implements the predicateAdder interface. +func (isq *IntSIDQuery) addPredicate(pred func(s *sql.Selector)) { + isq.predicates = append(isq.predicates, pred) +} + +// Filter returns a Filter implementation to apply filters on the IntSIDQuery builder. +func (isq *IntSIDQuery) Filter() *IntSIDFilter { + return &IntSIDFilter{config: isq.config, predicateAdder: isq} +} + +// addPredicate implements the predicateAdder interface. +func (m *IntSIDMutation) addPredicate(pred func(s *sql.Selector)) { + m.predicates = append(m.predicates, pred) +} + +// Filter returns an entql.Where implementation to apply filters on the IntSIDMutation builder. +func (m *IntSIDMutation) Filter() *IntSIDFilter { + return &IntSIDFilter{config: m.config, predicateAdder: m} +} + +// IntSIDFilter provides a generic filtering capability at runtime for IntSIDQuery. +type IntSIDFilter struct { + predicateAdder + config +} + +// Where applies the entql predicate on the query filter. +func (f *IntSIDFilter) Where(p entql.P) { + f.addPredicate(func(s *sql.Selector) { + if err := schemaGraph.EvalP(schemaGraph.Nodes[6].Type, p, s); err != nil { + s.AddError(err) + } + }) +} + +// WhereID applies the entql int64 predicate on the id field. +func (f *IntSIDFilter) WhereID(p entql.Int64P) { + f.Where(p.Field(intsid.FieldID)) +} + +// WhereHasParent applies a predicate to check if query has an edge parent. +func (f *IntSIDFilter) WhereHasParent() { + f.Where(entql.HasEdge("parent")) +} + +// WhereHasParentWith applies a predicate to check if query has an edge parent with a given conditions (other predicates). +func (f *IntSIDFilter) WhereHasParentWith(preds ...predicate.IntSID) { + f.Where(entql.HasEdgeWith("parent", sqlgraph.WrapFunc(func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }))) +} + +// WhereHasChildren applies a predicate to check if query has an edge children. +func (f *IntSIDFilter) WhereHasChildren() { + f.Where(entql.HasEdge("children")) +} + +// WhereHasChildrenWith applies a predicate to check if query has an edge children with a given conditions (other predicates). +func (f *IntSIDFilter) WhereHasChildrenWith(preds ...predicate.IntSID) { + f.Where(entql.HasEdgeWith("children", sqlgraph.WrapFunc(func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }))) +} + // addPredicate implements the predicateAdder interface. func (miq *MixinIDQuery) addPredicate(pred func(s *sql.Selector)) { miq.predicates = append(miq.predicates, pred) @@ -909,7 +1014,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[6].Type, p, s); err != nil { + if err := schemaGraph.EvalP(schemaGraph.Nodes[7].Type, p, s); err != nil { s.AddError(err) } }) @@ -959,7 +1064,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[7].Type, p, s); err != nil { + if err := schemaGraph.EvalP(schemaGraph.Nodes[8].Type, p, s); err != nil { s.AddError(err) } }) @@ -1032,7 +1137,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[8].Type, p, s); err != nil { + if err := schemaGraph.EvalP(schemaGraph.Nodes[9].Type, p, s); err != nil { s.AddError(err) } }) @@ -1072,7 +1177,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[9].Type, p, s); err != nil { + if err := schemaGraph.EvalP(schemaGraph.Nodes[10].Type, p, s); err != nil { s.AddError(err) } }) @@ -1168,7 +1273,7 @@ type RevisionFilter struct { // 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 { + if err := schemaGraph.EvalP(schemaGraph.Nodes[11].Type, p, s); err != nil { s.AddError(err) } }) @@ -1208,7 +1313,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[11].Type, p, s); err != nil { + if err := schemaGraph.EvalP(schemaGraph.Nodes[12].Type, p, s); err != nil { s.AddError(err) } }) @@ -1262,7 +1367,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[12].Type, p, s); err != nil { + if err := schemaGraph.EvalP(schemaGraph.Nodes[13].Type, p, s); err != nil { s.AddError(err) } }) @@ -1321,7 +1426,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[13].Type, p, s); err != nil { + if err := schemaGraph.EvalP(schemaGraph.Nodes[14].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 fe3536328..bcce3353e 100644 --- a/entc/integration/customid/ent/hook/hook.go +++ b/entc/integration/customid/ent/hook/hook.go @@ -91,6 +91,19 @@ func (f GroupFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error return f(ctx, mv) } +// The IntSIDFunc type is an adapter to allow the use of ordinary +// function as IntSID mutator. +type IntSIDFunc func(context.Context, *ent.IntSIDMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f IntSIDFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + mv, ok := m.(*ent.IntSIDMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.IntSIDMutation", m) + } + return f(ctx, mv) +} + // The MixinIDFunc type is an adapter to allow the use of ordinary // function as MixinID mutator. type MixinIDFunc func(context.Context, *ent.MixinIDMutation) (ent.Value, error) diff --git a/entc/integration/customid/ent/intsid.go b/entc/integration/customid/ent/intsid.go new file mode 100644 index 000000000..cf60dc9e1 --- /dev/null +++ b/entc/integration/customid/ent/intsid.go @@ -0,0 +1,149 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/entc/integration/customid/ent/intsid" + "entgo.io/ent/entc/integration/customid/sid" +) + +// IntSID is the model entity for the IntSID schema. +type IntSID struct { + config + // ID of the ent. + ID sid.ID `json:"id,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the IntSIDQuery when eager-loading is set. + Edges IntSIDEdges `json:"edges"` + int_sid_parent *sid.ID +} + +// IntSIDEdges holds the relations/edges for other nodes in the graph. +type IntSIDEdges struct { + // Parent holds the value of the parent edge. + Parent *IntSID `json:"parent,omitempty"` + // Children holds the value of the children edge. + Children []*IntSID `json:"children,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool +} + +// ParentOrErr returns the Parent value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e IntSIDEdges) ParentOrErr() (*IntSID, error) { + if e.loadedTypes[0] { + if e.Parent == nil { + // The edge parent was loaded in eager-loading, + // but was not found. + return nil, &NotFoundError{label: intsid.Label} + } + return e.Parent, nil + } + return nil, &NotLoadedError{edge: "parent"} +} + +// ChildrenOrErr returns the Children value or an error if the edge +// was not loaded in eager-loading. +func (e IntSIDEdges) ChildrenOrErr() ([]*IntSID, error) { + if e.loadedTypes[1] { + return e.Children, nil + } + return nil, &NotLoadedError{edge: "children"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*IntSID) scanValues(columns []string) ([]interface{}, error) { + values := make([]interface{}, len(columns)) + for i := range columns { + switch columns[i] { + case intsid.FieldID: + values[i] = new(sid.ID) + case intsid.ForeignKeys[0]: // int_sid_parent + values[i] = &sql.NullScanner{S: new(sid.ID)} + default: + return nil, fmt.Errorf("unexpected column %q for type IntSID", columns[i]) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the IntSID fields. +func (is *IntSID) 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 intsid.FieldID: + if value, ok := values[i].(*sid.ID); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value != nil { + is.ID = *value + } + case intsid.ForeignKeys[0]: + if value, ok := values[i].(*sql.NullScanner); !ok { + return fmt.Errorf("unexpected type %T for field int_sid_parent", values[i]) + } else if value.Valid { + is.int_sid_parent = new(sid.ID) + *is.int_sid_parent = *value.S.(*sid.ID) + } + } + } + return nil +} + +// QueryParent queries the "parent" edge of the IntSID entity. +func (is *IntSID) QueryParent() *IntSIDQuery { + return (&IntSIDClient{config: is.config}).QueryParent(is) +} + +// QueryChildren queries the "children" edge of the IntSID entity. +func (is *IntSID) QueryChildren() *IntSIDQuery { + return (&IntSIDClient{config: is.config}).QueryChildren(is) +} + +// Update returns a builder for updating this IntSID. +// Note that you need to call IntSID.Unwrap() before calling this method if this IntSID +// was returned from a transaction, and the transaction was committed or rolled back. +func (is *IntSID) Update() *IntSIDUpdateOne { + return (&IntSIDClient{config: is.config}).UpdateOne(is) +} + +// Unwrap unwraps the IntSID 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 (is *IntSID) Unwrap() *IntSID { + _tx, ok := is.config.driver.(*txDriver) + if !ok { + panic("ent: IntSID is not a transactional entity") + } + is.config.driver = _tx.drv + return is +} + +// String implements the fmt.Stringer. +func (is *IntSID) String() string { + var builder strings.Builder + builder.WriteString("IntSID(") + builder.WriteString(fmt.Sprintf("id=%v", is.ID)) + builder.WriteByte(')') + return builder.String() +} + +// IntSIDs is a parsable slice of IntSID. +type IntSIDs []*IntSID + +func (is IntSIDs) config(cfg config) { + for _i := range is { + is[_i].config = cfg + } +} diff --git a/entc/integration/customid/ent/intsid/intsid.go b/entc/integration/customid/ent/intsid/intsid.go new file mode 100644 index 000000000..1fcffc878 --- /dev/null +++ b/entc/integration/customid/ent/intsid/intsid.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 ent, DO NOT EDIT. + +package intsid + +const ( + // Label holds the string label denoting the intsid type in the database. + Label = "int_sid" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // EdgeParent holds the string denoting the parent edge name in mutations. + EdgeParent = "parent" + // EdgeChildren holds the string denoting the children edge name in mutations. + EdgeChildren = "children" + // Table holds the table name of the intsid in the database. + Table = "int_si_ds" + // ParentTable is the table that holds the parent relation/edge. + ParentTable = "int_si_ds" + // ParentColumn is the table column denoting the parent relation/edge. + ParentColumn = "int_sid_parent" + // ChildrenTable is the table that holds the children relation/edge. + ChildrenTable = "int_si_ds" + // ChildrenColumn is the table column denoting the children relation/edge. + ChildrenColumn = "int_sid_parent" +) + +// Columns holds all SQL columns for intsid fields. +var Columns = []string{ + FieldID, +} + +// ForeignKeys holds the SQL foreign-keys that are owned by the "int_si_ds" +// table and are not defined as standalone fields in the schema. +var ForeignKeys = []string{ + "int_sid_parent", +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + for i := range ForeignKeys { + if column == ForeignKeys[i] { + return true + } + } + return false +} diff --git a/entc/integration/customid/ent/intsid/where.go b/entc/integration/customid/ent/intsid/where.go new file mode 100644 index 000000000..f7cc25a5e --- /dev/null +++ b/entc/integration/customid/ent/intsid/where.go @@ -0,0 +1,185 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package intsid + +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.IntSID { + return predicate.IntSID(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.IntSID { + return predicate.IntSID(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.IntSID { + return predicate.IntSID(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.IntSID { + return predicate.IntSID(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.IntSID { + return predicate.IntSID(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.IntSID { + return predicate.IntSID(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.IntSID { + return predicate.IntSID(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.IntSID { + return predicate.IntSID(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.IntSID { + return predicate.IntSID(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldID), id)) + }) +} + +// HasParent applies the HasEdge predicate on the "parent" edge. +func HasParent() predicate.IntSID { + return predicate.IntSID(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ParentTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, ParentTable, ParentColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasParentWith applies the HasEdge predicate on the "parent" edge with a given conditions (other predicates). +func HasParentWith(preds ...predicate.IntSID) predicate.IntSID { + return predicate.IntSID(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, ParentTable, ParentColumn), + ) + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasChildren applies the HasEdge predicate on the "children" edge. +func HasChildren() predicate.IntSID { + return predicate.IntSID(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ChildrenTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, ChildrenTable, ChildrenColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasChildrenWith applies the HasEdge predicate on the "children" edge with a given conditions (other predicates). +func HasChildrenWith(preds ...predicate.IntSID) predicate.IntSID { + return predicate.IntSID(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, ChildrenTable, ChildrenColumn), + ) + 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.IntSID) predicate.IntSID { + return predicate.IntSID(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.IntSID) predicate.IntSID { + return predicate.IntSID(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.IntSID) predicate.IntSID { + return predicate.IntSID(func(s *sql.Selector) { + p(s.Not()) + }) +} diff --git a/entc/integration/customid/ent/intsid_create.go b/entc/integration/customid/ent/intsid_create.go new file mode 100644 index 000000000..392c9c045 --- /dev/null +++ b/entc/integration/customid/ent/intsid_create.go @@ -0,0 +1,547 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/customid/ent/intsid" + "entgo.io/ent/entc/integration/customid/sid" + "entgo.io/ent/schema/field" +) + +// IntSIDCreate is the builder for creating a IntSID entity. +type IntSIDCreate struct { + config + mutation *IntSIDMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetID sets the "id" field. +func (isc *IntSIDCreate) SetID(s sid.ID) *IntSIDCreate { + isc.mutation.SetID(s) + return isc +} + +// SetParentID sets the "parent" edge to the IntSID entity by ID. +func (isc *IntSIDCreate) SetParentID(id sid.ID) *IntSIDCreate { + isc.mutation.SetParentID(id) + return isc +} + +// SetNillableParentID sets the "parent" edge to the IntSID entity by ID if the given value is not nil. +func (isc *IntSIDCreate) SetNillableParentID(id *sid.ID) *IntSIDCreate { + if id != nil { + isc = isc.SetParentID(*id) + } + return isc +} + +// SetParent sets the "parent" edge to the IntSID entity. +func (isc *IntSIDCreate) SetParent(i *IntSID) *IntSIDCreate { + return isc.SetParentID(i.ID) +} + +// AddChildIDs adds the "children" edge to the IntSID entity by IDs. +func (isc *IntSIDCreate) AddChildIDs(ids ...sid.ID) *IntSIDCreate { + isc.mutation.AddChildIDs(ids...) + return isc +} + +// AddChildren adds the "children" edges to the IntSID entity. +func (isc *IntSIDCreate) AddChildren(i ...*IntSID) *IntSIDCreate { + ids := make([]sid.ID, len(i)) + for j := range i { + ids[j] = i[j].ID + } + return isc.AddChildIDs(ids...) +} + +// Mutation returns the IntSIDMutation object of the builder. +func (isc *IntSIDCreate) Mutation() *IntSIDMutation { + return isc.mutation +} + +// Save creates the IntSID in the database. +func (isc *IntSIDCreate) Save(ctx context.Context) (*IntSID, error) { + var ( + err error + node *IntSID + ) + if len(isc.hooks) == 0 { + if err = isc.check(); err != nil { + return nil, err + } + node, err = isc.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*IntSIDMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = isc.check(); err != nil { + return nil, err + } + isc.mutation = mutation + if node, err = isc.sqlSave(ctx); err != nil { + return nil, err + } + mutation.id = &node.ID + mutation.done = true + return node, err + }) + for i := len(isc.hooks) - 1; i >= 0; i-- { + if isc.hooks[i] == nil { + return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = isc.hooks[i](mut) + } + v, err := mut.Mutate(ctx, isc.mutation) + if err != nil { + return nil, err + } + nv, ok := v.(*IntSID) + if !ok { + return nil, fmt.Errorf("unexpected node type %T returned from IntSIDMutation", v) + } + node = nv + } + return node, err +} + +// SaveX calls Save and panics if Save returns an error. +func (isc *IntSIDCreate) SaveX(ctx context.Context) *IntSID { + v, err := isc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (isc *IntSIDCreate) Exec(ctx context.Context) error { + _, err := isc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (isc *IntSIDCreate) ExecX(ctx context.Context) { + if err := isc.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (isc *IntSIDCreate) check() error { + return nil +} + +func (isc *IntSIDCreate) sqlSave(ctx context.Context) (*IntSID, error) { + _node, _spec := isc.createSpec() + if err := sqlgraph.CreateNode(ctx, isc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: 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 (isc *IntSIDCreate) createSpec() (*IntSID, *sqlgraph.CreateSpec) { + var ( + _node = &IntSID{config: isc.config} + _spec = &sqlgraph.CreateSpec{ + Table: intsid.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt64, + Column: intsid.FieldID, + }, + } + ) + _spec.OnConflict = isc.conflict + if id, ok := isc.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = &id + } + if nodes := isc.mutation.ParentIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: intsid.ParentTable, + Columns: []string{intsid.ParentColumn}, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt64, + Column: intsid.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.int_sid_parent = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := isc.mutation.ChildrenIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: intsid.ChildrenTable, + Columns: []string{intsid.ChildrenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt64, + Column: intsid.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.IntSID.Create(). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// Exec(ctx) +// +func (isc *IntSIDCreate) OnConflict(opts ...sql.ConflictOption) *IntSIDUpsertOne { + isc.conflict = opts + return &IntSIDUpsertOne{ + create: isc, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.IntSID.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +// +func (isc *IntSIDCreate) OnConflictColumns(columns ...string) *IntSIDUpsertOne { + isc.conflict = append(isc.conflict, sql.ConflictColumns(columns...)) + return &IntSIDUpsertOne{ + create: isc, + } +} + +type ( + // IntSIDUpsertOne is the builder for "upsert"-ing + // one IntSID node. + IntSIDUpsertOne struct { + create *IntSIDCreate + } + + // IntSIDUpsert is the "OnConflict" setter. + IntSIDUpsert 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.IntSID.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(intsid.FieldID) +// }), +// ). +// Exec(ctx) +// +func (u *IntSIDUpsertOne) UpdateNewValues() *IntSIDUpsertOne { + 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(intsid.FieldID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.IntSID.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +// +func (u *IntSIDUpsertOne) Ignore() *IntSIDUpsertOne { + 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 *IntSIDUpsertOne) DoNothing() *IntSIDUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the IntSIDCreate.OnConflict +// documentation for more info. +func (u *IntSIDUpsertOne) Update(set func(*IntSIDUpsert)) *IntSIDUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&IntSIDUpsert{UpdateSet: update}) + })) + return u +} + +// Exec executes the query. +func (u *IntSIDUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("ent: missing options for IntSIDCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *IntSIDUpsertOne) 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 *IntSIDUpsertOne) ID(ctx context.Context) (id sid.ID, err error) { + 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 *IntSIDUpsertOne) IDX(ctx context.Context) sid.ID { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// IntSIDCreateBulk is the builder for creating many IntSID entities in bulk. +type IntSIDCreateBulk struct { + config + builders []*IntSIDCreate + conflict []sql.ConflictOption +} + +// Save creates the IntSID entities in the database. +func (iscb *IntSIDCreateBulk) Save(ctx context.Context) ([]*IntSID, error) { + specs := make([]*sqlgraph.CreateSpec, len(iscb.builders)) + nodes := make([]*IntSID, len(iscb.builders)) + mutators := make([]Mutator, len(iscb.builders)) + for i := range iscb.builders { + func(i int, root context.Context) { + builder := iscb.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*IntSIDMutation) + 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, iscb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = iscb.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, iscb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + if specs[i].ID.Value != nil { + if err := nodes[i].ID.Scan(specs[i].ID.Value); err != nil { + return nil, err + } + } + 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, iscb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (iscb *IntSIDCreateBulk) SaveX(ctx context.Context) []*IntSID { + v, err := iscb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (iscb *IntSIDCreateBulk) Exec(ctx context.Context) error { + _, err := iscb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (iscb *IntSIDCreateBulk) ExecX(ctx context.Context) { + if err := iscb.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.IntSID.CreateBulk(builders...). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// Exec(ctx) +// +func (iscb *IntSIDCreateBulk) OnConflict(opts ...sql.ConflictOption) *IntSIDUpsertBulk { + iscb.conflict = opts + return &IntSIDUpsertBulk{ + create: iscb, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.IntSID.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +// +func (iscb *IntSIDCreateBulk) OnConflictColumns(columns ...string) *IntSIDUpsertBulk { + iscb.conflict = append(iscb.conflict, sql.ConflictColumns(columns...)) + return &IntSIDUpsertBulk{ + create: iscb, + } +} + +// IntSIDUpsertBulk is the builder for "upsert"-ing +// a bulk of IntSID nodes. +type IntSIDUpsertBulk struct { + create *IntSIDCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.IntSID.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(intsid.FieldID) +// }), +// ). +// Exec(ctx) +// +func (u *IntSIDUpsertBulk) UpdateNewValues() *IntSIDUpsertBulk { + 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(intsid.FieldID) + return + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.IntSID.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +// +func (u *IntSIDUpsertBulk) Ignore() *IntSIDUpsertBulk { + 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 *IntSIDUpsertBulk) DoNothing() *IntSIDUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the IntSIDCreateBulk.OnConflict +// documentation for more info. +func (u *IntSIDUpsertBulk) Update(set func(*IntSIDUpsert)) *IntSIDUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&IntSIDUpsert{UpdateSet: update}) + })) + return u +} + +// Exec executes the query. +func (u *IntSIDUpsertBulk) 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 IntSIDCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("ent: missing options for IntSIDCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *IntSIDUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entc/integration/customid/ent/intsid_delete.go b/entc/integration/customid/ent/intsid_delete.go new file mode 100644 index 000000000..06873b56e --- /dev/null +++ b/entc/integration/customid/ent/intsid_delete.go @@ -0,0 +1,119 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/customid/ent/intsid" + "entgo.io/ent/entc/integration/customid/ent/predicate" + "entgo.io/ent/schema/field" +) + +// IntSIDDelete is the builder for deleting a IntSID entity. +type IntSIDDelete struct { + config + hooks []Hook + mutation *IntSIDMutation +} + +// Where appends a list predicates to the IntSIDDelete builder. +func (isd *IntSIDDelete) Where(ps ...predicate.IntSID) *IntSIDDelete { + isd.mutation.Where(ps...) + return isd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (isd *IntSIDDelete) Exec(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(isd.hooks) == 0 { + affected, err = isd.sqlExec(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*IntSIDMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + isd.mutation = mutation + affected, err = isd.sqlExec(ctx) + mutation.done = true + return affected, err + }) + for i := len(isd.hooks) - 1; i >= 0; i-- { + if isd.hooks[i] == nil { + return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = isd.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, isd.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// ExecX is like Exec, but panics if an error occurs. +func (isd *IntSIDDelete) ExecX(ctx context.Context) int { + n, err := isd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (isd *IntSIDDelete) sqlExec(ctx context.Context) (int, error) { + _spec := &sqlgraph.DeleteSpec{ + Node: &sqlgraph.NodeSpec{ + Table: intsid.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt64, + Column: intsid.FieldID, + }, + }, + } + if ps := isd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, isd.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return affected, err +} + +// IntSIDDeleteOne is the builder for deleting a single IntSID entity. +type IntSIDDeleteOne struct { + isd *IntSIDDelete +} + +// Exec executes the deletion query. +func (isdo *IntSIDDeleteOne) Exec(ctx context.Context) error { + n, err := isdo.isd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{intsid.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (isdo *IntSIDDeleteOne) ExecX(ctx context.Context) { + isdo.isd.ExecX(ctx) +} diff --git a/entc/integration/customid/ent/intsid_query.go b/entc/integration/customid/ent/intsid_query.go new file mode 100644 index 000000000..8c015296a --- /dev/null +++ b/entc/integration/customid/ent/intsid_query.go @@ -0,0 +1,653 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "database/sql/driver" + "fmt" + "math" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/customid/ent/intsid" + "entgo.io/ent/entc/integration/customid/ent/predicate" + "entgo.io/ent/entc/integration/customid/sid" + "entgo.io/ent/schema/field" +) + +// IntSIDQuery is the builder for querying IntSID entities. +type IntSIDQuery struct { + config + limit *int + offset *int + unique *bool + order []OrderFunc + fields []string + predicates []predicate.IntSID + // eager-loading edges. + withParent *IntSIDQuery + withChildren *IntSIDQuery + 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 IntSIDQuery builder. +func (isq *IntSIDQuery) Where(ps ...predicate.IntSID) *IntSIDQuery { + isq.predicates = append(isq.predicates, ps...) + return isq +} + +// Limit adds a limit step to the query. +func (isq *IntSIDQuery) Limit(limit int) *IntSIDQuery { + isq.limit = &limit + return isq +} + +// Offset adds an offset step to the query. +func (isq *IntSIDQuery) Offset(offset int) *IntSIDQuery { + isq.offset = &offset + return isq +} + +// 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 (isq *IntSIDQuery) Unique(unique bool) *IntSIDQuery { + isq.unique = &unique + return isq +} + +// Order adds an order step to the query. +func (isq *IntSIDQuery) Order(o ...OrderFunc) *IntSIDQuery { + isq.order = append(isq.order, o...) + return isq +} + +// QueryParent chains the current query on the "parent" edge. +func (isq *IntSIDQuery) QueryParent() *IntSIDQuery { + query := &IntSIDQuery{config: isq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := isq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := isq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(intsid.Table, intsid.FieldID, selector), + sqlgraph.To(intsid.Table, intsid.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, intsid.ParentTable, intsid.ParentColumn), + ) + fromU = sqlgraph.SetNeighbors(isq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryChildren chains the current query on the "children" edge. +func (isq *IntSIDQuery) QueryChildren() *IntSIDQuery { + query := &IntSIDQuery{config: isq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := isq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := isq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(intsid.Table, intsid.FieldID, selector), + sqlgraph.To(intsid.Table, intsid.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, intsid.ChildrenTable, intsid.ChildrenColumn), + ) + fromU = sqlgraph.SetNeighbors(isq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first IntSID entity from the query. +// Returns a *NotFoundError when no IntSID was found. +func (isq *IntSIDQuery) First(ctx context.Context) (*IntSID, error) { + nodes, err := isq.Limit(1).All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{intsid.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (isq *IntSIDQuery) FirstX(ctx context.Context) *IntSID { + node, err := isq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first IntSID ID from the query. +// Returns a *NotFoundError when no IntSID ID was found. +func (isq *IntSIDQuery) FirstID(ctx context.Context) (id sid.ID, err error) { + var ids []sid.ID + if ids, err = isq.Limit(1).IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{intsid.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (isq *IntSIDQuery) FirstIDX(ctx context.Context) sid.ID { + id, err := isq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single IntSID entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one IntSID entity is found. +// Returns a *NotFoundError when no IntSID entities are found. +func (isq *IntSIDQuery) Only(ctx context.Context) (*IntSID, error) { + nodes, err := isq.Limit(2).All(ctx) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{intsid.Label} + default: + return nil, &NotSingularError{intsid.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (isq *IntSIDQuery) OnlyX(ctx context.Context) *IntSID { + node, err := isq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only IntSID ID in the query. +// Returns a *NotSingularError when more than one IntSID ID is found. +// Returns a *NotFoundError when no entities are found. +func (isq *IntSIDQuery) OnlyID(ctx context.Context) (id sid.ID, err error) { + var ids []sid.ID + if ids, err = isq.Limit(2).IDs(ctx); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{intsid.Label} + default: + err = &NotSingularError{intsid.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (isq *IntSIDQuery) OnlyIDX(ctx context.Context) sid.ID { + id, err := isq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of IntSIDs. +func (isq *IntSIDQuery) All(ctx context.Context) ([]*IntSID, error) { + if err := isq.prepareQuery(ctx); err != nil { + return nil, err + } + return isq.sqlAll(ctx) +} + +// AllX is like All, but panics if an error occurs. +func (isq *IntSIDQuery) AllX(ctx context.Context) []*IntSID { + nodes, err := isq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of IntSID IDs. +func (isq *IntSIDQuery) IDs(ctx context.Context) ([]sid.ID, error) { + var ids []sid.ID + if err := isq.Select(intsid.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (isq *IntSIDQuery) IDsX(ctx context.Context) []sid.ID { + ids, err := isq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (isq *IntSIDQuery) Count(ctx context.Context) (int, error) { + if err := isq.prepareQuery(ctx); err != nil { + return 0, err + } + return isq.sqlCount(ctx) +} + +// CountX is like Count, but panics if an error occurs. +func (isq *IntSIDQuery) CountX(ctx context.Context) int { + count, err := isq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (isq *IntSIDQuery) Exist(ctx context.Context) (bool, error) { + if err := isq.prepareQuery(ctx); err != nil { + return false, err + } + return isq.sqlExist(ctx) +} + +// ExistX is like Exist, but panics if an error occurs. +func (isq *IntSIDQuery) ExistX(ctx context.Context) bool { + exist, err := isq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the IntSIDQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (isq *IntSIDQuery) Clone() *IntSIDQuery { + if isq == nil { + return nil + } + return &IntSIDQuery{ + config: isq.config, + limit: isq.limit, + offset: isq.offset, + order: append([]OrderFunc{}, isq.order...), + predicates: append([]predicate.IntSID{}, isq.predicates...), + withParent: isq.withParent.Clone(), + withChildren: isq.withChildren.Clone(), + // clone intermediate query. + sql: isq.sql.Clone(), + path: isq.path, + unique: isq.unique, + } +} + +// WithParent tells the query-builder to eager-load the nodes that are connected to +// the "parent" edge. The optional arguments are used to configure the query builder of the edge. +func (isq *IntSIDQuery) WithParent(opts ...func(*IntSIDQuery)) *IntSIDQuery { + query := &IntSIDQuery{config: isq.config} + for _, opt := range opts { + opt(query) + } + isq.withParent = query + return isq +} + +// WithChildren tells the query-builder to eager-load the nodes that are connected to +// the "children" edge. The optional arguments are used to configure the query builder of the edge. +func (isq *IntSIDQuery) WithChildren(opts ...func(*IntSIDQuery)) *IntSIDQuery { + query := &IntSIDQuery{config: isq.config} + for _, opt := range opts { + opt(query) + } + isq.withChildren = query + return isq +} + +// 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 (isq *IntSIDQuery) GroupBy(field string, fields ...string) *IntSIDGroupBy { + grbuild := &IntSIDGroupBy{config: isq.config} + grbuild.fields = append([]string{field}, fields...) + grbuild.path = func(ctx context.Context) (prev *sql.Selector, err error) { + if err := isq.prepareQuery(ctx); err != nil { + return nil, err + } + return isq.sqlQuery(ctx), nil + } + grbuild.label = intsid.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 (isq *IntSIDQuery) Select(fields ...string) *IntSIDSelect { + isq.fields = append(isq.fields, fields...) + selbuild := &IntSIDSelect{IntSIDQuery: isq} + selbuild.label = intsid.Label + selbuild.flds, selbuild.scan = &isq.fields, selbuild.Scan + return selbuild +} + +func (isq *IntSIDQuery) prepareQuery(ctx context.Context) error { + for _, f := range isq.fields { + if !intsid.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if isq.path != nil { + prev, err := isq.path(ctx) + if err != nil { + return err + } + isq.sql = prev + } + return nil +} + +func (isq *IntSIDQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*IntSID, error) { + var ( + nodes = []*IntSID{} + withFKs = isq.withFKs + _spec = isq.querySpec() + loadedTypes = [2]bool{ + isq.withParent != nil, + isq.withChildren != nil, + } + ) + if isq.withParent != nil { + withFKs = true + } + if withFKs { + _spec.Node.Columns = append(_spec.Node.Columns, intsid.ForeignKeys...) + } + _spec.ScanValues = func(columns []string) ([]interface{}, error) { + return (*IntSID).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []interface{}) error { + node := &IntSID{config: isq.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, isq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + + if query := isq.withParent; query != nil { + ids := make([]sid.ID, 0, len(nodes)) + nodeids := make(map[sid.ID][]*IntSID) + for i := range nodes { + if nodes[i].int_sid_parent == nil { + continue + } + fk := *nodes[i].int_sid_parent + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + query.Where(intsid.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 "int_sid_parent" returned %v`, n.ID) + } + for i := range nodes { + nodes[i].Edges.Parent = n + } + } + } + + if query := isq.withChildren; query != nil { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[sid.ID]*IntSID) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + nodes[i].Edges.Children = []*IntSID{} + } + query.withFKs = true + query.Where(predicate.IntSID(func(s *sql.Selector) { + s.Where(sql.InValues(intsid.ChildrenColumn, fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, n := range neighbors { + fk := n.int_sid_parent + if fk == nil { + return nil, fmt.Errorf(`foreign-key "int_sid_parent" is nil for node %v`, n.ID) + } + node, ok := nodeids[*fk] + if !ok { + return nil, fmt.Errorf(`unexpected foreign-key "int_sid_parent" returned %v for node %v`, *fk, n.ID) + } + node.Edges.Children = append(node.Edges.Children, n) + } + } + + return nodes, nil +} + +func (isq *IntSIDQuery) sqlCount(ctx context.Context) (int, error) { + _spec := isq.querySpec() + _spec.Node.Columns = isq.fields + if len(isq.fields) > 0 { + _spec.Unique = isq.unique != nil && *isq.unique + } + return sqlgraph.CountNodes(ctx, isq.driver, _spec) +} + +func (isq *IntSIDQuery) sqlExist(ctx context.Context) (bool, error) { + n, err := isq.sqlCount(ctx) + if err != nil { + return false, fmt.Errorf("ent: check existence: %w", err) + } + return n > 0, nil +} + +func (isq *IntSIDQuery) querySpec() *sqlgraph.QuerySpec { + _spec := &sqlgraph.QuerySpec{ + Node: &sqlgraph.NodeSpec{ + Table: intsid.Table, + Columns: intsid.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt64, + Column: intsid.FieldID, + }, + }, + From: isq.sql, + Unique: true, + } + if unique := isq.unique; unique != nil { + _spec.Unique = *unique + } + if fields := isq.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, intsid.FieldID) + for i := range fields { + if fields[i] != intsid.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := isq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := isq.limit; limit != nil { + _spec.Limit = *limit + } + if offset := isq.offset; offset != nil { + _spec.Offset = *offset + } + if ps := isq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (isq *IntSIDQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(isq.driver.Dialect()) + t1 := builder.Table(intsid.Table) + columns := isq.fields + if len(columns) == 0 { + columns = intsid.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if isq.sql != nil { + selector = isq.sql + selector.Select(selector.Columns(columns...)...) + } + if isq.unique != nil && *isq.unique { + selector.Distinct() + } + for _, p := range isq.predicates { + p(selector) + } + for _, p := range isq.order { + p(selector) + } + if offset := isq.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 := isq.limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// IntSIDGroupBy is the group-by builder for IntSID entities. +type IntSIDGroupBy 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 (isgb *IntSIDGroupBy) Aggregate(fns ...AggregateFunc) *IntSIDGroupBy { + isgb.fns = append(isgb.fns, fns...) + return isgb +} + +// Scan applies the group-by query and scans the result into the given value. +func (isgb *IntSIDGroupBy) Scan(ctx context.Context, v interface{}) error { + query, err := isgb.path(ctx) + if err != nil { + return err + } + isgb.sql = query + return isgb.sqlScan(ctx, v) +} + +func (isgb *IntSIDGroupBy) sqlScan(ctx context.Context, v interface{}) error { + for _, f := range isgb.fields { + if !intsid.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + } + } + selector := isgb.sqlQuery() + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := isgb.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +func (isgb *IntSIDGroupBy) sqlQuery() *sql.Selector { + selector := isgb.sql.Select() + aggregation := make([]string, 0, len(isgb.fns)) + for _, fn := range isgb.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(isgb.fields)+len(isgb.fns)) + for _, f := range isgb.fields { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + return selector.GroupBy(selector.Columns(isgb.fields...)...) +} + +// IntSIDSelect is the builder for selecting fields of IntSID entities. +type IntSIDSelect struct { + *IntSIDQuery + selector + // intermediate query (i.e. traversal path). + sql *sql.Selector +} + +// Scan applies the selector query and scans the result into the given value. +func (iss *IntSIDSelect) Scan(ctx context.Context, v interface{}) error { + if err := iss.prepareQuery(ctx); err != nil { + return err + } + iss.sql = iss.IntSIDQuery.sqlQuery(ctx) + return iss.sqlScan(ctx, v) +} + +func (iss *IntSIDSelect) sqlScan(ctx context.Context, v interface{}) error { + rows := &sql.Rows{} + query, args := iss.sql.Query() + if err := iss.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/intsid_update.go b/entc/integration/customid/ent/intsid_update.go new file mode 100644 index 000000000..869f404fd --- /dev/null +++ b/entc/integration/customid/ent/intsid_update.go @@ -0,0 +1,550 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/customid/ent/intsid" + "entgo.io/ent/entc/integration/customid/ent/predicate" + "entgo.io/ent/entc/integration/customid/sid" + "entgo.io/ent/schema/field" +) + +// IntSIDUpdate is the builder for updating IntSID entities. +type IntSIDUpdate struct { + config + hooks []Hook + mutation *IntSIDMutation +} + +// Where appends a list predicates to the IntSIDUpdate builder. +func (isu *IntSIDUpdate) Where(ps ...predicate.IntSID) *IntSIDUpdate { + isu.mutation.Where(ps...) + return isu +} + +// SetParentID sets the "parent" edge to the IntSID entity by ID. +func (isu *IntSIDUpdate) SetParentID(id sid.ID) *IntSIDUpdate { + isu.mutation.SetParentID(id) + return isu +} + +// SetNillableParentID sets the "parent" edge to the IntSID entity by ID if the given value is not nil. +func (isu *IntSIDUpdate) SetNillableParentID(id *sid.ID) *IntSIDUpdate { + if id != nil { + isu = isu.SetParentID(*id) + } + return isu +} + +// SetParent sets the "parent" edge to the IntSID entity. +func (isu *IntSIDUpdate) SetParent(i *IntSID) *IntSIDUpdate { + return isu.SetParentID(i.ID) +} + +// AddChildIDs adds the "children" edge to the IntSID entity by IDs. +func (isu *IntSIDUpdate) AddChildIDs(ids ...sid.ID) *IntSIDUpdate { + isu.mutation.AddChildIDs(ids...) + return isu +} + +// AddChildren adds the "children" edges to the IntSID entity. +func (isu *IntSIDUpdate) AddChildren(i ...*IntSID) *IntSIDUpdate { + ids := make([]sid.ID, len(i)) + for j := range i { + ids[j] = i[j].ID + } + return isu.AddChildIDs(ids...) +} + +// Mutation returns the IntSIDMutation object of the builder. +func (isu *IntSIDUpdate) Mutation() *IntSIDMutation { + return isu.mutation +} + +// ClearParent clears the "parent" edge to the IntSID entity. +func (isu *IntSIDUpdate) ClearParent() *IntSIDUpdate { + isu.mutation.ClearParent() + return isu +} + +// ClearChildren clears all "children" edges to the IntSID entity. +func (isu *IntSIDUpdate) ClearChildren() *IntSIDUpdate { + isu.mutation.ClearChildren() + return isu +} + +// RemoveChildIDs removes the "children" edge to IntSID entities by IDs. +func (isu *IntSIDUpdate) RemoveChildIDs(ids ...sid.ID) *IntSIDUpdate { + isu.mutation.RemoveChildIDs(ids...) + return isu +} + +// RemoveChildren removes "children" edges to IntSID entities. +func (isu *IntSIDUpdate) RemoveChildren(i ...*IntSID) *IntSIDUpdate { + ids := make([]sid.ID, len(i)) + for j := range i { + ids[j] = i[j].ID + } + return isu.RemoveChildIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (isu *IntSIDUpdate) Save(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(isu.hooks) == 0 { + affected, err = isu.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*IntSIDMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + isu.mutation = mutation + affected, err = isu.sqlSave(ctx) + mutation.done = true + return affected, err + }) + for i := len(isu.hooks) - 1; i >= 0; i-- { + if isu.hooks[i] == nil { + return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = isu.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, isu.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// SaveX is like Save, but panics if an error occurs. +func (isu *IntSIDUpdate) SaveX(ctx context.Context) int { + affected, err := isu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (isu *IntSIDUpdate) Exec(ctx context.Context) error { + _, err := isu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (isu *IntSIDUpdate) ExecX(ctx context.Context) { + if err := isu.Exec(ctx); err != nil { + panic(err) + } +} + +func (isu *IntSIDUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: intsid.Table, + Columns: intsid.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt64, + Column: intsid.FieldID, + }, + }, + } + if ps := isu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if isu.mutation.ParentCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: intsid.ParentTable, + Columns: []string{intsid.ParentColumn}, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt64, + Column: intsid.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := isu.mutation.ParentIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: intsid.ParentTable, + Columns: []string{intsid.ParentColumn}, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt64, + Column: intsid.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if isu.mutation.ChildrenCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: intsid.ChildrenTable, + Columns: []string{intsid.ChildrenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt64, + Column: intsid.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := isu.mutation.RemovedChildrenIDs(); len(nodes) > 0 && !isu.mutation.ChildrenCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: intsid.ChildrenTable, + Columns: []string{intsid.ChildrenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt64, + Column: intsid.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := isu.mutation.ChildrenIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: intsid.ChildrenTable, + Columns: []string{intsid.ChildrenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt64, + Column: intsid.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, isu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{intsid.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + return n, nil +} + +// IntSIDUpdateOne is the builder for updating a single IntSID entity. +type IntSIDUpdateOne struct { + config + fields []string + hooks []Hook + mutation *IntSIDMutation +} + +// SetParentID sets the "parent" edge to the IntSID entity by ID. +func (isuo *IntSIDUpdateOne) SetParentID(id sid.ID) *IntSIDUpdateOne { + isuo.mutation.SetParentID(id) + return isuo +} + +// SetNillableParentID sets the "parent" edge to the IntSID entity by ID if the given value is not nil. +func (isuo *IntSIDUpdateOne) SetNillableParentID(id *sid.ID) *IntSIDUpdateOne { + if id != nil { + isuo = isuo.SetParentID(*id) + } + return isuo +} + +// SetParent sets the "parent" edge to the IntSID entity. +func (isuo *IntSIDUpdateOne) SetParent(i *IntSID) *IntSIDUpdateOne { + return isuo.SetParentID(i.ID) +} + +// AddChildIDs adds the "children" edge to the IntSID entity by IDs. +func (isuo *IntSIDUpdateOne) AddChildIDs(ids ...sid.ID) *IntSIDUpdateOne { + isuo.mutation.AddChildIDs(ids...) + return isuo +} + +// AddChildren adds the "children" edges to the IntSID entity. +func (isuo *IntSIDUpdateOne) AddChildren(i ...*IntSID) *IntSIDUpdateOne { + ids := make([]sid.ID, len(i)) + for j := range i { + ids[j] = i[j].ID + } + return isuo.AddChildIDs(ids...) +} + +// Mutation returns the IntSIDMutation object of the builder. +func (isuo *IntSIDUpdateOne) Mutation() *IntSIDMutation { + return isuo.mutation +} + +// ClearParent clears the "parent" edge to the IntSID entity. +func (isuo *IntSIDUpdateOne) ClearParent() *IntSIDUpdateOne { + isuo.mutation.ClearParent() + return isuo +} + +// ClearChildren clears all "children" edges to the IntSID entity. +func (isuo *IntSIDUpdateOne) ClearChildren() *IntSIDUpdateOne { + isuo.mutation.ClearChildren() + return isuo +} + +// RemoveChildIDs removes the "children" edge to IntSID entities by IDs. +func (isuo *IntSIDUpdateOne) RemoveChildIDs(ids ...sid.ID) *IntSIDUpdateOne { + isuo.mutation.RemoveChildIDs(ids...) + return isuo +} + +// RemoveChildren removes "children" edges to IntSID entities. +func (isuo *IntSIDUpdateOne) RemoveChildren(i ...*IntSID) *IntSIDUpdateOne { + ids := make([]sid.ID, len(i)) + for j := range i { + ids[j] = i[j].ID + } + return isuo.RemoveChildIDs(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 (isuo *IntSIDUpdateOne) Select(field string, fields ...string) *IntSIDUpdateOne { + isuo.fields = append([]string{field}, fields...) + return isuo +} + +// Save executes the query and returns the updated IntSID entity. +func (isuo *IntSIDUpdateOne) Save(ctx context.Context) (*IntSID, error) { + var ( + err error + node *IntSID + ) + if len(isuo.hooks) == 0 { + node, err = isuo.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*IntSIDMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + isuo.mutation = mutation + node, err = isuo.sqlSave(ctx) + mutation.done = true + return node, err + }) + for i := len(isuo.hooks) - 1; i >= 0; i-- { + if isuo.hooks[i] == nil { + return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = isuo.hooks[i](mut) + } + v, err := mut.Mutate(ctx, isuo.mutation) + if err != nil { + return nil, err + } + nv, ok := v.(*IntSID) + if !ok { + return nil, fmt.Errorf("unexpected node type %T returned from IntSIDMutation", v) + } + node = nv + } + return node, err +} + +// SaveX is like Save, but panics if an error occurs. +func (isuo *IntSIDUpdateOne) SaveX(ctx context.Context) *IntSID { + node, err := isuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (isuo *IntSIDUpdateOne) Exec(ctx context.Context) error { + _, err := isuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (isuo *IntSIDUpdateOne) ExecX(ctx context.Context) { + if err := isuo.Exec(ctx); err != nil { + panic(err) + } +} + +func (isuo *IntSIDUpdateOne) sqlSave(ctx context.Context) (_node *IntSID, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: intsid.Table, + Columns: intsid.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt64, + Column: intsid.FieldID, + }, + }, + } + id, ok := isuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "IntSID.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := isuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, intsid.FieldID) + for _, f := range fields { + if !intsid.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != intsid.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := isuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if isuo.mutation.ParentCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: intsid.ParentTable, + Columns: []string{intsid.ParentColumn}, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt64, + Column: intsid.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := isuo.mutation.ParentIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: intsid.ParentTable, + Columns: []string{intsid.ParentColumn}, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt64, + Column: intsid.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if isuo.mutation.ChildrenCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: intsid.ChildrenTable, + Columns: []string{intsid.ChildrenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt64, + Column: intsid.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := isuo.mutation.RemovedChildrenIDs(); len(nodes) > 0 && !isuo.mutation.ChildrenCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: intsid.ChildrenTable, + Columns: []string{intsid.ChildrenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt64, + Column: intsid.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := isuo.mutation.ChildrenIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: intsid.ChildrenTable, + Columns: []string{intsid.ChildrenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt64, + Column: intsid.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &IntSID{config: isuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, isuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{intsid.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + return _node, nil +} diff --git a/entc/integration/customid/ent/migrate/schema.go b/entc/integration/customid/ent/migrate/schema.go index a2f686917..f4e33216f 100644 --- a/entc/integration/customid/ent/migrate/schema.go +++ b/entc/integration/customid/ent/migrate/schema.go @@ -115,6 +115,25 @@ var ( Columns: GroupsColumns, PrimaryKey: []*schema.Column{GroupsColumns[0]}, } + // IntSiDsColumns holds the columns for the "int_si_ds" table. + IntSiDsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt64, Increment: true}, + {Name: "int_sid_parent", Type: field.TypeInt64, Nullable: true}, + } + // IntSiDsTable holds the schema information for the "int_si_ds" table. + IntSiDsTable = &schema.Table{ + Name: "int_si_ds", + Columns: IntSiDsColumns, + PrimaryKey: []*schema.Column{IntSiDsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "int_si_ds_int_si_ds_parent", + Columns: []*schema.Column{IntSiDsColumns[1]}, + RefColumns: []*schema.Column{IntSiDsColumns[0]}, + OnDelete: schema.SetNull, + }, + }, + } // MixinIdsColumns holds the columns for the "mixin_ids" table. MixinIdsColumns = []*schema.Column{ {Name: "id", Type: field.TypeUUID}, @@ -356,6 +375,7 @@ var ( DevicesTable, DocsTable, GroupsTable, + IntSiDsTable, MixinIdsTable, NotesTable, OthersTable, @@ -375,6 +395,7 @@ func init() { CarsTable.ForeignKeys[0].RefTable = PetsTable DevicesTable.ForeignKeys[0].RefTable = SessionsTable DocsTable.ForeignKeys[0].RefTable = DocsTable + IntSiDsTable.ForeignKeys[0].RefTable = IntSiDsTable NotesTable.ForeignKeys[0].RefTable = NotesTable PetsTable.ForeignKeys[0].RefTable = PetsTable PetsTable.ForeignKeys[1].RefTable = UsersTable diff --git a/entc/integration/customid/ent/mutation.go b/entc/integration/customid/ent/mutation.go index 422145662..d530f96ce 100644 --- a/entc/integration/customid/ent/mutation.go +++ b/entc/integration/customid/ent/mutation.go @@ -18,6 +18,7 @@ import ( "entgo.io/ent/entc/integration/customid/ent/device" "entgo.io/ent/entc/integration/customid/ent/doc" "entgo.io/ent/entc/integration/customid/ent/group" + "entgo.io/ent/entc/integration/customid/ent/intsid" "entgo.io/ent/entc/integration/customid/ent/mixinid" "entgo.io/ent/entc/integration/customid/ent/note" "entgo.io/ent/entc/integration/customid/ent/pet" @@ -47,6 +48,7 @@ const ( TypeDevice = "Device" TypeDoc = "Doc" TypeGroup = "Group" + TypeIntSID = "IntSID" TypeMixinID = "MixinID" TypeNote = "Note" TypeOther = "Other" @@ -2878,6 +2880,413 @@ func (m *GroupMutation) ResetEdge(name string) error { return fmt.Errorf("unknown Group edge %s", name) } +// IntSIDMutation represents an operation that mutates the IntSID nodes in the graph. +type IntSIDMutation struct { + config + op Op + typ string + id *sid.ID + clearedFields map[string]struct{} + parent *sid.ID + clearedparent bool + children map[sid.ID]struct{} + removedchildren map[sid.ID]struct{} + clearedchildren bool + done bool + oldValue func(context.Context) (*IntSID, error) + predicates []predicate.IntSID +} + +var _ ent.Mutation = (*IntSIDMutation)(nil) + +// intsidOption allows management of the mutation configuration using functional options. +type intsidOption func(*IntSIDMutation) + +// newIntSIDMutation creates new mutation for the IntSID entity. +func newIntSIDMutation(c config, op Op, opts ...intsidOption) *IntSIDMutation { + m := &IntSIDMutation{ + config: c, + op: op, + typ: TypeIntSID, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withIntSIDID sets the ID field of the mutation. +func withIntSIDID(id sid.ID) intsidOption { + return func(m *IntSIDMutation) { + var ( + err error + once sync.Once + value *IntSID + ) + m.oldValue = func(ctx context.Context) (*IntSID, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().IntSID.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withIntSID sets the old IntSID of the mutation. +func withIntSID(node *IntSID) intsidOption { + return func(m *IntSIDMutation) { + m.oldValue = func(context.Context) (*IntSID, 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 IntSIDMutation) 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 IntSIDMutation) 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 IntSID entities. +func (m *IntSIDMutation) 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 *IntSIDMutation) 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 *IntSIDMutation) 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().IntSID.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetParentID sets the "parent" edge to the IntSID entity by id. +func (m *IntSIDMutation) SetParentID(id sid.ID) { + m.parent = &id +} + +// ClearParent clears the "parent" edge to the IntSID entity. +func (m *IntSIDMutation) ClearParent() { + m.clearedparent = true +} + +// ParentCleared reports if the "parent" edge to the IntSID entity was cleared. +func (m *IntSIDMutation) ParentCleared() bool { + return m.clearedparent +} + +// ParentID returns the "parent" edge ID in the mutation. +func (m *IntSIDMutation) ParentID() (id sid.ID, exists bool) { + if m.parent != nil { + return *m.parent, true + } + return +} + +// ParentIDs returns the "parent" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// ParentID instead. It exists only for internal usage by the builders. +func (m *IntSIDMutation) ParentIDs() (ids []sid.ID) { + if id := m.parent; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetParent resets all changes to the "parent" edge. +func (m *IntSIDMutation) ResetParent() { + m.parent = nil + m.clearedparent = false +} + +// AddChildIDs adds the "children" edge to the IntSID entity by ids. +func (m *IntSIDMutation) AddChildIDs(ids ...sid.ID) { + if m.children == nil { + m.children = make(map[sid.ID]struct{}) + } + for i := range ids { + m.children[ids[i]] = struct{}{} + } +} + +// ClearChildren clears the "children" edge to the IntSID entity. +func (m *IntSIDMutation) ClearChildren() { + m.clearedchildren = true +} + +// ChildrenCleared reports if the "children" edge to the IntSID entity was cleared. +func (m *IntSIDMutation) ChildrenCleared() bool { + return m.clearedchildren +} + +// RemoveChildIDs removes the "children" edge to the IntSID entity by IDs. +func (m *IntSIDMutation) RemoveChildIDs(ids ...sid.ID) { + if m.removedchildren == nil { + m.removedchildren = make(map[sid.ID]struct{}) + } + for i := range ids { + delete(m.children, ids[i]) + m.removedchildren[ids[i]] = struct{}{} + } +} + +// RemovedChildren returns the removed IDs of the "children" edge to the IntSID entity. +func (m *IntSIDMutation) RemovedChildrenIDs() (ids []sid.ID) { + for id := range m.removedchildren { + ids = append(ids, id) + } + return +} + +// ChildrenIDs returns the "children" edge IDs in the mutation. +func (m *IntSIDMutation) ChildrenIDs() (ids []sid.ID) { + for id := range m.children { + ids = append(ids, id) + } + return +} + +// ResetChildren resets all changes to the "children" edge. +func (m *IntSIDMutation) ResetChildren() { + m.children = nil + m.clearedchildren = false + m.removedchildren = nil +} + +// Where appends a list predicates to the IntSIDMutation builder. +func (m *IntSIDMutation) Where(ps ...predicate.IntSID) { + m.predicates = append(m.predicates, ps...) +} + +// Op returns the operation name. +func (m *IntSIDMutation) Op() Op { + return m.op +} + +// Type returns the node type of this mutation (IntSID). +func (m *IntSIDMutation) 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 *IntSIDMutation) 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 *IntSIDMutation) 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 *IntSIDMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + return nil, fmt.Errorf("unknown IntSID 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 *IntSIDMutation) SetField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown IntSID field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *IntSIDMutation) 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 *IntSIDMutation) 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 *IntSIDMutation) AddField(name string, value ent.Value) error { + return fmt.Errorf("unknown IntSID numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *IntSIDMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *IntSIDMutation) 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 *IntSIDMutation) ClearField(name string) error { + return fmt.Errorf("unknown IntSID 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 *IntSIDMutation) ResetField(name string) error { + return fmt.Errorf("unknown IntSID field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *IntSIDMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.parent != nil { + edges = append(edges, intsid.EdgeParent) + } + if m.children != nil { + edges = append(edges, intsid.EdgeChildren) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *IntSIDMutation) AddedIDs(name string) []ent.Value { + switch name { + case intsid.EdgeParent: + if id := m.parent; id != nil { + return []ent.Value{*id} + } + case intsid.EdgeChildren: + ids := make([]ent.Value, 0, len(m.children)) + for id := range m.children { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *IntSIDMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + if m.removedchildren != nil { + edges = append(edges, intsid.EdgeChildren) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *IntSIDMutation) RemovedIDs(name string) []ent.Value { + switch name { + case intsid.EdgeChildren: + ids := make([]ent.Value, 0, len(m.removedchildren)) + for id := range m.removedchildren { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *IntSIDMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedparent { + edges = append(edges, intsid.EdgeParent) + } + if m.clearedchildren { + edges = append(edges, intsid.EdgeChildren) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *IntSIDMutation) EdgeCleared(name string) bool { + switch name { + case intsid.EdgeParent: + return m.clearedparent + case intsid.EdgeChildren: + return m.clearedchildren + } + 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 *IntSIDMutation) ClearEdge(name string) error { + switch name { + case intsid.EdgeParent: + m.ClearParent() + return nil + } + return fmt.Errorf("unknown IntSID 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 *IntSIDMutation) ResetEdge(name string) error { + switch name { + case intsid.EdgeParent: + m.ResetParent() + return nil + case intsid.EdgeChildren: + m.ResetChildren() + return nil + } + return fmt.Errorf("unknown IntSID edge %s", name) +} + // MixinIDMutation represents an operation that mutates the MixinID nodes in the graph. type MixinIDMutation struct { config diff --git a/entc/integration/customid/ent/predicate/predicate.go b/entc/integration/customid/ent/predicate/predicate.go index 0de8dbff9..a41f9b661 100644 --- a/entc/integration/customid/ent/predicate/predicate.go +++ b/entc/integration/customid/ent/predicate/predicate.go @@ -28,6 +28,9 @@ type Doc func(*sql.Selector) // Group is the predicate function for group builders. type Group func(*sql.Selector) +// IntSID is the predicate function for intsid builders. +type IntSID func(*sql.Selector) + // MixinID is the predicate function for mixinid builders. type MixinID func(*sql.Selector) diff --git a/entc/integration/customid/ent/schema/intsid.go b/entc/integration/customid/ent/schema/intsid.go new file mode 100644 index 000000000..b9669a3f5 --- /dev/null +++ b/entc/integration/customid/ent/schema/intsid.go @@ -0,0 +1,37 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +package schema + +import ( + "entgo.io/ent" + "entgo.io/ent/entc/integration/customid/sid" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" +) + +// IntSID holds the schema definition for the IntSID entity. +type IntSID struct { + ent.Schema +} + +// Fields of the IntSid. +func (IntSID) Fields() []ent.Field { + return []ent.Field{ + field.Int64("id"). + GoType(sid.New()). + Unique(). + Immutable(), + } +} + +// Edges of the IntSid. +func (IntSID) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("parent", IntSID.Type). + Unique(), + edge.From("children", IntSID.Type). + Ref("parent"), + } +} diff --git a/entc/integration/customid/ent/tx.go b/entc/integration/customid/ent/tx.go index e17692346..cdfd32d66 100644 --- a/entc/integration/customid/ent/tx.go +++ b/entc/integration/customid/ent/tx.go @@ -28,6 +28,8 @@ type Tx struct { Doc *DocClient // Group is the client for interacting with the Group builders. Group *GroupClient + // IntSID is the client for interacting with the IntSID builders. + IntSID *IntSIDClient // MixinID is the client for interacting with the MixinID builders. MixinID *MixinIDClient // Note is the client for interacting with the Note builders. @@ -185,6 +187,7 @@ func (tx *Tx) init() { tx.Device = NewDeviceClient(tx.config) tx.Doc = NewDocClient(tx.config) tx.Group = NewGroupClient(tx.config) + tx.IntSID = NewIntSIDClient(tx.config) tx.MixinID = NewMixinIDClient(tx.config) tx.Note = NewNoteClient(tx.config) tx.Other = NewOtherClient(tx.config)