From 7cac3b2ed53241bec217c2fe8b0fca131b3e7024 Mon Sep 17 00:00:00 2001 From: Ariel Mashraki <7413593+a8m@users.noreply.github.com> Date: Sat, 25 Jun 2022 20:23:43 +0300 Subject: [PATCH] entc/gen: support default id values for edge schemas (#2688) --- entc/gen/template/dialect/sql/update.tmpl | 5 + .../integration/edgeschema/edgeschema_test.go | 19 + entc/integration/edgeschema/ent/client.go | 291 ++++ entc/integration/edgeschema/ent/config.go | 2 + entc/integration/edgeschema/ent/ent.go | 4 + entc/integration/edgeschema/ent/hook/hook.go | 26 + .../edgeschema/ent/migrate/schema.go | 49 + entc/integration/edgeschema/ent/mutation.go | 1192 ++++++++++++++++- .../edgeschema/ent/predicate/predicate.go | 6 + entc/integration/edgeschema/ent/runtime.go | 12 + entc/integration/edgeschema/ent/schema/tag.go | 31 + .../edgeschema/ent/schema/tweet.go | 3 + .../edgeschema/ent/schema/tweettag.go | 45 + entc/integration/edgeschema/ent/tag.go | 141 ++ entc/integration/edgeschema/ent/tag/tag.go | 52 + entc/integration/edgeschema/ent/tag/where.go | 298 +++++ entc/integration/edgeschema/ent/tag_create.go | 304 +++++ entc/integration/edgeschema/ent/tag_delete.go | 115 ++ entc/integration/edgeschema/ent/tag_query.go | 686 ++++++++++ entc/integration/edgeschema/ent/tag_update.go | 676 ++++++++++ entc/integration/edgeschema/ent/tweet.go | 38 +- .../integration/edgeschema/ent/tweet/tweet.go | 19 + .../integration/edgeschema/ent/tweet/where.go | 56 + .../edgeschema/ent/tweet_create.go | 78 ++ .../integration/edgeschema/ent/tweet_query.go | 154 ++- .../edgeschema/ent/tweet_update.go | 405 ++++++ entc/integration/edgeschema/ent/tweettag.go | 179 +++ .../edgeschema/ent/tweettag/tweettag.go | 67 + .../edgeschema/ent/tweettag/where.go | 376 ++++++ .../edgeschema/ent/tweettag_create.go | 345 +++++ .../edgeschema/ent/tweettag_delete.go | 115 ++ .../edgeschema/ent/tweettag_query.go | 660 +++++++++ .../edgeschema/ent/tweettag_update.go | 532 ++++++++ entc/integration/edgeschema/ent/tx.go | 6 + 34 files changed, 6980 insertions(+), 7 deletions(-) create mode 100644 entc/integration/edgeschema/ent/schema/tag.go create mode 100644 entc/integration/edgeschema/ent/schema/tweettag.go create mode 100644 entc/integration/edgeschema/ent/tag.go create mode 100644 entc/integration/edgeschema/ent/tag/tag.go create mode 100644 entc/integration/edgeschema/ent/tag/where.go create mode 100644 entc/integration/edgeschema/ent/tag_create.go create mode 100644 entc/integration/edgeschema/ent/tag_delete.go create mode 100644 entc/integration/edgeschema/ent/tag_query.go create mode 100644 entc/integration/edgeschema/ent/tag_update.go create mode 100644 entc/integration/edgeschema/ent/tweettag.go create mode 100644 entc/integration/edgeschema/ent/tweettag/tweettag.go create mode 100644 entc/integration/edgeschema/ent/tweettag/where.go create mode 100644 entc/integration/edgeschema/ent/tweettag_create.go create mode 100644 entc/integration/edgeschema/ent/tweettag_delete.go create mode 100644 entc/integration/edgeschema/ent/tweettag_query.go create mode 100644 entc/integration/edgeschema/ent/tweettag_update.go diff --git a/entc/gen/template/dialect/sql/update.tmpl b/entc/gen/template/dialect/sql/update.tmpl index 7a45bc255..aa422afee 100644 --- a/entc/gen/template/dialect/sql/update.tmpl +++ b/entc/gen/template/dialect/sql/update.tmpl @@ -177,6 +177,11 @@ func ({{ $receiver }} *{{ $builder }}) sqlSave(ctx context.Context) ({{ $ret }} {{ if or $.NumHooks $.NumPolicy }}_ = {{ end }}createE.defaults() _, specE := createE.createSpec() edge.Target.Fields = specE.Fields + {{- if and .HasOneFieldID .ID.Default }} + if specE.ID.Value != nil { + edge.Target.Fields = append(edge.Target.Fields, specE.ID) + } + {{- end }} {{- end }} {{- end }} {{- end }} diff --git a/entc/integration/edgeschema/edgeschema_test.go b/entc/integration/edgeschema/edgeschema_test.go index e3a07b21e..7aa06d34f 100644 --- a/entc/integration/edgeschema/edgeschema_test.go +++ b/entc/integration/edgeschema/edgeschema_test.go @@ -18,6 +18,7 @@ import ( "entgo.io/ent/entc/integration/edgeschema/ent/tweetlike" "entgo.io/ent/entc/integration/edgeschema/ent/user" + "github.com/google/uuid" _ "github.com/mattn/go-sqlite3" "github.com/stretchr/testify/require" ) @@ -115,6 +116,24 @@ func TestEdgeSchemaCompositeID(t *testing.T) { require.Equal(t, 2, v[1].Count) } +func TestEdgeSchemaDefaultID(t *testing.T) { + client, err := ent.Open(dialect.SQLite, "file:ent?mode=memory&cache=shared&_fk=1") + require.NoError(t, err) + defer client.Close() + ctx := context.Background() + require.NoError(t, client.Schema.Create(ctx)) + + tweet1 := client.Tweet.Create().SetText("foo").SaveX(ctx) + tag1 := client.Tag.Create().SetValue("1").SaveX(ctx) + tweet1.Update().AddTags(tag1).SaveX(ctx) + require.Equal(t, tag1.ID, tweet1.QueryTags().OnlyIDX(ctx)) + require.NotEqual(t, uuid.Nil, tweet1.QueryTweetTags().OnlyIDX(ctx)) + + tweet2 := client.Tweet.Create().SetText("bar").AddTags(tag1).SaveX(ctx) + require.Equal(t, tag1.ID, tweet2.QueryTags().OnlyIDX(ctx)) + require.NotEqual(t, uuid.Nil, tweet2.QueryTweetTags().OnlyIDX(ctx)) +} + func TestEdgeSchemaBidiWithID(t *testing.T) { client, err := ent.Open(dialect.SQLite, "file:ent?mode=memory&cache=shared&_fk=1") require.NoError(t, err) diff --git a/entc/integration/edgeschema/ent/client.go b/entc/integration/edgeschema/ent/client.go index ec8bdceab..416350542 100644 --- a/entc/integration/edgeschema/ent/client.go +++ b/entc/integration/edgeschema/ent/client.go @@ -8,12 +8,15 @@ import ( "log" "entgo.io/ent/entc/integration/edgeschema/ent/migrate" + "github.com/google/uuid" "entgo.io/ent/entc/integration/edgeschema/ent/friendship" "entgo.io/ent/entc/integration/edgeschema/ent/group" "entgo.io/ent/entc/integration/edgeschema/ent/relationship" + "entgo.io/ent/entc/integration/edgeschema/ent/tag" "entgo.io/ent/entc/integration/edgeschema/ent/tweet" "entgo.io/ent/entc/integration/edgeschema/ent/tweetlike" + "entgo.io/ent/entc/integration/edgeschema/ent/tweettag" "entgo.io/ent/entc/integration/edgeschema/ent/user" "entgo.io/ent/entc/integration/edgeschema/ent/usergroup" "entgo.io/ent/entc/integration/edgeschema/ent/usertweet" @@ -34,10 +37,14 @@ type Client struct { Group *GroupClient // Relationship is the client for interacting with the Relationship builders. Relationship *RelationshipClient + // Tag is the client for interacting with the Tag builders. + Tag *TagClient // Tweet is the client for interacting with the Tweet builders. Tweet *TweetClient // TweetLike is the client for interacting with the TweetLike builders. TweetLike *TweetLikeClient + // TweetTag is the client for interacting with the TweetTag builders. + TweetTag *TweetTagClient // User is the client for interacting with the User builders. User *UserClient // UserGroup is the client for interacting with the UserGroup builders. @@ -60,8 +67,10 @@ func (c *Client) init() { c.Friendship = NewFriendshipClient(c.config) c.Group = NewGroupClient(c.config) c.Relationship = NewRelationshipClient(c.config) + c.Tag = NewTagClient(c.config) c.Tweet = NewTweetClient(c.config) c.TweetLike = NewTweetLikeClient(c.config) + c.TweetTag = NewTweetTagClient(c.config) c.User = NewUserClient(c.config) c.UserGroup = NewUserGroupClient(c.config) c.UserTweet = NewUserTweetClient(c.config) @@ -101,8 +110,10 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { Friendship: NewFriendshipClient(cfg), Group: NewGroupClient(cfg), Relationship: NewRelationshipClient(cfg), + Tag: NewTagClient(cfg), Tweet: NewTweetClient(cfg), TweetLike: NewTweetLikeClient(cfg), + TweetTag: NewTweetTagClient(cfg), User: NewUserClient(cfg), UserGroup: NewUserGroupClient(cfg), UserTweet: NewUserTweetClient(cfg), @@ -128,8 +139,10 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) Friendship: NewFriendshipClient(cfg), Group: NewGroupClient(cfg), Relationship: NewRelationshipClient(cfg), + Tag: NewTagClient(cfg), Tweet: NewTweetClient(cfg), TweetLike: NewTweetLikeClient(cfg), + TweetTag: NewTweetTagClient(cfg), User: NewUserClient(cfg), UserGroup: NewUserGroupClient(cfg), UserTweet: NewUserTweetClient(cfg), @@ -165,8 +178,10 @@ func (c *Client) Use(hooks ...Hook) { c.Friendship.Use(hooks...) c.Group.Use(hooks...) c.Relationship.Use(hooks...) + c.Tag.Use(hooks...) c.Tweet.Use(hooks...) c.TweetLike.Use(hooks...) + c.TweetTag.Use(hooks...) c.User.Use(hooks...) c.UserGroup.Use(hooks...) c.UserTweet.Use(hooks...) @@ -488,6 +503,128 @@ func (c *RelationshipClient) Hooks() []Hook { return c.hooks.Relationship } +// TagClient is a client for the Tag schema. +type TagClient struct { + config +} + +// NewTagClient returns a client for the Tag from the given config. +func NewTagClient(c config) *TagClient { + return &TagClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `tag.Hooks(f(g(h())))`. +func (c *TagClient) Use(hooks ...Hook) { + c.hooks.Tag = append(c.hooks.Tag, hooks...) +} + +// Create returns a builder for creating a Tag entity. +func (c *TagClient) Create() *TagCreate { + mutation := newTagMutation(c.config, OpCreate) + return &TagCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Tag entities. +func (c *TagClient) CreateBulk(builders ...*TagCreate) *TagCreateBulk { + return &TagCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Tag. +func (c *TagClient) Update() *TagUpdate { + mutation := newTagMutation(c.config, OpUpdate) + return &TagUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *TagClient) UpdateOne(t *Tag) *TagUpdateOne { + mutation := newTagMutation(c.config, OpUpdateOne, withTag(t)) + return &TagUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *TagClient) UpdateOneID(id int) *TagUpdateOne { + mutation := newTagMutation(c.config, OpUpdateOne, withTagID(id)) + return &TagUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Tag. +func (c *TagClient) Delete() *TagDelete { + mutation := newTagMutation(c.config, OpDelete) + return &TagDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *TagClient) DeleteOne(t *Tag) *TagDeleteOne { + return c.DeleteOneID(t.ID) +} + +// DeleteOne returns a builder for deleting the given entity by its id. +func (c *TagClient) DeleteOneID(id int) *TagDeleteOne { + builder := c.Delete().Where(tag.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &TagDeleteOne{builder} +} + +// Query returns a query builder for Tag. +func (c *TagClient) Query() *TagQuery { + return &TagQuery{ + config: c.config, + } +} + +// Get returns a Tag entity by its id. +func (c *TagClient) Get(ctx context.Context, id int) (*Tag, error) { + return c.Query().Where(tag.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *TagClient) GetX(ctx context.Context, id int) *Tag { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryTweets queries the tweets edge of a Tag. +func (c *TagClient) QueryTweets(t *Tag) *TweetQuery { + query := &TweetQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := t.ID + step := sqlgraph.NewStep( + sqlgraph.From(tag.Table, tag.FieldID, id), + sqlgraph.To(tweet.Table, tweet.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, tag.TweetsTable, tag.TweetsPrimaryKey...), + ) + fromV = sqlgraph.Neighbors(t.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryTweetTags queries the tweet_tags edge of a Tag. +func (c *TagClient) QueryTweetTags(t *Tag) *TweetTagQuery { + query := &TweetTagQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := t.ID + step := sqlgraph.NewStep( + sqlgraph.From(tag.Table, tag.FieldID, id), + sqlgraph.To(tweettag.Table, tweettag.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, tag.TweetTagsTable, tag.TweetTagsColumn), + ) + fromV = sqlgraph.Neighbors(t.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *TagClient) Hooks() []Hook { + return c.hooks.Tag +} + // TweetClient is a client for the Tweet schema. type TweetClient struct { config @@ -605,6 +742,22 @@ func (c *TweetClient) QueryUser(t *Tweet) *UserQuery { return query } +// QueryTags queries the tags edge of a Tweet. +func (c *TweetClient) QueryTags(t *Tweet) *TagQuery { + query := &TagQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := t.ID + step := sqlgraph.NewStep( + sqlgraph.From(tweet.Table, tweet.FieldID, id), + sqlgraph.To(tag.Table, tag.FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, tweet.TagsTable, tweet.TagsPrimaryKey...), + ) + fromV = sqlgraph.Neighbors(t.driver.Dialect(), step) + return fromV, nil + } + return query +} + // QueryLikes queries the likes edge of a Tweet. func (c *TweetClient) QueryLikes(t *Tweet) *TweetLikeQuery { query := &TweetLikeQuery{config: c.config} @@ -637,6 +790,22 @@ func (c *TweetClient) QueryTweetUser(t *Tweet) *UserTweetQuery { return query } +// QueryTweetTags queries the tweet_tags edge of a Tweet. +func (c *TweetClient) QueryTweetTags(t *Tweet) *TweetTagQuery { + query := &TweetTagQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := t.ID + step := sqlgraph.NewStep( + sqlgraph.From(tweet.Table, tweet.FieldID, id), + sqlgraph.To(tweettag.Table, tweettag.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, tweet.TweetTagsTable, tweet.TweetTagsColumn), + ) + fromV = sqlgraph.Neighbors(t.driver.Dialect(), step) + return fromV, nil + } + return query +} + // Hooks returns the client hooks. func (c *TweetClient) Hooks() []Hook { return c.hooks.Tweet @@ -714,6 +883,128 @@ func (c *TweetLikeClient) Hooks() []Hook { return c.hooks.TweetLike } +// TweetTagClient is a client for the TweetTag schema. +type TweetTagClient struct { + config +} + +// NewTweetTagClient returns a client for the TweetTag from the given config. +func NewTweetTagClient(c config) *TweetTagClient { + return &TweetTagClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `tweettag.Hooks(f(g(h())))`. +func (c *TweetTagClient) Use(hooks ...Hook) { + c.hooks.TweetTag = append(c.hooks.TweetTag, hooks...) +} + +// Create returns a builder for creating a TweetTag entity. +func (c *TweetTagClient) Create() *TweetTagCreate { + mutation := newTweetTagMutation(c.config, OpCreate) + return &TweetTagCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of TweetTag entities. +func (c *TweetTagClient) CreateBulk(builders ...*TweetTagCreate) *TweetTagCreateBulk { + return &TweetTagCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for TweetTag. +func (c *TweetTagClient) Update() *TweetTagUpdate { + mutation := newTweetTagMutation(c.config, OpUpdate) + return &TweetTagUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *TweetTagClient) UpdateOne(tt *TweetTag) *TweetTagUpdateOne { + mutation := newTweetTagMutation(c.config, OpUpdateOne, withTweetTag(tt)) + return &TweetTagUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *TweetTagClient) UpdateOneID(id uuid.UUID) *TweetTagUpdateOne { + mutation := newTweetTagMutation(c.config, OpUpdateOne, withTweetTagID(id)) + return &TweetTagUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for TweetTag. +func (c *TweetTagClient) Delete() *TweetTagDelete { + mutation := newTweetTagMutation(c.config, OpDelete) + return &TweetTagDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *TweetTagClient) DeleteOne(tt *TweetTag) *TweetTagDeleteOne { + return c.DeleteOneID(tt.ID) +} + +// DeleteOne returns a builder for deleting the given entity by its id. +func (c *TweetTagClient) DeleteOneID(id uuid.UUID) *TweetTagDeleteOne { + builder := c.Delete().Where(tweettag.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &TweetTagDeleteOne{builder} +} + +// Query returns a query builder for TweetTag. +func (c *TweetTagClient) Query() *TweetTagQuery { + return &TweetTagQuery{ + config: c.config, + } +} + +// Get returns a TweetTag entity by its id. +func (c *TweetTagClient) Get(ctx context.Context, id uuid.UUID) (*TweetTag, error) { + return c.Query().Where(tweettag.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *TweetTagClient) GetX(ctx context.Context, id uuid.UUID) *TweetTag { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryTag queries the tag edge of a TweetTag. +func (c *TweetTagClient) QueryTag(tt *TweetTag) *TagQuery { + query := &TagQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := tt.ID + step := sqlgraph.NewStep( + sqlgraph.From(tweettag.Table, tweettag.FieldID, id), + sqlgraph.To(tag.Table, tag.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, tweettag.TagTable, tweettag.TagColumn), + ) + fromV = sqlgraph.Neighbors(tt.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryTweet queries the tweet edge of a TweetTag. +func (c *TweetTagClient) QueryTweet(tt *TweetTag) *TweetQuery { + query := &TweetQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := tt.ID + step := sqlgraph.NewStep( + sqlgraph.From(tweettag.Table, tweettag.FieldID, id), + sqlgraph.To(tweet.Table, tweet.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, tweettag.TweetTable, tweettag.TweetColumn), + ) + fromV = sqlgraph.Neighbors(tt.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *TweetTagClient) Hooks() []Hook { + return c.hooks.TweetTag +} + // UserClient is a client for the User schema. type UserClient struct { config diff --git a/entc/integration/edgeschema/ent/config.go b/entc/integration/edgeschema/ent/config.go index 62ddbdc32..114ebf2c4 100644 --- a/entc/integration/edgeschema/ent/config.go +++ b/entc/integration/edgeschema/ent/config.go @@ -27,8 +27,10 @@ type hooks struct { Friendship []ent.Hook Group []ent.Hook Relationship []ent.Hook + Tag []ent.Hook Tweet []ent.Hook TweetLike []ent.Hook + TweetTag []ent.Hook User []ent.Hook UserGroup []ent.Hook UserTweet []ent.Hook diff --git a/entc/integration/edgeschema/ent/ent.go b/entc/integration/edgeschema/ent/ent.go index 103f1b860..da489fdf2 100644 --- a/entc/integration/edgeschema/ent/ent.go +++ b/entc/integration/edgeschema/ent/ent.go @@ -13,8 +13,10 @@ import ( "entgo.io/ent/entc/integration/edgeschema/ent/friendship" "entgo.io/ent/entc/integration/edgeschema/ent/group" "entgo.io/ent/entc/integration/edgeschema/ent/relationship" + "entgo.io/ent/entc/integration/edgeschema/ent/tag" "entgo.io/ent/entc/integration/edgeschema/ent/tweet" "entgo.io/ent/entc/integration/edgeschema/ent/tweetlike" + "entgo.io/ent/entc/integration/edgeschema/ent/tweettag" "entgo.io/ent/entc/integration/edgeschema/ent/user" "entgo.io/ent/entc/integration/edgeschema/ent/usergroup" "entgo.io/ent/entc/integration/edgeschema/ent/usertweet" @@ -41,8 +43,10 @@ func columnChecker(table string) func(string) error { friendship.Table: friendship.ValidColumn, group.Table: group.ValidColumn, relationship.Table: relationship.ValidColumn, + tag.Table: tag.ValidColumn, tweet.Table: tweet.ValidColumn, tweetlike.Table: tweetlike.ValidColumn, + tweettag.Table: tweettag.ValidColumn, user.Table: user.ValidColumn, usergroup.Table: usergroup.ValidColumn, usertweet.Table: usertweet.ValidColumn, diff --git a/entc/integration/edgeschema/ent/hook/hook.go b/entc/integration/edgeschema/ent/hook/hook.go index 3829cd094..47cfaf0aa 100644 --- a/entc/integration/edgeschema/ent/hook/hook.go +++ b/entc/integration/edgeschema/ent/hook/hook.go @@ -48,6 +48,19 @@ func (f RelationshipFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value return f(ctx, mv) } +// The TagFunc type is an adapter to allow the use of ordinary +// function as Tag mutator. +type TagFunc func(context.Context, *ent.TagMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f TagFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + mv, ok := m.(*ent.TagMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.TagMutation", m) + } + return f(ctx, mv) +} + // The TweetFunc type is an adapter to allow the use of ordinary // function as Tweet mutator. type TweetFunc func(context.Context, *ent.TweetMutation) (ent.Value, error) @@ -74,6 +87,19 @@ func (f TweetLikeFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, e return f(ctx, mv) } +// The TweetTagFunc type is an adapter to allow the use of ordinary +// function as TweetTag mutator. +type TweetTagFunc func(context.Context, *ent.TweetTagMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f TweetTagFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + mv, ok := m.(*ent.TweetTagMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.TweetTagMutation", m) + } + return f(ctx, mv) +} + // The UserFunc type is an adapter to allow the use of ordinary // function as User mutator. type UserFunc func(context.Context, *ent.UserMutation) (ent.Value, error) diff --git a/entc/integration/edgeschema/ent/migrate/schema.go b/entc/integration/edgeschema/ent/migrate/schema.go index ce4c62977..10ab9998a 100644 --- a/entc/integration/edgeschema/ent/migrate/schema.go +++ b/entc/integration/edgeschema/ent/migrate/schema.go @@ -92,6 +92,17 @@ var ( }, }, } + // TagsColumns holds the columns for the "tags" table. + TagsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "value", Type: field.TypeString}, + } + // TagsTable holds the schema information for the "tags" table. + TagsTable = &schema.Table{ + Name: "tags", + Columns: TagsColumns, + PrimaryKey: []*schema.Column{TagsColumns[0]}, + } // TweetsColumns holds the columns for the "tweets" table. TweetsColumns = []*schema.Column{ {Name: "id", Type: field.TypeInt, Increment: true}, @@ -129,6 +140,40 @@ var ( }, }, } + // TweetTagsColumns holds the columns for the "tweet_tags" table. + TweetTagsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeUUID}, + {Name: "added_at", Type: field.TypeTime}, + {Name: "tag_id", Type: field.TypeInt}, + {Name: "tweet_id", Type: field.TypeInt}, + } + // TweetTagsTable holds the schema information for the "tweet_tags" table. + TweetTagsTable = &schema.Table{ + Name: "tweet_tags", + Columns: TweetTagsColumns, + PrimaryKey: []*schema.Column{TweetTagsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "tweet_tags_tags_tag", + Columns: []*schema.Column{TweetTagsColumns[2]}, + RefColumns: []*schema.Column{TagsColumns[0]}, + OnDelete: schema.NoAction, + }, + { + Symbol: "tweet_tags_tweets_tweet", + Columns: []*schema.Column{TweetTagsColumns[3]}, + RefColumns: []*schema.Column{TweetsColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + Indexes: []*schema.Index{ + { + Name: "tweettag_tag_id_tweet_id", + Unique: true, + Columns: []*schema.Column{TweetTagsColumns[2], TweetTagsColumns[3]}, + }, + }, + } // UsersColumns holds the columns for the "users" table. UsersColumns = []*schema.Column{ {Name: "id", Type: field.TypeInt, Increment: true}, @@ -218,8 +263,10 @@ var ( FriendshipsTable, GroupsTable, RelationshipsTable, + TagsTable, TweetsTable, TweetLikesTable, + TweetTagsTable, UsersTable, UserGroupsTable, UserTweetsTable, @@ -233,6 +280,8 @@ func init() { RelationshipsTable.ForeignKeys[1].RefTable = UsersTable TweetLikesTable.ForeignKeys[0].RefTable = UsersTable TweetLikesTable.ForeignKeys[1].RefTable = TweetsTable + TweetTagsTable.ForeignKeys[0].RefTable = TagsTable + TweetTagsTable.ForeignKeys[1].RefTable = TweetsTable UserGroupsTable.ForeignKeys[0].RefTable = UsersTable UserGroupsTable.ForeignKeys[1].RefTable = GroupsTable UserTweetsTable.ForeignKeys[0].RefTable = UsersTable diff --git a/entc/integration/edgeschema/ent/mutation.go b/entc/integration/edgeschema/ent/mutation.go index 4919c5b38..ee3bf7768 100644 --- a/entc/integration/edgeschema/ent/mutation.go +++ b/entc/integration/edgeschema/ent/mutation.go @@ -13,11 +13,14 @@ import ( "entgo.io/ent/entc/integration/edgeschema/ent/group" "entgo.io/ent/entc/integration/edgeschema/ent/predicate" "entgo.io/ent/entc/integration/edgeschema/ent/relationship" + "entgo.io/ent/entc/integration/edgeschema/ent/tag" "entgo.io/ent/entc/integration/edgeschema/ent/tweet" "entgo.io/ent/entc/integration/edgeschema/ent/tweetlike" + "entgo.io/ent/entc/integration/edgeschema/ent/tweettag" "entgo.io/ent/entc/integration/edgeschema/ent/user" "entgo.io/ent/entc/integration/edgeschema/ent/usergroup" "entgo.io/ent/entc/integration/edgeschema/ent/usertweet" + "github.com/google/uuid" "entgo.io/ent" ) @@ -34,8 +37,10 @@ const ( TypeFriendship = "Friendship" TypeGroup = "Group" TypeRelationship = "Relationship" + TypeTag = "Tag" TypeTweet = "Tweet" TypeTweetLike = "TweetLike" + TypeTweetTag = "TweetTag" TypeUser = "User" TypeUserGroup = "UserGroup" TypeUserTweet = "UserTweet" @@ -1572,6 +1577,493 @@ func (m *RelationshipMutation) ResetEdge(name string) error { return fmt.Errorf("unknown Relationship edge %s", name) } +// TagMutation represents an operation that mutates the Tag nodes in the graph. +type TagMutation struct { + config + op Op + typ string + id *int + value *string + clearedFields map[string]struct{} + tweets map[int]struct{} + removedtweets map[int]struct{} + clearedtweets bool + tweet_tags map[uuid.UUID]struct{} + removedtweet_tags map[uuid.UUID]struct{} + clearedtweet_tags bool + done bool + oldValue func(context.Context) (*Tag, error) + predicates []predicate.Tag +} + +var _ ent.Mutation = (*TagMutation)(nil) + +// tagOption allows management of the mutation configuration using functional options. +type tagOption func(*TagMutation) + +// newTagMutation creates new mutation for the Tag entity. +func newTagMutation(c config, op Op, opts ...tagOption) *TagMutation { + m := &TagMutation{ + config: c, + op: op, + typ: TypeTag, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withTagID sets the ID field of the mutation. +func withTagID(id int) tagOption { + return func(m *TagMutation) { + var ( + err error + once sync.Once + value *Tag + ) + m.oldValue = func(ctx context.Context) (*Tag, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Tag.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withTag sets the old Tag of the mutation. +func withTag(node *Tag) tagOption { + return func(m *TagMutation) { + m.oldValue = func(context.Context) (*Tag, 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 TagMutation) 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 TagMutation) 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 +} + +// 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 *TagMutation) ID() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *TagMutation) IDs(ctx context.Context) ([]int, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().Tag.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetValue sets the "value" field. +func (m *TagMutation) SetValue(s string) { + m.value = &s +} + +// Value returns the value of the "value" field in the mutation. +func (m *TagMutation) Value() (r string, exists bool) { + v := m.value + if v == nil { + return + } + return *v, true +} + +// OldValue returns the old "value" field's value of the Tag entity. +// If the Tag object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *TagMutation) OldValue(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldValue is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldValue requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldValue: %w", err) + } + return oldValue.Value, nil +} + +// ResetValue resets all changes to the "value" field. +func (m *TagMutation) ResetValue() { + m.value = nil +} + +// AddTweetIDs adds the "tweets" edge to the Tweet entity by ids. +func (m *TagMutation) AddTweetIDs(ids ...int) { + if m.tweets == nil { + m.tweets = make(map[int]struct{}) + } + for i := range ids { + m.tweets[ids[i]] = struct{}{} + } +} + +// ClearTweets clears the "tweets" edge to the Tweet entity. +func (m *TagMutation) ClearTweets() { + m.clearedtweets = true +} + +// TweetsCleared reports if the "tweets" edge to the Tweet entity was cleared. +func (m *TagMutation) TweetsCleared() bool { + return m.clearedtweets +} + +// RemoveTweetIDs removes the "tweets" edge to the Tweet entity by IDs. +func (m *TagMutation) RemoveTweetIDs(ids ...int) { + if m.removedtweets == nil { + m.removedtweets = make(map[int]struct{}) + } + for i := range ids { + delete(m.tweets, ids[i]) + m.removedtweets[ids[i]] = struct{}{} + } +} + +// RemovedTweets returns the removed IDs of the "tweets" edge to the Tweet entity. +func (m *TagMutation) RemovedTweetsIDs() (ids []int) { + for id := range m.removedtweets { + ids = append(ids, id) + } + return +} + +// TweetsIDs returns the "tweets" edge IDs in the mutation. +func (m *TagMutation) TweetsIDs() (ids []int) { + for id := range m.tweets { + ids = append(ids, id) + } + return +} + +// ResetTweets resets all changes to the "tweets" edge. +func (m *TagMutation) ResetTweets() { + m.tweets = nil + m.clearedtweets = false + m.removedtweets = nil +} + +// AddTweetTagIDs adds the "tweet_tags" edge to the TweetTag entity by ids. +func (m *TagMutation) AddTweetTagIDs(ids ...uuid.UUID) { + if m.tweet_tags == nil { + m.tweet_tags = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.tweet_tags[ids[i]] = struct{}{} + } +} + +// ClearTweetTags clears the "tweet_tags" edge to the TweetTag entity. +func (m *TagMutation) ClearTweetTags() { + m.clearedtweet_tags = true +} + +// TweetTagsCleared reports if the "tweet_tags" edge to the TweetTag entity was cleared. +func (m *TagMutation) TweetTagsCleared() bool { + return m.clearedtweet_tags +} + +// RemoveTweetTagIDs removes the "tweet_tags" edge to the TweetTag entity by IDs. +func (m *TagMutation) RemoveTweetTagIDs(ids ...uuid.UUID) { + if m.removedtweet_tags == nil { + m.removedtweet_tags = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.tweet_tags, ids[i]) + m.removedtweet_tags[ids[i]] = struct{}{} + } +} + +// RemovedTweetTags returns the removed IDs of the "tweet_tags" edge to the TweetTag entity. +func (m *TagMutation) RemovedTweetTagsIDs() (ids []uuid.UUID) { + for id := range m.removedtweet_tags { + ids = append(ids, id) + } + return +} + +// TweetTagsIDs returns the "tweet_tags" edge IDs in the mutation. +func (m *TagMutation) TweetTagsIDs() (ids []uuid.UUID) { + for id := range m.tweet_tags { + ids = append(ids, id) + } + return +} + +// ResetTweetTags resets all changes to the "tweet_tags" edge. +func (m *TagMutation) ResetTweetTags() { + m.tweet_tags = nil + m.clearedtweet_tags = false + m.removedtweet_tags = nil +} + +// Where appends a list predicates to the TagMutation builder. +func (m *TagMutation) Where(ps ...predicate.Tag) { + m.predicates = append(m.predicates, ps...) +} + +// Op returns the operation name. +func (m *TagMutation) Op() Op { + return m.op +} + +// Type returns the node type of this mutation (Tag). +func (m *TagMutation) 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 *TagMutation) Fields() []string { + fields := make([]string, 0, 1) + if m.value != nil { + fields = append(fields, tag.FieldValue) + } + 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 *TagMutation) Field(name string) (ent.Value, bool) { + switch name { + case tag.FieldValue: + return m.Value() + } + 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 *TagMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case tag.FieldValue: + return m.OldValue(ctx) + } + return nil, fmt.Errorf("unknown Tag 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 *TagMutation) SetField(name string, value ent.Value) error { + switch name { + case tag.FieldValue: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetValue(v) + return nil + } + return fmt.Errorf("unknown Tag field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *TagMutation) 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 *TagMutation) 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 *TagMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown Tag numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *TagMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *TagMutation) 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 *TagMutation) ClearField(name string) error { + return fmt.Errorf("unknown Tag 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 *TagMutation) ResetField(name string) error { + switch name { + case tag.FieldValue: + m.ResetValue() + return nil + } + return fmt.Errorf("unknown Tag field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *TagMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.tweets != nil { + edges = append(edges, tag.EdgeTweets) + } + if m.tweet_tags != nil { + edges = append(edges, tag.EdgeTweetTags) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *TagMutation) AddedIDs(name string) []ent.Value { + switch name { + case tag.EdgeTweets: + ids := make([]ent.Value, 0, len(m.tweets)) + for id := range m.tweets { + ids = append(ids, id) + } + return ids + case tag.EdgeTweetTags: + ids := make([]ent.Value, 0, len(m.tweet_tags)) + for id := range m.tweet_tags { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *TagMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + if m.removedtweets != nil { + edges = append(edges, tag.EdgeTweets) + } + if m.removedtweet_tags != nil { + edges = append(edges, tag.EdgeTweetTags) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *TagMutation) RemovedIDs(name string) []ent.Value { + switch name { + case tag.EdgeTweets: + ids := make([]ent.Value, 0, len(m.removedtweets)) + for id := range m.removedtweets { + ids = append(ids, id) + } + return ids + case tag.EdgeTweetTags: + ids := make([]ent.Value, 0, len(m.removedtweet_tags)) + for id := range m.removedtweet_tags { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *TagMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedtweets { + edges = append(edges, tag.EdgeTweets) + } + if m.clearedtweet_tags { + edges = append(edges, tag.EdgeTweetTags) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *TagMutation) EdgeCleared(name string) bool { + switch name { + case tag.EdgeTweets: + return m.clearedtweets + case tag.EdgeTweetTags: + return m.clearedtweet_tags + } + 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 *TagMutation) ClearEdge(name string) error { + switch name { + } + return fmt.Errorf("unknown Tag 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 *TagMutation) ResetEdge(name string) error { + switch name { + case tag.EdgeTweets: + m.ResetTweets() + return nil + case tag.EdgeTweetTags: + m.ResetTweetTags() + return nil + } + return fmt.Errorf("unknown Tag edge %s", name) +} + // TweetMutation represents an operation that mutates the Tweet nodes in the graph. type TweetMutation struct { config @@ -1586,9 +2078,15 @@ type TweetMutation struct { user map[int]struct{} removeduser map[int]struct{} cleareduser bool + tags map[int]struct{} + removedtags map[int]struct{} + clearedtags bool tweet_user map[int]struct{} removedtweet_user map[int]struct{} clearedtweet_user bool + tweet_tags map[uuid.UUID]struct{} + removedtweet_tags map[uuid.UUID]struct{} + clearedtweet_tags bool done bool oldValue func(context.Context) (*Tweet, error) predicates []predicate.Tweet @@ -1836,6 +2334,60 @@ func (m *TweetMutation) ResetUser() { m.removeduser = nil } +// AddTagIDs adds the "tags" edge to the Tag entity by ids. +func (m *TweetMutation) AddTagIDs(ids ...int) { + if m.tags == nil { + m.tags = make(map[int]struct{}) + } + for i := range ids { + m.tags[ids[i]] = struct{}{} + } +} + +// ClearTags clears the "tags" edge to the Tag entity. +func (m *TweetMutation) ClearTags() { + m.clearedtags = true +} + +// TagsCleared reports if the "tags" edge to the Tag entity was cleared. +func (m *TweetMutation) TagsCleared() bool { + return m.clearedtags +} + +// RemoveTagIDs removes the "tags" edge to the Tag entity by IDs. +func (m *TweetMutation) RemoveTagIDs(ids ...int) { + if m.removedtags == nil { + m.removedtags = make(map[int]struct{}) + } + for i := range ids { + delete(m.tags, ids[i]) + m.removedtags[ids[i]] = struct{}{} + } +} + +// RemovedTags returns the removed IDs of the "tags" edge to the Tag entity. +func (m *TweetMutation) RemovedTagsIDs() (ids []int) { + for id := range m.removedtags { + ids = append(ids, id) + } + return +} + +// TagsIDs returns the "tags" edge IDs in the mutation. +func (m *TweetMutation) TagsIDs() (ids []int) { + for id := range m.tags { + ids = append(ids, id) + } + return +} + +// ResetTags resets all changes to the "tags" edge. +func (m *TweetMutation) ResetTags() { + m.tags = nil + m.clearedtags = false + m.removedtags = nil +} + // AddTweetUserIDs adds the "tweet_user" edge to the UserTweet entity by ids. func (m *TweetMutation) AddTweetUserIDs(ids ...int) { if m.tweet_user == nil { @@ -1890,6 +2442,60 @@ func (m *TweetMutation) ResetTweetUser() { m.removedtweet_user = nil } +// AddTweetTagIDs adds the "tweet_tags" edge to the TweetTag entity by ids. +func (m *TweetMutation) AddTweetTagIDs(ids ...uuid.UUID) { + if m.tweet_tags == nil { + m.tweet_tags = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.tweet_tags[ids[i]] = struct{}{} + } +} + +// ClearTweetTags clears the "tweet_tags" edge to the TweetTag entity. +func (m *TweetMutation) ClearTweetTags() { + m.clearedtweet_tags = true +} + +// TweetTagsCleared reports if the "tweet_tags" edge to the TweetTag entity was cleared. +func (m *TweetMutation) TweetTagsCleared() bool { + return m.clearedtweet_tags +} + +// RemoveTweetTagIDs removes the "tweet_tags" edge to the TweetTag entity by IDs. +func (m *TweetMutation) RemoveTweetTagIDs(ids ...uuid.UUID) { + if m.removedtweet_tags == nil { + m.removedtweet_tags = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.tweet_tags, ids[i]) + m.removedtweet_tags[ids[i]] = struct{}{} + } +} + +// RemovedTweetTags returns the removed IDs of the "tweet_tags" edge to the TweetTag entity. +func (m *TweetMutation) RemovedTweetTagsIDs() (ids []uuid.UUID) { + for id := range m.removedtweet_tags { + ids = append(ids, id) + } + return +} + +// TweetTagsIDs returns the "tweet_tags" edge IDs in the mutation. +func (m *TweetMutation) TweetTagsIDs() (ids []uuid.UUID) { + for id := range m.tweet_tags { + ids = append(ids, id) + } + return +} + +// ResetTweetTags resets all changes to the "tweet_tags" edge. +func (m *TweetMutation) ResetTweetTags() { + m.tweet_tags = nil + m.clearedtweet_tags = false + m.removedtweet_tags = nil +} + // Where appends a list predicates to the TweetMutation builder. func (m *TweetMutation) Where(ps ...predicate.Tweet) { m.predicates = append(m.predicates, ps...) @@ -2008,16 +2614,22 @@ func (m *TweetMutation) ResetField(name string) error { // AddedEdges returns all edge names that were set/added in this mutation. func (m *TweetMutation) AddedEdges() []string { - edges := make([]string, 0, 3) + edges := make([]string, 0, 5) if m.liked_users != nil { edges = append(edges, tweet.EdgeLikedUsers) } if m.user != nil { edges = append(edges, tweet.EdgeUser) } + if m.tags != nil { + edges = append(edges, tweet.EdgeTags) + } if m.tweet_user != nil { edges = append(edges, tweet.EdgeTweetUser) } + if m.tweet_tags != nil { + edges = append(edges, tweet.EdgeTweetTags) + } return edges } @@ -2037,28 +2649,46 @@ func (m *TweetMutation) AddedIDs(name string) []ent.Value { ids = append(ids, id) } return ids + case tweet.EdgeTags: + ids := make([]ent.Value, 0, len(m.tags)) + for id := range m.tags { + ids = append(ids, id) + } + return ids case tweet.EdgeTweetUser: ids := make([]ent.Value, 0, len(m.tweet_user)) for id := range m.tweet_user { ids = append(ids, id) } return ids + case tweet.EdgeTweetTags: + ids := make([]ent.Value, 0, len(m.tweet_tags)) + for id := range m.tweet_tags { + ids = append(ids, id) + } + return ids } return nil } // RemovedEdges returns all edge names that were removed in this mutation. func (m *TweetMutation) RemovedEdges() []string { - edges := make([]string, 0, 3) + edges := make([]string, 0, 5) if m.removedliked_users != nil { edges = append(edges, tweet.EdgeLikedUsers) } if m.removeduser != nil { edges = append(edges, tweet.EdgeUser) } + if m.removedtags != nil { + edges = append(edges, tweet.EdgeTags) + } if m.removedtweet_user != nil { edges = append(edges, tweet.EdgeTweetUser) } + if m.removedtweet_tags != nil { + edges = append(edges, tweet.EdgeTweetTags) + } return edges } @@ -2078,28 +2708,46 @@ func (m *TweetMutation) RemovedIDs(name string) []ent.Value { ids = append(ids, id) } return ids + case tweet.EdgeTags: + ids := make([]ent.Value, 0, len(m.removedtags)) + for id := range m.removedtags { + ids = append(ids, id) + } + return ids case tweet.EdgeTweetUser: ids := make([]ent.Value, 0, len(m.removedtweet_user)) for id := range m.removedtweet_user { ids = append(ids, id) } return ids + case tweet.EdgeTweetTags: + ids := make([]ent.Value, 0, len(m.removedtweet_tags)) + for id := range m.removedtweet_tags { + ids = append(ids, id) + } + return ids } return nil } // ClearedEdges returns all edge names that were cleared in this mutation. func (m *TweetMutation) ClearedEdges() []string { - edges := make([]string, 0, 3) + edges := make([]string, 0, 5) if m.clearedliked_users { edges = append(edges, tweet.EdgeLikedUsers) } if m.cleareduser { edges = append(edges, tweet.EdgeUser) } + if m.clearedtags { + edges = append(edges, tweet.EdgeTags) + } if m.clearedtweet_user { edges = append(edges, tweet.EdgeTweetUser) } + if m.clearedtweet_tags { + edges = append(edges, tweet.EdgeTweetTags) + } return edges } @@ -2111,8 +2759,12 @@ func (m *TweetMutation) EdgeCleared(name string) bool { return m.clearedliked_users case tweet.EdgeUser: return m.cleareduser + case tweet.EdgeTags: + return m.clearedtags case tweet.EdgeTweetUser: return m.clearedtweet_user + case tweet.EdgeTweetTags: + return m.clearedtweet_tags } return false } @@ -2135,9 +2787,15 @@ func (m *TweetMutation) ResetEdge(name string) error { case tweet.EdgeUser: m.ResetUser() return nil + case tweet.EdgeTags: + m.ResetTags() + return nil case tweet.EdgeTweetUser: m.ResetTweetUser() return nil + case tweet.EdgeTweetTags: + m.ResetTweetTags() + return nil } return fmt.Errorf("unknown Tweet edge %s", name) } @@ -2544,6 +3202,534 @@ func (m *TweetLikeMutation) ResetEdge(name string) error { return fmt.Errorf("unknown TweetLike edge %s", name) } +// TweetTagMutation represents an operation that mutates the TweetTag nodes in the graph. +type TweetTagMutation struct { + config + op Op + typ string + id *uuid.UUID + added_at *time.Time + clearedFields map[string]struct{} + tag *int + clearedtag bool + tweet *int + clearedtweet bool + done bool + oldValue func(context.Context) (*TweetTag, error) + predicates []predicate.TweetTag +} + +var _ ent.Mutation = (*TweetTagMutation)(nil) + +// tweettagOption allows management of the mutation configuration using functional options. +type tweettagOption func(*TweetTagMutation) + +// newTweetTagMutation creates new mutation for the TweetTag entity. +func newTweetTagMutation(c config, op Op, opts ...tweettagOption) *TweetTagMutation { + m := &TweetTagMutation{ + config: c, + op: op, + typ: TypeTweetTag, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withTweetTagID sets the ID field of the mutation. +func withTweetTagID(id uuid.UUID) tweettagOption { + return func(m *TweetTagMutation) { + var ( + err error + once sync.Once + value *TweetTag + ) + m.oldValue = func(ctx context.Context) (*TweetTag, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().TweetTag.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withTweetTag sets the old TweetTag of the mutation. +func withTweetTag(node *TweetTag) tweettagOption { + return func(m *TweetTagMutation) { + m.oldValue = func(context.Context) (*TweetTag, 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 TweetTagMutation) 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 TweetTagMutation) 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 TweetTag entities. +func (m *TweetTagMutation) SetID(id uuid.UUID) { + 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 *TweetTagMutation) ID() (id uuid.UUID, 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 *TweetTagMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []uuid.UUID{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().TweetTag.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetAddedAt sets the "added_at" field. +func (m *TweetTagMutation) SetAddedAt(t time.Time) { + m.added_at = &t +} + +// AddedAt returns the value of the "added_at" field in the mutation. +func (m *TweetTagMutation) AddedAt() (r time.Time, exists bool) { + v := m.added_at + if v == nil { + return + } + return *v, true +} + +// OldAddedAt returns the old "added_at" field's value of the TweetTag entity. +// If the TweetTag object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *TweetTagMutation) OldAddedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAddedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAddedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAddedAt: %w", err) + } + return oldValue.AddedAt, nil +} + +// ResetAddedAt resets all changes to the "added_at" field. +func (m *TweetTagMutation) ResetAddedAt() { + m.added_at = nil +} + +// SetTagID sets the "tag_id" field. +func (m *TweetTagMutation) SetTagID(i int) { + m.tag = &i +} + +// TagID returns the value of the "tag_id" field in the mutation. +func (m *TweetTagMutation) TagID() (r int, exists bool) { + v := m.tag + if v == nil { + return + } + return *v, true +} + +// OldTagID returns the old "tag_id" field's value of the TweetTag entity. +// If the TweetTag object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *TweetTagMutation) OldTagID(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTagID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTagID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTagID: %w", err) + } + return oldValue.TagID, nil +} + +// ResetTagID resets all changes to the "tag_id" field. +func (m *TweetTagMutation) ResetTagID() { + m.tag = nil +} + +// SetTweetID sets the "tweet_id" field. +func (m *TweetTagMutation) SetTweetID(i int) { + m.tweet = &i +} + +// TweetID returns the value of the "tweet_id" field in the mutation. +func (m *TweetTagMutation) TweetID() (r int, exists bool) { + v := m.tweet + if v == nil { + return + } + return *v, true +} + +// OldTweetID returns the old "tweet_id" field's value of the TweetTag entity. +// If the TweetTag object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *TweetTagMutation) OldTweetID(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTweetID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTweetID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTweetID: %w", err) + } + return oldValue.TweetID, nil +} + +// ResetTweetID resets all changes to the "tweet_id" field. +func (m *TweetTagMutation) ResetTweetID() { + m.tweet = nil +} + +// ClearTag clears the "tag" edge to the Tag entity. +func (m *TweetTagMutation) ClearTag() { + m.clearedtag = true +} + +// TagCleared reports if the "tag" edge to the Tag entity was cleared. +func (m *TweetTagMutation) TagCleared() bool { + return m.clearedtag +} + +// TagIDs returns the "tag" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// TagID instead. It exists only for internal usage by the builders. +func (m *TweetTagMutation) TagIDs() (ids []int) { + if id := m.tag; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetTag resets all changes to the "tag" edge. +func (m *TweetTagMutation) ResetTag() { + m.tag = nil + m.clearedtag = false +} + +// ClearTweet clears the "tweet" edge to the Tweet entity. +func (m *TweetTagMutation) ClearTweet() { + m.clearedtweet = true +} + +// TweetCleared reports if the "tweet" edge to the Tweet entity was cleared. +func (m *TweetTagMutation) TweetCleared() bool { + return m.clearedtweet +} + +// TweetIDs returns the "tweet" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// TweetID instead. It exists only for internal usage by the builders. +func (m *TweetTagMutation) TweetIDs() (ids []int) { + if id := m.tweet; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetTweet resets all changes to the "tweet" edge. +func (m *TweetTagMutation) ResetTweet() { + m.tweet = nil + m.clearedtweet = false +} + +// Where appends a list predicates to the TweetTagMutation builder. +func (m *TweetTagMutation) Where(ps ...predicate.TweetTag) { + m.predicates = append(m.predicates, ps...) +} + +// Op returns the operation name. +func (m *TweetTagMutation) Op() Op { + return m.op +} + +// Type returns the node type of this mutation (TweetTag). +func (m *TweetTagMutation) 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 *TweetTagMutation) Fields() []string { + fields := make([]string, 0, 3) + if m.added_at != nil { + fields = append(fields, tweettag.FieldAddedAt) + } + if m.tag != nil { + fields = append(fields, tweettag.FieldTagID) + } + if m.tweet != nil { + fields = append(fields, tweettag.FieldTweetID) + } + 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 *TweetTagMutation) Field(name string) (ent.Value, bool) { + switch name { + case tweettag.FieldAddedAt: + return m.AddedAt() + case tweettag.FieldTagID: + return m.TagID() + case tweettag.FieldTweetID: + return m.TweetID() + } + 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 *TweetTagMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case tweettag.FieldAddedAt: + return m.OldAddedAt(ctx) + case tweettag.FieldTagID: + return m.OldTagID(ctx) + case tweettag.FieldTweetID: + return m.OldTweetID(ctx) + } + return nil, fmt.Errorf("unknown TweetTag 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 *TweetTagMutation) SetField(name string, value ent.Value) error { + switch name { + case tweettag.FieldAddedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAddedAt(v) + return nil + case tweettag.FieldTagID: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTagID(v) + return nil + case tweettag.FieldTweetID: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTweetID(v) + return nil + } + return fmt.Errorf("unknown TweetTag field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *TweetTagMutation) AddedFields() []string { + var fields []string + return fields +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *TweetTagMutation) AddedField(name string) (ent.Value, bool) { + switch name { + } + 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 *TweetTagMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown TweetTag numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *TweetTagMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *TweetTagMutation) 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 *TweetTagMutation) ClearField(name string) error { + return fmt.Errorf("unknown TweetTag 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 *TweetTagMutation) ResetField(name string) error { + switch name { + case tweettag.FieldAddedAt: + m.ResetAddedAt() + return nil + case tweettag.FieldTagID: + m.ResetTagID() + return nil + case tweettag.FieldTweetID: + m.ResetTweetID() + return nil + } + return fmt.Errorf("unknown TweetTag field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *TweetTagMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.tag != nil { + edges = append(edges, tweettag.EdgeTag) + } + if m.tweet != nil { + edges = append(edges, tweettag.EdgeTweet) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *TweetTagMutation) AddedIDs(name string) []ent.Value { + switch name { + case tweettag.EdgeTag: + if id := m.tag; id != nil { + return []ent.Value{*id} + } + case tweettag.EdgeTweet: + if id := m.tweet; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *TweetTagMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *TweetTagMutation) RemovedIDs(name string) []ent.Value { + switch name { + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *TweetTagMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedtag { + edges = append(edges, tweettag.EdgeTag) + } + if m.clearedtweet { + edges = append(edges, tweettag.EdgeTweet) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *TweetTagMutation) EdgeCleared(name string) bool { + switch name { + case tweettag.EdgeTag: + return m.clearedtag + case tweettag.EdgeTweet: + return m.clearedtweet + } + 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 *TweetTagMutation) ClearEdge(name string) error { + switch name { + case tweettag.EdgeTag: + m.ClearTag() + return nil + case tweettag.EdgeTweet: + m.ClearTweet() + return nil + } + return fmt.Errorf("unknown TweetTag 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 *TweetTagMutation) ResetEdge(name string) error { + switch name { + case tweettag.EdgeTag: + m.ResetTag() + return nil + case tweettag.EdgeTweet: + m.ResetTweet() + return nil + } + return fmt.Errorf("unknown TweetTag edge %s", name) +} + // UserMutation represents an operation that mutates the User nodes in the graph. type UserMutation struct { config diff --git a/entc/integration/edgeschema/ent/predicate/predicate.go b/entc/integration/edgeschema/ent/predicate/predicate.go index 4a38699bd..f461186fc 100644 --- a/entc/integration/edgeschema/ent/predicate/predicate.go +++ b/entc/integration/edgeschema/ent/predicate/predicate.go @@ -15,12 +15,18 @@ type Group func(*sql.Selector) // Relationship is the predicate function for relationship builders. type Relationship func(*sql.Selector) +// Tag is the predicate function for tag builders. +type Tag func(*sql.Selector) + // Tweet is the predicate function for tweet builders. type Tweet func(*sql.Selector) // TweetLike is the predicate function for tweetlike builders. type TweetLike func(*sql.Selector) +// TweetTag is the predicate function for tweettag builders. +type TweetTag func(*sql.Selector) + // User is the predicate function for user builders. type User func(*sql.Selector) diff --git a/entc/integration/edgeschema/ent/runtime.go b/entc/integration/edgeschema/ent/runtime.go index f7489c7f2..d7c5f3e7d 100644 --- a/entc/integration/edgeschema/ent/runtime.go +++ b/entc/integration/edgeschema/ent/runtime.go @@ -10,9 +10,11 @@ import ( "entgo.io/ent/entc/integration/edgeschema/ent/relationship" "entgo.io/ent/entc/integration/edgeschema/ent/schema" "entgo.io/ent/entc/integration/edgeschema/ent/tweetlike" + "entgo.io/ent/entc/integration/edgeschema/ent/tweettag" "entgo.io/ent/entc/integration/edgeschema/ent/user" "entgo.io/ent/entc/integration/edgeschema/ent/usergroup" "entgo.io/ent/entc/integration/edgeschema/ent/usertweet" + "github.com/google/uuid" ) // The init function reads all schema descriptors with runtime code @@ -47,6 +49,16 @@ func init() { tweetlikeDescLikedAt := tweetlikeFields[0].Descriptor() // tweetlike.DefaultLikedAt holds the default value on creation for the liked_at field. tweetlike.DefaultLikedAt = tweetlikeDescLikedAt.Default.(func() time.Time) + tweettagFields := schema.TweetTag{}.Fields() + _ = tweettagFields + // tweettagDescAddedAt is the schema descriptor for added_at field. + tweettagDescAddedAt := tweettagFields[1].Descriptor() + // tweettag.DefaultAddedAt holds the default value on creation for the added_at field. + tweettag.DefaultAddedAt = tweettagDescAddedAt.Default.(func() time.Time) + // tweettagDescID is the schema descriptor for id field. + tweettagDescID := tweettagFields[0].Descriptor() + // tweettag.DefaultID holds the default value on creation for the id field. + tweettag.DefaultID = tweettagDescID.Default.(func() uuid.UUID) userFields := schema.User{}.Fields() _ = userFields // userDescName is the schema descriptor for name field. diff --git a/entc/integration/edgeschema/ent/schema/tag.go b/entc/integration/edgeschema/ent/schema/tag.go new file mode 100644 index 000000000..2de2765b9 --- /dev/null +++ b/entc/integration/edgeschema/ent/schema/tag.go @@ -0,0 +1,31 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +package schema + +import ( + "entgo.io/ent" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" +) + +// Tag holds the schema definition for the Tag entity. +type Tag struct { + ent.Schema +} + +// Fields of the Tag. +func (Tag) Fields() []ent.Field { + return []ent.Field{ + field.String("value"), + } +} + +// Edges of the Tag. +func (Tag) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("tweets", Tweet.Type). + Through("tweet_tags", TweetTag.Type), + } +} diff --git a/entc/integration/edgeschema/ent/schema/tweet.go b/entc/integration/edgeschema/ent/schema/tweet.go index 4f9e61623..11bd74cd1 100644 --- a/entc/integration/edgeschema/ent/schema/tweet.go +++ b/entc/integration/edgeschema/ent/schema/tweet.go @@ -32,5 +32,8 @@ func (Tweet) Edges() []ent.Edge { Ref("tweets"). Through("tweet_user", UserTweet.Type). Comment("The uniqueness is enforced on the edge schema"), + edge.From("tags", Tag.Type). + Ref("tweets"). + Through("tweet_tags", TweetTag.Type), } } diff --git a/entc/integration/edgeschema/ent/schema/tweettag.go b/entc/integration/edgeschema/ent/schema/tweettag.go new file mode 100644 index 000000000..f4140cd39 --- /dev/null +++ b/entc/integration/edgeschema/ent/schema/tweettag.go @@ -0,0 +1,45 @@ +// 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 ( + "time" + + "entgo.io/ent" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" + "github.com/google/uuid" +) + +// TweetTag holds the schema definition for the TweetTag entity. +type TweetTag struct { + ent.Schema +} + +// Fields of the TweetTag. +func (TweetTag) Fields() []ent.Field { + return []ent.Field{ + field.UUID("id", uuid.UUID{}). + Default(uuid.New), + field.Time("added_at"). + Default(time.Now), + field.Int("tag_id"), + field.Int("tweet_id"), + } +} + +// Edges of the TweetTag. +func (TweetTag) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("tag", Tag.Type). + Unique(). + Required(). + Field("tag_id"), + edge.To("tweet", Tweet.Type). + Unique(). + Required(). + Field("tweet_id"), + } +} diff --git a/entc/integration/edgeschema/ent/tag.go b/entc/integration/edgeschema/ent/tag.go new file mode 100644 index 000000000..fd2cc90c0 --- /dev/null +++ b/entc/integration/edgeschema/ent/tag.go @@ -0,0 +1,141 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/entc/integration/edgeschema/ent/tag" +) + +// Tag is the model entity for the Tag schema. +type Tag struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // Value holds the value of the "value" field. + Value string `json:"value,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the TagQuery when eager-loading is set. + Edges TagEdges `json:"edges"` +} + +// TagEdges holds the relations/edges for other nodes in the graph. +type TagEdges struct { + // Tweets holds the value of the tweets edge. + Tweets []*Tweet `json:"tweets,omitempty"` + // TweetTags holds the value of the tweet_tags edge. + TweetTags []*TweetTag `json:"tweet_tags,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool +} + +// TweetsOrErr returns the Tweets value or an error if the edge +// was not loaded in eager-loading. +func (e TagEdges) TweetsOrErr() ([]*Tweet, error) { + if e.loadedTypes[0] { + return e.Tweets, nil + } + return nil, &NotLoadedError{edge: "tweets"} +} + +// TweetTagsOrErr returns the TweetTags value or an error if the edge +// was not loaded in eager-loading. +func (e TagEdges) TweetTagsOrErr() ([]*TweetTag, error) { + if e.loadedTypes[1] { + return e.TweetTags, nil + } + return nil, &NotLoadedError{edge: "tweet_tags"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Tag) scanValues(columns []string) ([]interface{}, error) { + values := make([]interface{}, len(columns)) + for i := range columns { + switch columns[i] { + case tag.FieldID: + values[i] = new(sql.NullInt64) + case tag.FieldValue: + values[i] = new(sql.NullString) + default: + return nil, fmt.Errorf("unexpected column %q for type Tag", columns[i]) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the Tag fields. +func (t *Tag) 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 tag.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + t.ID = int(value.Int64) + case tag.FieldValue: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field value", values[i]) + } else if value.Valid { + t.Value = value.String + } + } + } + return nil +} + +// QueryTweets queries the "tweets" edge of the Tag entity. +func (t *Tag) QueryTweets() *TweetQuery { + return (&TagClient{config: t.config}).QueryTweets(t) +} + +// QueryTweetTags queries the "tweet_tags" edge of the Tag entity. +func (t *Tag) QueryTweetTags() *TweetTagQuery { + return (&TagClient{config: t.config}).QueryTweetTags(t) +} + +// Update returns a builder for updating this Tag. +// Note that you need to call Tag.Unwrap() before calling this method if this Tag +// was returned from a transaction, and the transaction was committed or rolled back. +func (t *Tag) Update() *TagUpdateOne { + return (&TagClient{config: t.config}).UpdateOne(t) +} + +// Unwrap unwraps the Tag entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (t *Tag) Unwrap() *Tag { + _tx, ok := t.config.driver.(*txDriver) + if !ok { + panic("ent: Tag is not a transactional entity") + } + t.config.driver = _tx.drv + return t +} + +// String implements the fmt.Stringer. +func (t *Tag) String() string { + var builder strings.Builder + builder.WriteString("Tag(") + builder.WriteString(fmt.Sprintf("id=%v, ", t.ID)) + builder.WriteString("value=") + builder.WriteString(t.Value) + builder.WriteByte(')') + return builder.String() +} + +// Tags is a parsable slice of Tag. +type Tags []*Tag + +func (t Tags) config(cfg config) { + for _i := range t { + t[_i].config = cfg + } +} diff --git a/entc/integration/edgeschema/ent/tag/tag.go b/entc/integration/edgeschema/ent/tag/tag.go new file mode 100644 index 000000000..38a5a8886 --- /dev/null +++ b/entc/integration/edgeschema/ent/tag/tag.go @@ -0,0 +1,52 @@ +// Code generated by ent, DO NOT EDIT. + +package tag + +const ( + // Label holds the string label denoting the tag type in the database. + Label = "tag" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldValue holds the string denoting the value field in the database. + FieldValue = "value" + // EdgeTweets holds the string denoting the tweets edge name in mutations. + EdgeTweets = "tweets" + // EdgeTweetTags holds the string denoting the tweet_tags edge name in mutations. + EdgeTweetTags = "tweet_tags" + // Table holds the table name of the tag in the database. + Table = "tags" + // TweetsTable is the table that holds the tweets relation/edge. The primary key declared below. + TweetsTable = "tweet_tags" + // TweetsInverseTable is the table name for the Tweet entity. + // It exists in this package in order to avoid circular dependency with the "tweet" package. + TweetsInverseTable = "tweets" + // TweetTagsTable is the table that holds the tweet_tags relation/edge. + TweetTagsTable = "tweet_tags" + // TweetTagsInverseTable is the table name for the TweetTag entity. + // It exists in this package in order to avoid circular dependency with the "tweettag" package. + TweetTagsInverseTable = "tweet_tags" + // TweetTagsColumn is the table column denoting the tweet_tags relation/edge. + TweetTagsColumn = "tag_id" +) + +// Columns holds all SQL columns for tag fields. +var Columns = []string{ + FieldID, + FieldValue, +} + +var ( + // TweetsPrimaryKey and TweetsColumn2 are the table columns denoting the + // primary key for the tweets relation (M2M). + TweetsPrimaryKey = []string{"tag_id", "tweet_id"} +) + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} diff --git a/entc/integration/edgeschema/ent/tag/where.go b/entc/integration/edgeschema/ent/tag/where.go new file mode 100644 index 000000000..3e757b8d9 --- /dev/null +++ b/entc/integration/edgeschema/ent/tag/where.go @@ -0,0 +1,298 @@ +// Code generated by ent, DO NOT EDIT. + +package tag + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/edgeschema/ent/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.Tag { + return predicate.Tag(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.Tag { + return predicate.Tag(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.Tag { + return predicate.Tag(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldID), id)) + }) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.Tag { + return predicate.Tag(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(ids) == 0 { + s.Where(sql.False()) + return + } + v := make([]interface{}, len(ids)) + for i := range v { + v[i] = ids[i] + } + s.Where(sql.In(s.C(FieldID), v...)) + }) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.Tag { + return predicate.Tag(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(ids) == 0 { + s.Where(sql.False()) + return + } + v := make([]interface{}, len(ids)) + for i := range v { + v[i] = ids[i] + } + s.Where(sql.NotIn(s.C(FieldID), v...)) + }) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.Tag { + return predicate.Tag(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldID), id)) + }) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.Tag { + return predicate.Tag(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldID), id)) + }) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.Tag { + return predicate.Tag(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldID), id)) + }) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.Tag { + return predicate.Tag(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldID), id)) + }) +} + +// Value applies equality check predicate on the "value" field. It's identical to ValueEQ. +func Value(v string) predicate.Tag { + return predicate.Tag(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldValue), v)) + }) +} + +// ValueEQ applies the EQ predicate on the "value" field. +func ValueEQ(v string) predicate.Tag { + return predicate.Tag(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldValue), v)) + }) +} + +// ValueNEQ applies the NEQ predicate on the "value" field. +func ValueNEQ(v string) predicate.Tag { + return predicate.Tag(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldValue), v)) + }) +} + +// ValueIn applies the In predicate on the "value" field. +func ValueIn(vs ...string) predicate.Tag { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Tag(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldValue), v...)) + }) +} + +// ValueNotIn applies the NotIn predicate on the "value" field. +func ValueNotIn(vs ...string) predicate.Tag { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Tag(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldValue), v...)) + }) +} + +// ValueGT applies the GT predicate on the "value" field. +func ValueGT(v string) predicate.Tag { + return predicate.Tag(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldValue), v)) + }) +} + +// ValueGTE applies the GTE predicate on the "value" field. +func ValueGTE(v string) predicate.Tag { + return predicate.Tag(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldValue), v)) + }) +} + +// ValueLT applies the LT predicate on the "value" field. +func ValueLT(v string) predicate.Tag { + return predicate.Tag(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldValue), v)) + }) +} + +// ValueLTE applies the LTE predicate on the "value" field. +func ValueLTE(v string) predicate.Tag { + return predicate.Tag(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldValue), v)) + }) +} + +// ValueContains applies the Contains predicate on the "value" field. +func ValueContains(v string) predicate.Tag { + return predicate.Tag(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldValue), v)) + }) +} + +// ValueHasPrefix applies the HasPrefix predicate on the "value" field. +func ValueHasPrefix(v string) predicate.Tag { + return predicate.Tag(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldValue), v)) + }) +} + +// ValueHasSuffix applies the HasSuffix predicate on the "value" field. +func ValueHasSuffix(v string) predicate.Tag { + return predicate.Tag(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldValue), v)) + }) +} + +// ValueEqualFold applies the EqualFold predicate on the "value" field. +func ValueEqualFold(v string) predicate.Tag { + return predicate.Tag(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldValue), v)) + }) +} + +// ValueContainsFold applies the ContainsFold predicate on the "value" field. +func ValueContainsFold(v string) predicate.Tag { + return predicate.Tag(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldValue), v)) + }) +} + +// HasTweets applies the HasEdge predicate on the "tweets" edge. +func HasTweets() predicate.Tag { + return predicate.Tag(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(TweetsTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, TweetsTable, TweetsPrimaryKey...), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasTweetsWith applies the HasEdge predicate on the "tweets" edge with a given conditions (other predicates). +func HasTweetsWith(preds ...predicate.Tweet) predicate.Tag { + return predicate.Tag(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(TweetsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, TweetsTable, TweetsPrimaryKey...), + ) + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasTweetTags applies the HasEdge predicate on the "tweet_tags" edge. +func HasTweetTags() predicate.Tag { + return predicate.Tag(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(TweetTagsTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, TweetTagsTable, TweetTagsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasTweetTagsWith applies the HasEdge predicate on the "tweet_tags" edge with a given conditions (other predicates). +func HasTweetTagsWith(preds ...predicate.TweetTag) predicate.Tag { + return predicate.Tag(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(TweetTagsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, TweetTagsTable, TweetTagsColumn), + ) + 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.Tag) predicate.Tag { + return predicate.Tag(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.Tag) predicate.Tag { + return predicate.Tag(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.Tag) predicate.Tag { + return predicate.Tag(func(s *sql.Selector) { + p(s.Not()) + }) +} diff --git a/entc/integration/edgeschema/ent/tag_create.go b/entc/integration/edgeschema/ent/tag_create.go new file mode 100644 index 000000000..81046084c --- /dev/null +++ b/entc/integration/edgeschema/ent/tag_create.go @@ -0,0 +1,304 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/edgeschema/ent/tag" + "entgo.io/ent/entc/integration/edgeschema/ent/tweet" + "entgo.io/ent/entc/integration/edgeschema/ent/tweettag" + "entgo.io/ent/schema/field" + "github.com/google/uuid" +) + +// TagCreate is the builder for creating a Tag entity. +type TagCreate struct { + config + mutation *TagMutation + hooks []Hook +} + +// SetValue sets the "value" field. +func (tc *TagCreate) SetValue(s string) *TagCreate { + tc.mutation.SetValue(s) + return tc +} + +// AddTweetIDs adds the "tweets" edge to the Tweet entity by IDs. +func (tc *TagCreate) AddTweetIDs(ids ...int) *TagCreate { + tc.mutation.AddTweetIDs(ids...) + return tc +} + +// AddTweets adds the "tweets" edges to the Tweet entity. +func (tc *TagCreate) AddTweets(t ...*Tweet) *TagCreate { + ids := make([]int, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return tc.AddTweetIDs(ids...) +} + +// AddTweetTagIDs adds the "tweet_tags" edge to the TweetTag entity by IDs. +func (tc *TagCreate) AddTweetTagIDs(ids ...uuid.UUID) *TagCreate { + tc.mutation.AddTweetTagIDs(ids...) + return tc +} + +// AddTweetTags adds the "tweet_tags" edges to the TweetTag entity. +func (tc *TagCreate) AddTweetTags(t ...*TweetTag) *TagCreate { + ids := make([]uuid.UUID, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return tc.AddTweetTagIDs(ids...) +} + +// Mutation returns the TagMutation object of the builder. +func (tc *TagCreate) Mutation() *TagMutation { + return tc.mutation +} + +// Save creates the Tag in the database. +func (tc *TagCreate) Save(ctx context.Context) (*Tag, error) { + var ( + err error + node *Tag + ) + if len(tc.hooks) == 0 { + if err = tc.check(); err != nil { + return nil, err + } + node, err = tc.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*TagMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = tc.check(); err != nil { + return nil, err + } + tc.mutation = mutation + if node, err = tc.sqlSave(ctx); err != nil { + return nil, err + } + mutation.id = &node.ID + mutation.done = true + return node, err + }) + for i := len(tc.hooks) - 1; i >= 0; i-- { + if tc.hooks[i] == nil { + return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = tc.hooks[i](mut) + } + v, err := mut.Mutate(ctx, tc.mutation) + if err != nil { + return nil, err + } + nv, ok := v.(*Tag) + if !ok { + return nil, fmt.Errorf("unexpected node type %T returned from TagMutation", v) + } + node = nv + } + return node, err +} + +// SaveX calls Save and panics if Save returns an error. +func (tc *TagCreate) SaveX(ctx context.Context) *Tag { + v, err := tc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (tc *TagCreate) Exec(ctx context.Context) error { + _, err := tc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (tc *TagCreate) ExecX(ctx context.Context) { + if err := tc.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (tc *TagCreate) check() error { + if _, ok := tc.mutation.Value(); !ok { + return &ValidationError{Name: "value", err: errors.New(`ent: missing required field "Tag.value"`)} + } + return nil +} + +func (tc *TagCreate) sqlSave(ctx context.Context) (*Tag, error) { + _node, _spec := tc.createSpec() + if err := sqlgraph.CreateNode(ctx, tc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + return _node, nil +} + +func (tc *TagCreate) createSpec() (*Tag, *sqlgraph.CreateSpec) { + var ( + _node = &Tag{config: tc.config} + _spec = &sqlgraph.CreateSpec{ + Table: tag.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: tag.FieldID, + }, + } + ) + if value, ok := tc.mutation.Value(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: tag.FieldValue, + }) + _node.Value = value + } + if nodes := tc.mutation.TweetsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: tag.TweetsTable, + Columns: tag.TweetsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: tweet.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &TweetTagCreate{config: tc.config, mutation: newTweetTagMutation(tc.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + if specE.ID.Value != nil { + edge.Target.Fields = append(edge.Target.Fields, specE.ID) + } + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := tc.mutation.TweetTagsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: tag.TweetTagsTable, + Columns: []string{tag.TweetTagsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: tweettag.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// TagCreateBulk is the builder for creating many Tag entities in bulk. +type TagCreateBulk struct { + config + builders []*TagCreate +} + +// Save creates the Tag entities in the database. +func (tcb *TagCreateBulk) Save(ctx context.Context) ([]*Tag, error) { + specs := make([]*sqlgraph.CreateSpec, len(tcb.builders)) + nodes := make([]*Tag, len(tcb.builders)) + mutators := make([]Mutator, len(tcb.builders)) + for i := range tcb.builders { + func(i int, root context.Context) { + builder := tcb.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*TagMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + nodes[i], specs[i] = builder.createSpec() + var err error + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, tcb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, tcb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, tcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (tcb *TagCreateBulk) SaveX(ctx context.Context) []*Tag { + v, err := tcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (tcb *TagCreateBulk) Exec(ctx context.Context) error { + _, err := tcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (tcb *TagCreateBulk) ExecX(ctx context.Context) { + if err := tcb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entc/integration/edgeschema/ent/tag_delete.go b/entc/integration/edgeschema/ent/tag_delete.go new file mode 100644 index 000000000..32a5c6555 --- /dev/null +++ b/entc/integration/edgeschema/ent/tag_delete.go @@ -0,0 +1,115 @@ +// 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/edgeschema/ent/predicate" + "entgo.io/ent/entc/integration/edgeschema/ent/tag" + "entgo.io/ent/schema/field" +) + +// TagDelete is the builder for deleting a Tag entity. +type TagDelete struct { + config + hooks []Hook + mutation *TagMutation +} + +// Where appends a list predicates to the TagDelete builder. +func (td *TagDelete) Where(ps ...predicate.Tag) *TagDelete { + td.mutation.Where(ps...) + return td +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (td *TagDelete) Exec(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(td.hooks) == 0 { + affected, err = td.sqlExec(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*TagMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + td.mutation = mutation + affected, err = td.sqlExec(ctx) + mutation.done = true + return affected, err + }) + for i := len(td.hooks) - 1; i >= 0; i-- { + if td.hooks[i] == nil { + return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = td.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, td.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// ExecX is like Exec, but panics if an error occurs. +func (td *TagDelete) ExecX(ctx context.Context) int { + n, err := td.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (td *TagDelete) sqlExec(ctx context.Context) (int, error) { + _spec := &sqlgraph.DeleteSpec{ + Node: &sqlgraph.NodeSpec{ + Table: tag.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: tag.FieldID, + }, + }, + } + if ps := td.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, td.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return affected, err +} + +// TagDeleteOne is the builder for deleting a single Tag entity. +type TagDeleteOne struct { + td *TagDelete +} + +// Exec executes the deletion query. +func (tdo *TagDeleteOne) Exec(ctx context.Context) error { + n, err := tdo.td.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{tag.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (tdo *TagDeleteOne) ExecX(ctx context.Context) { + tdo.td.ExecX(ctx) +} diff --git a/entc/integration/edgeschema/ent/tag_query.go b/entc/integration/edgeschema/ent/tag_query.go new file mode 100644 index 000000000..ae5d3a247 --- /dev/null +++ b/entc/integration/edgeschema/ent/tag_query.go @@ -0,0 +1,686 @@ +// 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/edgeschema/ent/predicate" + "entgo.io/ent/entc/integration/edgeschema/ent/tag" + "entgo.io/ent/entc/integration/edgeschema/ent/tweet" + "entgo.io/ent/entc/integration/edgeschema/ent/tweettag" + "entgo.io/ent/schema/field" +) + +// TagQuery is the builder for querying Tag entities. +type TagQuery struct { + config + limit *int + offset *int + unique *bool + order []OrderFunc + fields []string + predicates []predicate.Tag + // eager-loading edges. + withTweets *TweetQuery + withTweetTags *TweetTagQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the TagQuery builder. +func (tq *TagQuery) Where(ps ...predicate.Tag) *TagQuery { + tq.predicates = append(tq.predicates, ps...) + return tq +} + +// Limit adds a limit step to the query. +func (tq *TagQuery) Limit(limit int) *TagQuery { + tq.limit = &limit + return tq +} + +// Offset adds an offset step to the query. +func (tq *TagQuery) Offset(offset int) *TagQuery { + tq.offset = &offset + return tq +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (tq *TagQuery) Unique(unique bool) *TagQuery { + tq.unique = &unique + return tq +} + +// Order adds an order step to the query. +func (tq *TagQuery) Order(o ...OrderFunc) *TagQuery { + tq.order = append(tq.order, o...) + return tq +} + +// QueryTweets chains the current query on the "tweets" edge. +func (tq *TagQuery) QueryTweets() *TweetQuery { + query := &TweetQuery{config: tq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := tq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := tq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(tag.Table, tag.FieldID, selector), + sqlgraph.To(tweet.Table, tweet.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, tag.TweetsTable, tag.TweetsPrimaryKey...), + ) + fromU = sqlgraph.SetNeighbors(tq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryTweetTags chains the current query on the "tweet_tags" edge. +func (tq *TagQuery) QueryTweetTags() *TweetTagQuery { + query := &TweetTagQuery{config: tq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := tq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := tq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(tag.Table, tag.FieldID, selector), + sqlgraph.To(tweettag.Table, tweettag.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, tag.TweetTagsTable, tag.TweetTagsColumn), + ) + fromU = sqlgraph.SetNeighbors(tq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first Tag entity from the query. +// Returns a *NotFoundError when no Tag was found. +func (tq *TagQuery) First(ctx context.Context) (*Tag, error) { + nodes, err := tq.Limit(1).All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{tag.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (tq *TagQuery) FirstX(ctx context.Context) *Tag { + node, err := tq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Tag ID from the query. +// Returns a *NotFoundError when no Tag ID was found. +func (tq *TagQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = tq.Limit(1).IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{tag.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (tq *TagQuery) FirstIDX(ctx context.Context) int { + id, err := tq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Tag entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Tag entity is found. +// Returns a *NotFoundError when no Tag entities are found. +func (tq *TagQuery) Only(ctx context.Context) (*Tag, error) { + nodes, err := tq.Limit(2).All(ctx) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{tag.Label} + default: + return nil, &NotSingularError{tag.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (tq *TagQuery) OnlyX(ctx context.Context) *Tag { + node, err := tq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Tag ID in the query. +// Returns a *NotSingularError when more than one Tag ID is found. +// Returns a *NotFoundError when no entities are found. +func (tq *TagQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = tq.Limit(2).IDs(ctx); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{tag.Label} + default: + err = &NotSingularError{tag.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (tq *TagQuery) OnlyIDX(ctx context.Context) int { + id, err := tq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Tags. +func (tq *TagQuery) All(ctx context.Context) ([]*Tag, error) { + if err := tq.prepareQuery(ctx); err != nil { + return nil, err + } + return tq.sqlAll(ctx) +} + +// AllX is like All, but panics if an error occurs. +func (tq *TagQuery) AllX(ctx context.Context) []*Tag { + nodes, err := tq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Tag IDs. +func (tq *TagQuery) IDs(ctx context.Context) ([]int, error) { + var ids []int + if err := tq.Select(tag.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (tq *TagQuery) IDsX(ctx context.Context) []int { + ids, err := tq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (tq *TagQuery) Count(ctx context.Context) (int, error) { + if err := tq.prepareQuery(ctx); err != nil { + return 0, err + } + return tq.sqlCount(ctx) +} + +// CountX is like Count, but panics if an error occurs. +func (tq *TagQuery) CountX(ctx context.Context) int { + count, err := tq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (tq *TagQuery) Exist(ctx context.Context) (bool, error) { + if err := tq.prepareQuery(ctx); err != nil { + return false, err + } + return tq.sqlExist(ctx) +} + +// ExistX is like Exist, but panics if an error occurs. +func (tq *TagQuery) ExistX(ctx context.Context) bool { + exist, err := tq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the TagQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (tq *TagQuery) Clone() *TagQuery { + if tq == nil { + return nil + } + return &TagQuery{ + config: tq.config, + limit: tq.limit, + offset: tq.offset, + order: append([]OrderFunc{}, tq.order...), + predicates: append([]predicate.Tag{}, tq.predicates...), + withTweets: tq.withTweets.Clone(), + withTweetTags: tq.withTweetTags.Clone(), + // clone intermediate query. + sql: tq.sql.Clone(), + path: tq.path, + unique: tq.unique, + } +} + +// WithTweets tells the query-builder to eager-load the nodes that are connected to +// the "tweets" edge. The optional arguments are used to configure the query builder of the edge. +func (tq *TagQuery) WithTweets(opts ...func(*TweetQuery)) *TagQuery { + query := &TweetQuery{config: tq.config} + for _, opt := range opts { + opt(query) + } + tq.withTweets = query + return tq +} + +// WithTweetTags tells the query-builder to eager-load the nodes that are connected to +// the "tweet_tags" edge. The optional arguments are used to configure the query builder of the edge. +func (tq *TagQuery) WithTweetTags(opts ...func(*TweetTagQuery)) *TagQuery { + query := &TweetTagQuery{config: tq.config} + for _, opt := range opts { + opt(query) + } + tq.withTweetTags = query + return tq +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// Value string `json:"value,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Tag.Query(). +// GroupBy(tag.FieldValue). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +// +func (tq *TagQuery) GroupBy(field string, fields ...string) *TagGroupBy { + grbuild := &TagGroupBy{config: tq.config} + grbuild.fields = append([]string{field}, fields...) + grbuild.path = func(ctx context.Context) (prev *sql.Selector, err error) { + if err := tq.prepareQuery(ctx); err != nil { + return nil, err + } + return tq.sqlQuery(ctx), nil + } + grbuild.label = tag.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. +// +// Example: +// +// var v []struct { +// Value string `json:"value,omitempty"` +// } +// +// client.Tag.Query(). +// Select(tag.FieldValue). +// Scan(ctx, &v) +// +func (tq *TagQuery) Select(fields ...string) *TagSelect { + tq.fields = append(tq.fields, fields...) + selbuild := &TagSelect{TagQuery: tq} + selbuild.label = tag.Label + selbuild.flds, selbuild.scan = &tq.fields, selbuild.Scan + return selbuild +} + +func (tq *TagQuery) prepareQuery(ctx context.Context) error { + for _, f := range tq.fields { + if !tag.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if tq.path != nil { + prev, err := tq.path(ctx) + if err != nil { + return err + } + tq.sql = prev + } + return nil +} + +func (tq *TagQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Tag, error) { + var ( + nodes = []*Tag{} + _spec = tq.querySpec() + loadedTypes = [2]bool{ + tq.withTweets != nil, + tq.withTweetTags != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]interface{}, error) { + return (*Tag).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []interface{}) error { + node := &Tag{config: tq.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, tq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + + if query := tq.withTweets; query != nil { + edgeids := make([]driver.Value, len(nodes)) + byid := make(map[int]*Tag) + nids := make(map[int]map[*Tag]struct{}) + for i, node := range nodes { + edgeids[i] = node.ID + byid[node.ID] = node + node.Edges.Tweets = []*Tweet{} + } + query.Where(func(s *sql.Selector) { + joinT := sql.Table(tag.TweetsTable) + s.Join(joinT).On(s.C(tweet.FieldID), joinT.C(tag.TweetsPrimaryKey[1])) + s.Where(sql.InValues(joinT.C(tag.TweetsPrimaryKey[0]), edgeids...)) + columns := s.SelectedColumns() + s.Select(joinT.C(tag.TweetsPrimaryKey[0])) + s.AppendSelect(columns...) + s.SetDistinct(false) + }) + neighbors, err := query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) { + assign := spec.Assign + values := spec.ScanValues + spec.ScanValues = func(columns []string) ([]interface{}, error) { + values, err := values(columns[1:]) + if err != nil { + return nil, err + } + return append([]interface{}{new(sql.NullInt64)}, values...), nil + } + spec.Assign = func(columns []string, values []interface{}) error { + outValue := int(values[0].(*sql.NullInt64).Int64) + inValue := int(values[1].(*sql.NullInt64).Int64) + if nids[inValue] == nil { + nids[inValue] = map[*Tag]struct{}{byid[outValue]: struct{}{}} + return assign(columns[1:], values[1:]) + } + nids[inValue][byid[outValue]] = struct{}{} + return nil + } + }) + if err != nil { + return nil, err + } + for _, n := range neighbors { + nodes, ok := nids[n.ID] + if !ok { + return nil, fmt.Errorf(`unexpected "tweets" node returned %v`, n.ID) + } + for kn := range nodes { + kn.Edges.Tweets = append(kn.Edges.Tweets, n) + } + } + } + + if query := tq.withTweetTags; query != nil { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int]*Tag) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + nodes[i].Edges.TweetTags = []*TweetTag{} + } + query.Where(predicate.TweetTag(func(s *sql.Selector) { + s.Where(sql.InValues(tag.TweetTagsColumn, fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, n := range neighbors { + fk := n.TagID + node, ok := nodeids[fk] + if !ok { + return nil, fmt.Errorf(`unexpected foreign-key "tag_id" returned %v for node %v`, fk, n.ID) + } + node.Edges.TweetTags = append(node.Edges.TweetTags, n) + } + } + + return nodes, nil +} + +func (tq *TagQuery) sqlCount(ctx context.Context) (int, error) { + _spec := tq.querySpec() + _spec.Node.Columns = tq.fields + if len(tq.fields) > 0 { + _spec.Unique = tq.unique != nil && *tq.unique + } + return sqlgraph.CountNodes(ctx, tq.driver, _spec) +} + +func (tq *TagQuery) sqlExist(ctx context.Context) (bool, error) { + n, err := tq.sqlCount(ctx) + if err != nil { + return false, fmt.Errorf("ent: check existence: %w", err) + } + return n > 0, nil +} + +func (tq *TagQuery) querySpec() *sqlgraph.QuerySpec { + _spec := &sqlgraph.QuerySpec{ + Node: &sqlgraph.NodeSpec{ + Table: tag.Table, + Columns: tag.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: tag.FieldID, + }, + }, + From: tq.sql, + Unique: true, + } + if unique := tq.unique; unique != nil { + _spec.Unique = *unique + } + if fields := tq.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, tag.FieldID) + for i := range fields { + if fields[i] != tag.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := tq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := tq.limit; limit != nil { + _spec.Limit = *limit + } + if offset := tq.offset; offset != nil { + _spec.Offset = *offset + } + if ps := tq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (tq *TagQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(tq.driver.Dialect()) + t1 := builder.Table(tag.Table) + columns := tq.fields + if len(columns) == 0 { + columns = tag.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if tq.sql != nil { + selector = tq.sql + selector.Select(selector.Columns(columns...)...) + } + if tq.unique != nil && *tq.unique { + selector.Distinct() + } + for _, p := range tq.predicates { + p(selector) + } + for _, p := range tq.order { + p(selector) + } + if offset := tq.offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := tq.limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// TagGroupBy is the group-by builder for Tag entities. +type TagGroupBy 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 (tgb *TagGroupBy) Aggregate(fns ...AggregateFunc) *TagGroupBy { + tgb.fns = append(tgb.fns, fns...) + return tgb +} + +// Scan applies the group-by query and scans the result into the given value. +func (tgb *TagGroupBy) Scan(ctx context.Context, v interface{}) error { + query, err := tgb.path(ctx) + if err != nil { + return err + } + tgb.sql = query + return tgb.sqlScan(ctx, v) +} + +func (tgb *TagGroupBy) sqlScan(ctx context.Context, v interface{}) error { + for _, f := range tgb.fields { + if !tag.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + } + } + selector := tgb.sqlQuery() + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := tgb.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +func (tgb *TagGroupBy) sqlQuery() *sql.Selector { + selector := tgb.sql.Select() + aggregation := make([]string, 0, len(tgb.fns)) + for _, fn := range tgb.fns { + aggregation = append(aggregation, fn(selector)) + } + // If no columns were selected in a custom aggregation function, the default + // selection is the fields used for "group-by", and the aggregation functions. + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(tgb.fields)+len(tgb.fns)) + for _, f := range tgb.fields { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + return selector.GroupBy(selector.Columns(tgb.fields...)...) +} + +// TagSelect is the builder for selecting fields of Tag entities. +type TagSelect struct { + *TagQuery + selector + // intermediate query (i.e. traversal path). + sql *sql.Selector +} + +// Scan applies the selector query and scans the result into the given value. +func (ts *TagSelect) Scan(ctx context.Context, v interface{}) error { + if err := ts.prepareQuery(ctx); err != nil { + return err + } + ts.sql = ts.TagQuery.sqlQuery(ctx) + return ts.sqlScan(ctx, v) +} + +func (ts *TagSelect) sqlScan(ctx context.Context, v interface{}) error { + rows := &sql.Rows{} + query, args := ts.sql.Query() + if err := ts.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/entc/integration/edgeschema/ent/tag_update.go b/entc/integration/edgeschema/ent/tag_update.go new file mode 100644 index 000000000..d235772c1 --- /dev/null +++ b/entc/integration/edgeschema/ent/tag_update.go @@ -0,0 +1,676 @@ +// 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/edgeschema/ent/predicate" + "entgo.io/ent/entc/integration/edgeschema/ent/tag" + "entgo.io/ent/entc/integration/edgeschema/ent/tweet" + "entgo.io/ent/entc/integration/edgeschema/ent/tweettag" + "entgo.io/ent/schema/field" + "github.com/google/uuid" +) + +// TagUpdate is the builder for updating Tag entities. +type TagUpdate struct { + config + hooks []Hook + mutation *TagMutation +} + +// Where appends a list predicates to the TagUpdate builder. +func (tu *TagUpdate) Where(ps ...predicate.Tag) *TagUpdate { + tu.mutation.Where(ps...) + return tu +} + +// SetValue sets the "value" field. +func (tu *TagUpdate) SetValue(s string) *TagUpdate { + tu.mutation.SetValue(s) + return tu +} + +// AddTweetIDs adds the "tweets" edge to the Tweet entity by IDs. +func (tu *TagUpdate) AddTweetIDs(ids ...int) *TagUpdate { + tu.mutation.AddTweetIDs(ids...) + return tu +} + +// AddTweets adds the "tweets" edges to the Tweet entity. +func (tu *TagUpdate) AddTweets(t ...*Tweet) *TagUpdate { + ids := make([]int, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return tu.AddTweetIDs(ids...) +} + +// AddTweetTagIDs adds the "tweet_tags" edge to the TweetTag entity by IDs. +func (tu *TagUpdate) AddTweetTagIDs(ids ...uuid.UUID) *TagUpdate { + tu.mutation.AddTweetTagIDs(ids...) + return tu +} + +// AddTweetTags adds the "tweet_tags" edges to the TweetTag entity. +func (tu *TagUpdate) AddTweetTags(t ...*TweetTag) *TagUpdate { + ids := make([]uuid.UUID, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return tu.AddTweetTagIDs(ids...) +} + +// Mutation returns the TagMutation object of the builder. +func (tu *TagUpdate) Mutation() *TagMutation { + return tu.mutation +} + +// ClearTweets clears all "tweets" edges to the Tweet entity. +func (tu *TagUpdate) ClearTweets() *TagUpdate { + tu.mutation.ClearTweets() + return tu +} + +// RemoveTweetIDs removes the "tweets" edge to Tweet entities by IDs. +func (tu *TagUpdate) RemoveTweetIDs(ids ...int) *TagUpdate { + tu.mutation.RemoveTweetIDs(ids...) + return tu +} + +// RemoveTweets removes "tweets" edges to Tweet entities. +func (tu *TagUpdate) RemoveTweets(t ...*Tweet) *TagUpdate { + ids := make([]int, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return tu.RemoveTweetIDs(ids...) +} + +// ClearTweetTags clears all "tweet_tags" edges to the TweetTag entity. +func (tu *TagUpdate) ClearTweetTags() *TagUpdate { + tu.mutation.ClearTweetTags() + return tu +} + +// RemoveTweetTagIDs removes the "tweet_tags" edge to TweetTag entities by IDs. +func (tu *TagUpdate) RemoveTweetTagIDs(ids ...uuid.UUID) *TagUpdate { + tu.mutation.RemoveTweetTagIDs(ids...) + return tu +} + +// RemoveTweetTags removes "tweet_tags" edges to TweetTag entities. +func (tu *TagUpdate) RemoveTweetTags(t ...*TweetTag) *TagUpdate { + ids := make([]uuid.UUID, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return tu.RemoveTweetTagIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (tu *TagUpdate) Save(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(tu.hooks) == 0 { + affected, err = tu.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*TagMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + tu.mutation = mutation + affected, err = tu.sqlSave(ctx) + mutation.done = true + return affected, err + }) + for i := len(tu.hooks) - 1; i >= 0; i-- { + if tu.hooks[i] == nil { + return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = tu.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, tu.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// SaveX is like Save, but panics if an error occurs. +func (tu *TagUpdate) SaveX(ctx context.Context) int { + affected, err := tu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (tu *TagUpdate) Exec(ctx context.Context) error { + _, err := tu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (tu *TagUpdate) ExecX(ctx context.Context) { + if err := tu.Exec(ctx); err != nil { + panic(err) + } +} + +func (tu *TagUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: tag.Table, + Columns: tag.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: tag.FieldID, + }, + }, + } + if ps := tu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := tu.mutation.Value(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: tag.FieldValue, + }) + } + if tu.mutation.TweetsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: tag.TweetsTable, + Columns: tag.TweetsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: tweet.FieldID, + }, + }, + } + createE := &TweetTagCreate{config: tu.config, mutation: newTweetTagMutation(tu.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + if specE.ID.Value != nil { + edge.Target.Fields = append(edge.Target.Fields, specE.ID) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tu.mutation.RemovedTweetsIDs(); len(nodes) > 0 && !tu.mutation.TweetsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: tag.TweetsTable, + Columns: tag.TweetsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: tweet.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &TweetTagCreate{config: tu.config, mutation: newTweetTagMutation(tu.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + if specE.ID.Value != nil { + edge.Target.Fields = append(edge.Target.Fields, specE.ID) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tu.mutation.TweetsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: tag.TweetsTable, + Columns: tag.TweetsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: tweet.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &TweetTagCreate{config: tu.config, mutation: newTweetTagMutation(tu.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + if specE.ID.Value != nil { + edge.Target.Fields = append(edge.Target.Fields, specE.ID) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if tu.mutation.TweetTagsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: tag.TweetTagsTable, + Columns: []string{tag.TweetTagsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: tweettag.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tu.mutation.RemovedTweetTagsIDs(); len(nodes) > 0 && !tu.mutation.TweetTagsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: tag.TweetTagsTable, + Columns: []string{tag.TweetTagsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: tweettag.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tu.mutation.TweetTagsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: tag.TweetTagsTable, + Columns: []string{tag.TweetTagsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: tweettag.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if n, err = sqlgraph.UpdateNodes(ctx, tu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{tag.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + return n, nil +} + +// TagUpdateOne is the builder for updating a single Tag entity. +type TagUpdateOne struct { + config + fields []string + hooks []Hook + mutation *TagMutation +} + +// SetValue sets the "value" field. +func (tuo *TagUpdateOne) SetValue(s string) *TagUpdateOne { + tuo.mutation.SetValue(s) + return tuo +} + +// AddTweetIDs adds the "tweets" edge to the Tweet entity by IDs. +func (tuo *TagUpdateOne) AddTweetIDs(ids ...int) *TagUpdateOne { + tuo.mutation.AddTweetIDs(ids...) + return tuo +} + +// AddTweets adds the "tweets" edges to the Tweet entity. +func (tuo *TagUpdateOne) AddTweets(t ...*Tweet) *TagUpdateOne { + ids := make([]int, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return tuo.AddTweetIDs(ids...) +} + +// AddTweetTagIDs adds the "tweet_tags" edge to the TweetTag entity by IDs. +func (tuo *TagUpdateOne) AddTweetTagIDs(ids ...uuid.UUID) *TagUpdateOne { + tuo.mutation.AddTweetTagIDs(ids...) + return tuo +} + +// AddTweetTags adds the "tweet_tags" edges to the TweetTag entity. +func (tuo *TagUpdateOne) AddTweetTags(t ...*TweetTag) *TagUpdateOne { + ids := make([]uuid.UUID, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return tuo.AddTweetTagIDs(ids...) +} + +// Mutation returns the TagMutation object of the builder. +func (tuo *TagUpdateOne) Mutation() *TagMutation { + return tuo.mutation +} + +// ClearTweets clears all "tweets" edges to the Tweet entity. +func (tuo *TagUpdateOne) ClearTweets() *TagUpdateOne { + tuo.mutation.ClearTweets() + return tuo +} + +// RemoveTweetIDs removes the "tweets" edge to Tweet entities by IDs. +func (tuo *TagUpdateOne) RemoveTweetIDs(ids ...int) *TagUpdateOne { + tuo.mutation.RemoveTweetIDs(ids...) + return tuo +} + +// RemoveTweets removes "tweets" edges to Tweet entities. +func (tuo *TagUpdateOne) RemoveTweets(t ...*Tweet) *TagUpdateOne { + ids := make([]int, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return tuo.RemoveTweetIDs(ids...) +} + +// ClearTweetTags clears all "tweet_tags" edges to the TweetTag entity. +func (tuo *TagUpdateOne) ClearTweetTags() *TagUpdateOne { + tuo.mutation.ClearTweetTags() + return tuo +} + +// RemoveTweetTagIDs removes the "tweet_tags" edge to TweetTag entities by IDs. +func (tuo *TagUpdateOne) RemoveTweetTagIDs(ids ...uuid.UUID) *TagUpdateOne { + tuo.mutation.RemoveTweetTagIDs(ids...) + return tuo +} + +// RemoveTweetTags removes "tweet_tags" edges to TweetTag entities. +func (tuo *TagUpdateOne) RemoveTweetTags(t ...*TweetTag) *TagUpdateOne { + ids := make([]uuid.UUID, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return tuo.RemoveTweetTagIDs(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 (tuo *TagUpdateOne) Select(field string, fields ...string) *TagUpdateOne { + tuo.fields = append([]string{field}, fields...) + return tuo +} + +// Save executes the query and returns the updated Tag entity. +func (tuo *TagUpdateOne) Save(ctx context.Context) (*Tag, error) { + var ( + err error + node *Tag + ) + if len(tuo.hooks) == 0 { + node, err = tuo.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*TagMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + tuo.mutation = mutation + node, err = tuo.sqlSave(ctx) + mutation.done = true + return node, err + }) + for i := len(tuo.hooks) - 1; i >= 0; i-- { + if tuo.hooks[i] == nil { + return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = tuo.hooks[i](mut) + } + v, err := mut.Mutate(ctx, tuo.mutation) + if err != nil { + return nil, err + } + nv, ok := v.(*Tag) + if !ok { + return nil, fmt.Errorf("unexpected node type %T returned from TagMutation", v) + } + node = nv + } + return node, err +} + +// SaveX is like Save, but panics if an error occurs. +func (tuo *TagUpdateOne) SaveX(ctx context.Context) *Tag { + node, err := tuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (tuo *TagUpdateOne) Exec(ctx context.Context) error { + _, err := tuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (tuo *TagUpdateOne) ExecX(ctx context.Context) { + if err := tuo.Exec(ctx); err != nil { + panic(err) + } +} + +func (tuo *TagUpdateOne) sqlSave(ctx context.Context) (_node *Tag, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: tag.Table, + Columns: tag.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: tag.FieldID, + }, + }, + } + id, ok := tuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Tag.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := tuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, tag.FieldID) + for _, f := range fields { + if !tag.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != tag.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := tuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := tuo.mutation.Value(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: tag.FieldValue, + }) + } + if tuo.mutation.TweetsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: tag.TweetsTable, + Columns: tag.TweetsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: tweet.FieldID, + }, + }, + } + createE := &TweetTagCreate{config: tuo.config, mutation: newTweetTagMutation(tuo.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + if specE.ID.Value != nil { + edge.Target.Fields = append(edge.Target.Fields, specE.ID) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tuo.mutation.RemovedTweetsIDs(); len(nodes) > 0 && !tuo.mutation.TweetsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: tag.TweetsTable, + Columns: tag.TweetsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: tweet.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &TweetTagCreate{config: tuo.config, mutation: newTweetTagMutation(tuo.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + if specE.ID.Value != nil { + edge.Target.Fields = append(edge.Target.Fields, specE.ID) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tuo.mutation.TweetsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: tag.TweetsTable, + Columns: tag.TweetsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: tweet.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &TweetTagCreate{config: tuo.config, mutation: newTweetTagMutation(tuo.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + if specE.ID.Value != nil { + edge.Target.Fields = append(edge.Target.Fields, specE.ID) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if tuo.mutation.TweetTagsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: tag.TweetTagsTable, + Columns: []string{tag.TweetTagsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: tweettag.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tuo.mutation.RemovedTweetTagsIDs(); len(nodes) > 0 && !tuo.mutation.TweetTagsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: tag.TweetTagsTable, + Columns: []string{tag.TweetTagsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: tweettag.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tuo.mutation.TweetTagsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: tag.TweetTagsTable, + Columns: []string{tag.TweetTagsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: tweettag.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &Tag{config: tuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, tuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{tag.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + return _node, nil +} diff --git a/entc/integration/edgeschema/ent/tweet.go b/entc/integration/edgeschema/ent/tweet.go index 2ff15a7f1..41ba60300 100644 --- a/entc/integration/edgeschema/ent/tweet.go +++ b/entc/integration/edgeschema/ent/tweet.go @@ -28,13 +28,17 @@ type TweetEdges struct { LikedUsers []*User `json:"liked_users,omitempty"` // The uniqueness is enforced on the edge schema User []*User `json:"user,omitempty"` + // Tags holds the value of the tags edge. + Tags []*Tag `json:"tags,omitempty"` // Likes holds the value of the likes edge. Likes []*TweetLike `json:"likes,omitempty"` // TweetUser holds the value of the tweet_user edge. TweetUser []*UserTweet `json:"tweet_user,omitempty"` + // TweetTags holds the value of the tweet_tags edge. + TweetTags []*TweetTag `json:"tweet_tags,omitempty"` // loadedTypes holds the information for reporting if a // type was loaded (or requested) in eager-loading or not. - loadedTypes [4]bool + loadedTypes [6]bool } // LikedUsersOrErr returns the LikedUsers value or an error if the edge @@ -55,10 +59,19 @@ func (e TweetEdges) UserOrErr() ([]*User, error) { return nil, &NotLoadedError{edge: "user"} } +// TagsOrErr returns the Tags value or an error if the edge +// was not loaded in eager-loading. +func (e TweetEdges) TagsOrErr() ([]*Tag, error) { + if e.loadedTypes[2] { + return e.Tags, nil + } + return nil, &NotLoadedError{edge: "tags"} +} + // LikesOrErr returns the Likes value or an error if the edge // was not loaded in eager-loading. func (e TweetEdges) LikesOrErr() ([]*TweetLike, error) { - if e.loadedTypes[2] { + if e.loadedTypes[3] { return e.Likes, nil } return nil, &NotLoadedError{edge: "likes"} @@ -67,12 +80,21 @@ func (e TweetEdges) LikesOrErr() ([]*TweetLike, error) { // TweetUserOrErr returns the TweetUser value or an error if the edge // was not loaded in eager-loading. func (e TweetEdges) TweetUserOrErr() ([]*UserTweet, error) { - if e.loadedTypes[3] { + if e.loadedTypes[4] { return e.TweetUser, nil } return nil, &NotLoadedError{edge: "tweet_user"} } +// TweetTagsOrErr returns the TweetTags value or an error if the edge +// was not loaded in eager-loading. +func (e TweetEdges) TweetTagsOrErr() ([]*TweetTag, error) { + if e.loadedTypes[5] { + return e.TweetTags, nil + } + return nil, &NotLoadedError{edge: "tweet_tags"} +} + // scanValues returns the types for scanning values from sql.Rows. func (*Tweet) scanValues(columns []string) ([]interface{}, error) { values := make([]interface{}, len(columns)) @@ -124,6 +146,11 @@ func (t *Tweet) QueryUser() *UserQuery { return (&TweetClient{config: t.config}).QueryUser(t) } +// QueryTags queries the "tags" edge of the Tweet entity. +func (t *Tweet) QueryTags() *TagQuery { + return (&TweetClient{config: t.config}).QueryTags(t) +} + // QueryLikes queries the "likes" edge of the Tweet entity. func (t *Tweet) QueryLikes() *TweetLikeQuery { return (&TweetClient{config: t.config}).QueryLikes(t) @@ -134,6 +161,11 @@ func (t *Tweet) QueryTweetUser() *UserTweetQuery { return (&TweetClient{config: t.config}).QueryTweetUser(t) } +// QueryTweetTags queries the "tweet_tags" edge of the Tweet entity. +func (t *Tweet) QueryTweetTags() *TweetTagQuery { + return (&TweetClient{config: t.config}).QueryTweetTags(t) +} + // Update returns a builder for updating this Tweet. // Note that you need to call Tweet.Unwrap() before calling this method if this Tweet // was returned from a transaction, and the transaction was committed or rolled back. diff --git a/entc/integration/edgeschema/ent/tweet/tweet.go b/entc/integration/edgeschema/ent/tweet/tweet.go index 650ffa2c9..a8eaed50f 100644 --- a/entc/integration/edgeschema/ent/tweet/tweet.go +++ b/entc/integration/edgeschema/ent/tweet/tweet.go @@ -13,10 +13,14 @@ const ( EdgeLikedUsers = "liked_users" // EdgeUser holds the string denoting the user edge name in mutations. EdgeUser = "user" + // EdgeTags holds the string denoting the tags edge name in mutations. + EdgeTags = "tags" // EdgeLikes holds the string denoting the likes edge name in mutations. EdgeLikes = "likes" // EdgeTweetUser holds the string denoting the tweet_user edge name in mutations. EdgeTweetUser = "tweet_user" + // EdgeTweetTags holds the string denoting the tweet_tags edge name in mutations. + EdgeTweetTags = "tweet_tags" // Table holds the table name of the tweet in the database. Table = "tweets" // LikedUsersTable is the table that holds the liked_users relation/edge. The primary key declared below. @@ -29,6 +33,11 @@ const ( // UserInverseTable is the table name for the User entity. // It exists in this package in order to avoid circular dependency with the "user" package. UserInverseTable = "users" + // TagsTable is the table that holds the tags relation/edge. The primary key declared below. + TagsTable = "tweet_tags" + // TagsInverseTable is the table name for the Tag entity. + // It exists in this package in order to avoid circular dependency with the "tag" package. + TagsInverseTable = "tags" // LikesTable is the table that holds the likes relation/edge. LikesTable = "tweet_likes" // LikesInverseTable is the table name for the TweetLike entity. @@ -43,6 +52,13 @@ const ( TweetUserInverseTable = "user_tweets" // TweetUserColumn is the table column denoting the tweet_user relation/edge. TweetUserColumn = "tweet_id" + // TweetTagsTable is the table that holds the tweet_tags relation/edge. + TweetTagsTable = "tweet_tags" + // TweetTagsInverseTable is the table name for the TweetTag entity. + // It exists in this package in order to avoid circular dependency with the "tweettag" package. + TweetTagsInverseTable = "tweet_tags" + // TweetTagsColumn is the table column denoting the tweet_tags relation/edge. + TweetTagsColumn = "tweet_id" ) // Columns holds all SQL columns for tweet fields. @@ -58,6 +74,9 @@ var ( // UserPrimaryKey and UserColumn2 are the table columns denoting the // primary key for the user relation (M2M). UserPrimaryKey = []string{"user_id", "tweet_id"} + // TagsPrimaryKey and TagsColumn2 are the table columns denoting the + // primary key for the tags relation (M2M). + TagsPrimaryKey = []string{"tag_id", "tweet_id"} ) // ValidColumn reports if the column name is valid (part of the table columns). diff --git a/entc/integration/edgeschema/ent/tweet/where.go b/entc/integration/edgeschema/ent/tweet/where.go index 024e4cfd8..39da58b90 100644 --- a/entc/integration/edgeschema/ent/tweet/where.go +++ b/entc/integration/edgeschema/ent/tweet/where.go @@ -265,6 +265,34 @@ func HasUserWith(preds ...predicate.User) predicate.Tweet { }) } +// HasTags applies the HasEdge predicate on the "tags" edge. +func HasTags() predicate.Tweet { + return predicate.Tweet(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(TagsTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, TagsTable, TagsPrimaryKey...), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasTagsWith applies the HasEdge predicate on the "tags" edge with a given conditions (other predicates). +func HasTagsWith(preds ...predicate.Tag) predicate.Tweet { + return predicate.Tweet(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(TagsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, TagsTable, TagsPrimaryKey...), + ) + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + // HasLikes applies the HasEdge predicate on the "likes" edge. func HasLikes() predicate.Tweet { return predicate.Tweet(func(s *sql.Selector) { @@ -321,6 +349,34 @@ func HasTweetUserWith(preds ...predicate.UserTweet) predicate.Tweet { }) } +// HasTweetTags applies the HasEdge predicate on the "tweet_tags" edge. +func HasTweetTags() predicate.Tweet { + return predicate.Tweet(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(TweetTagsTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, TweetTagsTable, TweetTagsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasTweetTagsWith applies the HasEdge predicate on the "tweet_tags" edge with a given conditions (other predicates). +func HasTweetTagsWith(preds ...predicate.TweetTag) predicate.Tweet { + return predicate.Tweet(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(TweetTagsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, TweetTagsTable, TweetTagsColumn), + ) + 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.Tweet) predicate.Tweet { return predicate.Tweet(func(s *sql.Selector) { diff --git a/entc/integration/edgeschema/ent/tweet_create.go b/entc/integration/edgeschema/ent/tweet_create.go index 14e845422..6e7fb5e21 100644 --- a/entc/integration/edgeschema/ent/tweet_create.go +++ b/entc/integration/edgeschema/ent/tweet_create.go @@ -8,10 +8,13 @@ import ( "fmt" "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/edgeschema/ent/tag" "entgo.io/ent/entc/integration/edgeschema/ent/tweet" + "entgo.io/ent/entc/integration/edgeschema/ent/tweettag" "entgo.io/ent/entc/integration/edgeschema/ent/user" "entgo.io/ent/entc/integration/edgeschema/ent/usertweet" "entgo.io/ent/schema/field" + "github.com/google/uuid" ) // TweetCreate is the builder for creating a Tweet entity. @@ -57,6 +60,21 @@ func (tc *TweetCreate) AddUser(u ...*User) *TweetCreate { return tc.AddUserIDs(ids...) } +// AddTagIDs adds the "tags" edge to the Tag entity by IDs. +func (tc *TweetCreate) AddTagIDs(ids ...int) *TweetCreate { + tc.mutation.AddTagIDs(ids...) + return tc +} + +// AddTags adds the "tags" edges to the Tag entity. +func (tc *TweetCreate) AddTags(t ...*Tag) *TweetCreate { + ids := make([]int, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return tc.AddTagIDs(ids...) +} + // AddTweetUserIDs adds the "tweet_user" edge to the UserTweet entity by IDs. func (tc *TweetCreate) AddTweetUserIDs(ids ...int) *TweetCreate { tc.mutation.AddTweetUserIDs(ids...) @@ -72,6 +90,21 @@ func (tc *TweetCreate) AddTweetUser(u ...*UserTweet) *TweetCreate { return tc.AddTweetUserIDs(ids...) } +// AddTweetTagIDs adds the "tweet_tags" edge to the TweetTag entity by IDs. +func (tc *TweetCreate) AddTweetTagIDs(ids ...uuid.UUID) *TweetCreate { + tc.mutation.AddTweetTagIDs(ids...) + return tc +} + +// AddTweetTags adds the "tweet_tags" edges to the TweetTag entity. +func (tc *TweetCreate) AddTweetTags(t ...*TweetTag) *TweetCreate { + ids := make([]uuid.UUID, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return tc.AddTweetTagIDs(ids...) +} + // Mutation returns the TweetMutation object of the builder. func (tc *TweetCreate) Mutation() *TweetMutation { return tc.mutation @@ -232,6 +265,32 @@ func (tc *TweetCreate) createSpec() (*Tweet, *sqlgraph.CreateSpec) { edge.Target.Fields = specE.Fields _spec.Edges = append(_spec.Edges, edge) } + if nodes := tc.mutation.TagsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: tweet.TagsTable, + Columns: tweet.TagsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: tag.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &TweetTagCreate{config: tc.config, mutation: newTweetTagMutation(tc.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + if specE.ID.Value != nil { + edge.Target.Fields = append(edge.Target.Fields, specE.ID) + } + _spec.Edges = append(_spec.Edges, edge) + } if nodes := tc.mutation.TweetUserIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, @@ -251,6 +310,25 @@ func (tc *TweetCreate) createSpec() (*Tweet, *sqlgraph.CreateSpec) { } _spec.Edges = append(_spec.Edges, edge) } + if nodes := tc.mutation.TweetTagsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: tweet.TweetTagsTable, + Columns: []string{tweet.TweetTagsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: tweettag.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } return _node, _spec } diff --git a/entc/integration/edgeschema/ent/tweet_query.go b/entc/integration/edgeschema/ent/tweet_query.go index 56800cf17..402101e50 100644 --- a/entc/integration/edgeschema/ent/tweet_query.go +++ b/entc/integration/edgeschema/ent/tweet_query.go @@ -11,8 +11,10 @@ import ( "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/entc/integration/edgeschema/ent/predicate" + "entgo.io/ent/entc/integration/edgeschema/ent/tag" "entgo.io/ent/entc/integration/edgeschema/ent/tweet" "entgo.io/ent/entc/integration/edgeschema/ent/tweetlike" + "entgo.io/ent/entc/integration/edgeschema/ent/tweettag" "entgo.io/ent/entc/integration/edgeschema/ent/user" "entgo.io/ent/entc/integration/edgeschema/ent/usertweet" "entgo.io/ent/schema/field" @@ -30,8 +32,10 @@ type TweetQuery struct { // eager-loading edges. withLikedUsers *UserQuery withUser *UserQuery + withTags *TagQuery withLikes *TweetLikeQuery withTweetUser *UserTweetQuery + withTweetTags *TweetTagQuery // intermediate query (i.e. traversal path). sql *sql.Selector path func(context.Context) (*sql.Selector, error) @@ -112,6 +116,28 @@ func (tq *TweetQuery) QueryUser() *UserQuery { return query } +// QueryTags chains the current query on the "tags" edge. +func (tq *TweetQuery) QueryTags() *TagQuery { + query := &TagQuery{config: tq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := tq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := tq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(tweet.Table, tweet.FieldID, selector), + sqlgraph.To(tag.Table, tag.FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, tweet.TagsTable, tweet.TagsPrimaryKey...), + ) + fromU = sqlgraph.SetNeighbors(tq.driver.Dialect(), step) + return fromU, nil + } + return query +} + // QueryLikes chains the current query on the "likes" edge. func (tq *TweetQuery) QueryLikes() *TweetLikeQuery { query := &TweetLikeQuery{config: tq.config} @@ -156,6 +182,28 @@ func (tq *TweetQuery) QueryTweetUser() *UserTweetQuery { return query } +// QueryTweetTags chains the current query on the "tweet_tags" edge. +func (tq *TweetQuery) QueryTweetTags() *TweetTagQuery { + query := &TweetTagQuery{config: tq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := tq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := tq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(tweet.Table, tweet.FieldID, selector), + sqlgraph.To(tweettag.Table, tweettag.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, tweet.TweetTagsTable, tweet.TweetTagsColumn), + ) + fromU = sqlgraph.SetNeighbors(tq.driver.Dialect(), step) + return fromU, nil + } + return query +} + // First returns the first Tweet entity from the query. // Returns a *NotFoundError when no Tweet was found. func (tq *TweetQuery) First(ctx context.Context) (*Tweet, error) { @@ -339,8 +387,10 @@ func (tq *TweetQuery) Clone() *TweetQuery { predicates: append([]predicate.Tweet{}, tq.predicates...), withLikedUsers: tq.withLikedUsers.Clone(), withUser: tq.withUser.Clone(), + withTags: tq.withTags.Clone(), withLikes: tq.withLikes.Clone(), withTweetUser: tq.withTweetUser.Clone(), + withTweetTags: tq.withTweetTags.Clone(), // clone intermediate query. sql: tq.sql.Clone(), path: tq.path, @@ -370,6 +420,17 @@ func (tq *TweetQuery) WithUser(opts ...func(*UserQuery)) *TweetQuery { return tq } +// WithTags tells the query-builder to eager-load the nodes that are connected to +// the "tags" edge. The optional arguments are used to configure the query builder of the edge. +func (tq *TweetQuery) WithTags(opts ...func(*TagQuery)) *TweetQuery { + query := &TagQuery{config: tq.config} + for _, opt := range opts { + opt(query) + } + tq.withTags = query + return tq +} + // WithLikes tells the query-builder to eager-load the nodes that are connected to // the "likes" edge. The optional arguments are used to configure the query builder of the edge. func (tq *TweetQuery) WithLikes(opts ...func(*TweetLikeQuery)) *TweetQuery { @@ -392,6 +453,17 @@ func (tq *TweetQuery) WithTweetUser(opts ...func(*UserTweetQuery)) *TweetQuery { return tq } +// WithTweetTags tells the query-builder to eager-load the nodes that are connected to +// the "tweet_tags" edge. The optional arguments are used to configure the query builder of the edge. +func (tq *TweetQuery) WithTweetTags(opts ...func(*TweetTagQuery)) *TweetQuery { + query := &TweetTagQuery{config: tq.config} + for _, opt := range opts { + opt(query) + } + tq.withTweetTags = query + return tq +} + // GroupBy is used to group vertices by one or more fields/columns. // It is often used with aggregate functions, like: count, max, mean, min, sum. // @@ -462,11 +534,13 @@ func (tq *TweetQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Tweet, var ( nodes = []*Tweet{} _spec = tq.querySpec() - loadedTypes = [4]bool{ + loadedTypes = [6]bool{ tq.withLikedUsers != nil, tq.withUser != nil, + tq.withTags != nil, tq.withLikes != nil, tq.withTweetUser != nil, + tq.withTweetTags != nil, } ) _spec.ScanValues = func(columns []string) ([]interface{}, error) { @@ -594,6 +668,59 @@ func (tq *TweetQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Tweet, } } + if query := tq.withTags; query != nil { + edgeids := make([]driver.Value, len(nodes)) + byid := make(map[int]*Tweet) + nids := make(map[int]map[*Tweet]struct{}) + for i, node := range nodes { + edgeids[i] = node.ID + byid[node.ID] = node + node.Edges.Tags = []*Tag{} + } + query.Where(func(s *sql.Selector) { + joinT := sql.Table(tweet.TagsTable) + s.Join(joinT).On(s.C(tag.FieldID), joinT.C(tweet.TagsPrimaryKey[0])) + s.Where(sql.InValues(joinT.C(tweet.TagsPrimaryKey[1]), edgeids...)) + columns := s.SelectedColumns() + s.Select(joinT.C(tweet.TagsPrimaryKey[1])) + s.AppendSelect(columns...) + s.SetDistinct(false) + }) + neighbors, err := query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) { + assign := spec.Assign + values := spec.ScanValues + spec.ScanValues = func(columns []string) ([]interface{}, error) { + values, err := values(columns[1:]) + if err != nil { + return nil, err + } + return append([]interface{}{new(sql.NullInt64)}, values...), nil + } + spec.Assign = func(columns []string, values []interface{}) error { + outValue := int(values[0].(*sql.NullInt64).Int64) + inValue := int(values[1].(*sql.NullInt64).Int64) + if nids[inValue] == nil { + nids[inValue] = map[*Tweet]struct{}{byid[outValue]: struct{}{}} + return assign(columns[1:], values[1:]) + } + nids[inValue][byid[outValue]] = struct{}{} + return nil + } + }) + if err != nil { + return nil, err + } + for _, n := range neighbors { + nodes, ok := nids[n.ID] + if !ok { + return nil, fmt.Errorf(`unexpected "tags" node returned %v`, n.ID) + } + for kn := range nodes { + kn.Edges.Tags = append(kn.Edges.Tags, n) + } + } + } + if query := tq.withLikes; query != nil { fks := make([]driver.Value, 0, len(nodes)) nodeids := make(map[int]*Tweet) @@ -644,6 +771,31 @@ func (tq *TweetQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Tweet, } } + if query := tq.withTweetTags; query != nil { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int]*Tweet) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + nodes[i].Edges.TweetTags = []*TweetTag{} + } + query.Where(predicate.TweetTag(func(s *sql.Selector) { + s.Where(sql.InValues(tweet.TweetTagsColumn, fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, n := range neighbors { + fk := n.TweetID + node, ok := nodeids[fk] + if !ok { + return nil, fmt.Errorf(`unexpected foreign-key "tweet_id" returned %v for node %v`, fk, n.ID) + } + node.Edges.TweetTags = append(node.Edges.TweetTags, n) + } + } + return nodes, nil } diff --git a/entc/integration/edgeschema/ent/tweet_update.go b/entc/integration/edgeschema/ent/tweet_update.go index 383bedcdb..a04fa01a8 100644 --- a/entc/integration/edgeschema/ent/tweet_update.go +++ b/entc/integration/edgeschema/ent/tweet_update.go @@ -10,10 +10,13 @@ import ( "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/entc/integration/edgeschema/ent/predicate" + "entgo.io/ent/entc/integration/edgeschema/ent/tag" "entgo.io/ent/entc/integration/edgeschema/ent/tweet" + "entgo.io/ent/entc/integration/edgeschema/ent/tweettag" "entgo.io/ent/entc/integration/edgeschema/ent/user" "entgo.io/ent/entc/integration/edgeschema/ent/usertweet" "entgo.io/ent/schema/field" + "github.com/google/uuid" ) // TweetUpdate is the builder for updating Tweet entities. @@ -65,6 +68,21 @@ func (tu *TweetUpdate) AddUser(u ...*User) *TweetUpdate { return tu.AddUserIDs(ids...) } +// AddTagIDs adds the "tags" edge to the Tag entity by IDs. +func (tu *TweetUpdate) AddTagIDs(ids ...int) *TweetUpdate { + tu.mutation.AddTagIDs(ids...) + return tu +} + +// AddTags adds the "tags" edges to the Tag entity. +func (tu *TweetUpdate) AddTags(t ...*Tag) *TweetUpdate { + ids := make([]int, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return tu.AddTagIDs(ids...) +} + // AddTweetUserIDs adds the "tweet_user" edge to the UserTweet entity by IDs. func (tu *TweetUpdate) AddTweetUserIDs(ids ...int) *TweetUpdate { tu.mutation.AddTweetUserIDs(ids...) @@ -80,6 +98,21 @@ func (tu *TweetUpdate) AddTweetUser(u ...*UserTweet) *TweetUpdate { return tu.AddTweetUserIDs(ids...) } +// AddTweetTagIDs adds the "tweet_tags" edge to the TweetTag entity by IDs. +func (tu *TweetUpdate) AddTweetTagIDs(ids ...uuid.UUID) *TweetUpdate { + tu.mutation.AddTweetTagIDs(ids...) + return tu +} + +// AddTweetTags adds the "tweet_tags" edges to the TweetTag entity. +func (tu *TweetUpdate) AddTweetTags(t ...*TweetTag) *TweetUpdate { + ids := make([]uuid.UUID, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return tu.AddTweetTagIDs(ids...) +} + // Mutation returns the TweetMutation object of the builder. func (tu *TweetUpdate) Mutation() *TweetMutation { return tu.mutation @@ -127,6 +160,27 @@ func (tu *TweetUpdate) RemoveUser(u ...*User) *TweetUpdate { return tu.RemoveUserIDs(ids...) } +// ClearTags clears all "tags" edges to the Tag entity. +func (tu *TweetUpdate) ClearTags() *TweetUpdate { + tu.mutation.ClearTags() + return tu +} + +// RemoveTagIDs removes the "tags" edge to Tag entities by IDs. +func (tu *TweetUpdate) RemoveTagIDs(ids ...int) *TweetUpdate { + tu.mutation.RemoveTagIDs(ids...) + return tu +} + +// RemoveTags removes "tags" edges to Tag entities. +func (tu *TweetUpdate) RemoveTags(t ...*Tag) *TweetUpdate { + ids := make([]int, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return tu.RemoveTagIDs(ids...) +} + // ClearTweetUser clears all "tweet_user" edges to the UserTweet entity. func (tu *TweetUpdate) ClearTweetUser() *TweetUpdate { tu.mutation.ClearTweetUser() @@ -148,6 +202,27 @@ func (tu *TweetUpdate) RemoveTweetUser(u ...*UserTweet) *TweetUpdate { return tu.RemoveTweetUserIDs(ids...) } +// ClearTweetTags clears all "tweet_tags" edges to the TweetTag entity. +func (tu *TweetUpdate) ClearTweetTags() *TweetUpdate { + tu.mutation.ClearTweetTags() + return tu +} + +// RemoveTweetTagIDs removes the "tweet_tags" edge to TweetTag entities by IDs. +func (tu *TweetUpdate) RemoveTweetTagIDs(ids ...uuid.UUID) *TweetUpdate { + tu.mutation.RemoveTweetTagIDs(ids...) + return tu +} + +// RemoveTweetTags removes "tweet_tags" edges to TweetTag entities. +func (tu *TweetUpdate) RemoveTweetTags(t ...*TweetTag) *TweetUpdate { + ids := make([]uuid.UUID, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return tu.RemoveTweetTagIDs(ids...) +} + // Save executes the query and returns the number of nodes affected by the update operation. func (tu *TweetUpdate) Save(ctx context.Context) (int, error) { var ( @@ -359,6 +434,81 @@ func (tu *TweetUpdate) sqlSave(ctx context.Context) (n int, err error) { edge.Target.Fields = specE.Fields _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if tu.mutation.TagsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: tweet.TagsTable, + Columns: tweet.TagsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: tag.FieldID, + }, + }, + } + createE := &TweetTagCreate{config: tu.config, mutation: newTweetTagMutation(tu.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + if specE.ID.Value != nil { + edge.Target.Fields = append(edge.Target.Fields, specE.ID) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tu.mutation.RemovedTagsIDs(); len(nodes) > 0 && !tu.mutation.TagsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: tweet.TagsTable, + Columns: tweet.TagsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: tag.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &TweetTagCreate{config: tu.config, mutation: newTweetTagMutation(tu.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + if specE.ID.Value != nil { + edge.Target.Fields = append(edge.Target.Fields, specE.ID) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tu.mutation.TagsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: tweet.TagsTable, + Columns: tweet.TagsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: tag.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &TweetTagCreate{config: tu.config, mutation: newTweetTagMutation(tu.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + if specE.ID.Value != nil { + edge.Target.Fields = append(edge.Target.Fields, specE.ID) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } if tu.mutation.TweetUserCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, @@ -413,6 +563,60 @@ func (tu *TweetUpdate) sqlSave(ctx context.Context) (n int, err error) { } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if tu.mutation.TweetTagsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: tweet.TweetTagsTable, + Columns: []string{tweet.TweetTagsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: tweettag.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tu.mutation.RemovedTweetTagsIDs(); len(nodes) > 0 && !tu.mutation.TweetTagsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: tweet.TweetTagsTable, + Columns: []string{tweet.TweetTagsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: tweettag.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tu.mutation.TweetTagsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: tweet.TweetTagsTable, + Columns: []string{tweet.TweetTagsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: tweettag.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } if n, err = sqlgraph.UpdateNodes(ctx, tu.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{tweet.Label} @@ -468,6 +672,21 @@ func (tuo *TweetUpdateOne) AddUser(u ...*User) *TweetUpdateOne { return tuo.AddUserIDs(ids...) } +// AddTagIDs adds the "tags" edge to the Tag entity by IDs. +func (tuo *TweetUpdateOne) AddTagIDs(ids ...int) *TweetUpdateOne { + tuo.mutation.AddTagIDs(ids...) + return tuo +} + +// AddTags adds the "tags" edges to the Tag entity. +func (tuo *TweetUpdateOne) AddTags(t ...*Tag) *TweetUpdateOne { + ids := make([]int, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return tuo.AddTagIDs(ids...) +} + // AddTweetUserIDs adds the "tweet_user" edge to the UserTweet entity by IDs. func (tuo *TweetUpdateOne) AddTweetUserIDs(ids ...int) *TweetUpdateOne { tuo.mutation.AddTweetUserIDs(ids...) @@ -483,6 +702,21 @@ func (tuo *TweetUpdateOne) AddTweetUser(u ...*UserTweet) *TweetUpdateOne { return tuo.AddTweetUserIDs(ids...) } +// AddTweetTagIDs adds the "tweet_tags" edge to the TweetTag entity by IDs. +func (tuo *TweetUpdateOne) AddTweetTagIDs(ids ...uuid.UUID) *TweetUpdateOne { + tuo.mutation.AddTweetTagIDs(ids...) + return tuo +} + +// AddTweetTags adds the "tweet_tags" edges to the TweetTag entity. +func (tuo *TweetUpdateOne) AddTweetTags(t ...*TweetTag) *TweetUpdateOne { + ids := make([]uuid.UUID, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return tuo.AddTweetTagIDs(ids...) +} + // Mutation returns the TweetMutation object of the builder. func (tuo *TweetUpdateOne) Mutation() *TweetMutation { return tuo.mutation @@ -530,6 +764,27 @@ func (tuo *TweetUpdateOne) RemoveUser(u ...*User) *TweetUpdateOne { return tuo.RemoveUserIDs(ids...) } +// ClearTags clears all "tags" edges to the Tag entity. +func (tuo *TweetUpdateOne) ClearTags() *TweetUpdateOne { + tuo.mutation.ClearTags() + return tuo +} + +// RemoveTagIDs removes the "tags" edge to Tag entities by IDs. +func (tuo *TweetUpdateOne) RemoveTagIDs(ids ...int) *TweetUpdateOne { + tuo.mutation.RemoveTagIDs(ids...) + return tuo +} + +// RemoveTags removes "tags" edges to Tag entities. +func (tuo *TweetUpdateOne) RemoveTags(t ...*Tag) *TweetUpdateOne { + ids := make([]int, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return tuo.RemoveTagIDs(ids...) +} + // ClearTweetUser clears all "tweet_user" edges to the UserTweet entity. func (tuo *TweetUpdateOne) ClearTweetUser() *TweetUpdateOne { tuo.mutation.ClearTweetUser() @@ -551,6 +806,27 @@ func (tuo *TweetUpdateOne) RemoveTweetUser(u ...*UserTweet) *TweetUpdateOne { return tuo.RemoveTweetUserIDs(ids...) } +// ClearTweetTags clears all "tweet_tags" edges to the TweetTag entity. +func (tuo *TweetUpdateOne) ClearTweetTags() *TweetUpdateOne { + tuo.mutation.ClearTweetTags() + return tuo +} + +// RemoveTweetTagIDs removes the "tweet_tags" edge to TweetTag entities by IDs. +func (tuo *TweetUpdateOne) RemoveTweetTagIDs(ids ...uuid.UUID) *TweetUpdateOne { + tuo.mutation.RemoveTweetTagIDs(ids...) + return tuo +} + +// RemoveTweetTags removes "tweet_tags" edges to TweetTag entities. +func (tuo *TweetUpdateOne) RemoveTweetTags(t ...*TweetTag) *TweetUpdateOne { + ids := make([]uuid.UUID, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return tuo.RemoveTweetTagIDs(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 (tuo *TweetUpdateOne) Select(field string, fields ...string) *TweetUpdateOne { @@ -792,6 +1068,81 @@ func (tuo *TweetUpdateOne) sqlSave(ctx context.Context) (_node *Tweet, err error edge.Target.Fields = specE.Fields _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if tuo.mutation.TagsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: tweet.TagsTable, + Columns: tweet.TagsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: tag.FieldID, + }, + }, + } + createE := &TweetTagCreate{config: tuo.config, mutation: newTweetTagMutation(tuo.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + if specE.ID.Value != nil { + edge.Target.Fields = append(edge.Target.Fields, specE.ID) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tuo.mutation.RemovedTagsIDs(); len(nodes) > 0 && !tuo.mutation.TagsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: tweet.TagsTable, + Columns: tweet.TagsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: tag.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &TweetTagCreate{config: tuo.config, mutation: newTweetTagMutation(tuo.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + if specE.ID.Value != nil { + edge.Target.Fields = append(edge.Target.Fields, specE.ID) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tuo.mutation.TagsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: tweet.TagsTable, + Columns: tweet.TagsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: tag.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &TweetTagCreate{config: tuo.config, mutation: newTweetTagMutation(tuo.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + if specE.ID.Value != nil { + edge.Target.Fields = append(edge.Target.Fields, specE.ID) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } if tuo.mutation.TweetUserCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, @@ -846,6 +1197,60 @@ func (tuo *TweetUpdateOne) sqlSave(ctx context.Context) (_node *Tweet, err error } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if tuo.mutation.TweetTagsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: tweet.TweetTagsTable, + Columns: []string{tweet.TweetTagsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: tweettag.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tuo.mutation.RemovedTweetTagsIDs(); len(nodes) > 0 && !tuo.mutation.TweetTagsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: tweet.TweetTagsTable, + Columns: []string{tweet.TweetTagsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: tweettag.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tuo.mutation.TweetTagsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: tweet.TweetTagsTable, + Columns: []string{tweet.TweetTagsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: tweettag.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } _node = &Tweet{config: tuo.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues diff --git a/entc/integration/edgeschema/ent/tweettag.go b/entc/integration/edgeschema/ent/tweettag.go new file mode 100644 index 000000000..1211810fe --- /dev/null +++ b/entc/integration/edgeschema/ent/tweettag.go @@ -0,0 +1,179 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/entc/integration/edgeschema/ent/tag" + "entgo.io/ent/entc/integration/edgeschema/ent/tweet" + "entgo.io/ent/entc/integration/edgeschema/ent/tweettag" + "github.com/google/uuid" +) + +// TweetTag is the model entity for the TweetTag schema. +type TweetTag struct { + config `json:"-"` + // ID of the ent. + ID uuid.UUID `json:"id,omitempty"` + // AddedAt holds the value of the "added_at" field. + AddedAt time.Time `json:"added_at,omitempty"` + // TagID holds the value of the "tag_id" field. + TagID int `json:"tag_id,omitempty"` + // TweetID holds the value of the "tweet_id" field. + TweetID int `json:"tweet_id,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the TweetTagQuery when eager-loading is set. + Edges TweetTagEdges `json:"edges"` +} + +// TweetTagEdges holds the relations/edges for other nodes in the graph. +type TweetTagEdges struct { + // Tag holds the value of the tag edge. + Tag *Tag `json:"tag,omitempty"` + // Tweet holds the value of the tweet edge. + Tweet *Tweet `json:"tweet,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool +} + +// TagOrErr returns the Tag value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e TweetTagEdges) TagOrErr() (*Tag, error) { + if e.loadedTypes[0] { + if e.Tag == nil { + // The edge tag was loaded in eager-loading, + // but was not found. + return nil, &NotFoundError{label: tag.Label} + } + return e.Tag, nil + } + return nil, &NotLoadedError{edge: "tag"} +} + +// TweetOrErr returns the Tweet value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e TweetTagEdges) TweetOrErr() (*Tweet, error) { + if e.loadedTypes[1] { + if e.Tweet == nil { + // The edge tweet was loaded in eager-loading, + // but was not found. + return nil, &NotFoundError{label: tweet.Label} + } + return e.Tweet, nil + } + return nil, &NotLoadedError{edge: "tweet"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*TweetTag) scanValues(columns []string) ([]interface{}, error) { + values := make([]interface{}, len(columns)) + for i := range columns { + switch columns[i] { + case tweettag.FieldTagID, tweettag.FieldTweetID: + values[i] = new(sql.NullInt64) + case tweettag.FieldAddedAt: + values[i] = new(sql.NullTime) + case tweettag.FieldID: + values[i] = new(uuid.UUID) + default: + return nil, fmt.Errorf("unexpected column %q for type TweetTag", columns[i]) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the TweetTag fields. +func (tt *TweetTag) 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 tweettag.FieldID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value != nil { + tt.ID = *value + } + case tweettag.FieldAddedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field added_at", values[i]) + } else if value.Valid { + tt.AddedAt = value.Time + } + case tweettag.FieldTagID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field tag_id", values[i]) + } else if value.Valid { + tt.TagID = int(value.Int64) + } + case tweettag.FieldTweetID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field tweet_id", values[i]) + } else if value.Valid { + tt.TweetID = int(value.Int64) + } + } + } + return nil +} + +// QueryTag queries the "tag" edge of the TweetTag entity. +func (tt *TweetTag) QueryTag() *TagQuery { + return (&TweetTagClient{config: tt.config}).QueryTag(tt) +} + +// QueryTweet queries the "tweet" edge of the TweetTag entity. +func (tt *TweetTag) QueryTweet() *TweetQuery { + return (&TweetTagClient{config: tt.config}).QueryTweet(tt) +} + +// Update returns a builder for updating this TweetTag. +// Note that you need to call TweetTag.Unwrap() before calling this method if this TweetTag +// was returned from a transaction, and the transaction was committed or rolled back. +func (tt *TweetTag) Update() *TweetTagUpdateOne { + return (&TweetTagClient{config: tt.config}).UpdateOne(tt) +} + +// Unwrap unwraps the TweetTag 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 (tt *TweetTag) Unwrap() *TweetTag { + _tx, ok := tt.config.driver.(*txDriver) + if !ok { + panic("ent: TweetTag is not a transactional entity") + } + tt.config.driver = _tx.drv + return tt +} + +// String implements the fmt.Stringer. +func (tt *TweetTag) String() string { + var builder strings.Builder + builder.WriteString("TweetTag(") + builder.WriteString(fmt.Sprintf("id=%v, ", tt.ID)) + builder.WriteString("added_at=") + builder.WriteString(tt.AddedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("tag_id=") + builder.WriteString(fmt.Sprintf("%v", tt.TagID)) + builder.WriteString(", ") + builder.WriteString("tweet_id=") + builder.WriteString(fmt.Sprintf("%v", tt.TweetID)) + builder.WriteByte(')') + return builder.String() +} + +// TweetTags is a parsable slice of TweetTag. +type TweetTags []*TweetTag + +func (tt TweetTags) config(cfg config) { + for _i := range tt { + tt[_i].config = cfg + } +} diff --git a/entc/integration/edgeschema/ent/tweettag/tweettag.go b/entc/integration/edgeschema/ent/tweettag/tweettag.go new file mode 100644 index 000000000..61011afbb --- /dev/null +++ b/entc/integration/edgeschema/ent/tweettag/tweettag.go @@ -0,0 +1,67 @@ +// Code generated by ent, DO NOT EDIT. + +package tweettag + +import ( + "time" + + "github.com/google/uuid" +) + +const ( + // Label holds the string label denoting the tweettag type in the database. + Label = "tweet_tag" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldAddedAt holds the string denoting the added_at field in the database. + FieldAddedAt = "added_at" + // FieldTagID holds the string denoting the tag_id field in the database. + FieldTagID = "tag_id" + // FieldTweetID holds the string denoting the tweet_id field in the database. + FieldTweetID = "tweet_id" + // EdgeTag holds the string denoting the tag edge name in mutations. + EdgeTag = "tag" + // EdgeTweet holds the string denoting the tweet edge name in mutations. + EdgeTweet = "tweet" + // Table holds the table name of the tweettag in the database. + Table = "tweet_tags" + // TagTable is the table that holds the tag relation/edge. + TagTable = "tweet_tags" + // TagInverseTable is the table name for the Tag entity. + // It exists in this package in order to avoid circular dependency with the "tag" package. + TagInverseTable = "tags" + // TagColumn is the table column denoting the tag relation/edge. + TagColumn = "tag_id" + // TweetTable is the table that holds the tweet relation/edge. + TweetTable = "tweet_tags" + // TweetInverseTable is the table name for the Tweet entity. + // It exists in this package in order to avoid circular dependency with the "tweet" package. + TweetInverseTable = "tweets" + // TweetColumn is the table column denoting the tweet relation/edge. + TweetColumn = "tweet_id" +) + +// Columns holds all SQL columns for tweettag fields. +var Columns = []string{ + FieldID, + FieldAddedAt, + FieldTagID, + FieldTweetID, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // DefaultAddedAt holds the default value on creation for the "added_at" field. + DefaultAddedAt func() time.Time + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() uuid.UUID +) diff --git a/entc/integration/edgeschema/ent/tweettag/where.go b/entc/integration/edgeschema/ent/tweettag/where.go new file mode 100644 index 000000000..7b2e80504 --- /dev/null +++ b/entc/integration/edgeschema/ent/tweettag/where.go @@ -0,0 +1,376 @@ +// Code generated by ent, DO NOT EDIT. + +package tweettag + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/edgeschema/ent/predicate" + "github.com/google/uuid" +) + +// ID filters vertices based on their ID field. +func ID(id uuid.UUID) predicate.TweetTag { + return predicate.TweetTag(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id uuid.UUID) predicate.TweetTag { + return predicate.TweetTag(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id uuid.UUID) predicate.TweetTag { + return predicate.TweetTag(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldID), id)) + }) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...uuid.UUID) predicate.TweetTag { + return predicate.TweetTag(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 ...uuid.UUID) predicate.TweetTag { + return predicate.TweetTag(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 uuid.UUID) predicate.TweetTag { + return predicate.TweetTag(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldID), id)) + }) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id uuid.UUID) predicate.TweetTag { + return predicate.TweetTag(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldID), id)) + }) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id uuid.UUID) predicate.TweetTag { + return predicate.TweetTag(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldID), id)) + }) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id uuid.UUID) predicate.TweetTag { + return predicate.TweetTag(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldID), id)) + }) +} + +// AddedAt applies equality check predicate on the "added_at" field. It's identical to AddedAtEQ. +func AddedAt(v time.Time) predicate.TweetTag { + return predicate.TweetTag(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldAddedAt), v)) + }) +} + +// TagID applies equality check predicate on the "tag_id" field. It's identical to TagIDEQ. +func TagID(v int) predicate.TweetTag { + return predicate.TweetTag(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldTagID), v)) + }) +} + +// TweetID applies equality check predicate on the "tweet_id" field. It's identical to TweetIDEQ. +func TweetID(v int) predicate.TweetTag { + return predicate.TweetTag(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldTweetID), v)) + }) +} + +// AddedAtEQ applies the EQ predicate on the "added_at" field. +func AddedAtEQ(v time.Time) predicate.TweetTag { + return predicate.TweetTag(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldAddedAt), v)) + }) +} + +// AddedAtNEQ applies the NEQ predicate on the "added_at" field. +func AddedAtNEQ(v time.Time) predicate.TweetTag { + return predicate.TweetTag(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldAddedAt), v)) + }) +} + +// AddedAtIn applies the In predicate on the "added_at" field. +func AddedAtIn(vs ...time.Time) predicate.TweetTag { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.TweetTag(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldAddedAt), v...)) + }) +} + +// AddedAtNotIn applies the NotIn predicate on the "added_at" field. +func AddedAtNotIn(vs ...time.Time) predicate.TweetTag { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.TweetTag(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldAddedAt), v...)) + }) +} + +// AddedAtGT applies the GT predicate on the "added_at" field. +func AddedAtGT(v time.Time) predicate.TweetTag { + return predicate.TweetTag(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldAddedAt), v)) + }) +} + +// AddedAtGTE applies the GTE predicate on the "added_at" field. +func AddedAtGTE(v time.Time) predicate.TweetTag { + return predicate.TweetTag(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldAddedAt), v)) + }) +} + +// AddedAtLT applies the LT predicate on the "added_at" field. +func AddedAtLT(v time.Time) predicate.TweetTag { + return predicate.TweetTag(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldAddedAt), v)) + }) +} + +// AddedAtLTE applies the LTE predicate on the "added_at" field. +func AddedAtLTE(v time.Time) predicate.TweetTag { + return predicate.TweetTag(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldAddedAt), v)) + }) +} + +// TagIDEQ applies the EQ predicate on the "tag_id" field. +func TagIDEQ(v int) predicate.TweetTag { + return predicate.TweetTag(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldTagID), v)) + }) +} + +// TagIDNEQ applies the NEQ predicate on the "tag_id" field. +func TagIDNEQ(v int) predicate.TweetTag { + return predicate.TweetTag(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldTagID), v)) + }) +} + +// TagIDIn applies the In predicate on the "tag_id" field. +func TagIDIn(vs ...int) predicate.TweetTag { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.TweetTag(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldTagID), v...)) + }) +} + +// TagIDNotIn applies the NotIn predicate on the "tag_id" field. +func TagIDNotIn(vs ...int) predicate.TweetTag { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.TweetTag(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldTagID), v...)) + }) +} + +// TweetIDEQ applies the EQ predicate on the "tweet_id" field. +func TweetIDEQ(v int) predicate.TweetTag { + return predicate.TweetTag(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldTweetID), v)) + }) +} + +// TweetIDNEQ applies the NEQ predicate on the "tweet_id" field. +func TweetIDNEQ(v int) predicate.TweetTag { + return predicate.TweetTag(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldTweetID), v)) + }) +} + +// TweetIDIn applies the In predicate on the "tweet_id" field. +func TweetIDIn(vs ...int) predicate.TweetTag { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.TweetTag(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldTweetID), v...)) + }) +} + +// TweetIDNotIn applies the NotIn predicate on the "tweet_id" field. +func TweetIDNotIn(vs ...int) predicate.TweetTag { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.TweetTag(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldTweetID), v...)) + }) +} + +// HasTag applies the HasEdge predicate on the "tag" edge. +func HasTag() predicate.TweetTag { + return predicate.TweetTag(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(TagTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, TagTable, TagColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasTagWith applies the HasEdge predicate on the "tag" edge with a given conditions (other predicates). +func HasTagWith(preds ...predicate.Tag) predicate.TweetTag { + return predicate.TweetTag(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(TagInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, TagTable, TagColumn), + ) + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasTweet applies the HasEdge predicate on the "tweet" edge. +func HasTweet() predicate.TweetTag { + return predicate.TweetTag(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(TweetTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, TweetTable, TweetColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasTweetWith applies the HasEdge predicate on the "tweet" edge with a given conditions (other predicates). +func HasTweetWith(preds ...predicate.Tweet) predicate.TweetTag { + return predicate.TweetTag(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(TweetInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, TweetTable, TweetColumn), + ) + 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.TweetTag) predicate.TweetTag { + return predicate.TweetTag(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.TweetTag) predicate.TweetTag { + return predicate.TweetTag(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.TweetTag) predicate.TweetTag { + return predicate.TweetTag(func(s *sql.Selector) { + p(s.Not()) + }) +} diff --git a/entc/integration/edgeschema/ent/tweettag_create.go b/entc/integration/edgeschema/ent/tweettag_create.go new file mode 100644 index 000000000..fa2953340 --- /dev/null +++ b/entc/integration/edgeschema/ent/tweettag_create.go @@ -0,0 +1,345 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/edgeschema/ent/tag" + "entgo.io/ent/entc/integration/edgeschema/ent/tweet" + "entgo.io/ent/entc/integration/edgeschema/ent/tweettag" + "entgo.io/ent/schema/field" + "github.com/google/uuid" +) + +// TweetTagCreate is the builder for creating a TweetTag entity. +type TweetTagCreate struct { + config + mutation *TweetTagMutation + hooks []Hook +} + +// SetAddedAt sets the "added_at" field. +func (ttc *TweetTagCreate) SetAddedAt(t time.Time) *TweetTagCreate { + ttc.mutation.SetAddedAt(t) + return ttc +} + +// SetNillableAddedAt sets the "added_at" field if the given value is not nil. +func (ttc *TweetTagCreate) SetNillableAddedAt(t *time.Time) *TweetTagCreate { + if t != nil { + ttc.SetAddedAt(*t) + } + return ttc +} + +// SetTagID sets the "tag_id" field. +func (ttc *TweetTagCreate) SetTagID(i int) *TweetTagCreate { + ttc.mutation.SetTagID(i) + return ttc +} + +// SetTweetID sets the "tweet_id" field. +func (ttc *TweetTagCreate) SetTweetID(i int) *TweetTagCreate { + ttc.mutation.SetTweetID(i) + return ttc +} + +// SetID sets the "id" field. +func (ttc *TweetTagCreate) SetID(u uuid.UUID) *TweetTagCreate { + ttc.mutation.SetID(u) + return ttc +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (ttc *TweetTagCreate) SetNillableID(u *uuid.UUID) *TweetTagCreate { + if u != nil { + ttc.SetID(*u) + } + return ttc +} + +// SetTag sets the "tag" edge to the Tag entity. +func (ttc *TweetTagCreate) SetTag(t *Tag) *TweetTagCreate { + return ttc.SetTagID(t.ID) +} + +// SetTweet sets the "tweet" edge to the Tweet entity. +func (ttc *TweetTagCreate) SetTweet(t *Tweet) *TweetTagCreate { + return ttc.SetTweetID(t.ID) +} + +// Mutation returns the TweetTagMutation object of the builder. +func (ttc *TweetTagCreate) Mutation() *TweetTagMutation { + return ttc.mutation +} + +// Save creates the TweetTag in the database. +func (ttc *TweetTagCreate) Save(ctx context.Context) (*TweetTag, error) { + var ( + err error + node *TweetTag + ) + ttc.defaults() + if len(ttc.hooks) == 0 { + if err = ttc.check(); err != nil { + return nil, err + } + node, err = ttc.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*TweetTagMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = ttc.check(); err != nil { + return nil, err + } + ttc.mutation = mutation + if node, err = ttc.sqlSave(ctx); err != nil { + return nil, err + } + mutation.id = &node.ID + mutation.done = true + return node, err + }) + for i := len(ttc.hooks) - 1; i >= 0; i-- { + if ttc.hooks[i] == nil { + return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = ttc.hooks[i](mut) + } + v, err := mut.Mutate(ctx, ttc.mutation) + if err != nil { + return nil, err + } + nv, ok := v.(*TweetTag) + if !ok { + return nil, fmt.Errorf("unexpected node type %T returned from TweetTagMutation", v) + } + node = nv + } + return node, err +} + +// SaveX calls Save and panics if Save returns an error. +func (ttc *TweetTagCreate) SaveX(ctx context.Context) *TweetTag { + v, err := ttc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (ttc *TweetTagCreate) Exec(ctx context.Context) error { + _, err := ttc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ttc *TweetTagCreate) ExecX(ctx context.Context) { + if err := ttc.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (ttc *TweetTagCreate) defaults() { + if _, ok := ttc.mutation.AddedAt(); !ok { + v := tweettag.DefaultAddedAt() + ttc.mutation.SetAddedAt(v) + } + if _, ok := ttc.mutation.ID(); !ok { + v := tweettag.DefaultID() + ttc.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (ttc *TweetTagCreate) check() error { + if _, ok := ttc.mutation.AddedAt(); !ok { + return &ValidationError{Name: "added_at", err: errors.New(`ent: missing required field "TweetTag.added_at"`)} + } + if _, ok := ttc.mutation.TagID(); !ok { + return &ValidationError{Name: "tag_id", err: errors.New(`ent: missing required field "TweetTag.tag_id"`)} + } + if _, ok := ttc.mutation.TweetID(); !ok { + return &ValidationError{Name: "tweet_id", err: errors.New(`ent: missing required field "TweetTag.tweet_id"`)} + } + if _, ok := ttc.mutation.TagID(); !ok { + return &ValidationError{Name: "tag", err: errors.New(`ent: missing required edge "TweetTag.tag"`)} + } + if _, ok := ttc.mutation.TweetID(); !ok { + return &ValidationError{Name: "tweet", err: errors.New(`ent: missing required edge "TweetTag.tweet"`)} + } + return nil +} + +func (ttc *TweetTagCreate) sqlSave(ctx context.Context) (*TweetTag, error) { + _node, _spec := ttc.createSpec() + if err := sqlgraph.CreateNode(ctx, ttc.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.(*uuid.UUID); ok { + _node.ID = *id + } else if err := _node.ID.Scan(_spec.ID.Value); err != nil { + return nil, err + } + } + return _node, nil +} + +func (ttc *TweetTagCreate) createSpec() (*TweetTag, *sqlgraph.CreateSpec) { + var ( + _node = &TweetTag{config: ttc.config} + _spec = &sqlgraph.CreateSpec{ + Table: tweettag.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: tweettag.FieldID, + }, + } + ) + if id, ok := ttc.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = &id + } + if value, ok := ttc.mutation.AddedAt(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: tweettag.FieldAddedAt, + }) + _node.AddedAt = value + } + if nodes := ttc.mutation.TagIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: tweettag.TagTable, + Columns: []string{tweettag.TagColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: tag.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.TagID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := ttc.mutation.TweetIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: tweettag.TweetTable, + Columns: []string{tweettag.TweetColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: tweet.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.TweetID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// TweetTagCreateBulk is the builder for creating many TweetTag entities in bulk. +type TweetTagCreateBulk struct { + config + builders []*TweetTagCreate +} + +// Save creates the TweetTag entities in the database. +func (ttcb *TweetTagCreateBulk) Save(ctx context.Context) ([]*TweetTag, error) { + specs := make([]*sqlgraph.CreateSpec, len(ttcb.builders)) + nodes := make([]*TweetTag, len(ttcb.builders)) + mutators := make([]Mutator, len(ttcb.builders)) + for i := range ttcb.builders { + func(i int, root context.Context) { + builder := ttcb.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*TweetTagMutation) + 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, ttcb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, ttcb.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 + 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, ttcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (ttcb *TweetTagCreateBulk) SaveX(ctx context.Context) []*TweetTag { + v, err := ttcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (ttcb *TweetTagCreateBulk) Exec(ctx context.Context) error { + _, err := ttcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ttcb *TweetTagCreateBulk) ExecX(ctx context.Context) { + if err := ttcb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entc/integration/edgeschema/ent/tweettag_delete.go b/entc/integration/edgeschema/ent/tweettag_delete.go new file mode 100644 index 000000000..c06883ce4 --- /dev/null +++ b/entc/integration/edgeschema/ent/tweettag_delete.go @@ -0,0 +1,115 @@ +// 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/edgeschema/ent/predicate" + "entgo.io/ent/entc/integration/edgeschema/ent/tweettag" + "entgo.io/ent/schema/field" +) + +// TweetTagDelete is the builder for deleting a TweetTag entity. +type TweetTagDelete struct { + config + hooks []Hook + mutation *TweetTagMutation +} + +// Where appends a list predicates to the TweetTagDelete builder. +func (ttd *TweetTagDelete) Where(ps ...predicate.TweetTag) *TweetTagDelete { + ttd.mutation.Where(ps...) + return ttd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (ttd *TweetTagDelete) Exec(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(ttd.hooks) == 0 { + affected, err = ttd.sqlExec(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*TweetTagMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + ttd.mutation = mutation + affected, err = ttd.sqlExec(ctx) + mutation.done = true + return affected, err + }) + for i := len(ttd.hooks) - 1; i >= 0; i-- { + if ttd.hooks[i] == nil { + return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = ttd.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, ttd.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ttd *TweetTagDelete) ExecX(ctx context.Context) int { + n, err := ttd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (ttd *TweetTagDelete) sqlExec(ctx context.Context) (int, error) { + _spec := &sqlgraph.DeleteSpec{ + Node: &sqlgraph.NodeSpec{ + Table: tweettag.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: tweettag.FieldID, + }, + }, + } + if ps := ttd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, ttd.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return affected, err +} + +// TweetTagDeleteOne is the builder for deleting a single TweetTag entity. +type TweetTagDeleteOne struct { + ttd *TweetTagDelete +} + +// Exec executes the deletion query. +func (ttdo *TweetTagDeleteOne) Exec(ctx context.Context) error { + n, err := ttdo.ttd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{tweettag.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (ttdo *TweetTagDeleteOne) ExecX(ctx context.Context) { + ttdo.ttd.ExecX(ctx) +} diff --git a/entc/integration/edgeschema/ent/tweettag_query.go b/entc/integration/edgeschema/ent/tweettag_query.go new file mode 100644 index 000000000..431588738 --- /dev/null +++ b/entc/integration/edgeschema/ent/tweettag_query.go @@ -0,0 +1,660 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + "math" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/edgeschema/ent/predicate" + "entgo.io/ent/entc/integration/edgeschema/ent/tag" + "entgo.io/ent/entc/integration/edgeschema/ent/tweet" + "entgo.io/ent/entc/integration/edgeschema/ent/tweettag" + "entgo.io/ent/schema/field" + "github.com/google/uuid" +) + +// TweetTagQuery is the builder for querying TweetTag entities. +type TweetTagQuery struct { + config + limit *int + offset *int + unique *bool + order []OrderFunc + fields []string + predicates []predicate.TweetTag + // eager-loading edges. + withTag *TagQuery + withTweet *TweetQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the TweetTagQuery builder. +func (ttq *TweetTagQuery) Where(ps ...predicate.TweetTag) *TweetTagQuery { + ttq.predicates = append(ttq.predicates, ps...) + return ttq +} + +// Limit adds a limit step to the query. +func (ttq *TweetTagQuery) Limit(limit int) *TweetTagQuery { + ttq.limit = &limit + return ttq +} + +// Offset adds an offset step to the query. +func (ttq *TweetTagQuery) Offset(offset int) *TweetTagQuery { + ttq.offset = &offset + return ttq +} + +// 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 (ttq *TweetTagQuery) Unique(unique bool) *TweetTagQuery { + ttq.unique = &unique + return ttq +} + +// Order adds an order step to the query. +func (ttq *TweetTagQuery) Order(o ...OrderFunc) *TweetTagQuery { + ttq.order = append(ttq.order, o...) + return ttq +} + +// QueryTag chains the current query on the "tag" edge. +func (ttq *TweetTagQuery) QueryTag() *TagQuery { + query := &TagQuery{config: ttq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := ttq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := ttq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(tweettag.Table, tweettag.FieldID, selector), + sqlgraph.To(tag.Table, tag.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, tweettag.TagTable, tweettag.TagColumn), + ) + fromU = sqlgraph.SetNeighbors(ttq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryTweet chains the current query on the "tweet" edge. +func (ttq *TweetTagQuery) QueryTweet() *TweetQuery { + query := &TweetQuery{config: ttq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := ttq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := ttq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(tweettag.Table, tweettag.FieldID, selector), + sqlgraph.To(tweet.Table, tweet.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, tweettag.TweetTable, tweettag.TweetColumn), + ) + fromU = sqlgraph.SetNeighbors(ttq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first TweetTag entity from the query. +// Returns a *NotFoundError when no TweetTag was found. +func (ttq *TweetTagQuery) First(ctx context.Context) (*TweetTag, error) { + nodes, err := ttq.Limit(1).All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{tweettag.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (ttq *TweetTagQuery) FirstX(ctx context.Context) *TweetTag { + node, err := ttq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first TweetTag ID from the query. +// Returns a *NotFoundError when no TweetTag ID was found. +func (ttq *TweetTagQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = ttq.Limit(1).IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{tweettag.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (ttq *TweetTagQuery) FirstIDX(ctx context.Context) uuid.UUID { + id, err := ttq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single TweetTag entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one TweetTag entity is found. +// Returns a *NotFoundError when no TweetTag entities are found. +func (ttq *TweetTagQuery) Only(ctx context.Context) (*TweetTag, error) { + nodes, err := ttq.Limit(2).All(ctx) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{tweettag.Label} + default: + return nil, &NotSingularError{tweettag.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (ttq *TweetTagQuery) OnlyX(ctx context.Context) *TweetTag { + node, err := ttq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only TweetTag ID in the query. +// Returns a *NotSingularError when more than one TweetTag ID is found. +// Returns a *NotFoundError when no entities are found. +func (ttq *TweetTagQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = ttq.Limit(2).IDs(ctx); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{tweettag.Label} + default: + err = &NotSingularError{tweettag.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (ttq *TweetTagQuery) OnlyIDX(ctx context.Context) uuid.UUID { + id, err := ttq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of TweetTags. +func (ttq *TweetTagQuery) All(ctx context.Context) ([]*TweetTag, error) { + if err := ttq.prepareQuery(ctx); err != nil { + return nil, err + } + return ttq.sqlAll(ctx) +} + +// AllX is like All, but panics if an error occurs. +func (ttq *TweetTagQuery) AllX(ctx context.Context) []*TweetTag { + nodes, err := ttq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of TweetTag IDs. +func (ttq *TweetTagQuery) IDs(ctx context.Context) ([]uuid.UUID, error) { + var ids []uuid.UUID + if err := ttq.Select(tweettag.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (ttq *TweetTagQuery) IDsX(ctx context.Context) []uuid.UUID { + ids, err := ttq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (ttq *TweetTagQuery) Count(ctx context.Context) (int, error) { + if err := ttq.prepareQuery(ctx); err != nil { + return 0, err + } + return ttq.sqlCount(ctx) +} + +// CountX is like Count, but panics if an error occurs. +func (ttq *TweetTagQuery) CountX(ctx context.Context) int { + count, err := ttq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (ttq *TweetTagQuery) Exist(ctx context.Context) (bool, error) { + if err := ttq.prepareQuery(ctx); err != nil { + return false, err + } + return ttq.sqlExist(ctx) +} + +// ExistX is like Exist, but panics if an error occurs. +func (ttq *TweetTagQuery) ExistX(ctx context.Context) bool { + exist, err := ttq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the TweetTagQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (ttq *TweetTagQuery) Clone() *TweetTagQuery { + if ttq == nil { + return nil + } + return &TweetTagQuery{ + config: ttq.config, + limit: ttq.limit, + offset: ttq.offset, + order: append([]OrderFunc{}, ttq.order...), + predicates: append([]predicate.TweetTag{}, ttq.predicates...), + withTag: ttq.withTag.Clone(), + withTweet: ttq.withTweet.Clone(), + // clone intermediate query. + sql: ttq.sql.Clone(), + path: ttq.path, + unique: ttq.unique, + } +} + +// WithTag tells the query-builder to eager-load the nodes that are connected to +// the "tag" edge. The optional arguments are used to configure the query builder of the edge. +func (ttq *TweetTagQuery) WithTag(opts ...func(*TagQuery)) *TweetTagQuery { + query := &TagQuery{config: ttq.config} + for _, opt := range opts { + opt(query) + } + ttq.withTag = query + return ttq +} + +// WithTweet tells the query-builder to eager-load the nodes that are connected to +// the "tweet" edge. The optional arguments are used to configure the query builder of the edge. +func (ttq *TweetTagQuery) WithTweet(opts ...func(*TweetQuery)) *TweetTagQuery { + query := &TweetQuery{config: ttq.config} + for _, opt := range opts { + opt(query) + } + ttq.withTweet = query + return ttq +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// AddedAt time.Time `json:"added_at,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.TweetTag.Query(). +// GroupBy(tweettag.FieldAddedAt). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +// +func (ttq *TweetTagQuery) GroupBy(field string, fields ...string) *TweetTagGroupBy { + grbuild := &TweetTagGroupBy{config: ttq.config} + grbuild.fields = append([]string{field}, fields...) + grbuild.path = func(ctx context.Context) (prev *sql.Selector, err error) { + if err := ttq.prepareQuery(ctx); err != nil { + return nil, err + } + return ttq.sqlQuery(ctx), nil + } + grbuild.label = tweettag.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. +// +// Example: +// +// var v []struct { +// AddedAt time.Time `json:"added_at,omitempty"` +// } +// +// client.TweetTag.Query(). +// Select(tweettag.FieldAddedAt). +// Scan(ctx, &v) +// +func (ttq *TweetTagQuery) Select(fields ...string) *TweetTagSelect { + ttq.fields = append(ttq.fields, fields...) + selbuild := &TweetTagSelect{TweetTagQuery: ttq} + selbuild.label = tweettag.Label + selbuild.flds, selbuild.scan = &ttq.fields, selbuild.Scan + return selbuild +} + +func (ttq *TweetTagQuery) prepareQuery(ctx context.Context) error { + for _, f := range ttq.fields { + if !tweettag.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if ttq.path != nil { + prev, err := ttq.path(ctx) + if err != nil { + return err + } + ttq.sql = prev + } + return nil +} + +func (ttq *TweetTagQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*TweetTag, error) { + var ( + nodes = []*TweetTag{} + _spec = ttq.querySpec() + loadedTypes = [2]bool{ + ttq.withTag != nil, + ttq.withTweet != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]interface{}, error) { + return (*TweetTag).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []interface{}) error { + node := &TweetTag{config: ttq.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, ttq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + + if query := ttq.withTag; query != nil { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*TweetTag) + for i := range nodes { + fk := nodes[i].TagID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + query.Where(tag.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 "tag_id" returned %v`, n.ID) + } + for i := range nodes { + nodes[i].Edges.Tag = n + } + } + } + + if query := ttq.withTweet; query != nil { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*TweetTag) + for i := range nodes { + fk := nodes[i].TweetID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + query.Where(tweet.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 "tweet_id" returned %v`, n.ID) + } + for i := range nodes { + nodes[i].Edges.Tweet = n + } + } + } + + return nodes, nil +} + +func (ttq *TweetTagQuery) sqlCount(ctx context.Context) (int, error) { + _spec := ttq.querySpec() + _spec.Node.Columns = ttq.fields + if len(ttq.fields) > 0 { + _spec.Unique = ttq.unique != nil && *ttq.unique + } + return sqlgraph.CountNodes(ctx, ttq.driver, _spec) +} + +func (ttq *TweetTagQuery) sqlExist(ctx context.Context) (bool, error) { + n, err := ttq.sqlCount(ctx) + if err != nil { + return false, fmt.Errorf("ent: check existence: %w", err) + } + return n > 0, nil +} + +func (ttq *TweetTagQuery) querySpec() *sqlgraph.QuerySpec { + _spec := &sqlgraph.QuerySpec{ + Node: &sqlgraph.NodeSpec{ + Table: tweettag.Table, + Columns: tweettag.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: tweettag.FieldID, + }, + }, + From: ttq.sql, + Unique: true, + } + if unique := ttq.unique; unique != nil { + _spec.Unique = *unique + } + if fields := ttq.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, tweettag.FieldID) + for i := range fields { + if fields[i] != tweettag.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := ttq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := ttq.limit; limit != nil { + _spec.Limit = *limit + } + if offset := ttq.offset; offset != nil { + _spec.Offset = *offset + } + if ps := ttq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (ttq *TweetTagQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(ttq.driver.Dialect()) + t1 := builder.Table(tweettag.Table) + columns := ttq.fields + if len(columns) == 0 { + columns = tweettag.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if ttq.sql != nil { + selector = ttq.sql + selector.Select(selector.Columns(columns...)...) + } + if ttq.unique != nil && *ttq.unique { + selector.Distinct() + } + for _, p := range ttq.predicates { + p(selector) + } + for _, p := range ttq.order { + p(selector) + } + if offset := ttq.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 := ttq.limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// TweetTagGroupBy is the group-by builder for TweetTag entities. +type TweetTagGroupBy 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 (ttgb *TweetTagGroupBy) Aggregate(fns ...AggregateFunc) *TweetTagGroupBy { + ttgb.fns = append(ttgb.fns, fns...) + return ttgb +} + +// Scan applies the group-by query and scans the result into the given value. +func (ttgb *TweetTagGroupBy) Scan(ctx context.Context, v interface{}) error { + query, err := ttgb.path(ctx) + if err != nil { + return err + } + ttgb.sql = query + return ttgb.sqlScan(ctx, v) +} + +func (ttgb *TweetTagGroupBy) sqlScan(ctx context.Context, v interface{}) error { + for _, f := range ttgb.fields { + if !tweettag.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + } + } + selector := ttgb.sqlQuery() + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := ttgb.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +func (ttgb *TweetTagGroupBy) sqlQuery() *sql.Selector { + selector := ttgb.sql.Select() + aggregation := make([]string, 0, len(ttgb.fns)) + for _, fn := range ttgb.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(ttgb.fields)+len(ttgb.fns)) + for _, f := range ttgb.fields { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + return selector.GroupBy(selector.Columns(ttgb.fields...)...) +} + +// TweetTagSelect is the builder for selecting fields of TweetTag entities. +type TweetTagSelect struct { + *TweetTagQuery + selector + // intermediate query (i.e. traversal path). + sql *sql.Selector +} + +// Scan applies the selector query and scans the result into the given value. +func (tts *TweetTagSelect) Scan(ctx context.Context, v interface{}) error { + if err := tts.prepareQuery(ctx); err != nil { + return err + } + tts.sql = tts.TweetTagQuery.sqlQuery(ctx) + return tts.sqlScan(ctx, v) +} + +func (tts *TweetTagSelect) sqlScan(ctx context.Context, v interface{}) error { + rows := &sql.Rows{} + query, args := tts.sql.Query() + if err := tts.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/entc/integration/edgeschema/ent/tweettag_update.go b/entc/integration/edgeschema/ent/tweettag_update.go new file mode 100644 index 000000000..03c92c4e9 --- /dev/null +++ b/entc/integration/edgeschema/ent/tweettag_update.go @@ -0,0 +1,532 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/edgeschema/ent/predicate" + "entgo.io/ent/entc/integration/edgeschema/ent/tag" + "entgo.io/ent/entc/integration/edgeschema/ent/tweet" + "entgo.io/ent/entc/integration/edgeschema/ent/tweettag" + "entgo.io/ent/schema/field" +) + +// TweetTagUpdate is the builder for updating TweetTag entities. +type TweetTagUpdate struct { + config + hooks []Hook + mutation *TweetTagMutation +} + +// Where appends a list predicates to the TweetTagUpdate builder. +func (ttu *TweetTagUpdate) Where(ps ...predicate.TweetTag) *TweetTagUpdate { + ttu.mutation.Where(ps...) + return ttu +} + +// SetAddedAt sets the "added_at" field. +func (ttu *TweetTagUpdate) SetAddedAt(t time.Time) *TweetTagUpdate { + ttu.mutation.SetAddedAt(t) + return ttu +} + +// SetNillableAddedAt sets the "added_at" field if the given value is not nil. +func (ttu *TweetTagUpdate) SetNillableAddedAt(t *time.Time) *TweetTagUpdate { + if t != nil { + ttu.SetAddedAt(*t) + } + return ttu +} + +// SetTagID sets the "tag_id" field. +func (ttu *TweetTagUpdate) SetTagID(i int) *TweetTagUpdate { + ttu.mutation.SetTagID(i) + return ttu +} + +// SetTweetID sets the "tweet_id" field. +func (ttu *TweetTagUpdate) SetTweetID(i int) *TweetTagUpdate { + ttu.mutation.SetTweetID(i) + return ttu +} + +// SetTag sets the "tag" edge to the Tag entity. +func (ttu *TweetTagUpdate) SetTag(t *Tag) *TweetTagUpdate { + return ttu.SetTagID(t.ID) +} + +// SetTweet sets the "tweet" edge to the Tweet entity. +func (ttu *TweetTagUpdate) SetTweet(t *Tweet) *TweetTagUpdate { + return ttu.SetTweetID(t.ID) +} + +// Mutation returns the TweetTagMutation object of the builder. +func (ttu *TweetTagUpdate) Mutation() *TweetTagMutation { + return ttu.mutation +} + +// ClearTag clears the "tag" edge to the Tag entity. +func (ttu *TweetTagUpdate) ClearTag() *TweetTagUpdate { + ttu.mutation.ClearTag() + return ttu +} + +// ClearTweet clears the "tweet" edge to the Tweet entity. +func (ttu *TweetTagUpdate) ClearTweet() *TweetTagUpdate { + ttu.mutation.ClearTweet() + return ttu +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (ttu *TweetTagUpdate) Save(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(ttu.hooks) == 0 { + if err = ttu.check(); err != nil { + return 0, err + } + affected, err = ttu.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*TweetTagMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = ttu.check(); err != nil { + return 0, err + } + ttu.mutation = mutation + affected, err = ttu.sqlSave(ctx) + mutation.done = true + return affected, err + }) + for i := len(ttu.hooks) - 1; i >= 0; i-- { + if ttu.hooks[i] == nil { + return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = ttu.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, ttu.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// SaveX is like Save, but panics if an error occurs. +func (ttu *TweetTagUpdate) SaveX(ctx context.Context) int { + affected, err := ttu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (ttu *TweetTagUpdate) Exec(ctx context.Context) error { + _, err := ttu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ttu *TweetTagUpdate) ExecX(ctx context.Context) { + if err := ttu.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (ttu *TweetTagUpdate) check() error { + if _, ok := ttu.mutation.TagID(); ttu.mutation.TagCleared() && !ok { + return errors.New(`ent: clearing a required unique edge "TweetTag.tag"`) + } + if _, ok := ttu.mutation.TweetID(); ttu.mutation.TweetCleared() && !ok { + return errors.New(`ent: clearing a required unique edge "TweetTag.tweet"`) + } + return nil +} + +func (ttu *TweetTagUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: tweettag.Table, + Columns: tweettag.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: tweettag.FieldID, + }, + }, + } + if ps := ttu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := ttu.mutation.AddedAt(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: tweettag.FieldAddedAt, + }) + } + if ttu.mutation.TagCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: tweettag.TagTable, + Columns: []string{tweettag.TagColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: tag.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ttu.mutation.TagIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: tweettag.TagTable, + Columns: []string{tweettag.TagColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: tag.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if ttu.mutation.TweetCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: tweettag.TweetTable, + Columns: []string{tweettag.TweetColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: tweet.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ttu.mutation.TweetIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: tweettag.TweetTable, + Columns: []string{tweettag.TweetColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: tweet.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, ttu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{tweettag.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + return n, nil +} + +// TweetTagUpdateOne is the builder for updating a single TweetTag entity. +type TweetTagUpdateOne struct { + config + fields []string + hooks []Hook + mutation *TweetTagMutation +} + +// SetAddedAt sets the "added_at" field. +func (ttuo *TweetTagUpdateOne) SetAddedAt(t time.Time) *TweetTagUpdateOne { + ttuo.mutation.SetAddedAt(t) + return ttuo +} + +// SetNillableAddedAt sets the "added_at" field if the given value is not nil. +func (ttuo *TweetTagUpdateOne) SetNillableAddedAt(t *time.Time) *TweetTagUpdateOne { + if t != nil { + ttuo.SetAddedAt(*t) + } + return ttuo +} + +// SetTagID sets the "tag_id" field. +func (ttuo *TweetTagUpdateOne) SetTagID(i int) *TweetTagUpdateOne { + ttuo.mutation.SetTagID(i) + return ttuo +} + +// SetTweetID sets the "tweet_id" field. +func (ttuo *TweetTagUpdateOne) SetTweetID(i int) *TweetTagUpdateOne { + ttuo.mutation.SetTweetID(i) + return ttuo +} + +// SetTag sets the "tag" edge to the Tag entity. +func (ttuo *TweetTagUpdateOne) SetTag(t *Tag) *TweetTagUpdateOne { + return ttuo.SetTagID(t.ID) +} + +// SetTweet sets the "tweet" edge to the Tweet entity. +func (ttuo *TweetTagUpdateOne) SetTweet(t *Tweet) *TweetTagUpdateOne { + return ttuo.SetTweetID(t.ID) +} + +// Mutation returns the TweetTagMutation object of the builder. +func (ttuo *TweetTagUpdateOne) Mutation() *TweetTagMutation { + return ttuo.mutation +} + +// ClearTag clears the "tag" edge to the Tag entity. +func (ttuo *TweetTagUpdateOne) ClearTag() *TweetTagUpdateOne { + ttuo.mutation.ClearTag() + return ttuo +} + +// ClearTweet clears the "tweet" edge to the Tweet entity. +func (ttuo *TweetTagUpdateOne) ClearTweet() *TweetTagUpdateOne { + ttuo.mutation.ClearTweet() + return ttuo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (ttuo *TweetTagUpdateOne) Select(field string, fields ...string) *TweetTagUpdateOne { + ttuo.fields = append([]string{field}, fields...) + return ttuo +} + +// Save executes the query and returns the updated TweetTag entity. +func (ttuo *TweetTagUpdateOne) Save(ctx context.Context) (*TweetTag, error) { + var ( + err error + node *TweetTag + ) + if len(ttuo.hooks) == 0 { + if err = ttuo.check(); err != nil { + return nil, err + } + node, err = ttuo.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*TweetTagMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = ttuo.check(); err != nil { + return nil, err + } + ttuo.mutation = mutation + node, err = ttuo.sqlSave(ctx) + mutation.done = true + return node, err + }) + for i := len(ttuo.hooks) - 1; i >= 0; i-- { + if ttuo.hooks[i] == nil { + return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = ttuo.hooks[i](mut) + } + v, err := mut.Mutate(ctx, ttuo.mutation) + if err != nil { + return nil, err + } + nv, ok := v.(*TweetTag) + if !ok { + return nil, fmt.Errorf("unexpected node type %T returned from TweetTagMutation", v) + } + node = nv + } + return node, err +} + +// SaveX is like Save, but panics if an error occurs. +func (ttuo *TweetTagUpdateOne) SaveX(ctx context.Context) *TweetTag { + node, err := ttuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (ttuo *TweetTagUpdateOne) Exec(ctx context.Context) error { + _, err := ttuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ttuo *TweetTagUpdateOne) ExecX(ctx context.Context) { + if err := ttuo.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (ttuo *TweetTagUpdateOne) check() error { + if _, ok := ttuo.mutation.TagID(); ttuo.mutation.TagCleared() && !ok { + return errors.New(`ent: clearing a required unique edge "TweetTag.tag"`) + } + if _, ok := ttuo.mutation.TweetID(); ttuo.mutation.TweetCleared() && !ok { + return errors.New(`ent: clearing a required unique edge "TweetTag.tweet"`) + } + return nil +} + +func (ttuo *TweetTagUpdateOne) sqlSave(ctx context.Context) (_node *TweetTag, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: tweettag.Table, + Columns: tweettag.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: tweettag.FieldID, + }, + }, + } + id, ok := ttuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "TweetTag.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := ttuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, tweettag.FieldID) + for _, f := range fields { + if !tweettag.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != tweettag.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := ttuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := ttuo.mutation.AddedAt(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: tweettag.FieldAddedAt, + }) + } + if ttuo.mutation.TagCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: tweettag.TagTable, + Columns: []string{tweettag.TagColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: tag.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ttuo.mutation.TagIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: tweettag.TagTable, + Columns: []string{tweettag.TagColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: tag.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if ttuo.mutation.TweetCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: tweettag.TweetTable, + Columns: []string{tweettag.TweetColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: tweet.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ttuo.mutation.TweetIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: tweettag.TweetTable, + Columns: []string{tweettag.TweetColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: tweet.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &TweetTag{config: ttuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, ttuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{tweettag.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + return _node, nil +} diff --git a/entc/integration/edgeschema/ent/tx.go b/entc/integration/edgeschema/ent/tx.go index 78dc59fd7..9be6e0d1d 100644 --- a/entc/integration/edgeschema/ent/tx.go +++ b/entc/integration/edgeschema/ent/tx.go @@ -18,10 +18,14 @@ type Tx struct { Group *GroupClient // Relationship is the client for interacting with the Relationship builders. Relationship *RelationshipClient + // Tag is the client for interacting with the Tag builders. + Tag *TagClient // Tweet is the client for interacting with the Tweet builders. Tweet *TweetClient // TweetLike is the client for interacting with the TweetLike builders. TweetLike *TweetLikeClient + // TweetTag is the client for interacting with the TweetTag builders. + TweetTag *TweetTagClient // User is the client for interacting with the User builders. User *UserClient // UserGroup is the client for interacting with the UserGroup builders. @@ -166,8 +170,10 @@ func (tx *Tx) init() { tx.Friendship = NewFriendshipClient(tx.config) tx.Group = NewGroupClient(tx.config) tx.Relationship = NewRelationshipClient(tx.config) + tx.Tag = NewTagClient(tx.config) tx.Tweet = NewTweetClient(tx.config) tx.TweetLike = NewTweetLikeClient(tx.config) + tx.TweetTag = NewTweetTagClient(tx.config) tx.User = NewUserClient(tx.config) tx.UserGroup = NewUserGroupClient(tx.config) tx.UserTweet = NewUserTweetClient(tx.config)